{"version":3,"file":"yorkie-js-sdk.es.mjs","sources":["../../../node_modules/.pnpm/@connectrpc+connect@2.1.1_@bufbuild+protobuf@2.10.1/node_modules/@connectrpc/connect/dist/esm/code.js","../../../node_modules/.pnpm/@bufbuild+protobuf@2.10.1/node_modules/@bufbuild/protobuf/dist/esm/is-message.js","../../../node_modules/.pnpm/@bufbuild+protobuf@2.10.1/node_modules/@bufbuild/protobuf/dist/esm/descriptors.js","../../../node_modules/.pnpm/@bufbuild+protobuf@2.10.1/node_modules/@bufbuild/protobuf/dist/esm/wire/varint.js","../../../node_modules/.pnpm/@bufbuild+protobuf@2.10.1/node_modules/@bufbuild/protobuf/dist/esm/proto-int64.js","../../../node_modules/.pnpm/@bufbuild+protobuf@2.10.1/node_modules/@bufbuild/protobuf/dist/esm/reflect/scalar.js","../../../node_modules/.pnpm/@bufbuild+protobuf@2.10.1/node_modules/@bufbuild/protobuf/dist/esm/reflect/unsafe.js","../../../node_modules/.pnpm/@bufbuild+protobuf@2.10.1/node_modules/@bufbuild/protobuf/dist/esm/reflect/guard.js","../../../node_modules/.pnpm/@bufbuild+protobuf@2.10.1/node_modules/@bufbuild/protobuf/dist/esm/wkt/wrappers.js","../../../node_modules/.pnpm/@bufbuild+protobuf@2.10.1/node_modules/@bufbuild/protobuf/dist/esm/create.js","../../../node_modules/.pnpm/@bufbuild+protobuf@2.10.1/node_modules/@bufbuild/protobuf/dist/esm/reflect/error.js","../../../node_modules/.pnpm/@bufbuild+protobuf@2.10.1/node_modules/@bufbuild/protobuf/dist/esm/wire/text-encoding.js","../../../node_modules/.pnpm/@bufbuild+protobuf@2.10.1/node_modules/@bufbuild/protobuf/dist/esm/wire/binary-encoding.js","../../../node_modules/.pnpm/@bufbuild+protobuf@2.10.1/node_modules/@bufbuild/protobuf/dist/esm/reflect/reflect-check.js","../../../node_modules/.pnpm/@bufbuild+protobuf@2.10.1/node_modules/@bufbuild/protobuf/dist/esm/reflect/reflect.js","../../../node_modules/.pnpm/@bufbuild+protobuf@2.10.1/node_modules/@bufbuild/protobuf/dist/esm/wire/base64-encoding.js","../../../node_modules/.pnpm/@bufbuild+protobuf@2.10.1/node_modules/@bufbuild/protobuf/dist/esm/reflect/names.js","../../../node_modules/.pnpm/@bufbuild+protobuf@2.10.1/node_modules/@bufbuild/protobuf/dist/esm/codegenv2/restore-json-names.js","../../../node_modules/.pnpm/@bufbuild+protobuf@2.10.1/node_modules/@bufbuild/protobuf/dist/esm/wire/text-format.js","../../../node_modules/.pnpm/@bufbuild+protobuf@2.10.1/node_modules/@bufbuild/protobuf/dist/esm/reflect/nested-types.js","../../../node_modules/.pnpm/@bufbuild+protobuf@2.10.1/node_modules/@bufbuild/protobuf/dist/esm/registry.js","../../../node_modules/.pnpm/@bufbuild+protobuf@2.10.1/node_modules/@bufbuild/protobuf/dist/esm/codegenv2/boot.js","../../../node_modules/.pnpm/@bufbuild+protobuf@2.10.1/node_modules/@bufbuild/protobuf/dist/esm/codegenv2/message.js","../../../node_modules/.pnpm/@bufbuild+protobuf@2.10.1/node_modules/@bufbuild/protobuf/dist/esm/wkt/gen/google/protobuf/descriptor_pb.js","../../../node_modules/.pnpm/@bufbuild+protobuf@2.10.1/node_modules/@bufbuild/protobuf/dist/esm/from-binary.js","../../../node_modules/.pnpm/@bufbuild+protobuf@2.10.1/node_modules/@bufbuild/protobuf/dist/esm/codegenv2/file.js","../../../node_modules/.pnpm/@bufbuild+protobuf@2.10.1/node_modules/@bufbuild/protobuf/dist/esm/wkt/gen/google/protobuf/timestamp_pb.js","../../../node_modules/.pnpm/@bufbuild+protobuf@2.10.1/node_modules/@bufbuild/protobuf/dist/esm/wkt/timestamp.js","../../../node_modules/.pnpm/@bufbuild+protobuf@2.10.1/node_modules/@bufbuild/protobuf/dist/esm/wkt/gen/google/protobuf/duration_pb.js","../../../node_modules/.pnpm/@bufbuild+protobuf@2.10.1/node_modules/@bufbuild/protobuf/dist/esm/wkt/gen/google/protobuf/any_pb.js","../../../node_modules/.pnpm/@bufbuild+protobuf@2.10.1/node_modules/@bufbuild/protobuf/dist/esm/to-binary.js","../../../node_modules/.pnpm/@bufbuild+protobuf@2.10.1/node_modules/@bufbuild/protobuf/dist/esm/wkt/any.js","../../../node_modules/.pnpm/@bufbuild+protobuf@2.10.1/node_modules/@bufbuild/protobuf/dist/esm/wkt/gen/google/protobuf/struct_pb.js","../../../node_modules/.pnpm/@bufbuild+protobuf@2.10.1/node_modules/@bufbuild/protobuf/dist/esm/wkt/gen/google/protobuf/wrappers_pb.js","../../../node_modules/.pnpm/@bufbuild+protobuf@2.10.1/node_modules/@bufbuild/protobuf/dist/esm/extensions.js","../../../node_modules/.pnpm/@bufbuild+protobuf@2.10.1/node_modules/@bufbuild/protobuf/dist/esm/to-json.js","../../../node_modules/.pnpm/@bufbuild+protobuf@2.10.1/node_modules/@bufbuild/protobuf/dist/esm/from-json.js","../../../node_modules/.pnpm/@connectrpc+connect@2.1.1_@bufbuild+protobuf@2.10.1/node_modules/@connectrpc/connect/dist/esm/protocol-connect/code-string.js","../../../node_modules/.pnpm/@connectrpc+connect@2.1.1_@bufbuild+protobuf@2.10.1/node_modules/@connectrpc/connect/dist/esm/connect-error.js","../../../node_modules/.pnpm/@connectrpc+connect@2.1.1_@bufbuild+protobuf@2.10.1/node_modules/@connectrpc/connect/dist/esm/http-headers.js","../../../node_modules/.pnpm/@connectrpc+connect@2.1.1_@bufbuild+protobuf@2.10.1/node_modules/@connectrpc/connect/dist/esm/any-client.js","../../../node_modules/.pnpm/@connectrpc+connect@2.1.1_@bufbuild+protobuf@2.10.1/node_modules/@connectrpc/connect/dist/esm/protocol/compression.js","../../../node_modules/.pnpm/@connectrpc+connect@2.1.1_@bufbuild+protobuf@2.10.1/node_modules/@connectrpc/connect/dist/esm/protocol/limit-io.js","../../../node_modules/.pnpm/@connectrpc+connect@2.1.1_@bufbuild+protobuf@2.10.1/node_modules/@connectrpc/connect/dist/esm/protocol/envelope.js","../../../node_modules/.pnpm/@connectrpc+connect@2.1.1_@bufbuild+protobuf@2.10.1/node_modules/@connectrpc/connect/dist/esm/protocol/async-iterable.js","../../../node_modules/.pnpm/@connectrpc+connect@2.1.1_@bufbuild+protobuf@2.10.1/node_modules/@connectrpc/connect/dist/esm/promise-client.js","../../../node_modules/.pnpm/@connectrpc+connect@2.1.1_@bufbuild+protobuf@2.10.1/node_modules/@connectrpc/connect/dist/esm/protocol/signals.js","../../../node_modules/.pnpm/@connectrpc+connect@2.1.1_@bufbuild+protobuf@2.10.1/node_modules/@connectrpc/connect/dist/esm/context-values.js","../../../node_modules/.pnpm/@connectrpc+connect@2.1.1_@bufbuild+protobuf@2.10.1/node_modules/@connectrpc/connect/dist/esm/protocol-grpc-web/trailer.js","../../../node_modules/.pnpm/@connectrpc+connect@2.1.1_@bufbuild+protobuf@2.10.1/node_modules/@connectrpc/connect/dist/esm/protocol-grpc/headers.js","../../../node_modules/.pnpm/@connectrpc+connect@2.1.1_@bufbuild+protobuf@2.10.1/node_modules/@connectrpc/connect/dist/esm/protocol-grpc-web/headers.js","../../../node_modules/.pnpm/@connectrpc+connect@2.1.1_@bufbuild+protobuf@2.10.1/node_modules/@connectrpc/connect/dist/esm/protocol-grpc-web/content-type.js","../../../node_modules/.pnpm/@bufbuild+protobuf@2.10.1/node_modules/@bufbuild/protobuf/dist/esm/codegenv2/service.js","../../../node_modules/.pnpm/@connectrpc+connect@2.1.1_@bufbuild+protobuf@2.10.1/node_modules/@connectrpc/connect/dist/esm/protocol-grpc/gen/status_pb.js","../../../node_modules/.pnpm/@connectrpc+connect@2.1.1_@bufbuild+protobuf@2.10.1/node_modules/@connectrpc/connect/dist/esm/protocol-grpc/trailer-status.js","../../../node_modules/.pnpm/@connectrpc+connect@2.1.1_@bufbuild+protobuf@2.10.1/node_modules/@connectrpc/connect/dist/esm/protocol/create-method-url.js","../../../node_modules/.pnpm/@connectrpc+connect@2.1.1_@bufbuild+protobuf@2.10.1/node_modules/@connectrpc/connect/dist/esm/protocol/normalize.js","../../../node_modules/.pnpm/@connectrpc+connect@2.1.1_@bufbuild+protobuf@2.10.1/node_modules/@connectrpc/connect/dist/esm/interceptor.js","../../../node_modules/.pnpm/@connectrpc+connect@2.1.1_@bufbuild+protobuf@2.10.1/node_modules/@connectrpc/connect/dist/esm/protocol/serialization.js","../../../node_modules/.pnpm/@connectrpc+connect@2.1.1_@bufbuild+protobuf@2.10.1/node_modules/@connectrpc/connect/dist/esm/protocol-connect/content-type.js","../../../node_modules/.pnpm/@connectrpc+connect@2.1.1_@bufbuild+protobuf@2.10.1/node_modules/@connectrpc/connect/dist/esm/protocol-connect/error-json.js","../../../node_modules/.pnpm/@connectrpc+connect@2.1.1_@bufbuild+protobuf@2.10.1/node_modules/@connectrpc/connect/dist/esm/protocol-connect/end-stream.js","../../../node_modules/.pnpm/@connectrpc+connect@2.1.1_@bufbuild+protobuf@2.10.1/node_modules/@connectrpc/connect/dist/esm/protocol-connect/headers.js","../../../node_modules/.pnpm/@connectrpc+connect@2.1.1_@bufbuild+protobuf@2.10.1/node_modules/@connectrpc/connect/dist/esm/protocol-connect/http-status.js","../../../node_modules/.pnpm/@connectrpc+connect@2.1.1_@bufbuild+protobuf@2.10.1/node_modules/@connectrpc/connect/dist/esm/protocol-connect/trailer-mux.js","../../../node_modules/.pnpm/@connectrpc+connect@2.1.1_@bufbuild+protobuf@2.10.1/node_modules/@connectrpc/connect/dist/esm/protocol-connect/version.js","../../../node_modules/.pnpm/@connectrpc+connect@2.1.1_@bufbuild+protobuf@2.10.1/node_modules/@connectrpc/connect/dist/esm/protocol-connect/request-header.js","../../../node_modules/.pnpm/@connectrpc+connect@2.1.1_@bufbuild+protobuf@2.10.1/node_modules/@connectrpc/connect/dist/esm/protocol-connect/validate-response.js","../../../node_modules/.pnpm/@connectrpc+connect@2.1.1_@bufbuild+protobuf@2.10.1/node_modules/@connectrpc/connect/dist/esm/protocol-connect/get-request.js","../../../node_modules/.pnpm/@connectrpc+connect@2.1.1_@bufbuild+protobuf@2.10.1/node_modules/@connectrpc/connect/dist/esm/protocol/run-call.js","../../../node_modules/.pnpm/@connectrpc+connect-web@2.1.1_@bufbuild+protobuf@2.10.1_@connectrpc+connect@2.1.1_@bufbuild+protobuf@2.10.1_/node_modules/@connectrpc/connect-web/dist/esm/assert-fetch-api.js","../../../node_modules/.pnpm/@connectrpc+connect-web@2.1.1_@bufbuild+protobuf@2.10.1_@connectrpc+connect@2.1.1_@bufbuild+protobuf@2.10.1_/node_modules/@connectrpc/connect-web/dist/esm/connect-transport.js","../../../node_modules/.pnpm/@connectrpc+connect@2.1.1_@bufbuild+protobuf@2.10.1/node_modules/@connectrpc/connect/dist/esm/protocol-grpc/validate-trailer.js","../../../node_modules/.pnpm/@connectrpc+connect@2.1.1_@bufbuild+protobuf@2.10.1/node_modules/@connectrpc/connect/dist/esm/protocol-grpc-web/request-header.js","../../../node_modules/.pnpm/@connectrpc+connect@2.1.1_@bufbuild+protobuf@2.10.1/node_modules/@connectrpc/connect/dist/esm/protocol-grpc/http-status.js","../../../node_modules/.pnpm/@connectrpc+connect@2.1.1_@bufbuild+protobuf@2.10.1/node_modules/@connectrpc/connect/dist/esm/protocol-grpc-web/validate-response.js","../../../node_modules/.pnpm/@connectrpc+connect-web@2.1.1_@bufbuild+protobuf@2.10.1_@connectrpc+connect@2.1.1_@bufbuild+protobuf@2.10.1_/node_modules/@connectrpc/connect-web/dist/esm/grpc-web-transport.js","../src/api/yorkie/v1/resources_pb.ts","../src/api/yorkie/v1/yorkie_pb.ts","../../../node_modules/.pnpm/@buf+googleapis_googleapis.bufbuild_es@2.10.1-20251126203132-004180b77378.1_@bufbuild+protobuf@2.10.1/node_modules/@buf/googleapis_googleapis.bufbuild_es/google/rpc/error_details_pb.js","../src/util/error.ts","../src/util/object.ts","../src/document/presence/change.ts","../src/document/time/actor_id.ts","../src/document/time/ticket.ts","../src/document/json/strings.ts","../src/document/crdt/element.ts","../src/document/crdt/element_rht.ts","../src/document/crdt/object.ts","../src/document/operation/operation.ts","../src/util/treelist.ts","../src/util/logger.ts","../src/util/number.ts","../src/document/crdt/primitive.ts","../src/document/crdt/rga_tree_list.ts","../src/document/crdt/array.ts","../src/document/operation/add_operation.ts","../src/document/operation/remove_operation.ts","../src/document/operation/set_operation.ts","../src/document/operation/move_operation.ts","../src/util/splay_tree.ts","../src/util/comparator.ts","../src/util/llrb_tree.ts","../src/document/time/version_vector.ts","../src/util/resource.ts","../src/document/crdt/rga_tree_split.ts","../src/document/crdt/rht.ts","../src/util/index_tree.ts","../src/document/crdt/tree.ts","../src/document/crdt/text.ts","../src/document/operation/edit_operation.ts","../src/document/operation/style_operation.ts","../src/document/operation/tree_edit_operation.ts","../src/document/change/change_id.ts","../src/document/change/change.ts","../src/document/change/change_pack.ts","../src/document/change/checkpoint.ts","../src/document/crdt/split_links.ts","../src/document/crdt/hll.ts","../src/document/crdt/counter.ts","../src/document/operation/increase_operation.ts","../src/document/operation/tree_style_operation.ts","../src/document/operation/array_set_operation.ts","../src/api/converter.ts","../src/util/uuid.ts","../src/api/reissue.ts","../src/util/observable.ts","../src/document/change/context.ts","../src/document/json/object.ts","../src/document/json/array.ts","../src/document/json/text.ts","../src/document/json/counter.ts","../src/document/json/tree.ts","../src/document/json/element.ts","../src/document/crdt/root.ts","../src/document/presence/presence.ts","../src/document/history.ts","../src/document/schema/content-expression.ts","../src/document/schema/tree-validator.ts","../src/document/schema/ruleset_validator.ts","../src/devtools/protocol.ts","../src/devtools/types.ts","../src/devtools/index.ts","../src/document/document.ts","../src/client/attachment.ts","../src/client/auth_interceptor.ts","../src/client/metric_interceptor.ts","../src/util/validator.ts","../src/channel/channel.ts","../src/client/persist-policy.ts","../src/client/session-lock.ts","../src/client/watch.ts","../src/client/client.ts","../src/client/doc-store.ts","../src/document/yson/types.ts","../src/document/yson/parser.ts","../src/yorkie.ts"],"sourcesContent":["// Copyright 2021-2025 The Connect Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n/**\n * Connect represents categories of errors as codes, and each code maps to a\n * specific HTTP status code. The codes and their semantics were chosen to\n * match gRPC. Only the codes below are valid — there are no user-defined\n * codes.\n *\n * See the specification at https://connectrpc.com/docs/protocol#error-codes\n * for details.\n */\nexport var Code;\n(function (Code) {\n    /**\n     * Canceled, usually by the user\n     */\n    Code[Code[\"Canceled\"] = 1] = \"Canceled\";\n    /**\n     * Unknown error\n     */\n    Code[Code[\"Unknown\"] = 2] = \"Unknown\";\n    /**\n     * Argument invalid regardless of system state\n     */\n    Code[Code[\"InvalidArgument\"] = 3] = \"InvalidArgument\";\n    /**\n     * Operation expired, may or may not have completed.\n     */\n    Code[Code[\"DeadlineExceeded\"] = 4] = \"DeadlineExceeded\";\n    /**\n     * Entity not found.\n     */\n    Code[Code[\"NotFound\"] = 5] = \"NotFound\";\n    /**\n     * Entity already exists.\n     */\n    Code[Code[\"AlreadyExists\"] = 6] = \"AlreadyExists\";\n    /**\n     * Operation not authorized.\n     */\n    Code[Code[\"PermissionDenied\"] = 7] = \"PermissionDenied\";\n    /**\n     * Quota exhausted.\n     */\n    Code[Code[\"ResourceExhausted\"] = 8] = \"ResourceExhausted\";\n    /**\n     * Argument invalid in current system state.\n     */\n    Code[Code[\"FailedPrecondition\"] = 9] = \"FailedPrecondition\";\n    /**\n     * Operation aborted.\n     */\n    Code[Code[\"Aborted\"] = 10] = \"Aborted\";\n    /**\n     * Out of bounds, use instead of FailedPrecondition.\n     */\n    Code[Code[\"OutOfRange\"] = 11] = \"OutOfRange\";\n    /**\n     * Operation not implemented or disabled.\n     */\n    Code[Code[\"Unimplemented\"] = 12] = \"Unimplemented\";\n    /**\n     * Internal error, reserved for \"serious errors\".\n     */\n    Code[Code[\"Internal\"] = 13] = \"Internal\";\n    /**\n     * Unavailable, client should back off and retry.\n     */\n    Code[Code[\"Unavailable\"] = 14] = \"Unavailable\";\n    /**\n     * Unrecoverable data loss or corruption.\n     */\n    Code[Code[\"DataLoss\"] = 15] = \"DataLoss\";\n    /**\n     * Request isn't authenticated.\n     */\n    Code[Code[\"Unauthenticated\"] = 16] = \"Unauthenticated\";\n})(Code || (Code = {}));\n","// Copyright 2021-2025 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n/**\n * Determine whether the given `arg` is a message.\n * If `desc` is set, determine whether `arg` is this specific message.\n */\nexport function isMessage(arg, schema) {\n    const isMessage = arg !== null &&\n        typeof arg == \"object\" &&\n        \"$typeName\" in arg &&\n        typeof arg.$typeName == \"string\";\n    if (!isMessage) {\n        return false;\n    }\n    if (schema === undefined) {\n        return true;\n    }\n    return schema.typeName === arg.$typeName;\n}\n","// Copyright 2021-2025 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n/**\n * Scalar value types. This is a subset of field types declared by protobuf\n * enum google.protobuf.FieldDescriptorProto.Type The types GROUP and MESSAGE\n * are omitted, but the numerical values are identical.\n */\nexport var ScalarType;\n(function (ScalarType) {\n    // 0 is reserved for errors.\n    // Order is weird for historical reasons.\n    ScalarType[ScalarType[\"DOUBLE\"] = 1] = \"DOUBLE\";\n    ScalarType[ScalarType[\"FLOAT\"] = 2] = \"FLOAT\";\n    // Not ZigZag encoded.  Negative numbers take 10 bytes.  Use TYPE_SINT64 if\n    // negative values are likely.\n    ScalarType[ScalarType[\"INT64\"] = 3] = \"INT64\";\n    ScalarType[ScalarType[\"UINT64\"] = 4] = \"UINT64\";\n    // Not ZigZag encoded.  Negative numbers take 10 bytes.  Use TYPE_SINT32 if\n    // negative values are likely.\n    ScalarType[ScalarType[\"INT32\"] = 5] = \"INT32\";\n    ScalarType[ScalarType[\"FIXED64\"] = 6] = \"FIXED64\";\n    ScalarType[ScalarType[\"FIXED32\"] = 7] = \"FIXED32\";\n    ScalarType[ScalarType[\"BOOL\"] = 8] = \"BOOL\";\n    ScalarType[ScalarType[\"STRING\"] = 9] = \"STRING\";\n    // Tag-delimited aggregate.\n    // Group type is deprecated and not supported in proto3. However, Proto3\n    // implementations should still be able to parse the group wire format and\n    // treat group fields as unknown fields.\n    // TYPE_GROUP = 10,\n    // TYPE_MESSAGE = 11,  // Length-delimited aggregate.\n    // New in version 2.\n    ScalarType[ScalarType[\"BYTES\"] = 12] = \"BYTES\";\n    ScalarType[ScalarType[\"UINT32\"] = 13] = \"UINT32\";\n    // TYPE_ENUM = 14,\n    ScalarType[ScalarType[\"SFIXED32\"] = 15] = \"SFIXED32\";\n    ScalarType[ScalarType[\"SFIXED64\"] = 16] = \"SFIXED64\";\n    ScalarType[ScalarType[\"SINT32\"] = 17] = \"SINT32\";\n    ScalarType[ScalarType[\"SINT64\"] = 18] = \"SINT64\";\n})(ScalarType || (ScalarType = {}));\n","// Copyright 2008 Google Inc.  All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n// * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n// * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// Code generated by the Protocol Buffer compiler is owned by the owner\n// of the input file used when generating it.  This code is not\n// standalone and requires a support library to be linked with it.  This\n// support library is itself covered by the above license.\n/**\n * Read a 64 bit varint as two JS numbers.\n *\n * Returns tuple:\n * [0]: low bits\n * [1]: high bits\n *\n * Copyright 2008 Google Inc.  All rights reserved.\n *\n * See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/buffer_decoder.js#L175\n */\nexport function varint64read() {\n    let lowBits = 0;\n    let highBits = 0;\n    for (let shift = 0; shift < 28; shift += 7) {\n        let b = this.buf[this.pos++];\n        lowBits |= (b & 0x7f) << shift;\n        if ((b & 0x80) == 0) {\n            this.assertBounds();\n            return [lowBits, highBits];\n        }\n    }\n    let middleByte = this.buf[this.pos++];\n    // last four bits of the first 32 bit number\n    lowBits |= (middleByte & 0x0f) << 28;\n    // 3 upper bits are part of the next 32 bit number\n    highBits = (middleByte & 0x70) >> 4;\n    if ((middleByte & 0x80) == 0) {\n        this.assertBounds();\n        return [lowBits, highBits];\n    }\n    for (let shift = 3; shift <= 31; shift += 7) {\n        let b = this.buf[this.pos++];\n        highBits |= (b & 0x7f) << shift;\n        if ((b & 0x80) == 0) {\n            this.assertBounds();\n            return [lowBits, highBits];\n        }\n    }\n    throw new Error(\"invalid varint\");\n}\n/**\n * Write a 64 bit varint, given as two JS numbers, to the given bytes array.\n *\n * Copyright 2008 Google Inc.  All rights reserved.\n *\n * See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/writer.js#L344\n */\nexport function varint64write(lo, hi, bytes) {\n    for (let i = 0; i < 28; i = i + 7) {\n        const shift = lo >>> i;\n        const hasNext = !(shift >>> 7 == 0 && hi == 0);\n        const byte = (hasNext ? shift | 0x80 : shift) & 0xff;\n        bytes.push(byte);\n        if (!hasNext) {\n            return;\n        }\n    }\n    const splitBits = ((lo >>> 28) & 0x0f) | ((hi & 0x07) << 4);\n    const hasMoreBits = !(hi >> 3 == 0);\n    bytes.push((hasMoreBits ? splitBits | 0x80 : splitBits) & 0xff);\n    if (!hasMoreBits) {\n        return;\n    }\n    for (let i = 3; i < 31; i = i + 7) {\n        const shift = hi >>> i;\n        const hasNext = !(shift >>> 7 == 0);\n        const byte = (hasNext ? shift | 0x80 : shift) & 0xff;\n        bytes.push(byte);\n        if (!hasNext) {\n            return;\n        }\n    }\n    bytes.push((hi >>> 31) & 0x01);\n}\n// constants for binary math\nconst TWO_PWR_32_DBL = 0x100000000;\n/**\n * Parse decimal string of 64 bit integer value as two JS numbers.\n *\n * Copyright 2008 Google Inc.  All rights reserved.\n *\n * See https://github.com/protocolbuffers/protobuf-javascript/blob/a428c58273abad07c66071d9753bc4d1289de426/experimental/runtime/int64.js#L10\n */\nexport function int64FromString(dec) {\n    // Check for minus sign.\n    const minus = dec[0] === \"-\";\n    if (minus) {\n        dec = dec.slice(1);\n    }\n    // Work 6 decimal digits at a time, acting like we're converting base 1e6\n    // digits to binary. This is safe to do with floating point math because\n    // Number.isSafeInteger(ALL_32_BITS * 1e6) == true.\n    const base = 1e6;\n    let lowBits = 0;\n    let highBits = 0;\n    function add1e6digit(begin, end) {\n        // Note: Number('') is 0.\n        const digit1e6 = Number(dec.slice(begin, end));\n        highBits *= base;\n        lowBits = lowBits * base + digit1e6;\n        // Carry bits from lowBits to\n        if (lowBits >= TWO_PWR_32_DBL) {\n            highBits = highBits + ((lowBits / TWO_PWR_32_DBL) | 0);\n            lowBits = lowBits % TWO_PWR_32_DBL;\n        }\n    }\n    add1e6digit(-24, -18);\n    add1e6digit(-18, -12);\n    add1e6digit(-12, -6);\n    add1e6digit(-6);\n    return minus ? negate(lowBits, highBits) : newBits(lowBits, highBits);\n}\n/**\n * Losslessly converts a 64-bit signed integer in 32:32 split representation\n * into a decimal string.\n *\n * Copyright 2008 Google Inc.  All rights reserved.\n *\n * See https://github.com/protocolbuffers/protobuf-javascript/blob/a428c58273abad07c66071d9753bc4d1289de426/experimental/runtime/int64.js#L10\n */\nexport function int64ToString(lo, hi) {\n    let bits = newBits(lo, hi);\n    // If we're treating the input as a signed value and the high bit is set, do\n    // a manual two's complement conversion before the decimal conversion.\n    const negative = bits.hi & 0x80000000;\n    if (negative) {\n        bits = negate(bits.lo, bits.hi);\n    }\n    const result = uInt64ToString(bits.lo, bits.hi);\n    return negative ? \"-\" + result : result;\n}\n/**\n * Losslessly converts a 64-bit unsigned integer in 32:32 split representation\n * into a decimal string.\n *\n * Copyright 2008 Google Inc.  All rights reserved.\n *\n * See https://github.com/protocolbuffers/protobuf-javascript/blob/a428c58273abad07c66071d9753bc4d1289de426/experimental/runtime/int64.js#L10\n */\nexport function uInt64ToString(lo, hi) {\n    ({ lo, hi } = toUnsigned(lo, hi));\n    // Skip the expensive conversion if the number is small enough to use the\n    // built-in conversions.\n    // Number.MAX_SAFE_INTEGER = 0x001FFFFF FFFFFFFF, thus any number with\n    // highBits <= 0x1FFFFF can be safely expressed with a double and retain\n    // integer precision.\n    // Proven by: Number.isSafeInteger(0x1FFFFF * 2**32 + 0xFFFFFFFF) == true.\n    if (hi <= 0x1fffff) {\n        return String(TWO_PWR_32_DBL * hi + lo);\n    }\n    // What this code is doing is essentially converting the input number from\n    // base-2 to base-1e7, which allows us to represent the 64-bit range with\n    // only 3 (very large) digits. Those digits are then trivial to convert to\n    // a base-10 string.\n    // The magic numbers used here are -\n    // 2^24 = 16777216 = (1,6777216) in base-1e7.\n    // 2^48 = 281474976710656 = (2,8147497,6710656) in base-1e7.\n    // Split 32:32 representation into 16:24:24 representation so our\n    // intermediate digits don't overflow.\n    const low = lo & 0xffffff;\n    const mid = ((lo >>> 24) | (hi << 8)) & 0xffffff;\n    const high = (hi >> 16) & 0xffff;\n    // Assemble our three base-1e7 digits, ignoring carries. The maximum\n    // value in a digit at this step is representable as a 48-bit integer, which\n    // can be stored in a 64-bit floating point number.\n    let digitA = low + mid * 6777216 + high * 6710656;\n    let digitB = mid + high * 8147497;\n    let digitC = high * 2;\n    // Apply carries from A to B and from B to C.\n    const base = 10000000;\n    if (digitA >= base) {\n        digitB += Math.floor(digitA / base);\n        digitA %= base;\n    }\n    if (digitB >= base) {\n        digitC += Math.floor(digitB / base);\n        digitB %= base;\n    }\n    // If digitC is 0, then we should have returned in the trivial code path\n    // at the top for non-safe integers. Given this, we can assume both digitB\n    // and digitA need leading zeros.\n    return (digitC.toString() +\n        decimalFrom1e7WithLeadingZeros(digitB) +\n        decimalFrom1e7WithLeadingZeros(digitA));\n}\nfunction toUnsigned(lo, hi) {\n    return { lo: lo >>> 0, hi: hi >>> 0 };\n}\nfunction newBits(lo, hi) {\n    return { lo: lo | 0, hi: hi | 0 };\n}\n/**\n * Returns two's compliment negation of input.\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Signed_32-bit_integers\n */\nfunction negate(lowBits, highBits) {\n    highBits = ~highBits;\n    if (lowBits) {\n        lowBits = ~lowBits + 1;\n    }\n    else {\n        // If lowBits is 0, then bitwise-not is 0xFFFFFFFF,\n        // adding 1 to that, results in 0x100000000, which leaves\n        // the low bits 0x0 and simply adds one to the high bits.\n        highBits += 1;\n    }\n    return newBits(lowBits, highBits);\n}\n/**\n * Returns decimal representation of digit1e7 with leading zeros.\n */\nconst decimalFrom1e7WithLeadingZeros = (digit1e7) => {\n    const partial = String(digit1e7);\n    return \"0000000\".slice(partial.length) + partial;\n};\n/**\n * Write a 32 bit varint, signed or unsigned. Same as `varint64write(0, value, bytes)`\n *\n * Copyright 2008 Google Inc.  All rights reserved.\n *\n * See https://github.com/protocolbuffers/protobuf/blob/1b18833f4f2a2f681f4e4a25cdf3b0a43115ec26/js/binary/encoder.js#L144\n */\nexport function varint32write(value, bytes) {\n    if (value >= 0) {\n        // write value as varint 32\n        while (value > 0x7f) {\n            bytes.push((value & 0x7f) | 0x80);\n            value = value >>> 7;\n        }\n        bytes.push(value);\n    }\n    else {\n        for (let i = 0; i < 9; i++) {\n            bytes.push((value & 127) | 128);\n            value = value >> 7;\n        }\n        bytes.push(1);\n    }\n}\n/**\n * Read an unsigned 32 bit varint.\n *\n * See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/buffer_decoder.js#L220\n */\nexport function varint32read() {\n    let b = this.buf[this.pos++];\n    let result = b & 0x7f;\n    if ((b & 0x80) == 0) {\n        this.assertBounds();\n        return result;\n    }\n    b = this.buf[this.pos++];\n    result |= (b & 0x7f) << 7;\n    if ((b & 0x80) == 0) {\n        this.assertBounds();\n        return result;\n    }\n    b = this.buf[this.pos++];\n    result |= (b & 0x7f) << 14;\n    if ((b & 0x80) == 0) {\n        this.assertBounds();\n        return result;\n    }\n    b = this.buf[this.pos++];\n    result |= (b & 0x7f) << 21;\n    if ((b & 0x80) == 0) {\n        this.assertBounds();\n        return result;\n    }\n    // Extract only last 4 bits\n    b = this.buf[this.pos++];\n    result |= (b & 0x0f) << 28;\n    for (let readBytes = 5; (b & 0x80) !== 0 && readBytes < 10; readBytes++)\n        b = this.buf[this.pos++];\n    if ((b & 0x80) != 0)\n        throw new Error(\"invalid varint\");\n    this.assertBounds();\n    // Result can have 32 bits, convert it to unsigned\n    return result >>> 0;\n}\n","// Copyright 2021-2025 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { int64FromString, int64ToString, uInt64ToString, } from \"./wire/varint.js\";\n/**\n * Int64Support for the current environment.\n */\nexport const protoInt64 = /*@__PURE__*/ makeInt64Support();\nfunction makeInt64Support() {\n    const dv = new DataView(new ArrayBuffer(8));\n    // note that Safari 14 implements BigInt, but not the DataView methods\n    const ok = typeof BigInt === \"function\" &&\n        typeof dv.getBigInt64 === \"function\" &&\n        typeof dv.getBigUint64 === \"function\" &&\n        typeof dv.setBigInt64 === \"function\" &&\n        typeof dv.setBigUint64 === \"function\" &&\n        (!!globalThis.Deno ||\n            typeof process != \"object\" ||\n            typeof process.env != \"object\" ||\n            process.env.BUF_BIGINT_DISABLE !== \"1\");\n    if (ok) {\n        const MIN = BigInt(\"-9223372036854775808\");\n        const MAX = BigInt(\"9223372036854775807\");\n        const UMIN = BigInt(\"0\");\n        const UMAX = BigInt(\"18446744073709551615\");\n        return {\n            zero: BigInt(0),\n            supported: true,\n            parse(value) {\n                const bi = typeof value == \"bigint\" ? value : BigInt(value);\n                if (bi > MAX || bi < MIN) {\n                    throw new Error(`invalid int64: ${value}`);\n                }\n                return bi;\n            },\n            uParse(value) {\n                const bi = typeof value == \"bigint\" ? value : BigInt(value);\n                if (bi > UMAX || bi < UMIN) {\n                    throw new Error(`invalid uint64: ${value}`);\n                }\n                return bi;\n            },\n            enc(value) {\n                dv.setBigInt64(0, this.parse(value), true);\n                return {\n                    lo: dv.getInt32(0, true),\n                    hi: dv.getInt32(4, true),\n                };\n            },\n            uEnc(value) {\n                dv.setBigInt64(0, this.uParse(value), true);\n                return {\n                    lo: dv.getInt32(0, true),\n                    hi: dv.getInt32(4, true),\n                };\n            },\n            dec(lo, hi) {\n                dv.setInt32(0, lo, true);\n                dv.setInt32(4, hi, true);\n                return dv.getBigInt64(0, true);\n            },\n            uDec(lo, hi) {\n                dv.setInt32(0, lo, true);\n                dv.setInt32(4, hi, true);\n                return dv.getBigUint64(0, true);\n            },\n        };\n    }\n    return {\n        zero: \"0\",\n        supported: false,\n        parse(value) {\n            if (typeof value != \"string\") {\n                value = value.toString();\n            }\n            assertInt64String(value);\n            return value;\n        },\n        uParse(value) {\n            if (typeof value != \"string\") {\n                value = value.toString();\n            }\n            assertUInt64String(value);\n            return value;\n        },\n        enc(value) {\n            if (typeof value != \"string\") {\n                value = value.toString();\n            }\n            assertInt64String(value);\n            return int64FromString(value);\n        },\n        uEnc(value) {\n            if (typeof value != \"string\") {\n                value = value.toString();\n            }\n            assertUInt64String(value);\n            return int64FromString(value);\n        },\n        dec(lo, hi) {\n            return int64ToString(lo, hi);\n        },\n        uDec(lo, hi) {\n            return uInt64ToString(lo, hi);\n        },\n    };\n}\nfunction assertInt64String(value) {\n    if (!/^-?[0-9]+$/.test(value)) {\n        throw new Error(\"invalid int64: \" + value);\n    }\n}\nfunction assertUInt64String(value) {\n    if (!/^[0-9]+$/.test(value)) {\n        throw new Error(\"invalid uint64: \" + value);\n    }\n}\n","// Copyright 2021-2025 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { protoInt64 } from \"../proto-int64.js\";\nimport { ScalarType } from \"../descriptors.js\";\n/**\n * Returns true if both scalar values are equal.\n */\nexport function scalarEquals(type, a, b) {\n    if (a === b) {\n        // This correctly matches equal values except BYTES and (possibly) 64-bit integers.\n        return true;\n    }\n    // Special case BYTES - we need to compare each byte individually\n    if (type == ScalarType.BYTES) {\n        if (!(a instanceof Uint8Array) || !(b instanceof Uint8Array)) {\n            return false;\n        }\n        if (a.length !== b.length) {\n            return false;\n        }\n        for (let i = 0; i < a.length; i++) {\n            if (a[i] !== b[i]) {\n                return false;\n            }\n        }\n        return true;\n    }\n    // Special case 64-bit integers - we support number, string and bigint representation.\n    switch (type) {\n        case ScalarType.UINT64:\n        case ScalarType.FIXED64:\n        case ScalarType.INT64:\n        case ScalarType.SFIXED64:\n        case ScalarType.SINT64:\n            // Loose comparison will match between 0n, 0 and \"0\".\n            return a == b;\n    }\n    // Anything that hasn't been caught by strict comparison or special cased\n    // BYTES and 64-bit integers is not equal.\n    return false;\n}\n/**\n * Returns the zero value for the given scalar type.\n */\nexport function scalarZeroValue(type, longAsString) {\n    switch (type) {\n        case ScalarType.STRING:\n            return \"\";\n        case ScalarType.BOOL:\n            return false;\n        case ScalarType.DOUBLE:\n        case ScalarType.FLOAT:\n            return 0.0;\n        case ScalarType.INT64:\n        case ScalarType.UINT64:\n        case ScalarType.SFIXED64:\n        case ScalarType.FIXED64:\n        case ScalarType.SINT64:\n            return (longAsString ? \"0\" : protoInt64.zero);\n        case ScalarType.BYTES:\n            return new Uint8Array(0);\n        default:\n            // Handles INT32, UINT32, SINT32, FIXED32, SFIXED32.\n            // We do not use individual cases to save a few bytes code size.\n            return 0;\n    }\n}\n/**\n * Returns true for a zero-value. For example, an integer has the zero-value `0`,\n * a boolean is `false`, a string is `\"\"`, and bytes is an empty Uint8Array.\n *\n * In proto3, zero-values are not written to the wire, unless the field is\n * optional or repeated.\n */\nexport function isScalarZeroValue(type, value) {\n    switch (type) {\n        case ScalarType.BOOL:\n            return value === false;\n        case ScalarType.STRING:\n            return value === \"\";\n        case ScalarType.BYTES:\n            return value instanceof Uint8Array && !value.byteLength;\n        default:\n            return value == 0; // Loose comparison matches 0n, 0 and \"0\"\n    }\n}\n","// Copyright 2021-2025 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { isScalarZeroValue, scalarZeroValue } from \"./scalar.js\";\n// bootstrap-inject google.protobuf.FeatureSet.FieldPresence.IMPLICIT: const $name: FeatureSet_FieldPresence.$localName = $number;\nconst IMPLICIT = 2;\nexport const unsafeLocal = Symbol.for(\"reflect unsafe local\");\n/**\n * Return the selected field of a oneof group.\n *\n * @private\n */\nexport function unsafeOneofCase(\n// biome-ignore lint/suspicious/noExplicitAny: `any` is the best choice for dynamic access\ntarget, oneof) {\n    const c = target[oneof.localName].case;\n    if (c === undefined) {\n        return c;\n    }\n    return oneof.fields.find((f) => f.localName === c);\n}\n/**\n * Returns true if the field is set.\n *\n * @private\n */\nexport function unsafeIsSet(\n// biome-ignore lint/suspicious/noExplicitAny: `any` is the best choice for dynamic access\ntarget, field) {\n    const name = field.localName;\n    if (field.oneof) {\n        return target[field.oneof.localName].case === name;\n    }\n    if (field.presence != IMPLICIT) {\n        // Fields with explicit presence have properties on the prototype chain\n        // for default / zero values (except for proto3).\n        return (target[name] !== undefined &&\n            Object.prototype.hasOwnProperty.call(target, name));\n    }\n    switch (field.fieldKind) {\n        case \"list\":\n            return target[name].length > 0;\n        case \"map\":\n            return Object.keys(target[name]).length > 0;\n        case \"scalar\":\n            return !isScalarZeroValue(field.scalar, target[name]);\n        case \"enum\":\n            return target[name] !== field.enum.values[0].number;\n    }\n    throw new Error(\"message field with implicit presence\");\n}\n/**\n * Returns true if the field is set, but only for singular fields with explicit\n * presence (proto2).\n *\n * @private\n */\nexport function unsafeIsSetExplicit(target, localName) {\n    return (Object.prototype.hasOwnProperty.call(target, localName) &&\n        target[localName] !== undefined);\n}\n/**\n * Return a field value, respecting oneof groups.\n *\n * @private\n */\nexport function unsafeGet(target, field) {\n    if (field.oneof) {\n        const oneof = target[field.oneof.localName];\n        if (oneof.case === field.localName) {\n            return oneof.value;\n        }\n        return undefined;\n    }\n    return target[field.localName];\n}\n/**\n * Set a field value, respecting oneof groups.\n *\n * @private\n */\nexport function unsafeSet(target, field, value) {\n    if (field.oneof) {\n        target[field.oneof.localName] = {\n            case: field.localName,\n            value: value,\n        };\n    }\n    else {\n        target[field.localName] = value;\n    }\n}\n/**\n * Resets the field, so that unsafeIsSet() will return false.\n *\n * @private\n */\nexport function unsafeClear(\n// biome-ignore lint/suspicious/noExplicitAny: `any` is the best choice for dynamic access\ntarget, field) {\n    const name = field.localName;\n    if (field.oneof) {\n        const oneofLocalName = field.oneof.localName;\n        if (target[oneofLocalName].case === name) {\n            target[oneofLocalName] = { case: undefined };\n        }\n    }\n    else if (field.presence != IMPLICIT) {\n        // Fields with explicit presence have properties on the prototype chain\n        // for default / zero values (except for proto3). By deleting their own\n        // property, the field is reset.\n        delete target[name];\n    }\n    else {\n        switch (field.fieldKind) {\n            case \"map\":\n                target[name] = {};\n                break;\n            case \"list\":\n                target[name] = [];\n                break;\n            case \"enum\":\n                target[name] = field.enum.values[0].number;\n                break;\n            case \"scalar\":\n                target[name] = scalarZeroValue(field.scalar, field.longAsString);\n                break;\n        }\n    }\n}\n","// Copyright 2021-2025 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { unsafeLocal } from \"./unsafe.js\";\nexport function isObject(arg) {\n    return arg !== null && typeof arg == \"object\" && !Array.isArray(arg);\n}\nexport function isOneofADT(arg) {\n    return (arg !== null &&\n        typeof arg == \"object\" &&\n        \"case\" in arg &&\n        ((typeof arg.case == \"string\" && \"value\" in arg && arg.value != null) ||\n            (arg.case === undefined &&\n                (!(\"value\" in arg) || arg.value === undefined))));\n}\nexport function isReflectList(arg, field) {\n    var _a, _b, _c, _d;\n    if (isObject(arg) &&\n        unsafeLocal in arg &&\n        \"add\" in arg &&\n        \"field\" in arg &&\n        typeof arg.field == \"function\") {\n        if (field !== undefined) {\n            const a = field;\n            const b = arg.field();\n            return (a.listKind == b.listKind &&\n                a.scalar === b.scalar &&\n                ((_a = a.message) === null || _a === void 0 ? void 0 : _a.typeName) === ((_b = b.message) === null || _b === void 0 ? void 0 : _b.typeName) &&\n                ((_c = a.enum) === null || _c === void 0 ? void 0 : _c.typeName) === ((_d = b.enum) === null || _d === void 0 ? void 0 : _d.typeName));\n        }\n        return true;\n    }\n    return false;\n}\nexport function isReflectMap(arg, field) {\n    var _a, _b, _c, _d;\n    if (isObject(arg) &&\n        unsafeLocal in arg &&\n        \"has\" in arg &&\n        \"field\" in arg &&\n        typeof arg.field == \"function\") {\n        if (field !== undefined) {\n            const a = field, b = arg.field();\n            return (a.mapKey === b.mapKey &&\n                a.mapKind == b.mapKind &&\n                a.scalar === b.scalar &&\n                ((_a = a.message) === null || _a === void 0 ? void 0 : _a.typeName) === ((_b = b.message) === null || _b === void 0 ? void 0 : _b.typeName) &&\n                ((_c = a.enum) === null || _c === void 0 ? void 0 : _c.typeName) === ((_d = b.enum) === null || _d === void 0 ? void 0 : _d.typeName));\n        }\n        return true;\n    }\n    return false;\n}\nexport function isReflectMessage(arg, messageDesc) {\n    return (isObject(arg) &&\n        unsafeLocal in arg &&\n        \"desc\" in arg &&\n        isObject(arg.desc) &&\n        arg.desc.kind === \"message\" &&\n        (messageDesc === undefined || arg.desc.typeName == messageDesc.typeName));\n}\n","// Copyright 2021-2025 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nexport function isWrapper(arg) {\n    return isWrapperTypeName(arg.$typeName);\n}\nexport function isWrapperDesc(messageDesc) {\n    const f = messageDesc.fields[0];\n    return (isWrapperTypeName(messageDesc.typeName) &&\n        f !== undefined &&\n        f.fieldKind == \"scalar\" &&\n        f.name == \"value\" &&\n        f.number == 1);\n}\nfunction isWrapperTypeName(name) {\n    return (name.startsWith(\"google.protobuf.\") &&\n        [\n            \"DoubleValue\",\n            \"FloatValue\",\n            \"Int64Value\",\n            \"UInt64Value\",\n            \"Int32Value\",\n            \"UInt32Value\",\n            \"BoolValue\",\n            \"StringValue\",\n            \"BytesValue\",\n        ].includes(name.substring(16)));\n}\n","// Copyright 2021-2025 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { isMessage } from \"./is-message.js\";\nimport { ScalarType, } from \"./descriptors.js\";\nimport { scalarZeroValue } from \"./reflect/scalar.js\";\nimport { isObject } from \"./reflect/guard.js\";\nimport { unsafeGet, unsafeOneofCase, unsafeSet } from \"./reflect/unsafe.js\";\nimport { isWrapperDesc } from \"./wkt/wrappers.js\";\n// bootstrap-inject google.protobuf.Edition.EDITION_PROTO3: const $name: Edition.$localName = $number;\nconst EDITION_PROTO3 = 999;\n// bootstrap-inject google.protobuf.Edition.EDITION_PROTO2: const $name: Edition.$localName = $number;\nconst EDITION_PROTO2 = 998;\n// bootstrap-inject google.protobuf.FeatureSet.FieldPresence.IMPLICIT: const $name: FeatureSet_FieldPresence.$localName = $number;\nconst IMPLICIT = 2;\n/**\n * Create a new message instance.\n *\n * The second argument is an optional initializer object, where all fields are\n * optional.\n */\nexport function create(schema, init) {\n    if (isMessage(init, schema)) {\n        return init;\n    }\n    const message = createZeroMessage(schema);\n    if (init !== undefined) {\n        initMessage(schema, message, init);\n    }\n    return message;\n}\n/**\n * Sets field values from a MessageInitShape on a zero message.\n */\nfunction initMessage(messageDesc, message, init) {\n    for (const member of messageDesc.members) {\n        let value = init[member.localName];\n        if (value == null) {\n            // intentionally ignore undefined and null\n            continue;\n        }\n        let field;\n        if (member.kind == \"oneof\") {\n            const oneofField = unsafeOneofCase(init, member);\n            if (!oneofField) {\n                continue;\n            }\n            field = oneofField;\n            value = unsafeGet(init, oneofField);\n        }\n        else {\n            field = member;\n        }\n        switch (field.fieldKind) {\n            case \"message\":\n                value = toMessage(field, value);\n                break;\n            case \"scalar\":\n                value = initScalar(field, value);\n                break;\n            case \"list\":\n                value = initList(field, value);\n                break;\n            case \"map\":\n                value = initMap(field, value);\n                break;\n        }\n        unsafeSet(message, field, value);\n    }\n    return message;\n}\nfunction initScalar(field, value) {\n    if (field.scalar == ScalarType.BYTES) {\n        return toU8Arr(value);\n    }\n    return value;\n}\nfunction initMap(field, value) {\n    if (isObject(value)) {\n        if (field.scalar == ScalarType.BYTES) {\n            return convertObjectValues(value, toU8Arr);\n        }\n        if (field.mapKind == \"message\") {\n            return convertObjectValues(value, (val) => toMessage(field, val));\n        }\n    }\n    return value;\n}\nfunction initList(field, value) {\n    if (Array.isArray(value)) {\n        if (field.scalar == ScalarType.BYTES) {\n            return value.map(toU8Arr);\n        }\n        if (field.listKind == \"message\") {\n            return value.map((item) => toMessage(field, item));\n        }\n    }\n    return value;\n}\nfunction toMessage(field, value) {\n    if (field.fieldKind == \"message\" &&\n        !field.oneof &&\n        isWrapperDesc(field.message)) {\n        // Types from google/protobuf/wrappers.proto are unwrapped when used in\n        // a singular field that is not part of a oneof group.\n        return initScalar(field.message.fields[0], value);\n    }\n    if (isObject(value)) {\n        if (field.message.typeName == \"google.protobuf.Struct\" &&\n            field.parent.typeName !== \"google.protobuf.Value\") {\n            // google.protobuf.Struct is represented with JsonObject when used in a\n            // field, except when used in google.protobuf.Value.\n            return value;\n        }\n        if (!isMessage(value, field.message)) {\n            return create(field.message, value);\n        }\n    }\n    return value;\n}\n// converts any ArrayLike<number> to Uint8Array if necessary.\nfunction toU8Arr(value) {\n    return Array.isArray(value) ? new Uint8Array(value) : value;\n}\nfunction convertObjectValues(obj, fn) {\n    const ret = {};\n    for (const entry of Object.entries(obj)) {\n        ret[entry[0]] = fn(entry[1]);\n    }\n    return ret;\n}\nconst tokenZeroMessageField = Symbol();\nconst messagePrototypes = new WeakMap();\n/**\n * Create a zero message.\n */\nfunction createZeroMessage(desc) {\n    let msg;\n    if (!needsPrototypeChain(desc)) {\n        msg = {\n            $typeName: desc.typeName,\n        };\n        for (const member of desc.members) {\n            if (member.kind == \"oneof\" || member.presence == IMPLICIT) {\n                msg[member.localName] = createZeroField(member);\n            }\n        }\n    }\n    else {\n        // Support default values and track presence via the prototype chain\n        const cached = messagePrototypes.get(desc);\n        let prototype;\n        let members;\n        if (cached) {\n            ({ prototype, members } = cached);\n        }\n        else {\n            prototype = {};\n            members = new Set();\n            for (const member of desc.members) {\n                if (member.kind == \"oneof\") {\n                    // we can only put immutable values on the prototype,\n                    // oneof ADTs are mutable\n                    continue;\n                }\n                if (member.fieldKind != \"scalar\" && member.fieldKind != \"enum\") {\n                    // only scalar and enum values are immutable, map, list, and message\n                    // are not\n                    continue;\n                }\n                if (member.presence == IMPLICIT) {\n                    // implicit presence tracks field presence by zero values - e.g. 0, false, \"\", are unset, 1, true, \"x\" are set.\n                    // message, map, list fields are mutable, and also have IMPLICIT presence.\n                    continue;\n                }\n                members.add(member);\n                prototype[member.localName] = createZeroField(member);\n            }\n            messagePrototypes.set(desc, { prototype, members });\n        }\n        msg = Object.create(prototype);\n        msg.$typeName = desc.typeName;\n        for (const member of desc.members) {\n            if (members.has(member)) {\n                continue;\n            }\n            if (member.kind == \"field\") {\n                if (member.fieldKind == \"message\") {\n                    continue;\n                }\n                if (member.fieldKind == \"scalar\" || member.fieldKind == \"enum\") {\n                    if (member.presence != IMPLICIT) {\n                        continue;\n                    }\n                }\n            }\n            msg[member.localName] = createZeroField(member);\n        }\n    }\n    return msg;\n}\n/**\n * Do we need the prototype chain to track field presence?\n */\nfunction needsPrototypeChain(desc) {\n    switch (desc.file.edition) {\n        case EDITION_PROTO3:\n            // proto3 always uses implicit presence, we never need the prototype chain.\n            return false;\n        case EDITION_PROTO2:\n            // proto2 never uses implicit presence, we always need the prototype chain.\n            return true;\n        default:\n            // If a message uses scalar or enum fields with explicit presence, we need\n            // the prototype chain to track presence. This rule does not apply to fields\n            // in a oneof group - they use a different mechanism to track presence.\n            return desc.fields.some((f) => f.presence != IMPLICIT && f.fieldKind != \"message\" && !f.oneof);\n    }\n}\n/**\n * Returns a zero value for oneof groups, and for every field kind except\n * messages. Scalar and enum fields can have default values.\n */\nfunction createZeroField(field) {\n    if (field.kind == \"oneof\") {\n        return { case: undefined };\n    }\n    if (field.fieldKind == \"list\") {\n        return [];\n    }\n    if (field.fieldKind == \"map\") {\n        return {}; // Object.create(null) would be desirable here, but is unsupported by react https://react.dev/reference/react/use-server#serializable-parameters-and-return-values\n    }\n    if (field.fieldKind == \"message\") {\n        return tokenZeroMessageField;\n    }\n    const defaultValue = field.getDefaultValue();\n    if (defaultValue !== undefined) {\n        return field.fieldKind == \"scalar\" && field.longAsString\n            ? defaultValue.toString()\n            : defaultValue;\n    }\n    return field.fieldKind == \"scalar\"\n        ? scalarZeroValue(field.scalar, field.longAsString)\n        : field.enum.values[0].number;\n}\n","// Copyright 2021-2025 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nconst errorNames = [\n    \"FieldValueInvalidError\",\n    \"FieldListRangeError\",\n    \"ForeignFieldError\",\n];\nexport class FieldError extends Error {\n    constructor(fieldOrOneof, message, name = \"FieldValueInvalidError\") {\n        super(message);\n        this.name = name;\n        this.field = () => fieldOrOneof;\n    }\n}\nexport function isFieldError(arg) {\n    return (arg instanceof Error &&\n        errorNames.includes(arg.name) &&\n        \"field\" in arg &&\n        typeof arg.field == \"function\");\n}\n","// Copyright 2021-2025 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nconst symbol = Symbol.for(\"@bufbuild/protobuf/text-encoding\");\n/**\n * Protobuf-ES requires the Text Encoding API to convert UTF-8 from and to\n * binary. This WHATWG API is widely available, but it is not part of the\n * ECMAScript standard. On runtimes where it is not available, use this\n * function to provide your own implementation.\n *\n * Note that the Text Encoding API does not provide a way to validate UTF-8.\n * Our implementation falls back to use encodeURIComponent().\n */\nexport function configureTextEncoding(textEncoding) {\n    globalThis[symbol] = textEncoding;\n}\nexport function getTextEncoding() {\n    if (globalThis[symbol] == undefined) {\n        const te = new globalThis.TextEncoder();\n        const td = new globalThis.TextDecoder();\n        globalThis[symbol] = {\n            encodeUtf8(text) {\n                return te.encode(text);\n            },\n            decodeUtf8(bytes) {\n                return td.decode(bytes);\n            },\n            checkUtf8(text) {\n                try {\n                    encodeURIComponent(text);\n                    return true;\n                }\n                catch (_) {\n                    return false;\n                }\n            },\n        };\n    }\n    return globalThis[symbol];\n}\n","// Copyright 2021-2025 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { varint32read, varint32write, varint64read, varint64write, } from \"./varint.js\";\nimport { protoInt64 } from \"../proto-int64.js\";\nimport { getTextEncoding } from \"./text-encoding.js\";\n/**\n * Protobuf binary format wire types.\n *\n * A wire type provides just enough information to find the length of the\n * following value.\n *\n * See https://developers.google.com/protocol-buffers/docs/encoding#structure\n */\nexport var WireType;\n(function (WireType) {\n    /**\n     * Used for int32, int64, uint32, uint64, sint32, sint64, bool, enum\n     */\n    WireType[WireType[\"Varint\"] = 0] = \"Varint\";\n    /**\n     * Used for fixed64, sfixed64, double.\n     * Always 8 bytes with little-endian byte order.\n     */\n    WireType[WireType[\"Bit64\"] = 1] = \"Bit64\";\n    /**\n     * Used for string, bytes, embedded messages, packed repeated fields\n     *\n     * Only repeated numeric types (types which use the varint, 32-bit,\n     * or 64-bit wire types) can be packed. In proto3, such fields are\n     * packed by default.\n     */\n    WireType[WireType[\"LengthDelimited\"] = 2] = \"LengthDelimited\";\n    /**\n     * Start of a tag-delimited aggregate, such as a proto2 group, or a message\n     * in editions with message_encoding = DELIMITED.\n     */\n    WireType[WireType[\"StartGroup\"] = 3] = \"StartGroup\";\n    /**\n     * End of a tag-delimited aggregate.\n     */\n    WireType[WireType[\"EndGroup\"] = 4] = \"EndGroup\";\n    /**\n     * Used for fixed32, sfixed32, float.\n     * Always 4 bytes with little-endian byte order.\n     */\n    WireType[WireType[\"Bit32\"] = 5] = \"Bit32\";\n})(WireType || (WireType = {}));\n/**\n * Maximum value for a 32-bit floating point value (Protobuf FLOAT).\n */\nexport const FLOAT32_MAX = 3.4028234663852886e38;\n/**\n * Minimum value for a 32-bit floating point value (Protobuf FLOAT).\n */\nexport const FLOAT32_MIN = -3.4028234663852886e38;\n/**\n * Maximum value for an unsigned 32-bit integer (Protobuf UINT32, FIXED32).\n */\nexport const UINT32_MAX = 0xffffffff;\n/**\n * Maximum value for a signed 32-bit integer (Protobuf INT32, SFIXED32, SINT32).\n */\nexport const INT32_MAX = 0x7fffffff;\n/**\n * Minimum value for a signed 32-bit integer (Protobuf INT32, SFIXED32, SINT32).\n */\nexport const INT32_MIN = -0x80000000;\nexport class BinaryWriter {\n    constructor(encodeUtf8 = getTextEncoding().encodeUtf8) {\n        this.encodeUtf8 = encodeUtf8;\n        /**\n         * Previous fork states.\n         */\n        this.stack = [];\n        this.chunks = [];\n        this.buf = [];\n    }\n    /**\n     * Return all bytes written and reset this writer.\n     */\n    finish() {\n        if (this.buf.length) {\n            this.chunks.push(new Uint8Array(this.buf)); // flush the buffer\n            this.buf = [];\n        }\n        let len = 0;\n        for (let i = 0; i < this.chunks.length; i++)\n            len += this.chunks[i].length;\n        let bytes = new Uint8Array(len);\n        let offset = 0;\n        for (let i = 0; i < this.chunks.length; i++) {\n            bytes.set(this.chunks[i], offset);\n            offset += this.chunks[i].length;\n        }\n        this.chunks = [];\n        return bytes;\n    }\n    /**\n     * Start a new fork for length-delimited data like a message\n     * or a packed repeated field.\n     *\n     * Must be joined later with `join()`.\n     */\n    fork() {\n        this.stack.push({ chunks: this.chunks, buf: this.buf });\n        this.chunks = [];\n        this.buf = [];\n        return this;\n    }\n    /**\n     * Join the last fork. Write its length and bytes, then\n     * return to the previous state.\n     */\n    join() {\n        // get chunk of fork\n        let chunk = this.finish();\n        // restore previous state\n        let prev = this.stack.pop();\n        if (!prev)\n            throw new Error(\"invalid state, fork stack empty\");\n        this.chunks = prev.chunks;\n        this.buf = prev.buf;\n        // write length of chunk as varint\n        this.uint32(chunk.byteLength);\n        return this.raw(chunk);\n    }\n    /**\n     * Writes a tag (field number and wire type).\n     *\n     * Equivalent to `uint32( (fieldNo << 3 | type) >>> 0 )`.\n     *\n     * Generated code should compute the tag ahead of time and call `uint32()`.\n     */\n    tag(fieldNo, type) {\n        return this.uint32(((fieldNo << 3) | type) >>> 0);\n    }\n    /**\n     * Write a chunk of raw bytes.\n     */\n    raw(chunk) {\n        if (this.buf.length) {\n            this.chunks.push(new Uint8Array(this.buf));\n            this.buf = [];\n        }\n        this.chunks.push(chunk);\n        return this;\n    }\n    /**\n     * Write a `uint32` value, an unsigned 32 bit varint.\n     */\n    uint32(value) {\n        assertUInt32(value);\n        // write value as varint 32, inlined for speed\n        while (value > 0x7f) {\n            this.buf.push((value & 0x7f) | 0x80);\n            value = value >>> 7;\n        }\n        this.buf.push(value);\n        return this;\n    }\n    /**\n     * Write a `int32` value, a signed 32 bit varint.\n     */\n    int32(value) {\n        assertInt32(value);\n        varint32write(value, this.buf);\n        return this;\n    }\n    /**\n     * Write a `bool` value, a variant.\n     */\n    bool(value) {\n        this.buf.push(value ? 1 : 0);\n        return this;\n    }\n    /**\n     * Write a `bytes` value, length-delimited arbitrary data.\n     */\n    bytes(value) {\n        this.uint32(value.byteLength); // write length of chunk as varint\n        return this.raw(value);\n    }\n    /**\n     * Write a `string` value, length-delimited data converted to UTF-8 text.\n     */\n    string(value) {\n        let chunk = this.encodeUtf8(value);\n        this.uint32(chunk.byteLength); // write length of chunk as varint\n        return this.raw(chunk);\n    }\n    /**\n     * Write a `float` value, 32-bit floating point number.\n     */\n    float(value) {\n        assertFloat32(value);\n        let chunk = new Uint8Array(4);\n        new DataView(chunk.buffer).setFloat32(0, value, true);\n        return this.raw(chunk);\n    }\n    /**\n     * Write a `double` value, a 64-bit floating point number.\n     */\n    double(value) {\n        let chunk = new Uint8Array(8);\n        new DataView(chunk.buffer).setFloat64(0, value, true);\n        return this.raw(chunk);\n    }\n    /**\n     * Write a `fixed32` value, an unsigned, fixed-length 32-bit integer.\n     */\n    fixed32(value) {\n        assertUInt32(value);\n        let chunk = new Uint8Array(4);\n        new DataView(chunk.buffer).setUint32(0, value, true);\n        return this.raw(chunk);\n    }\n    /**\n     * Write a `sfixed32` value, a signed, fixed-length 32-bit integer.\n     */\n    sfixed32(value) {\n        assertInt32(value);\n        let chunk = new Uint8Array(4);\n        new DataView(chunk.buffer).setInt32(0, value, true);\n        return this.raw(chunk);\n    }\n    /**\n     * Write a `sint32` value, a signed, zigzag-encoded 32-bit varint.\n     */\n    sint32(value) {\n        assertInt32(value);\n        // zigzag encode\n        value = ((value << 1) ^ (value >> 31)) >>> 0;\n        varint32write(value, this.buf);\n        return this;\n    }\n    /**\n     * Write a `fixed64` value, a signed, fixed-length 64-bit integer.\n     */\n    sfixed64(value) {\n        let chunk = new Uint8Array(8), view = new DataView(chunk.buffer), tc = protoInt64.enc(value);\n        view.setInt32(0, tc.lo, true);\n        view.setInt32(4, tc.hi, true);\n        return this.raw(chunk);\n    }\n    /**\n     * Write a `fixed64` value, an unsigned, fixed-length 64 bit integer.\n     */\n    fixed64(value) {\n        let chunk = new Uint8Array(8), view = new DataView(chunk.buffer), tc = protoInt64.uEnc(value);\n        view.setInt32(0, tc.lo, true);\n        view.setInt32(4, tc.hi, true);\n        return this.raw(chunk);\n    }\n    /**\n     * Write a `int64` value, a signed 64-bit varint.\n     */\n    int64(value) {\n        let tc = protoInt64.enc(value);\n        varint64write(tc.lo, tc.hi, this.buf);\n        return this;\n    }\n    /**\n     * Write a `sint64` value, a signed, zig-zag-encoded 64-bit varint.\n     */\n    sint64(value) {\n        const tc = protoInt64.enc(value), \n        // zigzag encode\n        sign = tc.hi >> 31, lo = (tc.lo << 1) ^ sign, hi = ((tc.hi << 1) | (tc.lo >>> 31)) ^ sign;\n        varint64write(lo, hi, this.buf);\n        return this;\n    }\n    /**\n     * Write a `uint64` value, an unsigned 64-bit varint.\n     */\n    uint64(value) {\n        const tc = protoInt64.uEnc(value);\n        varint64write(tc.lo, tc.hi, this.buf);\n        return this;\n    }\n}\nexport class BinaryReader {\n    constructor(buf, decodeUtf8 = getTextEncoding().decodeUtf8) {\n        this.decodeUtf8 = decodeUtf8;\n        this.varint64 = varint64read; // dirty cast for `this`\n        /**\n         * Read a `uint32` field, an unsigned 32 bit varint.\n         */\n        this.uint32 = varint32read;\n        this.buf = buf;\n        this.len = buf.length;\n        this.pos = 0;\n        this.view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n    }\n    /**\n     * Reads a tag - field number and wire type.\n     */\n    tag() {\n        let tag = this.uint32(), fieldNo = tag >>> 3, wireType = tag & 7;\n        if (fieldNo <= 0 || wireType < 0 || wireType > 5)\n            throw new Error(\"illegal tag: field no \" + fieldNo + \" wire type \" + wireType);\n        return [fieldNo, wireType];\n    }\n    /**\n     * Skip one element and return the skipped data.\n     *\n     * When skipping StartGroup, provide the tags field number to check for\n     * matching field number in the EndGroup tag.\n     */\n    skip(wireType, fieldNo) {\n        let start = this.pos;\n        switch (wireType) {\n            case WireType.Varint:\n                while (this.buf[this.pos++] & 0x80) {\n                    // ignore\n                }\n                break;\n            // @ts-ignore TS7029: Fallthrough case in switch -- ignore instead of expect-error for compiler settings without noFallthroughCasesInSwitch: true\n            case WireType.Bit64:\n                this.pos += 4;\n            case WireType.Bit32:\n                this.pos += 4;\n                break;\n            case WireType.LengthDelimited:\n                let len = this.uint32();\n                this.pos += len;\n                break;\n            case WireType.StartGroup:\n                for (;;) {\n                    const [fn, wt] = this.tag();\n                    if (wt === WireType.EndGroup) {\n                        if (fieldNo !== undefined && fn !== fieldNo) {\n                            throw new Error(\"invalid end group tag\");\n                        }\n                        break;\n                    }\n                    this.skip(wt, fn);\n                }\n                break;\n            default:\n                throw new Error(\"cant skip wire type \" + wireType);\n        }\n        this.assertBounds();\n        return this.buf.subarray(start, this.pos);\n    }\n    /**\n     * Throws error if position in byte array is out of range.\n     */\n    assertBounds() {\n        if (this.pos > this.len)\n            throw new RangeError(\"premature EOF\");\n    }\n    /**\n     * Read a `int32` field, a signed 32 bit varint.\n     */\n    int32() {\n        return this.uint32() | 0;\n    }\n    /**\n     * Read a `sint32` field, a signed, zigzag-encoded 32-bit varint.\n     */\n    sint32() {\n        let zze = this.uint32();\n        // decode zigzag\n        return (zze >>> 1) ^ -(zze & 1);\n    }\n    /**\n     * Read a `int64` field, a signed 64-bit varint.\n     */\n    int64() {\n        return protoInt64.dec(...this.varint64());\n    }\n    /**\n     * Read a `uint64` field, an unsigned 64-bit varint.\n     */\n    uint64() {\n        return protoInt64.uDec(...this.varint64());\n    }\n    /**\n     * Read a `sint64` field, a signed, zig-zag-encoded 64-bit varint.\n     */\n    sint64() {\n        let [lo, hi] = this.varint64();\n        // decode zig zag\n        let s = -(lo & 1);\n        lo = ((lo >>> 1) | ((hi & 1) << 31)) ^ s;\n        hi = (hi >>> 1) ^ s;\n        return protoInt64.dec(lo, hi);\n    }\n    /**\n     * Read a `bool` field, a variant.\n     */\n    bool() {\n        let [lo, hi] = this.varint64();\n        return lo !== 0 || hi !== 0;\n    }\n    /**\n     * Read a `fixed32` field, an unsigned, fixed-length 32-bit integer.\n     */\n    fixed32() {\n        // biome-ignore lint/suspicious/noAssignInExpressions: no\n        return this.view.getUint32((this.pos += 4) - 4, true);\n    }\n    /**\n     * Read a `sfixed32` field, a signed, fixed-length 32-bit integer.\n     */\n    sfixed32() {\n        // biome-ignore lint/suspicious/noAssignInExpressions: no\n        return this.view.getInt32((this.pos += 4) - 4, true);\n    }\n    /**\n     * Read a `fixed64` field, an unsigned, fixed-length 64 bit integer.\n     */\n    fixed64() {\n        return protoInt64.uDec(this.sfixed32(), this.sfixed32());\n    }\n    /**\n     * Read a `fixed64` field, a signed, fixed-length 64-bit integer.\n     */\n    sfixed64() {\n        return protoInt64.dec(this.sfixed32(), this.sfixed32());\n    }\n    /**\n     * Read a `float` field, 32-bit floating point number.\n     */\n    float() {\n        // biome-ignore lint/suspicious/noAssignInExpressions: no\n        return this.view.getFloat32((this.pos += 4) - 4, true);\n    }\n    /**\n     * Read a `double` field, a 64-bit floating point number.\n     */\n    double() {\n        // biome-ignore lint/suspicious/noAssignInExpressions: no\n        return this.view.getFloat64((this.pos += 8) - 8, true);\n    }\n    /**\n     * Read a `bytes` field, length-delimited arbitrary data.\n     */\n    bytes() {\n        let len = this.uint32(), start = this.pos;\n        this.pos += len;\n        this.assertBounds();\n        return this.buf.subarray(start, start + len);\n    }\n    /**\n     * Read a `string` field, length-delimited data converted to UTF-8 text.\n     */\n    string() {\n        return this.decodeUtf8(this.bytes());\n    }\n}\n/**\n * Assert a valid signed protobuf 32-bit integer as a number or string.\n */\nfunction assertInt32(arg) {\n    if (typeof arg == \"string\") {\n        arg = Number(arg);\n    }\n    else if (typeof arg != \"number\") {\n        throw new Error(\"invalid int32: \" + typeof arg);\n    }\n    if (!Number.isInteger(arg) ||\n        arg > INT32_MAX ||\n        arg < INT32_MIN)\n        throw new Error(\"invalid int32: \" + arg);\n}\n/**\n * Assert a valid unsigned protobuf 32-bit integer as a number or string.\n */\nfunction assertUInt32(arg) {\n    if (typeof arg == \"string\") {\n        arg = Number(arg);\n    }\n    else if (typeof arg != \"number\") {\n        throw new Error(\"invalid uint32: \" + typeof arg);\n    }\n    if (!Number.isInteger(arg) ||\n        arg > UINT32_MAX ||\n        arg < 0)\n        throw new Error(\"invalid uint32: \" + arg);\n}\n/**\n * Assert a valid protobuf float value as a number or string.\n */\nfunction assertFloat32(arg) {\n    if (typeof arg == \"string\") {\n        const o = arg;\n        arg = Number(arg);\n        if (Number.isNaN(arg) && o !== \"NaN\") {\n            throw new Error(\"invalid float32: \" + o);\n        }\n    }\n    else if (typeof arg != \"number\") {\n        throw new Error(\"invalid float32: \" + typeof arg);\n    }\n    if (Number.isFinite(arg) &&\n        (arg > FLOAT32_MAX || arg < FLOAT32_MIN))\n        throw new Error(\"invalid float32: \" + arg);\n}\n","// Copyright 2021-2025 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { ScalarType, } from \"../descriptors.js\";\nimport { isMessage } from \"../is-message.js\";\nimport { FieldError } from \"./error.js\";\nimport { isReflectList, isReflectMap, isReflectMessage } from \"./guard.js\";\nimport { FLOAT32_MAX, FLOAT32_MIN, INT32_MAX, INT32_MIN, UINT32_MAX, } from \"../wire/binary-encoding.js\";\nimport { getTextEncoding } from \"../wire/text-encoding.js\";\nimport { protoInt64 } from \"../proto-int64.js\";\n/**\n * Check whether the given field value is valid for the reflect API.\n */\nexport function checkField(field, value) {\n    const check = field.fieldKind == \"list\"\n        ? isReflectList(value, field)\n        : field.fieldKind == \"map\"\n            ? isReflectMap(value, field)\n            : checkSingular(field, value);\n    if (check === true) {\n        return undefined;\n    }\n    let reason;\n    switch (field.fieldKind) {\n        case \"list\":\n            reason = `expected ${formatReflectList(field)}, got ${formatVal(value)}`;\n            break;\n        case \"map\":\n            reason = `expected ${formatReflectMap(field)}, got ${formatVal(value)}`;\n            break;\n        default: {\n            reason = reasonSingular(field, value, check);\n        }\n    }\n    return new FieldError(field, reason);\n}\n/**\n * Check whether the given list item is valid for the reflect API.\n */\nexport function checkListItem(field, index, value) {\n    const check = checkSingular(field, value);\n    if (check !== true) {\n        return new FieldError(field, `list item #${index + 1}: ${reasonSingular(field, value, check)}`);\n    }\n    return undefined;\n}\n/**\n * Check whether the given map key and value are valid for the reflect API.\n */\nexport function checkMapEntry(field, key, value) {\n    const checkKey = checkScalarValue(key, field.mapKey);\n    if (checkKey !== true) {\n        return new FieldError(field, `invalid map key: ${reasonSingular({ scalar: field.mapKey }, key, checkKey)}`);\n    }\n    const checkVal = checkSingular(field, value);\n    if (checkVal !== true) {\n        return new FieldError(field, `map entry ${formatVal(key)}: ${reasonSingular(field, value, checkVal)}`);\n    }\n    return undefined;\n}\nfunction checkSingular(field, value) {\n    if (field.scalar !== undefined) {\n        return checkScalarValue(value, field.scalar);\n    }\n    if (field.enum !== undefined) {\n        if (field.enum.open) {\n            return Number.isInteger(value);\n        }\n        return field.enum.values.some((v) => v.number === value);\n    }\n    return isReflectMessage(value, field.message);\n}\nfunction checkScalarValue(value, scalar) {\n    switch (scalar) {\n        case ScalarType.DOUBLE:\n            return typeof value == \"number\";\n        case ScalarType.FLOAT:\n            if (typeof value != \"number\") {\n                return false;\n            }\n            if (Number.isNaN(value) || !Number.isFinite(value)) {\n                return true;\n            }\n            if (value > FLOAT32_MAX || value < FLOAT32_MIN) {\n                return `${value.toFixed()} out of range`;\n            }\n            return true;\n        case ScalarType.INT32:\n        case ScalarType.SFIXED32:\n        case ScalarType.SINT32:\n            // signed\n            if (typeof value !== \"number\" || !Number.isInteger(value)) {\n                return false;\n            }\n            if (value > INT32_MAX || value < INT32_MIN) {\n                return `${value.toFixed()} out of range`;\n            }\n            return true;\n        case ScalarType.FIXED32:\n        case ScalarType.UINT32:\n            // unsigned\n            if (typeof value !== \"number\" || !Number.isInteger(value)) {\n                return false;\n            }\n            if (value > UINT32_MAX || value < 0) {\n                return `${value.toFixed()} out of range`;\n            }\n            return true;\n        case ScalarType.BOOL:\n            return typeof value == \"boolean\";\n        case ScalarType.STRING:\n            if (typeof value != \"string\") {\n                return false;\n            }\n            return getTextEncoding().checkUtf8(value) || \"invalid UTF8\";\n        case ScalarType.BYTES:\n            return value instanceof Uint8Array;\n        case ScalarType.INT64:\n        case ScalarType.SFIXED64:\n        case ScalarType.SINT64:\n            // signed\n            if (typeof value == \"bigint\" ||\n                typeof value == \"number\" ||\n                (typeof value == \"string\" && value.length > 0)) {\n                try {\n                    protoInt64.parse(value);\n                    return true;\n                }\n                catch (_) {\n                    return `${value} out of range`;\n                }\n            }\n            return false;\n        case ScalarType.FIXED64:\n        case ScalarType.UINT64:\n            // unsigned\n            if (typeof value == \"bigint\" ||\n                typeof value == \"number\" ||\n                (typeof value == \"string\" && value.length > 0)) {\n                try {\n                    protoInt64.uParse(value);\n                    return true;\n                }\n                catch (_) {\n                    return `${value} out of range`;\n                }\n            }\n            return false;\n    }\n}\nfunction reasonSingular(field, val, details) {\n    details =\n        typeof details == \"string\" ? `: ${details}` : `, got ${formatVal(val)}`;\n    if (field.scalar !== undefined) {\n        return `expected ${scalarTypeDescription(field.scalar)}` + details;\n    }\n    if (field.enum !== undefined) {\n        return `expected ${field.enum.toString()}` + details;\n    }\n    return `expected ${formatReflectMessage(field.message)}` + details;\n}\nexport function formatVal(val) {\n    switch (typeof val) {\n        case \"object\":\n            if (val === null) {\n                return \"null\";\n            }\n            if (val instanceof Uint8Array) {\n                return `Uint8Array(${val.length})`;\n            }\n            if (Array.isArray(val)) {\n                return `Array(${val.length})`;\n            }\n            if (isReflectList(val)) {\n                return formatReflectList(val.field());\n            }\n            if (isReflectMap(val)) {\n                return formatReflectMap(val.field());\n            }\n            if (isReflectMessage(val)) {\n                return formatReflectMessage(val.desc);\n            }\n            if (isMessage(val)) {\n                return `message ${val.$typeName}`;\n            }\n            return \"object\";\n        case \"string\":\n            return val.length > 30 ? \"string\" : `\"${val.split('\"').join('\\\\\"')}\"`;\n        case \"boolean\":\n            return String(val);\n        case \"number\":\n            return String(val);\n        case \"bigint\":\n            return String(val) + \"n\";\n        default:\n            // \"symbol\" | \"undefined\" | \"object\" | \"function\"\n            return typeof val;\n    }\n}\nfunction formatReflectMessage(desc) {\n    return `ReflectMessage (${desc.typeName})`;\n}\nfunction formatReflectList(field) {\n    switch (field.listKind) {\n        case \"message\":\n            return `ReflectList (${field.message.toString()})`;\n        case \"enum\":\n            return `ReflectList (${field.enum.toString()})`;\n        case \"scalar\":\n            return `ReflectList (${ScalarType[field.scalar]})`;\n    }\n}\nfunction formatReflectMap(field) {\n    switch (field.mapKind) {\n        case \"message\":\n            return `ReflectMap (${ScalarType[field.mapKey]}, ${field.message.toString()})`;\n        case \"enum\":\n            return `ReflectMap (${ScalarType[field.mapKey]}, ${field.enum.toString()})`;\n        case \"scalar\":\n            return `ReflectMap (${ScalarType[field.mapKey]}, ${ScalarType[field.scalar]})`;\n    }\n}\nfunction scalarTypeDescription(scalar) {\n    switch (scalar) {\n        case ScalarType.STRING:\n            return \"string\";\n        case ScalarType.BOOL:\n            return \"boolean\";\n        case ScalarType.INT64:\n        case ScalarType.SINT64:\n        case ScalarType.SFIXED64:\n            return \"bigint (int64)\";\n        case ScalarType.UINT64:\n        case ScalarType.FIXED64:\n            return \"bigint (uint64)\";\n        case ScalarType.BYTES:\n            return \"Uint8Array\";\n        case ScalarType.DOUBLE:\n            return \"number (float64)\";\n        case ScalarType.FLOAT:\n            return \"number (float32)\";\n        case ScalarType.FIXED32:\n        case ScalarType.UINT32:\n            return \"number (uint32)\";\n        case ScalarType.INT32:\n        case ScalarType.SFIXED32:\n        case ScalarType.SINT32:\n            return \"number (int32)\";\n    }\n}\n","// Copyright 2021-2025 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { ScalarType, } from \"../descriptors.js\";\nimport { checkField, checkListItem, checkMapEntry } from \"./reflect-check.js\";\nimport { FieldError } from \"./error.js\";\nimport { unsafeClear, unsafeGet, unsafeIsSet, unsafeLocal, unsafeOneofCase, unsafeSet, } from \"./unsafe.js\";\nimport { create } from \"../create.js\";\nimport { isWrapper, isWrapperDesc } from \"../wkt/wrappers.js\";\nimport { scalarZeroValue } from \"./scalar.js\";\nimport { protoInt64 } from \"../proto-int64.js\";\nimport { isObject, isReflectList, isReflectMap, isReflectMessage, } from \"./guard.js\";\n/**\n * Create a ReflectMessage.\n */\nexport function reflect(messageDesc, message, \n/**\n * By default, field values are validated when setting them. For example,\n * a value for an uint32 field must be a ECMAScript Number >= 0.\n *\n * When field values are trusted, performance can be improved by disabling\n * checks.\n */\ncheck = true) {\n    return new ReflectMessageImpl(messageDesc, message, check);\n}\nconst messageSortedFields = new WeakMap();\nclass ReflectMessageImpl {\n    get sortedFields() {\n        const cached = messageSortedFields.get(this.desc);\n        if (cached) {\n            return cached;\n        }\n        const sortedFields = this.desc.fields\n            .concat()\n            .sort((a, b) => a.number - b.number);\n        messageSortedFields.set(this.desc, sortedFields);\n        return sortedFields;\n    }\n    constructor(messageDesc, message, check = true) {\n        this.lists = new Map();\n        this.maps = new Map();\n        this.check = check;\n        this.desc = messageDesc;\n        this.message = this[unsafeLocal] = message !== null && message !== void 0 ? message : create(messageDesc);\n        this.fields = messageDesc.fields;\n        this.oneofs = messageDesc.oneofs;\n        this.members = messageDesc.members;\n    }\n    findNumber(number) {\n        if (!this._fieldsByNumber) {\n            this._fieldsByNumber = new Map(this.desc.fields.map((f) => [f.number, f]));\n        }\n        return this._fieldsByNumber.get(number);\n    }\n    oneofCase(oneof) {\n        assertOwn(this.message, oneof);\n        return unsafeOneofCase(this.message, oneof);\n    }\n    isSet(field) {\n        assertOwn(this.message, field);\n        return unsafeIsSet(this.message, field);\n    }\n    clear(field) {\n        assertOwn(this.message, field);\n        unsafeClear(this.message, field);\n    }\n    get(field) {\n        assertOwn(this.message, field);\n        const value = unsafeGet(this.message, field);\n        switch (field.fieldKind) {\n            case \"list\":\n                // eslint-disable-next-line no-case-declarations\n                let list = this.lists.get(field);\n                if (!list || list[unsafeLocal] !== value) {\n                    this.lists.set(field, \n                    // biome-ignore lint/suspicious/noAssignInExpressions: no\n                    (list = new ReflectListImpl(field, value, this.check)));\n                }\n                return list;\n            case \"map\":\n                let map = this.maps.get(field);\n                if (!map || map[unsafeLocal] !== value) {\n                    this.maps.set(field, \n                    // biome-ignore lint/suspicious/noAssignInExpressions: no\n                    (map = new ReflectMapImpl(field, value, this.check)));\n                }\n                return map;\n            case \"message\":\n                return messageToReflect(field, value, this.check);\n            case \"scalar\":\n                return (value === undefined\n                    ? scalarZeroValue(field.scalar, false)\n                    : longToReflect(field, value));\n            case \"enum\":\n                return (value !== null && value !== void 0 ? value : field.enum.values[0].number);\n        }\n    }\n    set(field, value) {\n        assertOwn(this.message, field);\n        if (this.check) {\n            const err = checkField(field, value);\n            if (err) {\n                throw err;\n            }\n        }\n        let local;\n        if (field.fieldKind == \"message\") {\n            local = messageToLocal(field, value);\n        }\n        else if (isReflectMap(value) || isReflectList(value)) {\n            local = value[unsafeLocal];\n        }\n        else {\n            local = longToLocal(field, value);\n        }\n        unsafeSet(this.message, field, local);\n    }\n    getUnknown() {\n        return this.message.$unknown;\n    }\n    setUnknown(value) {\n        this.message.$unknown = value;\n    }\n}\nfunction assertOwn(owner, member) {\n    if (member.parent.typeName !== owner.$typeName) {\n        throw new FieldError(member, `cannot use ${member.toString()} with message ${owner.$typeName}`, \"ForeignFieldError\");\n    }\n}\n/**\n * Create a ReflectList.\n */\nexport function reflectList(field, unsafeInput, \n/**\n * By default, field values are validated when setting them. For example,\n * a value for an uint32 field must be a ECMAScript Number >= 0.\n *\n * When field values are trusted, performance can be improved by disabling\n * checks.\n */\ncheck = true) {\n    return new ReflectListImpl(field, unsafeInput !== null && unsafeInput !== void 0 ? unsafeInput : [], check);\n}\nclass ReflectListImpl {\n    field() {\n        return this._field;\n    }\n    get size() {\n        return this._arr.length;\n    }\n    constructor(field, unsafeInput, check) {\n        this._field = field;\n        this._arr = this[unsafeLocal] = unsafeInput;\n        this.check = check;\n    }\n    get(index) {\n        const item = this._arr[index];\n        return item === undefined\n            ? undefined\n            : listItemToReflect(this._field, item, this.check);\n    }\n    set(index, item) {\n        if (index < 0 || index >= this._arr.length) {\n            throw new FieldError(this._field, `list item #${index + 1}: out of range`);\n        }\n        if (this.check) {\n            const err = checkListItem(this._field, index, item);\n            if (err) {\n                throw err;\n            }\n        }\n        this._arr[index] = listItemToLocal(this._field, item);\n    }\n    add(item) {\n        if (this.check) {\n            const err = checkListItem(this._field, this._arr.length, item);\n            if (err) {\n                throw err;\n            }\n        }\n        this._arr.push(listItemToLocal(this._field, item));\n        return undefined;\n    }\n    clear() {\n        this._arr.splice(0, this._arr.length);\n    }\n    [Symbol.iterator]() {\n        return this.values();\n    }\n    keys() {\n        return this._arr.keys();\n    }\n    *values() {\n        for (const item of this._arr) {\n            yield listItemToReflect(this._field, item, this.check);\n        }\n    }\n    *entries() {\n        for (let i = 0; i < this._arr.length; i++) {\n            yield [i, listItemToReflect(this._field, this._arr[i], this.check)];\n        }\n    }\n}\n/**\n * Create a ReflectMap.\n */\nexport function reflectMap(field, unsafeInput, \n/**\n * By default, field values are validated when setting them. For example,\n * a value for an uint32 field must be a ECMAScript Number >= 0.\n *\n * When field values are trusted, performance can be improved by disabling\n * checks.\n */\ncheck = true) {\n    return new ReflectMapImpl(field, unsafeInput, check);\n}\nclass ReflectMapImpl {\n    constructor(field, unsafeInput, check = true) {\n        this.obj = this[unsafeLocal] = unsafeInput !== null && unsafeInput !== void 0 ? unsafeInput : {};\n        this.check = check;\n        this._field = field;\n    }\n    field() {\n        return this._field;\n    }\n    set(key, value) {\n        if (this.check) {\n            const err = checkMapEntry(this._field, key, value);\n            if (err) {\n                throw err;\n            }\n        }\n        this.obj[mapKeyToLocal(key)] = mapValueToLocal(this._field, value);\n        return this;\n    }\n    delete(key) {\n        const k = mapKeyToLocal(key);\n        const has = Object.prototype.hasOwnProperty.call(this.obj, k);\n        if (has) {\n            delete this.obj[k];\n        }\n        return has;\n    }\n    clear() {\n        for (const key of Object.keys(this.obj)) {\n            delete this.obj[key];\n        }\n    }\n    get(key) {\n        let val = this.obj[mapKeyToLocal(key)];\n        if (val !== undefined) {\n            val = mapValueToReflect(this._field, val, this.check);\n        }\n        return val;\n    }\n    has(key) {\n        return Object.prototype.hasOwnProperty.call(this.obj, mapKeyToLocal(key));\n    }\n    *keys() {\n        for (const objKey of Object.keys(this.obj)) {\n            yield mapKeyToReflect(objKey, this._field.mapKey);\n        }\n    }\n    *entries() {\n        for (const objEntry of Object.entries(this.obj)) {\n            yield [\n                mapKeyToReflect(objEntry[0], this._field.mapKey),\n                mapValueToReflect(this._field, objEntry[1], this.check),\n            ];\n        }\n    }\n    [Symbol.iterator]() {\n        return this.entries();\n    }\n    get size() {\n        return Object.keys(this.obj).length;\n    }\n    *values() {\n        for (const val of Object.values(this.obj)) {\n            yield mapValueToReflect(this._field, val, this.check);\n        }\n    }\n    forEach(callbackfn, thisArg) {\n        for (const mapEntry of this.entries()) {\n            callbackfn.call(thisArg, mapEntry[1], mapEntry[0], this);\n        }\n    }\n}\nfunction messageToLocal(field, value) {\n    if (!isReflectMessage(value)) {\n        return value;\n    }\n    if (isWrapper(value.message) &&\n        !field.oneof &&\n        field.fieldKind == \"message\") {\n        // Types from google/protobuf/wrappers.proto are unwrapped when used in\n        // a singular field that is not part of a oneof group.\n        return value.message.value;\n    }\n    if (value.desc.typeName == \"google.protobuf.Struct\" &&\n        field.parent.typeName != \"google.protobuf.Value\") {\n        // google.protobuf.Struct is represented with JsonObject when used in a\n        // field, except when used in google.protobuf.Value.\n        return wktStructToLocal(value.message);\n    }\n    return value.message;\n}\nfunction messageToReflect(field, value, check) {\n    if (value !== undefined) {\n        if (isWrapperDesc(field.message) &&\n            !field.oneof &&\n            field.fieldKind == \"message\") {\n            // Types from google/protobuf/wrappers.proto are unwrapped when used in\n            // a singular field that is not part of a oneof group.\n            value = {\n                $typeName: field.message.typeName,\n                value: longToReflect(field.message.fields[0], value),\n            };\n        }\n        else if (field.message.typeName == \"google.protobuf.Struct\" &&\n            field.parent.typeName != \"google.protobuf.Value\" &&\n            isObject(value)) {\n            // google.protobuf.Struct is represented with JsonObject when used in a\n            // field, except when used in google.protobuf.Value.\n            value = wktStructToReflect(value);\n        }\n    }\n    return new ReflectMessageImpl(field.message, value, check);\n}\nfunction listItemToLocal(field, value) {\n    if (field.listKind == \"message\") {\n        return messageToLocal(field, value);\n    }\n    return longToLocal(field, value);\n}\nfunction listItemToReflect(field, value, check) {\n    if (field.listKind == \"message\") {\n        return messageToReflect(field, value, check);\n    }\n    return longToReflect(field, value);\n}\nfunction mapValueToLocal(field, value) {\n    if (field.mapKind == \"message\") {\n        return messageToLocal(field, value);\n    }\n    return longToLocal(field, value);\n}\nfunction mapValueToReflect(field, value, check) {\n    if (field.mapKind == \"message\") {\n        return messageToReflect(field, value, check);\n    }\n    return value;\n}\nfunction mapKeyToLocal(key) {\n    return typeof key == \"string\" || typeof key == \"number\" ? key : String(key);\n}\n/**\n * Converts a map key (any scalar value except float, double, or bytes) from its\n * representation in a message (string or number, the only possible object key\n * types) to the closest possible type in ECMAScript.\n */\nfunction mapKeyToReflect(key, type) {\n    switch (type) {\n        case ScalarType.STRING:\n            return key;\n        case ScalarType.INT32:\n        case ScalarType.FIXED32:\n        case ScalarType.UINT32:\n        case ScalarType.SFIXED32:\n        case ScalarType.SINT32: {\n            const n = Number.parseInt(key);\n            if (Number.isFinite(n)) {\n                return n;\n            }\n            break;\n        }\n        case ScalarType.BOOL:\n            switch (key) {\n                case \"true\":\n                    return true;\n                case \"false\":\n                    return false;\n            }\n            break;\n        case ScalarType.UINT64:\n        case ScalarType.FIXED64:\n            try {\n                return protoInt64.uParse(key);\n            }\n            catch (_a) {\n                //\n            }\n            break;\n        default:\n            // INT64, SFIXED64, SINT64\n            try {\n                return protoInt64.parse(key);\n            }\n            catch (_b) {\n                //\n            }\n            break;\n    }\n    return key;\n}\nfunction longToReflect(field, value) {\n    switch (field.scalar) {\n        case ScalarType.INT64:\n        case ScalarType.SFIXED64:\n        case ScalarType.SINT64:\n            if (\"longAsString\" in field &&\n                field.longAsString &&\n                typeof value == \"string\") {\n                value = protoInt64.parse(value);\n            }\n            break;\n        case ScalarType.FIXED64:\n        case ScalarType.UINT64:\n            if (\"longAsString\" in field &&\n                field.longAsString &&\n                typeof value == \"string\") {\n                value = protoInt64.uParse(value);\n            }\n            break;\n    }\n    return value;\n}\nfunction longToLocal(field, value) {\n    switch (field.scalar) {\n        case ScalarType.INT64:\n        case ScalarType.SFIXED64:\n        case ScalarType.SINT64:\n            if (\"longAsString\" in field && field.longAsString) {\n                value = String(value);\n            }\n            else if (typeof value == \"string\" || typeof value == \"number\") {\n                value = protoInt64.parse(value);\n            }\n            break;\n        case ScalarType.FIXED64:\n        case ScalarType.UINT64:\n            if (\"longAsString\" in field && field.longAsString) {\n                value = String(value);\n            }\n            else if (typeof value == \"string\" || typeof value == \"number\") {\n                value = protoInt64.uParse(value);\n            }\n            break;\n    }\n    return value;\n}\nfunction wktStructToReflect(json) {\n    const struct = {\n        $typeName: \"google.protobuf.Struct\",\n        fields: {},\n    };\n    if (isObject(json)) {\n        for (const [k, v] of Object.entries(json)) {\n            struct.fields[k] = wktValueToReflect(v);\n        }\n    }\n    return struct;\n}\nfunction wktStructToLocal(val) {\n    const json = {};\n    for (const [k, v] of Object.entries(val.fields)) {\n        json[k] = wktValueToLocal(v);\n    }\n    return json;\n}\nfunction wktValueToLocal(val) {\n    switch (val.kind.case) {\n        case \"structValue\":\n            return wktStructToLocal(val.kind.value);\n        case \"listValue\":\n            return val.kind.value.values.map(wktValueToLocal);\n        case \"nullValue\":\n        case undefined:\n            return null;\n        default:\n            return val.kind.value;\n    }\n}\nfunction wktValueToReflect(json) {\n    const value = {\n        $typeName: \"google.protobuf.Value\",\n        kind: { case: undefined },\n    };\n    switch (typeof json) {\n        case \"number\":\n            value.kind = { case: \"numberValue\", value: json };\n            break;\n        case \"string\":\n            value.kind = { case: \"stringValue\", value: json };\n            break;\n        case \"boolean\":\n            value.kind = { case: \"boolValue\", value: json };\n            break;\n        case \"object\":\n            if (json === null) {\n                const nullValue = 0;\n                value.kind = { case: \"nullValue\", value: nullValue };\n            }\n            else if (Array.isArray(json)) {\n                const listValue = {\n                    $typeName: \"google.protobuf.ListValue\",\n                    values: [],\n                };\n                if (Array.isArray(json)) {\n                    for (const e of json) {\n                        listValue.values.push(wktValueToReflect(e));\n                    }\n                }\n                value.kind = {\n                    case: \"listValue\",\n                    value: listValue,\n                };\n            }\n            else {\n                value.kind = {\n                    case: \"structValue\",\n                    value: wktStructToReflect(json),\n                };\n            }\n            break;\n    }\n    return value;\n}\n","// Copyright 2021-2025 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n/**\n * Decodes a base64 string to a byte array.\n *\n * - ignores white-space, including line breaks and tabs\n * - allows inner padding (can decode concatenated base64 strings)\n * - does not require padding\n * - understands base64url encoding:\n *   \"-\" instead of \"+\",\n *   \"_\" instead of \"/\",\n *   no padding\n */\nexport function base64Decode(base64Str) {\n    const table = getDecodeTable();\n    // estimate byte size, not accounting for inner padding and whitespace\n    let es = (base64Str.length * 3) / 4;\n    if (base64Str[base64Str.length - 2] == \"=\")\n        es -= 2;\n    else if (base64Str[base64Str.length - 1] == \"=\")\n        es -= 1;\n    let bytes = new Uint8Array(es), bytePos = 0, // position in byte array\n    groupPos = 0, // position in base64 group\n    b, // current byte\n    p = 0; // previous byte\n    for (let i = 0; i < base64Str.length; i++) {\n        b = table[base64Str.charCodeAt(i)];\n        if (b === undefined) {\n            switch (base64Str[i]) {\n                // @ts-ignore TS7029: Fallthrough case in switch -- ignore instead of expect-error for compiler settings without noFallthroughCasesInSwitch: true\n                case \"=\":\n                    groupPos = 0; // reset state when padding found\n                case \"\\n\":\n                case \"\\r\":\n                case \"\\t\":\n                case \" \":\n                    continue; // skip white-space, and padding\n                default:\n                    throw Error(\"invalid base64 string\");\n            }\n        }\n        switch (groupPos) {\n            case 0:\n                p = b;\n                groupPos = 1;\n                break;\n            case 1:\n                bytes[bytePos++] = (p << 2) | ((b & 48) >> 4);\n                p = b;\n                groupPos = 2;\n                break;\n            case 2:\n                bytes[bytePos++] = ((p & 15) << 4) | ((b & 60) >> 2);\n                p = b;\n                groupPos = 3;\n                break;\n            case 3:\n                bytes[bytePos++] = ((p & 3) << 6) | b;\n                groupPos = 0;\n                break;\n        }\n    }\n    if (groupPos == 1)\n        throw Error(\"invalid base64 string\");\n    return bytes.subarray(0, bytePos);\n}\n/**\n * Encode a byte array to a base64 string.\n *\n * By default, this function uses the standard base64 encoding with padding.\n *\n * To encode without padding, use encoding = \"std_raw\".\n *\n * To encode with the URL encoding, use encoding = \"url\", which replaces the\n * characters +/ by their URL-safe counterparts -_, and omits padding.\n */\nexport function base64Encode(bytes, encoding = \"std\") {\n    const table = getEncodeTable(encoding);\n    const pad = encoding == \"std\";\n    let base64 = \"\", groupPos = 0, // position in base64 group\n    b, // current byte\n    p = 0; // carry over from previous byte\n    for (let i = 0; i < bytes.length; i++) {\n        b = bytes[i];\n        switch (groupPos) {\n            case 0:\n                base64 += table[b >> 2];\n                p = (b & 3) << 4;\n                groupPos = 1;\n                break;\n            case 1:\n                base64 += table[p | (b >> 4)];\n                p = (b & 15) << 2;\n                groupPos = 2;\n                break;\n            case 2:\n                base64 += table[p | (b >> 6)];\n                base64 += table[b & 63];\n                groupPos = 0;\n                break;\n        }\n    }\n    // add output padding\n    if (groupPos) {\n        base64 += table[p];\n        if (pad) {\n            base64 += \"=\";\n            if (groupPos == 1)\n                base64 += \"=\";\n        }\n    }\n    return base64;\n}\n// lookup table from base64 character to byte\nlet encodeTableStd;\nlet encodeTableUrl;\n// lookup table from base64 character *code* to byte because lookup by number is fast\nlet decodeTable;\nfunction getEncodeTable(encoding) {\n    if (!encodeTableStd) {\n        encodeTableStd =\n            \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\".split(\"\");\n        encodeTableUrl = encodeTableStd.slice(0, -2).concat(\"-\", \"_\");\n    }\n    return encoding == \"url\"\n        ? // biome-ignore lint/style/noNonNullAssertion: TS fails to narrow down\n            encodeTableUrl\n        : encodeTableStd;\n}\nfunction getDecodeTable() {\n    if (!decodeTable) {\n        decodeTable = [];\n        const encodeTable = getEncodeTable(\"std\");\n        for (let i = 0; i < encodeTable.length; i++)\n            decodeTable[encodeTable[i].charCodeAt(0)] = i;\n        // support base64url variants\n        decodeTable[\"-\".charCodeAt(0)] = encodeTable.indexOf(\"+\");\n        decodeTable[\"_\".charCodeAt(0)] = encodeTable.indexOf(\"/\");\n    }\n    return decodeTable;\n}\n","// Copyright 2021-2025 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n/**\n * Return a fully-qualified name for a Protobuf descriptor.\n * For a file descriptor, return the original file path.\n *\n * See https://protobuf.com/docs/language-spec#fully-qualified-names\n */\nexport function qualifiedName(desc) {\n    switch (desc.kind) {\n        case \"field\":\n        case \"oneof\":\n        case \"rpc\":\n            return desc.parent.typeName + \".\" + desc.name;\n        case \"enum_value\": {\n            const p = desc.parent.parent\n                ? desc.parent.parent.typeName\n                : desc.parent.file.proto.package;\n            return p + (p.length > 0 ? \".\" : \"\") + desc.name;\n        }\n        case \"service\":\n        case \"message\":\n        case \"enum\":\n        case \"extension\":\n            return desc.typeName;\n        case \"file\":\n            return desc.proto.name;\n    }\n}\n/**\n * Converts snake_case to protoCamelCase according to the convention\n * used by protoc to convert a field name to a JSON name.\n */\nexport function protoCamelCase(snakeCase) {\n    let capNext = false;\n    const b = [];\n    for (let i = 0; i < snakeCase.length; i++) {\n        let c = snakeCase.charAt(i);\n        switch (c) {\n            case \"_\":\n                capNext = true;\n                break;\n            case \"0\":\n            case \"1\":\n            case \"2\":\n            case \"3\":\n            case \"4\":\n            case \"5\":\n            case \"6\":\n            case \"7\":\n            case \"8\":\n            case \"9\":\n                b.push(c);\n                capNext = false;\n                break;\n            default:\n                if (capNext) {\n                    capNext = false;\n                    c = c.toUpperCase();\n                }\n                b.push(c);\n                break;\n        }\n    }\n    return b.join(\"\");\n}\n/**\n * Names that cannot be used for object properties because they are reserved\n * by built-in JavaScript properties.\n */\nconst reservedObjectProperties = new Set([\n    // names reserved by JavaScript\n    \"constructor\",\n    \"toString\",\n    \"toJSON\",\n    \"valueOf\",\n]);\n/**\n * Escapes names that are reserved for ECMAScript built-in object properties.\n *\n * Also see safeIdentifier() from @bufbuild/protoplugin.\n */\nexport function safeObjectProperty(name) {\n    return reservedObjectProperties.has(name) ? name + \"$\" : name;\n}\n","// Copyright 2021-2025 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { protoCamelCase } from \"../reflect/names.js\";\nimport { unsafeIsSetExplicit } from \"../reflect/unsafe.js\";\n/**\n * @private\n */\nexport function restoreJsonNames(message) {\n    for (const f of message.field) {\n        if (!unsafeIsSetExplicit(f, \"jsonName\")) {\n            f.jsonName = protoCamelCase(f.name);\n        }\n    }\n    message.nestedType.forEach(restoreJsonNames);\n}\n","// Copyright 2021-2025 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { ScalarType } from \"../descriptors.js\";\nimport { protoInt64 } from \"../proto-int64.js\";\n/**\n * Parse an enum value from the Protobuf text format.\n *\n * @private\n */\nexport function parseTextFormatEnumValue(descEnum, value) {\n    const enumValue = descEnum.values.find((v) => v.name === value);\n    if (!enumValue) {\n        throw new Error(`cannot parse ${descEnum} default value: ${value}`);\n    }\n    return enumValue.number;\n}\n/**\n * Parse a scalar value from the Protobuf text format.\n *\n * @private\n */\nexport function parseTextFormatScalarValue(type, value) {\n    switch (type) {\n        case ScalarType.STRING:\n            return value;\n        case ScalarType.BYTES: {\n            const u = unescapeBytesDefaultValue(value);\n            if (u === false) {\n                throw new Error(`cannot parse ${ScalarType[type]} default value: ${value}`);\n            }\n            return u;\n        }\n        case ScalarType.INT64:\n        case ScalarType.SFIXED64:\n        case ScalarType.SINT64:\n            return protoInt64.parse(value);\n        case ScalarType.UINT64:\n        case ScalarType.FIXED64:\n            return protoInt64.uParse(value);\n        case ScalarType.DOUBLE:\n        case ScalarType.FLOAT:\n            switch (value) {\n                case \"inf\":\n                    return Number.POSITIVE_INFINITY;\n                case \"-inf\":\n                    return Number.NEGATIVE_INFINITY;\n                case \"nan\":\n                    return Number.NaN;\n                default:\n                    return parseFloat(value);\n            }\n        case ScalarType.BOOL:\n            return value === \"true\";\n        case ScalarType.INT32:\n        case ScalarType.UINT32:\n        case ScalarType.SINT32:\n        case ScalarType.FIXED32:\n        case ScalarType.SFIXED32:\n            return parseInt(value, 10);\n    }\n}\n/**\n * Parses a text-encoded default value (proto2) of a BYTES field.\n */\nfunction unescapeBytesDefaultValue(str) {\n    const b = [];\n    const input = {\n        tail: str,\n        c: \"\",\n        next() {\n            if (this.tail.length == 0) {\n                return false;\n            }\n            this.c = this.tail[0];\n            this.tail = this.tail.substring(1);\n            return true;\n        },\n        take(n) {\n            if (this.tail.length >= n) {\n                const r = this.tail.substring(0, n);\n                this.tail = this.tail.substring(n);\n                return r;\n            }\n            return false;\n        },\n    };\n    while (input.next()) {\n        switch (input.c) {\n            case \"\\\\\":\n                if (input.next()) {\n                    switch (input.c) {\n                        case \"\\\\\":\n                            b.push(input.c.charCodeAt(0));\n                            break;\n                        case \"b\":\n                            b.push(0x08);\n                            break;\n                        case \"f\":\n                            b.push(0x0c);\n                            break;\n                        case \"n\":\n                            b.push(0x0a);\n                            break;\n                        case \"r\":\n                            b.push(0x0d);\n                            break;\n                        case \"t\":\n                            b.push(0x09);\n                            break;\n                        case \"v\":\n                            b.push(0x0b);\n                            break;\n                        case \"0\":\n                        case \"1\":\n                        case \"2\":\n                        case \"3\":\n                        case \"4\":\n                        case \"5\":\n                        case \"6\":\n                        case \"7\": {\n                            const s = input.c;\n                            const t = input.take(2);\n                            if (t === false) {\n                                return false;\n                            }\n                            const n = parseInt(s + t, 8);\n                            if (Number.isNaN(n)) {\n                                return false;\n                            }\n                            b.push(n);\n                            break;\n                        }\n                        case \"x\": {\n                            const s = input.c;\n                            const t = input.take(2);\n                            if (t === false) {\n                                return false;\n                            }\n                            const n = parseInt(s + t, 16);\n                            if (Number.isNaN(n)) {\n                                return false;\n                            }\n                            b.push(n);\n                            break;\n                        }\n                        case \"u\": {\n                            const s = input.c;\n                            const t = input.take(4);\n                            if (t === false) {\n                                return false;\n                            }\n                            const n = parseInt(s + t, 16);\n                            if (Number.isNaN(n)) {\n                                return false;\n                            }\n                            const chunk = new Uint8Array(4);\n                            const view = new DataView(chunk.buffer);\n                            view.setInt32(0, n, true);\n                            b.push(chunk[0], chunk[1], chunk[2], chunk[3]);\n                            break;\n                        }\n                        case \"U\": {\n                            const s = input.c;\n                            const t = input.take(8);\n                            if (t === false) {\n                                return false;\n                            }\n                            const tc = protoInt64.uEnc(s + t);\n                            const chunk = new Uint8Array(8);\n                            const view = new DataView(chunk.buffer);\n                            view.setInt32(0, tc.lo, true);\n                            view.setInt32(4, tc.hi, true);\n                            b.push(chunk[0], chunk[1], chunk[2], chunk[3], chunk[4], chunk[5], chunk[6], chunk[7]);\n                            break;\n                        }\n                    }\n                }\n                break;\n            default:\n                b.push(input.c.charCodeAt(0));\n        }\n    }\n    return new Uint8Array(b);\n}\n","// Copyright 2021-2025 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n/**\n * Iterate over all types - enumerations, extensions, services, messages -\n * and enumerations, extensions and messages nested in messages.\n */\nexport function* nestedTypes(desc) {\n    switch (desc.kind) {\n        case \"file\":\n            for (const message of desc.messages) {\n                yield message;\n                yield* nestedTypes(message);\n            }\n            yield* desc.enums;\n            yield* desc.services;\n            yield* desc.extensions;\n            break;\n        case \"message\":\n            for (const message of desc.nestedMessages) {\n                yield message;\n                yield* nestedTypes(message);\n            }\n            yield* desc.nestedEnums;\n            yield* desc.nestedExtensions;\n            break;\n    }\n}\n/**\n * Iterate over types referenced by fields of the given message.\n *\n * For example:\n *\n * ```proto\n * syntax=\"proto3\";\n *\n * message Example {\n *   Msg singular = 1;\n *   repeated Level list = 2;\n * }\n *\n * message Msg {}\n *\n * enum Level {\n *   LEVEL_UNSPECIFIED = 0;\n * }\n * ```\n *\n * The message Example references the message Msg, and the enum Level.\n */\nexport function usedTypes(descMessage) {\n    return usedTypesInternal(descMessage, new Set());\n}\nfunction* usedTypesInternal(descMessage, seen) {\n    var _a, _b;\n    for (const field of descMessage.fields) {\n        const ref = (_b = (_a = field.enum) !== null && _a !== void 0 ? _a : field.message) !== null && _b !== void 0 ? _b : undefined;\n        if (!ref || seen.has(ref.typeName)) {\n            continue;\n        }\n        seen.add(ref.typeName);\n        yield ref;\n        if (ref.kind == \"message\") {\n            yield* usedTypesInternal(ref, seen);\n        }\n    }\n}\n/**\n * Returns the ancestors of a given Protobuf element, up to the file.\n */\nexport function parentTypes(desc) {\n    const parents = [];\n    while (desc.kind !== \"file\") {\n        const p = parent(desc);\n        desc = p;\n        parents.push(p);\n    }\n    return parents;\n}\nfunction parent(desc) {\n    var _a;\n    switch (desc.kind) {\n        case \"enum_value\":\n        case \"field\":\n        case \"oneof\":\n        case \"rpc\":\n            return desc.parent;\n        case \"service\":\n            return desc.file;\n        case \"extension\":\n        case \"enum\":\n        case \"message\":\n            return (_a = desc.parent) !== null && _a !== void 0 ? _a : desc.file;\n    }\n}\n","// Copyright 2021-2025 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { ScalarType, } from \"./descriptors.js\";\nimport { parseTextFormatEnumValue, parseTextFormatScalarValue, } from \"./wire/text-format.js\";\nimport { nestedTypes } from \"./reflect/nested-types.js\";\nimport { unsafeIsSetExplicit } from \"./reflect/unsafe.js\";\nimport { protoCamelCase, safeObjectProperty } from \"./reflect/names.js\";\n/**\n * Create a registry from the given inputs.\n *\n * An input can be:\n * - Any message, enum, service, or extension descriptor, which adds just the\n *   descriptor for this type.\n * - A file descriptor, which adds all typed defined in this file.\n * - A registry, which adds all types from the registry.\n *\n * For duplicate descriptors (same type name), the one given last wins.\n */\nexport function createRegistry(...input) {\n    return initBaseRegistry(input);\n}\n/**\n * Create a registry that allows adding and removing descriptors.\n */\nexport function createMutableRegistry(...input) {\n    const reg = initBaseRegistry(input);\n    return Object.assign(Object.assign({}, reg), { remove(desc) {\n            var _a;\n            if (desc.kind == \"extension\") {\n                (_a = reg.extendees.get(desc.extendee.typeName)) === null || _a === void 0 ? void 0 : _a.delete(desc.number);\n            }\n            reg.types.delete(desc.typeName);\n        } });\n}\nexport function createFileRegistry(...args) {\n    const registry = createBaseRegistry();\n    if (!args.length) {\n        return registry;\n    }\n    if (\"$typeName\" in args[0] &&\n        args[0].$typeName == \"google.protobuf.FileDescriptorSet\") {\n        for (const file of args[0].file) {\n            addFile(file, registry);\n        }\n        return registry;\n    }\n    if (\"$typeName\" in args[0]) {\n        const input = args[0];\n        const resolve = args[1];\n        const seen = new Set();\n        function recurseDeps(file) {\n            const deps = [];\n            for (const protoFileName of file.dependency) {\n                if (registry.getFile(protoFileName) != undefined) {\n                    continue;\n                }\n                if (seen.has(protoFileName)) {\n                    continue;\n                }\n                const dep = resolve(protoFileName);\n                if (!dep) {\n                    throw new Error(`Unable to resolve ${protoFileName}, imported by ${file.name}`);\n                }\n                if (\"kind\" in dep) {\n                    registry.addFile(dep, false, true);\n                }\n                else {\n                    seen.add(dep.name);\n                    deps.push(dep);\n                }\n            }\n            return deps.concat(...deps.map(recurseDeps));\n        }\n        for (const file of [input, ...recurseDeps(input)].reverse()) {\n            addFile(file, registry);\n        }\n    }\n    else {\n        for (const fileReg of args) {\n            for (const file of fileReg.files) {\n                registry.addFile(file);\n            }\n        }\n    }\n    return registry;\n}\n/**\n * @private\n */\nfunction createBaseRegistry() {\n    const types = new Map();\n    const extendees = new Map();\n    const files = new Map();\n    return {\n        kind: \"registry\",\n        types,\n        extendees,\n        [Symbol.iterator]() {\n            return types.values();\n        },\n        get files() {\n            return files.values();\n        },\n        addFile(file, skipTypes, withDeps) {\n            files.set(file.proto.name, file);\n            if (!skipTypes) {\n                for (const type of nestedTypes(file)) {\n                    this.add(type);\n                }\n            }\n            if (withDeps) {\n                for (const f of file.dependencies) {\n                    this.addFile(f, skipTypes, withDeps);\n                }\n            }\n        },\n        add(desc) {\n            if (desc.kind == \"extension\") {\n                let numberToExt = extendees.get(desc.extendee.typeName);\n                if (!numberToExt) {\n                    extendees.set(desc.extendee.typeName, \n                    // biome-ignore lint/suspicious/noAssignInExpressions: no\n                    (numberToExt = new Map()));\n                }\n                numberToExt.set(desc.number, desc);\n            }\n            types.set(desc.typeName, desc);\n        },\n        get(typeName) {\n            return types.get(typeName);\n        },\n        getFile(fileName) {\n            return files.get(fileName);\n        },\n        getMessage(typeName) {\n            const t = types.get(typeName);\n            return (t === null || t === void 0 ? void 0 : t.kind) == \"message\" ? t : undefined;\n        },\n        getEnum(typeName) {\n            const t = types.get(typeName);\n            return (t === null || t === void 0 ? void 0 : t.kind) == \"enum\" ? t : undefined;\n        },\n        getExtension(typeName) {\n            const t = types.get(typeName);\n            return (t === null || t === void 0 ? void 0 : t.kind) == \"extension\" ? t : undefined;\n        },\n        getExtensionFor(extendee, no) {\n            var _a;\n            return (_a = extendees.get(extendee.typeName)) === null || _a === void 0 ? void 0 : _a.get(no);\n        },\n        getService(typeName) {\n            const t = types.get(typeName);\n            return (t === null || t === void 0 ? void 0 : t.kind) == \"service\" ? t : undefined;\n        },\n    };\n}\n/**\n * @private\n */\nfunction initBaseRegistry(inputs) {\n    const registry = createBaseRegistry();\n    for (const input of inputs) {\n        switch (input.kind) {\n            case \"registry\":\n                for (const n of input) {\n                    registry.add(n);\n                }\n                break;\n            case \"file\":\n                registry.addFile(input);\n                break;\n            default:\n                registry.add(input);\n                break;\n        }\n    }\n    return registry;\n}\n// bootstrap-inject google.protobuf.Edition.EDITION_PROTO2: const $name: Edition.$localName = $number;\nconst EDITION_PROTO2 = 998;\n// bootstrap-inject google.protobuf.Edition.EDITION_PROTO3: const $name: Edition.$localName = $number;\nconst EDITION_PROTO3 = 999;\n// bootstrap-inject google.protobuf.FieldDescriptorProto.Type.TYPE_STRING: const $name: FieldDescriptorProto_Type.$localName = $number;\nconst TYPE_STRING = 9;\n// bootstrap-inject google.protobuf.FieldDescriptorProto.Type.TYPE_GROUP: const $name: FieldDescriptorProto_Type.$localName = $number;\nconst TYPE_GROUP = 10;\n// bootstrap-inject google.protobuf.FieldDescriptorProto.Type.TYPE_MESSAGE: const $name: FieldDescriptorProto_Type.$localName = $number;\nconst TYPE_MESSAGE = 11;\n// bootstrap-inject google.protobuf.FieldDescriptorProto.Type.TYPE_BYTES: const $name: FieldDescriptorProto_Type.$localName = $number;\nconst TYPE_BYTES = 12;\n// bootstrap-inject google.protobuf.FieldDescriptorProto.Type.TYPE_ENUM: const $name: FieldDescriptorProto_Type.$localName = $number;\nconst TYPE_ENUM = 14;\n// bootstrap-inject google.protobuf.FieldDescriptorProto.Label.LABEL_REPEATED: const $name: FieldDescriptorProto_Label.$localName = $number;\nconst LABEL_REPEATED = 3;\n// bootstrap-inject google.protobuf.FieldDescriptorProto.Label.LABEL_REQUIRED: const $name: FieldDescriptorProto_Label.$localName = $number;\nconst LABEL_REQUIRED = 2;\n// bootstrap-inject google.protobuf.FieldOptions.JSType.JS_STRING: const $name: FieldOptions_JSType.$localName = $number;\nconst JS_STRING = 1;\n// bootstrap-inject google.protobuf.MethodOptions.IdempotencyLevel.IDEMPOTENCY_UNKNOWN: const $name: MethodOptions_IdempotencyLevel.$localName = $number;\nconst IDEMPOTENCY_UNKNOWN = 0;\n// bootstrap-inject google.protobuf.FeatureSet.FieldPresence.EXPLICIT: const $name: FeatureSet_FieldPresence.$localName = $number;\nconst EXPLICIT = 1;\n// bootstrap-inject google.protobuf.FeatureSet.FieldPresence.IMPLICIT: const $name: FeatureSet_FieldPresence.$localName = $number;\nconst IMPLICIT = 2;\n// bootstrap-inject google.protobuf.FeatureSet.FieldPresence.LEGACY_REQUIRED: const $name: FeatureSet_FieldPresence.$localName = $number;\nconst LEGACY_REQUIRED = 3;\n// bootstrap-inject google.protobuf.FeatureSet.RepeatedFieldEncoding.PACKED: const $name: FeatureSet_RepeatedFieldEncoding.$localName = $number;\nconst PACKED = 1;\n// bootstrap-inject google.protobuf.FeatureSet.MessageEncoding.DELIMITED: const $name: FeatureSet_MessageEncoding.$localName = $number;\nconst DELIMITED = 2;\n// bootstrap-inject google.protobuf.FeatureSet.EnumType.OPEN: const $name: FeatureSet_EnumType.$localName = $number;\nconst OPEN = 1;\n// biome-ignore format: want this to read well\n// bootstrap-inject defaults: EDITION_PROTO2 to EDITION_2024: export const minimumEdition: SupportedEdition = $minimumEdition, maximumEdition: SupportedEdition = $maximumEdition;\n// generated from protoc v33.0\nexport const minimumEdition = 998, maximumEdition = 1001;\nconst featureDefaults = {\n    // EDITION_PROTO2\n    998: {\n        fieldPresence: 1, // EXPLICIT,\n        enumType: 2, // CLOSED,\n        repeatedFieldEncoding: 2, // EXPANDED,\n        utf8Validation: 3, // NONE,\n        messageEncoding: 1, // LENGTH_PREFIXED,\n        jsonFormat: 2, // LEGACY_BEST_EFFORT,\n        enforceNamingStyle: 2, // STYLE_LEGACY,\n        defaultSymbolVisibility: 1, // EXPORT_ALL,\n    },\n    // EDITION_PROTO3\n    999: {\n        fieldPresence: 2, // IMPLICIT,\n        enumType: 1, // OPEN,\n        repeatedFieldEncoding: 1, // PACKED,\n        utf8Validation: 2, // VERIFY,\n        messageEncoding: 1, // LENGTH_PREFIXED,\n        jsonFormat: 1, // ALLOW,\n        enforceNamingStyle: 2, // STYLE_LEGACY,\n        defaultSymbolVisibility: 1, // EXPORT_ALL,\n    },\n    // EDITION_2023\n    1000: {\n        fieldPresence: 1, // EXPLICIT,\n        enumType: 1, // OPEN,\n        repeatedFieldEncoding: 1, // PACKED,\n        utf8Validation: 2, // VERIFY,\n        messageEncoding: 1, // LENGTH_PREFIXED,\n        jsonFormat: 1, // ALLOW,\n        enforceNamingStyle: 2, // STYLE_LEGACY,\n        defaultSymbolVisibility: 1, // EXPORT_ALL,\n    },\n    // EDITION_2024\n    1001: {\n        fieldPresence: 1, // EXPLICIT,\n        enumType: 1, // OPEN,\n        repeatedFieldEncoding: 1, // PACKED,\n        utf8Validation: 2, // VERIFY,\n        messageEncoding: 1, // LENGTH_PREFIXED,\n        jsonFormat: 1, // ALLOW,\n        enforceNamingStyle: 1, // STYLE2024,\n        defaultSymbolVisibility: 2, // EXPORT_TOP_LEVEL,\n    },\n};\n/**\n * Create a descriptor for a file, add it to the registry.\n */\nfunction addFile(proto, reg) {\n    var _a, _b;\n    const file = {\n        kind: \"file\",\n        proto,\n        deprecated: (_b = (_a = proto.options) === null || _a === void 0 ? void 0 : _a.deprecated) !== null && _b !== void 0 ? _b : false,\n        edition: getFileEdition(proto),\n        name: proto.name.replace(/\\.proto$/, \"\"),\n        dependencies: findFileDependencies(proto, reg),\n        enums: [],\n        messages: [],\n        extensions: [],\n        services: [],\n        toString() {\n            // eslint-disable-next-line @typescript-eslint/restrict-template-expressions -- we asserted above\n            return `file ${proto.name}`;\n        },\n    };\n    const mapEntriesStore = new Map();\n    const mapEntries = {\n        get(typeName) {\n            return mapEntriesStore.get(typeName);\n        },\n        add(desc) {\n            var _a;\n            assert(((_a = desc.proto.options) === null || _a === void 0 ? void 0 : _a.mapEntry) === true);\n            mapEntriesStore.set(desc.typeName, desc);\n        },\n    };\n    for (const enumProto of proto.enumType) {\n        addEnum(enumProto, file, undefined, reg);\n    }\n    for (const messageProto of proto.messageType) {\n        addMessage(messageProto, file, undefined, reg, mapEntries);\n    }\n    for (const serviceProto of proto.service) {\n        addService(serviceProto, file, reg);\n    }\n    addExtensions(file, reg);\n    for (const mapEntry of mapEntriesStore.values()) {\n        // to create a map field, we need access to the map entry's fields\n        addFields(mapEntry, reg, mapEntries);\n    }\n    for (const message of file.messages) {\n        addFields(message, reg, mapEntries);\n        addExtensions(message, reg);\n    }\n    reg.addFile(file, true);\n}\n/**\n * Create descriptors for extensions, and add them to the message / file,\n * and to our cart.\n * Recurses into nested types.\n */\nfunction addExtensions(desc, reg) {\n    switch (desc.kind) {\n        case \"file\":\n            for (const proto of desc.proto.extension) {\n                const ext = newField(proto, desc, reg);\n                desc.extensions.push(ext);\n                reg.add(ext);\n            }\n            break;\n        case \"message\":\n            for (const proto of desc.proto.extension) {\n                const ext = newField(proto, desc, reg);\n                desc.nestedExtensions.push(ext);\n                reg.add(ext);\n            }\n            for (const message of desc.nestedMessages) {\n                addExtensions(message, reg);\n            }\n            break;\n    }\n}\n/**\n * Create descriptors for fields and oneof groups, and add them to the message.\n * Recurses into nested types.\n */\nfunction addFields(message, reg, mapEntries) {\n    const allOneofs = message.proto.oneofDecl.map((proto) => newOneof(proto, message));\n    const oneofsSeen = new Set();\n    for (const proto of message.proto.field) {\n        const oneof = findOneof(proto, allOneofs);\n        const field = newField(proto, message, reg, oneof, mapEntries);\n        message.fields.push(field);\n        message.field[field.localName] = field;\n        if (oneof === undefined) {\n            message.members.push(field);\n        }\n        else {\n            oneof.fields.push(field);\n            if (!oneofsSeen.has(oneof)) {\n                oneofsSeen.add(oneof);\n                message.members.push(oneof);\n            }\n        }\n    }\n    for (const oneof of allOneofs.filter((o) => oneofsSeen.has(o))) {\n        message.oneofs.push(oneof);\n    }\n    for (const child of message.nestedMessages) {\n        addFields(child, reg, mapEntries);\n    }\n}\n/**\n * Create a descriptor for an enumeration, and add it our cart and to the\n * parent type, if any.\n */\nfunction addEnum(proto, file, parent, reg) {\n    var _a, _b, _c, _d, _e;\n    const sharedPrefix = findEnumSharedPrefix(proto.name, proto.value);\n    const desc = {\n        kind: \"enum\",\n        proto,\n        deprecated: (_b = (_a = proto.options) === null || _a === void 0 ? void 0 : _a.deprecated) !== null && _b !== void 0 ? _b : false,\n        file,\n        parent,\n        open: true,\n        name: proto.name,\n        typeName: makeTypeName(proto, parent, file),\n        value: {},\n        values: [],\n        sharedPrefix,\n        toString() {\n            return `enum ${this.typeName}`;\n        },\n    };\n    desc.open = isEnumOpen(desc);\n    reg.add(desc);\n    for (const p of proto.value) {\n        const name = p.name;\n        desc.values.push(\n        // biome-ignore lint/suspicious/noAssignInExpressions: no\n        (desc.value[p.number] = {\n            kind: \"enum_value\",\n            proto: p,\n            deprecated: (_d = (_c = p.options) === null || _c === void 0 ? void 0 : _c.deprecated) !== null && _d !== void 0 ? _d : false,\n            parent: desc,\n            name,\n            localName: safeObjectProperty(sharedPrefix == undefined\n                ? name\n                : name.substring(sharedPrefix.length)),\n            number: p.number,\n            toString() {\n                return `enum value ${desc.typeName}.${name}`;\n            },\n        }));\n    }\n    ((_e = parent === null || parent === void 0 ? void 0 : parent.nestedEnums) !== null && _e !== void 0 ? _e : file.enums).push(desc);\n}\n/**\n * Create a descriptor for a message, including nested types, and add it to our\n * cart. Note that this does not create descriptors fields.\n */\nfunction addMessage(proto, file, parent, reg, mapEntries) {\n    var _a, _b, _c, _d;\n    const desc = {\n        kind: \"message\",\n        proto,\n        deprecated: (_b = (_a = proto.options) === null || _a === void 0 ? void 0 : _a.deprecated) !== null && _b !== void 0 ? _b : false,\n        file,\n        parent,\n        name: proto.name,\n        typeName: makeTypeName(proto, parent, file),\n        fields: [],\n        field: {},\n        oneofs: [],\n        members: [],\n        nestedEnums: [],\n        nestedMessages: [],\n        nestedExtensions: [],\n        toString() {\n            return `message ${this.typeName}`;\n        },\n    };\n    if (((_c = proto.options) === null || _c === void 0 ? void 0 : _c.mapEntry) === true) {\n        mapEntries.add(desc);\n    }\n    else {\n        ((_d = parent === null || parent === void 0 ? void 0 : parent.nestedMessages) !== null && _d !== void 0 ? _d : file.messages).push(desc);\n        reg.add(desc);\n    }\n    for (const enumProto of proto.enumType) {\n        addEnum(enumProto, file, desc, reg);\n    }\n    for (const messageProto of proto.nestedType) {\n        addMessage(messageProto, file, desc, reg, mapEntries);\n    }\n}\n/**\n * Create a descriptor for a service, including methods, and add it to our\n * cart.\n */\nfunction addService(proto, file, reg) {\n    var _a, _b;\n    const desc = {\n        kind: \"service\",\n        proto,\n        deprecated: (_b = (_a = proto.options) === null || _a === void 0 ? void 0 : _a.deprecated) !== null && _b !== void 0 ? _b : false,\n        file,\n        name: proto.name,\n        typeName: makeTypeName(proto, undefined, file),\n        methods: [],\n        method: {},\n        toString() {\n            return `service ${this.typeName}`;\n        },\n    };\n    file.services.push(desc);\n    reg.add(desc);\n    for (const methodProto of proto.method) {\n        const method = newMethod(methodProto, desc, reg);\n        desc.methods.push(method);\n        desc.method[method.localName] = method;\n    }\n}\n/**\n * Create a descriptor for a method.\n */\nfunction newMethod(proto, parent, reg) {\n    var _a, _b, _c, _d;\n    let methodKind;\n    if (proto.clientStreaming && proto.serverStreaming) {\n        methodKind = \"bidi_streaming\";\n    }\n    else if (proto.clientStreaming) {\n        methodKind = \"client_streaming\";\n    }\n    else if (proto.serverStreaming) {\n        methodKind = \"server_streaming\";\n    }\n    else {\n        methodKind = \"unary\";\n    }\n    const input = reg.getMessage(trimLeadingDot(proto.inputType));\n    const output = reg.getMessage(trimLeadingDot(proto.outputType));\n    assert(input, `invalid MethodDescriptorProto: input_type ${proto.inputType} not found`);\n    assert(output, `invalid MethodDescriptorProto: output_type ${proto.inputType} not found`);\n    const name = proto.name;\n    return {\n        kind: \"rpc\",\n        proto,\n        deprecated: (_b = (_a = proto.options) === null || _a === void 0 ? void 0 : _a.deprecated) !== null && _b !== void 0 ? _b : false,\n        parent,\n        name,\n        localName: safeObjectProperty(name.length\n            ? safeObjectProperty(name[0].toLowerCase() + name.substring(1))\n            : name),\n        methodKind,\n        input,\n        output,\n        idempotency: (_d = (_c = proto.options) === null || _c === void 0 ? void 0 : _c.idempotencyLevel) !== null && _d !== void 0 ? _d : IDEMPOTENCY_UNKNOWN,\n        toString() {\n            return `rpc ${parent.typeName}.${name}`;\n        },\n    };\n}\n/**\n * Create a descriptor for a oneof group.\n */\nfunction newOneof(proto, parent) {\n    return {\n        kind: \"oneof\",\n        proto,\n        deprecated: false,\n        parent,\n        fields: [],\n        name: proto.name,\n        localName: safeObjectProperty(protoCamelCase(proto.name)),\n        toString() {\n            return `oneof ${parent.typeName}.${this.name}`;\n        },\n    };\n}\nfunction newField(proto, parentOrFile, reg, oneof, mapEntries) {\n    var _a, _b, _c;\n    const isExtension = mapEntries === undefined;\n    const field = {\n        kind: \"field\",\n        proto,\n        deprecated: (_b = (_a = proto.options) === null || _a === void 0 ? void 0 : _a.deprecated) !== null && _b !== void 0 ? _b : false,\n        name: proto.name,\n        number: proto.number,\n        scalar: undefined,\n        message: undefined,\n        enum: undefined,\n        presence: getFieldPresence(proto, oneof, isExtension, parentOrFile),\n        listKind: undefined,\n        mapKind: undefined,\n        mapKey: undefined,\n        delimitedEncoding: undefined,\n        packed: undefined,\n        longAsString: false,\n        getDefaultValue: undefined,\n    };\n    if (isExtension) {\n        // extension field\n        const file = parentOrFile.kind == \"file\" ? parentOrFile : parentOrFile.file;\n        const parent = parentOrFile.kind == \"file\" ? undefined : parentOrFile;\n        const typeName = makeTypeName(proto, parent, file);\n        field.kind = \"extension\";\n        field.file = file;\n        field.parent = parent;\n        field.oneof = undefined;\n        field.typeName = typeName;\n        field.jsonName = `[${typeName}]`; // option json_name is not allowed on extension fields\n        field.toString = () => `extension ${typeName}`;\n        const extendee = reg.getMessage(trimLeadingDot(proto.extendee));\n        assert(extendee, `invalid FieldDescriptorProto: extendee ${proto.extendee} not found`);\n        field.extendee = extendee;\n    }\n    else {\n        // regular field\n        const parent = parentOrFile;\n        assert(parent.kind == \"message\");\n        field.parent = parent;\n        field.oneof = oneof;\n        field.localName = oneof\n            ? protoCamelCase(proto.name)\n            : safeObjectProperty(protoCamelCase(proto.name));\n        field.jsonName = proto.jsonName;\n        field.toString = () => `field ${parent.typeName}.${proto.name}`;\n    }\n    const label = proto.label;\n    const type = proto.type;\n    const jstype = (_c = proto.options) === null || _c === void 0 ? void 0 : _c.jstype;\n    if (label === LABEL_REPEATED) {\n        // list or map field\n        const mapEntry = type == TYPE_MESSAGE\n            ? mapEntries === null || mapEntries === void 0 ? void 0 : mapEntries.get(trimLeadingDot(proto.typeName))\n            : undefined;\n        if (mapEntry) {\n            // map field\n            field.fieldKind = \"map\";\n            const { key, value } = findMapEntryFields(mapEntry);\n            field.mapKey = key.scalar;\n            field.mapKind = value.fieldKind;\n            field.message = value.message;\n            field.delimitedEncoding = false; // map fields are always LENGTH_PREFIXED\n            field.enum = value.enum;\n            field.scalar = value.scalar;\n            return field;\n        }\n        // list field\n        field.fieldKind = \"list\";\n        switch (type) {\n            case TYPE_MESSAGE:\n            case TYPE_GROUP:\n                field.listKind = \"message\";\n                field.message = reg.getMessage(trimLeadingDot(proto.typeName));\n                assert(field.message);\n                field.delimitedEncoding = isDelimitedEncoding(proto, parentOrFile);\n                break;\n            case TYPE_ENUM:\n                field.listKind = \"enum\";\n                field.enum = reg.getEnum(trimLeadingDot(proto.typeName));\n                assert(field.enum);\n                break;\n            default:\n                field.listKind = \"scalar\";\n                field.scalar = type;\n                field.longAsString = jstype == JS_STRING;\n                break;\n        }\n        field.packed = isPackedField(proto, parentOrFile);\n        return field;\n    }\n    // singular\n    switch (type) {\n        case TYPE_MESSAGE:\n        case TYPE_GROUP:\n            field.fieldKind = \"message\";\n            field.message = reg.getMessage(trimLeadingDot(proto.typeName));\n            assert(field.message, `invalid FieldDescriptorProto: type_name ${proto.typeName} not found`);\n            field.delimitedEncoding = isDelimitedEncoding(proto, parentOrFile);\n            field.getDefaultValue = () => undefined;\n            break;\n        case TYPE_ENUM: {\n            const enumeration = reg.getEnum(trimLeadingDot(proto.typeName));\n            assert(enumeration !== undefined, `invalid FieldDescriptorProto: type_name ${proto.typeName} not found`);\n            field.fieldKind = \"enum\";\n            field.enum = reg.getEnum(trimLeadingDot(proto.typeName));\n            field.getDefaultValue = () => {\n                return unsafeIsSetExplicit(proto, \"defaultValue\")\n                    ? parseTextFormatEnumValue(enumeration, proto.defaultValue)\n                    : undefined;\n            };\n            break;\n        }\n        default: {\n            field.fieldKind = \"scalar\";\n            field.scalar = type;\n            field.longAsString = jstype == JS_STRING;\n            field.getDefaultValue = () => {\n                return unsafeIsSetExplicit(proto, \"defaultValue\")\n                    ? parseTextFormatScalarValue(type, proto.defaultValue)\n                    : undefined;\n            };\n            break;\n        }\n    }\n    return field;\n}\n/**\n * Parse the \"syntax\" and \"edition\" fields, returning one of the supported\n * editions.\n */\nfunction getFileEdition(proto) {\n    switch (proto.syntax) {\n        case \"\":\n        case \"proto2\":\n            return EDITION_PROTO2;\n        case \"proto3\":\n            return EDITION_PROTO3;\n        case \"editions\":\n            if (proto.edition in featureDefaults) {\n                return proto.edition;\n            }\n            throw new Error(`${proto.name}: unsupported edition`);\n        default:\n            throw new Error(`${proto.name}: unsupported syntax \"${proto.syntax}\"`);\n    }\n}\n/**\n * Resolve dependencies of FileDescriptorProto to DescFile.\n */\nfunction findFileDependencies(proto, reg) {\n    return proto.dependency.map((wantName) => {\n        const dep = reg.getFile(wantName);\n        if (!dep) {\n            throw new Error(`Cannot find ${wantName}, imported by ${proto.name}`);\n        }\n        return dep;\n    });\n}\n/**\n * Finds a prefix shared by enum values, for example `my_enum_` for\n * `enum MyEnum {MY_ENUM_A=0; MY_ENUM_B=1;}`.\n */\nfunction findEnumSharedPrefix(enumName, values) {\n    const prefix = camelToSnakeCase(enumName) + \"_\";\n    for (const value of values) {\n        if (!value.name.toLowerCase().startsWith(prefix)) {\n            return undefined;\n        }\n        const shortName = value.name.substring(prefix.length);\n        if (shortName.length == 0) {\n            return undefined;\n        }\n        if (/^\\d/.test(shortName)) {\n            // identifiers must not start with numbers\n            return undefined;\n        }\n    }\n    return prefix;\n}\n/**\n * Converts lowerCamelCase or UpperCamelCase into lower_snake_case.\n * This is used to find shared prefixes in an enum.\n */\nfunction camelToSnakeCase(camel) {\n    return (camel.substring(0, 1) + camel.substring(1).replace(/[A-Z]/g, (c) => \"_\" + c)).toLowerCase();\n}\n/**\n * Create a fully qualified name for a protobuf type or extension field.\n *\n * The fully qualified name for messages, enumerations, and services is\n * constructed by concatenating the package name (if present), parent\n * message names (for nested types), and the type name. We omit the leading\n * dot added by protobuf compilers. Examples:\n * - mypackage.MyMessage\n * - mypackage.MyMessage.NestedMessage\n *\n * The fully qualified name for extension fields is constructed by\n * concatenating the package name (if present), parent message names (for\n * extensions declared within a message), and the field name. Examples:\n * - mypackage.extfield\n * - mypackage.MyMessage.extfield\n */\nfunction makeTypeName(proto, parent, file) {\n    let typeName;\n    if (parent) {\n        typeName = `${parent.typeName}.${proto.name}`;\n    }\n    else if (file.proto.package.length > 0) {\n        typeName = `${file.proto.package}.${proto.name}`;\n    }\n    else {\n        typeName = `${proto.name}`;\n    }\n    return typeName;\n}\n/**\n * Remove the leading dot from a fully qualified type name.\n */\nfunction trimLeadingDot(typeName) {\n    return typeName.startsWith(\".\") ? typeName.substring(1) : typeName;\n}\n/**\n * Did the user put the field in a oneof group?\n * Synthetic oneofs for proto3 optionals are ignored.\n */\nfunction findOneof(proto, allOneofs) {\n    if (!unsafeIsSetExplicit(proto, \"oneofIndex\")) {\n        return undefined;\n    }\n    if (proto.proto3Optional) {\n        return undefined;\n    }\n    const oneof = allOneofs[proto.oneofIndex];\n    assert(oneof, `invalid FieldDescriptorProto: oneof #${proto.oneofIndex} for field #${proto.number} not found`);\n    return oneof;\n}\n/**\n * Presence of the field.\n * See https://protobuf.dev/programming-guides/field_presence/\n */\nfunction getFieldPresence(proto, oneof, isExtension, parent) {\n    if (proto.label == LABEL_REQUIRED) {\n        // proto2 required is LEGACY_REQUIRED\n        return LEGACY_REQUIRED;\n    }\n    if (proto.label == LABEL_REPEATED) {\n        // repeated fields (including maps) do not track presence\n        return IMPLICIT;\n    }\n    if (!!oneof || proto.proto3Optional) {\n        // oneof is always explicit\n        return EXPLICIT;\n    }\n    if (isExtension) {\n        // extensions always track presence\n        return EXPLICIT;\n    }\n    const resolved = resolveFeature(\"fieldPresence\", { proto, parent });\n    if (resolved == IMPLICIT &&\n        (proto.type == TYPE_MESSAGE || proto.type == TYPE_GROUP)) {\n        // singular message field cannot be implicit\n        return EXPLICIT;\n    }\n    return resolved;\n}\n/**\n * Pack this repeated field?\n */\nfunction isPackedField(proto, parent) {\n    if (proto.label != LABEL_REPEATED) {\n        return false;\n    }\n    switch (proto.type) {\n        case TYPE_STRING:\n        case TYPE_BYTES:\n        case TYPE_GROUP:\n        case TYPE_MESSAGE:\n            // length-delimited types cannot be packed\n            return false;\n    }\n    const o = proto.options;\n    if (o && unsafeIsSetExplicit(o, \"packed\")) {\n        // prefer the field option over edition features\n        return o.packed;\n    }\n    return (PACKED ==\n        resolveFeature(\"repeatedFieldEncoding\", {\n            proto,\n            parent,\n        }));\n}\n/**\n * Find the key and value fields of a synthetic map entry message.\n */\nfunction findMapEntryFields(mapEntry) {\n    const key = mapEntry.fields.find((f) => f.number === 1);\n    const value = mapEntry.fields.find((f) => f.number === 2);\n    assert(key &&\n        key.fieldKind == \"scalar\" &&\n        key.scalar != ScalarType.BYTES &&\n        key.scalar != ScalarType.FLOAT &&\n        key.scalar != ScalarType.DOUBLE &&\n        value &&\n        value.fieldKind != \"list\" &&\n        value.fieldKind != \"map\");\n    return { key, value };\n}\n/**\n * Enumerations can be open or closed.\n * See https://protobuf.dev/programming-guides/enum/\n */\nfunction isEnumOpen(desc) {\n    var _a;\n    return (OPEN ==\n        resolveFeature(\"enumType\", {\n            proto: desc.proto,\n            parent: (_a = desc.parent) !== null && _a !== void 0 ? _a : desc.file,\n        }));\n}\n/**\n * Encode the message delimited (a.k.a. proto2 group encoding), or\n * length-prefixed?\n */\nfunction isDelimitedEncoding(proto, parent) {\n    if (proto.type == TYPE_GROUP) {\n        return true;\n    }\n    return (DELIMITED ==\n        resolveFeature(\"messageEncoding\", {\n            proto,\n            parent,\n        }));\n}\nfunction resolveFeature(name, ref) {\n    var _a, _b;\n    const featureSet = (_a = ref.proto.options) === null || _a === void 0 ? void 0 : _a.features;\n    if (featureSet) {\n        const val = featureSet[name];\n        if (val != 0) {\n            return val;\n        }\n    }\n    if (\"kind\" in ref) {\n        if (ref.kind == \"message\") {\n            return resolveFeature(name, (_b = ref.parent) !== null && _b !== void 0 ? _b : ref.file);\n        }\n        const editionDefaults = featureDefaults[ref.edition];\n        if (!editionDefaults) {\n            throw new Error(`feature default for edition ${ref.edition} not found`);\n        }\n        return editionDefaults[name];\n    }\n    return resolveFeature(name, ref.parent);\n}\n/**\n * Assert that condition is truthy or throw error (with message)\n */\nfunction assert(condition, msg) {\n    if (!condition) {\n        throw new Error(msg);\n    }\n}\n","// Copyright 2021-2025 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { restoreJsonNames } from \"./restore-json-names.js\";\nimport { createFileRegistry } from \"../registry.js\";\n/**\n * Hydrate a file descriptor for google/protobuf/descriptor.proto from a plain\n * object.\n *\n * See createFileDescriptorProtoBoot() for details.\n *\n * @private\n */\nexport function boot(boot) {\n    const root = bootFileDescriptorProto(boot);\n    root.messageType.forEach(restoreJsonNames);\n    const reg = createFileRegistry(root, () => undefined);\n    // biome-ignore lint/style/noNonNullAssertion: non-null assertion because we just created the registry from the file we look up\n    return reg.getFile(root.name);\n}\n/**\n * Creates the message google.protobuf.FileDescriptorProto from an object literal.\n *\n * See createFileDescriptorProtoBoot() for details.\n *\n * @private\n */\nexport function bootFileDescriptorProto(init) {\n    const proto = Object.create({\n        syntax: \"\",\n        edition: 0,\n    });\n    return Object.assign(proto, Object.assign(Object.assign({ $typeName: \"google.protobuf.FileDescriptorProto\", dependency: [], publicDependency: [], weakDependency: [], optionDependency: [], service: [], extension: [] }, init), { messageType: init.messageType.map(bootDescriptorProto), enumType: init.enumType.map(bootEnumDescriptorProto) }));\n}\nfunction bootDescriptorProto(init) {\n    var _a, _b, _c, _d, _e, _f, _g, _h;\n    const proto = Object.create({\n        visibility: 0,\n    });\n    return Object.assign(proto, {\n        $typeName: \"google.protobuf.DescriptorProto\",\n        name: init.name,\n        field: (_b = (_a = init.field) === null || _a === void 0 ? void 0 : _a.map(bootFieldDescriptorProto)) !== null && _b !== void 0 ? _b : [],\n        extension: [],\n        nestedType: (_d = (_c = init.nestedType) === null || _c === void 0 ? void 0 : _c.map(bootDescriptorProto)) !== null && _d !== void 0 ? _d : [],\n        enumType: (_f = (_e = init.enumType) === null || _e === void 0 ? void 0 : _e.map(bootEnumDescriptorProto)) !== null && _f !== void 0 ? _f : [],\n        extensionRange: (_h = (_g = init.extensionRange) === null || _g === void 0 ? void 0 : _g.map((e) => (Object.assign({ $typeName: \"google.protobuf.DescriptorProto.ExtensionRange\" }, e)))) !== null && _h !== void 0 ? _h : [],\n        oneofDecl: [],\n        reservedRange: [],\n        reservedName: [],\n    });\n}\nfunction bootFieldDescriptorProto(init) {\n    const proto = Object.create({\n        label: 1,\n        typeName: \"\",\n        extendee: \"\",\n        defaultValue: \"\",\n        oneofIndex: 0,\n        jsonName: \"\",\n        proto3Optional: false,\n    });\n    return Object.assign(proto, Object.assign(Object.assign({ $typeName: \"google.protobuf.FieldDescriptorProto\" }, init), { options: init.options ? bootFieldOptions(init.options) : undefined }));\n}\nfunction bootFieldOptions(init) {\n    var _a, _b, _c;\n    const proto = Object.create({\n        ctype: 0,\n        packed: false,\n        jstype: 0,\n        lazy: false,\n        unverifiedLazy: false,\n        deprecated: false,\n        weak: false,\n        debugRedact: false,\n        retention: 0,\n    });\n    return Object.assign(proto, Object.assign(Object.assign({ $typeName: \"google.protobuf.FieldOptions\" }, init), { targets: (_a = init.targets) !== null && _a !== void 0 ? _a : [], editionDefaults: (_c = (_b = init.editionDefaults) === null || _b === void 0 ? void 0 : _b.map((e) => (Object.assign({ $typeName: \"google.protobuf.FieldOptions.EditionDefault\" }, e)))) !== null && _c !== void 0 ? _c : [], uninterpretedOption: [] }));\n}\nfunction bootEnumDescriptorProto(init) {\n    const proto = Object.create({\n        visibility: 0,\n    });\n    return Object.assign(proto, {\n        $typeName: \"google.protobuf.EnumDescriptorProto\",\n        name: init.name,\n        reservedName: [],\n        reservedRange: [],\n        value: init.value.map((e) => (Object.assign({ $typeName: \"google.protobuf.EnumValueDescriptorProto\" }, e))),\n    });\n}\n","// Copyright 2021-2025 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n/**\n * Hydrate a message descriptor.\n *\n * @private\n */\nexport function messageDesc(file, path, ...paths) {\n    return paths.reduce((acc, cur) => acc.nestedMessages[cur], file.messages[path]);\n}\n","// Copyright 2021-2025 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { boot } from \"../../../../codegenv2/boot.js\";\nimport { messageDesc } from \"../../../../codegenv2/message.js\";\nimport { enumDesc } from \"../../../../codegenv2/enum.js\";\n/**\n * Describes the file google/protobuf/descriptor.proto.\n */\nexport const file_google_protobuf_descriptor = /*@__PURE__*/ boot({ \"name\": \"google/protobuf/descriptor.proto\", \"package\": \"google.protobuf\", \"messageType\": [{ \"name\": \"FileDescriptorSet\", \"field\": [{ \"name\": \"file\", \"number\": 1, \"type\": 11, \"label\": 3, \"typeName\": \".google.protobuf.FileDescriptorProto\" }], \"extensionRange\": [{ \"start\": 536000000, \"end\": 536000001 }] }, { \"name\": \"FileDescriptorProto\", \"field\": [{ \"name\": \"name\", \"number\": 1, \"type\": 9, \"label\": 1 }, { \"name\": \"package\", \"number\": 2, \"type\": 9, \"label\": 1 }, { \"name\": \"dependency\", \"number\": 3, \"type\": 9, \"label\": 3 }, { \"name\": \"public_dependency\", \"number\": 10, \"type\": 5, \"label\": 3 }, { \"name\": \"weak_dependency\", \"number\": 11, \"type\": 5, \"label\": 3 }, { \"name\": \"option_dependency\", \"number\": 15, \"type\": 9, \"label\": 3 }, { \"name\": \"message_type\", \"number\": 4, \"type\": 11, \"label\": 3, \"typeName\": \".google.protobuf.DescriptorProto\" }, { \"name\": \"enum_type\", \"number\": 5, \"type\": 11, \"label\": 3, \"typeName\": \".google.protobuf.EnumDescriptorProto\" }, { \"name\": \"service\", \"number\": 6, \"type\": 11, \"label\": 3, \"typeName\": \".google.protobuf.ServiceDescriptorProto\" }, { \"name\": \"extension\", \"number\": 7, \"type\": 11, \"label\": 3, \"typeName\": \".google.protobuf.FieldDescriptorProto\" }, { \"name\": \"options\", \"number\": 8, \"type\": 11, \"label\": 1, \"typeName\": \".google.protobuf.FileOptions\" }, { \"name\": \"source_code_info\", \"number\": 9, \"type\": 11, \"label\": 1, \"typeName\": \".google.protobuf.SourceCodeInfo\" }, { \"name\": \"syntax\", \"number\": 12, \"type\": 9, \"label\": 1 }, { \"name\": \"edition\", \"number\": 14, \"type\": 14, \"label\": 1, \"typeName\": \".google.protobuf.Edition\" }] }, { \"name\": \"DescriptorProto\", \"field\": [{ \"name\": \"name\", \"number\": 1, \"type\": 9, \"label\": 1 }, { \"name\": \"field\", \"number\": 2, \"type\": 11, \"label\": 3, \"typeName\": \".google.protobuf.FieldDescriptorProto\" }, { \"name\": \"extension\", \"number\": 6, \"type\": 11, \"label\": 3, \"typeName\": \".google.protobuf.FieldDescriptorProto\" }, { \"name\": \"nested_type\", \"number\": 3, \"type\": 11, \"label\": 3, \"typeName\": \".google.protobuf.DescriptorProto\" }, { \"name\": \"enum_type\", \"number\": 4, \"type\": 11, \"label\": 3, \"typeName\": \".google.protobuf.EnumDescriptorProto\" }, { \"name\": \"extension_range\", \"number\": 5, \"type\": 11, \"label\": 3, \"typeName\": \".google.protobuf.DescriptorProto.ExtensionRange\" }, { \"name\": \"oneof_decl\", \"number\": 8, \"type\": 11, \"label\": 3, \"typeName\": \".google.protobuf.OneofDescriptorProto\" }, { \"name\": \"options\", \"number\": 7, \"type\": 11, \"label\": 1, \"typeName\": \".google.protobuf.MessageOptions\" }, { \"name\": \"reserved_range\", \"number\": 9, \"type\": 11, \"label\": 3, \"typeName\": \".google.protobuf.DescriptorProto.ReservedRange\" }, { \"name\": \"reserved_name\", \"number\": 10, \"type\": 9, \"label\": 3 }, { \"name\": \"visibility\", \"number\": 11, \"type\": 14, \"label\": 1, \"typeName\": \".google.protobuf.SymbolVisibility\" }], \"nestedType\": [{ \"name\": \"ExtensionRange\", \"field\": [{ \"name\": \"start\", \"number\": 1, \"type\": 5, \"label\": 1 }, { \"name\": \"end\", \"number\": 2, \"type\": 5, \"label\": 1 }, { \"name\": \"options\", \"number\": 3, \"type\": 11, \"label\": 1, \"typeName\": \".google.protobuf.ExtensionRangeOptions\" }] }, { \"name\": \"ReservedRange\", \"field\": [{ \"name\": \"start\", \"number\": 1, \"type\": 5, \"label\": 1 }, { \"name\": \"end\", \"number\": 2, \"type\": 5, \"label\": 1 }] }] }, { \"name\": \"ExtensionRangeOptions\", \"field\": [{ \"name\": \"uninterpreted_option\", \"number\": 999, \"type\": 11, \"label\": 3, \"typeName\": \".google.protobuf.UninterpretedOption\" }, { \"name\": \"declaration\", \"number\": 2, \"type\": 11, \"label\": 3, \"typeName\": \".google.protobuf.ExtensionRangeOptions.Declaration\", \"options\": { \"retention\": 2 } }, { \"name\": \"features\", \"number\": 50, \"type\": 11, \"label\": 1, \"typeName\": \".google.protobuf.FeatureSet\" }, { \"name\": \"verification\", \"number\": 3, \"type\": 14, \"label\": 1, \"typeName\": \".google.protobuf.ExtensionRangeOptions.VerificationState\", \"defaultValue\": \"UNVERIFIED\", \"options\": { \"retention\": 2 } }], \"nestedType\": [{ \"name\": \"Declaration\", \"field\": [{ \"name\": \"number\", \"number\": 1, \"type\": 5, \"label\": 1 }, { \"name\": \"full_name\", \"number\": 2, \"type\": 9, \"label\": 1 }, { \"name\": \"type\", \"number\": 3, \"type\": 9, \"label\": 1 }, { \"name\": \"reserved\", \"number\": 5, \"type\": 8, \"label\": 1 }, { \"name\": \"repeated\", \"number\": 6, \"type\": 8, \"label\": 1 }] }], \"enumType\": [{ \"name\": \"VerificationState\", \"value\": [{ \"name\": \"DECLARATION\", \"number\": 0 }, { \"name\": \"UNVERIFIED\", \"number\": 1 }] }], \"extensionRange\": [{ \"start\": 1000, \"end\": 536870912 }] }, { \"name\": \"FieldDescriptorProto\", \"field\": [{ \"name\": \"name\", \"number\": 1, \"type\": 9, \"label\": 1 }, { \"name\": \"number\", \"number\": 3, \"type\": 5, \"label\": 1 }, { \"name\": \"label\", \"number\": 4, \"type\": 14, \"label\": 1, \"typeName\": \".google.protobuf.FieldDescriptorProto.Label\" }, { \"name\": \"type\", \"number\": 5, \"type\": 14, \"label\": 1, \"typeName\": \".google.protobuf.FieldDescriptorProto.Type\" }, { \"name\": \"type_name\", \"number\": 6, \"type\": 9, \"label\": 1 }, { \"name\": \"extendee\", \"number\": 2, \"type\": 9, \"label\": 1 }, { \"name\": \"default_value\", \"number\": 7, \"type\": 9, \"label\": 1 }, { \"name\": \"oneof_index\", \"number\": 9, \"type\": 5, \"label\": 1 }, { \"name\": \"json_name\", \"number\": 10, \"type\": 9, \"label\": 1 }, { \"name\": \"options\", \"number\": 8, \"type\": 11, \"label\": 1, \"typeName\": \".google.protobuf.FieldOptions\" }, { \"name\": \"proto3_optional\", \"number\": 17, \"type\": 8, \"label\": 1 }], \"enumType\": [{ \"name\": \"Type\", \"value\": [{ \"name\": \"TYPE_DOUBLE\", \"number\": 1 }, { \"name\": \"TYPE_FLOAT\", \"number\": 2 }, { \"name\": \"TYPE_INT64\", \"number\": 3 }, { \"name\": \"TYPE_UINT64\", \"number\": 4 }, { \"name\": \"TYPE_INT32\", \"number\": 5 }, { \"name\": \"TYPE_FIXED64\", \"number\": 6 }, { \"name\": \"TYPE_FIXED32\", \"number\": 7 }, { \"name\": \"TYPE_BOOL\", \"number\": 8 }, { \"name\": \"TYPE_STRING\", \"number\": 9 }, { \"name\": \"TYPE_GROUP\", \"number\": 10 }, { \"name\": \"TYPE_MESSAGE\", \"number\": 11 }, { \"name\": \"TYPE_BYTES\", \"number\": 12 }, { \"name\": \"TYPE_UINT32\", \"number\": 13 }, { \"name\": \"TYPE_ENUM\", \"number\": 14 }, { \"name\": \"TYPE_SFIXED32\", \"number\": 15 }, { \"name\": \"TYPE_SFIXED64\", \"number\": 16 }, { \"name\": \"TYPE_SINT32\", \"number\": 17 }, { \"name\": \"TYPE_SINT64\", \"number\": 18 }] }, { \"name\": \"Label\", \"value\": [{ \"name\": \"LABEL_OPTIONAL\", \"number\": 1 }, { \"name\": \"LABEL_REPEATED\", \"number\": 3 }, { \"name\": \"LABEL_REQUIRED\", \"number\": 2 }] }] }, { \"name\": \"OneofDescriptorProto\", \"field\": [{ \"name\": \"name\", \"number\": 1, \"type\": 9, \"label\": 1 }, { \"name\": \"options\", \"number\": 2, \"type\": 11, \"label\": 1, \"typeName\": \".google.protobuf.OneofOptions\" }] }, { \"name\": \"EnumDescriptorProto\", \"field\": [{ \"name\": \"name\", \"number\": 1, \"type\": 9, \"label\": 1 }, { \"name\": \"value\", \"number\": 2, \"type\": 11, \"label\": 3, \"typeName\": \".google.protobuf.EnumValueDescriptorProto\" }, { \"name\": \"options\", \"number\": 3, \"type\": 11, \"label\": 1, \"typeName\": \".google.protobuf.EnumOptions\" }, { \"name\": \"reserved_range\", \"number\": 4, \"type\": 11, \"label\": 3, \"typeName\": \".google.protobuf.EnumDescriptorProto.EnumReservedRange\" }, { \"name\": \"reserved_name\", \"number\": 5, \"type\": 9, \"label\": 3 }, { \"name\": \"visibility\", \"number\": 6, \"type\": 14, \"label\": 1, \"typeName\": \".google.protobuf.SymbolVisibility\" }], \"nestedType\": [{ \"name\": \"EnumReservedRange\", \"field\": [{ \"name\": \"start\", \"number\": 1, \"type\": 5, \"label\": 1 }, { \"name\": \"end\", \"number\": 2, \"type\": 5, \"label\": 1 }] }] }, { \"name\": \"EnumValueDescriptorProto\", \"field\": [{ \"name\": \"name\", \"number\": 1, \"type\": 9, \"label\": 1 }, { \"name\": \"number\", \"number\": 2, \"type\": 5, \"label\": 1 }, { \"name\": \"options\", \"number\": 3, \"type\": 11, \"label\": 1, \"typeName\": \".google.protobuf.EnumValueOptions\" }] }, { \"name\": \"ServiceDescriptorProto\", \"field\": [{ \"name\": \"name\", \"number\": 1, \"type\": 9, \"label\": 1 }, { \"name\": \"method\", \"number\": 2, \"type\": 11, \"label\": 3, \"typeName\": \".google.protobuf.MethodDescriptorProto\" }, { \"name\": \"options\", \"number\": 3, \"type\": 11, \"label\": 1, \"typeName\": \".google.protobuf.ServiceOptions\" }] }, { \"name\": \"MethodDescriptorProto\", \"field\": [{ \"name\": \"name\", \"number\": 1, \"type\": 9, \"label\": 1 }, { \"name\": \"input_type\", \"number\": 2, \"type\": 9, \"label\": 1 }, { \"name\": \"output_type\", \"number\": 3, \"type\": 9, \"label\": 1 }, { \"name\": \"options\", \"number\": 4, \"type\": 11, \"label\": 1, \"typeName\": \".google.protobuf.MethodOptions\" }, { \"name\": \"client_streaming\", \"number\": 5, \"type\": 8, \"label\": 1, \"defaultValue\": \"false\" }, { \"name\": \"server_streaming\", \"number\": 6, \"type\": 8, \"label\": 1, \"defaultValue\": \"false\" }] }, { \"name\": \"FileOptions\", \"field\": [{ \"name\": \"java_package\", \"number\": 1, \"type\": 9, \"label\": 1 }, { \"name\": \"java_outer_classname\", \"number\": 8, \"type\": 9, \"label\": 1 }, { \"name\": \"java_multiple_files\", \"number\": 10, \"type\": 8, \"label\": 1, \"defaultValue\": \"false\" }, { \"name\": \"java_generate_equals_and_hash\", \"number\": 20, \"type\": 8, \"label\": 1, \"options\": { \"deprecated\": true } }, { \"name\": \"java_string_check_utf8\", \"number\": 27, \"type\": 8, \"label\": 1, \"defaultValue\": \"false\" }, { \"name\": \"optimize_for\", \"number\": 9, \"type\": 14, \"label\": 1, \"typeName\": \".google.protobuf.FileOptions.OptimizeMode\", \"defaultValue\": \"SPEED\" }, { \"name\": \"go_package\", \"number\": 11, \"type\": 9, \"label\": 1 }, { \"name\": \"cc_generic_services\", \"number\": 16, \"type\": 8, \"label\": 1, \"defaultValue\": \"false\" }, { \"name\": \"java_generic_services\", \"number\": 17, \"type\": 8, \"label\": 1, \"defaultValue\": \"false\" }, { \"name\": \"py_generic_services\", \"number\": 18, \"type\": 8, \"label\": 1, \"defaultValue\": \"false\" }, { \"name\": \"deprecated\", \"number\": 23, \"type\": 8, \"label\": 1, \"defaultValue\": \"false\" }, { \"name\": \"cc_enable_arenas\", \"number\": 31, \"type\": 8, \"label\": 1, \"defaultValue\": \"true\" }, { \"name\": \"objc_class_prefix\", \"number\": 36, \"type\": 9, \"label\": 1 }, { \"name\": \"csharp_namespace\", \"number\": 37, \"type\": 9, \"label\": 1 }, { \"name\": \"swift_prefix\", \"number\": 39, \"type\": 9, \"label\": 1 }, { \"name\": \"php_class_prefix\", \"number\": 40, \"type\": 9, \"label\": 1 }, { \"name\": \"php_namespace\", \"number\": 41, \"type\": 9, \"label\": 1 }, { \"name\": \"php_metadata_namespace\", \"number\": 44, \"type\": 9, \"label\": 1 }, { \"name\": \"ruby_package\", \"number\": 45, \"type\": 9, \"label\": 1 }, { \"name\": \"features\", \"number\": 50, \"type\": 11, \"label\": 1, \"typeName\": \".google.protobuf.FeatureSet\" }, { \"name\": \"uninterpreted_option\", \"number\": 999, \"type\": 11, \"label\": 3, \"typeName\": \".google.protobuf.UninterpretedOption\" }], \"enumType\": [{ \"name\": \"OptimizeMode\", \"value\": [{ \"name\": \"SPEED\", \"number\": 1 }, { \"name\": \"CODE_SIZE\", \"number\": 2 }, { \"name\": \"LITE_RUNTIME\", \"number\": 3 }] }], \"extensionRange\": [{ \"start\": 1000, \"end\": 536870912 }] }, { \"name\": \"MessageOptions\", \"field\": [{ \"name\": \"message_set_wire_format\", \"number\": 1, \"type\": 8, \"label\": 1, \"defaultValue\": \"false\" }, { \"name\": \"no_standard_descriptor_accessor\", \"number\": 2, \"type\": 8, \"label\": 1, \"defaultValue\": \"false\" }, { \"name\": \"deprecated\", \"number\": 3, \"type\": 8, \"label\": 1, \"defaultValue\": \"false\" }, { \"name\": \"map_entry\", \"number\": 7, \"type\": 8, \"label\": 1 }, { \"name\": \"deprecated_legacy_json_field_conflicts\", \"number\": 11, \"type\": 8, \"label\": 1, \"options\": { \"deprecated\": true } }, { \"name\": \"features\", \"number\": 12, \"type\": 11, \"label\": 1, \"typeName\": \".google.protobuf.FeatureSet\" }, { \"name\": \"uninterpreted_option\", \"number\": 999, \"type\": 11, \"label\": 3, \"typeName\": \".google.protobuf.UninterpretedOption\" }], \"extensionRange\": [{ \"start\": 1000, \"end\": 536870912 }] }, { \"name\": \"FieldOptions\", \"field\": [{ \"name\": \"ctype\", \"number\": 1, \"type\": 14, \"label\": 1, \"typeName\": \".google.protobuf.FieldOptions.CType\", \"defaultValue\": \"STRING\" }, { \"name\": \"packed\", \"number\": 2, \"type\": 8, \"label\": 1 }, { \"name\": \"jstype\", \"number\": 6, \"type\": 14, \"label\": 1, \"typeName\": \".google.protobuf.FieldOptions.JSType\", \"defaultValue\": \"JS_NORMAL\" }, { \"name\": \"lazy\", \"number\": 5, \"type\": 8, \"label\": 1, \"defaultValue\": \"false\" }, { \"name\": \"unverified_lazy\", \"number\": 15, \"type\": 8, \"label\": 1, \"defaultValue\": \"false\" }, { \"name\": \"deprecated\", \"number\": 3, \"type\": 8, \"label\": 1, \"defaultValue\": \"false\" }, { \"name\": \"weak\", \"number\": 10, \"type\": 8, \"label\": 1, \"defaultValue\": \"false\", \"options\": { \"deprecated\": true } }, { \"name\": \"debug_redact\", \"number\": 16, \"type\": 8, \"label\": 1, \"defaultValue\": \"false\" }, { \"name\": \"retention\", \"number\": 17, \"type\": 14, \"label\": 1, \"typeName\": \".google.protobuf.FieldOptions.OptionRetention\" }, { \"name\": \"targets\", \"number\": 19, \"type\": 14, \"label\": 3, \"typeName\": \".google.protobuf.FieldOptions.OptionTargetType\" }, { \"name\": \"edition_defaults\", \"number\": 20, \"type\": 11, \"label\": 3, \"typeName\": \".google.protobuf.FieldOptions.EditionDefault\" }, { \"name\": \"features\", \"number\": 21, \"type\": 11, \"label\": 1, \"typeName\": \".google.protobuf.FeatureSet\" }, { \"name\": \"feature_support\", \"number\": 22, \"type\": 11, \"label\": 1, \"typeName\": \".google.protobuf.FieldOptions.FeatureSupport\" }, { \"name\": \"uninterpreted_option\", \"number\": 999, \"type\": 11, \"label\": 3, \"typeName\": \".google.protobuf.UninterpretedOption\" }], \"nestedType\": [{ \"name\": \"EditionDefault\", \"field\": [{ \"name\": \"edition\", \"number\": 3, \"type\": 14, \"label\": 1, \"typeName\": \".google.protobuf.Edition\" }, { \"name\": \"value\", \"number\": 2, \"type\": 9, \"label\": 1 }] }, { \"name\": \"FeatureSupport\", \"field\": [{ \"name\": \"edition_introduced\", \"number\": 1, \"type\": 14, \"label\": 1, \"typeName\": \".google.protobuf.Edition\" }, { \"name\": \"edition_deprecated\", \"number\": 2, \"type\": 14, \"label\": 1, \"typeName\": \".google.protobuf.Edition\" }, { \"name\": \"deprecation_warning\", \"number\": 3, \"type\": 9, \"label\": 1 }, { \"name\": \"edition_removed\", \"number\": 4, \"type\": 14, \"label\": 1, \"typeName\": \".google.protobuf.Edition\" }] }], \"enumType\": [{ \"name\": \"CType\", \"value\": [{ \"name\": \"STRING\", \"number\": 0 }, { \"name\": \"CORD\", \"number\": 1 }, { \"name\": \"STRING_PIECE\", \"number\": 2 }] }, { \"name\": \"JSType\", \"value\": [{ \"name\": \"JS_NORMAL\", \"number\": 0 }, { \"name\": \"JS_STRING\", \"number\": 1 }, { \"name\": \"JS_NUMBER\", \"number\": 2 }] }, { \"name\": \"OptionRetention\", \"value\": [{ \"name\": \"RETENTION_UNKNOWN\", \"number\": 0 }, { \"name\": \"RETENTION_RUNTIME\", \"number\": 1 }, { \"name\": \"RETENTION_SOURCE\", \"number\": 2 }] }, { \"name\": \"OptionTargetType\", \"value\": [{ \"name\": \"TARGET_TYPE_UNKNOWN\", \"number\": 0 }, { \"name\": \"TARGET_TYPE_FILE\", \"number\": 1 }, { \"name\": \"TARGET_TYPE_EXTENSION_RANGE\", \"number\": 2 }, { \"name\": \"TARGET_TYPE_MESSAGE\", \"number\": 3 }, { \"name\": \"TARGET_TYPE_FIELD\", \"number\": 4 }, { \"name\": \"TARGET_TYPE_ONEOF\", \"number\": 5 }, { \"name\": \"TARGET_TYPE_ENUM\", \"number\": 6 }, { \"name\": \"TARGET_TYPE_ENUM_ENTRY\", \"number\": 7 }, { \"name\": \"TARGET_TYPE_SERVICE\", \"number\": 8 }, { \"name\": \"TARGET_TYPE_METHOD\", \"number\": 9 }] }], \"extensionRange\": [{ \"start\": 1000, \"end\": 536870912 }] }, { \"name\": \"OneofOptions\", \"field\": [{ \"name\": \"features\", \"number\": 1, \"type\": 11, \"label\": 1, \"typeName\": \".google.protobuf.FeatureSet\" }, { \"name\": \"uninterpreted_option\", \"number\": 999, \"type\": 11, \"label\": 3, \"typeName\": \".google.protobuf.UninterpretedOption\" }], \"extensionRange\": [{ \"start\": 1000, \"end\": 536870912 }] }, { \"name\": \"EnumOptions\", \"field\": [{ \"name\": \"allow_alias\", \"number\": 2, \"type\": 8, \"label\": 1 }, { \"name\": \"deprecated\", \"number\": 3, \"type\": 8, \"label\": 1, \"defaultValue\": \"false\" }, { \"name\": \"deprecated_legacy_json_field_conflicts\", \"number\": 6, \"type\": 8, \"label\": 1, \"options\": { \"deprecated\": true } }, { \"name\": \"features\", \"number\": 7, \"type\": 11, \"label\": 1, \"typeName\": \".google.protobuf.FeatureSet\" }, { \"name\": \"uninterpreted_option\", \"number\": 999, \"type\": 11, \"label\": 3, \"typeName\": \".google.protobuf.UninterpretedOption\" }], \"extensionRange\": [{ \"start\": 1000, \"end\": 536870912 }] }, { \"name\": \"EnumValueOptions\", \"field\": [{ \"name\": \"deprecated\", \"number\": 1, \"type\": 8, \"label\": 1, \"defaultValue\": \"false\" }, { \"name\": \"features\", \"number\": 2, \"type\": 11, \"label\": 1, \"typeName\": \".google.protobuf.FeatureSet\" }, { \"name\": \"debug_redact\", \"number\": 3, \"type\": 8, \"label\": 1, \"defaultValue\": \"false\" }, { \"name\": \"feature_support\", \"number\": 4, \"type\": 11, \"label\": 1, \"typeName\": \".google.protobuf.FieldOptions.FeatureSupport\" }, { \"name\": \"uninterpreted_option\", \"number\": 999, \"type\": 11, \"label\": 3, \"typeName\": \".google.protobuf.UninterpretedOption\" }], \"extensionRange\": [{ \"start\": 1000, \"end\": 536870912 }] }, { \"name\": \"ServiceOptions\", \"field\": [{ \"name\": \"features\", \"number\": 34, \"type\": 11, \"label\": 1, \"typeName\": \".google.protobuf.FeatureSet\" }, { \"name\": \"deprecated\", \"number\": 33, \"type\": 8, \"label\": 1, \"defaultValue\": \"false\" }, { \"name\": \"uninterpreted_option\", \"number\": 999, \"type\": 11, \"label\": 3, \"typeName\": \".google.protobuf.UninterpretedOption\" }], \"extensionRange\": [{ \"start\": 1000, \"end\": 536870912 }] }, { \"name\": \"MethodOptions\", \"field\": [{ \"name\": \"deprecated\", \"number\": 33, \"type\": 8, \"label\": 1, \"defaultValue\": \"false\" }, { \"name\": \"idempotency_level\", \"number\": 34, \"type\": 14, \"label\": 1, \"typeName\": \".google.protobuf.MethodOptions.IdempotencyLevel\", \"defaultValue\": \"IDEMPOTENCY_UNKNOWN\" }, { \"name\": \"features\", \"number\": 35, \"type\": 11, \"label\": 1, \"typeName\": \".google.protobuf.FeatureSet\" }, { \"name\": \"uninterpreted_option\", \"number\": 999, \"type\": 11, \"label\": 3, \"typeName\": \".google.protobuf.UninterpretedOption\" }], \"enumType\": [{ \"name\": \"IdempotencyLevel\", \"value\": [{ \"name\": \"IDEMPOTENCY_UNKNOWN\", \"number\": 0 }, { \"name\": \"NO_SIDE_EFFECTS\", \"number\": 1 }, { \"name\": \"IDEMPOTENT\", \"number\": 2 }] }], \"extensionRange\": [{ \"start\": 1000, \"end\": 536870912 }] }, { \"name\": \"UninterpretedOption\", \"field\": [{ \"name\": \"name\", \"number\": 2, \"type\": 11, \"label\": 3, \"typeName\": \".google.protobuf.UninterpretedOption.NamePart\" }, { \"name\": \"identifier_value\", \"number\": 3, \"type\": 9, \"label\": 1 }, { \"name\": \"positive_int_value\", \"number\": 4, \"type\": 4, \"label\": 1 }, { \"name\": \"negative_int_value\", \"number\": 5, \"type\": 3, \"label\": 1 }, { \"name\": \"double_value\", \"number\": 6, \"type\": 1, \"label\": 1 }, { \"name\": \"string_value\", \"number\": 7, \"type\": 12, \"label\": 1 }, { \"name\": \"aggregate_value\", \"number\": 8, \"type\": 9, \"label\": 1 }], \"nestedType\": [{ \"name\": \"NamePart\", \"field\": [{ \"name\": \"name_part\", \"number\": 1, \"type\": 9, \"label\": 2 }, { \"name\": \"is_extension\", \"number\": 2, \"type\": 8, \"label\": 2 }] }] }, { \"name\": \"FeatureSet\", \"field\": [{ \"name\": \"field_presence\", \"number\": 1, \"type\": 14, \"label\": 1, \"typeName\": \".google.protobuf.FeatureSet.FieldPresence\", \"options\": { \"retention\": 1, \"targets\": [4, 1], \"editionDefaults\": [{ \"value\": \"EXPLICIT\", \"edition\": 900 }, { \"value\": \"IMPLICIT\", \"edition\": 999 }, { \"value\": \"EXPLICIT\", \"edition\": 1000 }] } }, { \"name\": \"enum_type\", \"number\": 2, \"type\": 14, \"label\": 1, \"typeName\": \".google.protobuf.FeatureSet.EnumType\", \"options\": { \"retention\": 1, \"targets\": [6, 1], \"editionDefaults\": [{ \"value\": \"CLOSED\", \"edition\": 900 }, { \"value\": \"OPEN\", \"edition\": 999 }] } }, { \"name\": \"repeated_field_encoding\", \"number\": 3, \"type\": 14, \"label\": 1, \"typeName\": \".google.protobuf.FeatureSet.RepeatedFieldEncoding\", \"options\": { \"retention\": 1, \"targets\": [4, 1], \"editionDefaults\": [{ \"value\": \"EXPANDED\", \"edition\": 900 }, { \"value\": \"PACKED\", \"edition\": 999 }] } }, { \"name\": \"utf8_validation\", \"number\": 4, \"type\": 14, \"label\": 1, \"typeName\": \".google.protobuf.FeatureSet.Utf8Validation\", \"options\": { \"retention\": 1, \"targets\": [4, 1], \"editionDefaults\": [{ \"value\": \"NONE\", \"edition\": 900 }, { \"value\": \"VERIFY\", \"edition\": 999 }] } }, { \"name\": \"message_encoding\", \"number\": 5, \"type\": 14, \"label\": 1, \"typeName\": \".google.protobuf.FeatureSet.MessageEncoding\", \"options\": { \"retention\": 1, \"targets\": [4, 1], \"editionDefaults\": [{ \"value\": \"LENGTH_PREFIXED\", \"edition\": 900 }] } }, { \"name\": \"json_format\", \"number\": 6, \"type\": 14, \"label\": 1, \"typeName\": \".google.protobuf.FeatureSet.JsonFormat\", \"options\": { \"retention\": 1, \"targets\": [3, 6, 1], \"editionDefaults\": [{ \"value\": \"LEGACY_BEST_EFFORT\", \"edition\": 900 }, { \"value\": \"ALLOW\", \"edition\": 999 }] } }, { \"name\": \"enforce_naming_style\", \"number\": 7, \"type\": 14, \"label\": 1, \"typeName\": \".google.protobuf.FeatureSet.EnforceNamingStyle\", \"options\": { \"retention\": 2, \"targets\": [1, 2, 3, 4, 5, 6, 7, 8, 9], \"editionDefaults\": [{ \"value\": \"STYLE_LEGACY\", \"edition\": 900 }, { \"value\": \"STYLE2024\", \"edition\": 1001 }] } }, { \"name\": \"default_symbol_visibility\", \"number\": 8, \"type\": 14, \"label\": 1, \"typeName\": \".google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility\", \"options\": { \"retention\": 2, \"targets\": [1], \"editionDefaults\": [{ \"value\": \"EXPORT_ALL\", \"edition\": 900 }, { \"value\": \"EXPORT_TOP_LEVEL\", \"edition\": 1001 }] } }], \"nestedType\": [{ \"name\": \"VisibilityFeature\", \"enumType\": [{ \"name\": \"DefaultSymbolVisibility\", \"value\": [{ \"name\": \"DEFAULT_SYMBOL_VISIBILITY_UNKNOWN\", \"number\": 0 }, { \"name\": \"EXPORT_ALL\", \"number\": 1 }, { \"name\": \"EXPORT_TOP_LEVEL\", \"number\": 2 }, { \"name\": \"LOCAL_ALL\", \"number\": 3 }, { \"name\": \"STRICT\", \"number\": 4 }] }] }], \"enumType\": [{ \"name\": \"FieldPresence\", \"value\": [{ \"name\": \"FIELD_PRESENCE_UNKNOWN\", \"number\": 0 }, { \"name\": \"EXPLICIT\", \"number\": 1 }, { \"name\": \"IMPLICIT\", \"number\": 2 }, { \"name\": \"LEGACY_REQUIRED\", \"number\": 3 }] }, { \"name\": \"EnumType\", \"value\": [{ \"name\": \"ENUM_TYPE_UNKNOWN\", \"number\": 0 }, { \"name\": \"OPEN\", \"number\": 1 }, { \"name\": \"CLOSED\", \"number\": 2 }] }, { \"name\": \"RepeatedFieldEncoding\", \"value\": [{ \"name\": \"REPEATED_FIELD_ENCODING_UNKNOWN\", \"number\": 0 }, { \"name\": \"PACKED\", \"number\": 1 }, { \"name\": \"EXPANDED\", \"number\": 2 }] }, { \"name\": \"Utf8Validation\", \"value\": [{ \"name\": \"UTF8_VALIDATION_UNKNOWN\", \"number\": 0 }, { \"name\": \"VERIFY\", \"number\": 2 }, { \"name\": \"NONE\", \"number\": 3 }] }, { \"name\": \"MessageEncoding\", \"value\": [{ \"name\": \"MESSAGE_ENCODING_UNKNOWN\", \"number\": 0 }, { \"name\": \"LENGTH_PREFIXED\", \"number\": 1 }, { \"name\": \"DELIMITED\", \"number\": 2 }] }, { \"name\": \"JsonFormat\", \"value\": [{ \"name\": \"JSON_FORMAT_UNKNOWN\", \"number\": 0 }, { \"name\": \"ALLOW\", \"number\": 1 }, { \"name\": \"LEGACY_BEST_EFFORT\", \"number\": 2 }] }, { \"name\": \"EnforceNamingStyle\", \"value\": [{ \"name\": \"ENFORCE_NAMING_STYLE_UNKNOWN\", \"number\": 0 }, { \"name\": \"STYLE2024\", \"number\": 1 }, { \"name\": \"STYLE_LEGACY\", \"number\": 2 }] }], \"extensionRange\": [{ \"start\": 1000, \"end\": 9995 }, { \"start\": 9995, \"end\": 10000 }, { \"start\": 10000, \"end\": 10001 }] }, { \"name\": \"FeatureSetDefaults\", \"field\": [{ \"name\": \"defaults\", \"number\": 1, \"type\": 11, \"label\": 3, \"typeName\": \".google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault\" }, { \"name\": \"minimum_edition\", \"number\": 4, \"type\": 14, \"label\": 1, \"typeName\": \".google.protobuf.Edition\" }, { \"name\": \"maximum_edition\", \"number\": 5, \"type\": 14, \"label\": 1, \"typeName\": \".google.protobuf.Edition\" }], \"nestedType\": [{ \"name\": \"FeatureSetEditionDefault\", \"field\": [{ \"name\": \"edition\", \"number\": 3, \"type\": 14, \"label\": 1, \"typeName\": \".google.protobuf.Edition\" }, { \"name\": \"overridable_features\", \"number\": 4, \"type\": 11, \"label\": 1, \"typeName\": \".google.protobuf.FeatureSet\" }, { \"name\": \"fixed_features\", \"number\": 5, \"type\": 11, \"label\": 1, \"typeName\": \".google.protobuf.FeatureSet\" }] }] }, { \"name\": \"SourceCodeInfo\", \"field\": [{ \"name\": \"location\", \"number\": 1, \"type\": 11, \"label\": 3, \"typeName\": \".google.protobuf.SourceCodeInfo.Location\" }], \"nestedType\": [{ \"name\": \"Location\", \"field\": [{ \"name\": \"path\", \"number\": 1, \"type\": 5, \"label\": 3, \"options\": { \"packed\": true } }, { \"name\": \"span\", \"number\": 2, \"type\": 5, \"label\": 3, \"options\": { \"packed\": true } }, { \"name\": \"leading_comments\", \"number\": 3, \"type\": 9, \"label\": 1 }, { \"name\": \"trailing_comments\", \"number\": 4, \"type\": 9, \"label\": 1 }, { \"name\": \"leading_detached_comments\", \"number\": 6, \"type\": 9, \"label\": 3 }] }], \"extensionRange\": [{ \"start\": 536000000, \"end\": 536000001 }] }, { \"name\": \"GeneratedCodeInfo\", \"field\": [{ \"name\": \"annotation\", \"number\": 1, \"type\": 11, \"label\": 3, \"typeName\": \".google.protobuf.GeneratedCodeInfo.Annotation\" }], \"nestedType\": [{ \"name\": \"Annotation\", \"field\": [{ \"name\": \"path\", \"number\": 1, \"type\": 5, \"label\": 3, \"options\": { \"packed\": true } }, { \"name\": \"source_file\", \"number\": 2, \"type\": 9, \"label\": 1 }, { \"name\": \"begin\", \"number\": 3, \"type\": 5, \"label\": 1 }, { \"name\": \"end\", \"number\": 4, \"type\": 5, \"label\": 1 }, { \"name\": \"semantic\", \"number\": 5, \"type\": 14, \"label\": 1, \"typeName\": \".google.protobuf.GeneratedCodeInfo.Annotation.Semantic\" }], \"enumType\": [{ \"name\": \"Semantic\", \"value\": [{ \"name\": \"NONE\", \"number\": 0 }, { \"name\": \"SET\", \"number\": 1 }, { \"name\": \"ALIAS\", \"number\": 2 }] }] }] }], \"enumType\": [{ \"name\": \"Edition\", \"value\": [{ \"name\": \"EDITION_UNKNOWN\", \"number\": 0 }, { \"name\": \"EDITION_LEGACY\", \"number\": 900 }, { \"name\": \"EDITION_PROTO2\", \"number\": 998 }, { \"name\": \"EDITION_PROTO3\", \"number\": 999 }, { \"name\": \"EDITION_2023\", \"number\": 1000 }, { \"name\": \"EDITION_2024\", \"number\": 1001 }, { \"name\": \"EDITION_1_TEST_ONLY\", \"number\": 1 }, { \"name\": \"EDITION_2_TEST_ONLY\", \"number\": 2 }, { \"name\": \"EDITION_99997_TEST_ONLY\", \"number\": 99997 }, { \"name\": \"EDITION_99998_TEST_ONLY\", \"number\": 99998 }, { \"name\": \"EDITION_99999_TEST_ONLY\", \"number\": 99999 }, { \"name\": \"EDITION_MAX\", \"number\": 2147483647 }] }, { \"name\": \"SymbolVisibility\", \"value\": [{ \"name\": \"VISIBILITY_UNSET\", \"number\": 0 }, { \"name\": \"VISIBILITY_LOCAL\", \"number\": 1 }, { \"name\": \"VISIBILITY_EXPORT\", \"number\": 2 }] }] });\n/**\n * Describes the message google.protobuf.FileDescriptorSet.\n * Use `create(FileDescriptorSetSchema)` to create a new message.\n */\nexport const FileDescriptorSetSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_descriptor, 0);\n/**\n * Describes the message google.protobuf.FileDescriptorProto.\n * Use `create(FileDescriptorProtoSchema)` to create a new message.\n */\nexport const FileDescriptorProtoSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_descriptor, 1);\n/**\n * Describes the message google.protobuf.DescriptorProto.\n * Use `create(DescriptorProtoSchema)` to create a new message.\n */\nexport const DescriptorProtoSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_descriptor, 2);\n/**\n * Describes the message google.protobuf.DescriptorProto.ExtensionRange.\n * Use `create(DescriptorProto_ExtensionRangeSchema)` to create a new message.\n */\nexport const DescriptorProto_ExtensionRangeSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_descriptor, 2, 0);\n/**\n * Describes the message google.protobuf.DescriptorProto.ReservedRange.\n * Use `create(DescriptorProto_ReservedRangeSchema)` to create a new message.\n */\nexport const DescriptorProto_ReservedRangeSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_descriptor, 2, 1);\n/**\n * Describes the message google.protobuf.ExtensionRangeOptions.\n * Use `create(ExtensionRangeOptionsSchema)` to create a new message.\n */\nexport const ExtensionRangeOptionsSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_descriptor, 3);\n/**\n * Describes the message google.protobuf.ExtensionRangeOptions.Declaration.\n * Use `create(ExtensionRangeOptions_DeclarationSchema)` to create a new message.\n */\nexport const ExtensionRangeOptions_DeclarationSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_descriptor, 3, 0);\n/**\n * The verification state of the extension range.\n *\n * @generated from enum google.protobuf.ExtensionRangeOptions.VerificationState\n */\nexport var ExtensionRangeOptions_VerificationState;\n(function (ExtensionRangeOptions_VerificationState) {\n    /**\n     * All the extensions of the range must be declared.\n     *\n     * @generated from enum value: DECLARATION = 0;\n     */\n    ExtensionRangeOptions_VerificationState[ExtensionRangeOptions_VerificationState[\"DECLARATION\"] = 0] = \"DECLARATION\";\n    /**\n     * @generated from enum value: UNVERIFIED = 1;\n     */\n    ExtensionRangeOptions_VerificationState[ExtensionRangeOptions_VerificationState[\"UNVERIFIED\"] = 1] = \"UNVERIFIED\";\n})(ExtensionRangeOptions_VerificationState || (ExtensionRangeOptions_VerificationState = {}));\n/**\n * Describes the enum google.protobuf.ExtensionRangeOptions.VerificationState.\n */\nexport const ExtensionRangeOptions_VerificationStateSchema = /*@__PURE__*/ enumDesc(file_google_protobuf_descriptor, 3, 0);\n/**\n * Describes the message google.protobuf.FieldDescriptorProto.\n * Use `create(FieldDescriptorProtoSchema)` to create a new message.\n */\nexport const FieldDescriptorProtoSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_descriptor, 4);\n/**\n * @generated from enum google.protobuf.FieldDescriptorProto.Type\n */\nexport var FieldDescriptorProto_Type;\n(function (FieldDescriptorProto_Type) {\n    /**\n     * 0 is reserved for errors.\n     * Order is weird for historical reasons.\n     *\n     * @generated from enum value: TYPE_DOUBLE = 1;\n     */\n    FieldDescriptorProto_Type[FieldDescriptorProto_Type[\"DOUBLE\"] = 1] = \"DOUBLE\";\n    /**\n     * @generated from enum value: TYPE_FLOAT = 2;\n     */\n    FieldDescriptorProto_Type[FieldDescriptorProto_Type[\"FLOAT\"] = 2] = \"FLOAT\";\n    /**\n     * Not ZigZag encoded.  Negative numbers take 10 bytes.  Use TYPE_SINT64 if\n     * negative values are likely.\n     *\n     * @generated from enum value: TYPE_INT64 = 3;\n     */\n    FieldDescriptorProto_Type[FieldDescriptorProto_Type[\"INT64\"] = 3] = \"INT64\";\n    /**\n     * @generated from enum value: TYPE_UINT64 = 4;\n     */\n    FieldDescriptorProto_Type[FieldDescriptorProto_Type[\"UINT64\"] = 4] = \"UINT64\";\n    /**\n     * Not ZigZag encoded.  Negative numbers take 10 bytes.  Use TYPE_SINT32 if\n     * negative values are likely.\n     *\n     * @generated from enum value: TYPE_INT32 = 5;\n     */\n    FieldDescriptorProto_Type[FieldDescriptorProto_Type[\"INT32\"] = 5] = \"INT32\";\n    /**\n     * @generated from enum value: TYPE_FIXED64 = 6;\n     */\n    FieldDescriptorProto_Type[FieldDescriptorProto_Type[\"FIXED64\"] = 6] = \"FIXED64\";\n    /**\n     * @generated from enum value: TYPE_FIXED32 = 7;\n     */\n    FieldDescriptorProto_Type[FieldDescriptorProto_Type[\"FIXED32\"] = 7] = \"FIXED32\";\n    /**\n     * @generated from enum value: TYPE_BOOL = 8;\n     */\n    FieldDescriptorProto_Type[FieldDescriptorProto_Type[\"BOOL\"] = 8] = \"BOOL\";\n    /**\n     * @generated from enum value: TYPE_STRING = 9;\n     */\n    FieldDescriptorProto_Type[FieldDescriptorProto_Type[\"STRING\"] = 9] = \"STRING\";\n    /**\n     * Tag-delimited aggregate.\n     * Group type is deprecated and not supported after google.protobuf. However, Proto3\n     * implementations should still be able to parse the group wire format and\n     * treat group fields as unknown fields.  In Editions, the group wire format\n     * can be enabled via the `message_encoding` feature.\n     *\n     * @generated from enum value: TYPE_GROUP = 10;\n     */\n    FieldDescriptorProto_Type[FieldDescriptorProto_Type[\"GROUP\"] = 10] = \"GROUP\";\n    /**\n     * Length-delimited aggregate.\n     *\n     * @generated from enum value: TYPE_MESSAGE = 11;\n     */\n    FieldDescriptorProto_Type[FieldDescriptorProto_Type[\"MESSAGE\"] = 11] = \"MESSAGE\";\n    /**\n     * New in version 2.\n     *\n     * @generated from enum value: TYPE_BYTES = 12;\n     */\n    FieldDescriptorProto_Type[FieldDescriptorProto_Type[\"BYTES\"] = 12] = \"BYTES\";\n    /**\n     * @generated from enum value: TYPE_UINT32 = 13;\n     */\n    FieldDescriptorProto_Type[FieldDescriptorProto_Type[\"UINT32\"] = 13] = \"UINT32\";\n    /**\n     * @generated from enum value: TYPE_ENUM = 14;\n     */\n    FieldDescriptorProto_Type[FieldDescriptorProto_Type[\"ENUM\"] = 14] = \"ENUM\";\n    /**\n     * @generated from enum value: TYPE_SFIXED32 = 15;\n     */\n    FieldDescriptorProto_Type[FieldDescriptorProto_Type[\"SFIXED32\"] = 15] = \"SFIXED32\";\n    /**\n     * @generated from enum value: TYPE_SFIXED64 = 16;\n     */\n    FieldDescriptorProto_Type[FieldDescriptorProto_Type[\"SFIXED64\"] = 16] = \"SFIXED64\";\n    /**\n     * Uses ZigZag encoding.\n     *\n     * @generated from enum value: TYPE_SINT32 = 17;\n     */\n    FieldDescriptorProto_Type[FieldDescriptorProto_Type[\"SINT32\"] = 17] = \"SINT32\";\n    /**\n     * Uses ZigZag encoding.\n     *\n     * @generated from enum value: TYPE_SINT64 = 18;\n     */\n    FieldDescriptorProto_Type[FieldDescriptorProto_Type[\"SINT64\"] = 18] = \"SINT64\";\n})(FieldDescriptorProto_Type || (FieldDescriptorProto_Type = {}));\n/**\n * Describes the enum google.protobuf.FieldDescriptorProto.Type.\n */\nexport const FieldDescriptorProto_TypeSchema = /*@__PURE__*/ enumDesc(file_google_protobuf_descriptor, 4, 0);\n/**\n * @generated from enum google.protobuf.FieldDescriptorProto.Label\n */\nexport var FieldDescriptorProto_Label;\n(function (FieldDescriptorProto_Label) {\n    /**\n     * 0 is reserved for errors\n     *\n     * @generated from enum value: LABEL_OPTIONAL = 1;\n     */\n    FieldDescriptorProto_Label[FieldDescriptorProto_Label[\"OPTIONAL\"] = 1] = \"OPTIONAL\";\n    /**\n     * @generated from enum value: LABEL_REPEATED = 3;\n     */\n    FieldDescriptorProto_Label[FieldDescriptorProto_Label[\"REPEATED\"] = 3] = \"REPEATED\";\n    /**\n     * The required label is only allowed in google.protobuf.  In proto3 and Editions\n     * it's explicitly prohibited.  In Editions, the `field_presence` feature\n     * can be used to get this behavior.\n     *\n     * @generated from enum value: LABEL_REQUIRED = 2;\n     */\n    FieldDescriptorProto_Label[FieldDescriptorProto_Label[\"REQUIRED\"] = 2] = \"REQUIRED\";\n})(FieldDescriptorProto_Label || (FieldDescriptorProto_Label = {}));\n/**\n * Describes the enum google.protobuf.FieldDescriptorProto.Label.\n */\nexport const FieldDescriptorProto_LabelSchema = /*@__PURE__*/ enumDesc(file_google_protobuf_descriptor, 4, 1);\n/**\n * Describes the message google.protobuf.OneofDescriptorProto.\n * Use `create(OneofDescriptorProtoSchema)` to create a new message.\n */\nexport const OneofDescriptorProtoSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_descriptor, 5);\n/**\n * Describes the message google.protobuf.EnumDescriptorProto.\n * Use `create(EnumDescriptorProtoSchema)` to create a new message.\n */\nexport const EnumDescriptorProtoSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_descriptor, 6);\n/**\n * Describes the message google.protobuf.EnumDescriptorProto.EnumReservedRange.\n * Use `create(EnumDescriptorProto_EnumReservedRangeSchema)` to create a new message.\n */\nexport const EnumDescriptorProto_EnumReservedRangeSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_descriptor, 6, 0);\n/**\n * Describes the message google.protobuf.EnumValueDescriptorProto.\n * Use `create(EnumValueDescriptorProtoSchema)` to create a new message.\n */\nexport const EnumValueDescriptorProtoSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_descriptor, 7);\n/**\n * Describes the message google.protobuf.ServiceDescriptorProto.\n * Use `create(ServiceDescriptorProtoSchema)` to create a new message.\n */\nexport const ServiceDescriptorProtoSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_descriptor, 8);\n/**\n * Describes the message google.protobuf.MethodDescriptorProto.\n * Use `create(MethodDescriptorProtoSchema)` to create a new message.\n */\nexport const MethodDescriptorProtoSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_descriptor, 9);\n/**\n * Describes the message google.protobuf.FileOptions.\n * Use `create(FileOptionsSchema)` to create a new message.\n */\nexport const FileOptionsSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_descriptor, 10);\n/**\n * Generated classes can be optimized for speed or code size.\n *\n * @generated from enum google.protobuf.FileOptions.OptimizeMode\n */\nexport var FileOptions_OptimizeMode;\n(function (FileOptions_OptimizeMode) {\n    /**\n     * Generate complete code for parsing, serialization,\n     *\n     * @generated from enum value: SPEED = 1;\n     */\n    FileOptions_OptimizeMode[FileOptions_OptimizeMode[\"SPEED\"] = 1] = \"SPEED\";\n    /**\n     * etc.\n     *\n     * Use ReflectionOps to implement these methods.\n     *\n     * @generated from enum value: CODE_SIZE = 2;\n     */\n    FileOptions_OptimizeMode[FileOptions_OptimizeMode[\"CODE_SIZE\"] = 2] = \"CODE_SIZE\";\n    /**\n     * Generate code using MessageLite and the lite runtime.\n     *\n     * @generated from enum value: LITE_RUNTIME = 3;\n     */\n    FileOptions_OptimizeMode[FileOptions_OptimizeMode[\"LITE_RUNTIME\"] = 3] = \"LITE_RUNTIME\";\n})(FileOptions_OptimizeMode || (FileOptions_OptimizeMode = {}));\n/**\n * Describes the enum google.protobuf.FileOptions.OptimizeMode.\n */\nexport const FileOptions_OptimizeModeSchema = /*@__PURE__*/ enumDesc(file_google_protobuf_descriptor, 10, 0);\n/**\n * Describes the message google.protobuf.MessageOptions.\n * Use `create(MessageOptionsSchema)` to create a new message.\n */\nexport const MessageOptionsSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_descriptor, 11);\n/**\n * Describes the message google.protobuf.FieldOptions.\n * Use `create(FieldOptionsSchema)` to create a new message.\n */\nexport const FieldOptionsSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_descriptor, 12);\n/**\n * Describes the message google.protobuf.FieldOptions.EditionDefault.\n * Use `create(FieldOptions_EditionDefaultSchema)` to create a new message.\n */\nexport const FieldOptions_EditionDefaultSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_descriptor, 12, 0);\n/**\n * Describes the message google.protobuf.FieldOptions.FeatureSupport.\n * Use `create(FieldOptions_FeatureSupportSchema)` to create a new message.\n */\nexport const FieldOptions_FeatureSupportSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_descriptor, 12, 1);\n/**\n * @generated from enum google.protobuf.FieldOptions.CType\n */\nexport var FieldOptions_CType;\n(function (FieldOptions_CType) {\n    /**\n     * Default mode.\n     *\n     * @generated from enum value: STRING = 0;\n     */\n    FieldOptions_CType[FieldOptions_CType[\"STRING\"] = 0] = \"STRING\";\n    /**\n     * The option [ctype=CORD] may be applied to a non-repeated field of type\n     * \"bytes\". It indicates that in C++, the data should be stored in a Cord\n     * instead of a string.  For very large strings, this may reduce memory\n     * fragmentation. It may also allow better performance when parsing from a\n     * Cord, or when parsing with aliasing enabled, as the parsed Cord may then\n     * alias the original buffer.\n     *\n     * @generated from enum value: CORD = 1;\n     */\n    FieldOptions_CType[FieldOptions_CType[\"CORD\"] = 1] = \"CORD\";\n    /**\n     * @generated from enum value: STRING_PIECE = 2;\n     */\n    FieldOptions_CType[FieldOptions_CType[\"STRING_PIECE\"] = 2] = \"STRING_PIECE\";\n})(FieldOptions_CType || (FieldOptions_CType = {}));\n/**\n * Describes the enum google.protobuf.FieldOptions.CType.\n */\nexport const FieldOptions_CTypeSchema = /*@__PURE__*/ enumDesc(file_google_protobuf_descriptor, 12, 0);\n/**\n * @generated from enum google.protobuf.FieldOptions.JSType\n */\nexport var FieldOptions_JSType;\n(function (FieldOptions_JSType) {\n    /**\n     * Use the default type.\n     *\n     * @generated from enum value: JS_NORMAL = 0;\n     */\n    FieldOptions_JSType[FieldOptions_JSType[\"JS_NORMAL\"] = 0] = \"JS_NORMAL\";\n    /**\n     * Use JavaScript strings.\n     *\n     * @generated from enum value: JS_STRING = 1;\n     */\n    FieldOptions_JSType[FieldOptions_JSType[\"JS_STRING\"] = 1] = \"JS_STRING\";\n    /**\n     * Use JavaScript numbers.\n     *\n     * @generated from enum value: JS_NUMBER = 2;\n     */\n    FieldOptions_JSType[FieldOptions_JSType[\"JS_NUMBER\"] = 2] = \"JS_NUMBER\";\n})(FieldOptions_JSType || (FieldOptions_JSType = {}));\n/**\n * Describes the enum google.protobuf.FieldOptions.JSType.\n */\nexport const FieldOptions_JSTypeSchema = /*@__PURE__*/ enumDesc(file_google_protobuf_descriptor, 12, 1);\n/**\n * If set to RETENTION_SOURCE, the option will be omitted from the binary.\n *\n * @generated from enum google.protobuf.FieldOptions.OptionRetention\n */\nexport var FieldOptions_OptionRetention;\n(function (FieldOptions_OptionRetention) {\n    /**\n     * @generated from enum value: RETENTION_UNKNOWN = 0;\n     */\n    FieldOptions_OptionRetention[FieldOptions_OptionRetention[\"RETENTION_UNKNOWN\"] = 0] = \"RETENTION_UNKNOWN\";\n    /**\n     * @generated from enum value: RETENTION_RUNTIME = 1;\n     */\n    FieldOptions_OptionRetention[FieldOptions_OptionRetention[\"RETENTION_RUNTIME\"] = 1] = \"RETENTION_RUNTIME\";\n    /**\n     * @generated from enum value: RETENTION_SOURCE = 2;\n     */\n    FieldOptions_OptionRetention[FieldOptions_OptionRetention[\"RETENTION_SOURCE\"] = 2] = \"RETENTION_SOURCE\";\n})(FieldOptions_OptionRetention || (FieldOptions_OptionRetention = {}));\n/**\n * Describes the enum google.protobuf.FieldOptions.OptionRetention.\n */\nexport const FieldOptions_OptionRetentionSchema = /*@__PURE__*/ enumDesc(file_google_protobuf_descriptor, 12, 2);\n/**\n * This indicates the types of entities that the field may apply to when used\n * as an option. If it is unset, then the field may be freely used as an\n * option on any kind of entity.\n *\n * @generated from enum google.protobuf.FieldOptions.OptionTargetType\n */\nexport var FieldOptions_OptionTargetType;\n(function (FieldOptions_OptionTargetType) {\n    /**\n     * @generated from enum value: TARGET_TYPE_UNKNOWN = 0;\n     */\n    FieldOptions_OptionTargetType[FieldOptions_OptionTargetType[\"TARGET_TYPE_UNKNOWN\"] = 0] = \"TARGET_TYPE_UNKNOWN\";\n    /**\n     * @generated from enum value: TARGET_TYPE_FILE = 1;\n     */\n    FieldOptions_OptionTargetType[FieldOptions_OptionTargetType[\"TARGET_TYPE_FILE\"] = 1] = \"TARGET_TYPE_FILE\";\n    /**\n     * @generated from enum value: TARGET_TYPE_EXTENSION_RANGE = 2;\n     */\n    FieldOptions_OptionTargetType[FieldOptions_OptionTargetType[\"TARGET_TYPE_EXTENSION_RANGE\"] = 2] = \"TARGET_TYPE_EXTENSION_RANGE\";\n    /**\n     * @generated from enum value: TARGET_TYPE_MESSAGE = 3;\n     */\n    FieldOptions_OptionTargetType[FieldOptions_OptionTargetType[\"TARGET_TYPE_MESSAGE\"] = 3] = \"TARGET_TYPE_MESSAGE\";\n    /**\n     * @generated from enum value: TARGET_TYPE_FIELD = 4;\n     */\n    FieldOptions_OptionTargetType[FieldOptions_OptionTargetType[\"TARGET_TYPE_FIELD\"] = 4] = \"TARGET_TYPE_FIELD\";\n    /**\n     * @generated from enum value: TARGET_TYPE_ONEOF = 5;\n     */\n    FieldOptions_OptionTargetType[FieldOptions_OptionTargetType[\"TARGET_TYPE_ONEOF\"] = 5] = \"TARGET_TYPE_ONEOF\";\n    /**\n     * @generated from enum value: TARGET_TYPE_ENUM = 6;\n     */\n    FieldOptions_OptionTargetType[FieldOptions_OptionTargetType[\"TARGET_TYPE_ENUM\"] = 6] = \"TARGET_TYPE_ENUM\";\n    /**\n     * @generated from enum value: TARGET_TYPE_ENUM_ENTRY = 7;\n     */\n    FieldOptions_OptionTargetType[FieldOptions_OptionTargetType[\"TARGET_TYPE_ENUM_ENTRY\"] = 7] = \"TARGET_TYPE_ENUM_ENTRY\";\n    /**\n     * @generated from enum value: TARGET_TYPE_SERVICE = 8;\n     */\n    FieldOptions_OptionTargetType[FieldOptions_OptionTargetType[\"TARGET_TYPE_SERVICE\"] = 8] = \"TARGET_TYPE_SERVICE\";\n    /**\n     * @generated from enum value: TARGET_TYPE_METHOD = 9;\n     */\n    FieldOptions_OptionTargetType[FieldOptions_OptionTargetType[\"TARGET_TYPE_METHOD\"] = 9] = \"TARGET_TYPE_METHOD\";\n})(FieldOptions_OptionTargetType || (FieldOptions_OptionTargetType = {}));\n/**\n * Describes the enum google.protobuf.FieldOptions.OptionTargetType.\n */\nexport const FieldOptions_OptionTargetTypeSchema = /*@__PURE__*/ enumDesc(file_google_protobuf_descriptor, 12, 3);\n/**\n * Describes the message google.protobuf.OneofOptions.\n * Use `create(OneofOptionsSchema)` to create a new message.\n */\nexport const OneofOptionsSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_descriptor, 13);\n/**\n * Describes the message google.protobuf.EnumOptions.\n * Use `create(EnumOptionsSchema)` to create a new message.\n */\nexport const EnumOptionsSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_descriptor, 14);\n/**\n * Describes the message google.protobuf.EnumValueOptions.\n * Use `create(EnumValueOptionsSchema)` to create a new message.\n */\nexport const EnumValueOptionsSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_descriptor, 15);\n/**\n * Describes the message google.protobuf.ServiceOptions.\n * Use `create(ServiceOptionsSchema)` to create a new message.\n */\nexport const ServiceOptionsSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_descriptor, 16);\n/**\n * Describes the message google.protobuf.MethodOptions.\n * Use `create(MethodOptionsSchema)` to create a new message.\n */\nexport const MethodOptionsSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_descriptor, 17);\n/**\n * Is this method side-effect-free (or safe in HTTP parlance), or idempotent,\n * or neither? HTTP based RPC implementation may choose GET verb for safe\n * methods, and PUT verb for idempotent methods instead of the default POST.\n *\n * @generated from enum google.protobuf.MethodOptions.IdempotencyLevel\n */\nexport var MethodOptions_IdempotencyLevel;\n(function (MethodOptions_IdempotencyLevel) {\n    /**\n     * @generated from enum value: IDEMPOTENCY_UNKNOWN = 0;\n     */\n    MethodOptions_IdempotencyLevel[MethodOptions_IdempotencyLevel[\"IDEMPOTENCY_UNKNOWN\"] = 0] = \"IDEMPOTENCY_UNKNOWN\";\n    /**\n     * implies idempotent\n     *\n     * @generated from enum value: NO_SIDE_EFFECTS = 1;\n     */\n    MethodOptions_IdempotencyLevel[MethodOptions_IdempotencyLevel[\"NO_SIDE_EFFECTS\"] = 1] = \"NO_SIDE_EFFECTS\";\n    /**\n     * idempotent, but may have side effects\n     *\n     * @generated from enum value: IDEMPOTENT = 2;\n     */\n    MethodOptions_IdempotencyLevel[MethodOptions_IdempotencyLevel[\"IDEMPOTENT\"] = 2] = \"IDEMPOTENT\";\n})(MethodOptions_IdempotencyLevel || (MethodOptions_IdempotencyLevel = {}));\n/**\n * Describes the enum google.protobuf.MethodOptions.IdempotencyLevel.\n */\nexport const MethodOptions_IdempotencyLevelSchema = /*@__PURE__*/ enumDesc(file_google_protobuf_descriptor, 17, 0);\n/**\n * Describes the message google.protobuf.UninterpretedOption.\n * Use `create(UninterpretedOptionSchema)` to create a new message.\n */\nexport const UninterpretedOptionSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_descriptor, 18);\n/**\n * Describes the message google.protobuf.UninterpretedOption.NamePart.\n * Use `create(UninterpretedOption_NamePartSchema)` to create a new message.\n */\nexport const UninterpretedOption_NamePartSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_descriptor, 18, 0);\n/**\n * Describes the message google.protobuf.FeatureSet.\n * Use `create(FeatureSetSchema)` to create a new message.\n */\nexport const FeatureSetSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_descriptor, 19);\n/**\n * Describes the message google.protobuf.FeatureSet.VisibilityFeature.\n * Use `create(FeatureSet_VisibilityFeatureSchema)` to create a new message.\n */\nexport const FeatureSet_VisibilityFeatureSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_descriptor, 19, 0);\n/**\n * @generated from enum google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility\n */\nexport var FeatureSet_VisibilityFeature_DefaultSymbolVisibility;\n(function (FeatureSet_VisibilityFeature_DefaultSymbolVisibility) {\n    /**\n     * @generated from enum value: DEFAULT_SYMBOL_VISIBILITY_UNKNOWN = 0;\n     */\n    FeatureSet_VisibilityFeature_DefaultSymbolVisibility[FeatureSet_VisibilityFeature_DefaultSymbolVisibility[\"DEFAULT_SYMBOL_VISIBILITY_UNKNOWN\"] = 0] = \"DEFAULT_SYMBOL_VISIBILITY_UNKNOWN\";\n    /**\n     * Default pre-EDITION_2024, all UNSET visibility are export.\n     *\n     * @generated from enum value: EXPORT_ALL = 1;\n     */\n    FeatureSet_VisibilityFeature_DefaultSymbolVisibility[FeatureSet_VisibilityFeature_DefaultSymbolVisibility[\"EXPORT_ALL\"] = 1] = \"EXPORT_ALL\";\n    /**\n     * All top-level symbols default to export, nested default to local.\n     *\n     * @generated from enum value: EXPORT_TOP_LEVEL = 2;\n     */\n    FeatureSet_VisibilityFeature_DefaultSymbolVisibility[FeatureSet_VisibilityFeature_DefaultSymbolVisibility[\"EXPORT_TOP_LEVEL\"] = 2] = \"EXPORT_TOP_LEVEL\";\n    /**\n     * All symbols default to local.\n     *\n     * @generated from enum value: LOCAL_ALL = 3;\n     */\n    FeatureSet_VisibilityFeature_DefaultSymbolVisibility[FeatureSet_VisibilityFeature_DefaultSymbolVisibility[\"LOCAL_ALL\"] = 3] = \"LOCAL_ALL\";\n    /**\n     * All symbols local by default. Nested types cannot be exported.\n     * With special case caveat for message { enum {} reserved 1 to max; }\n     * This is the recommended setting for new protos.\n     *\n     * @generated from enum value: STRICT = 4;\n     */\n    FeatureSet_VisibilityFeature_DefaultSymbolVisibility[FeatureSet_VisibilityFeature_DefaultSymbolVisibility[\"STRICT\"] = 4] = \"STRICT\";\n})(FeatureSet_VisibilityFeature_DefaultSymbolVisibility || (FeatureSet_VisibilityFeature_DefaultSymbolVisibility = {}));\n/**\n * Describes the enum google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility.\n */\nexport const FeatureSet_VisibilityFeature_DefaultSymbolVisibilitySchema = /*@__PURE__*/ enumDesc(file_google_protobuf_descriptor, 19, 0, 0);\n/**\n * @generated from enum google.protobuf.FeatureSet.FieldPresence\n */\nexport var FeatureSet_FieldPresence;\n(function (FeatureSet_FieldPresence) {\n    /**\n     * @generated from enum value: FIELD_PRESENCE_UNKNOWN = 0;\n     */\n    FeatureSet_FieldPresence[FeatureSet_FieldPresence[\"FIELD_PRESENCE_UNKNOWN\"] = 0] = \"FIELD_PRESENCE_UNKNOWN\";\n    /**\n     * @generated from enum value: EXPLICIT = 1;\n     */\n    FeatureSet_FieldPresence[FeatureSet_FieldPresence[\"EXPLICIT\"] = 1] = \"EXPLICIT\";\n    /**\n     * @generated from enum value: IMPLICIT = 2;\n     */\n    FeatureSet_FieldPresence[FeatureSet_FieldPresence[\"IMPLICIT\"] = 2] = \"IMPLICIT\";\n    /**\n     * @generated from enum value: LEGACY_REQUIRED = 3;\n     */\n    FeatureSet_FieldPresence[FeatureSet_FieldPresence[\"LEGACY_REQUIRED\"] = 3] = \"LEGACY_REQUIRED\";\n})(FeatureSet_FieldPresence || (FeatureSet_FieldPresence = {}));\n/**\n * Describes the enum google.protobuf.FeatureSet.FieldPresence.\n */\nexport const FeatureSet_FieldPresenceSchema = /*@__PURE__*/ enumDesc(file_google_protobuf_descriptor, 19, 0);\n/**\n * @generated from enum google.protobuf.FeatureSet.EnumType\n */\nexport var FeatureSet_EnumType;\n(function (FeatureSet_EnumType) {\n    /**\n     * @generated from enum value: ENUM_TYPE_UNKNOWN = 0;\n     */\n    FeatureSet_EnumType[FeatureSet_EnumType[\"ENUM_TYPE_UNKNOWN\"] = 0] = \"ENUM_TYPE_UNKNOWN\";\n    /**\n     * @generated from enum value: OPEN = 1;\n     */\n    FeatureSet_EnumType[FeatureSet_EnumType[\"OPEN\"] = 1] = \"OPEN\";\n    /**\n     * @generated from enum value: CLOSED = 2;\n     */\n    FeatureSet_EnumType[FeatureSet_EnumType[\"CLOSED\"] = 2] = \"CLOSED\";\n})(FeatureSet_EnumType || (FeatureSet_EnumType = {}));\n/**\n * Describes the enum google.protobuf.FeatureSet.EnumType.\n */\nexport const FeatureSet_EnumTypeSchema = /*@__PURE__*/ enumDesc(file_google_protobuf_descriptor, 19, 1);\n/**\n * @generated from enum google.protobuf.FeatureSet.RepeatedFieldEncoding\n */\nexport var FeatureSet_RepeatedFieldEncoding;\n(function (FeatureSet_RepeatedFieldEncoding) {\n    /**\n     * @generated from enum value: REPEATED_FIELD_ENCODING_UNKNOWN = 0;\n     */\n    FeatureSet_RepeatedFieldEncoding[FeatureSet_RepeatedFieldEncoding[\"REPEATED_FIELD_ENCODING_UNKNOWN\"] = 0] = \"REPEATED_FIELD_ENCODING_UNKNOWN\";\n    /**\n     * @generated from enum value: PACKED = 1;\n     */\n    FeatureSet_RepeatedFieldEncoding[FeatureSet_RepeatedFieldEncoding[\"PACKED\"] = 1] = \"PACKED\";\n    /**\n     * @generated from enum value: EXPANDED = 2;\n     */\n    FeatureSet_RepeatedFieldEncoding[FeatureSet_RepeatedFieldEncoding[\"EXPANDED\"] = 2] = \"EXPANDED\";\n})(FeatureSet_RepeatedFieldEncoding || (FeatureSet_RepeatedFieldEncoding = {}));\n/**\n * Describes the enum google.protobuf.FeatureSet.RepeatedFieldEncoding.\n */\nexport const FeatureSet_RepeatedFieldEncodingSchema = /*@__PURE__*/ enumDesc(file_google_protobuf_descriptor, 19, 2);\n/**\n * @generated from enum google.protobuf.FeatureSet.Utf8Validation\n */\nexport var FeatureSet_Utf8Validation;\n(function (FeatureSet_Utf8Validation) {\n    /**\n     * @generated from enum value: UTF8_VALIDATION_UNKNOWN = 0;\n     */\n    FeatureSet_Utf8Validation[FeatureSet_Utf8Validation[\"UTF8_VALIDATION_UNKNOWN\"] = 0] = \"UTF8_VALIDATION_UNKNOWN\";\n    /**\n     * @generated from enum value: VERIFY = 2;\n     */\n    FeatureSet_Utf8Validation[FeatureSet_Utf8Validation[\"VERIFY\"] = 2] = \"VERIFY\";\n    /**\n     * @generated from enum value: NONE = 3;\n     */\n    FeatureSet_Utf8Validation[FeatureSet_Utf8Validation[\"NONE\"] = 3] = \"NONE\";\n})(FeatureSet_Utf8Validation || (FeatureSet_Utf8Validation = {}));\n/**\n * Describes the enum google.protobuf.FeatureSet.Utf8Validation.\n */\nexport const FeatureSet_Utf8ValidationSchema = /*@__PURE__*/ enumDesc(file_google_protobuf_descriptor, 19, 3);\n/**\n * @generated from enum google.protobuf.FeatureSet.MessageEncoding\n */\nexport var FeatureSet_MessageEncoding;\n(function (FeatureSet_MessageEncoding) {\n    /**\n     * @generated from enum value: MESSAGE_ENCODING_UNKNOWN = 0;\n     */\n    FeatureSet_MessageEncoding[FeatureSet_MessageEncoding[\"MESSAGE_ENCODING_UNKNOWN\"] = 0] = \"MESSAGE_ENCODING_UNKNOWN\";\n    /**\n     * @generated from enum value: LENGTH_PREFIXED = 1;\n     */\n    FeatureSet_MessageEncoding[FeatureSet_MessageEncoding[\"LENGTH_PREFIXED\"] = 1] = \"LENGTH_PREFIXED\";\n    /**\n     * @generated from enum value: DELIMITED = 2;\n     */\n    FeatureSet_MessageEncoding[FeatureSet_MessageEncoding[\"DELIMITED\"] = 2] = \"DELIMITED\";\n})(FeatureSet_MessageEncoding || (FeatureSet_MessageEncoding = {}));\n/**\n * Describes the enum google.protobuf.FeatureSet.MessageEncoding.\n */\nexport const FeatureSet_MessageEncodingSchema = /*@__PURE__*/ enumDesc(file_google_protobuf_descriptor, 19, 4);\n/**\n * @generated from enum google.protobuf.FeatureSet.JsonFormat\n */\nexport var FeatureSet_JsonFormat;\n(function (FeatureSet_JsonFormat) {\n    /**\n     * @generated from enum value: JSON_FORMAT_UNKNOWN = 0;\n     */\n    FeatureSet_JsonFormat[FeatureSet_JsonFormat[\"JSON_FORMAT_UNKNOWN\"] = 0] = \"JSON_FORMAT_UNKNOWN\";\n    /**\n     * @generated from enum value: ALLOW = 1;\n     */\n    FeatureSet_JsonFormat[FeatureSet_JsonFormat[\"ALLOW\"] = 1] = \"ALLOW\";\n    /**\n     * @generated from enum value: LEGACY_BEST_EFFORT = 2;\n     */\n    FeatureSet_JsonFormat[FeatureSet_JsonFormat[\"LEGACY_BEST_EFFORT\"] = 2] = \"LEGACY_BEST_EFFORT\";\n})(FeatureSet_JsonFormat || (FeatureSet_JsonFormat = {}));\n/**\n * Describes the enum google.protobuf.FeatureSet.JsonFormat.\n */\nexport const FeatureSet_JsonFormatSchema = /*@__PURE__*/ enumDesc(file_google_protobuf_descriptor, 19, 5);\n/**\n * @generated from enum google.protobuf.FeatureSet.EnforceNamingStyle\n */\nexport var FeatureSet_EnforceNamingStyle;\n(function (FeatureSet_EnforceNamingStyle) {\n    /**\n     * @generated from enum value: ENFORCE_NAMING_STYLE_UNKNOWN = 0;\n     */\n    FeatureSet_EnforceNamingStyle[FeatureSet_EnforceNamingStyle[\"ENFORCE_NAMING_STYLE_UNKNOWN\"] = 0] = \"ENFORCE_NAMING_STYLE_UNKNOWN\";\n    /**\n     * @generated from enum value: STYLE2024 = 1;\n     */\n    FeatureSet_EnforceNamingStyle[FeatureSet_EnforceNamingStyle[\"STYLE2024\"] = 1] = \"STYLE2024\";\n    /**\n     * @generated from enum value: STYLE_LEGACY = 2;\n     */\n    FeatureSet_EnforceNamingStyle[FeatureSet_EnforceNamingStyle[\"STYLE_LEGACY\"] = 2] = \"STYLE_LEGACY\";\n})(FeatureSet_EnforceNamingStyle || (FeatureSet_EnforceNamingStyle = {}));\n/**\n * Describes the enum google.protobuf.FeatureSet.EnforceNamingStyle.\n */\nexport const FeatureSet_EnforceNamingStyleSchema = /*@__PURE__*/ enumDesc(file_google_protobuf_descriptor, 19, 6);\n/**\n * Describes the message google.protobuf.FeatureSetDefaults.\n * Use `create(FeatureSetDefaultsSchema)` to create a new message.\n */\nexport const FeatureSetDefaultsSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_descriptor, 20);\n/**\n * Describes the message google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault.\n * Use `create(FeatureSetDefaults_FeatureSetEditionDefaultSchema)` to create a new message.\n */\nexport const FeatureSetDefaults_FeatureSetEditionDefaultSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_descriptor, 20, 0);\n/**\n * Describes the message google.protobuf.SourceCodeInfo.\n * Use `create(SourceCodeInfoSchema)` to create a new message.\n */\nexport const SourceCodeInfoSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_descriptor, 21);\n/**\n * Describes the message google.protobuf.SourceCodeInfo.Location.\n * Use `create(SourceCodeInfo_LocationSchema)` to create a new message.\n */\nexport const SourceCodeInfo_LocationSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_descriptor, 21, 0);\n/**\n * Describes the message google.protobuf.GeneratedCodeInfo.\n * Use `create(GeneratedCodeInfoSchema)` to create a new message.\n */\nexport const GeneratedCodeInfoSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_descriptor, 22);\n/**\n * Describes the message google.protobuf.GeneratedCodeInfo.Annotation.\n * Use `create(GeneratedCodeInfo_AnnotationSchema)` to create a new message.\n */\nexport const GeneratedCodeInfo_AnnotationSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_descriptor, 22, 0);\n/**\n * Represents the identified object's effect on the element in the original\n * .proto file.\n *\n * @generated from enum google.protobuf.GeneratedCodeInfo.Annotation.Semantic\n */\nexport var GeneratedCodeInfo_Annotation_Semantic;\n(function (GeneratedCodeInfo_Annotation_Semantic) {\n    /**\n     * There is no effect or the effect is indescribable.\n     *\n     * @generated from enum value: NONE = 0;\n     */\n    GeneratedCodeInfo_Annotation_Semantic[GeneratedCodeInfo_Annotation_Semantic[\"NONE\"] = 0] = \"NONE\";\n    /**\n     * The element is set or otherwise mutated.\n     *\n     * @generated from enum value: SET = 1;\n     */\n    GeneratedCodeInfo_Annotation_Semantic[GeneratedCodeInfo_Annotation_Semantic[\"SET\"] = 1] = \"SET\";\n    /**\n     * An alias to the element is returned.\n     *\n     * @generated from enum value: ALIAS = 2;\n     */\n    GeneratedCodeInfo_Annotation_Semantic[GeneratedCodeInfo_Annotation_Semantic[\"ALIAS\"] = 2] = \"ALIAS\";\n})(GeneratedCodeInfo_Annotation_Semantic || (GeneratedCodeInfo_Annotation_Semantic = {}));\n/**\n * Describes the enum google.protobuf.GeneratedCodeInfo.Annotation.Semantic.\n */\nexport const GeneratedCodeInfo_Annotation_SemanticSchema = /*@__PURE__*/ enumDesc(file_google_protobuf_descriptor, 22, 0, 0);\n/**\n * The full set of known editions.\n *\n * @generated from enum google.protobuf.Edition\n */\nexport var Edition;\n(function (Edition) {\n    /**\n     * A placeholder for an unknown edition value.\n     *\n     * @generated from enum value: EDITION_UNKNOWN = 0;\n     */\n    Edition[Edition[\"EDITION_UNKNOWN\"] = 0] = \"EDITION_UNKNOWN\";\n    /**\n     * A placeholder edition for specifying default behaviors *before* a feature\n     * was first introduced.  This is effectively an \"infinite past\".\n     *\n     * @generated from enum value: EDITION_LEGACY = 900;\n     */\n    Edition[Edition[\"EDITION_LEGACY\"] = 900] = \"EDITION_LEGACY\";\n    /**\n     * Legacy syntax \"editions\".  These pre-date editions, but behave much like\n     * distinct editions.  These can't be used to specify the edition of proto\n     * files, but feature definitions must supply proto2/proto3 defaults for\n     * backwards compatibility.\n     *\n     * @generated from enum value: EDITION_PROTO2 = 998;\n     */\n    Edition[Edition[\"EDITION_PROTO2\"] = 998] = \"EDITION_PROTO2\";\n    /**\n     * @generated from enum value: EDITION_PROTO3 = 999;\n     */\n    Edition[Edition[\"EDITION_PROTO3\"] = 999] = \"EDITION_PROTO3\";\n    /**\n     * Editions that have been released.  The specific values are arbitrary and\n     * should not be depended on, but they will always be time-ordered for easy\n     * comparison.\n     *\n     * @generated from enum value: EDITION_2023 = 1000;\n     */\n    Edition[Edition[\"EDITION_2023\"] = 1000] = \"EDITION_2023\";\n    /**\n     * @generated from enum value: EDITION_2024 = 1001;\n     */\n    Edition[Edition[\"EDITION_2024\"] = 1001] = \"EDITION_2024\";\n    /**\n     * Placeholder editions for testing feature resolution.  These should not be\n     * used or relied on outside of tests.\n     *\n     * @generated from enum value: EDITION_1_TEST_ONLY = 1;\n     */\n    Edition[Edition[\"EDITION_1_TEST_ONLY\"] = 1] = \"EDITION_1_TEST_ONLY\";\n    /**\n     * @generated from enum value: EDITION_2_TEST_ONLY = 2;\n     */\n    Edition[Edition[\"EDITION_2_TEST_ONLY\"] = 2] = \"EDITION_2_TEST_ONLY\";\n    /**\n     * @generated from enum value: EDITION_99997_TEST_ONLY = 99997;\n     */\n    Edition[Edition[\"EDITION_99997_TEST_ONLY\"] = 99997] = \"EDITION_99997_TEST_ONLY\";\n    /**\n     * @generated from enum value: EDITION_99998_TEST_ONLY = 99998;\n     */\n    Edition[Edition[\"EDITION_99998_TEST_ONLY\"] = 99998] = \"EDITION_99998_TEST_ONLY\";\n    /**\n     * @generated from enum value: EDITION_99999_TEST_ONLY = 99999;\n     */\n    Edition[Edition[\"EDITION_99999_TEST_ONLY\"] = 99999] = \"EDITION_99999_TEST_ONLY\";\n    /**\n     * Placeholder for specifying unbounded edition support.  This should only\n     * ever be used by plugins that can expect to never require any changes to\n     * support a new edition.\n     *\n     * @generated from enum value: EDITION_MAX = 2147483647;\n     */\n    Edition[Edition[\"EDITION_MAX\"] = 2147483647] = \"EDITION_MAX\";\n})(Edition || (Edition = {}));\n/**\n * Describes the enum google.protobuf.Edition.\n */\nexport const EditionSchema = /*@__PURE__*/ enumDesc(file_google_protobuf_descriptor, 0);\n/**\n * Describes the 'visibility' of a symbol with respect to the proto import\n * system. Symbols can only be imported when the visibility rules do not prevent\n * it (ex: local symbols cannot be imported).  Visibility modifiers can only set\n * on `message` and `enum` as they are the only types available to be referenced\n * from other files.\n *\n * @generated from enum google.protobuf.SymbolVisibility\n */\nexport var SymbolVisibility;\n(function (SymbolVisibility) {\n    /**\n     * @generated from enum value: VISIBILITY_UNSET = 0;\n     */\n    SymbolVisibility[SymbolVisibility[\"VISIBILITY_UNSET\"] = 0] = \"VISIBILITY_UNSET\";\n    /**\n     * @generated from enum value: VISIBILITY_LOCAL = 1;\n     */\n    SymbolVisibility[SymbolVisibility[\"VISIBILITY_LOCAL\"] = 1] = \"VISIBILITY_LOCAL\";\n    /**\n     * @generated from enum value: VISIBILITY_EXPORT = 2;\n     */\n    SymbolVisibility[SymbolVisibility[\"VISIBILITY_EXPORT\"] = 2] = \"VISIBILITY_EXPORT\";\n})(SymbolVisibility || (SymbolVisibility = {}));\n/**\n * Describes the enum google.protobuf.SymbolVisibility.\n */\nexport const SymbolVisibilitySchema = /*@__PURE__*/ enumDesc(file_google_protobuf_descriptor, 1);\n","// Copyright 2021-2025 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { ScalarType } from \"./descriptors.js\";\nimport { scalarZeroValue } from \"./reflect/scalar.js\";\nimport { reflect } from \"./reflect/reflect.js\";\nimport { BinaryReader, WireType } from \"./wire/binary-encoding.js\";\nimport { varint32write } from \"./wire/varint.js\";\n// Default options for parsing binary data.\nconst readDefaults = {\n    readUnknownFields: true,\n};\nfunction makeReadOptions(options) {\n    return options ? Object.assign(Object.assign({}, readDefaults), options) : readDefaults;\n}\n/**\n * Parse serialized binary data.\n */\nexport function fromBinary(schema, bytes, options) {\n    const msg = reflect(schema, undefined, false);\n    readMessage(msg, new BinaryReader(bytes), makeReadOptions(options), false, bytes.byteLength);\n    return msg.message;\n}\n/**\n * Parse from binary data, merging fields.\n *\n * Repeated fields are appended. Map entries are added, overwriting\n * existing keys.\n *\n * If a message field is already present, it will be merged with the\n * new data.\n */\nexport function mergeFromBinary(schema, target, bytes, options) {\n    readMessage(reflect(schema, target, false), new BinaryReader(bytes), makeReadOptions(options), false, bytes.byteLength);\n    return target;\n}\n/**\n * If `delimited` is false, read the length given in `lengthOrDelimitedFieldNo`.\n *\n * If `delimited` is true, read until an EndGroup tag. `lengthOrDelimitedFieldNo`\n * is the expected field number.\n *\n * @private\n */\nfunction readMessage(message, reader, options, delimited, lengthOrDelimitedFieldNo) {\n    var _a;\n    const end = delimited ? reader.len : reader.pos + lengthOrDelimitedFieldNo;\n    let fieldNo;\n    let wireType;\n    const unknownFields = (_a = message.getUnknown()) !== null && _a !== void 0 ? _a : [];\n    while (reader.pos < end) {\n        [fieldNo, wireType] = reader.tag();\n        if (delimited && wireType == WireType.EndGroup) {\n            break;\n        }\n        const field = message.findNumber(fieldNo);\n        if (!field) {\n            const data = reader.skip(wireType, fieldNo);\n            if (options.readUnknownFields) {\n                unknownFields.push({ no: fieldNo, wireType, data });\n            }\n            continue;\n        }\n        readField(message, reader, field, wireType, options);\n    }\n    if (delimited) {\n        if (wireType != WireType.EndGroup || fieldNo !== lengthOrDelimitedFieldNo) {\n            throw new Error(\"invalid end group tag\");\n        }\n    }\n    if (unknownFields.length > 0) {\n        message.setUnknown(unknownFields);\n    }\n}\n/**\n * @private\n */\nexport function readField(message, reader, field, wireType, options) {\n    var _a;\n    switch (field.fieldKind) {\n        case \"scalar\":\n            message.set(field, readScalar(reader, field.scalar));\n            break;\n        case \"enum\":\n            const val = readScalar(reader, ScalarType.INT32);\n            if (field.enum.open) {\n                message.set(field, val);\n            }\n            else {\n                const ok = field.enum.values.some((v) => v.number === val);\n                if (ok) {\n                    message.set(field, val);\n                }\n                else if (options.readUnknownFields) {\n                    const bytes = [];\n                    varint32write(val, bytes);\n                    const unknownFields = (_a = message.getUnknown()) !== null && _a !== void 0 ? _a : [];\n                    unknownFields.push({\n                        no: field.number,\n                        wireType,\n                        data: new Uint8Array(bytes),\n                    });\n                    message.setUnknown(unknownFields);\n                }\n            }\n            break;\n        case \"message\":\n            message.set(field, readMessageField(reader, options, field, message.get(field)));\n            break;\n        case \"list\":\n            readListField(reader, wireType, message.get(field), options);\n            break;\n        case \"map\":\n            readMapEntry(reader, message.get(field), options);\n            break;\n    }\n}\n// Read a map field, expecting key field = 1, value field = 2\nfunction readMapEntry(reader, map, options) {\n    const field = map.field();\n    let key;\n    let val;\n    // Read the length of the map entry, which is a varint.\n    const len = reader.uint32();\n    // WARNING: Calculate end AFTER advancing reader.pos (above), so that\n    //          reader.pos is at the start of the map entry.\n    const end = reader.pos + len;\n    while (reader.pos < end) {\n        const [fieldNo] = reader.tag();\n        switch (fieldNo) {\n            case 1:\n                key = readScalar(reader, field.mapKey);\n                break;\n            case 2:\n                switch (field.mapKind) {\n                    case \"scalar\":\n                        val = readScalar(reader, field.scalar);\n                        break;\n                    case \"enum\":\n                        val = reader.int32();\n                        break;\n                    case \"message\":\n                        val = readMessageField(reader, options, field);\n                        break;\n                }\n                break;\n        }\n    }\n    if (key === undefined) {\n        key = scalarZeroValue(field.mapKey, false);\n    }\n    if (val === undefined) {\n        switch (field.mapKind) {\n            case \"scalar\":\n                val = scalarZeroValue(field.scalar, false);\n                break;\n            case \"enum\":\n                val = field.enum.values[0].number;\n                break;\n            case \"message\":\n                val = reflect(field.message, undefined, false);\n                break;\n        }\n    }\n    map.set(key, val);\n}\nfunction readListField(reader, wireType, list, options) {\n    var _a;\n    const field = list.field();\n    if (field.listKind === \"message\") {\n        list.add(readMessageField(reader, options, field));\n        return;\n    }\n    const scalarType = (_a = field.scalar) !== null && _a !== void 0 ? _a : ScalarType.INT32;\n    const packed = wireType == WireType.LengthDelimited &&\n        scalarType != ScalarType.STRING &&\n        scalarType != ScalarType.BYTES;\n    if (!packed) {\n        list.add(readScalar(reader, scalarType));\n        return;\n    }\n    const e = reader.uint32() + reader.pos;\n    while (reader.pos < e) {\n        list.add(readScalar(reader, scalarType));\n    }\n}\nfunction readMessageField(reader, options, field, mergeMessage) {\n    const delimited = field.delimitedEncoding;\n    const message = mergeMessage !== null && mergeMessage !== void 0 ? mergeMessage : reflect(field.message, undefined, false);\n    readMessage(message, reader, options, delimited, delimited ? field.number : reader.uint32());\n    return message;\n}\nfunction readScalar(reader, type) {\n    switch (type) {\n        case ScalarType.STRING:\n            return reader.string();\n        case ScalarType.BOOL:\n            return reader.bool();\n        case ScalarType.DOUBLE:\n            return reader.double();\n        case ScalarType.FLOAT:\n            return reader.float();\n        case ScalarType.INT32:\n            return reader.int32();\n        case ScalarType.INT64:\n            return reader.int64();\n        case ScalarType.UINT64:\n            return reader.uint64();\n        case ScalarType.FIXED64:\n            return reader.fixed64();\n        case ScalarType.BYTES:\n            return reader.bytes();\n        case ScalarType.FIXED32:\n            return reader.fixed32();\n        case ScalarType.SFIXED32:\n            return reader.sfixed32();\n        case ScalarType.SFIXED64:\n            return reader.sfixed64();\n        case ScalarType.SINT64:\n            return reader.sint64();\n        case ScalarType.UINT32:\n            return reader.uint32();\n        case ScalarType.SINT32:\n            return reader.sint32();\n    }\n}\n","// Copyright 2021-2025 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { base64Decode } from \"../wire/base64-encoding.js\";\nimport { FileDescriptorProtoSchema } from \"../wkt/gen/google/protobuf/descriptor_pb.js\";\nimport { createFileRegistry } from \"../registry.js\";\nimport { restoreJsonNames } from \"./restore-json-names.js\";\nimport { fromBinary } from \"../from-binary.js\";\n/**\n * Hydrate a file descriptor.\n *\n * @private\n */\nexport function fileDesc(b64, imports) {\n    var _a;\n    const root = fromBinary(FileDescriptorProtoSchema, base64Decode(b64));\n    root.messageType.forEach(restoreJsonNames);\n    root.dependency = (_a = imports === null || imports === void 0 ? void 0 : imports.map((f) => f.proto.name)) !== null && _a !== void 0 ? _a : [];\n    const reg = createFileRegistry(root, (protoFileName) => imports === null || imports === void 0 ? void 0 : imports.find((f) => f.proto.name === protoFileName));\n    // biome-ignore lint/style/noNonNullAssertion: non-null assertion because we just created the registry from the file we look up\n    return reg.getFile(root.name);\n}\n","// Copyright 2021-2025 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { fileDesc } from \"../../../../codegenv2/file.js\";\nimport { messageDesc } from \"../../../../codegenv2/message.js\";\n/**\n * Describes the file google/protobuf/timestamp.proto.\n */\nexport const file_google_protobuf_timestamp = /*@__PURE__*/ fileDesc(\"Ch9nb29nbGUvcHJvdG9idWYvdGltZXN0YW1wLnByb3RvEg9nb29nbGUucHJvdG9idWYiKwoJVGltZXN0YW1wEg8KB3NlY29uZHMYASABKAMSDQoFbmFub3MYAiABKAVChQEKE2NvbS5nb29nbGUucHJvdG9idWZCDlRpbWVzdGFtcFByb3RvUAFaMmdvb2dsZS5nb2xhbmcub3JnL3Byb3RvYnVmL3R5cGVzL2tub3duL3RpbWVzdGFtcHBi+AEBogIDR1BCqgIeR29vZ2xlLlByb3RvYnVmLldlbGxLbm93blR5cGVzYgZwcm90bzM\");\n/**\n * Describes the message google.protobuf.Timestamp.\n * Use `create(TimestampSchema)` to create a new message.\n */\nexport const TimestampSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_timestamp, 0);\n","// Copyright 2021-2025 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { TimestampSchema } from \"./gen/google/protobuf/timestamp_pb.js\";\nimport { create } from \"../create.js\";\nimport { protoInt64 } from \"../proto-int64.js\";\n/**\n * Create a google.protobuf.Timestamp for the current time.\n */\nexport function timestampNow() {\n    return timestampFromDate(new Date());\n}\n/**\n * Create a google.protobuf.Timestamp message from an ECMAScript Date.\n */\nexport function timestampFromDate(date) {\n    return timestampFromMs(date.getTime());\n}\n/**\n * Convert a google.protobuf.Timestamp message to an ECMAScript Date.\n */\nexport function timestampDate(timestamp) {\n    return new Date(timestampMs(timestamp));\n}\n/**\n * Create a google.protobuf.Timestamp message from a Unix timestamp in milliseconds.\n */\nexport function timestampFromMs(timestampMs) {\n    const seconds = Math.floor(timestampMs / 1000);\n    return create(TimestampSchema, {\n        seconds: protoInt64.parse(seconds),\n        nanos: (timestampMs - seconds * 1000) * 1000000,\n    });\n}\n/**\n * Convert a google.protobuf.Timestamp to a Unix timestamp in milliseconds.\n */\nexport function timestampMs(timestamp) {\n    return (Number(timestamp.seconds) * 1000 + Math.round(timestamp.nanos / 1000000));\n}\n","// Copyright 2021-2025 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { fileDesc } from \"../../../../codegenv2/file.js\";\nimport { messageDesc } from \"../../../../codegenv2/message.js\";\n/**\n * Describes the file google/protobuf/duration.proto.\n */\nexport const file_google_protobuf_duration = /*@__PURE__*/ fileDesc(\"Ch5nb29nbGUvcHJvdG9idWYvZHVyYXRpb24ucHJvdG8SD2dvb2dsZS5wcm90b2J1ZiIqCghEdXJhdGlvbhIPCgdzZWNvbmRzGAEgASgDEg0KBW5hbm9zGAIgASgFQoMBChNjb20uZ29vZ2xlLnByb3RvYnVmQg1EdXJhdGlvblByb3RvUAFaMWdvb2dsZS5nb2xhbmcub3JnL3Byb3RvYnVmL3R5cGVzL2tub3duL2R1cmF0aW9ucGL4AQGiAgNHUEKqAh5Hb29nbGUuUHJvdG9idWYuV2VsbEtub3duVHlwZXNiBnByb3RvMw\");\n/**\n * Describes the message google.protobuf.Duration.\n * Use `create(DurationSchema)` to create a new message.\n */\nexport const DurationSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_duration, 0);\n","// Copyright 2021-2025 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { fileDesc } from \"../../../../codegenv2/file.js\";\nimport { messageDesc } from \"../../../../codegenv2/message.js\";\n/**\n * Describes the file google/protobuf/any.proto.\n */\nexport const file_google_protobuf_any = /*@__PURE__*/ fileDesc(\"Chlnb29nbGUvcHJvdG9idWYvYW55LnByb3RvEg9nb29nbGUucHJvdG9idWYiJgoDQW55EhAKCHR5cGVfdXJsGAEgASgJEg0KBXZhbHVlGAIgASgMQnYKE2NvbS5nb29nbGUucHJvdG9idWZCCEFueVByb3RvUAFaLGdvb2dsZS5nb2xhbmcub3JnL3Byb3RvYnVmL3R5cGVzL2tub3duL2FueXBiogIDR1BCqgIeR29vZ2xlLlByb3RvYnVmLldlbGxLbm93blR5cGVzYgZwcm90bzM\");\n/**\n * Describes the message google.protobuf.Any.\n * Use `create(AnySchema)` to create a new message.\n */\nexport const AnySchema = /*@__PURE__*/ messageDesc(file_google_protobuf_any, 0);\n","// Copyright 2021-2025 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { reflect } from \"./reflect/reflect.js\";\nimport { BinaryWriter, WireType } from \"./wire/binary-encoding.js\";\nimport { ScalarType } from \"./descriptors.js\";\n// bootstrap-inject google.protobuf.FeatureSet.FieldPresence.LEGACY_REQUIRED: const $name: FeatureSet_FieldPresence.$localName = $number;\nconst LEGACY_REQUIRED = 3;\n// Default options for serializing binary data.\nconst writeDefaults = {\n    writeUnknownFields: true,\n};\nfunction makeWriteOptions(options) {\n    return options ? Object.assign(Object.assign({}, writeDefaults), options) : writeDefaults;\n}\nexport function toBinary(schema, message, options) {\n    return writeFields(new BinaryWriter(), makeWriteOptions(options), reflect(schema, message)).finish();\n}\nfunction writeFields(writer, opts, msg) {\n    var _a;\n    for (const f of msg.sortedFields) {\n        if (!msg.isSet(f)) {\n            if (f.presence == LEGACY_REQUIRED) {\n                throw new Error(`cannot encode ${f} to binary: required field not set`);\n            }\n            continue;\n        }\n        writeField(writer, opts, msg, f);\n    }\n    if (opts.writeUnknownFields) {\n        for (const { no, wireType, data } of (_a = msg.getUnknown()) !== null && _a !== void 0 ? _a : []) {\n            writer.tag(no, wireType).raw(data);\n        }\n    }\n    return writer;\n}\n/**\n * @private\n */\nexport function writeField(writer, opts, msg, field) {\n    var _a;\n    switch (field.fieldKind) {\n        case \"scalar\":\n        case \"enum\":\n            writeScalar(writer, msg.desc.typeName, field.name, (_a = field.scalar) !== null && _a !== void 0 ? _a : ScalarType.INT32, field.number, msg.get(field));\n            break;\n        case \"list\":\n            writeListField(writer, opts, field, msg.get(field));\n            break;\n        case \"message\":\n            writeMessageField(writer, opts, field, msg.get(field));\n            break;\n        case \"map\":\n            for (const [key, val] of msg.get(field)) {\n                writeMapEntry(writer, opts, field, key, val);\n            }\n            break;\n    }\n}\nfunction writeScalar(writer, msgName, fieldName, scalarType, fieldNo, value) {\n    writeScalarValue(writer.tag(fieldNo, writeTypeOfScalar(scalarType)), msgName, fieldName, scalarType, value);\n}\nfunction writeMessageField(writer, opts, field, message) {\n    if (field.delimitedEncoding) {\n        writeFields(writer.tag(field.number, WireType.StartGroup), opts, message).tag(field.number, WireType.EndGroup);\n    }\n    else {\n        writeFields(writer.tag(field.number, WireType.LengthDelimited).fork(), opts, message).join();\n    }\n}\nfunction writeListField(writer, opts, field, list) {\n    var _a;\n    if (field.listKind == \"message\") {\n        for (const item of list) {\n            writeMessageField(writer, opts, field, item);\n        }\n        return;\n    }\n    const scalarType = (_a = field.scalar) !== null && _a !== void 0 ? _a : ScalarType.INT32;\n    if (field.packed) {\n        if (!list.size) {\n            return;\n        }\n        writer.tag(field.number, WireType.LengthDelimited).fork();\n        for (const item of list) {\n            writeScalarValue(writer, field.parent.typeName, field.name, scalarType, item);\n        }\n        writer.join();\n        return;\n    }\n    for (const item of list) {\n        writeScalar(writer, field.parent.typeName, field.name, scalarType, field.number, item);\n    }\n}\nfunction writeMapEntry(writer, opts, field, key, value) {\n    var _a;\n    writer.tag(field.number, WireType.LengthDelimited).fork();\n    // write key, expecting key field number = 1\n    writeScalar(writer, field.parent.typeName, field.name, field.mapKey, 1, key);\n    // write value, expecting value field number = 2\n    switch (field.mapKind) {\n        case \"scalar\":\n        case \"enum\":\n            writeScalar(writer, field.parent.typeName, field.name, (_a = field.scalar) !== null && _a !== void 0 ? _a : ScalarType.INT32, 2, value);\n            break;\n        case \"message\":\n            writeFields(writer.tag(2, WireType.LengthDelimited).fork(), opts, value).join();\n            break;\n    }\n    writer.join();\n}\nfunction writeScalarValue(writer, msgName, fieldName, type, value) {\n    try {\n        switch (type) {\n            case ScalarType.STRING:\n                writer.string(value);\n                break;\n            case ScalarType.BOOL:\n                writer.bool(value);\n                break;\n            case ScalarType.DOUBLE:\n                writer.double(value);\n                break;\n            case ScalarType.FLOAT:\n                writer.float(value);\n                break;\n            case ScalarType.INT32:\n                writer.int32(value);\n                break;\n            case ScalarType.INT64:\n                writer.int64(value);\n                break;\n            case ScalarType.UINT64:\n                writer.uint64(value);\n                break;\n            case ScalarType.FIXED64:\n                writer.fixed64(value);\n                break;\n            case ScalarType.BYTES:\n                writer.bytes(value);\n                break;\n            case ScalarType.FIXED32:\n                writer.fixed32(value);\n                break;\n            case ScalarType.SFIXED32:\n                writer.sfixed32(value);\n                break;\n            case ScalarType.SFIXED64:\n                writer.sfixed64(value);\n                break;\n            case ScalarType.SINT64:\n                writer.sint64(value);\n                break;\n            case ScalarType.UINT32:\n                writer.uint32(value);\n                break;\n            case ScalarType.SINT32:\n                writer.sint32(value);\n                break;\n        }\n    }\n    catch (e) {\n        if (e instanceof Error) {\n            throw new Error(`cannot encode field ${msgName}.${fieldName} to binary: ${e.message}`);\n        }\n        throw e;\n    }\n}\nfunction writeTypeOfScalar(type) {\n    switch (type) {\n        case ScalarType.BYTES:\n        case ScalarType.STRING:\n            return WireType.LengthDelimited;\n        case ScalarType.DOUBLE:\n        case ScalarType.FIXED64:\n        case ScalarType.SFIXED64:\n            return WireType.Bit64;\n        case ScalarType.FIXED32:\n        case ScalarType.SFIXED32:\n        case ScalarType.FLOAT:\n            return WireType.Bit32;\n        default:\n            return WireType.Varint;\n    }\n}\n","// Copyright 2021-2025 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { AnySchema } from \"./gen/google/protobuf/any_pb.js\";\nimport { create } from \"../create.js\";\nimport { toBinary } from \"../to-binary.js\";\nimport { fromBinary, mergeFromBinary } from \"../from-binary.js\";\nexport function anyPack(schema, message, into) {\n    let ret = false;\n    if (!into) {\n        into = create(AnySchema);\n        ret = true;\n    }\n    into.value = toBinary(schema, message);\n    into.typeUrl = typeNameToUrl(message.$typeName);\n    return ret ? into : undefined;\n}\nexport function anyIs(any, descOrTypeName) {\n    if (any.typeUrl === \"\") {\n        return false;\n    }\n    const want = typeof descOrTypeName == \"string\"\n        ? descOrTypeName\n        : descOrTypeName.typeName;\n    const got = typeUrlToName(any.typeUrl);\n    return want === got;\n}\nexport function anyUnpack(any, registryOrMessageDesc) {\n    if (any.typeUrl === \"\") {\n        return undefined;\n    }\n    const desc = registryOrMessageDesc.kind == \"message\"\n        ? registryOrMessageDesc\n        : registryOrMessageDesc.getMessage(typeUrlToName(any.typeUrl));\n    if (!desc || !anyIs(any, desc)) {\n        return undefined;\n    }\n    return fromBinary(desc, any.value);\n}\n/**\n * Same as anyUnpack but unpacks into the target message.\n */\nexport function anyUnpackTo(any, schema, message) {\n    if (!anyIs(any, schema)) {\n        return undefined;\n    }\n    return mergeFromBinary(schema, message, any.value);\n}\nfunction typeNameToUrl(name) {\n    return `type.googleapis.com/${name}`;\n}\nfunction typeUrlToName(url) {\n    const slash = url.lastIndexOf(\"/\");\n    const name = slash >= 0 ? url.substring(slash + 1) : url;\n    if (!name.length) {\n        throw new Error(`invalid type url: ${url}`);\n    }\n    return name;\n}\n","// Copyright 2021-2025 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { fileDesc } from \"../../../../codegenv2/file.js\";\nimport { messageDesc } from \"../../../../codegenv2/message.js\";\nimport { enumDesc } from \"../../../../codegenv2/enum.js\";\n/**\n * Describes the file google/protobuf/struct.proto.\n */\nexport const file_google_protobuf_struct = /*@__PURE__*/ fileDesc(\"Chxnb29nbGUvcHJvdG9idWYvc3RydWN0LnByb3RvEg9nb29nbGUucHJvdG9idWYihAEKBlN0cnVjdBIzCgZmaWVsZHMYASADKAsyIy5nb29nbGUucHJvdG9idWYuU3RydWN0LkZpZWxkc0VudHJ5GkUKC0ZpZWxkc0VudHJ5EgsKA2tleRgBIAEoCRIlCgV2YWx1ZRgCIAEoCzIWLmdvb2dsZS5wcm90b2J1Zi5WYWx1ZToCOAEi6gEKBVZhbHVlEjAKCm51bGxfdmFsdWUYASABKA4yGi5nb29nbGUucHJvdG9idWYuTnVsbFZhbHVlSAASFgoMbnVtYmVyX3ZhbHVlGAIgASgBSAASFgoMc3RyaW5nX3ZhbHVlGAMgASgJSAASFAoKYm9vbF92YWx1ZRgEIAEoCEgAEi8KDHN0cnVjdF92YWx1ZRgFIAEoCzIXLmdvb2dsZS5wcm90b2J1Zi5TdHJ1Y3RIABIwCgpsaXN0X3ZhbHVlGAYgASgLMhouZ29vZ2xlLnByb3RvYnVmLkxpc3RWYWx1ZUgAQgYKBGtpbmQiMwoJTGlzdFZhbHVlEiYKBnZhbHVlcxgBIAMoCzIWLmdvb2dsZS5wcm90b2J1Zi5WYWx1ZSobCglOdWxsVmFsdWUSDgoKTlVMTF9WQUxVRRAAQn8KE2NvbS5nb29nbGUucHJvdG9idWZCC1N0cnVjdFByb3RvUAFaL2dvb2dsZS5nb2xhbmcub3JnL3Byb3RvYnVmL3R5cGVzL2tub3duL3N0cnVjdHBi+AEBogIDR1BCqgIeR29vZ2xlLlByb3RvYnVmLldlbGxLbm93blR5cGVzYgZwcm90bzM\");\n/**\n * Describes the message google.protobuf.Struct.\n * Use `create(StructSchema)` to create a new message.\n */\nexport const StructSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_struct, 0);\n/**\n * Describes the message google.protobuf.Value.\n * Use `create(ValueSchema)` to create a new message.\n */\nexport const ValueSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_struct, 1);\n/**\n * Describes the message google.protobuf.ListValue.\n * Use `create(ListValueSchema)` to create a new message.\n */\nexport const ListValueSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_struct, 2);\n/**\n * `NullValue` is a singleton enumeration to represent the null value for the\n * `Value` type union.\n *\n * The JSON representation for `NullValue` is JSON `null`.\n *\n * @generated from enum google.protobuf.NullValue\n */\nexport var NullValue;\n(function (NullValue) {\n    /**\n     * Null value.\n     *\n     * @generated from enum value: NULL_VALUE = 0;\n     */\n    NullValue[NullValue[\"NULL_VALUE\"] = 0] = \"NULL_VALUE\";\n})(NullValue || (NullValue = {}));\n/**\n * Describes the enum google.protobuf.NullValue.\n */\nexport const NullValueSchema = /*@__PURE__*/ enumDesc(file_google_protobuf_struct, 0);\n","// Copyright 2021-2025 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { fileDesc } from \"../../../../codegenv2/file.js\";\nimport { messageDesc } from \"../../../../codegenv2/message.js\";\n/**\n * Describes the file google/protobuf/wrappers.proto.\n */\nexport const file_google_protobuf_wrappers = /*@__PURE__*/ fileDesc(\"Ch5nb29nbGUvcHJvdG9idWYvd3JhcHBlcnMucHJvdG8SD2dvb2dsZS5wcm90b2J1ZiIcCgtEb3VibGVWYWx1ZRINCgV2YWx1ZRgBIAEoASIbCgpGbG9hdFZhbHVlEg0KBXZhbHVlGAEgASgCIhsKCkludDY0VmFsdWUSDQoFdmFsdWUYASABKAMiHAoLVUludDY0VmFsdWUSDQoFdmFsdWUYASABKAQiGwoKSW50MzJWYWx1ZRINCgV2YWx1ZRgBIAEoBSIcCgtVSW50MzJWYWx1ZRINCgV2YWx1ZRgBIAEoDSIaCglCb29sVmFsdWUSDQoFdmFsdWUYASABKAgiHAoLU3RyaW5nVmFsdWUSDQoFdmFsdWUYASABKAkiGwoKQnl0ZXNWYWx1ZRINCgV2YWx1ZRgBIAEoDEKDAQoTY29tLmdvb2dsZS5wcm90b2J1ZkINV3JhcHBlcnNQcm90b1ABWjFnb29nbGUuZ29sYW5nLm9yZy9wcm90b2J1Zi90eXBlcy9rbm93bi93cmFwcGVyc3Bi+AEBogIDR1BCqgIeR29vZ2xlLlByb3RvYnVmLldlbGxLbm93blR5cGVzYgZwcm90bzM\");\n/**\n * Describes the message google.protobuf.DoubleValue.\n * Use `create(DoubleValueSchema)` to create a new message.\n */\nexport const DoubleValueSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_wrappers, 0);\n/**\n * Describes the message google.protobuf.FloatValue.\n * Use `create(FloatValueSchema)` to create a new message.\n */\nexport const FloatValueSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_wrappers, 1);\n/**\n * Describes the message google.protobuf.Int64Value.\n * Use `create(Int64ValueSchema)` to create a new message.\n */\nexport const Int64ValueSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_wrappers, 2);\n/**\n * Describes the message google.protobuf.UInt64Value.\n * Use `create(UInt64ValueSchema)` to create a new message.\n */\nexport const UInt64ValueSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_wrappers, 3);\n/**\n * Describes the message google.protobuf.Int32Value.\n * Use `create(Int32ValueSchema)` to create a new message.\n */\nexport const Int32ValueSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_wrappers, 4);\n/**\n * Describes the message google.protobuf.UInt32Value.\n * Use `create(UInt32ValueSchema)` to create a new message.\n */\nexport const UInt32ValueSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_wrappers, 5);\n/**\n * Describes the message google.protobuf.BoolValue.\n * Use `create(BoolValueSchema)` to create a new message.\n */\nexport const BoolValueSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_wrappers, 6);\n/**\n * Describes the message google.protobuf.StringValue.\n * Use `create(StringValueSchema)` to create a new message.\n */\nexport const StringValueSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_wrappers, 7);\n/**\n * Describes the message google.protobuf.BytesValue.\n * Use `create(BytesValueSchema)` to create a new message.\n */\nexport const BytesValueSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_wrappers, 8);\n","// Copyright 2021-2025 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { create } from \"./create.js\";\nimport { readField } from \"./from-binary.js\";\nimport { reflect } from \"./reflect/reflect.js\";\nimport { scalarZeroValue } from \"./reflect/scalar.js\";\nimport { writeField } from \"./to-binary.js\";\nimport { BinaryReader, BinaryWriter } from \"./wire/binary-encoding.js\";\nimport { isWrapperDesc } from \"./wkt/wrappers.js\";\n/**\n * Retrieve an extension value from a message.\n *\n * The function never returns undefined. Use hasExtension() to check whether an\n * extension is set. If the extension is not set, this function returns the\n * default value (if one was specified in the protobuf source), or the zero value\n * (for example `0` for numeric types, `[]` for repeated extension fields, and\n * an empty message instance for message fields).\n *\n * Extensions are stored as unknown fields on a message. To mutate an extension\n * value, make sure to store the new value with setExtension() after mutating.\n *\n * If the extension does not extend the given message, an error is raised.\n */\nexport function getExtension(message, extension) {\n    assertExtendee(extension, message);\n    const ufs = filterUnknownFields(message.$unknown, extension);\n    const [container, field, get] = createExtensionContainer(extension);\n    for (const uf of ufs) {\n        readField(container, new BinaryReader(uf.data), field, uf.wireType, {\n            readUnknownFields: true,\n        });\n    }\n    return get();\n}\n/**\n * Set an extension value on a message. If the message already has a value for\n * this extension, the value is replaced.\n *\n * If the extension does not extend the given message, an error is raised.\n */\nexport function setExtension(message, extension, value) {\n    var _a;\n    assertExtendee(extension, message);\n    const ufs = ((_a = message.$unknown) !== null && _a !== void 0 ? _a : []).filter((uf) => uf.no !== extension.number);\n    const [container, field] = createExtensionContainer(extension, value);\n    const writer = new BinaryWriter();\n    writeField(writer, { writeUnknownFields: true }, container, field);\n    const reader = new BinaryReader(writer.finish());\n    while (reader.pos < reader.len) {\n        const [no, wireType] = reader.tag();\n        const data = reader.skip(wireType, no);\n        ufs.push({ no, wireType, data });\n    }\n    message.$unknown = ufs;\n}\n/**\n * Remove an extension value from a message.\n *\n * If the extension does not extend the given message, an error is raised.\n */\nexport function clearExtension(message, extension) {\n    assertExtendee(extension, message);\n    if (message.$unknown === undefined) {\n        return;\n    }\n    message.$unknown = message.$unknown.filter((uf) => uf.no !== extension.number);\n}\n/**\n * Check whether an extension is set on a message.\n */\nexport function hasExtension(message, extension) {\n    var _a;\n    return (extension.extendee.typeName === message.$typeName &&\n        !!((_a = message.$unknown) === null || _a === void 0 ? void 0 : _a.find((uf) => uf.no === extension.number)));\n}\n/**\n * Check whether an option is set on a descriptor.\n *\n * Options are extensions to the `google.protobuf.*Options` messages defined in\n * google/protobuf/descriptor.proto. This function gets the option message from\n * the descriptor, and calls hasExtension().\n */\nexport function hasOption(element, option) {\n    const message = element.proto.options;\n    if (!message) {\n        return false;\n    }\n    return hasExtension(message, option);\n}\n/**\n * Retrieve an option value from a descriptor.\n *\n * Options are extensions to the `google.protobuf.*Options` messages defined in\n * google/protobuf/descriptor.proto. This function gets the option message from\n * the descriptor, and calls getExtension(). Same as getExtension(), this\n * function never returns undefined.\n */\nexport function getOption(element, option) {\n    const message = element.proto.options;\n    if (!message) {\n        const [, , get] = createExtensionContainer(option);\n        return get();\n    }\n    return getExtension(message, option);\n}\nfunction filterUnknownFields(unknownFields, extension) {\n    if (unknownFields === undefined)\n        return [];\n    if (extension.fieldKind === \"enum\" || extension.fieldKind === \"scalar\") {\n        // singular scalar fields do not merge, we pick the last\n        for (let i = unknownFields.length - 1; i >= 0; --i) {\n            if (unknownFields[i].no == extension.number) {\n                return [unknownFields[i]];\n            }\n        }\n        return [];\n    }\n    return unknownFields.filter((uf) => uf.no === extension.number);\n}\n/**\n * @private\n */\nexport function createExtensionContainer(extension, value) {\n    const localName = extension.typeName;\n    const field = Object.assign(Object.assign({}, extension), { kind: \"field\", parent: extension.extendee, localName });\n    const desc = Object.assign(Object.assign({}, extension.extendee), { fields: [field], members: [field], oneofs: [] });\n    const container = create(desc, value !== undefined ? { [localName]: value } : undefined);\n    return [\n        reflect(desc, container),\n        field,\n        () => {\n            const value = container[localName];\n            if (value === undefined) {\n                // biome-ignore lint/style/noNonNullAssertion: Only message fields are undefined, rest will have a zero value.\n                const desc = extension.message;\n                if (isWrapperDesc(desc)) {\n                    return scalarZeroValue(desc.fields[0].scalar, desc.fields[0].longAsString);\n                }\n                return create(desc);\n            }\n            return value;\n        },\n    ];\n}\nfunction assertExtendee(extension, message) {\n    if (extension.extendee.typeName != message.$typeName) {\n        throw new Error(`extension ${extension.typeName} can only be applied to message ${extension.extendee.typeName}`);\n    }\n}\n","// Copyright 2021-2025 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { ScalarType, } from \"./descriptors.js\";\nimport { protoCamelCase } from \"./reflect/names.js\";\nimport { reflect } from \"./reflect/reflect.js\";\nimport { anyUnpack } from \"./wkt/index.js\";\nimport { isWrapperDesc } from \"./wkt/wrappers.js\";\nimport { base64Encode } from \"./wire/index.js\";\nimport { createExtensionContainer, getExtension } from \"./extensions.js\";\nimport { checkField, formatVal } from \"./reflect/reflect-check.js\";\n// bootstrap-inject google.protobuf.FeatureSet.FieldPresence.LEGACY_REQUIRED: const $name: FeatureSet_FieldPresence.$localName = $number;\nconst LEGACY_REQUIRED = 3;\n// bootstrap-inject google.protobuf.FeatureSet.FieldPresence.IMPLICIT: const $name: FeatureSet_FieldPresence.$localName = $number;\nconst IMPLICIT = 2;\n// Default options for serializing to JSON.\nconst jsonWriteDefaults = {\n    alwaysEmitImplicit: false,\n    enumAsInteger: false,\n    useProtoFieldName: false,\n};\nfunction makeWriteOptions(options) {\n    return options ? Object.assign(Object.assign({}, jsonWriteDefaults), options) : jsonWriteDefaults;\n}\n/**\n * Serialize the message to a JSON value, a JavaScript value that can be\n * passed to JSON.stringify().\n */\nexport function toJson(schema, message, options) {\n    return reflectToJson(reflect(schema, message), makeWriteOptions(options));\n}\n/**\n * Serialize the message to a JSON string.\n */\nexport function toJsonString(schema, message, options) {\n    var _a;\n    const jsonValue = toJson(schema, message, options);\n    return JSON.stringify(jsonValue, null, (_a = options === null || options === void 0 ? void 0 : options.prettySpaces) !== null && _a !== void 0 ? _a : 0);\n}\n/**\n * Serialize a single enum value to JSON.\n */\nexport function enumToJson(descEnum, value) {\n    var _a;\n    if (descEnum.typeName == \"google.protobuf.NullValue\") {\n        return null;\n    }\n    const name = (_a = descEnum.value[value]) === null || _a === void 0 ? void 0 : _a.name;\n    if (name === undefined) {\n        throw new Error(`${value} is not a value in ${descEnum}`);\n    }\n    return name;\n}\nfunction reflectToJson(msg, opts) {\n    var _a;\n    const wktJson = tryWktToJson(msg, opts);\n    if (wktJson !== undefined)\n        return wktJson;\n    const json = {};\n    for (const f of msg.sortedFields) {\n        if (!msg.isSet(f)) {\n            if (f.presence == LEGACY_REQUIRED) {\n                throw new Error(`cannot encode ${f} to JSON: required field not set`);\n            }\n            if (!opts.alwaysEmitImplicit || f.presence !== IMPLICIT) {\n                // Fields with implicit presence omit zero values (e.g. empty string) by default\n                continue;\n            }\n        }\n        const jsonValue = fieldToJson(f, msg.get(f), opts);\n        if (jsonValue !== undefined) {\n            json[jsonName(f, opts)] = jsonValue;\n        }\n    }\n    if (opts.registry) {\n        const tagSeen = new Set();\n        for (const { no } of (_a = msg.getUnknown()) !== null && _a !== void 0 ? _a : []) {\n            // Same tag can appear multiple times, so we\n            // keep track and skip identical ones.\n            if (!tagSeen.has(no)) {\n                tagSeen.add(no);\n                const extension = opts.registry.getExtensionFor(msg.desc, no);\n                if (!extension) {\n                    continue;\n                }\n                const value = getExtension(msg.message, extension);\n                const [container, field] = createExtensionContainer(extension, value);\n                const jsonValue = fieldToJson(field, container.get(field), opts);\n                if (jsonValue !== undefined) {\n                    json[extension.jsonName] = jsonValue;\n                }\n            }\n        }\n    }\n    return json;\n}\nfunction fieldToJson(f, val, opts) {\n    switch (f.fieldKind) {\n        case \"scalar\":\n            return scalarToJson(f, val);\n        case \"message\":\n            return reflectToJson(val, opts);\n        case \"enum\":\n            return enumToJsonInternal(f.enum, val, opts.enumAsInteger);\n        case \"list\":\n            return listToJson(val, opts);\n        case \"map\":\n            return mapToJson(val, opts);\n    }\n}\nfunction mapToJson(map, opts) {\n    const f = map.field();\n    const jsonObj = {};\n    switch (f.mapKind) {\n        case \"scalar\":\n            for (const [entryKey, entryValue] of map) {\n                jsonObj[entryKey] = scalarToJson(f, entryValue);\n            }\n            break;\n        case \"message\":\n            for (const [entryKey, entryValue] of map) {\n                jsonObj[entryKey] = reflectToJson(entryValue, opts);\n            }\n            break;\n        case \"enum\":\n            for (const [entryKey, entryValue] of map) {\n                jsonObj[entryKey] = enumToJsonInternal(f.enum, entryValue, opts.enumAsInteger);\n            }\n            break;\n    }\n    return opts.alwaysEmitImplicit || map.size > 0 ? jsonObj : undefined;\n}\nfunction listToJson(list, opts) {\n    const f = list.field();\n    const jsonArr = [];\n    switch (f.listKind) {\n        case \"scalar\":\n            for (const item of list) {\n                jsonArr.push(scalarToJson(f, item));\n            }\n            break;\n        case \"enum\":\n            for (const item of list) {\n                jsonArr.push(enumToJsonInternal(f.enum, item, opts.enumAsInteger));\n            }\n            break;\n        case \"message\":\n            for (const item of list) {\n                jsonArr.push(reflectToJson(item, opts));\n            }\n            break;\n    }\n    return opts.alwaysEmitImplicit || jsonArr.length > 0 ? jsonArr : undefined;\n}\nfunction enumToJsonInternal(desc, value, enumAsInteger) {\n    var _a;\n    if (typeof value != \"number\") {\n        throw new Error(`cannot encode ${desc} to JSON: expected number, got ${formatVal(value)}`);\n    }\n    if (desc.typeName == \"google.protobuf.NullValue\") {\n        return null;\n    }\n    if (enumAsInteger) {\n        return value;\n    }\n    const val = desc.value[value];\n    return (_a = val === null || val === void 0 ? void 0 : val.name) !== null && _a !== void 0 ? _a : value; // if we don't know the enum value, just return the number\n}\nfunction scalarToJson(field, value) {\n    var _a, _b, _c, _d, _e, _f;\n    switch (field.scalar) {\n        // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted.\n        case ScalarType.INT32:\n        case ScalarType.SFIXED32:\n        case ScalarType.SINT32:\n        case ScalarType.FIXED32:\n        case ScalarType.UINT32:\n            if (typeof value != \"number\") {\n                throw new Error(`cannot encode ${field} to JSON: ${(_a = checkField(field, value)) === null || _a === void 0 ? void 0 : _a.message}`);\n            }\n            return value;\n        // float, double: JSON value will be a number or one of the special string values \"NaN\", \"Infinity\", and \"-Infinity\".\n        // Either numbers or strings are accepted. Exponent notation is also accepted.\n        case ScalarType.FLOAT:\n        case ScalarType.DOUBLE: // eslint-disable-line no-fallthrough\n            if (typeof value != \"number\") {\n                throw new Error(`cannot encode ${field} to JSON: ${(_b = checkField(field, value)) === null || _b === void 0 ? void 0 : _b.message}`);\n            }\n            if (Number.isNaN(value))\n                return \"NaN\";\n            if (value === Number.POSITIVE_INFINITY)\n                return \"Infinity\";\n            if (value === Number.NEGATIVE_INFINITY)\n                return \"-Infinity\";\n            return value;\n        // string:\n        case ScalarType.STRING:\n            if (typeof value != \"string\") {\n                throw new Error(`cannot encode ${field} to JSON: ${(_c = checkField(field, value)) === null || _c === void 0 ? void 0 : _c.message}`);\n            }\n            return value;\n        // bool:\n        case ScalarType.BOOL:\n            if (typeof value != \"boolean\") {\n                throw new Error(`cannot encode ${field} to JSON: ${(_d = checkField(field, value)) === null || _d === void 0 ? void 0 : _d.message}`);\n            }\n            return value;\n        // JSON value will be a decimal string. Either numbers or strings are accepted.\n        case ScalarType.UINT64:\n        case ScalarType.FIXED64:\n        case ScalarType.INT64:\n        case ScalarType.SFIXED64:\n        case ScalarType.SINT64:\n            if (typeof value != \"bigint\" && typeof value != \"string\") {\n                throw new Error(`cannot encode ${field} to JSON: ${(_e = checkField(field, value)) === null || _e === void 0 ? void 0 : _e.message}`);\n            }\n            return value.toString();\n        // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings.\n        // Either standard or URL-safe base64 encoding with/without paddings are accepted.\n        case ScalarType.BYTES:\n            if (value instanceof Uint8Array) {\n                return base64Encode(value);\n            }\n            throw new Error(`cannot encode ${field} to JSON: ${(_f = checkField(field, value)) === null || _f === void 0 ? void 0 : _f.message}`);\n    }\n}\nfunction jsonName(f, opts) {\n    return opts.useProtoFieldName ? f.name : f.jsonName;\n}\n// returns a json value if wkt, otherwise returns undefined.\nfunction tryWktToJson(msg, opts) {\n    if (!msg.desc.typeName.startsWith(\"google.protobuf.\")) {\n        return undefined;\n    }\n    switch (msg.desc.typeName) {\n        case \"google.protobuf.Any\":\n            return anyToJson(msg.message, opts);\n        case \"google.protobuf.Timestamp\":\n            return timestampToJson(msg.message);\n        case \"google.protobuf.Duration\":\n            return durationToJson(msg.message);\n        case \"google.protobuf.FieldMask\":\n            return fieldMaskToJson(msg.message);\n        case \"google.protobuf.Struct\":\n            return structToJson(msg.message);\n        case \"google.protobuf.Value\":\n            return valueToJson(msg.message);\n        case \"google.protobuf.ListValue\":\n            return listValueToJson(msg.message);\n        default:\n            if (isWrapperDesc(msg.desc)) {\n                const valueField = msg.desc.fields[0];\n                return scalarToJson(valueField, msg.get(valueField));\n            }\n            return undefined;\n    }\n}\nfunction anyToJson(val, opts) {\n    if (val.typeUrl === \"\") {\n        return {};\n    }\n    const { registry } = opts;\n    let message;\n    let desc;\n    if (registry) {\n        message = anyUnpack(val, registry);\n        if (message) {\n            desc = registry.getMessage(message.$typeName);\n        }\n    }\n    if (!desc || !message) {\n        throw new Error(`cannot encode message ${val.$typeName} to JSON: \"${val.typeUrl}\" is not in the type registry`);\n    }\n    let json = reflectToJson(reflect(desc, message), opts);\n    if (desc.typeName.startsWith(\"google.protobuf.\") ||\n        json === null ||\n        Array.isArray(json) ||\n        typeof json !== \"object\") {\n        json = { value: json };\n    }\n    json[\"@type\"] = val.typeUrl;\n    return json;\n}\nfunction durationToJson(val) {\n    const seconds = Number(val.seconds);\n    const nanos = val.nanos;\n    if (seconds > 315576000000 || seconds < -315576000000) {\n        throw new Error(`cannot encode message ${val.$typeName} to JSON: value out of range`);\n    }\n    if ((seconds > 0 && nanos < 0) || (seconds < 0 && nanos > 0)) {\n        throw new Error(`cannot encode message ${val.$typeName} to JSON: nanos sign must match seconds sign`);\n    }\n    let text = val.seconds.toString();\n    if (nanos !== 0) {\n        let nanosStr = Math.abs(nanos).toString();\n        nanosStr = \"0\".repeat(9 - nanosStr.length) + nanosStr;\n        if (nanosStr.substring(3) === \"000000\") {\n            nanosStr = nanosStr.substring(0, 3);\n        }\n        else if (nanosStr.substring(6) === \"000\") {\n            nanosStr = nanosStr.substring(0, 6);\n        }\n        text += \".\" + nanosStr;\n        if (nanos < 0 && seconds == 0) {\n            text = \"-\" + text;\n        }\n    }\n    return text + \"s\";\n}\nfunction fieldMaskToJson(val) {\n    return val.paths\n        .map((p) => {\n        if (p.match(/_[0-9]?_/g) || p.match(/[A-Z]/g)) {\n            throw new Error(`cannot encode message ${val.$typeName} to JSON: lowerCamelCase of path name \"` +\n                p +\n                '\" is irreversible');\n        }\n        return protoCamelCase(p);\n    })\n        .join(\",\");\n}\nfunction structToJson(val) {\n    const json = {};\n    for (const [k, v] of Object.entries(val.fields)) {\n        json[k] = valueToJson(v);\n    }\n    return json;\n}\nfunction valueToJson(val) {\n    switch (val.kind.case) {\n        case \"nullValue\":\n            return null;\n        case \"numberValue\":\n            if (!Number.isFinite(val.kind.value)) {\n                throw new Error(`${val.$typeName} cannot be NaN or Infinity`);\n            }\n            return val.kind.value;\n        case \"boolValue\":\n            return val.kind.value;\n        case \"stringValue\":\n            return val.kind.value;\n        case \"structValue\":\n            return structToJson(val.kind.value);\n        case \"listValue\":\n            return listValueToJson(val.kind.value);\n        default:\n            throw new Error(`${val.$typeName} must have a value`);\n    }\n}\nfunction listValueToJson(val) {\n    return val.values.map(valueToJson);\n}\nfunction timestampToJson(val) {\n    const ms = Number(val.seconds) * 1000;\n    if (ms < Date.parse(\"0001-01-01T00:00:00Z\") ||\n        ms > Date.parse(\"9999-12-31T23:59:59Z\")) {\n        throw new Error(`cannot encode message ${val.$typeName} to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive`);\n    }\n    if (val.nanos < 0) {\n        throw new Error(`cannot encode message ${val.$typeName} to JSON: nanos must not be negative`);\n    }\n    if (val.nanos > 999999999) {\n        throw new Error(`cannot encode message ${val.$typeName} to JSON: nanos must not be greater than 99999999`);\n    }\n    let z = \"Z\";\n    if (val.nanos > 0) {\n        const nanosStr = (val.nanos + 1000000000).toString().substring(1);\n        if (nanosStr.substring(3) === \"000000\") {\n            z = \".\" + nanosStr.substring(0, 3) + \"Z\";\n        }\n        else if (nanosStr.substring(6) === \"000\") {\n            z = \".\" + nanosStr.substring(0, 6) + \"Z\";\n        }\n        else {\n            z = \".\" + nanosStr + \"Z\";\n        }\n    }\n    return new Date(ms).toISOString().replace(\".000Z\", z);\n}\n","// Copyright 2021-2025 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { ScalarType, } from \"./descriptors.js\";\nimport { protoInt64 } from \"./proto-int64.js\";\nimport { create } from \"./create.js\";\nimport { reflect } from \"./reflect/reflect.js\";\nimport { FieldError, isFieldError } from \"./reflect/error.js\";\nimport { formatVal } from \"./reflect/reflect-check.js\";\nimport { scalarZeroValue } from \"./reflect/scalar.js\";\nimport { base64Decode } from \"./wire/base64-encoding.js\";\nimport { isWrapperDesc, anyPack, ListValueSchema, NullValue, StructSchema, ValueSchema, } from \"./wkt/index.js\";\nimport { createExtensionContainer, setExtension } from \"./extensions.js\";\n// Default options for parsing JSON.\nconst jsonReadDefaults = {\n    ignoreUnknownFields: false,\n};\nfunction makeReadOptions(options) {\n    return options ? Object.assign(Object.assign({}, jsonReadDefaults), options) : jsonReadDefaults;\n}\n/**\n * Parse a message from a JSON string.\n */\nexport function fromJsonString(schema, json, options) {\n    return fromJson(schema, parseJsonString(json, schema.typeName), options);\n}\n/**\n * Parse a message from a JSON string, merging fields.\n *\n * Repeated fields are appended. Map entries are added, overwriting\n * existing keys.\n *\n * If a message field is already present, it will be merged with the\n * new data.\n */\nexport function mergeFromJsonString(schema, target, json, options) {\n    return mergeFromJson(schema, target, parseJsonString(json, schema.typeName), options);\n}\n/**\n * Parse a message from a JSON value.\n */\nexport function fromJson(schema, json, options) {\n    const msg = reflect(schema);\n    try {\n        readMessage(msg, json, makeReadOptions(options));\n    }\n    catch (e) {\n        if (isFieldError(e)) {\n            // @ts-expect-error we use the ES2022 error CTOR option \"cause\" for better stack traces\n            throw new Error(`cannot decode ${e.field()} from JSON: ${e.message}`, {\n                cause: e,\n            });\n        }\n        throw e;\n    }\n    return msg.message;\n}\n/**\n * Parse a message from a JSON value, merging fields.\n *\n * Repeated fields are appended. Map entries are added, overwriting\n * existing keys.\n *\n * If a message field is already present, it will be merged with the\n * new data.\n */\nexport function mergeFromJson(schema, target, json, options) {\n    try {\n        readMessage(reflect(schema, target), json, makeReadOptions(options));\n    }\n    catch (e) {\n        if (isFieldError(e)) {\n            // @ts-expect-error we use the ES2022 error CTOR option \"cause\" for better stack traces\n            throw new Error(`cannot decode ${e.field()} from JSON: ${e.message}`, {\n                cause: e,\n            });\n        }\n        throw e;\n    }\n    return target;\n}\n/**\n * Parses an enum value from JSON.\n */\nexport function enumFromJson(descEnum, json) {\n    const val = readEnum(descEnum, json, false, false);\n    if (val === tokenIgnoredUnknownEnum) {\n        throw new Error(`cannot decode ${descEnum} from JSON: ${formatVal(json)}`);\n    }\n    return val;\n}\n/**\n * Is the given value a JSON enum value?\n */\nexport function isEnumJson(descEnum, value) {\n    return undefined !== descEnum.values.find((v) => v.name === value);\n}\nfunction readMessage(msg, json, opts) {\n    var _a;\n    if (tryWktFromJson(msg, json, opts)) {\n        return;\n    }\n    if (json == null || Array.isArray(json) || typeof json != \"object\") {\n        throw new Error(`cannot decode ${msg.desc} from JSON: ${formatVal(json)}`);\n    }\n    const oneofSeen = new Map();\n    const jsonNames = new Map();\n    for (const field of msg.desc.fields) {\n        jsonNames.set(field.name, field).set(field.jsonName, field);\n    }\n    for (const [jsonKey, jsonValue] of Object.entries(json)) {\n        const field = jsonNames.get(jsonKey);\n        if (field) {\n            if (field.oneof) {\n                if (jsonValue === null && field.fieldKind == \"scalar\") {\n                    // see conformance test Required.Proto3.JsonInput.OneofFieldNull{First,Second}\n                    continue;\n                }\n                const seen = oneofSeen.get(field.oneof);\n                if (seen !== undefined) {\n                    throw new FieldError(field.oneof, `oneof set multiple times by ${seen.name} and ${field.name}`);\n                }\n                oneofSeen.set(field.oneof, field);\n            }\n            readField(msg, field, jsonValue, opts);\n        }\n        else {\n            let extension = undefined;\n            if (jsonKey.startsWith(\"[\") &&\n                jsonKey.endsWith(\"]\") &&\n                // biome-ignore lint/suspicious/noAssignInExpressions: no\n                (extension = (_a = opts.registry) === null || _a === void 0 ? void 0 : _a.getExtension(jsonKey.substring(1, jsonKey.length - 1))) &&\n                extension.extendee.typeName === msg.desc.typeName) {\n                const [container, field, get] = createExtensionContainer(extension);\n                readField(container, field, jsonValue, opts);\n                setExtension(msg.message, extension, get());\n            }\n            if (!extension && !opts.ignoreUnknownFields) {\n                throw new Error(`cannot decode ${msg.desc} from JSON: key \"${jsonKey}\" is unknown`);\n            }\n        }\n    }\n}\nfunction readField(msg, field, json, opts) {\n    switch (field.fieldKind) {\n        case \"scalar\":\n            readScalarField(msg, field, json);\n            break;\n        case \"enum\":\n            readEnumField(msg, field, json, opts);\n            break;\n        case \"message\":\n            readMessageField(msg, field, json, opts);\n            break;\n        case \"list\":\n            readListField(msg.get(field), json, opts);\n            break;\n        case \"map\":\n            readMapField(msg.get(field), json, opts);\n            break;\n    }\n}\nfunction readMapField(map, json, opts) {\n    if (json === null) {\n        return;\n    }\n    const field = map.field();\n    if (typeof json != \"object\" || Array.isArray(json)) {\n        throw new FieldError(field, \"expected object, got \" + formatVal(json));\n    }\n    for (const [jsonMapKey, jsonMapValue] of Object.entries(json)) {\n        if (jsonMapValue === null) {\n            throw new FieldError(field, \"map value must not be null\");\n        }\n        let value;\n        switch (field.mapKind) {\n            case \"message\":\n                const msgValue = reflect(field.message);\n                readMessage(msgValue, jsonMapValue, opts);\n                value = msgValue;\n                break;\n            case \"enum\":\n                value = readEnum(field.enum, jsonMapValue, opts.ignoreUnknownFields, true);\n                if (value === tokenIgnoredUnknownEnum) {\n                    return;\n                }\n                break;\n            case \"scalar\":\n                value = scalarFromJson(field, jsonMapValue, true);\n                break;\n        }\n        const key = mapKeyFromJson(field.mapKey, jsonMapKey);\n        map.set(key, value);\n    }\n}\nfunction readListField(list, json, opts) {\n    if (json === null) {\n        return;\n    }\n    const field = list.field();\n    if (!Array.isArray(json)) {\n        throw new FieldError(field, \"expected Array, got \" + formatVal(json));\n    }\n    for (const jsonItem of json) {\n        if (jsonItem === null) {\n            throw new FieldError(field, \"list item must not be null\");\n        }\n        switch (field.listKind) {\n            case \"message\":\n                const msgValue = reflect(field.message);\n                readMessage(msgValue, jsonItem, opts);\n                list.add(msgValue);\n                break;\n            case \"enum\":\n                const enumValue = readEnum(field.enum, jsonItem, opts.ignoreUnknownFields, true);\n                if (enumValue !== tokenIgnoredUnknownEnum) {\n                    list.add(enumValue);\n                }\n                break;\n            case \"scalar\":\n                list.add(scalarFromJson(field, jsonItem, true));\n                break;\n        }\n    }\n}\nfunction readMessageField(msg, field, json, opts) {\n    if (json === null && field.message.typeName != \"google.protobuf.Value\") {\n        msg.clear(field);\n        return;\n    }\n    const msgValue = msg.isSet(field) ? msg.get(field) : reflect(field.message);\n    readMessage(msgValue, json, opts);\n    msg.set(field, msgValue);\n}\nfunction readEnumField(msg, field, json, opts) {\n    const enumValue = readEnum(field.enum, json, opts.ignoreUnknownFields, false);\n    if (enumValue === tokenNull) {\n        msg.clear(field);\n    }\n    else if (enumValue !== tokenIgnoredUnknownEnum) {\n        msg.set(field, enumValue);\n    }\n}\nfunction readScalarField(msg, field, json) {\n    const scalarValue = scalarFromJson(field, json, false);\n    if (scalarValue === tokenNull) {\n        msg.clear(field);\n    }\n    else {\n        msg.set(field, scalarValue);\n    }\n}\nconst tokenIgnoredUnknownEnum = Symbol();\nfunction readEnum(desc, json, ignoreUnknownFields, nullAsZeroValue) {\n    if (json === null) {\n        if (desc.typeName == \"google.protobuf.NullValue\") {\n            return 0; // google.protobuf.NullValue.NULL_VALUE = 0\n        }\n        return nullAsZeroValue ? desc.values[0].number : tokenNull;\n    }\n    switch (typeof json) {\n        case \"number\":\n            if (Number.isInteger(json)) {\n                return json;\n            }\n            break;\n        case \"string\":\n            const value = desc.values.find((ev) => ev.name === json);\n            if (value !== undefined) {\n                return value.number;\n            }\n            if (ignoreUnknownFields) {\n                return tokenIgnoredUnknownEnum;\n            }\n            break;\n    }\n    throw new Error(`cannot decode ${desc} from JSON: ${formatVal(json)}`);\n}\nconst tokenNull = Symbol();\nfunction scalarFromJson(field, json, nullAsZeroValue) {\n    if (json === null) {\n        if (nullAsZeroValue) {\n            return scalarZeroValue(field.scalar, false);\n        }\n        return tokenNull;\n    }\n    // int64, sfixed64, sint64, fixed64, uint64: Reflect supports string and number.\n    // string, bool: Supported by reflect.\n    switch (field.scalar) {\n        // float, double: JSON value will be a number or one of the special string values \"NaN\", \"Infinity\", and \"-Infinity\".\n        // Either numbers or strings are accepted. Exponent notation is also accepted.\n        case ScalarType.DOUBLE:\n        case ScalarType.FLOAT:\n            if (json === \"NaN\")\n                return NaN;\n            if (json === \"Infinity\")\n                return Number.POSITIVE_INFINITY;\n            if (json === \"-Infinity\")\n                return Number.NEGATIVE_INFINITY;\n            if (typeof json == \"number\") {\n                if (Number.isNaN(json)) {\n                    // NaN must be encoded with string constants\n                    throw new FieldError(field, \"unexpected NaN number\");\n                }\n                if (!Number.isFinite(json)) {\n                    // Infinity must be encoded with string constants\n                    throw new FieldError(field, \"unexpected infinite number\");\n                }\n                break;\n            }\n            if (typeof json == \"string\") {\n                if (json === \"\") {\n                    // empty string is not a number\n                    break;\n                }\n                if (json.trim().length !== json.length) {\n                    // extra whitespace\n                    break;\n                }\n                const float = Number(json);\n                if (!Number.isFinite(float)) {\n                    // Infinity and NaN must be encoded with string constants\n                    break;\n                }\n                return float;\n            }\n            break;\n        // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted.\n        case ScalarType.INT32:\n        case ScalarType.FIXED32:\n        case ScalarType.SFIXED32:\n        case ScalarType.SINT32:\n        case ScalarType.UINT32:\n            return int32FromJson(json);\n        // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings.\n        // Either standard or URL-safe base64 encoding with/without paddings are accepted.\n        case ScalarType.BYTES:\n            if (typeof json == \"string\") {\n                if (json === \"\") {\n                    return new Uint8Array(0);\n                }\n                try {\n                    return base64Decode(json);\n                }\n                catch (e) {\n                    const message = e instanceof Error ? e.message : String(e);\n                    throw new FieldError(field, message);\n                }\n            }\n            break;\n    }\n    return json;\n}\n/**\n * Try to parse a JSON value to a map key for the reflect API.\n *\n * Returns the input if the JSON value cannot be converted.\n */\nfunction mapKeyFromJson(type, json) {\n    switch (type) {\n        case ScalarType.BOOL:\n            switch (json) {\n                case \"true\":\n                    return true;\n                case \"false\":\n                    return false;\n            }\n            return json;\n        case ScalarType.INT32:\n        case ScalarType.FIXED32:\n        case ScalarType.UINT32:\n        case ScalarType.SFIXED32:\n        case ScalarType.SINT32:\n            return int32FromJson(json);\n        default:\n            return json;\n    }\n}\n/**\n * Try to parse a JSON value to a 32-bit integer for the reflect API.\n *\n * Returns the input if the JSON value cannot be converted.\n */\nfunction int32FromJson(json) {\n    if (typeof json == \"string\") {\n        if (json === \"\") {\n            // empty string is not a number\n            return json;\n        }\n        if (json.trim().length !== json.length) {\n            // extra whitespace\n            return json;\n        }\n        const num = Number(json);\n        if (Number.isNaN(num)) {\n            // not a number\n            return json;\n        }\n        return num;\n    }\n    return json;\n}\nfunction parseJsonString(jsonString, typeName) {\n    try {\n        return JSON.parse(jsonString);\n    }\n    catch (e) {\n        const message = e instanceof Error ? e.message : String(e);\n        throw new Error(`cannot decode message ${typeName} from JSON: ${message}`, \n        // @ts-expect-error we use the ES2022 error CTOR option \"cause\" for better stack traces\n        { cause: e });\n    }\n}\nfunction tryWktFromJson(msg, jsonValue, opts) {\n    if (!msg.desc.typeName.startsWith(\"google.protobuf.\")) {\n        return false;\n    }\n    switch (msg.desc.typeName) {\n        case \"google.protobuf.Any\":\n            anyFromJson(msg.message, jsonValue, opts);\n            return true;\n        case \"google.protobuf.Timestamp\":\n            timestampFromJson(msg.message, jsonValue);\n            return true;\n        case \"google.protobuf.Duration\":\n            durationFromJson(msg.message, jsonValue);\n            return true;\n        case \"google.protobuf.FieldMask\":\n            fieldMaskFromJson(msg.message, jsonValue);\n            return true;\n        case \"google.protobuf.Struct\":\n            structFromJson(msg.message, jsonValue);\n            return true;\n        case \"google.protobuf.Value\":\n            valueFromJson(msg.message, jsonValue);\n            return true;\n        case \"google.protobuf.ListValue\":\n            listValueFromJson(msg.message, jsonValue);\n            return true;\n        default:\n            if (isWrapperDesc(msg.desc)) {\n                const valueField = msg.desc.fields[0];\n                if (jsonValue === null) {\n                    msg.clear(valueField);\n                }\n                else {\n                    msg.set(valueField, scalarFromJson(valueField, jsonValue, true));\n                }\n                return true;\n            }\n            return false;\n    }\n}\nfunction anyFromJson(any, json, opts) {\n    var _a;\n    if (json === null || Array.isArray(json) || typeof json != \"object\") {\n        throw new Error(`cannot decode message ${any.$typeName} from JSON: expected object but got ${formatVal(json)}`);\n    }\n    if (Object.keys(json).length == 0) {\n        return;\n    }\n    const typeUrl = json[\"@type\"];\n    if (typeof typeUrl != \"string\" || typeUrl == \"\") {\n        throw new Error(`cannot decode message ${any.$typeName} from JSON: \"@type\" is empty`);\n    }\n    const typeName = typeUrl.includes(\"/\")\n        ? typeUrl.substring(typeUrl.lastIndexOf(\"/\") + 1)\n        : typeUrl;\n    if (!typeName.length) {\n        throw new Error(`cannot decode message ${any.$typeName} from JSON: \"@type\" is invalid`);\n    }\n    const desc = (_a = opts.registry) === null || _a === void 0 ? void 0 : _a.getMessage(typeName);\n    if (!desc) {\n        throw new Error(`cannot decode message ${any.$typeName} from JSON: ${typeUrl} is not in the type registry`);\n    }\n    const msg = reflect(desc);\n    if (typeName.startsWith(\"google.protobuf.\") &&\n        Object.prototype.hasOwnProperty.call(json, \"value\")) {\n        const value = json.value;\n        readMessage(msg, value, opts);\n    }\n    else {\n        const copy = Object.assign({}, json);\n        // biome-ignore lint/performance/noDelete: <explanation>\n        delete copy[\"@type\"];\n        readMessage(msg, copy, opts);\n    }\n    anyPack(msg.desc, msg.message, any);\n}\nfunction timestampFromJson(timestamp, json) {\n    if (typeof json !== \"string\") {\n        throw new Error(`cannot decode message ${timestamp.$typeName} from JSON: ${formatVal(json)}`);\n    }\n    const matches = json.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\\.([0-9]{1,9}))?(?:Z|([+-][0-9][0-9]:[0-9][0-9]))$/);\n    if (!matches) {\n        throw new Error(`cannot decode message ${timestamp.$typeName} from JSON: invalid RFC 3339 string`);\n    }\n    const ms = Date.parse(\n    // biome-ignore format: want this to read well\n    matches[1] + \"-\" + matches[2] + \"-\" + matches[3] + \"T\" + matches[4] + \":\" + matches[5] + \":\" + matches[6] + (matches[8] ? matches[8] : \"Z\"));\n    if (Number.isNaN(ms)) {\n        throw new Error(`cannot decode message ${timestamp.$typeName} from JSON: invalid RFC 3339 string`);\n    }\n    if (ms < Date.parse(\"0001-01-01T00:00:00Z\") ||\n        ms > Date.parse(\"9999-12-31T23:59:59Z\")) {\n        throw new Error(`cannot decode message ${timestamp.$typeName} from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive`);\n    }\n    timestamp.seconds = protoInt64.parse(ms / 1000);\n    timestamp.nanos = 0;\n    if (matches[7]) {\n        timestamp.nanos =\n            parseInt(\"1\" + matches[7] + \"0\".repeat(9 - matches[7].length)) -\n                1000000000;\n    }\n}\nfunction durationFromJson(duration, json) {\n    if (typeof json !== \"string\") {\n        throw new Error(`cannot decode message ${duration.$typeName} from JSON: ${formatVal(json)}`);\n    }\n    const match = json.match(/^(-?[0-9]+)(?:\\.([0-9]+))?s/);\n    if (match === null) {\n        throw new Error(`cannot decode message ${duration.$typeName} from JSON: ${formatVal(json)}`);\n    }\n    const longSeconds = Number(match[1]);\n    if (longSeconds > 315576000000 || longSeconds < -315576000000) {\n        throw new Error(`cannot decode message ${duration.$typeName} from JSON: ${formatVal(json)}`);\n    }\n    duration.seconds = protoInt64.parse(longSeconds);\n    if (typeof match[2] !== \"string\") {\n        return;\n    }\n    const nanosStr = match[2] + \"0\".repeat(9 - match[2].length);\n    duration.nanos = parseInt(nanosStr);\n    if (longSeconds < 0 || Object.is(longSeconds, -0)) {\n        duration.nanos = -duration.nanos;\n    }\n}\nfunction fieldMaskFromJson(fieldMask, json) {\n    if (typeof json !== \"string\") {\n        throw new Error(`cannot decode message ${fieldMask.$typeName} from JSON: ${formatVal(json)}`);\n    }\n    if (json === \"\") {\n        return;\n    }\n    function camelToSnake(str) {\n        if (str.includes(\"_\")) {\n            throw new Error(`cannot decode message ${fieldMask.$typeName} from JSON: path names must be lowerCamelCase`);\n        }\n        const sc = str.replace(/[A-Z]/g, (letter) => \"_\" + letter.toLowerCase());\n        return sc[0] === \"_\" ? sc.substring(1) : sc;\n    }\n    fieldMask.paths = json.split(\",\").map(camelToSnake);\n}\nfunction structFromJson(struct, json) {\n    if (typeof json != \"object\" || json == null || Array.isArray(json)) {\n        throw new Error(`cannot decode message ${struct.$typeName} from JSON ${formatVal(json)}`);\n    }\n    for (const [k, v] of Object.entries(json)) {\n        const parsedV = create(ValueSchema);\n        valueFromJson(parsedV, v);\n        struct.fields[k] = parsedV;\n    }\n}\nfunction valueFromJson(value, json) {\n    switch (typeof json) {\n        case \"number\":\n            value.kind = { case: \"numberValue\", value: json };\n            break;\n        case \"string\":\n            value.kind = { case: \"stringValue\", value: json };\n            break;\n        case \"boolean\":\n            value.kind = { case: \"boolValue\", value: json };\n            break;\n        case \"object\":\n            if (json === null) {\n                value.kind = { case: \"nullValue\", value: NullValue.NULL_VALUE };\n            }\n            else if (Array.isArray(json)) {\n                const listValue = create(ListValueSchema);\n                listValueFromJson(listValue, json);\n                value.kind = { case: \"listValue\", value: listValue };\n            }\n            else {\n                const struct = create(StructSchema);\n                structFromJson(struct, json);\n                value.kind = { case: \"structValue\", value: struct };\n            }\n            break;\n        default:\n            throw new Error(`cannot decode message ${value.$typeName} from JSON ${formatVal(json)}`);\n    }\n    return value;\n}\nfunction listValueFromJson(listValue, json) {\n    if (!Array.isArray(json)) {\n        throw new Error(`cannot decode message ${listValue.$typeName} from JSON ${formatVal(json)}`);\n    }\n    for (const e of json) {\n        const value = create(ValueSchema);\n        valueFromJson(value, e);\n        listValue.values.push(value);\n    }\n}\n","// Copyright 2021-2025 The Connect Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { Code } from \"../code.js\";\n/**\n * codeToString returns the string representation of a Code.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function codeToString(value) {\n    const name = Code[value];\n    if (typeof name != \"string\") {\n        return value.toString();\n    }\n    return (name[0].toLowerCase() +\n        name.substring(1).replace(/[A-Z]/g, (c) => \"_\" + c.toLowerCase()));\n}\nlet stringToCode;\n/**\n * codeFromString parses the string representation of a Code in snake_case.\n * For example, the string \"permission_denied\" parses into Code.PermissionDenied.\n *\n * If the given string cannot be parsed, the function returns undefined.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function codeFromString(value) {\n    if (!stringToCode) {\n        stringToCode = {};\n        for (const value of Object.values(Code)) {\n            if (typeof value == \"string\") {\n                continue;\n            }\n            stringToCode[codeToString(value)] = value;\n        }\n    }\n    return stringToCode[value];\n}\n","// Copyright 2021-2025 The Connect Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { Code } from \"./code.js\";\nimport { create, fromBinary } from \"@bufbuild/protobuf\";\nimport { codeToString } from \"./protocol-connect/code-string.js\";\n/**\n * ConnectError captures four pieces of information: a Code, an error\n * message, an optional cause of the error, and an optional collection of\n * arbitrary Protobuf messages called  \"details\".\n *\n * Because developer tools typically show just the error message, we prefix\n * it with the status code, so that the most important information is always\n * visible immediately.\n *\n * Error details are wrapped with google.protobuf.Any on the wire, so that\n * a server or middleware can attach arbitrary data to an error. Use the\n * method findDetails() to retrieve the details.\n */\nexport class ConnectError extends Error {\n    /**\n     * Create a new ConnectError.\n     * If no code is provided, code \"unknown\" is used.\n     * Outgoing details are only relevant for the server side - a service may\n     * raise an error with details, and it is up to the protocol implementation\n     * to encode and send the details along with the error.\n     */\n    constructor(message, code = Code.Unknown, metadata, outgoingDetails, cause) {\n        super(createMessage(message, code));\n        this.name = \"ConnectError\";\n        // see https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#example\n        Object.setPrototypeOf(this, new.target.prototype);\n        this.rawMessage = message;\n        this.code = code;\n        this.metadata = new Headers(metadata !== null && metadata !== void 0 ? metadata : {});\n        this.details = outgoingDetails !== null && outgoingDetails !== void 0 ? outgoingDetails : [];\n        this.cause = cause;\n    }\n    /**\n     * Convert any value - typically a caught error into a ConnectError,\n     * following these rules:\n     * - If the value is already a ConnectError, return it as is.\n     * - If the value is an AbortError or TimeoutError from the fetch API, return\n     *   the message of the error with code Canceled.\n     * - For other Errors, return the error message with code Unknown by default.\n     * - For other values, return the values String representation as a message,\n     *   with the code Unknown by default.\n     * The original value will be used for the \"cause\" property for the new\n     * ConnectError.\n     */\n    static from(reason, code = Code.Unknown) {\n        if (reason instanceof ConnectError) {\n            return reason;\n        }\n        if (reason instanceof Error) {\n            if (reason.name == \"AbortError\" || reason.name == \"TimeoutError\") {\n                // Fetch requests can only be canceled with an AbortController,\n                // or with AbortSignal.timeout().\n                return new ConnectError(reason.message, Code.Canceled);\n            }\n            return new ConnectError(reason.message, code, undefined, undefined, reason);\n        }\n        return new ConnectError(String(reason), code, undefined, undefined, reason);\n    }\n    static [Symbol.hasInstance](v) {\n        if (!(v instanceof Error)) {\n            return false;\n        }\n        if (Object.getPrototypeOf(v) === ConnectError.prototype) {\n            return true;\n        }\n        return (v.name === \"ConnectError\" &&\n            \"code\" in v &&\n            typeof v.code === \"number\" &&\n            \"metadata\" in v &&\n            \"details\" in v &&\n            Array.isArray(v.details) &&\n            \"rawMessage\" in v &&\n            typeof v.rawMessage == \"string\" &&\n            \"cause\" in v);\n    }\n    findDetails(typeOrRegistry) {\n        const registry = typeOrRegistry.kind === \"message\"\n            ? {\n                getMessage: (typeName) => typeName === typeOrRegistry.typeName ? typeOrRegistry : undefined,\n            }\n            : typeOrRegistry;\n        const details = [];\n        for (const data of this.details) {\n            if (\"desc\" in data) {\n                if (registry.getMessage(data.desc.typeName)) {\n                    details.push(create(data.desc, data.value));\n                }\n                continue;\n            }\n            const desc = registry.getMessage(data.type);\n            if (desc) {\n                try {\n                    details.push(fromBinary(desc, data.value));\n                }\n                catch (_) {\n                    // We silently give up if we are unable to parse the detail, because\n                    // that appears to be the least worst behavior.\n                    // It is very unlikely that a user surrounds a catch body handling the\n                    // error with another try-catch statement, and we do not want to\n                    // recommend doing so.\n                }\n            }\n        }\n        return details;\n    }\n}\n/**\n * Create an error message, prefixing the given code.\n */\nfunction createMessage(message, code) {\n    return message.length\n        ? `[${codeToString(code)}] ${message}`\n        : `[${codeToString(code)}]`;\n}\n","// Copyright 2021-2025 The Connect Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { fromBinary, toBinary } from \"@bufbuild/protobuf\";\nimport { base64Encode, base64Decode } from \"@bufbuild/protobuf/wire\";\nimport { ConnectError } from \"./connect-error.js\";\nimport { Code } from \"./code.js\";\nexport function encodeBinaryHeader(value, desc) {\n    let bytes;\n    if (desc !== undefined) {\n        bytes = toBinary(desc, value);\n    }\n    else if (typeof value == \"string\") {\n        bytes = new TextEncoder().encode(value);\n    }\n    else {\n        bytes =\n            value instanceof Uint8Array\n                ? value\n                : new Uint8Array(value);\n    }\n    return base64Encode(bytes, \"std_raw\");\n}\nexport function decodeBinaryHeader(value, desc, options) {\n    try {\n        const bytes = base64Decode(value);\n        if (desc) {\n            return fromBinary(desc, bytes, options);\n        }\n        return bytes;\n    }\n    catch (e) {\n        throw ConnectError.from(e, Code.DataLoss);\n    }\n}\n/**\n * Merge two or more Headers objects by appending all fields from\n * all inputs to a new Headers object.\n */\nexport function appendHeaders(...headers) {\n    const h = new Headers();\n    for (const e of headers) {\n        e.forEach((value, key) => {\n            h.append(key, value);\n        });\n    }\n    return h;\n}\n","// Copyright 2021-2025 The Connect Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n/**\n * Create any client for the given service.\n *\n * The given createMethod function is called for each method definition\n * of the service. The function it returns is added to the client object\n * as a method.\n */\nexport function makeAnyClient(service, createMethod) {\n    const client = {};\n    for (const desc of service.methods) {\n        const method = createMethod(desc);\n        if (method != null) {\n            client[desc.localName] = method;\n        }\n    }\n    return client;\n}\n","// Copyright 2021-2025 The Connect Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { ConnectError } from \"../connect-error.js\";\nimport { Code } from \"../code.js\";\n/**\n * compressedFlag indicates that the data in a EnvelopedMessage is\n * compressed. It has the same meaning in the gRPC-Web, gRPC-HTTP2,\n * and Connect protocols.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport const compressedFlag = 0b00000001;\n/**\n * Validates the request encoding and determines the accepted response encoding.\n *\n * Returns the request and response compression to use. If the client requested\n * an encoding that is not available, the returned object contains an error that\n * must be used for the response.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function compressionNegotiate(available, requested, // e.g. the value of the Grpc-Encoding header\naccepted, // e.g. the value of the Grpc-Accept-Encoding header\nheaderNameAcceptEncoding) {\n    let request = null;\n    let response = null;\n    let error = undefined;\n    if (requested !== null && requested !== \"identity\") {\n        const found = available.find((c) => c.name === requested);\n        if (found) {\n            request = found;\n        }\n        else {\n            // To comply with https://github.com/grpc/grpc/blob/master/doc/compression.md\n            // and the Connect protocol, we return code \"unimplemented\" and specify\n            // acceptable compression(s).\n            const acceptable = available.map((c) => c.name).join(\",\");\n            error = new ConnectError(`unknown compression \"${requested}\": supported encodings are ${acceptable}`, Code.Unimplemented, {\n                [headerNameAcceptEncoding]: acceptable,\n            });\n        }\n    }\n    if (accepted === null || accepted === \"\") {\n        // Support asymmetric compression. This logic follows\n        // https://github.com/grpc/grpc/blob/master/doc/compression.md and common\n        // sense.\n        response = request;\n    }\n    else {\n        const acceptNames = accepted.split(\",\").map((n) => n.trim());\n        for (const name of acceptNames) {\n            const found = available.find((c) => c.name === name);\n            if (found) {\n                response = found;\n                break;\n            }\n        }\n    }\n    return { request, response, error };\n}\n","// Copyright 2021-2025 The Connect Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { ConnectError } from \"../connect-error.js\";\nimport { Code } from \"../code.js\";\n/**\n * At most, allow ~4GiB to be received or sent per message.\n * zlib used by Node.js caps maxOutputLength at this value. It also happens to\n * be the maximum theoretical message size supported by protobuf-es.\n */\nconst maxReadMaxBytes = 0xffffffff;\nconst maxWriteMaxBytes = maxReadMaxBytes;\n/**\n * The default value for the compressMinBytes option. The CPU cost of compressing\n * very small messages usually isn't worth the small reduction in network I/O, so\n * the default value is 1 kibibyte.\n */\nconst defaultCompressMinBytes = 1024;\n/**\n * Asserts that the options writeMaxBytes, readMaxBytes, and compressMinBytes\n * are within sane limits, and returns default values where no value is\n * provided.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function validateReadWriteMaxBytes(readMaxBytes, writeMaxBytes, compressMinBytes) {\n    writeMaxBytes !== null && writeMaxBytes !== void 0 ? writeMaxBytes : (writeMaxBytes = maxWriteMaxBytes);\n    readMaxBytes !== null && readMaxBytes !== void 0 ? readMaxBytes : (readMaxBytes = maxReadMaxBytes);\n    compressMinBytes !== null && compressMinBytes !== void 0 ? compressMinBytes : (compressMinBytes = defaultCompressMinBytes);\n    if (writeMaxBytes < 1 || writeMaxBytes > maxWriteMaxBytes) {\n        throw new ConnectError(`writeMaxBytes ${writeMaxBytes} must be >= 1 and <= ${maxWriteMaxBytes}`, Code.Internal);\n    }\n    if (readMaxBytes < 1 || readMaxBytes > maxReadMaxBytes) {\n        throw new ConnectError(`readMaxBytes ${readMaxBytes} must be >= 1 and <= ${maxReadMaxBytes}`, Code.Internal);\n    }\n    return {\n        readMaxBytes,\n        writeMaxBytes,\n        compressMinBytes,\n    };\n}\n/**\n * Raise an error ResourceExhausted if more than writeMaxByte are written.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function assertWriteMaxBytes(writeMaxBytes, bytesWritten) {\n    if (bytesWritten > writeMaxBytes) {\n        throw new ConnectError(`message size ${bytesWritten} is larger than configured writeMaxBytes ${writeMaxBytes}`, Code.ResourceExhausted);\n    }\n}\n/**\n * Raise an error ResourceExhausted if more than readMaxBytes are read.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function assertReadMaxBytes(readMaxBytes, bytesRead, totalSizeKnown = false) {\n    if (bytesRead > readMaxBytes) {\n        let message = `message size is larger than configured readMaxBytes ${readMaxBytes}`;\n        if (totalSizeKnown) {\n            message = `message size ${bytesRead} is larger than configured readMaxBytes ${readMaxBytes}`;\n        }\n        throw new ConnectError(message, Code.ResourceExhausted);\n    }\n}\n","// Copyright 2021-2025 The Connect Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { ConnectError } from \"../connect-error.js\";\nimport { Code } from \"../code.js\";\nimport { compressedFlag } from \"./compression.js\";\nimport { assertReadMaxBytes } from \"./limit-io.js\";\n/**\n * Create an EnvelopeDecoder. The `readMaxBytes` argument limits the maximum\n * size for individual messages.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function createEnvelopeDecoder(readMaxBytes) {\n    return new EnvelopeDecoderImpl(readMaxBytes);\n}\nclass EnvelopeDecoderImpl {\n    constructor(readMaxBytes) {\n        this.readMaxBytes = readMaxBytes;\n        // Envelope headers are 5 bytes: 1 byte for flags, 4 bytes message length\n        this.header = new Uint8Array(5);\n        this.headerView = new DataView(this.header.buffer);\n        this.buf = [];\n    }\n    get byteLength() {\n        return this.buf.reduce((a, b) => a + b.byteLength, 0);\n    }\n    decode(chunk) {\n        this.buf.push(chunk);\n        const envs = [];\n        for (;;) {\n            let env = this.pop();\n            if (!env) {\n                break;\n            }\n            envs.push(env);\n        }\n        return envs;\n    }\n    // consume an enveloped message\n    pop() {\n        if (!this.env) {\n            this.env = this.head();\n            if (!this.env) {\n                return undefined;\n            }\n        }\n        if (this.cons(this.env.data)) {\n            const env = this.env;\n            this.env = undefined;\n            return env;\n        }\n        return undefined;\n    }\n    // consume header\n    head() {\n        if (!this.cons(this.header)) {\n            return undefined;\n        }\n        const flags = this.headerView.getUint8(0); // first byte is flags\n        const length = this.headerView.getUint32(1); // 4 bytes message length\n        assertReadMaxBytes(this.readMaxBytes, length, true);\n        return {\n            flags,\n            data: new Uint8Array(length),\n        };\n    }\n    // consume from buffer, fill target\n    cons(target) {\n        const wantLength = target.byteLength;\n        if (this.byteLength < wantLength) {\n            return false;\n        }\n        let offset = 0;\n        while (offset < wantLength) {\n            const chunk = this.buf.shift(); // we check length above\n            if (chunk.byteLength > wantLength - offset) {\n                target.set(chunk.subarray(0, wantLength - offset), offset);\n                this.buf.unshift(chunk.subarray(wantLength - offset));\n                offset += wantLength - offset;\n            }\n            else {\n                target.set(chunk, offset);\n                offset += chunk.byteLength;\n            }\n        }\n        return true;\n    }\n}\n/**\n * Create a WHATWG ReadableStream of enveloped messages from a ReadableStream\n * of bytes.\n *\n * Ideally, this would simply be a TransformStream, but ReadableStream.pipeThrough\n * does not have the necessary availability at this time.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function createEnvelopeReadableStream(stream) {\n    let reader;\n    const buffer = createEnvelopeDecoder(0xffffffff);\n    return new ReadableStream({\n        start() {\n            reader = stream.getReader();\n        },\n        async pull(controller) {\n            let enqueuedOnce = false;\n            while (!enqueuedOnce) {\n                const result = await reader.read();\n                if (result.done) {\n                    if (buffer.byteLength > 0) {\n                        controller.error(new ConnectError(\"protocol error: incomplete envelope\", Code.InvalidArgument));\n                    }\n                    controller.close();\n                }\n                else {\n                    for (const env of buffer.decode(result.value)) {\n                        controller.enqueue(env);\n                        enqueuedOnce = true;\n                    }\n                }\n            }\n        },\n    });\n}\n/**\n * Compress an EnvelopedMessage.\n *\n * Raises Internal if an enveloped message is already compressed.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport async function envelopeCompress(envelope, compression, compressMinBytes) {\n    let { flags, data } = envelope;\n    if ((flags & compressedFlag) === compressedFlag) {\n        throw new ConnectError(\"invalid envelope, already compressed\", Code.Internal);\n    }\n    if (compression && data.byteLength >= compressMinBytes) {\n        data = await compression.compress(data);\n        flags = flags | compressedFlag;\n    }\n    return { data, flags };\n}\n/**\n * Decompress an EnvelopedMessage.\n *\n * Raises InvalidArgument if an envelope is compressed, but compression is null.\n *\n * Relies on the provided Compression to raise ResourceExhausted if the\n * *decompressed* message size is larger than readMaxBytes. If the envelope is\n * not compressed, readMaxBytes is not honored.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport async function envelopeDecompress(envelope, compression, readMaxBytes) {\n    let { flags, data } = envelope;\n    if ((flags & compressedFlag) === compressedFlag) {\n        if (!compression) {\n            throw new ConnectError(\"received compressed envelope, but do not know how to decompress\", Code.Internal);\n        }\n        data = await compression.decompress(data, readMaxBytes);\n        flags = flags ^ compressedFlag;\n    }\n    return { data, flags };\n}\n/**\n * Encode a single enveloped message.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function encodeEnvelope(flags, data) {\n    const bytes = new Uint8Array(data.length + 5);\n    bytes.set(data, 5);\n    const v = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n    v.setUint8(0, flags); // first byte is flags\n    v.setUint32(1, data.length); // 4 bytes message length\n    return bytes;\n}\n/**\n * Encode a set of enveloped messages.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function encodeEnvelopes(...envelopes) {\n    const len = envelopes.reduce((previousValue, currentValue) => previousValue + currentValue.data.length + 5, 0);\n    const bytes = new Uint8Array(len);\n    const v = new DataView(bytes.buffer);\n    let offset = 0;\n    for (const e of envelopes) {\n        v.setUint8(offset, e.flags); // first byte is flags\n        v.setUint32(offset + 1, e.data.length); // 4 bytes message length\n        bytes.set(e.data, offset + 5);\n        offset += e.data.length + 5;\n    }\n    return bytes;\n}\n","// Copyright 2021-2025 The Connect Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nvar __asyncValues = (this && this.__asyncValues) || function (o) {\n    if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n    var m = o[Symbol.asyncIterator], i;\n    return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n    function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n    function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n};\nvar __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }\nvar __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n    if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n    var g = generator.apply(thisArg, _arguments || []), i, q = [];\n    return i = Object.create((typeof AsyncIterator === \"function\" ? AsyncIterator : Object).prototype), verb(\"next\"), verb(\"throw\"), verb(\"return\", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;\n    function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }\n    function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }\n    function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n    function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n    function fulfill(value) { resume(\"next\", value); }\n    function reject(value) { resume(\"throw\", value); }\n    function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n};\nvar __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n    var i, p;\n    return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n    function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\n};\nimport { Code } from \"../code.js\";\nimport { ConnectError } from \"../connect-error.js\";\nimport { createEnvelopeDecoder } from \"./envelope.js\";\nimport { encodeEnvelope, envelopeCompress, envelopeDecompress, } from \"./envelope.js\";\nimport { assertReadMaxBytes } from \"./limit-io.js\";\nexport function pipeTo(source, ...rest) {\n    const [transforms, sink, opt] = pickTransformsAndSink(rest);\n    let iterable = source;\n    let abortable;\n    if ((opt === null || opt === void 0 ? void 0 : opt.propagateDownStreamError) === true) {\n        iterable = abortable = makeIterableAbortable(iterable);\n    }\n    // @ts-ignore\n    iterable = pipe(iterable, ...transforms, { propagateDownStreamError: false });\n    return sink(iterable).catch((reason) => {\n        if (abortable) {\n            return abortable.abort(reason).then(() => Promise.reject(reason));\n        }\n        return Promise.reject(reason);\n    });\n}\n// pick transforms, the sink, and options from the pipeTo() rest parameter\nfunction pickTransformsAndSink(rest) {\n    let opt;\n    if (typeof rest[rest.length - 1] != \"function\") {\n        opt = rest.pop();\n    }\n    const sink = rest.pop();\n    return [rest, sink, opt];\n}\n/**\n * Creates an AsyncIterableSink that concatenates all elements from the input.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function sinkAll() {\n    return async (iterable) => {\n        var _a, e_1, _b, _c;\n        const all = [];\n        try {\n            for (var _d = true, iterable_1 = __asyncValues(iterable), iterable_1_1; iterable_1_1 = await iterable_1.next(), _a = iterable_1_1.done, !_a; _d = true) {\n                _c = iterable_1_1.value;\n                _d = false;\n                const chunk = _c;\n                all.push(chunk);\n            }\n        }\n        catch (e_1_1) { e_1 = { error: e_1_1 }; }\n        finally {\n            try {\n                if (!_d && !_a && (_b = iterable_1.return)) await _b.call(iterable_1);\n            }\n            finally { if (e_1) throw e_1.error; }\n        }\n        return all;\n    };\n}\n/**\n * Creates an AsyncIterableSink that concatenates all chunks from the input into\n * a single Uint8Array.\n *\n * The iterable raises an error if the more than readMaxBytes are read.\n *\n * An optional length hint can be provided to optimize allocation and validation.\n * If more or less bytes are present in the source that the length hint indicates,\n * and error is raised.\n * If the length hint is larger than readMaxBytes, an error is raised.\n * If the length hint is not a positive integer, it is ignored.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function sinkAllBytes(readMaxBytes, lengthHint) {\n    return async (iterable) => await readAllBytes(iterable, readMaxBytes, lengthHint);\n}\nexport function pipe(source, ...rest) {\n    return __asyncGenerator(this, arguments, function* pipe_1() {\n        var _a;\n        const [transforms, opt] = pickTransforms(rest);\n        let abortable;\n        const sourceIt = source[Symbol.asyncIterator]();\n        const cachedSource = {\n            [Symbol.asyncIterator]() {\n                return sourceIt;\n            },\n        };\n        let iterable = cachedSource;\n        if ((opt === null || opt === void 0 ? void 0 : opt.propagateDownStreamError) === true) {\n            iterable = abortable = makeIterableAbortable(iterable);\n        }\n        for (const t of transforms) {\n            iterable = t(iterable);\n        }\n        const it = iterable[Symbol.asyncIterator]();\n        try {\n            for (;;) {\n                const r = yield __await(it.next());\n                if (r.done === true) {\n                    break;\n                }\n                if (!abortable) {\n                    yield yield __await(r.value);\n                    continue;\n                }\n                try {\n                    yield yield __await(r.value);\n                }\n                catch (e) {\n                    yield __await(abortable.abort(e)); // propagate downstream error to the source\n                    throw e;\n                }\n            }\n        }\n        finally {\n            if ((opt === null || opt === void 0 ? void 0 : opt.propagateDownStreamError) === true) {\n                // Call return on the source iterable to indicate\n                // that we will no longer consume it and it should\n                // cleanup any allocated resources.\n                (_a = sourceIt.return) === null || _a === void 0 ? void 0 : _a.call(sourceIt).catch(() => {\n                    // return returns a promise, which we don't care about.\n                    //\n                    // Uncaught promises are thrown at sometime/somewhere by the event loop,\n                    // this is to ensure error is caught and ignored.\n                });\n            }\n        }\n    });\n}\nfunction pickTransforms(rest) {\n    let opt;\n    if (typeof rest[rest.length - 1] != \"function\") {\n        opt = rest.pop();\n    }\n    return [rest, opt];\n}\n/**\n * Creates an AsyncIterableTransform that catches any error from the input, and\n * passes it to the given catchError function.\n *\n * The catchError function may return a final value.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function transformCatch(catchError) {\n    return function (iterable) {\n        return __asyncGenerator(this, arguments, function* () {\n            // we deliberate avoid a for-await loop because we only want to catch upstream\n            // errors, not downstream errors (yield).\n            const it = iterable[Symbol.asyncIterator]();\n            for (;;) {\n                let r;\n                try {\n                    r = yield __await(it.next());\n                }\n                catch (e) {\n                    const caught = yield __await(catchError(e));\n                    if (caught !== undefined) {\n                        yield yield __await(caught);\n                    }\n                    break;\n                }\n                if (r.done === true) {\n                    break;\n                }\n                yield yield __await(r.value);\n            }\n        });\n    };\n}\n/**\n * Creates an AsyncIterableTransform that catches any error from the input, and\n * passes it to the given function. Unlike transformCatch(), the given function\n * is also called when no error is raised.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function transformCatchFinally(catchFinally) {\n    return function (iterable) {\n        return __asyncGenerator(this, arguments, function* () {\n            // we deliberate avoid a for-await loop because we only want to catch upstream\n            // errors, not downstream errors (yield).\n            let err;\n            const it = iterable[Symbol.asyncIterator]();\n            for (;;) {\n                let r;\n                try {\n                    r = yield __await(it.next());\n                }\n                catch (e) {\n                    err = e;\n                    break;\n                }\n                if (r.done === true) {\n                    break;\n                }\n                yield yield __await(r.value);\n            }\n            const caught = yield __await(catchFinally(err));\n            if (caught !== undefined) {\n                yield yield __await(caught);\n            }\n        });\n    };\n}\n/**\n * Creates an AsyncIterableTransform that appends a value.\n *\n * The element to append is provided by a function. If the function returns\n * undefined, no element is appended.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function transformAppend(provide) {\n    return function (iterable) {\n        return __asyncGenerator(this, arguments, function* () {\n            var _a, e_2, _b, _c;\n            try {\n                for (var _d = true, iterable_2 = __asyncValues(iterable), iterable_2_1; iterable_2_1 = yield __await(iterable_2.next()), _a = iterable_2_1.done, !_a; _d = true) {\n                    _c = iterable_2_1.value;\n                    _d = false;\n                    const chunk = _c;\n                    yield yield __await(chunk);\n                }\n            }\n            catch (e_2_1) { e_2 = { error: e_2_1 }; }\n            finally {\n                try {\n                    if (!_d && !_a && (_b = iterable_2.return)) yield __await(_b.call(iterable_2));\n                }\n                finally { if (e_2) throw e_2.error; }\n            }\n            const append = yield __await(provide());\n            if (append !== undefined) {\n                yield yield __await(append);\n            }\n        });\n    };\n}\n/**\n * Creates an AsyncIterableTransform that prepends an element.\n *\n * The element to prepend is provided by a function. If the function returns\n * undefined, no element is appended.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function transformPrepend(provide) {\n    return function (iterable) {\n        return __asyncGenerator(this, arguments, function* () {\n            var _a, e_3, _b, _c;\n            const prepend = yield __await(provide());\n            if (prepend !== undefined) {\n                yield yield __await(prepend);\n            }\n            try {\n                for (var _d = true, iterable_3 = __asyncValues(iterable), iterable_3_1; iterable_3_1 = yield __await(iterable_3.next()), _a = iterable_3_1.done, !_a; _d = true) {\n                    _c = iterable_3_1.value;\n                    _d = false;\n                    const chunk = _c;\n                    yield yield __await(chunk);\n                }\n            }\n            catch (e_3_1) { e_3 = { error: e_3_1 }; }\n            finally {\n                try {\n                    if (!_d && !_a && (_b = iterable_3.return)) yield __await(_b.call(iterable_3));\n                }\n                finally { if (e_3) throw e_3.error; }\n            }\n        });\n    };\n}\n/**\n * Creates an AsyncIterableTransform that reads all bytes from the input, and\n * concatenates them to a single Uint8Array.\n *\n * The iterable raises an error if the more than readMaxBytes are read.\n *\n * An optional length hint can be provided to optimize allocation and validation.\n * If more or less bytes are present in the source that the length hint indicates,\n * and error is raised.\n * If the length hint is larger than readMaxBytes, an error is raised.\n * If the length hint is not a positive integer, it is ignored.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function transformReadAllBytes(readMaxBytes, lengthHint) {\n    return function (iterable) {\n        return __asyncGenerator(this, arguments, function* () {\n            yield yield __await(yield __await(readAllBytes(iterable, readMaxBytes, lengthHint)));\n        });\n    };\n}\nexport function transformSerializeEnvelope(serialization, endStreamFlag, endSerialization) {\n    if (endStreamFlag === undefined || endSerialization === undefined) {\n        return function (iterable) {\n            return __asyncGenerator(this, arguments, function* () {\n                var _a, e_4, _b, _c;\n                try {\n                    for (var _d = true, iterable_4 = __asyncValues(iterable), iterable_4_1; iterable_4_1 = yield __await(iterable_4.next()), _a = iterable_4_1.done, !_a; _d = true) {\n                        _c = iterable_4_1.value;\n                        _d = false;\n                        const chunk = _c;\n                        const data = serialization.serialize(chunk);\n                        yield yield __await({ flags: 0, data });\n                    }\n                }\n                catch (e_4_1) { e_4 = { error: e_4_1 }; }\n                finally {\n                    try {\n                        if (!_d && !_a && (_b = iterable_4.return)) yield __await(_b.call(iterable_4));\n                    }\n                    finally { if (e_4) throw e_4.error; }\n                }\n            });\n        };\n    }\n    return function (iterable) {\n        return __asyncGenerator(this, arguments, function* () {\n            var _a, e_5, _b, _c;\n            try {\n                for (var _d = true, iterable_5 = __asyncValues(iterable), iterable_5_1; iterable_5_1 = yield __await(iterable_5.next()), _a = iterable_5_1.done, !_a; _d = true) {\n                    _c = iterable_5_1.value;\n                    _d = false;\n                    const chunk = _c;\n                    let data;\n                    let flags = 0;\n                    if (chunk.end) {\n                        flags = flags | endStreamFlag;\n                        data = endSerialization.serialize(chunk.value);\n                    }\n                    else {\n                        data = serialization.serialize(chunk.value);\n                    }\n                    yield yield __await({ flags, data });\n                }\n            }\n            catch (e_5_1) { e_5 = { error: e_5_1 }; }\n            finally {\n                try {\n                    if (!_d && !_a && (_b = iterable_5.return)) yield __await(_b.call(iterable_5));\n                }\n                finally { if (e_5) throw e_5.error; }\n            }\n        });\n    };\n}\nexport function transformParseEnvelope(serialization, endStreamFlag, endSerialization) {\n    // code path always yields ParsedEnvelopedMessage<T, E>\n    if (endSerialization && endStreamFlag !== undefined) {\n        return function (iterable) {\n            return __asyncGenerator(this, arguments, function* () {\n                var _a, e_6, _b, _c;\n                try {\n                    for (var _d = true, iterable_6 = __asyncValues(iterable), iterable_6_1; iterable_6_1 = yield __await(iterable_6.next()), _a = iterable_6_1.done, !_a; _d = true) {\n                        _c = iterable_6_1.value;\n                        _d = false;\n                        const { flags, data } = _c;\n                        if ((flags & endStreamFlag) === endStreamFlag) {\n                            yield yield __await({ value: endSerialization.parse(data), end: true });\n                        }\n                        else {\n                            yield yield __await({ value: serialization.parse(data), end: false });\n                        }\n                    }\n                }\n                catch (e_6_1) { e_6 = { error: e_6_1 }; }\n                finally {\n                    try {\n                        if (!_d && !_a && (_b = iterable_6.return)) yield __await(_b.call(iterable_6));\n                    }\n                    finally { if (e_6) throw e_6.error; }\n                }\n            });\n        };\n    }\n    // code path always yields T\n    return function (iterable) {\n        return __asyncGenerator(this, arguments, function* () {\n            var _a, e_7, _b, _c;\n            try {\n                for (var _d = true, iterable_7 = __asyncValues(iterable), iterable_7_1; iterable_7_1 = yield __await(iterable_7.next()), _a = iterable_7_1.done, !_a; _d = true) {\n                    _c = iterable_7_1.value;\n                    _d = false;\n                    const { flags, data } = _c;\n                    if (endStreamFlag !== undefined &&\n                        (flags & endStreamFlag) === endStreamFlag) {\n                        if (endSerialization === null) {\n                            throw new ConnectError(\"unexpected end flag\", Code.InvalidArgument);\n                        }\n                        // skips end-of-stream envelope\n                        continue;\n                    }\n                    yield yield __await(serialization.parse(data));\n                }\n            }\n            catch (e_7_1) { e_7 = { error: e_7_1 }; }\n            finally {\n                try {\n                    if (!_d && !_a && (_b = iterable_7.return)) yield __await(_b.call(iterable_7));\n                }\n                finally { if (e_7) throw e_7.error; }\n            }\n        });\n    };\n}\n/**\n * Creates an AsyncIterableTransform that takes enveloped messages as a source,\n * and compresses them if they are larger than compressMinBytes.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function transformCompressEnvelope(compression, compressMinBytes) {\n    return function (iterable) {\n        return __asyncGenerator(this, arguments, function* () {\n            var _a, e_8, _b, _c;\n            try {\n                for (var _d = true, iterable_8 = __asyncValues(iterable), iterable_8_1; iterable_8_1 = yield __await(iterable_8.next()), _a = iterable_8_1.done, !_a; _d = true) {\n                    _c = iterable_8_1.value;\n                    _d = false;\n                    const env = _c;\n                    yield yield __await(yield __await(envelopeCompress(env, compression, compressMinBytes)));\n                }\n            }\n            catch (e_8_1) { e_8 = { error: e_8_1 }; }\n            finally {\n                try {\n                    if (!_d && !_a && (_b = iterable_8.return)) yield __await(_b.call(iterable_8));\n                }\n                finally { if (e_8) throw e_8.error; }\n            }\n        });\n    };\n}\n/**\n * Creates an AsyncIterableTransform that takes enveloped messages as a source,\n * and decompresses them using the given compression.\n *\n * The iterable raises an error if the decompressed payload of an enveloped\n * message is larger than readMaxBytes, or if no compression is provided.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function transformDecompressEnvelope(compression, readMaxBytes) {\n    return function (iterable) {\n        return __asyncGenerator(this, arguments, function* () {\n            var _a, e_9, _b, _c;\n            try {\n                for (var _d = true, iterable_9 = __asyncValues(iterable), iterable_9_1; iterable_9_1 = yield __await(iterable_9.next()), _a = iterable_9_1.done, !_a; _d = true) {\n                    _c = iterable_9_1.value;\n                    _d = false;\n                    const env = _c;\n                    yield yield __await(yield __await(envelopeDecompress(env, compression, readMaxBytes)));\n                }\n            }\n            catch (e_9_1) { e_9 = { error: e_9_1 }; }\n            finally {\n                try {\n                    if (!_d && !_a && (_b = iterable_9.return)) yield __await(_b.call(iterable_9));\n                }\n                finally { if (e_9) throw e_9.error; }\n            }\n        });\n    };\n}\n/**\n * Create an AsyncIterableTransform that takes enveloped messages as a source,\n * and joins them into a stream of raw bytes.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function transformJoinEnvelopes() {\n    return function (iterable) {\n        return __asyncGenerator(this, arguments, function* () {\n            var _a, e_10, _b, _c;\n            try {\n                for (var _d = true, iterable_10 = __asyncValues(iterable), iterable_10_1; iterable_10_1 = yield __await(iterable_10.next()), _a = iterable_10_1.done, !_a; _d = true) {\n                    _c = iterable_10_1.value;\n                    _d = false;\n                    const { flags, data } = _c;\n                    yield yield __await(encodeEnvelope(flags, data));\n                }\n            }\n            catch (e_10_1) { e_10 = { error: e_10_1 }; }\n            finally {\n                try {\n                    if (!_d && !_a && (_b = iterable_10.return)) yield __await(_b.call(iterable_10));\n                }\n                finally { if (e_10) throw e_10.error; }\n            }\n        });\n    };\n}\n/**\n * Create an AsyncIterableTransform that takes raw bytes as a source, and splits\n * them into enveloped messages.\n *\n * The iterable raises an error\n * - if the payload of an enveloped message is larger than readMaxBytes,\n * - if the stream ended before an enveloped message fully arrived,\n * - or if the stream ended with extraneous data.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function transformSplitEnvelope(readMaxBytes) {\n    return function (iterable) {\n        return __asyncGenerator(this, arguments, function* () {\n            var _a, e_11, _b, _c;\n            const buffer = createEnvelopeDecoder(readMaxBytes);\n            try {\n                for (var _d = true, iterable_11 = __asyncValues(iterable), iterable_11_1; iterable_11_1 = yield __await(iterable_11.next()), _a = iterable_11_1.done, !_a; _d = true) {\n                    _c = iterable_11_1.value;\n                    _d = false;\n                    const chunk = _c;\n                    for (const env of buffer.decode(chunk)) {\n                        yield yield __await(env);\n                    }\n                }\n            }\n            catch (e_11_1) { e_11 = { error: e_11_1 }; }\n            finally {\n                try {\n                    if (!_d && !_a && (_b = iterable_11.return)) yield __await(_b.call(iterable_11));\n                }\n                finally { if (e_11) throw e_11.error; }\n            }\n            if (buffer.byteLength > 0) {\n                throw new ConnectError(\"protocol error: incomplete envelope\", Code.InvalidArgument);\n            }\n        });\n    };\n}\n/**\n * Reads all bytes from the source, and concatenates them to a single Uint8Array.\n *\n * Raises an error if:\n * - more than readMaxBytes are read\n * - lengthHint is a positive integer, but larger than readMaxBytes\n * - lengthHint is a positive integer, and the source contains more or less bytes\n *   than promised\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport async function readAllBytes(iterable, readMaxBytes, lengthHint) {\n    var _a, e_12, _b, _c, _d, e_13, _e, _f;\n    const [ok, hint] = parseLengthHint(lengthHint);\n    if (ok) {\n        if (hint > readMaxBytes) {\n            assertReadMaxBytes(readMaxBytes, hint, true);\n        }\n        const buffer = new Uint8Array(hint);\n        let offset = 0;\n        try {\n            for (var _g = true, iterable_12 = __asyncValues(iterable), iterable_12_1; iterable_12_1 = await iterable_12.next(), _a = iterable_12_1.done, !_a; _g = true) {\n                _c = iterable_12_1.value;\n                _g = false;\n                const chunk = _c;\n                if (offset + chunk.byteLength > hint) {\n                    throw new ConnectError(`protocol error: promised ${hint} bytes, received ${offset + chunk.byteLength}`, Code.InvalidArgument);\n                }\n                buffer.set(chunk, offset);\n                offset += chunk.byteLength;\n            }\n        }\n        catch (e_12_1) { e_12 = { error: e_12_1 }; }\n        finally {\n            try {\n                if (!_g && !_a && (_b = iterable_12.return)) await _b.call(iterable_12);\n            }\n            finally { if (e_12) throw e_12.error; }\n        }\n        if (offset < hint) {\n            throw new ConnectError(`protocol error: promised ${hint} bytes, received ${offset}`, Code.InvalidArgument);\n        }\n        return buffer;\n    }\n    const chunks = [];\n    let count = 0;\n    try {\n        for (var _h = true, iterable_13 = __asyncValues(iterable), iterable_13_1; iterable_13_1 = await iterable_13.next(), _d = iterable_13_1.done, !_d; _h = true) {\n            _f = iterable_13_1.value;\n            _h = false;\n            const chunk = _f;\n            count += chunk.byteLength;\n            assertReadMaxBytes(readMaxBytes, count);\n            chunks.push(chunk);\n        }\n    }\n    catch (e_13_1) { e_13 = { error: e_13_1 }; }\n    finally {\n        try {\n            if (!_h && !_d && (_e = iterable_13.return)) await _e.call(iterable_13);\n        }\n        finally { if (e_13) throw e_13.error; }\n    }\n    const all = new Uint8Array(count);\n    let offset = 0;\n    for (let chunk = chunks.shift(); chunk; chunk = chunks.shift()) {\n        all.set(chunk, offset);\n        offset += chunk.byteLength;\n    }\n    return all;\n}\n// parse the lengthHint argument of readAllBytes()\nfunction parseLengthHint(lengthHint) {\n    if (lengthHint === undefined || lengthHint === null) {\n        return [false, 0];\n    }\n    const n = typeof lengthHint == \"string\" ? parseInt(lengthHint, 10) : lengthHint;\n    if (!Number.isSafeInteger(n) || n < 0) {\n        return [false, n];\n    }\n    return [true, n];\n}\n/**\n * Wait for the first element of an iterable without modifying the iterable.\n * This consumes the first element, but pushes it back on the stack.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport async function untilFirst(iterable) {\n    const it = iterable[Symbol.asyncIterator]();\n    let first = await it.next();\n    return {\n        [Symbol.asyncIterator]() {\n            const w = {\n                async next() {\n                    if (first !== null) {\n                        const n = first;\n                        first = null;\n                        return n;\n                    }\n                    return await it.next();\n                },\n            };\n            if (it.throw !== undefined) {\n                w.throw = (e) => it.throw(e);\n            }\n            if (it.return !== undefined) {\n                w.return = (value) => it.return(value);\n            }\n            return w;\n        },\n    };\n}\n/**\n * Wrap the given iterable and return an iterable with an abort() method.\n *\n * This function exists purely for convenience. Where one would typically have\n * to access the iterator directly, advance through all elements, and call\n * AsyncIterator.throw() to notify the upstream iterable, this function allows\n * to use convenient for-await loops and still notify the upstream iterable:\n *\n * ```ts\n * const abortable = makeIterableAbortable(iterable);\n * for await (const ele of abortable) {\n *   await abortable.abort(\"ERR\");\n * }\n * ```\n * There are a couple of limitations of this function:\n * - the given async iterable must implement throw\n * - the async iterable cannot be re-use\n * - if source catches errors and yields values for them, they are ignored, and\n *   the source may still dangle\n *\n * There are four possible ways an async function* can handle yield errors:\n * 1. don't catch errors at all - Abortable.abort() will resolve \"rethrown\"\n * 2. catch errors and rethrow - Abortable.abort() will resolve \"rethrown\"\n * 3. catch errors and return - Abortable.abort() will resolve \"completed\"\n * 4. catch errors and yield a value - Abortable.abort() will resolve \"caught\"\n *\n * Note that catching errors and yielding a value is problematic, and it should\n * be documented that this may leave the source in a dangling state.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function makeIterableAbortable(iterable) {\n    const innerCandidate = iterable[Symbol.asyncIterator]();\n    if (innerCandidate.throw === undefined) {\n        throw new Error(\"AsyncIterable does not implement throw\");\n    }\n    const inner = innerCandidate;\n    let aborted;\n    let resultPromise;\n    let it = {\n        next() {\n            resultPromise = inner.next().finally(() => {\n                resultPromise = undefined;\n            });\n            return resultPromise;\n        },\n        throw(e) {\n            return inner.throw(e);\n        },\n    };\n    if (innerCandidate.return !== undefined) {\n        it = Object.assign(Object.assign({}, it), { return(value) {\n                return inner.return(value);\n            } });\n    }\n    let used = false;\n    return {\n        abort(reason) {\n            if (aborted) {\n                return aborted.state;\n            }\n            const f = () => {\n                return inner.throw(reason).then((r) => (r.done === true ? \"completed\" : \"caught\"), () => \"rethrown\");\n            };\n            if (resultPromise) {\n                aborted = { reason, state: resultPromise.then(f, f) };\n                return aborted.state;\n            }\n            aborted = { reason, state: f() };\n            return aborted.state;\n        },\n        [Symbol.asyncIterator]() {\n            if (used) {\n                throw new Error(\"AsyncIterable cannot be re-used\");\n            }\n            used = true;\n            return it;\n        },\n    };\n}\n/**\n * Create a new WritableIterable.\n */\nexport function createWritableIterable() {\n    // We start with two queues to capture the read and write attempts.\n    //\n    // The writes and reads each check of their counterpart is\n    // already available and either interact/add themselves to the queue.\n    const readQueue = [];\n    const writeQueue = [];\n    let err = undefined;\n    let nextResolve;\n    let nextReject;\n    let nextPromise = new Promise((resolve, reject) => {\n        nextResolve = resolve;\n        nextReject = reject;\n    });\n    let closed = false;\n    // drain the readQueue in case of error/writer is closed by sending a\n    // done result.\n    function drain() {\n        for (const next of readQueue.splice(0, readQueue.length)) {\n            next({ done: true, value: undefined });\n        }\n    }\n    return {\n        close() {\n            closed = true;\n            drain();\n        },\n        async write(payload) {\n            if (closed) {\n                throw err !== null && err !== void 0 ? err : new Error(\"cannot write, WritableIterable already closed\");\n            }\n            const read = readQueue.shift();\n            if (read === undefined) {\n                // We didn't find a pending read so we add the payload to the write queue.\n                writeQueue.push(payload);\n            }\n            else {\n                // We found a pending read so we respond with the payload.\n                read({ done: false, value: payload });\n                if (readQueue.length > 0) {\n                    // If there are more in the read queue we can mark the write as complete.\n                    // as the error reporting is not guaranteed to be sequential and therefore cannot\n                    // to linked to a specific write.\n                    return;\n                }\n            }\n            // We await the next call for as many times as there are items in the queue + 1\n            //\n            // If there are no items in the write queue that means write happened and we just have\n            // to wait for one more call likewise if we are the nth write in the queue we\n            // have to wait for n writes to complete and one more.\n            const limit = writeQueue.length + 1;\n            for (let i = 0; i < limit; i++) {\n                await nextPromise;\n            }\n        },\n        [Symbol.asyncIterator]() {\n            return {\n                next() {\n                    // Resolve the nextPromise to indicate\n                    // pending writes that a read attempt has been made\n                    // after their write.\n                    //\n                    // We also need to reset the promise for future writes.\n                    nextResolve();\n                    nextPromise = new Promise((resolve, reject) => {\n                        nextResolve = resolve;\n                        nextReject = reject;\n                    });\n                    const write = writeQueue.shift();\n                    if (write !== undefined) {\n                        // We found a pending write so response with the payload.\n                        return Promise.resolve({ done: false, value: write });\n                    }\n                    if (closed) {\n                        return Promise.resolve({ done: true, value: undefined });\n                    }\n                    // We return a promise immediately that is either resolved/rejected\n                    // as writes happen.\n                    let readResolve;\n                    const readPromise = new Promise((resolve) => {\n                        readResolve = resolve;\n                    });\n                    // biome-ignore lint/style/noNonNullAssertion: initialized by promise executor\n                    readQueue.push(readResolve);\n                    return readPromise;\n                },\n                throw(throwErr) {\n                    err = throwErr;\n                    closed = true;\n                    writeQueue.splice(0, writeQueue.length);\n                    nextPromise.catch(() => {\n                        // To make sure that the nextPromise is always resolved.\n                    });\n                    // This will reject all pending writes.\n                    nextReject(err);\n                    drain();\n                    return Promise.resolve({ done: true, value: undefined });\n                },\n                return() {\n                    closed = true;\n                    writeQueue.splice(0, writeQueue.length);\n                    // Resolve once for the write awaiting confirmation.\n                    nextResolve();\n                    // Reject all future writes.\n                    nextPromise = Promise.reject(new Error(\"cannot write, consumer called return\"));\n                    nextPromise.catch(() => {\n                        // To make sure that the nextPromise is always resolved.\n                    });\n                    drain();\n                    return Promise.resolve({ done: true, value: undefined });\n                },\n            };\n        },\n    };\n}\n/**\n * Create an asynchronous iterable from an array.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function createAsyncIterable(items) {\n    return __asyncGenerator(this, arguments, function* createAsyncIterable_1() {\n        yield __await(yield* __asyncDelegator(__asyncValues(items)));\n    });\n}\n","// Copyright 2021-2025 The Connect Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nvar __asyncValues = (this && this.__asyncValues) || function (o) {\n    if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n    var m = o[Symbol.asyncIterator], i;\n    return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n    function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n    function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n};\nvar __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }\nvar __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n    var i, p;\n    return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n    function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\n};\nvar __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n    if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n    var g = generator.apply(thisArg, _arguments || []), i, q = [];\n    return i = Object.create((typeof AsyncIterator === \"function\" ? AsyncIterator : Object).prototype), verb(\"next\"), verb(\"throw\"), verb(\"return\", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;\n    function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }\n    function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }\n    function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n    function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n    function fulfill(value) { resume(\"next\", value); }\n    function reject(value) { resume(\"throw\", value); }\n    function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n};\nimport { makeAnyClient } from \"./any-client.js\";\nimport { ConnectError } from \"./connect-error.js\";\nimport { Code } from \"./code.js\";\nimport { createAsyncIterable } from \"./protocol/async-iterable.js\";\n/**\n * Create a Client for the given service, invoking RPCs through the\n * given transport.\n */\nexport function createClient(service, transport) {\n    return makeAnyClient(service, (method) => {\n        switch (method.methodKind) {\n            case \"unary\":\n                return createUnaryFn(transport, method);\n            case \"server_streaming\":\n                return createServerStreamingFn(transport, method);\n            case \"client_streaming\":\n                return createClientStreamingFn(transport, method);\n            case \"bidi_streaming\":\n                return createBiDiStreamingFn(transport, method);\n            default:\n                return null;\n        }\n    });\n}\nexport function createUnaryFn(transport, method) {\n    return async (input, options) => {\n        var _a, _b;\n        const response = await transport.unary(method, options === null || options === void 0 ? void 0 : options.signal, options === null || options === void 0 ? void 0 : options.timeoutMs, options === null || options === void 0 ? void 0 : options.headers, input, options === null || options === void 0 ? void 0 : options.contextValues);\n        (_a = options === null || options === void 0 ? void 0 : options.onHeader) === null || _a === void 0 ? void 0 : _a.call(options, response.header);\n        (_b = options === null || options === void 0 ? void 0 : options.onTrailer) === null || _b === void 0 ? void 0 : _b.call(options, response.trailer);\n        return response.message;\n    };\n}\nexport function createServerStreamingFn(transport, method) {\n    return (input, options) => handleStreamResponse(transport.stream(method, options === null || options === void 0 ? void 0 : options.signal, options === null || options === void 0 ? void 0 : options.timeoutMs, options === null || options === void 0 ? void 0 : options.headers, createAsyncIterable([input]), options === null || options === void 0 ? void 0 : options.contextValues), options);\n}\nexport function createClientStreamingFn(transport, method) {\n    return async (request, options) => {\n        var _a, e_1, _b, _c;\n        var _d, _e;\n        const response = await transport.stream(method, options === null || options === void 0 ? void 0 : options.signal, options === null || options === void 0 ? void 0 : options.timeoutMs, options === null || options === void 0 ? void 0 : options.headers, request, options === null || options === void 0 ? void 0 : options.contextValues);\n        (_d = options === null || options === void 0 ? void 0 : options.onHeader) === null || _d === void 0 ? void 0 : _d.call(options, response.header);\n        let singleMessage;\n        let count = 0;\n        try {\n            for (var _f = true, _g = __asyncValues(response.message), _h; _h = await _g.next(), _a = _h.done, !_a; _f = true) {\n                _c = _h.value;\n                _f = false;\n                const message = _c;\n                singleMessage = message;\n                count++;\n            }\n        }\n        catch (e_1_1) { e_1 = { error: e_1_1 }; }\n        finally {\n            try {\n                if (!_f && !_a && (_b = _g.return)) await _b.call(_g);\n            }\n            finally { if (e_1) throw e_1.error; }\n        }\n        if (!singleMessage) {\n            throw new ConnectError(\"protocol error: missing response message\", Code.Unimplemented);\n        }\n        if (count > 1) {\n            throw new ConnectError(\"protocol error: received extra messages for client streaming method\", Code.Unimplemented);\n        }\n        (_e = options === null || options === void 0 ? void 0 : options.onTrailer) === null || _e === void 0 ? void 0 : _e.call(options, response.trailer);\n        return singleMessage;\n    };\n}\nexport function createBiDiStreamingFn(transport, method) {\n    return (request, options) => handleStreamResponse(transport.stream(method, options === null || options === void 0 ? void 0 : options.signal, options === null || options === void 0 ? void 0 : options.timeoutMs, options === null || options === void 0 ? void 0 : options.headers, request, options === null || options === void 0 ? void 0 : options.contextValues), options);\n}\nfunction handleStreamResponse(stream, options) {\n    const it = (function () {\n        return __asyncGenerator(this, arguments, function* () {\n            var _a, _b;\n            const response = yield __await(stream);\n            (_a = options === null || options === void 0 ? void 0 : options.onHeader) === null || _a === void 0 ? void 0 : _a.call(options, response.header);\n            yield __await(yield* __asyncDelegator(__asyncValues(response.message)));\n            (_b = options === null || options === void 0 ? void 0 : options.onTrailer) === null || _b === void 0 ? void 0 : _b.call(options, response.trailer);\n        });\n    })()[Symbol.asyncIterator]();\n    // Create a new iterable to omit throw/return.\n    return {\n        [Symbol.asyncIterator]: () => ({\n            next: () => it.next(),\n        }),\n    };\n}\n","// Copyright 2021-2025 The Connect Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { ConnectError } from \"../connect-error.js\";\nimport { Code } from \"../code.js\";\n/**\n * Create an AbortController that is automatically aborted if one of the given\n * signals is aborted.\n *\n * For convenience, the linked AbortSignals can be undefined.\n *\n * If the controller or any of the signals is aborted, all event listeners are\n * removed.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function createLinkedAbortController(...signals) {\n    const controller = new AbortController();\n    const sa = signals.filter((s) => s !== undefined).concat(controller.signal);\n    for (const signal of sa) {\n        if (signal.aborted) {\n            onAbort.apply(signal);\n            break;\n        }\n        signal.addEventListener(\"abort\", onAbort);\n    }\n    function onAbort() {\n        if (!controller.signal.aborted) {\n            controller.abort(getAbortSignalReason(this));\n        }\n        for (const signal of sa) {\n            signal.removeEventListener(\"abort\", onAbort);\n        }\n    }\n    return controller;\n}\n/**\n * Create a deadline signal. The returned object contains an AbortSignal, but\n * also a cleanup function to stop the timer, which must be called once the\n * calling code is no longer interested in the signal.\n *\n * Ideally, we would simply use AbortSignal.timeout(), but it is not widely\n * available yet.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function createDeadlineSignal(timeoutMs) {\n    const controller = new AbortController();\n    const listener = () => {\n        controller.abort(new ConnectError(\"the operation timed out\", Code.DeadlineExceeded));\n    };\n    let timeoutId;\n    if (timeoutMs !== undefined) {\n        if (timeoutMs <= 0)\n            listener();\n        else\n            timeoutId = setTimeout(listener, timeoutMs);\n    }\n    return {\n        signal: controller.signal,\n        cleanup: () => clearTimeout(timeoutId),\n    };\n}\n/**\n * Returns the reason why an AbortSignal was aborted. Returns undefined if the\n * signal has not been aborted.\n *\n * The property AbortSignal.reason is not widely available. This function\n * returns an AbortError if the signal is aborted, but reason is undefined.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function getAbortSignalReason(signal) {\n    if (!signal.aborted) {\n        return undefined;\n    }\n    if (signal.reason !== undefined) {\n        return signal.reason;\n    }\n    // AbortSignal.reason is available in Node.js v16, v18, and later,\n    // and in all browsers since early 2022.\n    const e = new Error(\"This operation was aborted\");\n    e.name = \"AbortError\";\n    return e;\n}\n","// Copyright 2021-2025 The Connect Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n/**\n * createContextValues creates a new ContextValues.\n */\nexport function createContextValues() {\n    return {\n        get(key) {\n            return key.id in this ? this[key.id] : key.defaultValue;\n        },\n        set(key, value) {\n            this[key.id] = value;\n            return this;\n        },\n        delete(key) {\n            delete this[key.id];\n            return this;\n        },\n    };\n}\n/**\n * createContextKey creates a new ContextKey.\n */\nexport function createContextKey(defaultValue, options) {\n    return { id: Symbol(options === null || options === void 0 ? void 0 : options.description), defaultValue };\n}\n","// Copyright 2021-2025 The Connect Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n/**\n * trailerFlag indicates that the data in a EnvelopedMessage\n * is a set of trailers of the gRPC-web protocol.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport const trailerFlag = 0b10000000;\n/**\n * Parse a gRPC-web trailer, a set of header fields separated by CRLF.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function trailerParse(data) {\n    const headers = new Headers();\n    const lines = new TextDecoder().decode(data).split(\"\\r\\n\");\n    for (const line of lines) {\n        if (line === \"\") {\n            continue;\n        }\n        const i = line.indexOf(\":\");\n        if (i > 0) {\n            const name = line.substring(0, i).trim();\n            const value = line.substring(i + 1).trim();\n            headers.append(name, value);\n        }\n    }\n    return headers;\n}\n/**\n * Serialize a Headers object as a gRPC-web trailer.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function trailerSerialize(trailer) {\n    const lines = [];\n    trailer.forEach((value, key) => {\n        lines.push(`${key}: ${value}\\r\\n`);\n    });\n    return new TextEncoder().encode(lines.join(\"\"));\n}\n/**\n * Create a Serialization object that serializes a gRPC-web trailer, a Headers\n * object that is serialized as a set of header fields, separated by CRLF.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function createTrailerSerialization() {\n    return {\n        serialize: trailerSerialize,\n        parse: trailerParse,\n    };\n}\n","// Copyright 2021-2025 The Connect Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n/**\n * @private Internal code, does not follow semantic versioning.\n */\nexport const headerContentType = \"Content-Type\";\nexport const headerEncoding = \"Grpc-Encoding\";\nexport const headerAcceptEncoding = \"Grpc-Accept-Encoding\";\nexport const headerTimeout = \"Grpc-Timeout\";\nexport const headerGrpcStatus = \"Grpc-Status\";\nexport const headerGrpcMessage = \"Grpc-Message\";\nexport const headerStatusDetailsBin = \"Grpc-Status-Details-Bin\";\nexport const headerMessageType = \"Grpc-Message-Type\";\nexport const headerUserAgent = \"User-Agent\";\n","// Copyright 2021-2025 The Connect Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n/**\n * @private Internal code, does not follow semantic versioning.\n */\nexport { headerContentType, headerEncoding, headerAcceptEncoding, headerTimeout, headerGrpcStatus, headerGrpcMessage, headerStatusDetailsBin, headerUserAgent, } from \"../protocol-grpc/headers.js\";\n/**\n * gRPC-web does not use the standard header User-Agent.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport const headerXUserAgent = \"X-User-Agent\";\n/**\n * The canonical grpc/grpc-web JavaScript implementation sets\n * this request header with value \"1\".\n * Some servers may rely on the header to identify gRPC-web\n * requests. For example the proxy by improbable:\n * https://github.com/improbable-eng/grpc-web/blob/53aaf4cdc0fede7103c1b06f0cfc560c003a5c41/go/grpcweb/wrapper.go#L231\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport const headerXGrpcWeb = \"X-Grpc-Web\";\n","// Copyright 2021-2025 The Connect Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n/**\n * Regular Expression that matches any valid gRPC-web Content-Type header value.\n * Note that this includes application/grpc-web-text with the additional base64\n * encoding.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport const contentTypeRegExp = /^application\\/grpc-web(-text)?(?:\\+(?:(json)(?:; ?charset=utf-?8)?|proto))?$/i;\nexport const contentTypeProto = \"application/grpc-web+proto\";\nexport const contentTypeJson = \"application/grpc-web+json\";\n/**\n * Parse a gRPC-web Content-Type header value.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function parseContentType(contentType) {\n    const match = contentType === null || contentType === void 0 ? void 0 : contentType.match(contentTypeRegExp);\n    if (!match) {\n        return undefined;\n    }\n    const text = !!match[1];\n    const binary = !match[2];\n    return { text, binary };\n}\n","// Copyright 2021-2025 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n/**\n * Hydrate a service descriptor.\n *\n * @private\n */\nexport function serviceDesc(file, path, ...paths) {\n    if (paths.length > 0) {\n        throw new Error();\n    }\n    return file.services[path];\n}\n","// Copyright 2021-2025 The Connect Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { fileDesc, messageDesc } from \"@bufbuild/protobuf/codegenv2\";\nimport { file_google_protobuf_any } from \"@bufbuild/protobuf/wkt\";\n/**\n * Describes the file status.proto.\n */\nexport const file_status = /*@__PURE__*/ fileDesc(\"CgxzdGF0dXMucHJvdG8SCmdvb2dsZS5ycGMiTgoGU3RhdHVzEgwKBGNvZGUYASABKAUSDwoHbWVzc2FnZRgCIAEoCRIlCgdkZXRhaWxzGAMgAygLMhQuZ29vZ2xlLnByb3RvYnVmLkFueUJeCg5jb20uZ29vZ2xlLnJwY0ILU3RhdHVzUHJvdG9QAVo3Z29vZ2xlLmdvbGFuZy5vcmcvZ2VucHJvdG8vZ29vZ2xlYXBpcy9ycGMvc3RhdHVzO3N0YXR1c6ICA1JQQ2IGcHJvdG8z\", [file_google_protobuf_any]);\n/**\n * Describes the message google.rpc.Status.\n * Use `create(StatusSchema)` to create a new message.\n */\nexport const StatusSchema = /*@__PURE__*/ messageDesc(file_status, 0);\n","// Copyright 2021-2025 The Connect Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { StatusSchema } from \"./gen/status_pb.js\";\nimport { ConnectError } from \"../connect-error.js\";\nimport { decodeBinaryHeader, encodeBinaryHeader } from \"../http-headers.js\";\nimport { Code } from \"../code.js\";\nimport { anyPack } from \"@bufbuild/protobuf/wkt\";\nimport { headerGrpcMessage, headerGrpcStatus, headerStatusDetailsBin, } from \"./headers.js\";\nimport { create } from \"@bufbuild/protobuf\";\n/**\n * The value of the Grpc-Status header or trailer in case of success.\n * Used by the gRPC and gRPC-web protocols.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport const grpcStatusOk = \"0\";\n/**\n * Sets the fields \"grpc-status\" and \"grpc-message\" in the given\n * Headers object.\n * If an error is given and contains error details, the function\n * will also set the field \"grpc-status-details-bin\" with an encoded\n * google.rpc.Status message including the error details.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function setTrailerStatus(target, error) {\n    if (error) {\n        // Copy any metadata specified in the error into the target Headers\n        // Note that if a protocol header happens to be specified in metadata, it\n        // its value will be overridden below by the official protocol headers.\n        error.metadata.forEach((value, key) => {\n            target.append(key, value);\n        });\n        target.set(headerGrpcStatus, error.code.toString(10));\n        target.set(headerGrpcMessage, encodeURIComponent(error.rawMessage));\n        if (error.details.length > 0) {\n            const status = create(StatusSchema, {\n                code: error.code,\n                message: error.rawMessage,\n                details: error.details.map((detail) => \"desc\" in detail\n                    ? anyPack(detail.desc, create(detail.desc, detail.value))\n                    : {\n                        typeUrl: `type.googleapis.com/${detail.type}`,\n                        value: detail.value,\n                    }),\n            });\n            target.set(headerStatusDetailsBin, encodeBinaryHeader(status, StatusSchema));\n        }\n    }\n    else {\n        target.set(headerGrpcStatus, grpcStatusOk.toString());\n    }\n    return target;\n}\n/**\n * Find an error status in the given Headers object, which can be either\n * a trailer, or a header (as allowed for so-called trailers-only responses).\n * The field \"grpc-status-details-bin\" is inspected, and if not present,\n * the fields \"grpc-status\" and \"grpc-message\" are used.\n * Returns an error only if the gRPC status code is > 0.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function findTrailerError(headerOrTrailer) {\n    // TODO\n    // let code: Code;\n    // let message: string = \"\";\n    var _a;\n    // Prefer the protobuf-encoded data to the grpc-status header.\n    const statusBytes = headerOrTrailer.get(headerStatusDetailsBin);\n    if (statusBytes != null) {\n        const status = decodeBinaryHeader(statusBytes, StatusSchema);\n        if (status.code == 0) {\n            return undefined;\n        }\n        const error = new ConnectError(status.message, status.code, headerOrTrailer);\n        error.details = status.details.map((any) => ({\n            type: any.typeUrl.substring(any.typeUrl.lastIndexOf(\"/\") + 1),\n            value: any.value,\n        }));\n        return error;\n    }\n    const grpcStatus = headerOrTrailer.get(headerGrpcStatus);\n    if (grpcStatus != null) {\n        if (grpcStatus === grpcStatusOk) {\n            return undefined;\n        }\n        const code = parseInt(grpcStatus, 10);\n        if (code in Code) {\n            return new ConnectError(decodeURIComponent((_a = headerOrTrailer.get(headerGrpcMessage)) !== null && _a !== void 0 ? _a : \"\"), code, headerOrTrailer);\n        }\n        return new ConnectError(`invalid grpc-status: ${grpcStatus}`, Code.Internal, headerOrTrailer);\n    }\n    return undefined;\n}\n","// Copyright 2021-2025 The Connect Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n/**\n * Create a URL for the given RPC. This simply adds the qualified\n * service name, a slash, and the method name to the path of the given\n * baseUrl.\n *\n * For example, the baseUri https://example.com and method \"Say\" from\n * the service example.ElizaService results in:\n * https://example.com/example.ElizaService/Say\n *\n * This format is used by the protocols Connect, gRPC and Twirp.\n *\n * Note that this function also accepts a protocol-relative baseUrl.\n * If given an empty string or \"/\" as a baseUrl, it returns just the\n * path.\n */\nexport function createMethodUrl(baseUrl, method) {\n    return baseUrl\n        .toString()\n        .replace(/\\/?$/, `/${method.parent.typeName}/${method.name}`);\n}\n","// Copyright 2021-2025 The Connect Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { create } from \"@bufbuild/protobuf\";\n/**\n *  Takes a partial protobuf messages of the\n *  specified message type as input, and returns full instances.\n */\nexport function normalize(desc, message) {\n    return create(desc, message);\n}\n/**\n * Takes an AsyncIterable of partial protobuf messages of the\n * specified message type as input, and yields full instances.\n */\nexport function normalizeIterable(desc, input) {\n    function transform(result) {\n        if (result.done === true) {\n            return result;\n        }\n        return {\n            done: result.done,\n            value: normalize(desc, result.value),\n        };\n    }\n    return {\n        [Symbol.asyncIterator]() {\n            const it = input[Symbol.asyncIterator]();\n            const res = {\n                next: () => it.next().then(transform),\n            };\n            if (it.throw !== undefined) {\n                res.throw = (e) => it.throw(e).then(transform);\n            }\n            if (it.return !== undefined) {\n                res.return = (v) => it.return(v).then(transform);\n            }\n            return res;\n        },\n    };\n}\n","// Copyright 2021-2025 The Connect Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n/**\n * applyInterceptors takes the given UnaryFn or ServerStreamingFn, and wraps\n * it with each of the given interceptors, returning a new UnaryFn or\n * ServerStreamingFn.\n */\nexport function applyInterceptors(next, interceptors) {\n    if (!interceptors) {\n        return next;\n    }\n    for (const i of interceptors.concat().reverse()) {\n        next = i(next);\n    }\n    return next;\n}\n","// Copyright 2021-2025 The Connect Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { fromBinary, fromJsonString, toBinary, toJsonString, } from \"@bufbuild/protobuf\";\nimport { ConnectError } from \"../connect-error.js\";\nimport { Code } from \"../code.js\";\nimport { assertReadMaxBytes, assertWriteMaxBytes } from \"./limit-io.js\";\n/**\n * Sets default JSON serialization options for connect-es.\n *\n * With standard protobuf JSON serialization, unknown JSON fields are\n * rejected by default. In connect-es, unknown JSON fields are ignored\n * by default.\n */\nexport function getJsonOptions(options) {\n    var _a;\n    const o = Object.assign({}, options);\n    (_a = o.ignoreUnknownFields) !== null && _a !== void 0 ? _a : (o.ignoreUnknownFields = true);\n    return o;\n}\n/**\n * Create an object that provides convenient access to request and response\n * message serialization for a given method.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function createMethodSerializationLookup(method, binaryOptions, jsonOptions, limitOptions) {\n    const inputBinary = limitSerialization(createBinarySerialization(method.input, binaryOptions), limitOptions);\n    const inputJson = limitSerialization(createJsonSerialization(method.input, jsonOptions), limitOptions);\n    const outputBinary = limitSerialization(createBinarySerialization(method.output, binaryOptions), limitOptions);\n    const outputJson = limitSerialization(createJsonSerialization(method.output, jsonOptions), limitOptions);\n    return {\n        getI(useBinaryFormat) {\n            return useBinaryFormat ? inputBinary : inputJson;\n        },\n        getO(useBinaryFormat) {\n            return useBinaryFormat ? outputBinary : outputJson;\n        },\n    };\n}\n/**\n * Returns functions to normalize and serialize the input message\n * of an RPC, and to parse the output message of an RPC.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function createClientMethodSerializers(method, useBinaryFormat, jsonOptions, binaryOptions) {\n    const input = useBinaryFormat\n        ? createBinarySerialization(method.input, binaryOptions)\n        : createJsonSerialization(method.input, jsonOptions);\n    const output = useBinaryFormat\n        ? createBinarySerialization(method.output, binaryOptions)\n        : createJsonSerialization(method.output, jsonOptions);\n    return { parse: output.parse, serialize: input.serialize };\n}\n/**\n * Apply I/O limits to a Serialization object, returning a new object.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function limitSerialization(serialization, limitOptions) {\n    return {\n        serialize(data) {\n            const bytes = serialization.serialize(data);\n            assertWriteMaxBytes(limitOptions.writeMaxBytes, bytes.byteLength);\n            return bytes;\n        },\n        parse(data) {\n            assertReadMaxBytes(limitOptions.readMaxBytes, data.byteLength, true);\n            return serialization.parse(data);\n        },\n    };\n}\n/**\n * Creates a Serialization object for serializing the given protobuf message\n * with the protobuf binary format.\n */\nexport function createBinarySerialization(desc, options) {\n    return {\n        parse(data) {\n            try {\n                return fromBinary(desc, data, options);\n            }\n            catch (e) {\n                const m = e instanceof Error ? e.message : String(e);\n                throw new ConnectError(`parse binary: ${m}`, Code.Internal);\n            }\n        },\n        serialize(data) {\n            try {\n                return toBinary(desc, data, options);\n            }\n            catch (e) {\n                const m = e instanceof Error ? e.message : String(e);\n                throw new ConnectError(`serialize binary: ${m}`, Code.Internal);\n            }\n        },\n    };\n}\n/**\n * Creates a Serialization object for serializing the given protobuf message\n * with the protobuf canonical JSON encoding.\n *\n * By default, unknown fields are ignored.\n */\nexport function createJsonSerialization(desc, options) {\n    var _a, _b;\n    const textEncoder = (_a = options === null || options === void 0 ? void 0 : options.textEncoder) !== null && _a !== void 0 ? _a : new TextEncoder();\n    const textDecoder = (_b = options === null || options === void 0 ? void 0 : options.textDecoder) !== null && _b !== void 0 ? _b : new TextDecoder();\n    const o = getJsonOptions(options);\n    return {\n        parse(data) {\n            try {\n                const json = textDecoder.decode(data);\n                return fromJsonString(desc, json, o);\n            }\n            catch (e) {\n                throw ConnectError.from(e, Code.InvalidArgument);\n            }\n        },\n        serialize(data) {\n            try {\n                const json = toJsonString(desc, data, o);\n                return textEncoder.encode(json);\n            }\n            catch (e) {\n                throw ConnectError.from(e, Code.Internal);\n            }\n        },\n    };\n}\n","// Copyright 2021-2025 The Connect Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n/**\n * Regular Expression that matches any valid Connect Content-Type header value.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport const contentTypeRegExp = /^application\\/(connect\\+)?(?:(json)(?:; ?charset=utf-?8)?|(proto))$/i;\n/**\n * Regular Expression that matches a Connect unary Content-Type header value.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport const contentTypeUnaryRegExp = /^application\\/(?:json(?:; ?charset=utf-?8)?|proto)$/i;\n/**\n * Regular Expression that matches a Connect streaming Content-Type header value.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport const contentTypeStreamRegExp = /^application\\/connect\\+?(?:json(?:; ?charset=utf-?8)?|proto)$/i;\nexport const contentTypeUnaryProto = \"application/proto\";\nexport const contentTypeUnaryJson = \"application/json\";\nexport const contentTypeStreamProto = \"application/connect+proto\";\nexport const contentTypeStreamJson = \"application/connect+json\";\nconst encodingProto = \"proto\";\nconst encodingJson = \"json\";\n/**\n * Parse a Connect Content-Type header.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function parseContentType(contentType) {\n    const match = contentType === null || contentType === void 0 ? void 0 : contentType.match(contentTypeRegExp);\n    if (!match) {\n        return undefined;\n    }\n    const stream = !!match[1];\n    const binary = !!match[3];\n    return { stream, binary };\n}\n/**\n * Parse a Connect Get encoding query parameter.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function parseEncodingQuery(encoding) {\n    switch (encoding) {\n        case encodingProto:\n            return { stream: false, binary: true };\n        case encodingJson:\n            return { stream: false, binary: false };\n        default:\n            return undefined;\n    }\n}\n","// Copyright 2021-2025 The Connect Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nvar __rest = (this && this.__rest) || function (s, e) {\n    var t = {};\n    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n        t[p] = s[p];\n    if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n                t[p[i]] = s[p[i]];\n        }\n    return t;\n};\nimport { base64Decode, base64Encode } from \"@bufbuild/protobuf/wire\";\nimport { create, toBinary, toJson } from \"@bufbuild/protobuf\";\nimport { Code } from \"../code.js\";\nimport { ConnectError } from \"../connect-error.js\";\nimport { codeFromString, codeToString } from \"./code-string.js\";\n/**\n * Parse a Connect error from a JSON value.\n * Will return a ConnectError, and throw the provided fallback if parsing failed.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function errorFromJson(jsonValue, metadata, fallback) {\n    var _a;\n    if (metadata) {\n        new Headers(metadata).forEach((value, key) => fallback.metadata.append(key, value));\n    }\n    if (typeof jsonValue !== \"object\" ||\n        jsonValue == null ||\n        Array.isArray(jsonValue)) {\n        throw fallback;\n    }\n    let code = fallback.code;\n    if (\"code\" in jsonValue && typeof jsonValue.code === \"string\") {\n        code = (_a = codeFromString(jsonValue.code)) !== null && _a !== void 0 ? _a : code;\n    }\n    const message = jsonValue.message;\n    if (message != null && typeof message !== \"string\") {\n        throw fallback;\n    }\n    const error = new ConnectError(message !== null && message !== void 0 ? message : \"\", code, metadata);\n    if (\"details\" in jsonValue && Array.isArray(jsonValue.details)) {\n        for (const detail of jsonValue.details) {\n            if (detail === null ||\n                typeof detail != \"object\" ||\n                Array.isArray(detail) ||\n                typeof detail.type != \"string\" ||\n                typeof detail.value != \"string\") {\n                throw fallback;\n            }\n            try {\n                error.details.push({\n                    type: detail.type,\n                    value: base64Decode(detail.value),\n                    debug: detail.debug,\n                });\n            }\n            catch (e) {\n                throw fallback;\n            }\n        }\n    }\n    return error;\n}\n/**\n * Parse a Connect error from a serialized JSON value.\n * Will return a ConnectError, and throw the provided fallback if parsing failed.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function errorFromJsonBytes(bytes, metadata, fallback) {\n    let jsonValue;\n    try {\n        jsonValue = JSON.parse(new TextDecoder().decode(bytes));\n    }\n    catch (e) {\n        throw fallback;\n    }\n    return errorFromJson(jsonValue, metadata, fallback);\n}\n/**\n * Serialize the given error to JSON.\n *\n * The JSON serialization options are required to produce the optional\n * human-readable representation in the \"debug\" key if the detail uses\n * google.protobuf.Any. If serialization of the \"debug\" value fails, it\n * is silently disregarded.\n *\n * See https://connectrpc.com/docs/protocol#error-end-stream\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function errorToJson(error, jsonWriteOptions) {\n    const o = {\n        code: codeToString(error.code),\n    };\n    if (error.rawMessage.length > 0) {\n        o.message = error.rawMessage;\n    }\n    if (error.details.length > 0) {\n        o.details = error.details\n            .map((detail) => {\n            if (\"desc\" in detail) {\n                const msg = create(detail.desc, detail.value);\n                const i = {\n                    type: detail.desc.typeName,\n                    value: toBinary(detail.desc, msg),\n                };\n                try {\n                    i.debug = toJson(detail.desc, msg, jsonWriteOptions);\n                }\n                catch (e) {\n                    // We deliberately ignore errors that may occur when serializing\n                    // a message to JSON (the message contains an Any).\n                    // The rationale is that we are only trying to provide optional\n                    // debug information.\n                }\n                return i;\n            }\n            return detail;\n        })\n            .map((_a) => {\n            var { value } = _a, rest = __rest(_a, [\"value\"]);\n            return (Object.assign(Object.assign({}, rest), { value: base64Encode(value, \"std_raw\") }));\n        });\n    }\n    return o;\n}\n/**\n * Serialize the given error to JSON. This calls errorToJson(), but stringifies\n * the result, and converts it into a UInt8Array.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function errorToJsonBytes(error, jsonWriteOptions) {\n    const textEncoder = new TextEncoder();\n    try {\n        const jsonObject = errorToJson(error, jsonWriteOptions);\n        const jsonString = JSON.stringify(jsonObject);\n        return textEncoder.encode(jsonString);\n    }\n    catch (e) {\n        const m = e instanceof Error ? e.message : String(e);\n        throw new ConnectError(`failed to serialize Connect Error: ${m}`, Code.Internal);\n    }\n}\n","// Copyright 2021-2025 The Connect Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { errorFromJson, errorToJson } from \"./error-json.js\";\nimport { appendHeaders } from \"../http-headers.js\";\nimport { ConnectError } from \"../connect-error.js\";\nimport { Code } from \"../code.js\";\n/**\n * endStreamFlag indicates that the data in a EnvelopedMessage\n * is a EndStreamResponse of the Connect protocol.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport const endStreamFlag = 0b00000010;\n/**\n * Parse an EndStreamResponse of the Connect protocol.\n * Throws a ConnectError on malformed input.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function endStreamFromJson(data) {\n    const parseErr = new ConnectError(\"invalid end stream\", Code.Unknown);\n    let jsonValue;\n    try {\n        // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n        jsonValue = JSON.parse(typeof data == \"string\" ? data : new TextDecoder().decode(data));\n    }\n    catch (e) {\n        throw parseErr;\n    }\n    if (typeof jsonValue != \"object\" ||\n        jsonValue == null ||\n        Array.isArray(jsonValue)) {\n        throw parseErr;\n    }\n    const metadata = new Headers();\n    if (\"metadata\" in jsonValue) {\n        if (typeof jsonValue.metadata != \"object\" ||\n            jsonValue.metadata == null ||\n            Array.isArray(jsonValue.metadata)) {\n            throw parseErr;\n        }\n        for (const [key, values] of Object.entries(jsonValue.metadata)) {\n            if (!Array.isArray(values) ||\n                values.some((value) => typeof value != \"string\")) {\n                throw parseErr;\n            }\n            for (const value of values) {\n                metadata.append(key, value);\n            }\n        }\n    }\n    const error = \"error\" in jsonValue && jsonValue.error != null\n        ? errorFromJson(jsonValue.error, metadata, parseErr)\n        : undefined;\n    return { metadata, error };\n}\n/**\n * Serialize the given EndStreamResponse to JSON.\n *\n * The JSON serialization options are required to produce the optional\n * human-readable representation of error details if the detail uses\n * google.protobuf.Any.\n *\n * See https://connectrpc.com/docs/protocol#error-end-stream\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function endStreamToJson(metadata, error, jsonWriteOptions) {\n    const es = {};\n    if (error !== undefined) {\n        es.error = errorToJson(error, jsonWriteOptions);\n        metadata = appendHeaders(metadata, error.metadata);\n    }\n    let hasMetadata = false;\n    const md = {};\n    metadata.forEach((value, key) => {\n        hasMetadata = true;\n        md[key] = [value];\n    });\n    // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n    if (hasMetadata) {\n        es.metadata = md;\n    }\n    return es;\n}\n/**\n * Create a Serialization object that serializes a Connect EndStreamResponse.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function createEndStreamSerialization(options) {\n    const textEncoder = new TextEncoder();\n    return {\n        serialize(data) {\n            try {\n                const jsonObject = endStreamToJson(data.metadata, data.error, options);\n                const jsonString = JSON.stringify(jsonObject);\n                return textEncoder.encode(jsonString);\n            }\n            catch (e) {\n                const m = e instanceof Error ? e.message : String(e);\n                throw new ConnectError(`failed to serialize EndStreamResponse: ${m}`, Code.Internal);\n            }\n        },\n        parse(data) {\n            try {\n                return endStreamFromJson(data);\n            }\n            catch (e) {\n                const m = e instanceof Error ? e.message : String(e);\n                throw new ConnectError(`failed to parse EndStreamResponse: ${m}`, Code.InvalidArgument);\n            }\n        },\n    };\n}\n","// Copyright 2021-2025 The Connect Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n/**\n * @private Internal code, does not follow semantic versioning.\n */\nexport const headerContentType = \"Content-Type\";\nexport const headerUnaryContentLength = \"Content-Length\";\nexport const headerUnaryEncoding = \"Content-Encoding\";\nexport const headerStreamEncoding = \"Connect-Content-Encoding\";\nexport const headerUnaryAcceptEncoding = \"Accept-Encoding\";\nexport const headerStreamAcceptEncoding = \"Connect-Accept-Encoding\";\nexport const headerTimeout = \"Connect-Timeout-Ms\";\nexport const headerProtocolVersion = \"Connect-Protocol-Version\";\nexport const headerUserAgent = \"User-Agent\";\n","// Copyright 2021-2025 The Connect Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { Code } from \"../code.js\";\n/**\n * Determine the Connect error code for the given HTTP status code.\n * See https://connectrpc.com/docs/protocol/#http-to-error-code\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function codeFromHttpStatus(httpStatus) {\n    switch (httpStatus) {\n        case 400: // Bad Request\n            return Code.Internal;\n        case 401: // Unauthorized\n            return Code.Unauthenticated;\n        case 403: // Forbidden\n            return Code.PermissionDenied;\n        case 404: // Not Found\n            return Code.Unimplemented;\n        case 429: // Too Many Requests\n            return Code.Unavailable;\n        case 502: // Bad Gateway\n            return Code.Unavailable;\n        case 503: // Service Unavailable\n            return Code.Unavailable;\n        case 504: // Gateway Timeout\n            return Code.Unavailable;\n        default:\n            return Code.Unknown;\n    }\n}\n/**\n * Returns a HTTP status code for the given Connect code.\n * See https://connectrpc.com/docs/protocol#error-codes\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function codeToHttpStatus(code) {\n    switch (code) {\n        case Code.Canceled:\n            return 499; // Client Closed Request\n        case Code.Unknown:\n            return 500; // Internal Server Error\n        case Code.InvalidArgument:\n            return 400; // Bad Request\n        case Code.DeadlineExceeded:\n            return 504; // Gateway Timeout\n        case Code.NotFound:\n            return 404; // Not Found\n        case Code.AlreadyExists:\n            return 409; // Conflict\n        case Code.PermissionDenied:\n            return 403; // Forbidden\n        case Code.ResourceExhausted:\n            return 429; // Too Many Requests\n        case Code.FailedPrecondition:\n            return 400; // Bad Request\n        case Code.Aborted:\n            return 409; // Conflict\n        case Code.OutOfRange:\n            return 400; // Bad Request\n        case Code.Unimplemented:\n            return 501; // Not Implemented\n        case Code.Internal:\n            return 500; // Internal Server Error\n        case Code.Unavailable:\n            return 503; // Service Unavailable\n        case Code.DataLoss:\n            return 500; // Internal Server Error\n        case Code.Unauthenticated:\n            return 401; // Unauthorized\n        default:\n            return 500; // same as CodeUnknown\n    }\n}\n","// Copyright 2021-2025 The Connect Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n/**\n * In unary RPCs, Connect transports trailing metadata as response header\n * fields, prefixed with \"trailer-\".\n *\n * This function demuxes headers and trailers into two separate Headers\n * objects.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function trailerDemux(header) {\n    const h = new Headers(), t = new Headers();\n    header.forEach((value, key) => {\n        if (key.toLowerCase().startsWith(\"trailer-\")) {\n            t.append(key.substring(8), value);\n        }\n        else {\n            h.append(key, value);\n        }\n    });\n    return [h, t];\n}\n/**\n * In unary RPCs, Connect transports trailing metadata as response header\n * fields, prefixed with \"trailer-\".\n *\n * This function muxes a header and a trailer into a single Headers object.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function trailerMux(header, trailer) {\n    const h = new Headers(header);\n    trailer.forEach((value, key) => {\n        h.append(`trailer-${key}`, value);\n    });\n    return h;\n}\n","// Copyright 2021-2025 The Connect Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { headerProtocolVersion } from \"./headers.js\";\nimport { paramConnectVersion } from \"./query-params.js\";\nimport { ConnectError } from \"../connect-error.js\";\nimport { Code } from \"../code.js\";\n/**\n * The only know value for the header Connect-Protocol-Version.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport const protocolVersion = \"1\";\n/**\n * Requires the Connect-Protocol-Version header to be present with the expected\n * value. Raises a ConnectError with Code.InvalidArgument otherwise.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function requireProtocolVersionHeader(requestHeader) {\n    const v = requestHeader.get(headerProtocolVersion);\n    if (v === null) {\n        throw new ConnectError(`missing required header: set ${headerProtocolVersion} to \"${protocolVersion}\"`, Code.InvalidArgument);\n    }\n    if (v !== protocolVersion) {\n        throw new ConnectError(`${headerProtocolVersion} must be \"${protocolVersion}\": got \"${v}\"`, Code.InvalidArgument);\n    }\n}\n/**\n * Requires the connect query parameter to be present with the expected value.\n * Raises a ConnectError with Code.InvalidArgument otherwise.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function requireProtocolVersionParam(queryParams) {\n    const v = queryParams.get(paramConnectVersion);\n    if (v === null) {\n        throw new ConnectError(`missing required parameter: set ${paramConnectVersion} to \"v${protocolVersion}\"`, Code.InvalidArgument);\n    }\n    if (v !== `v${protocolVersion}`) {\n        throw new ConnectError(`${paramConnectVersion} must be \"v${protocolVersion}\": got \"${v}\"`, Code.InvalidArgument);\n    }\n}\n","// Copyright 2021-2025 The Connect Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { headerContentType, headerStreamAcceptEncoding, headerStreamEncoding, headerUnaryAcceptEncoding, headerUnaryEncoding, headerTimeout, headerProtocolVersion, headerUserAgent, } from \"./headers.js\";\nimport { protocolVersion } from \"./version.js\";\nimport { contentTypeStreamJson, contentTypeStreamProto, contentTypeUnaryJson, contentTypeUnaryProto, } from \"./content-type.js\";\n/**\n * Creates headers for a Connect request.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function requestHeader(methodKind, useBinaryFormat, timeoutMs, userProvidedHeaders, setUserAgent) {\n    const result = new Headers(userProvidedHeaders !== null && userProvidedHeaders !== void 0 ? userProvidedHeaders : {});\n    if (timeoutMs !== undefined) {\n        result.set(headerTimeout, `${timeoutMs}`);\n    }\n    result.set(headerContentType, methodKind == \"unary\"\n        ? useBinaryFormat\n            ? contentTypeUnaryProto\n            : contentTypeUnaryJson\n        : useBinaryFormat\n            ? contentTypeStreamProto\n            : contentTypeStreamJson);\n    result.set(headerProtocolVersion, protocolVersion);\n    if (!result.has(headerUserAgent) && setUserAgent) {\n        // Note that we do not strictly comply with gRPC user agents.\n        // We use \"connect-es/1.2.3\" where gRPC would use \"grpc-es/1.2.3\".\n        // See https://github.com/grpc/grpc/blob/c462bb8d485fc1434ecfae438823ca8d14cf3154/doc/PROTOCOL-HTTP2.md#user-agents\n        result.set(headerUserAgent, \"connect-es/2.1.1\");\n    }\n    return result;\n}\n/**\n * Creates headers for a Connect request with compression.\n *\n * Note that we always set the Content-Encoding header for unary methods.\n * It is up to the caller to decide whether to apply compression - and remove\n * the header if compression is not used, for example because the payload is\n * too small to make compression effective.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function requestHeaderWithCompression(methodKind, useBinaryFormat, timeoutMs, userProvidedHeaders, acceptCompression, sendCompression, setUserAgent) {\n    const result = requestHeader(methodKind, useBinaryFormat, timeoutMs, userProvidedHeaders, setUserAgent);\n    if (sendCompression != null) {\n        const name = methodKind == \"unary\" ? headerUnaryEncoding : headerStreamEncoding;\n        result.set(name, sendCompression.name);\n    }\n    if (acceptCompression.length > 0) {\n        const name = methodKind == \"unary\"\n            ? headerUnaryAcceptEncoding\n            : headerStreamAcceptEncoding;\n        result.set(name, acceptCompression.map((c) => c.name).join(\",\"));\n    }\n    return result;\n}\n","// Copyright 2021-2025 The Connect Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { Code } from \"../code.js\";\nimport { codeFromHttpStatus } from \"./http-status.js\";\nimport { ConnectError } from \"../connect-error.js\";\nimport { parseContentType } from \"./content-type.js\";\nimport { headerContentType, headerStreamEncoding, headerUnaryEncoding, } from \"./headers.js\";\n/**\n * Validates response status and header for the Connect protocol.\n * Throws a ConnectError if the header indicates an error, or if\n * the content type is unexpected, with the following exception:\n * For unary RPCs with an HTTP error status, this returns an error\n * derived from the HTTP status instead of throwing it, giving an\n * implementation a chance to parse a Connect error from the wire.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function validateResponse(methodKind, useBinaryFormat, status, headers) {\n    const mimeType = headers.get(headerContentType);\n    const parsedType = parseContentType(mimeType);\n    if (status !== 200) {\n        const errorFromStatus = new ConnectError(`HTTP ${status}`, codeFromHttpStatus(status), headers);\n        // If parsedType is defined and it is not binary, then this is a unary JSON response\n        if (methodKind == \"unary\" && parsedType && !parsedType.binary) {\n            return { isUnaryError: true, unaryError: errorFromStatus };\n        }\n        throw errorFromStatus;\n    }\n    const allowedContentType = {\n        binary: useBinaryFormat,\n        stream: methodKind !== \"unary\",\n    };\n    if ((parsedType === null || parsedType === void 0 ? void 0 : parsedType.binary) !== allowedContentType.binary ||\n        parsedType.stream !== allowedContentType.stream) {\n        throw new ConnectError(`unsupported content type ${mimeType}`, parsedType === undefined ? Code.Unknown : Code.Internal, headers);\n    }\n    return { isUnaryError: false };\n}\n/**\n * Validates response status and header for the Connect protocol.\n * This function is identical to validateResponse(), but also verifies\n * that a given encoding header is acceptable.\n *\n * @private\n */\nexport function validateResponseWithCompression(methodKind, acceptCompression, useBinaryFormat, status, headers) {\n    let compression;\n    const encoding = headers.get(methodKind == \"unary\" ? headerUnaryEncoding : headerStreamEncoding);\n    if (encoding != null && encoding.toLowerCase() !== \"identity\") {\n        compression = acceptCompression.find((c) => c.name === encoding);\n        if (!compression) {\n            throw new ConnectError(`unsupported response encoding \"${encoding}\"`, Code.Internal, headers);\n        }\n    }\n    return Object.assign({ compression }, validateResponse(methodKind, useBinaryFormat, status, headers));\n}\n","// Copyright 2021-2025 The Connect Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { base64Encode } from \"@bufbuild/protobuf/wire\";\nimport { headerContentType, headerProtocolVersion, headerUnaryAcceptEncoding, headerUnaryContentLength, headerUnaryEncoding, } from \"./headers.js\";\nimport { protocolVersion } from \"./version.js\";\nconst contentTypePrefix = \"application/\";\nfunction encodeMessageForUrl(message, useBase64) {\n    if (useBase64) {\n        return base64Encode(message, \"url\");\n    }\n    return encodeURIComponent(new TextDecoder().decode(message));\n}\n/**\n * @private Internal code, does not follow semantic versioning.\n */\nexport function transformConnectPostToGetRequest(request, message, useBase64) {\n    let query = `?connect=v${protocolVersion}`;\n    const contentType = request.header.get(headerContentType);\n    if ((contentType === null || contentType === void 0 ? void 0 : contentType.indexOf(contentTypePrefix)) === 0) {\n        query +=\n            \"&encoding=\" +\n                encodeURIComponent(contentType.slice(contentTypePrefix.length));\n    }\n    const compression = request.header.get(headerUnaryEncoding);\n    if (compression !== null && compression !== \"identity\") {\n        query += \"&compression=\" + encodeURIComponent(compression);\n        // Force base64 for compressed payloads.\n        useBase64 = true;\n    }\n    if (useBase64) {\n        query += \"&base64=1\";\n    }\n    query += \"&message=\" + encodeMessageForUrl(message, useBase64);\n    const url = request.url + query;\n    const header = new Headers(request.header);\n    // Omit headers that are not used for unary GET requests.\n    for (const h of [\n        headerProtocolVersion,\n        headerContentType,\n        headerUnaryContentLength,\n        headerUnaryEncoding,\n        headerUnaryAcceptEncoding,\n    ]) {\n        header.delete(h);\n    }\n    return Object.assign(Object.assign({}, request), { requestMethod: \"GET\", url,\n        header });\n}\n","// Copyright 2021-2025 The Connect Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { applyInterceptors } from \"../interceptor.js\";\nimport { ConnectError } from \"../connect-error.js\";\nimport { createDeadlineSignal, createLinkedAbortController, getAbortSignalReason, } from \"./signals.js\";\nimport { normalize, normalizeIterable } from \"./normalize.js\";\n/**\n * Runs a unary method with the given interceptors. Note that this function\n * is only used when implementing a Transport.\n */\nexport function runUnaryCall(opt) {\n    const next = applyInterceptors(opt.next, opt.interceptors);\n    const [signal, abort, done] = setupSignal(opt);\n    const req = Object.assign(Object.assign({}, opt.req), { message: normalize(opt.req.method.input, opt.req.message), signal });\n    return next(req).then((res) => {\n        done();\n        return res;\n    }, abort);\n}\n/**\n * Runs a server-streaming method with the given interceptors. Note that this\n * function is only used when implementing a Transport.\n */\nexport function runStreamingCall(opt) {\n    const next = applyInterceptors(opt.next, opt.interceptors);\n    const [signal, abort, done] = setupSignal(opt);\n    const req = Object.assign(Object.assign({}, opt.req), { message: normalizeIterable(opt.req.method.input, opt.req.message), signal });\n    let doneCalled = false;\n    // Call return on the request iterable to indicate\n    // that we will no longer consume it and it should\n    // cleanup any allocated resources.\n    signal.addEventListener(\"abort\", function () {\n        var _a, _b;\n        const it = opt.req.message[Symbol.asyncIterator]();\n        // If the signal is aborted due to an error, we want to throw\n        // the error to the request iterator.\n        if (!doneCalled) {\n            (_a = it.throw) === null || _a === void 0 ? void 0 : _a.call(it, this.reason).catch(() => {\n                // throw returns a promise, which we don't care about.\n                //\n                // Uncaught promises are thrown at sometime/somewhere by the event loop,\n                // this is to ensure error is caught and ignored.\n            });\n        }\n        (_b = it.return) === null || _b === void 0 ? void 0 : _b.call(it).catch(() => {\n            // return returns a promise, which we don't care about.\n            //\n            // Uncaught promises are thrown at sometime/somewhere by the event loop,\n            // this is to ensure error is caught and ignored.\n        });\n    });\n    return next(req).then((res) => {\n        return Object.assign(Object.assign({}, res), { message: {\n                [Symbol.asyncIterator]() {\n                    const it = res.message[Symbol.asyncIterator]();\n                    return {\n                        next() {\n                            return it.next().then((r) => {\n                                if (r.done == true) {\n                                    doneCalled = true;\n                                    done();\n                                }\n                                return r;\n                            }, abort);\n                        },\n                        // We deliberately omit throw/return.\n                    };\n                },\n            } });\n    }, abort);\n}\n/**\n * Create an AbortSignal for Transport implementations. The signal is available\n * in UnaryRequest and StreamingRequest, and is triggered when the call is\n * aborted (via a timeout or explicit cancellation), errored (e.g. when reading\n * an error from the server from the wire), or finished successfully.\n *\n * Transport implementations can pass the signal to HTTP clients to ensure that\n * there are no unused connections leak.\n *\n * Returns a tuple:\n * [0]: The signal, which is also aborted if the optional deadline is reached.\n * [1]: Function to call if the Transport encountered an error.\n * [2]: Function to call if the Transport finished without an error.\n */\nfunction setupSignal(opt) {\n    const { signal, cleanup } = createDeadlineSignal(opt.timeoutMs);\n    const controller = createLinkedAbortController(opt.signal, signal);\n    return [\n        controller.signal,\n        function abort(reason) {\n            // We peek at the deadline signal because fetch() will throw an error on\n            // abort that discards the signal reason.\n            const e = ConnectError.from(signal.aborted ? getAbortSignalReason(signal) : reason);\n            controller.abort(e);\n            cleanup();\n            return Promise.reject(e);\n        },\n        function done() {\n            cleanup();\n            controller.abort();\n        },\n    ];\n}\n","// Copyright 2021-2025 The Connect Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n/**\n * Asserts that the fetch API is available.\n */\nexport function assertFetchApi() {\n    try {\n        new Headers();\n    }\n    catch (_) {\n        throw new Error(\"connect-web requires the fetch API. Are you running on an old version of Node.js? Node.js is not supported in Connect for Web - please stay tuned for Connect for Node.\");\n    }\n}\n","// Copyright 2021-2025 The Connect Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nvar __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }\nvar __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n    if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n    var g = generator.apply(thisArg, _arguments || []), i, q = [];\n    return i = Object.create((typeof AsyncIterator === \"function\" ? AsyncIterator : Object).prototype), verb(\"next\"), verb(\"throw\"), verb(\"return\", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;\n    function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }\n    function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }\n    function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n    function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n    function fulfill(value) { resume(\"next\", value); }\n    function reject(value) { resume(\"throw\", value); }\n    function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n};\nimport { fromJson } from \"@bufbuild/protobuf\";\nimport { Code, ConnectError, appendHeaders, createContextValues, } from \"@connectrpc/connect\";\nimport { createClientMethodSerializers, createEnvelopeReadableStream, createMethodUrl, getJsonOptions, encodeEnvelope, runStreamingCall, runUnaryCall, compressedFlag, } from \"@connectrpc/connect/protocol\";\nimport { endStreamFlag, endStreamFromJson, errorFromJson, requestHeader, trailerDemux, transformConnectPostToGetRequest, validateResponse, } from \"@connectrpc/connect/protocol-connect\";\nimport { assertFetchApi } from \"./assert-fetch-api.js\";\nimport { MethodOptions_IdempotencyLevel } from \"@bufbuild/protobuf/wkt\";\nconst fetchOptions = {\n    redirect: \"error\",\n};\n/**\n * Create a Transport for the Connect protocol, which makes unary and\n * server-streaming methods available to web browsers. It uses the fetch\n * API to make HTTP requests.\n */\nexport function createConnectTransport(options) {\n    var _a;\n    assertFetchApi();\n    const useBinaryFormat = (_a = options.useBinaryFormat) !== null && _a !== void 0 ? _a : false;\n    return {\n        async unary(method, signal, timeoutMs, header, message, contextValues) {\n            const { serialize, parse } = createClientMethodSerializers(method, useBinaryFormat, options.jsonOptions, options.binaryOptions);\n            timeoutMs =\n                timeoutMs === undefined\n                    ? options.defaultTimeoutMs\n                    : timeoutMs <= 0\n                        ? undefined\n                        : timeoutMs;\n            return await runUnaryCall({\n                interceptors: options.interceptors,\n                signal,\n                timeoutMs,\n                req: {\n                    stream: false,\n                    service: method.parent,\n                    method,\n                    requestMethod: \"POST\",\n                    url: createMethodUrl(options.baseUrl, method),\n                    header: requestHeader(method.methodKind, useBinaryFormat, timeoutMs, header, false),\n                    contextValues: contextValues !== null && contextValues !== void 0 ? contextValues : createContextValues(),\n                    message,\n                },\n                next: async (req) => {\n                    var _a;\n                    const useGet = options.useHttpGet === true &&\n                        method.idempotency ===\n                            MethodOptions_IdempotencyLevel.NO_SIDE_EFFECTS;\n                    let body = null;\n                    if (useGet) {\n                        req = transformConnectPostToGetRequest(req, serialize(req.message), useBinaryFormat);\n                    }\n                    else {\n                        body = serialize(req.message);\n                    }\n                    const fetch = (_a = options.fetch) !== null && _a !== void 0 ? _a : globalThis.fetch;\n                    const response = await fetch(req.url, Object.assign(Object.assign({}, fetchOptions), { method: req.requestMethod, headers: req.header, signal: req.signal, body }));\n                    const { isUnaryError, unaryError } = validateResponse(method.methodKind, useBinaryFormat, response.status, response.headers);\n                    if (isUnaryError) {\n                        throw errorFromJson((await response.json()), appendHeaders(...trailerDemux(response.headers)), unaryError);\n                    }\n                    const [demuxedHeader, demuxedTrailer] = trailerDemux(response.headers);\n                    return {\n                        stream: false,\n                        service: method.parent,\n                        method,\n                        header: demuxedHeader,\n                        message: useBinaryFormat\n                            ? parse(new Uint8Array(await response.arrayBuffer()))\n                            : fromJson(method.output, (await response.json()), getJsonOptions(options.jsonOptions)),\n                        trailer: demuxedTrailer,\n                    };\n                },\n            });\n        },\n        async stream(method, signal, timeoutMs, header, input, contextValues) {\n            const { serialize, parse } = createClientMethodSerializers(method, useBinaryFormat, options.jsonOptions, options.binaryOptions);\n            function parseResponseBody(body, trailerTarget, header, signal) {\n                return __asyncGenerator(this, arguments, function* parseResponseBody_1() {\n                    const reader = createEnvelopeReadableStream(body).getReader();\n                    let endStreamReceived = false;\n                    for (;;) {\n                        const result = yield __await(reader.read());\n                        if (result.done) {\n                            break;\n                        }\n                        const { flags, data } = result.value;\n                        if ((flags & compressedFlag) === compressedFlag) {\n                            throw new ConnectError(`protocol error: received unsupported compressed output`, Code.Internal);\n                        }\n                        if ((flags & endStreamFlag) === endStreamFlag) {\n                            endStreamReceived = true;\n                            const endStream = endStreamFromJson(data);\n                            if (endStream.error) {\n                                const error = endStream.error;\n                                header.forEach((value, key) => {\n                                    error.metadata.append(key, value);\n                                });\n                                throw error;\n                            }\n                            endStream.metadata.forEach((value, key) => trailerTarget.set(key, value));\n                            continue;\n                        }\n                        yield yield __await(parse(data));\n                    }\n                    // Node wil not throw an AbortError on `read` if the\n                    // signal is aborted before `getReader` is called.\n                    // As a work around we check at the end and throw.\n                    //\n                    // Ref: https://github.com/nodejs/undici/issues/1940\n                    if (\"throwIfAborted\" in signal) {\n                        // We assume that implementations without `throwIfAborted` (old\n                        // browsers) do honor aborted signals on `read`.\n                        signal.throwIfAborted();\n                    }\n                    if (!endStreamReceived) {\n                        throw \"missing EndStreamResponse\";\n                    }\n                });\n            }\n            async function createRequestBody(input) {\n                if (method.methodKind != \"server_streaming\") {\n                    throw \"The fetch API does not support streaming request bodies\";\n                }\n                const r = await input[Symbol.asyncIterator]().next();\n                if (r.done == true) {\n                    throw \"missing request message\";\n                }\n                return encodeEnvelope(0, serialize(r.value));\n            }\n            timeoutMs =\n                timeoutMs === undefined\n                    ? options.defaultTimeoutMs\n                    : timeoutMs <= 0\n                        ? undefined\n                        : timeoutMs;\n            return await runStreamingCall({\n                interceptors: options.interceptors,\n                timeoutMs,\n                signal,\n                req: {\n                    stream: true,\n                    service: method.parent,\n                    method,\n                    requestMethod: \"POST\",\n                    url: createMethodUrl(options.baseUrl, method),\n                    header: requestHeader(method.methodKind, useBinaryFormat, timeoutMs, header, false),\n                    contextValues: contextValues !== null && contextValues !== void 0 ? contextValues : createContextValues(),\n                    message: input,\n                },\n                next: async (req) => {\n                    var _a;\n                    const fetch = (_a = options.fetch) !== null && _a !== void 0 ? _a : globalThis.fetch;\n                    const fRes = await fetch(req.url, Object.assign(Object.assign({}, fetchOptions), { method: req.requestMethod, headers: req.header, signal: req.signal, body: await createRequestBody(req.message) }));\n                    validateResponse(method.methodKind, useBinaryFormat, fRes.status, fRes.headers);\n                    if (fRes.body === null) {\n                        throw \"missing response body\";\n                    }\n                    const trailer = new Headers();\n                    const res = Object.assign(Object.assign({}, req), { header: fRes.headers, trailer, message: parseResponseBody(fRes.body, trailer, fRes.headers, req.signal) });\n                    return res;\n                },\n            });\n        },\n    };\n}\n","// Copyright 2021-2025 The Connect Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { Code } from \"../code.js\";\nimport { ConnectError } from \"../connect-error.js\";\nimport { headerGrpcStatus } from \"./headers.js\";\nimport { findTrailerError } from \"./trailer-status.js\";\n/**\n * Validates a trailer for the gRPC and the gRPC-web protocol.\n *\n * If the trailer contains an error status, a ConnectError is\n * thrown. It will include trailer and header in the error's\n * \"metadata\" property.\n *\n * Throws a ConnectError with code \"internal\" if neither the trailer\n * nor the header contain the Grpc-Status field.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function validateTrailer(trailer, header) {\n    const err = findTrailerError(trailer);\n    if (err) {\n        header.forEach((value, key) => {\n            err.metadata.append(key, value);\n        });\n        throw err;\n    }\n    if (!header.has(headerGrpcStatus) && !trailer.has(headerGrpcStatus)) {\n        throw new ConnectError(\"protocol error: missing status\", Code.Internal);\n    }\n}\n","// Copyright 2021-2025 The Connect Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { headerAcceptEncoding, headerContentType, headerEncoding, headerTimeout, headerXGrpcWeb, headerUserAgent, headerXUserAgent, } from \"./headers.js\";\nimport { contentTypeJson, contentTypeProto } from \"./content-type.js\";\n/**\n * Creates headers for a gRPC-web request.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function requestHeader(useBinaryFormat, timeoutMs, userProvidedHeaders, setUserAgent) {\n    var _a, _b;\n    const result = new Headers(userProvidedHeaders !== null && userProvidedHeaders !== void 0 ? userProvidedHeaders : {});\n    // Note that we do not support the grpc-web-text format.\n    // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-WEB.md#protocol-differences-vs-grpc-over-http2\n    result.set(headerContentType, useBinaryFormat ? contentTypeProto : contentTypeJson);\n    result.set(headerXGrpcWeb, \"1\");\n    // Note that we do not strictly comply with gRPC user agents.\n    // We use \"connect-es/1.2.3\" where gRPC would use \"grpc-es/1.2.3\".\n    // See https://github.com/grpc/grpc/blob/c462bb8d485fc1434ecfae438823ca8d14cf3154/doc/PROTOCOL-HTTP2.md#user-agents\n    const userAgent = (_b = (_a = result.get(headerUserAgent)) !== null && _a !== void 0 ? _a : result.get(headerXUserAgent)) !== null && _b !== void 0 ? _b : \"connect-es/2.1.1\";\n    result.set(headerXUserAgent, userAgent);\n    if (setUserAgent) {\n        result.set(headerUserAgent, userAgent);\n    }\n    if (timeoutMs !== undefined) {\n        result.set(headerTimeout, `${timeoutMs}m`);\n    }\n    return result;\n}\n/**\n * Creates headers for a gRPC-web request with compression.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function requestHeaderWithCompression(useBinaryFormat, timeoutMs, userProvidedHeaders, acceptCompression, sendCompression, setUserAgent) {\n    const result = requestHeader(useBinaryFormat, timeoutMs, userProvidedHeaders, setUserAgent);\n    if (sendCompression != null) {\n        result.set(headerEncoding, sendCompression.name);\n    }\n    if (acceptCompression.length > 0) {\n        result.set(headerAcceptEncoding, acceptCompression.map((c) => c.name).join(\",\"));\n    }\n    return result;\n}\n","// Copyright 2021-2025 The Connect Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { Code } from \"../code.js\";\n/**\n * Determine the gRPC-web error code for the given HTTP status code.\n * See https://github.com/grpc/grpc/blob/master/doc/http-grpc-status-mapping.md.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function codeFromHttpStatus(httpStatus) {\n    switch (httpStatus) {\n        case 400: // Bad Request\n            return Code.Internal;\n        case 401: // Unauthorized\n            return Code.Unauthenticated;\n        case 403: // Forbidden\n            return Code.PermissionDenied;\n        case 404: // Not Found\n            return Code.Unimplemented;\n        case 429: // Too Many Requests\n            return Code.Unavailable;\n        case 502: // Bad Gateway\n            return Code.Unavailable;\n        case 503: // Service Unavailable\n            return Code.Unavailable;\n        case 504: // Gateway Timeout\n            return Code.Unavailable;\n        default:\n            // 200 is UNKNOWN because there should be a grpc-status in case of truly OK response.\n            return Code.Unknown;\n    }\n}\n","// Copyright 2021-2025 The Connect Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { ConnectError } from \"../connect-error.js\";\nimport { Code } from \"../code.js\";\nimport { headerEncoding, headerGrpcMessage, headerGrpcStatus, } from \"./headers.js\";\nimport { codeFromHttpStatus } from \"../protocol-grpc/http-status.js\";\nimport { findTrailerError } from \"../protocol-grpc/trailer-status.js\";\n/**\n * Validates response status and header for the gRPC-web protocol.\n *\n * Throws a ConnectError if the header contains an error status,\n * or if the HTTP status indicates an error.\n *\n * Returns an object that indicates whether a gRPC status was found\n * in the response header. In this case, clients can not expect a\n * trailer.\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function validateResponse(status, headers) {\n    var _a;\n    // For compatibility with the `grpc-web` package, we treat all HTTP status\n    // codes in the 200 range as valid, not just HTTP 200.\n    if (status >= 200 && status < 300) {\n        return {\n            foundStatus: headers.has(headerGrpcStatus),\n            headerError: findTrailerError(headers),\n        };\n    }\n    throw new ConnectError(decodeURIComponent((_a = headers.get(headerGrpcMessage)) !== null && _a !== void 0 ? _a : `HTTP ${status}`), codeFromHttpStatus(status), headers);\n}\n/**\n * Validates response status and header for the gRPC-web protocol.\n * This function is identical to validateResponse(), but also verifies\n * that a given encoding header is acceptable.\n *\n * Returns an object with the response compression, and a boolean\n * indicating whether a gRPC status was found in the response header\n * (in this case, clients can not expect a trailer).\n *\n * @private Internal code, does not follow semantic versioning.\n */\nexport function validateResponseWithCompression(acceptCompression, status, headers) {\n    const { foundStatus, headerError } = validateResponse(status, headers);\n    let compression;\n    const encoding = headers.get(headerEncoding);\n    if (encoding !== null && encoding.toLowerCase() !== \"identity\") {\n        compression = acceptCompression.find((c) => c.name === encoding);\n        if (!compression) {\n            throw new ConnectError(`unsupported response encoding \"${encoding}\"`, Code.Internal, headers);\n        }\n    }\n    return {\n        foundStatus,\n        compression,\n        headerError,\n    };\n}\n","// Copyright 2021-2025 The Connect Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nvar __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }\nvar __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n    if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n    var g = generator.apply(thisArg, _arguments || []), i, q = [];\n    return i = Object.create((typeof AsyncIterator === \"function\" ? AsyncIterator : Object).prototype), verb(\"next\"), verb(\"throw\"), verb(\"return\", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;\n    function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }\n    function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }\n    function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n    function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n    function fulfill(value) { resume(\"next\", value); }\n    function reject(value) { resume(\"throw\", value); }\n    function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n};\nimport { createContextValues, ConnectError, Code } from \"@connectrpc/connect\";\nimport { compressedFlag, createClientMethodSerializers, createEnvelopeReadableStream, createMethodUrl, encodeEnvelope, runStreamingCall, runUnaryCall, } from \"@connectrpc/connect/protocol\";\nimport { headerGrpcStatus, requestHeader, trailerFlag, trailerParse, validateResponse, validateTrailer, } from \"@connectrpc/connect/protocol-grpc-web\";\nimport { assertFetchApi } from \"./assert-fetch-api.js\";\nconst fetchOptions = {\n    redirect: \"error\",\n};\n/**\n * Create a Transport for the gRPC-web protocol. The protocol encodes\n * trailers in the response body and makes unary and server-streaming\n * methods available to web browsers. It uses the fetch API to make\n * HTTP requests.\n *\n * Note that this transport does not implement the grpc-web-text format,\n * which applies base64 encoding to the request and response bodies to\n * support reading streaming responses from an XMLHttpRequest.\n */\nexport function createGrpcWebTransport(options) {\n    var _a;\n    assertFetchApi();\n    const useBinaryFormat = (_a = options.useBinaryFormat) !== null && _a !== void 0 ? _a : true;\n    return {\n        async unary(method, signal, timeoutMs, header, message, contextValues) {\n            const { serialize, parse } = createClientMethodSerializers(method, useBinaryFormat, options.jsonOptions, options.binaryOptions);\n            timeoutMs =\n                timeoutMs === undefined\n                    ? options.defaultTimeoutMs\n                    : timeoutMs <= 0\n                        ? undefined\n                        : timeoutMs;\n            return await runUnaryCall({\n                interceptors: options.interceptors,\n                signal,\n                timeoutMs,\n                req: {\n                    stream: false,\n                    service: method.parent,\n                    method,\n                    requestMethod: \"POST\",\n                    url: createMethodUrl(options.baseUrl, method),\n                    header: requestHeader(useBinaryFormat, timeoutMs, header, false),\n                    contextValues: contextValues !== null && contextValues !== void 0 ? contextValues : createContextValues(),\n                    message,\n                },\n                next: async (req) => {\n                    var _a;\n                    const fetch = (_a = options.fetch) !== null && _a !== void 0 ? _a : globalThis.fetch;\n                    const response = await fetch(req.url, Object.assign(Object.assign({}, fetchOptions), { method: req.requestMethod, headers: req.header, signal: req.signal, body: encodeEnvelope(0, serialize(req.message)) }));\n                    const { headerError } = validateResponse(response.status, response.headers);\n                    if (!response.body) {\n                        if (headerError !== undefined)\n                            throw headerError;\n                        throw \"missing response body\";\n                    }\n                    const reader = createEnvelopeReadableStream(response.body).getReader();\n                    let trailer;\n                    let message;\n                    for (;;) {\n                        const r = await reader.read();\n                        if (r.done) {\n                            break;\n                        }\n                        const { flags, data } = r.value;\n                        if ((flags & compressedFlag) === compressedFlag) {\n                            throw new ConnectError(`protocol error: received unsupported compressed output`, Code.Internal);\n                        }\n                        if (flags === trailerFlag) {\n                            if (trailer !== undefined) {\n                                throw \"extra trailer\";\n                            }\n                            // Unary responses require exactly one response message, but in\n                            // case of an error, it is perfectly valid to have a response body\n                            // that only contains error trailers.\n                            trailer = trailerParse(data);\n                            continue;\n                        }\n                        if (message !== undefined) {\n                            throw new ConnectError(\"extra message\", Code.Unimplemented);\n                        }\n                        message = parse(data);\n                    }\n                    if (trailer === undefined) {\n                        if (headerError !== undefined)\n                            throw headerError;\n                        throw new ConnectError(\"missing trailer\", response.headers.has(headerGrpcStatus)\n                            ? Code.Unimplemented\n                            : Code.Unknown);\n                    }\n                    validateTrailer(trailer, response.headers);\n                    if (message === undefined) {\n                        throw new ConnectError(\"missing message\", trailer.has(headerGrpcStatus) ? Code.Unimplemented : Code.Unknown);\n                    }\n                    return {\n                        stream: false,\n                        service: method.parent,\n                        method,\n                        header: response.headers,\n                        message,\n                        trailer,\n                    };\n                },\n            });\n        },\n        async stream(method, signal, timeoutMs, header, input, contextValues) {\n            const { serialize, parse } = createClientMethodSerializers(method, useBinaryFormat, options.jsonOptions, options.binaryOptions);\n            function parseResponseBody(body, foundStatus, trailerTarget, header, signal) {\n                return __asyncGenerator(this, arguments, function* parseResponseBody_1() {\n                    const reader = createEnvelopeReadableStream(body).getReader();\n                    if (foundStatus) {\n                        // A grpc-status: 0 response header was present. This is a \"trailers-only\"\n                        // response (a response without a body and no trailers).\n                        //\n                        // The spec seems to disallow a trailers-only response for status 0 - we are\n                        // lenient and only verify that the body is empty.\n                        //\n                        // > [...] Trailers-Only is permitted for calls that produce an immediate error.\n                        // See https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md\n                        if (!(yield __await(reader.read())).done) {\n                            throw \"extra data for trailers-only\";\n                        }\n                        return yield __await(void 0);\n                    }\n                    let trailerReceived = false;\n                    for (;;) {\n                        const result = yield __await(reader.read());\n                        if (result.done) {\n                            break;\n                        }\n                        const { flags, data } = result.value;\n                        if ((flags & trailerFlag) === trailerFlag) {\n                            if (trailerReceived) {\n                                throw \"extra trailer\";\n                            }\n                            trailerReceived = true;\n                            const trailer = trailerParse(data);\n                            validateTrailer(trailer, header);\n                            trailer.forEach((value, key) => trailerTarget.set(key, value));\n                            continue;\n                        }\n                        if (trailerReceived) {\n                            throw \"extra message\";\n                        }\n                        yield yield __await(parse(data));\n                    }\n                    // Node wil not throw an AbortError on `read` if the\n                    // signal is aborted before `getReader` is called.\n                    // As a work around we check at the end and throw.\n                    //\n                    // Ref: https://github.com/nodejs/undici/issues/1940\n                    if (\"throwIfAborted\" in signal) {\n                        // We assume that implementations without `throwIfAborted` (old\n                        // browsers) do honor aborted signals on `read`.\n                        signal.throwIfAborted();\n                    }\n                    if (!trailerReceived) {\n                        throw \"missing trailer\";\n                    }\n                });\n            }\n            async function createRequestBody(input) {\n                if (method.methodKind != \"server_streaming\") {\n                    throw \"The fetch API does not support streaming request bodies\";\n                }\n                const r = await input[Symbol.asyncIterator]().next();\n                if (r.done == true) {\n                    throw \"missing request message\";\n                }\n                return encodeEnvelope(0, serialize(r.value));\n            }\n            timeoutMs =\n                timeoutMs === undefined\n                    ? options.defaultTimeoutMs\n                    : timeoutMs <= 0\n                        ? undefined\n                        : timeoutMs;\n            return runStreamingCall({\n                interceptors: options.interceptors,\n                signal,\n                timeoutMs,\n                req: {\n                    stream: true,\n                    service: method.parent,\n                    method,\n                    requestMethod: \"POST\",\n                    url: createMethodUrl(options.baseUrl, method),\n                    header: requestHeader(useBinaryFormat, timeoutMs, header, false),\n                    contextValues: contextValues !== null && contextValues !== void 0 ? contextValues : createContextValues(),\n                    message: input,\n                },\n                next: async (req) => {\n                    var _a;\n                    const fetch = (_a = options.fetch) !== null && _a !== void 0 ? _a : globalThis.fetch;\n                    const fRes = await fetch(req.url, Object.assign(Object.assign({}, fetchOptions), { method: req.requestMethod, headers: req.header, signal: req.signal, body: await createRequestBody(req.message) }));\n                    const { foundStatus, headerError } = validateResponse(fRes.status, fRes.headers);\n                    if (headerError != undefined) {\n                        throw headerError;\n                    }\n                    if (!fRes.body) {\n                        throw \"missing response body\";\n                    }\n                    const trailer = new Headers();\n                    const res = Object.assign(Object.assign({}, req), { header: fRes.headers, trailer, message: parseResponseBody(fRes.body, foundStatus, trailer, fRes.headers, req.signal) });\n                    return res;\n                },\n            });\n        },\n    };\n}\n","//\n// Copyright 2022 The Yorkie Authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n// @generated by protoc-gen-es v2.10.1 with parameter \"target=ts,import_extension=none\"\n// @generated from file yorkie/v1/resources.proto (package yorkie.v1, syntax proto3)\n/* eslint-disable */\n\nimport type { GenEnum, GenFile, GenMessage } from \"@bufbuild/protobuf/codegenv2\";\nimport { enumDesc, fileDesc, messageDesc } from \"@bufbuild/protobuf/codegenv2\";\nimport type { Timestamp } from \"@bufbuild/protobuf/wkt\";\nimport { file_google_protobuf_timestamp, file_google_protobuf_wrappers } from \"@bufbuild/protobuf/wkt\";\nimport type { Message } from \"@bufbuild/protobuf\";\n\n/**\n * Describes the file yorkie/v1/resources.proto.\n */\nexport const file_yorkie_v1_resources: GenFile = /*@__PURE__*/\n  fileDesc(\"Chl5b3JraWUvdjEvcmVzb3VyY2VzLnByb3RvEgl5b3JraWUudjEirgEKCFNuYXBzaG90EiQKBHJvb3QYASABKAsyFi55b3JraWUudjEuSlNPTk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0JZVEVTEAYSEwoPVkFMVUVfVFlQRV9EQVRFEAcSGgoWVkFMVUVfVFlQRV9KU09OX09CSkVDVBAIEhkKFVZBTFVFX1RZUEVfSlNPTl9BUlJBWRAJEhMKD1ZBTFVFX1RZUEVfVEVYVBAKEhoKFlZBTFVFX1RZUEVfSU5URUdFUl9DTlQQCxIXChNWQUxVRV9UWVBFX0xPTkdfQ05UEAwSEwoPVkFMVUVfVFlQRV9UUkVFEA0SIAocVkFMVUVfVFlQRV9JTlRFR0VSX0RFRFVQX0NOVBAOIgQIDxAPKqYBCgxEb2NFdmVudFR5cGUSIwofRE9DX0VWRU5UX1RZUEVfRE9DVU1FTlRfQ0hBTkdFRBAAEiMKH0RPQ19FVkVOVF9UWVBFX0RPQ1VNRU5UX1dBVENIRUQQARIlCiFET0NfRVZFTlRfVFlQRV9ET0NVTUVOVF9VTldBVENIRUQQAhIlCiFET0NfRVZFTlRfVFlQRV9ET0NVTUVOVF9CUk9BRENBU1QQA0JFChFkZXYueW9ya2llLmFwaS52MVABWi5naXRodWIuY29tL3lvcmtpZS10ZWFtL3lvcmtpZS9hcGkveW9ya2llL3YxO3YxYgZwcm90bzM\", [file_google_protobuf_timestamp, file_google_protobuf_wrappers]);\n\n/**\n * ///////////////////////////////////////\n * Messages for Snapshot               //\n * ///////////////////////////////////////\n *\n * @generated from message yorkie.v1.Snapshot\n */\nexport type Snapshot = Message<\"yorkie.v1.Snapshot\"> & {\n  /**\n   * @generated from field: yorkie.v1.JSONElement root = 1;\n   */\n  root?: JSONElement;\n\n  /**\n   * @generated from field: map<string, yorkie.v1.Presence> presences = 2;\n   */\n  presences: { [key: string]: Presence };\n};\n\n/**\n * Describes the message yorkie.v1.Snapshot.\n * Use `create(SnapshotSchema)` to create a new message.\n */\nexport const SnapshotSchema: GenMessage<Snapshot> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 0);\n\n/**\n * ChangePack is a message that contains all changes that occurred in a document.\n * It is used to synchronize changes between clients and servers.\n *\n * @generated from message yorkie.v1.ChangePack\n */\nexport type ChangePack = Message<\"yorkie.v1.ChangePack\"> & {\n  /**\n   * @generated from field: string document_key = 1;\n   */\n  documentKey: string;\n\n  /**\n   * @generated from field: yorkie.v1.Checkpoint checkpoint = 2;\n   */\n  checkpoint?: Checkpoint;\n\n  /**\n   * @generated from field: bytes snapshot = 3;\n   */\n  snapshot: Uint8Array;\n\n  /**\n   * @generated from field: repeated yorkie.v1.Change changes = 4;\n   */\n  changes: Change[];\n\n  /**\n   * deprecated\n   *\n   * @generated from field: yorkie.v1.TimeTicket min_synced_ticket = 5;\n   */\n  minSyncedTicket?: TimeTicket;\n\n  /**\n   * @generated from field: bool is_removed = 6;\n   */\n  isRemoved: boolean;\n\n  /**\n   * @generated from field: yorkie.v1.VersionVector version_vector = 7;\n   */\n  versionVector?: VersionVector;\n\n  /**\n   * @generated from field: int64 epoch = 8;\n   */\n  epoch: bigint;\n\n  /**\n   * capabilities is the negotiation channel for wire features a peer may not\n   * understand. A server sets it on the pack it returns to advertise what it\n   * supports; a client must treat absence as \"unsupported\" rather than as\n   * \"unknown\", because a server that predates a feature cannot say so.\n   *\n   * It exists because a server does not store the bytes a client sent: it\n   * re-encodes from its own domain model, so a field it does not know is\n   * dropped from the stored change log and the push still succeeds. Without a\n   * handshake a client cannot tell that its restore was silently downgraded to\n   * an ordinary insert. Measured against a pinned v0.7.20 server.\n   *\n   * @generated from field: repeated string capabilities = 9;\n   */\n  capabilities: string[];\n};\n\n/**\n * Describes the message yorkie.v1.ChangePack.\n * Use `create(ChangePackSchema)` to create a new message.\n */\nexport const ChangePackSchema: GenMessage<ChangePack> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 1);\n\n/**\n * @generated from message yorkie.v1.Change\n */\nexport type Change = Message<\"yorkie.v1.Change\"> & {\n  /**\n   * @generated from field: yorkie.v1.ChangeID id = 1;\n   */\n  id?: ChangeID;\n\n  /**\n   * @generated from field: string message = 2;\n   */\n  message: string;\n\n  /**\n   * @generated from field: repeated yorkie.v1.Operation operations = 3;\n   */\n  operations: Operation[];\n\n  /**\n   * @generated from field: yorkie.v1.PresenceChange presence_change = 4;\n   */\n  presenceChange?: PresenceChange;\n};\n\n/**\n * Describes the message yorkie.v1.Change.\n * Use `create(ChangeSchema)` to create a new message.\n */\nexport const ChangeSchema: GenMessage<Change> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 2);\n\n/**\n * @generated from message yorkie.v1.ChangeID\n */\nexport type ChangeID = Message<\"yorkie.v1.ChangeID\"> & {\n  /**\n   * @generated from field: uint32 client_seq = 1;\n   */\n  clientSeq: number;\n\n  /**\n   * @generated from field: int64 server_seq = 2;\n   */\n  serverSeq: bigint;\n\n  /**\n   * @generated from field: int64 lamport = 3;\n   */\n  lamport: bigint;\n\n  /**\n   * @generated from field: bytes actor_id = 4;\n   */\n  actorId: Uint8Array;\n\n  /**\n   * @generated from field: yorkie.v1.VersionVector version_vector = 5;\n   */\n  versionVector?: VersionVector;\n};\n\n/**\n * Describes the message yorkie.v1.ChangeID.\n * Use `create(ChangeIDSchema)` to create a new message.\n */\nexport const ChangeIDSchema: GenMessage<ChangeID> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 3);\n\n/**\n * @generated from message yorkie.v1.VersionVector\n */\nexport type VersionVector = Message<\"yorkie.v1.VersionVector\"> & {\n  /**\n   * @generated from field: map<string, int64> vector = 1;\n   */\n  vector: { [key: string]: bigint };\n};\n\n/**\n * Describes the message yorkie.v1.VersionVector.\n * Use `create(VersionVectorSchema)` to create a new message.\n */\nexport const VersionVectorSchema: GenMessage<VersionVector> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 4);\n\n/**\n * @generated from message yorkie.v1.Operation\n */\nexport type Operation = Message<\"yorkie.v1.Operation\"> & {\n  /**\n   * @generated from oneof yorkie.v1.Operation.body\n   */\n  body: {\n    /**\n     * @generated from field: yorkie.v1.Operation.Set set = 1;\n     */\n    value: Operation_Set;\n    case: \"set\";\n  } | {\n    /**\n     * @generated from field: yorkie.v1.Operation.Add add = 2;\n     */\n    value: Operation_Add;\n    case: \"add\";\n  } | {\n    /**\n     * @generated from field: yorkie.v1.Operation.Move move = 3;\n     */\n    value: Operation_Move;\n    case: \"move\";\n  } | {\n    /**\n     * @generated from field: yorkie.v1.Operation.Remove remove = 4;\n     */\n    value: Operation_Remove;\n    case: \"remove\";\n  } | {\n    /**\n     * @generated from field: yorkie.v1.Operation.Edit edit = 5;\n     */\n    value: Operation_Edit;\n    case: \"edit\";\n  } | {\n    /**\n     * @generated from field: yorkie.v1.Operation.Style style = 7;\n     */\n    value: Operation_Style;\n    case: \"style\";\n  } | {\n    /**\n     * @generated from field: yorkie.v1.Operation.Increase increase = 8;\n     */\n    value: Operation_Increase;\n    case: \"increase\";\n  } | {\n    /**\n     * @generated from field: yorkie.v1.Operation.TreeEdit tree_edit = 9;\n     */\n    value: Operation_TreeEdit;\n    case: \"treeEdit\";\n  } | {\n    /**\n     * @generated from field: yorkie.v1.Operation.TreeStyle tree_style = 10;\n     */\n    value: Operation_TreeStyle;\n    case: \"treeStyle\";\n  } | {\n    /**\n     * @generated from field: yorkie.v1.Operation.ArraySet array_set = 11;\n     */\n    value: Operation_ArraySet;\n    case: \"arraySet\";\n  } | { case: undefined; value?: undefined };\n};\n\n/**\n * Describes the message yorkie.v1.Operation.\n * Use `create(OperationSchema)` to create a new message.\n */\nexport const OperationSchema: GenMessage<Operation> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 5);\n\n/**\n * @generated from message yorkie.v1.Operation.Set\n */\nexport type Operation_Set = Message<\"yorkie.v1.Operation.Set\"> & {\n  /**\n   * @generated from field: yorkie.v1.TimeTicket parent_created_at = 1;\n   */\n  parentCreatedAt?: TimeTicket;\n\n  /**\n   * @generated from field: string key = 2;\n   */\n  key: string;\n\n  /**\n   * @generated from field: yorkie.v1.JSONElementSimple value = 3;\n   */\n  value?: JSONElementSimple;\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket executed_at = 4;\n   */\n  executedAt?: TimeTicket;\n\n  /**\n   * @generated from field: yorkie.v1.RestoreMode restore_mode = 5;\n   */\n  restoreMode: RestoreMode;\n};\n\n/**\n * Describes the message yorkie.v1.Operation.Set.\n * Use `create(Operation_SetSchema)` to create a new message.\n */\nexport const Operation_SetSchema: GenMessage<Operation_Set> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 5, 0);\n\n/**\n * @generated from message yorkie.v1.Operation.Add\n */\nexport type Operation_Add = Message<\"yorkie.v1.Operation.Add\"> & {\n  /**\n   * @generated from field: yorkie.v1.TimeTicket parent_created_at = 1;\n   */\n  parentCreatedAt?: TimeTicket;\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket prev_created_at = 2;\n   */\n  prevCreatedAt?: TimeTicket;\n\n  /**\n   * @generated from field: yorkie.v1.JSONElementSimple value = 3;\n   */\n  value?: JSONElementSimple;\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket executed_at = 4;\n   */\n  executedAt?: TimeTicket;\n\n  /**\n   * @generated from field: yorkie.v1.RestoreMode restore_mode = 5;\n   */\n  restoreMode: RestoreMode;\n};\n\n/**\n * Describes the message yorkie.v1.Operation.Add.\n * Use `create(Operation_AddSchema)` to create a new message.\n */\nexport const Operation_AddSchema: GenMessage<Operation_Add> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 5, 1);\n\n/**\n * @generated from message yorkie.v1.Operation.Move\n */\nexport type Operation_Move = Message<\"yorkie.v1.Operation.Move\"> & {\n  /**\n   * @generated from field: yorkie.v1.TimeTicket parent_created_at = 1;\n   */\n  parentCreatedAt?: TimeTicket;\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket prev_created_at = 2;\n   */\n  prevCreatedAt?: TimeTicket;\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket created_at = 3;\n   */\n  createdAt?: TimeTicket;\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket executed_at = 4;\n   */\n  executedAt?: TimeTicket;\n};\n\n/**\n * Describes the message yorkie.v1.Operation.Move.\n * Use `create(Operation_MoveSchema)` to create a new message.\n */\nexport const Operation_MoveSchema: GenMessage<Operation_Move> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 5, 2);\n\n/**\n * @generated from message yorkie.v1.Operation.Remove\n */\nexport type Operation_Remove = Message<\"yorkie.v1.Operation.Remove\"> & {\n  /**\n   * @generated from field: yorkie.v1.TimeTicket parent_created_at = 1;\n   */\n  parentCreatedAt?: TimeTicket;\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket created_at = 2;\n   */\n  createdAt?: TimeTicket;\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket executed_at = 3;\n   */\n  executedAt?: TimeTicket;\n};\n\n/**\n * Describes the message yorkie.v1.Operation.Remove.\n * Use `create(Operation_RemoveSchema)` to create a new message.\n */\nexport const Operation_RemoveSchema: GenMessage<Operation_Remove> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 5, 3);\n\n/**\n * @generated from message yorkie.v1.Operation.Edit\n */\nexport type Operation_Edit = Message<\"yorkie.v1.Operation.Edit\"> & {\n  /**\n   * @generated from field: yorkie.v1.TimeTicket parent_created_at = 1;\n   */\n  parentCreatedAt?: TimeTicket;\n\n  /**\n   * @generated from field: yorkie.v1.TextNodePos from = 2;\n   */\n  from?: TextNodePos;\n\n  /**\n   * @generated from field: yorkie.v1.TextNodePos to = 3;\n   */\n  to?: TextNodePos;\n\n  /**\n   * deprecated\n   *\n   * @generated from field: map<string, yorkie.v1.TimeTicket> created_at_map_by_actor = 4;\n   */\n  createdAtMapByActor: { [key: string]: TimeTicket };\n\n  /**\n   * @generated from field: string content = 5;\n   */\n  content: string;\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket executed_at = 6;\n   */\n  executedAt?: TimeTicket;\n\n  /**\n   * @generated from field: map<string, string> attributes = 7;\n   */\n  attributes: { [key: string]: string };\n\n  /**\n   * identity-preserving undo/redo\n   *\n   * @generated from field: repeated yorkie.v1.RestoreSpan restore_spans = 8;\n   */\n  restoreSpans: RestoreSpan[];\n\n  /**\n   * @generated from field: yorkie.v1.RestoreMode restore_mode = 9;\n   */\n  restoreMode: RestoreMode;\n\n  /**\n   * retombstone_spans is the companion span set for an identity-preserving\n   * reverse op: restore_spans is content the reversed edit removed (to\n   * revive), retombstone_spans is content it inserted (to re-remove). Both\n   * are addressed by original identity so a revived neighbour keeps its\n   * relative order across chained undo/redo. restore_mode selects direction.\n   *\n   * @generated from field: repeated yorkie.v1.RestoreSpan retombstone_spans = 10;\n   */\n  retombstoneSpans: RestoreSpan[];\n};\n\n/**\n * Describes the message yorkie.v1.Operation.Edit.\n * Use `create(Operation_EditSchema)` to create a new message.\n */\nexport const Operation_EditSchema: GenMessage<Operation_Edit> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 5, 4);\n\n/**\n * @generated from message yorkie.v1.Operation.Style\n */\nexport type Operation_Style = Message<\"yorkie.v1.Operation.Style\"> & {\n  /**\n   * @generated from field: yorkie.v1.TimeTicket parent_created_at = 1;\n   */\n  parentCreatedAt?: TimeTicket;\n\n  /**\n   * @generated from field: yorkie.v1.TextNodePos from = 2;\n   */\n  from?: TextNodePos;\n\n  /**\n   * @generated from field: yorkie.v1.TextNodePos to = 3;\n   */\n  to?: TextNodePos;\n\n  /**\n   * @generated from field: map<string, string> attributes = 4;\n   */\n  attributes: { [key: string]: string };\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket executed_at = 5;\n   */\n  executedAt?: TimeTicket;\n\n  /**\n   * deprecated\n   *\n   * @generated from field: map<string, yorkie.v1.TimeTicket> created_at_map_by_actor = 6;\n   */\n  createdAtMapByActor: { [key: string]: TimeTicket };\n\n  /**\n   * @generated from field: repeated string attributes_to_remove = 7;\n   */\n  attributesToRemove: string[];\n};\n\n/**\n * Describes the message yorkie.v1.Operation.Style.\n * Use `create(Operation_StyleSchema)` to create a new message.\n */\nexport const Operation_StyleSchema: GenMessage<Operation_Style> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 5, 5);\n\n/**\n * @generated from message yorkie.v1.Operation.Increase\n */\nexport type Operation_Increase = Message<\"yorkie.v1.Operation.Increase\"> & {\n  /**\n   * @generated from field: yorkie.v1.TimeTicket parent_created_at = 1;\n   */\n  parentCreatedAt?: TimeTicket;\n\n  /**\n   * @generated from field: yorkie.v1.JSONElementSimple value = 2;\n   */\n  value?: JSONElementSimple;\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket executed_at = 3;\n   */\n  executedAt?: TimeTicket;\n\n  /**\n   * @generated from field: string actor = 4;\n   */\n  actor: string;\n};\n\n/**\n * Describes the message yorkie.v1.Operation.Increase.\n * Use `create(Operation_IncreaseSchema)` to create a new message.\n */\nexport const Operation_IncreaseSchema: GenMessage<Operation_Increase> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 5, 6);\n\n/**\n * @generated from message yorkie.v1.Operation.TreeEdit\n */\nexport type Operation_TreeEdit = Message<\"yorkie.v1.Operation.TreeEdit\"> & {\n  /**\n   * @generated from field: yorkie.v1.TimeTicket parent_created_at = 1;\n   */\n  parentCreatedAt?: TimeTicket;\n\n  /**\n   * @generated from field: yorkie.v1.TreePos from = 2;\n   */\n  from?: TreePos;\n\n  /**\n   * @generated from field: yorkie.v1.TreePos to = 3;\n   */\n  to?: TreePos;\n\n  /**\n   * deprecated\n   *\n   * @generated from field: map<string, yorkie.v1.TimeTicket> created_at_map_by_actor = 4;\n   */\n  createdAtMapByActor: { [key: string]: TimeTicket };\n\n  /**\n   * @generated from field: repeated yorkie.v1.TreeNodes contents = 5;\n   */\n  contents: TreeNodes[];\n\n  /**\n   * @generated from field: int32 split_level = 7;\n   */\n  splitLevel: number;\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket executed_at = 6;\n   */\n  executedAt?: TimeTicket;\n\n  /**\n   * identity-preserving undo/redo\n   *\n   * @generated from field: repeated yorkie.v1.TreeRestoreSpan restore_spans = 8;\n   */\n  restoreSpans: TreeRestoreSpan[];\n\n  /**\n   * @generated from field: yorkie.v1.RestoreMode restore_mode = 9;\n   */\n  restoreMode: RestoreMode;\n\n  /**\n   * @generated from field: repeated yorkie.v1.TreeRestoreSpan retombstone_spans = 10;\n   */\n  retombstoneSpans: TreeRestoreSpan[];\n\n  /**\n   * split_tickets carries the tickets the originating replica issued for the\n   * nodes an element split creates, in issue order. Empty for a change\n   * written before this field existed, which replays through the simulation\n   * that reconstructed them from executed_at and the content count.\n   *\n   * @generated from field: repeated yorkie.v1.TimeTicket split_tickets = 11;\n   */\n  splitTickets: TimeTicket[];\n};\n\n/**\n * Describes the message yorkie.v1.Operation.TreeEdit.\n * Use `create(Operation_TreeEditSchema)` to create a new message.\n */\nexport const Operation_TreeEditSchema: GenMessage<Operation_TreeEdit> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 5, 7);\n\n/**\n * @generated from message yorkie.v1.Operation.TreeStyle\n */\nexport type Operation_TreeStyle = Message<\"yorkie.v1.Operation.TreeStyle\"> & {\n  /**\n   * @generated from field: yorkie.v1.TimeTicket parent_created_at = 1;\n   */\n  parentCreatedAt?: TimeTicket;\n\n  /**\n   * @generated from field: yorkie.v1.TreePos from = 2;\n   */\n  from?: TreePos;\n\n  /**\n   * @generated from field: yorkie.v1.TreePos to = 3;\n   */\n  to?: TreePos;\n\n  /**\n   * @generated from field: map<string, string> attributes = 4;\n   */\n  attributes: { [key: string]: string };\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket executed_at = 5;\n   */\n  executedAt?: TimeTicket;\n\n  /**\n   * @generated from field: repeated string attributes_to_remove = 6;\n   */\n  attributesToRemove: string[];\n\n  /**\n   * deprecated\n   *\n   * @generated from field: map<string, yorkie.v1.TimeTicket> created_at_map_by_actor = 7;\n   */\n  createdAtMapByActor: { [key: string]: TimeTicket };\n};\n\n/**\n * Describes the message yorkie.v1.Operation.TreeStyle.\n * Use `create(Operation_TreeStyleSchema)` to create a new message.\n */\nexport const Operation_TreeStyleSchema: GenMessage<Operation_TreeStyle> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 5, 8);\n\n/**\n * @generated from message yorkie.v1.Operation.ArraySet\n */\nexport type Operation_ArraySet = Message<\"yorkie.v1.Operation.ArraySet\"> & {\n  /**\n   * @generated from field: yorkie.v1.TimeTicket parent_created_at = 1;\n   */\n  parentCreatedAt?: TimeTicket;\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket created_at = 2;\n   */\n  createdAt?: TimeTicket;\n\n  /**\n   * @generated from field: yorkie.v1.JSONElementSimple value = 3;\n   */\n  value?: JSONElementSimple;\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket executed_at = 4;\n   */\n  executedAt?: TimeTicket;\n\n  /**\n   * @generated from field: yorkie.v1.RestoreMode restore_mode = 5;\n   */\n  restoreMode: RestoreMode;\n};\n\n/**\n * Describes the message yorkie.v1.Operation.ArraySet.\n * Use `create(Operation_ArraySetSchema)` to create a new message.\n */\nexport const Operation_ArraySetSchema: GenMessage<Operation_ArraySet> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 5, 9);\n\n/**\n * @generated from message yorkie.v1.JSONElementSimple\n */\nexport type JSONElementSimple = Message<\"yorkie.v1.JSONElementSimple\"> & {\n  /**\n   * @generated from field: yorkie.v1.TimeTicket created_at = 1;\n   */\n  createdAt?: TimeTicket;\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket moved_at = 2;\n   */\n  movedAt?: TimeTicket;\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket removed_at = 3;\n   */\n  removedAt?: TimeTicket;\n\n  /**\n   * @generated from field: yorkie.v1.ValueType type = 4;\n   */\n  type: ValueType;\n\n  /**\n   * @generated from field: bytes value = 5;\n   */\n  value: Uint8Array;\n};\n\n/**\n * Describes the message yorkie.v1.JSONElementSimple.\n * Use `create(JSONElementSimpleSchema)` to create a new message.\n */\nexport const JSONElementSimpleSchema: GenMessage<JSONElementSimple> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 6);\n\n/**\n * @generated from message yorkie.v1.JSONElement\n */\nexport type JSONElement = Message<\"yorkie.v1.JSONElement\"> & {\n  /**\n   * @generated from oneof yorkie.v1.JSONElement.body\n   */\n  body: {\n    /**\n     * @generated from field: yorkie.v1.JSONElement.JSONObject json_object = 1;\n     */\n    value: JSONElement_JSONObject;\n    case: \"jsonObject\";\n  } | {\n    /**\n     * @generated from field: yorkie.v1.JSONElement.JSONArray json_array = 2;\n     */\n    value: JSONElement_JSONArray;\n    case: \"jsonArray\";\n  } | {\n    /**\n     * @generated from field: yorkie.v1.JSONElement.Primitive primitive = 3;\n     */\n    value: JSONElement_Primitive;\n    case: \"primitive\";\n  } | {\n    /**\n     * @generated from field: yorkie.v1.JSONElement.Text text = 5;\n     */\n    value: JSONElement_Text;\n    case: \"text\";\n  } | {\n    /**\n     * @generated from field: yorkie.v1.JSONElement.Counter counter = 6;\n     */\n    value: JSONElement_Counter;\n    case: \"counter\";\n  } | {\n    /**\n     * @generated from field: yorkie.v1.JSONElement.Tree tree = 7;\n     */\n    value: JSONElement_Tree;\n    case: \"tree\";\n  } | { case: undefined; value?: undefined };\n};\n\n/**\n * Describes the message yorkie.v1.JSONElement.\n * Use `create(JSONElementSchema)` to create a new message.\n */\nexport const JSONElementSchema: GenMessage<JSONElement> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 7);\n\n/**\n * @generated from message yorkie.v1.JSONElement.JSONObject\n */\nexport type JSONElement_JSONObject = Message<\"yorkie.v1.JSONElement.JSONObject\"> & {\n  /**\n   * @generated from field: repeated yorkie.v1.RHTNode nodes = 1;\n   */\n  nodes: RHTNode[];\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket created_at = 2;\n   */\n  createdAt?: TimeTicket;\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket moved_at = 3;\n   */\n  movedAt?: TimeTicket;\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket removed_at = 4;\n   */\n  removedAt?: TimeTicket;\n\n  /**\n   * revived_at is the revive half of the liveness register. See the comment\n   * on RestoreMode for why an element needs one.\n   *\n   * @generated from field: yorkie.v1.TimeTicket revived_at = 5;\n   */\n  revivedAt?: TimeTicket;\n};\n\n/**\n * Describes the message yorkie.v1.JSONElement.JSONObject.\n * Use `create(JSONElement_JSONObjectSchema)` to create a new message.\n */\nexport const JSONElement_JSONObjectSchema: GenMessage<JSONElement_JSONObject> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 7, 0);\n\n/**\n * @generated from message yorkie.v1.JSONElement.JSONArray\n */\nexport type JSONElement_JSONArray = Message<\"yorkie.v1.JSONElement.JSONArray\"> & {\n  /**\n   * @generated from field: repeated yorkie.v1.RGANode nodes = 1;\n   */\n  nodes: RGANode[];\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket created_at = 2;\n   */\n  createdAt?: TimeTicket;\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket moved_at = 3;\n   */\n  movedAt?: TimeTicket;\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket removed_at = 4;\n   */\n  removedAt?: TimeTicket;\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket revived_at = 5;\n   */\n  revivedAt?: TimeTicket;\n};\n\n/**\n * Describes the message yorkie.v1.JSONElement.JSONArray.\n * Use `create(JSONElement_JSONArraySchema)` to create a new message.\n */\nexport const JSONElement_JSONArraySchema: GenMessage<JSONElement_JSONArray> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 7, 1);\n\n/**\n * @generated from message yorkie.v1.JSONElement.Primitive\n */\nexport type JSONElement_Primitive = Message<\"yorkie.v1.JSONElement.Primitive\"> & {\n  /**\n   * @generated from field: yorkie.v1.ValueType type = 1;\n   */\n  type: ValueType;\n\n  /**\n   * @generated from field: bytes value = 2;\n   */\n  value: Uint8Array;\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket created_at = 3;\n   */\n  createdAt?: TimeTicket;\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket moved_at = 4;\n   */\n  movedAt?: TimeTicket;\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket removed_at = 5;\n   */\n  removedAt?: TimeTicket;\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket revived_at = 6;\n   */\n  revivedAt?: TimeTicket;\n};\n\n/**\n * Describes the message yorkie.v1.JSONElement.Primitive.\n * Use `create(JSONElement_PrimitiveSchema)` to create a new message.\n */\nexport const JSONElement_PrimitiveSchema: GenMessage<JSONElement_Primitive> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 7, 2);\n\n/**\n * @generated from message yorkie.v1.JSONElement.Text\n */\nexport type JSONElement_Text = Message<\"yorkie.v1.JSONElement.Text\"> & {\n  /**\n   * @generated from field: repeated yorkie.v1.TextNode nodes = 1;\n   */\n  nodes: TextNode[];\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket created_at = 2;\n   */\n  createdAt?: TimeTicket;\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket moved_at = 3;\n   */\n  movedAt?: TimeTicket;\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket removed_at = 4;\n   */\n  removedAt?: TimeTicket;\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket revived_at = 5;\n   */\n  revivedAt?: TimeTicket;\n};\n\n/**\n * Describes the message yorkie.v1.JSONElement.Text.\n * Use `create(JSONElement_TextSchema)` to create a new message.\n */\nexport const JSONElement_TextSchema: GenMessage<JSONElement_Text> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 7, 3);\n\n/**\n * @generated from message yorkie.v1.JSONElement.Counter\n */\nexport type JSONElement_Counter = Message<\"yorkie.v1.JSONElement.Counter\"> & {\n  /**\n   * @generated from field: yorkie.v1.ValueType type = 1;\n   */\n  type: ValueType;\n\n  /**\n   * @generated from field: bytes value = 2;\n   */\n  value: Uint8Array;\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket created_at = 3;\n   */\n  createdAt?: TimeTicket;\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket moved_at = 4;\n   */\n  movedAt?: TimeTicket;\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket removed_at = 5;\n   */\n  removedAt?: TimeTicket;\n\n  /**\n   * @generated from field: bytes hll_registers = 7;\n   */\n  hllRegisters: Uint8Array;\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket revived_at = 8;\n   */\n  revivedAt?: TimeTicket;\n};\n\n/**\n * Describes the message yorkie.v1.JSONElement.Counter.\n * Use `create(JSONElement_CounterSchema)` to create a new message.\n */\nexport const JSONElement_CounterSchema: GenMessage<JSONElement_Counter> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 7, 4);\n\n/**\n * @generated from message yorkie.v1.JSONElement.Tree\n */\nexport type JSONElement_Tree = Message<\"yorkie.v1.JSONElement.Tree\"> & {\n  /**\n   * @generated from field: repeated yorkie.v1.TreeNode nodes = 1;\n   */\n  nodes: TreeNode[];\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket created_at = 2;\n   */\n  createdAt?: TimeTicket;\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket moved_at = 3;\n   */\n  movedAt?: TimeTicket;\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket removed_at = 4;\n   */\n  removedAt?: TimeTicket;\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket revived_at = 5;\n   */\n  revivedAt?: TimeTicket;\n};\n\n/**\n * Describes the message yorkie.v1.JSONElement.Tree.\n * Use `create(JSONElement_TreeSchema)` to create a new message.\n */\nexport const JSONElement_TreeSchema: GenMessage<JSONElement_Tree> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 7, 5);\n\n/**\n * @generated from message yorkie.v1.RHTNode\n */\nexport type RHTNode = Message<\"yorkie.v1.RHTNode\"> & {\n  /**\n   * @generated from field: string key = 1;\n   */\n  key: string;\n\n  /**\n   * @generated from field: yorkie.v1.JSONElement element = 2;\n   */\n  element?: JSONElement;\n};\n\n/**\n * Describes the message yorkie.v1.RHTNode.\n * Use `create(RHTNodeSchema)` to create a new message.\n */\nexport const RHTNodeSchema: GenMessage<RHTNode> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 8);\n\n/**\n * @generated from message yorkie.v1.RGANode\n */\nexport type RGANode = Message<\"yorkie.v1.RGANode\"> & {\n  /**\n   * @generated from field: yorkie.v1.RGANode next = 1;\n   */\n  next?: RGANode;\n\n  /**\n   * @generated from field: yorkie.v1.JSONElement element = 2;\n   */\n  element?: JSONElement;\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket position_created_at = 3;\n   */\n  positionCreatedAt?: TimeTicket;\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket position_moved_at = 4;\n   */\n  positionMovedAt?: TimeTicket;\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket position_removed_at = 5;\n   */\n  positionRemovedAt?: TimeTicket;\n};\n\n/**\n * Describes the message yorkie.v1.RGANode.\n * Use `create(RGANodeSchema)` to create a new message.\n */\nexport const RGANodeSchema: GenMessage<RGANode> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 9);\n\n/**\n * @generated from message yorkie.v1.NodeAttr\n */\nexport type NodeAttr = Message<\"yorkie.v1.NodeAttr\"> & {\n  /**\n   * @generated from field: string value = 1;\n   */\n  value: string;\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket updated_at = 2;\n   */\n  updatedAt?: TimeTicket;\n\n  /**\n   * @generated from field: bool is_removed = 3;\n   */\n  isRemoved: boolean;\n};\n\n/**\n * Describes the message yorkie.v1.NodeAttr.\n * Use `create(NodeAttrSchema)` to create a new message.\n */\nexport const NodeAttrSchema: GenMessage<NodeAttr> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 10);\n\n/**\n * @generated from message yorkie.v1.TextNode\n */\nexport type TextNode = Message<\"yorkie.v1.TextNode\"> & {\n  /**\n   * @generated from field: yorkie.v1.TextNodeID id = 1;\n   */\n  id?: TextNodeID;\n\n  /**\n   * @generated from field: string value = 2;\n   */\n  value: string;\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket removed_at = 3;\n   */\n  removedAt?: TimeTicket;\n\n  /**\n   * @generated from field: yorkie.v1.TextNodeID ins_prev_id = 4;\n   */\n  insPrevId?: TextNodeID;\n\n  /**\n   * @generated from field: map<string, yorkie.v1.NodeAttr> attributes = 5;\n   */\n  attributes: { [key: string]: NodeAttr };\n\n  /**\n   * removal_events is the removal ledger beyond removed_at: every removal of\n   * this node and every undo that cancelled one, except removed_at itself.\n   * An actor's events alternate in ticket order, a removal then the undo\n   * cancelling it, so each is told apart by its place. Empty when removed_at\n   * says it all. A piece recreated after GC records a stand-in removal by the\n   * undoing actor at lamport 0, then its cancel. The pairing relies on an\n   * undo cancelling only its own actor's removal; a change to that rule needs\n   * a new field, not a new reading of this one.\n   *\n   * @generated from field: repeated yorkie.v1.TimeTicket removal_events = 6;\n   */\n  removalEvents: TimeTicket[];\n};\n\n/**\n * Describes the message yorkie.v1.TextNode.\n * Use `create(TextNodeSchema)` to create a new message.\n */\nexport const TextNodeSchema: GenMessage<TextNode> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 11);\n\n/**\n * @generated from message yorkie.v1.TextNodeID\n */\nexport type TextNodeID = Message<\"yorkie.v1.TextNodeID\"> & {\n  /**\n   * @generated from field: yorkie.v1.TimeTicket created_at = 1;\n   */\n  createdAt?: TimeTicket;\n\n  /**\n   * @generated from field: int32 offset = 2;\n   */\n  offset: number;\n};\n\n/**\n * Describes the message yorkie.v1.TextNodeID.\n * Use `create(TextNodeIDSchema)` to create a new message.\n */\nexport const TextNodeIDSchema: GenMessage<TextNodeID> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 12);\n\n/**\n * @generated from message yorkie.v1.TreeNode\n */\nexport type TreeNode = Message<\"yorkie.v1.TreeNode\"> & {\n  /**\n   * @generated from field: yorkie.v1.TreeNodeID id = 1;\n   */\n  id?: TreeNodeID;\n\n  /**\n   * @generated from field: string type = 2;\n   */\n  type: string;\n\n  /**\n   * @generated from field: string value = 3;\n   */\n  value: string;\n\n  /**\n   * @generated from field: yorkie.v1.TimeTicket removed_at = 4;\n   */\n  removedAt?: TimeTicket;\n\n  /**\n   * @generated from field: yorkie.v1.TreeNodeID ins_prev_id = 5;\n   */\n  insPrevId?: TreeNodeID;\n\n  /**\n   * @generated from field: yorkie.v1.TreeNodeID ins_next_id = 6;\n   */\n  insNextId?: TreeNodeID;\n\n  /**\n   * @generated from field: int32 depth = 7;\n   */\n  depth: number;\n\n  /**\n   * @generated from field: map<string, yorkie.v1.NodeAttr> attributes = 8;\n   */\n  attributes: { [key: string]: NodeAttr };\n\n  /**\n   * merged_from is set when this node was moved to a new parent by a\n   * concurrent merge. It points to the source parent's ID.\n   *\n   * @generated from field: yorkie.v1.TreeNodeID merged_from = 9;\n   */\n  mergedFrom?: TreeNodeID;\n\n  /**\n   * merged_at records the immutable ticket of the merge operation.\n   * Stored alongside merged_from because the source parent's removed_at\n   * may be overwritten by later LWW tombstones and thus cannot serve as\n   * the merge-time causal boundary for SplitElement. See\n   * docs/design/concurrent-merge-split.md for details.\n   *\n   * @generated from field: yorkie.v1.TimeTicket merged_at = 10;\n   */\n  mergedAt?: TimeTicket;\n};\n\n/**\n * Describes the message yorkie.v1.TreeNode.\n * Use `create(TreeNodeSchema)` to create a new message.\n */\nexport const TreeNodeSchema: GenMessage<TreeNode> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 13);\n\n/**\n * @generated from message yorkie.v1.TreeNodes\n */\nexport type TreeNodes = Message<\"yorkie.v1.TreeNodes\"> & {\n  /**\n   * @generated from field: repeated yorkie.v1.TreeNode content = 1;\n   */\n  content: TreeNode[];\n};\n\n/**\n * Describes the message yorkie.v1.TreeNodes.\n * Use `create(TreeNodesSchema)` to create a new message.\n */\nexport const TreeNodesSchema: GenMessage<TreeNodes> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 14);\n\n/**\n * @generated from message yorkie.v1.TreeNodeID\n */\nexport type TreeNodeID = Message<\"yorkie.v1.TreeNodeID\"> & {\n  /**\n   * @generated from field: yorkie.v1.TimeTicket created_at = 1;\n   */\n  createdAt?: TimeTicket;\n\n  /**\n   * @generated from field: int32 offset = 2;\n   */\n  offset: number;\n};\n\n/**\n * Describes the message yorkie.v1.TreeNodeID.\n * Use `create(TreeNodeIDSchema)` to create a new message.\n */\nexport const TreeNodeIDSchema: GenMessage<TreeNodeID> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 15);\n\n/**\n * @generated from message yorkie.v1.TreePos\n */\nexport type TreePos = Message<\"yorkie.v1.TreePos\"> & {\n  /**\n   * @generated from field: yorkie.v1.TreeNodeID parent_id = 1;\n   */\n  parentId?: TreeNodeID;\n\n  /**\n   * @generated from field: yorkie.v1.TreeNodeID left_sibling_id = 2;\n   */\n  leftSiblingId?: TreeNodeID;\n};\n\n/**\n * Describes the message yorkie.v1.TreePos.\n * Use `create(TreePosSchema)` to create a new message.\n */\nexport const TreePosSchema: GenMessage<TreePos> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 16);\n\n/**\n * @generated from message yorkie.v1.User\n */\nexport type User = Message<\"yorkie.v1.User\"> & {\n  /**\n   * @generated from field: string id = 1;\n   */\n  id: string;\n\n  /**\n   * @generated from field: string auth_provider = 2;\n   */\n  authProvider: string;\n\n  /**\n   * @generated from field: string username = 3;\n   */\n  username: string;\n\n  /**\n   * @generated from field: google.protobuf.Timestamp created_at = 4;\n   */\n  createdAt?: Timestamp;\n};\n\n/**\n * Describes the message yorkie.v1.User.\n * Use `create(UserSchema)` to create a new message.\n */\nexport const UserSchema: GenMessage<User> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 17);\n\n/**\n * @generated from message yorkie.v1.Member\n */\nexport type Member = Message<\"yorkie.v1.Member\"> & {\n  /**\n   * @generated from field: string id = 1;\n   */\n  id: string;\n\n  /**\n   * @generated from field: string project_id = 2;\n   */\n  projectId: string;\n\n  /**\n   * @generated from field: string user_id = 3;\n   */\n  userId: string;\n\n  /**\n   * @generated from field: string username = 4;\n   */\n  username: string;\n\n  /**\n   * @generated from field: string role = 5;\n   */\n  role: string;\n\n  /**\n   * @generated from field: google.protobuf.Timestamp invited_at = 6;\n   */\n  invitedAt?: Timestamp;\n};\n\n/**\n * Describes the message yorkie.v1.Member.\n * Use `create(MemberSchema)` to create a new message.\n */\nexport const MemberSchema: GenMessage<Member> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 18);\n\n/**\n * @generated from message yorkie.v1.Project\n */\nexport type Project = Message<\"yorkie.v1.Project\"> & {\n  /**\n   * @generated from field: string id = 1;\n   */\n  id: string;\n\n  /**\n   * @generated from field: string name = 2;\n   */\n  name: string;\n\n  /**\n   * @generated from field: string public_key = 3;\n   */\n  publicKey: string;\n\n  /**\n   * @generated from field: string secret_key = 4;\n   */\n  secretKey: string;\n\n  /**\n   * @generated from field: string auth_webhook_url = 5;\n   */\n  authWebhookUrl: string;\n\n  /**\n   * @generated from field: repeated string auth_webhook_methods = 6;\n   */\n  authWebhookMethods: string[];\n\n  /**\n   * @generated from field: uint64 auth_webhook_max_retries = 17;\n   */\n  authWebhookMaxRetries: bigint;\n\n  /**\n   * @generated from field: string auth_webhook_min_wait_interval = 18;\n   */\n  authWebhookMinWaitInterval: string;\n\n  /**\n   * @generated from field: string auth_webhook_max_wait_interval = 19;\n   */\n  authWebhookMaxWaitInterval: string;\n\n  /**\n   * @generated from field: string auth_webhook_request_timeout = 20;\n   */\n  authWebhookRequestTimeout: string;\n\n  /**\n   * @generated from field: string event_webhook_url = 7;\n   */\n  eventWebhookUrl: string;\n\n  /**\n   * @generated from field: repeated string event_webhook_events = 8;\n   */\n  eventWebhookEvents: string[];\n\n  /**\n   * @generated from field: uint64 event_webhook_max_retries = 21;\n   */\n  eventWebhookMaxRetries: bigint;\n\n  /**\n   * @generated from field: string event_webhook_min_wait_interval = 22;\n   */\n  eventWebhookMinWaitInterval: string;\n\n  /**\n   * @generated from field: string event_webhook_max_wait_interval = 23;\n   */\n  eventWebhookMaxWaitInterval: string;\n\n  /**\n   * @generated from field: string event_webhook_request_timeout = 24;\n   */\n  eventWebhookRequestTimeout: string;\n\n  /**\n   * @generated from field: string client_deactivate_threshold = 9;\n   */\n  clientDeactivateThreshold: string;\n\n  /**\n   * @generated from field: int64 snapshot_threshold = 25;\n   */\n  snapshotThreshold: bigint;\n\n  /**\n   * @generated from field: int64 snapshot_interval = 26;\n   */\n  snapshotInterval: bigint;\n\n  /**\n   * @generated from field: int32 max_subscribers_per_document = 10;\n   */\n  maxSubscribersPerDocument: number;\n\n  /**\n   * @generated from field: int32 max_attachments_per_document = 11;\n   */\n  maxAttachmentsPerDocument: number;\n\n  /**\n   * @generated from field: int32 max_size_per_document = 15;\n   */\n  maxSizePerDocument: number;\n\n  /**\n   * @generated from field: bool remove_on_detach = 16;\n   */\n  removeOnDetach: boolean;\n\n  /**\n   * @generated from field: bool auto_revision_enabled = 27;\n   */\n  autoRevisionEnabled: boolean;\n\n  /**\n   * @generated from field: string channel_session_ttl = 28;\n   */\n  channelSessionTtl: string;\n\n  /**\n   * @generated from field: repeated string allowed_origins = 14;\n   */\n  allowedOrigins: string[];\n\n  /**\n   * @generated from field: google.protobuf.Timestamp created_at = 12;\n   */\n  createdAt?: Timestamp;\n\n  /**\n   * @generated from field: google.protobuf.Timestamp updated_at = 13;\n   */\n  updatedAt?: Timestamp;\n};\n\n/**\n * Describes the message yorkie.v1.Project.\n * Use `create(ProjectSchema)` to create a new message.\n */\nexport const ProjectSchema: GenMessage<Project> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 19);\n\n/**\n * @generated from message yorkie.v1.MetricPoint\n */\nexport type MetricPoint = Message<\"yorkie.v1.MetricPoint\"> & {\n  /**\n   * @generated from field: int64 timestamp = 1;\n   */\n  timestamp: bigint;\n\n  /**\n   * @generated from field: int32 value = 2;\n   */\n  value: number;\n};\n\n/**\n * Describes the message yorkie.v1.MetricPoint.\n * Use `create(MetricPointSchema)` to create a new message.\n */\nexport const MetricPointSchema: GenMessage<MetricPoint> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 20);\n\n/**\n * @generated from message yorkie.v1.UpdatableProjectFields\n */\nexport type UpdatableProjectFields = Message<\"yorkie.v1.UpdatableProjectFields\"> & {\n  /**\n   * @generated from field: google.protobuf.StringValue name = 1;\n   */\n  name?: string;\n\n  /**\n   * @generated from field: google.protobuf.StringValue auth_webhook_url = 2;\n   */\n  authWebhookUrl?: string;\n\n  /**\n   * @generated from field: yorkie.v1.UpdatableProjectFields.AuthWebhookMethods auth_webhook_methods = 3;\n   */\n  authWebhookMethods?: UpdatableProjectFields_AuthWebhookMethods;\n\n  /**\n   * @generated from field: google.protobuf.UInt64Value auth_webhook_max_retries = 12;\n   */\n  authWebhookMaxRetries?: bigint;\n\n  /**\n   * @generated from field: google.protobuf.StringValue auth_webhook_min_wait_interval = 13;\n   */\n  authWebhookMinWaitInterval?: string;\n\n  /**\n   * @generated from field: google.protobuf.StringValue auth_webhook_max_wait_interval = 14;\n   */\n  authWebhookMaxWaitInterval?: string;\n\n  /**\n   * @generated from field: google.protobuf.StringValue auth_webhook_request_timeout = 15;\n   */\n  authWebhookRequestTimeout?: string;\n\n  /**\n   * @generated from field: google.protobuf.StringValue event_webhook_url = 4;\n   */\n  eventWebhookUrl?: string;\n\n  /**\n   * @generated from field: yorkie.v1.UpdatableProjectFields.EventWebhookEvents event_webhook_events = 5;\n   */\n  eventWebhookEvents?: UpdatableProjectFields_EventWebhookEvents;\n\n  /**\n   * @generated from field: google.protobuf.UInt64Value event_webhook_max_retries = 16;\n   */\n  eventWebhookMaxRetries?: bigint;\n\n  /**\n   * @generated from field: google.protobuf.StringValue event_webhook_min_wait_interval = 17;\n   */\n  eventWebhookMinWaitInterval?: string;\n\n  /**\n   * @generated from field: google.protobuf.StringValue event_webhook_max_wait_interval = 18;\n   */\n  eventWebhookMaxWaitInterval?: string;\n\n  /**\n   * @generated from field: google.protobuf.StringValue event_webhook_request_timeout = 19;\n   */\n  eventWebhookRequestTimeout?: string;\n\n  /**\n   * @generated from field: google.protobuf.Int64Value snapshot_threshold = 20;\n   */\n  snapshotThreshold?: bigint;\n\n  /**\n   * @generated from field: google.protobuf.Int64Value snapshot_interval = 21;\n   */\n  snapshotInterval?: bigint;\n\n  /**\n   * @generated from field: google.protobuf.StringValue client_deactivate_threshold = 6;\n   */\n  clientDeactivateThreshold?: string;\n\n  /**\n   * @generated from field: google.protobuf.Int32Value max_subscribers_per_document = 7;\n   */\n  maxSubscribersPerDocument?: number;\n\n  /**\n   * @generated from field: google.protobuf.Int32Value max_attachments_per_document = 8;\n   */\n  maxAttachmentsPerDocument?: number;\n\n  /**\n   * @generated from field: google.protobuf.Int32Value max_size_per_document = 10;\n   */\n  maxSizePerDocument?: number;\n\n  /**\n   * @generated from field: google.protobuf.BoolValue remove_on_detach = 11;\n   */\n  removeOnDetach?: boolean;\n\n  /**\n   * @generated from field: google.protobuf.BoolValue auto_revision_enabled = 22;\n   */\n  autoRevisionEnabled?: boolean;\n\n  /**\n   * @generated from field: google.protobuf.StringValue channel_session_ttl = 23;\n   */\n  channelSessionTtl?: string;\n\n  /**\n   * @generated from field: yorkie.v1.UpdatableProjectFields.AllowedOrigins allowed_origins = 9;\n   */\n  allowedOrigins?: UpdatableProjectFields_AllowedOrigins;\n};\n\n/**\n * Describes the message yorkie.v1.UpdatableProjectFields.\n * Use `create(UpdatableProjectFieldsSchema)` to create a new message.\n */\nexport const UpdatableProjectFieldsSchema: GenMessage<UpdatableProjectFields> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 21);\n\n/**\n * @generated from message yorkie.v1.UpdatableProjectFields.AuthWebhookMethods\n */\nexport type UpdatableProjectFields_AuthWebhookMethods = Message<\"yorkie.v1.UpdatableProjectFields.AuthWebhookMethods\"> & {\n  /**\n   * @generated from field: repeated string methods = 1;\n   */\n  methods: string[];\n};\n\n/**\n * Describes the message yorkie.v1.UpdatableProjectFields.AuthWebhookMethods.\n * Use `create(UpdatableProjectFields_AuthWebhookMethodsSchema)` to create a new message.\n */\nexport const UpdatableProjectFields_AuthWebhookMethodsSchema: GenMessage<UpdatableProjectFields_AuthWebhookMethods> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 21, 0);\n\n/**\n * @generated from message yorkie.v1.UpdatableProjectFields.EventWebhookEvents\n */\nexport type UpdatableProjectFields_EventWebhookEvents = Message<\"yorkie.v1.UpdatableProjectFields.EventWebhookEvents\"> & {\n  /**\n   * @generated from field: repeated string events = 1;\n   */\n  events: string[];\n};\n\n/**\n * Describes the message yorkie.v1.UpdatableProjectFields.EventWebhookEvents.\n * Use `create(UpdatableProjectFields_EventWebhookEventsSchema)` to create a new message.\n */\nexport const UpdatableProjectFields_EventWebhookEventsSchema: GenMessage<UpdatableProjectFields_EventWebhookEvents> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 21, 1);\n\n/**\n * @generated from message yorkie.v1.UpdatableProjectFields.AllowedOrigins\n */\nexport type UpdatableProjectFields_AllowedOrigins = Message<\"yorkie.v1.UpdatableProjectFields.AllowedOrigins\"> & {\n  /**\n   * @generated from field: repeated string origins = 1;\n   */\n  origins: string[];\n};\n\n/**\n * Describes the message yorkie.v1.UpdatableProjectFields.AllowedOrigins.\n * Use `create(UpdatableProjectFields_AllowedOriginsSchema)` to create a new message.\n */\nexport const UpdatableProjectFields_AllowedOriginsSchema: GenMessage<UpdatableProjectFields_AllowedOrigins> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 21, 2);\n\n/**\n * @generated from message yorkie.v1.DocumentSummary\n */\nexport type DocumentSummary = Message<\"yorkie.v1.DocumentSummary\"> & {\n  /**\n   * @generated from field: string id = 1;\n   */\n  id: string;\n\n  /**\n   * @generated from field: string key = 2;\n   */\n  key: string;\n\n  /**\n   * @generated from field: string root = 3;\n   */\n  root: string;\n\n  /**\n   * @generated from field: int32 attached_clients = 7;\n   */\n  attachedClients: number;\n\n  /**\n   * @generated from field: yorkie.v1.DocSize document_size = 8;\n   */\n  documentSize?: DocSize;\n\n  /**\n   * @generated from field: string schema_key = 9;\n   */\n  schemaKey: string;\n\n  /**\n   * @generated from field: map<string, yorkie.v1.Presence> presences = 10;\n   */\n  presences: { [key: string]: Presence };\n\n  /**\n   * @generated from field: google.protobuf.Timestamp created_at = 4;\n   */\n  createdAt?: Timestamp;\n\n  /**\n   * @generated from field: google.protobuf.Timestamp accessed_at = 5;\n   */\n  accessedAt?: Timestamp;\n\n  /**\n   * @generated from field: google.protobuf.Timestamp updated_at = 6;\n   */\n  updatedAt?: Timestamp;\n};\n\n/**\n * Describes the message yorkie.v1.DocumentSummary.\n * Use `create(DocumentSummarySchema)` to create a new message.\n */\nexport const DocumentSummarySchema: GenMessage<DocumentSummary> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 22);\n\n/**\n * @generated from message yorkie.v1.PresenceChange\n */\nexport type PresenceChange = Message<\"yorkie.v1.PresenceChange\"> & {\n  /**\n   * @generated from field: yorkie.v1.PresenceChange.ChangeType type = 1;\n   */\n  type: PresenceChange_ChangeType;\n\n  /**\n   * @generated from field: yorkie.v1.Presence presence = 2;\n   */\n  presence?: Presence;\n\n  /**\n   * removed_keys lists the top-level keys a CHANGE_TYPE_PATCH deletes. Unused\n   * by the other change types.\n   *\n   * @generated from field: repeated string removed_keys = 3;\n   */\n  removedKeys: string[];\n};\n\n/**\n * Describes the message yorkie.v1.PresenceChange.\n * Use `create(PresenceChangeSchema)` to create a new message.\n */\nexport const PresenceChangeSchema: GenMessage<PresenceChange> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 23);\n\n/**\n * @generated from enum yorkie.v1.PresenceChange.ChangeType\n */\nexport enum PresenceChange_ChangeType {\n  /**\n   * @generated from enum value: CHANGE_TYPE_UNSPECIFIED = 0;\n   */\n  UNSPECIFIED = 0,\n\n  /**\n   * @generated from enum value: CHANGE_TYPE_PUT = 1;\n   */\n  PUT = 1,\n\n  /**\n   * @generated from enum value: CHANGE_TYPE_DELETE = 2;\n   */\n  DELETE = 2,\n\n  /**\n   * @generated from enum value: CHANGE_TYPE_CLEAR = 3;\n   */\n  CLEAR = 3,\n\n  /**\n   * CHANGE_TYPE_PATCH carries only the top-level keys that changed since\n   * the sender's previous presence: set entries in presence, deleted keys\n   * in removed_keys. Clients send it only to a server that advertises the\n   * \"presence-patch\" capability on ChangePack. The server folds it into\n   * a CHANGE_TYPE_PUT of the full presence before storing, so it never\n   * appears in a pulled change.\n   *\n   * @generated from enum value: CHANGE_TYPE_PATCH = 4;\n   */\n  PATCH = 4,\n}\n\n/**\n * Describes the enum yorkie.v1.PresenceChange.ChangeType.\n */\nexport const PresenceChange_ChangeTypeSchema: GenEnum<PresenceChange_ChangeType> = /*@__PURE__*/\n  enumDesc(file_yorkie_v1_resources, 23, 0);\n\n/**\n * @generated from message yorkie.v1.Presence\n */\nexport type Presence = Message<\"yorkie.v1.Presence\"> & {\n  /**\n   * @generated from field: map<string, string> data = 1;\n   */\n  data: { [key: string]: string };\n};\n\n/**\n * Describes the message yorkie.v1.Presence.\n * Use `create(PresenceSchema)` to create a new message.\n */\nexport const PresenceSchema: GenMessage<Presence> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 24);\n\n/**\n * @generated from message yorkie.v1.ChannelSummary\n */\nexport type ChannelSummary = Message<\"yorkie.v1.ChannelSummary\"> & {\n  /**\n   * @generated from field: string key = 1;\n   */\n  key: string;\n\n  /**\n   * @generated from field: int32 session_count = 2;\n   */\n  sessionCount: number;\n};\n\n/**\n * Describes the message yorkie.v1.ChannelSummary.\n * Use `create(ChannelSummarySchema)` to create a new message.\n */\nexport const ChannelSummarySchema: GenMessage<ChannelSummary> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 25);\n\n/**\n * @generated from message yorkie.v1.Checkpoint\n */\nexport type Checkpoint = Message<\"yorkie.v1.Checkpoint\"> & {\n  /**\n   * @generated from field: int64 server_seq = 1;\n   */\n  serverSeq: bigint;\n\n  /**\n   * @generated from field: uint32 client_seq = 2;\n   */\n  clientSeq: number;\n};\n\n/**\n * Describes the message yorkie.v1.Checkpoint.\n * Use `create(CheckpointSchema)` to create a new message.\n */\nexport const CheckpointSchema: GenMessage<Checkpoint> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 26);\n\n/**\n * @generated from message yorkie.v1.TextNodePos\n */\nexport type TextNodePos = Message<\"yorkie.v1.TextNodePos\"> & {\n  /**\n   * @generated from field: yorkie.v1.TimeTicket created_at = 1;\n   */\n  createdAt?: TimeTicket;\n\n  /**\n   * @generated from field: int32 offset = 2;\n   */\n  offset: number;\n\n  /**\n   * @generated from field: int32 relative_offset = 3;\n   */\n  relativeOffset: number;\n};\n\n/**\n * Describes the message yorkie.v1.TextNodePos.\n * Use `create(TextNodePosSchema)` to create a new message.\n */\nexport const TextNodePosSchema: GenMessage<TextNodePos> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 27);\n\n/**\n * RestoreSpan carries a run of characters from a single original text\n * insertion, addressed by split-invariant absolute offsets [start, end),\n * for identity-preserving undo/redo. content and attributes are a deep\n * copy of the removed value so restore is independent of GC state.\n *\n * @generated from message yorkie.v1.RestoreSpan\n */\nexport type RestoreSpan = Message<\"yorkie.v1.RestoreSpan\"> & {\n  /**\n   * @generated from field: yorkie.v1.TimeTicket created_at = 1;\n   */\n  createdAt?: TimeTicket;\n\n  /**\n   * @generated from field: int32 start = 2;\n   */\n  start: number;\n\n  /**\n   * @generated from field: int32 end = 3;\n   */\n  end: number;\n\n  /**\n   * @generated from field: string content = 4;\n   */\n  content: string;\n\n  /**\n   * @generated from field: map<string, string> attributes = 5;\n   */\n  attributes: { [key: string]: string };\n};\n\n/**\n * Describes the message yorkie.v1.RestoreSpan.\n * Use `create(RestoreSpanSchema)` to create a new message.\n */\nexport const RestoreSpanSchema: GenMessage<RestoreSpan> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 28);\n\n/**\n * TreeRestoreSpan carries a tree node run from a single deletion, addressed\n * by TreeNodeID identity, for identity-preserving Tree undo/redo. Unlike the\n * text RestoreSpan (flat offsets), a tree span records the node's structure\n * (type/attrs) and its position anchors, because in a tree id-order is not\n * sibling-order: left_sibling_id and right_sibling_id are redundant external\n * boundary anchors of the deleted run, so restore can reconstruct the run's\n * internal order from the op's own spans and needs only one surviving\n * boundary to place it. value/attributes are a deep copy so a GC-purged node\n * can be recreated.\n *\n * @generated from message yorkie.v1.TreeRestoreSpan\n */\nexport type TreeRestoreSpan = Message<\"yorkie.v1.TreeRestoreSpan\"> & {\n  /**\n   * @generated from field: yorkie.v1.TreeNodeID id = 1;\n   */\n  id?: TreeNodeID;\n\n  /**\n   * @generated from field: string node_type = 2;\n   */\n  nodeType: string;\n\n  /**\n   * @generated from field: bool is_text = 3;\n   */\n  isText: boolean;\n\n  /**\n   * @generated from field: int32 length = 4;\n   */\n  length: number;\n\n  /**\n   * @generated from field: string value = 5;\n   */\n  value: string;\n\n  /**\n   * @generated from field: map<string, yorkie.v1.NodeAttr> attributes = 6;\n   */\n  attributes: { [key: string]: NodeAttr };\n\n  /**\n   * @generated from field: yorkie.v1.TreeNodeID parent_id = 7;\n   */\n  parentId?: TreeNodeID;\n\n  /**\n   * @generated from field: yorkie.v1.TreeNodeID left_sibling_id = 8;\n   */\n  leftSiblingId?: TreeNodeID;\n\n  /**\n   * @generated from field: yorkie.v1.TreeNodeID right_sibling_id = 9;\n   */\n  rightSiblingId?: TreeNodeID;\n};\n\n/**\n * Describes the message yorkie.v1.TreeRestoreSpan.\n * Use `create(TreeRestoreSpanSchema)` to create a new message.\n */\nexport const TreeRestoreSpanSchema: GenMessage<TreeRestoreSpan> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 29);\n\n/**\n * @generated from message yorkie.v1.TimeTicket\n */\nexport type TimeTicket = Message<\"yorkie.v1.TimeTicket\"> & {\n  /**\n   * @generated from field: int64 lamport = 1;\n   */\n  lamport: bigint;\n\n  /**\n   * @generated from field: uint32 delimiter = 2;\n   */\n  delimiter: number;\n\n  /**\n   * @generated from field: bytes actor_id = 3;\n   */\n  actorId: Uint8Array;\n};\n\n/**\n * Describes the message yorkie.v1.TimeTicket.\n * Use `create(TimeTicketSchema)` to create a new message.\n */\nexport const TimeTicketSchema: GenMessage<TimeTicket> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 30);\n\n/**\n * @generated from message yorkie.v1.DocEventBody\n */\nexport type DocEventBody = Message<\"yorkie.v1.DocEventBody\"> & {\n  /**\n   * @generated from field: string topic = 1;\n   */\n  topic: string;\n\n  /**\n   * @generated from field: bytes payload = 2;\n   */\n  payload: Uint8Array;\n};\n\n/**\n * Describes the message yorkie.v1.DocEventBody.\n * Use `create(DocEventBodySchema)` to create a new message.\n */\nexport const DocEventBodySchema: GenMessage<DocEventBody> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 31);\n\n/**\n * @generated from message yorkie.v1.DocEvent\n */\nexport type DocEvent = Message<\"yorkie.v1.DocEvent\"> & {\n  /**\n   * @generated from field: yorkie.v1.DocEventType type = 1;\n   */\n  type: DocEventType;\n\n  /**\n   * @generated from field: string publisher = 2;\n   */\n  publisher: string;\n\n  /**\n   * @generated from field: yorkie.v1.DocEventBody body = 3;\n   */\n  body?: DocEventBody;\n};\n\n/**\n * Describes the message yorkie.v1.DocEvent.\n * Use `create(DocEventSchema)` to create a new message.\n */\nexport const DocEventSchema: GenMessage<DocEvent> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 32);\n\n/**\n * @generated from message yorkie.v1.ChannelEvent\n */\nexport type ChannelEvent = Message<\"yorkie.v1.ChannelEvent\"> & {\n  /**\n   * @generated from field: yorkie.v1.ChannelEvent.Type type = 1;\n   */\n  type: ChannelEvent_Type;\n\n  /**\n   * @generated from field: string publisher = 2;\n   */\n  publisher: string;\n\n  /**\n   * @generated from field: int64 session_count = 3;\n   */\n  sessionCount: bigint;\n\n  /**\n   * @generated from field: int64 seq = 4;\n   */\n  seq: bigint;\n\n  /**\n   * @generated from field: string topic = 5;\n   */\n  topic: string;\n\n  /**\n   * @generated from field: bytes payload = 6;\n   */\n  payload: Uint8Array;\n};\n\n/**\n * Describes the message yorkie.v1.ChannelEvent.\n * Use `create(ChannelEventSchema)` to create a new message.\n */\nexport const ChannelEventSchema: GenMessage<ChannelEvent> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 33);\n\n/**\n * @generated from enum yorkie.v1.ChannelEvent.Type\n */\nexport enum ChannelEvent_Type {\n  /**\n   * @generated from enum value: TYPE_UNSPECIFIED = 0;\n   */\n  UNSPECIFIED = 0,\n\n  /**\n   * @generated from enum value: TYPE_PRESENCE = 1;\n   */\n  PRESENCE = 1,\n\n  /**\n   * @generated from enum value: TYPE_BROADCAST = 2;\n   */\n  BROADCAST = 2,\n}\n\n/**\n * Describes the enum yorkie.v1.ChannelEvent.Type.\n */\nexport const ChannelEvent_TypeSchema: GenEnum<ChannelEvent_Type> = /*@__PURE__*/\n  enumDesc(file_yorkie_v1_resources, 33, 0);\n\n/**\n * @generated from message yorkie.v1.DataSize\n */\nexport type DataSize = Message<\"yorkie.v1.DataSize\"> & {\n  /**\n   * @generated from field: int32 data = 1;\n   */\n  data: number;\n\n  /**\n   * @generated from field: int32 meta = 2;\n   */\n  meta: number;\n};\n\n/**\n * Describes the message yorkie.v1.DataSize.\n * Use `create(DataSizeSchema)` to create a new message.\n */\nexport const DataSizeSchema: GenMessage<DataSize> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 34);\n\n/**\n * @generated from message yorkie.v1.DocSize\n */\nexport type DocSize = Message<\"yorkie.v1.DocSize\"> & {\n  /**\n   * @generated from field: yorkie.v1.DataSize live = 1;\n   */\n  live?: DataSize;\n\n  /**\n   * @generated from field: yorkie.v1.DataSize gc = 2;\n   */\n  gc?: DataSize;\n};\n\n/**\n * Describes the message yorkie.v1.DocSize.\n * Use `create(DocSizeSchema)` to create a new message.\n */\nexport const DocSizeSchema: GenMessage<DocSize> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 35);\n\n/**\n * @generated from message yorkie.v1.Schema\n */\nexport type Schema = Message<\"yorkie.v1.Schema\"> & {\n  /**\n   * @generated from field: string id = 1;\n   */\n  id: string;\n\n  /**\n   * @generated from field: string name = 2;\n   */\n  name: string;\n\n  /**\n   * @generated from field: int32 version = 3;\n   */\n  version: number;\n\n  /**\n   * @generated from field: string body = 4;\n   */\n  body: string;\n\n  /**\n   * @generated from field: repeated yorkie.v1.Rule rules = 5;\n   */\n  rules: Rule[];\n\n  /**\n   * @generated from field: google.protobuf.Timestamp created_at = 6;\n   */\n  createdAt?: Timestamp;\n};\n\n/**\n * Describes the message yorkie.v1.Schema.\n * Use `create(SchemaSchema)` to create a new message.\n */\nexport const SchemaSchema: GenMessage<Schema> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 36);\n\n/**\n * @generated from message yorkie.v1.TreeNodeRule\n */\nexport type TreeNodeRule = Message<\"yorkie.v1.TreeNodeRule\"> & {\n  /**\n   * @generated from field: string node_type = 1;\n   */\n  nodeType: string;\n\n  /**\n   * @generated from field: string content = 2;\n   */\n  content: string;\n\n  /**\n   * @generated from field: string marks = 3;\n   */\n  marks: string;\n\n  /**\n   * @generated from field: string group = 4;\n   */\n  group: string;\n};\n\n/**\n * Describes the message yorkie.v1.TreeNodeRule.\n * Use `create(TreeNodeRuleSchema)` to create a new message.\n */\nexport const TreeNodeRuleSchema: GenMessage<TreeNodeRule> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 37);\n\n/**\n * @generated from message yorkie.v1.Rule\n */\nexport type Rule = Message<\"yorkie.v1.Rule\"> & {\n  /**\n   * @generated from field: string path = 1;\n   */\n  path: string;\n\n  /**\n   * @generated from field: string type = 2;\n   */\n  type: string;\n\n  /**\n   * @generated from field: repeated yorkie.v1.TreeNodeRule tree_nodes = 3;\n   */\n  treeNodes: TreeNodeRule[];\n};\n\n/**\n * Describes the message yorkie.v1.Rule.\n * Use `create(RuleSchema)` to create a new message.\n */\nexport const RuleSchema: GenMessage<Rule> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 38);\n\n/**\n * @generated from message yorkie.v1.RevisionSummary\n */\nexport type RevisionSummary = Message<\"yorkie.v1.RevisionSummary\"> & {\n  /**\n   * @generated from field: string id = 1;\n   */\n  id: string;\n\n  /**\n   * @generated from field: string label = 2;\n   */\n  label: string;\n\n  /**\n   * @generated from field: string description = 3;\n   */\n  description: string;\n\n  /**\n   * @generated from field: string snapshot = 4;\n   */\n  snapshot: string;\n\n  /**\n   * @generated from field: google.protobuf.Timestamp created_at = 5;\n   */\n  createdAt?: Timestamp;\n};\n\n/**\n * Describes the message yorkie.v1.RevisionSummary.\n * Use `create(RevisionSummarySchema)` to create a new message.\n */\nexport const RevisionSummarySchema: GenMessage<RevisionSummary> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_resources, 39);\n\n/**\n * RestoreMode selects the identity-preserving path. RESTORE_MODE_UNSPECIFIED\n * means an ordinary edit (no restore semantics), keeping forward edits\n * unchanged on the wire.\n *\n * For elements it selects between reviving the element already in the tree and\n * inserting a copy of it. The copy is what undo does today, and because a\n * deep copy keeps every descendant's created_at, it puts a second live element\n * under ids the document is indexed by. Reviving needs a replicated liveness\n * register -- removed_at paired with revived_at on each element -- so that\n * every replica resolves a remove/revive race the same way, with a tie going\n * to the removal as the shipped remove register already does.\n *\n * The branch cannot be chosen from local state. A replica that collected\n * between the removal and the undo has purged the tombstone, and one that\n * joined from a later snapshot never had it, so \"revive if a tombstone is\n * present\" is a function of local collection timing and the same change log\n * would produce different documents. That is why the branch is on the wire.\n *\n * @generated from enum yorkie.v1.RestoreMode\n */\nexport enum RestoreMode {\n  /**\n   * @generated from enum value: RESTORE_MODE_UNSPECIFIED = 0;\n   */\n  UNSPECIFIED = 0,\n\n  /**\n   * @generated from enum value: RESTORE_MODE_RESTORE = 1;\n   */\n  RESTORE = 1,\n\n  /**\n   * @generated from enum value: RESTORE_MODE_RETOMBSTONE = 2;\n   */\n  RETOMBSTONE = 2,\n}\n\n/**\n * Describes the enum yorkie.v1.RestoreMode.\n */\nexport const RestoreModeSchema: GenEnum<RestoreMode> = /*@__PURE__*/\n  enumDesc(file_yorkie_v1_resources, 0);\n\n/**\n * @generated from enum yorkie.v1.ValueType\n */\nexport enum ValueType {\n  /**\n   * @generated from enum value: VALUE_TYPE_NULL = 0;\n   */\n  NULL = 0,\n\n  /**\n   * @generated from enum value: VALUE_TYPE_BOOLEAN = 1;\n   */\n  BOOLEAN = 1,\n\n  /**\n   * @generated from enum value: VALUE_TYPE_INTEGER = 2;\n   */\n  INTEGER = 2,\n\n  /**\n   * @generated from enum value: VALUE_TYPE_LONG = 3;\n   */\n  LONG = 3,\n\n  /**\n   * @generated from enum value: VALUE_TYPE_DOUBLE = 4;\n   */\n  DOUBLE = 4,\n\n  /**\n   * @generated from enum value: VALUE_TYPE_STRING = 5;\n   */\n  STRING = 5,\n\n  /**\n   * @generated from enum value: VALUE_TYPE_BYTES = 6;\n   */\n  BYTES = 6,\n\n  /**\n   * @generated from enum value: VALUE_TYPE_DATE = 7;\n   */\n  DATE = 7,\n\n  /**\n   * @generated from enum value: VALUE_TYPE_JSON_OBJECT = 8;\n   */\n  JSON_OBJECT = 8,\n\n  /**\n   * @generated from enum value: VALUE_TYPE_JSON_ARRAY = 9;\n   */\n  JSON_ARRAY = 9,\n\n  /**\n   * @generated from enum value: VALUE_TYPE_TEXT = 10;\n   */\n  TEXT = 10,\n\n  /**\n   * @generated from enum value: VALUE_TYPE_INTEGER_CNT = 11;\n   */\n  INTEGER_CNT = 11,\n\n  /**\n   * @generated from enum value: VALUE_TYPE_LONG_CNT = 12;\n   */\n  LONG_CNT = 12,\n\n  /**\n   * @generated from enum value: VALUE_TYPE_TREE = 13;\n   */\n  TREE = 13,\n\n  /**\n   * @generated from enum value: VALUE_TYPE_INTEGER_DEDUP_CNT = 14;\n   */\n  INTEGER_DEDUP_CNT = 14,\n}\n\n/**\n * Describes the enum yorkie.v1.ValueType.\n */\nexport const ValueTypeSchema: GenEnum<ValueType> = /*@__PURE__*/\n  enumDesc(file_yorkie_v1_resources, 1);\n\n/**\n * @generated from enum yorkie.v1.DocEventType\n */\nexport enum DocEventType {\n  /**\n   * @generated from enum value: DOC_EVENT_TYPE_DOCUMENT_CHANGED = 0;\n   */\n  DOCUMENT_CHANGED = 0,\n\n  /**\n   * @generated from enum value: DOC_EVENT_TYPE_DOCUMENT_WATCHED = 1;\n   */\n  DOCUMENT_WATCHED = 1,\n\n  /**\n   * @generated from enum value: DOC_EVENT_TYPE_DOCUMENT_UNWATCHED = 2;\n   */\n  DOCUMENT_UNWATCHED = 2,\n\n  /**\n   * @generated from enum value: DOC_EVENT_TYPE_DOCUMENT_BROADCAST = 3;\n   */\n  DOCUMENT_BROADCAST = 3,\n}\n\n/**\n * Describes the enum yorkie.v1.DocEventType.\n */\nexport const DocEventTypeSchema: GenEnum<DocEventType> = /*@__PURE__*/\n  enumDesc(file_yorkie_v1_resources, 2);\n\n","//\n// Copyright 2020 The Yorkie Authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n// @generated by protoc-gen-es v2.10.1 with parameter \"target=ts,import_extension=none\"\n// @generated from file yorkie/v1/yorkie.proto (package yorkie.v1, syntax proto3)\n/* eslint-disable */\n\nimport type { GenFile, GenMessage, GenService } from \"@bufbuild/protobuf/codegenv2\";\nimport { fileDesc, messageDesc, serviceDesc } from \"@bufbuild/protobuf/codegenv2\";\nimport type { ChangePack, ChannelEvent, DocEvent, RevisionSummary, Rule } from \"./resources_pb\";\nimport { file_yorkie_v1_resources } from \"./resources_pb\";\nimport type { Message } from \"@bufbuild/protobuf\";\n\n/**\n * Describes the file yorkie/v1/yorkie.proto.\n */\nexport const file_yorkie_v1_yorkie: GenFile = /*@__PURE__*/\n  fileDesc(\"ChZ5b3JraWUvdjEveW9ya2llLnByb3RvEgl5b3JraWUudjEingEKFUFjdGl2YXRlQ2xpZW50UmVxdWVzdBISCgpjbGllbnRfa2V5GAEgASgJEkAKCG1ldGFkYXRhGAIgAygLMi4ueW9ya2llLnYxLkFjdGl2YXRlQ2xpZW50UmVxdWVzdC5NZXRhZGF0YUVudHJ5Gi8KDU1ldGFkYXRhRW50cnkSCwoDa2V5GAEgASgJEg0KBXZhbHVlGAIgASgJOgI4ASI9ChZBY3RpdmF0ZUNsaWVudFJlc3BvbnNlEhEKCWNsaWVudF9pZBgBIAEoCRIQCghhY3Rvcl9pZBgCIAEoCSJBChdEZWFjdGl2YXRlQ2xpZW50UmVxdWVzdBIRCgljbGllbnRfaWQYASABKAkSEwoLc3luY2hyb25vdXMYAiABKAgiGgoYRGVhY3RpdmF0ZUNsaWVudFJlc3BvbnNlIpgBChVBdHRhY2hEb2N1bWVudFJlcXVlc3QSEQoJY2xpZW50X2lkGAEgASgJEioKC2NoYW5nZV9wYWNrGAIgASgLMhUueW9ya2llLnYxLkNoYW5nZVBhY2sSEgoKc2NoZW1hX2tleRgDIAEoCRISCgpkaXNhYmxlX2djGAQgASgIEhgKEGRpc2FibGVfcHJlc2VuY2UYBSABKAgiuQEKFkF0dGFjaERvY3VtZW50UmVzcG9uc2USEwoLZG9jdW1lbnRfaWQYASABKAkSKgoLY2hhbmdlX3BhY2sYAiABKAsyFS55b3JraWUudjEuQ2hhbmdlUGFjaxIdChVtYXhfc2l6ZV9wZXJfZG9jdW1lbnQYAyABKAUSJQoMc2NoZW1hX3J1bGVzGAQgAygLMg8ue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ABJUCg1BdHRhY2hDaGFubmVsEh8ueW9ya2llLnYxLkF0dGFjaENoYW5uZWxSZXF1ZXN0GiAueW9ya2llLnYxLkF0dGFjaENoYW5uZWxSZXNwb25zZSIAElQKDURldGFjaENoYW5uZWwSHy55b3JraWUudjEuRGV0YWNoQ2hhbm5lbFJlcXVlc3QaIC55b3JraWUudjEuRGV0YWNoQ2hhbm5lbFJlc3BvbnNlIgASVwoOUmVmcmVzaENoYW5uZWwSIC55b3JraWUudjEuUmVmcmVzaENoYW5uZWxSZXF1ZXN0GiEueW9ya2llLnYxLlJlZnJlc2hDaGFubmVsUmVzcG9uc2UiABJOCgtQZWVrQ2hhbm5lbBIdLnlvcmtpZS52MS5QZWVrQ2hhbm5lbFJlcXVlc3QaHi55b3JraWUudjEuUGVla0NoYW5uZWxSZXNwb25zZSIAEkgKCUJyb2FkY2FzdBIbLnlvcmtpZS52MS5Ccm9hZGNhc3RSZXF1ZXN0GhwueW9ya2llLnYxLkJyb2FkY2FzdFJlc3BvbnNlIgBCRQoRZGV2LnlvcmtpZS5hcGkudjFQAVouZ2l0aHViLmNvbS95b3JraWUtdGVhbS95b3JraWUvYXBpL3lvcmtpZS92MTt2MWIGcHJvdG8z\", [file_yorkie_v1_resources]);\n\n/**\n * @generated from message yorkie.v1.ActivateClientRequest\n */\nexport type ActivateClientRequest = Message<\"yorkie.v1.ActivateClientRequest\"> & {\n  /**\n   * @generated from field: string client_key = 1;\n   */\n  clientKey: string;\n\n  /**\n   * @generated from field: map<string, string> metadata = 2;\n   */\n  metadata: { [key: string]: string };\n};\n\n/**\n * Describes the message yorkie.v1.ActivateClientRequest.\n * Use `create(ActivateClientRequestSchema)` to create a new message.\n */\nexport const ActivateClientRequestSchema: GenMessage<ActivateClientRequest> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 0);\n\n/**\n * @generated from message yorkie.v1.ActivateClientResponse\n */\nexport type ActivateClientResponse = Message<\"yorkie.v1.ActivateClientResponse\"> & {\n  /**\n   * @generated from field: string client_id = 1;\n   */\n  clientId: string;\n\n  /**\n   * actor_id is the stable actor derived from the project and client key.\n   * Opted-in SDKs stamp it into changes; old SDKs ignore it and keep using\n   * client_id as their actor.\n   *\n   * @generated from field: string actor_id = 2;\n   */\n  actorId: string;\n};\n\n/**\n * Describes the message yorkie.v1.ActivateClientResponse.\n * Use `create(ActivateClientResponseSchema)` to create a new message.\n */\nexport const ActivateClientResponseSchema: GenMessage<ActivateClientResponse> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 1);\n\n/**\n * @generated from message yorkie.v1.DeactivateClientRequest\n */\nexport type DeactivateClientRequest = Message<\"yorkie.v1.DeactivateClientRequest\"> & {\n  /**\n   * @generated from field: string client_id = 1;\n   */\n  clientId: string;\n\n  /**\n   * @generated from field: bool synchronous = 2;\n   */\n  synchronous: boolean;\n};\n\n/**\n * Describes the message yorkie.v1.DeactivateClientRequest.\n * Use `create(DeactivateClientRequestSchema)` to create a new message.\n */\nexport const DeactivateClientRequestSchema: GenMessage<DeactivateClientRequest> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 2);\n\n/**\n * @generated from message yorkie.v1.DeactivateClientResponse\n */\nexport type DeactivateClientResponse = Message<\"yorkie.v1.DeactivateClientResponse\"> & {\n};\n\n/**\n * Describes the message yorkie.v1.DeactivateClientResponse.\n * Use `create(DeactivateClientResponseSchema)` to create a new message.\n */\nexport const DeactivateClientResponseSchema: GenMessage<DeactivateClientResponse> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 3);\n\n/**\n * @generated from message yorkie.v1.AttachDocumentRequest\n */\nexport type AttachDocumentRequest = Message<\"yorkie.v1.AttachDocumentRequest\"> & {\n  /**\n   * @generated from field: string client_id = 1;\n   */\n  clientId: string;\n\n  /**\n   * @generated from field: yorkie.v1.ChangePack change_pack = 2;\n   */\n  changePack?: ChangePack;\n\n  /**\n   * @generated from field: string schema_key = 3;\n   */\n  schemaKey: string;\n\n  /**\n   * disable_gc declares that this attachment will not produce or consume\n   * tombstones. The server skips minVV tracking and omits the response\n   * VersionVector for this client. Use only with Counter / primitive\n   * workloads; misuse leads to undefined GC behavior on this client.\n   *\n   * @generated from field: bool disable_gc = 4;\n   */\n  disableGc: boolean;\n\n  /**\n   * disable_presence declares that this document does not produce, consume,\n   * or store presence. Honored on first attach only; subsequent attaches\n   * observe the value persisted in the server-side document metadata. See\n   * docs/tasks/active/20260616-presenceless-document-option-todo.md.\n   *\n   * @generated from field: bool disable_presence = 5;\n   */\n  disablePresence: boolean;\n};\n\n/**\n * Describes the message yorkie.v1.AttachDocumentRequest.\n * Use `create(AttachDocumentRequestSchema)` to create a new message.\n */\nexport const AttachDocumentRequestSchema: GenMessage<AttachDocumentRequest> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 4);\n\n/**\n * @generated from message yorkie.v1.AttachDocumentResponse\n */\nexport type AttachDocumentResponse = Message<\"yorkie.v1.AttachDocumentResponse\"> & {\n  /**\n   * @generated from field: string document_id = 1;\n   */\n  documentId: string;\n\n  /**\n   * @generated from field: yorkie.v1.ChangePack change_pack = 2;\n   */\n  changePack?: ChangePack;\n\n  /**\n   * @generated from field: int32 max_size_per_document = 3;\n   */\n  maxSizePerDocument: number;\n\n  /**\n   * @generated from field: repeated yorkie.v1.Rule schema_rules = 4;\n   */\n  schemaRules: Rule[];\n\n  /**\n   * disable_presence carries the server-fixated value of the document's\n   * presence option (see AttachDocumentRequest.disable_presence). Clients\n   * align their local gating state to this value rather than the requested\n   * value, so an attach to an already-fixated document observes the\n   * persisted decision.\n   *\n   * @generated from field: bool disable_presence = 5;\n   */\n  disablePresence: boolean;\n};\n\n/**\n * Describes the message yorkie.v1.AttachDocumentResponse.\n * Use `create(AttachDocumentResponseSchema)` to create a new message.\n */\nexport const AttachDocumentResponseSchema: GenMessage<AttachDocumentResponse> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 5);\n\n/**\n * @generated from message yorkie.v1.DetachDocumentRequest\n */\nexport type DetachDocumentRequest = Message<\"yorkie.v1.DetachDocumentRequest\"> & {\n  /**\n   * @generated from field: string client_id = 1;\n   */\n  clientId: string;\n\n  /**\n   * @generated from field: string document_id = 2;\n   */\n  documentId: string;\n\n  /**\n   * @generated from field: yorkie.v1.ChangePack change_pack = 3;\n   */\n  changePack?: ChangePack;\n\n  /**\n   * @generated from field: bool remove_if_not_attached = 4;\n   */\n  removeIfNotAttached: boolean;\n};\n\n/**\n * Describes the message yorkie.v1.DetachDocumentRequest.\n * Use `create(DetachDocumentRequestSchema)` to create a new message.\n */\nexport const DetachDocumentRequestSchema: GenMessage<DetachDocumentRequest> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 6);\n\n/**\n * @generated from message yorkie.v1.DetachDocumentResponse\n */\nexport type DetachDocumentResponse = Message<\"yorkie.v1.DetachDocumentResponse\"> & {\n  /**\n   * @generated from field: yorkie.v1.ChangePack change_pack = 2;\n   */\n  changePack?: ChangePack;\n};\n\n/**\n * Describes the message yorkie.v1.DetachDocumentResponse.\n * Use `create(DetachDocumentResponseSchema)` to create a new message.\n */\nexport const DetachDocumentResponseSchema: GenMessage<DetachDocumentResponse> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 7);\n\n/**\n * @generated from message yorkie.v1.WatchRequest\n */\nexport type WatchRequest = Message<\"yorkie.v1.WatchRequest\"> & {\n  /**\n   * @generated from field: string client_id = 1;\n   */\n  clientId: string;\n\n  /**\n   * resources lists what the stream delivers. It must hold between 1 and 100\n   * descriptors, and the server must recognize every one of them: a request\n   * naming a resource the server cannot subscribe to is rejected whole rather\n   * than served in part, so a client never watches fewer resources than it\n   * asked for without being told.\n   *\n   * @generated from field: repeated yorkie.v1.ResourceDescriptor resources = 2;\n   */\n  resources: ResourceDescriptor[];\n\n  /**\n   * actor_id is the stable actor the client stamps into its changes. When set,\n   * the server subscribes the client under it so watch peer ids and\n   * watched/unwatched events match the presence CRDT keying. Old SDKs omit it\n   * and the server falls back to client_id (the session id).\n   *\n   * @generated from field: string actor_id = 3;\n   */\n  actorId: string;\n\n  /**\n   * heartbeat_interval_ms is the interval, in milliseconds, at which this\n   * stream asks the server to send a WatchHeartbeat while it is idle. 0, which\n   * is also what an SDK older than the heartbeat leaves here, asks for none:\n   * such a stream gets no WatchHeartbeat bodies at all, so the heartbeat can\n   * never reach a client that would not recognize it. The server clamps the\n   * request to its own bounds and reports the value it settled on in\n   * WatchInitialization.heartbeat_interval_ms.\n   *\n   * @generated from field: int64 heartbeat_interval_ms = 4;\n   */\n  heartbeatIntervalMs: bigint;\n};\n\n/**\n * Describes the message yorkie.v1.WatchRequest.\n * Use `create(WatchRequestSchema)` to create a new message.\n */\nexport const WatchRequestSchema: GenMessage<WatchRequest> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 8);\n\n/**\n * @generated from message yorkie.v1.ResourceDescriptor\n */\nexport type ResourceDescriptor = Message<\"yorkie.v1.ResourceDescriptor\"> & {\n  /**\n   * @generated from oneof yorkie.v1.ResourceDescriptor.resource\n   */\n  resource: {\n    /**\n     * @generated from field: yorkie.v1.DocumentDescriptor document = 1;\n     */\n    value: DocumentDescriptor;\n    case: \"document\";\n  } | {\n    /**\n     * @generated from field: yorkie.v1.ChannelDescriptor channel = 2;\n     */\n    value: ChannelDescriptor;\n    case: \"channel\";\n  } | { case: undefined; value?: undefined };\n};\n\n/**\n * Describes the message yorkie.v1.ResourceDescriptor.\n * Use `create(ResourceDescriptorSchema)` to create a new message.\n */\nexport const ResourceDescriptorSchema: GenMessage<ResourceDescriptor> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 9);\n\n/**\n * @generated from message yorkie.v1.DocumentDescriptor\n */\nexport type DocumentDescriptor = Message<\"yorkie.v1.DocumentDescriptor\"> & {\n  /**\n   * @generated from field: string document_id = 1;\n   */\n  documentId: string;\n};\n\n/**\n * Describes the message yorkie.v1.DocumentDescriptor.\n * Use `create(DocumentDescriptorSchema)` to create a new message.\n */\nexport const DocumentDescriptorSchema: GenMessage<DocumentDescriptor> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 10);\n\n/**\n * @generated from message yorkie.v1.ChannelDescriptor\n */\nexport type ChannelDescriptor = Message<\"yorkie.v1.ChannelDescriptor\"> & {\n  /**\n   * @generated from field: string channel_key = 1;\n   */\n  channelKey: string;\n};\n\n/**\n * Describes the message yorkie.v1.ChannelDescriptor.\n * Use `create(ChannelDescriptorSchema)` to create a new message.\n */\nexport const ChannelDescriptorSchema: GenMessage<ChannelDescriptor> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 11);\n\n/**\n * @generated from message yorkie.v1.WatchResponse\n */\nexport type WatchResponse = Message<\"yorkie.v1.WatchResponse\"> & {\n  /**\n   * @generated from oneof yorkie.v1.WatchResponse.body\n   */\n  body: {\n    /**\n     * @generated from field: yorkie.v1.WatchInitialization initialization = 1;\n     */\n    value: WatchInitialization;\n    case: \"initialization\";\n  } | {\n    /**\n     * @generated from field: yorkie.v1.WatchEvent event = 2;\n     */\n    value: WatchEvent;\n    case: \"event\";\n  } | {\n    /**\n     * @generated from field: yorkie.v1.WatchHeartbeat heartbeat = 3;\n     */\n    value: WatchHeartbeat;\n    case: \"heartbeat\";\n  } | { case: undefined; value?: undefined };\n};\n\n/**\n * Describes the message yorkie.v1.WatchResponse.\n * Use `create(WatchResponseSchema)` to create a new message.\n */\nexport const WatchResponseSchema: GenMessage<WatchResponse> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 12);\n\n/**\n * @generated from message yorkie.v1.WatchInitialization\n */\nexport type WatchInitialization = Message<\"yorkie.v1.WatchInitialization\"> & {\n  /**\n   * @generated from field: repeated yorkie.v1.ResourceInit resource_inits = 1;\n   */\n  resourceInits: ResourceInit[];\n\n  /**\n   * heartbeat_interval_ms is the interval, in milliseconds, at which the\n   * server sends a WatchHeartbeat on this stream while it is idle. 0 means\n   * the server sends none, so the client must not apply an idle timeout.\n   *\n   * @generated from field: int64 heartbeat_interval_ms = 2;\n   */\n  heartbeatIntervalMs: bigint;\n};\n\n/**\n * Describes the message yorkie.v1.WatchInitialization.\n * Use `create(WatchInitializationSchema)` to create a new message.\n */\nexport const WatchInitializationSchema: GenMessage<WatchInitialization> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 13);\n\n/**\n * WatchHeartbeat is sent on an idle Watch stream so a client can tell a live\n * stream from a half-open one. It carries no payload: its arrival is the\n * signal.\n *\n * @generated from message yorkie.v1.WatchHeartbeat\n */\nexport type WatchHeartbeat = Message<\"yorkie.v1.WatchHeartbeat\"> & {\n};\n\n/**\n * Describes the message yorkie.v1.WatchHeartbeat.\n * Use `create(WatchHeartbeatSchema)` to create a new message.\n */\nexport const WatchHeartbeatSchema: GenMessage<WatchHeartbeat> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 14);\n\n/**\n * @generated from message yorkie.v1.ResourceInit\n */\nexport type ResourceInit = Message<\"yorkie.v1.ResourceInit\"> & {\n  /**\n   * @generated from oneof yorkie.v1.ResourceInit.init\n   */\n  init: {\n    /**\n     * @generated from field: yorkie.v1.DocumentInit document_init = 1;\n     */\n    value: DocumentInit;\n    case: \"documentInit\";\n  } | {\n    /**\n     * @generated from field: yorkie.v1.ChannelInit channel_init = 2;\n     */\n    value: ChannelInit;\n    case: \"channelInit\";\n  } | { case: undefined; value?: undefined };\n};\n\n/**\n * Describes the message yorkie.v1.ResourceInit.\n * Use `create(ResourceInitSchema)` to create a new message.\n */\nexport const ResourceInitSchema: GenMessage<ResourceInit> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 15);\n\n/**\n * @generated from message yorkie.v1.DocumentInit\n */\nexport type DocumentInit = Message<\"yorkie.v1.DocumentInit\"> & {\n  /**\n   * @generated from field: string document_id = 1;\n   */\n  documentId: string;\n\n  /**\n   * @generated from field: repeated string client_ids = 2;\n   */\n  clientIds: string[];\n};\n\n/**\n * Describes the message yorkie.v1.DocumentInit.\n * Use `create(DocumentInitSchema)` to create a new message.\n */\nexport const DocumentInitSchema: GenMessage<DocumentInit> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 16);\n\n/**\n * @generated from message yorkie.v1.ChannelInit\n */\nexport type ChannelInit = Message<\"yorkie.v1.ChannelInit\"> & {\n  /**\n   * @generated from field: string channel_key = 1;\n   */\n  channelKey: string;\n\n  /**\n   * @generated from field: int64 session_count = 2;\n   */\n  sessionCount: bigint;\n\n  /**\n   * @generated from field: int64 seq = 3;\n   */\n  seq: bigint;\n};\n\n/**\n * Describes the message yorkie.v1.ChannelInit.\n * Use `create(ChannelInitSchema)` to create a new message.\n */\nexport const ChannelInitSchema: GenMessage<ChannelInit> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 17);\n\n/**\n * @generated from message yorkie.v1.WatchEvent\n */\nexport type WatchEvent = Message<\"yorkie.v1.WatchEvent\"> & {\n  /**\n   * @generated from oneof yorkie.v1.WatchEvent.event\n   */\n  event: {\n    /**\n     * @generated from field: yorkie.v1.DocWatchEvent doc_event = 1;\n     */\n    value: DocWatchEvent;\n    case: \"docEvent\";\n  } | {\n    /**\n     * @generated from field: yorkie.v1.ChannelWatchEvent channel_event = 2;\n     */\n    value: ChannelWatchEvent;\n    case: \"channelEvent\";\n  } | { case: undefined; value?: undefined };\n};\n\n/**\n * Describes the message yorkie.v1.WatchEvent.\n * Use `create(WatchEventSchema)` to create a new message.\n */\nexport const WatchEventSchema: GenMessage<WatchEvent> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 18);\n\n/**\n * @generated from message yorkie.v1.DocWatchEvent\n */\nexport type DocWatchEvent = Message<\"yorkie.v1.DocWatchEvent\"> & {\n  /**\n   * @generated from field: string document_id = 1;\n   */\n  documentId: string;\n\n  /**\n   * @generated from field: yorkie.v1.DocEvent event = 2;\n   */\n  event?: DocEvent;\n};\n\n/**\n * Describes the message yorkie.v1.DocWatchEvent.\n * Use `create(DocWatchEventSchema)` to create a new message.\n */\nexport const DocWatchEventSchema: GenMessage<DocWatchEvent> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 19);\n\n/**\n * @generated from message yorkie.v1.ChannelWatchEvent\n */\nexport type ChannelWatchEvent = Message<\"yorkie.v1.ChannelWatchEvent\"> & {\n  /**\n   * @generated from field: string channel_key = 1;\n   */\n  channelKey: string;\n\n  /**\n   * @generated from field: yorkie.v1.ChannelEvent event = 2;\n   */\n  event?: ChannelEvent;\n};\n\n/**\n * Describes the message yorkie.v1.ChannelWatchEvent.\n * Use `create(ChannelWatchEventSchema)` to create a new message.\n */\nexport const ChannelWatchEventSchema: GenMessage<ChannelWatchEvent> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 20);\n\n/**\n * Deprecated: Use WatchRequest instead.\n *\n * @generated from message yorkie.v1.WatchDocumentRequest\n */\nexport type WatchDocumentRequest = Message<\"yorkie.v1.WatchDocumentRequest\"> & {\n  /**\n   * @generated from field: string client_id = 1;\n   */\n  clientId: string;\n\n  /**\n   * @generated from field: string document_id = 2;\n   */\n  documentId: string;\n};\n\n/**\n * Describes the message yorkie.v1.WatchDocumentRequest.\n * Use `create(WatchDocumentRequestSchema)` to create a new message.\n */\nexport const WatchDocumentRequestSchema: GenMessage<WatchDocumentRequest> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 21);\n\n/**\n * Deprecated: Use WatchResponse instead.\n *\n * @generated from message yorkie.v1.WatchDocumentResponse\n */\nexport type WatchDocumentResponse = Message<\"yorkie.v1.WatchDocumentResponse\"> & {\n  /**\n   * @generated from oneof yorkie.v1.WatchDocumentResponse.body\n   */\n  body: {\n    /**\n     * @generated from field: yorkie.v1.WatchDocumentResponse.Initialization initialization = 1;\n     */\n    value: WatchDocumentResponse_Initialization;\n    case: \"initialization\";\n  } | {\n    /**\n     * @generated from field: yorkie.v1.DocEvent event = 2;\n     */\n    value: DocEvent;\n    case: \"event\";\n  } | { case: undefined; value?: undefined };\n};\n\n/**\n * Describes the message yorkie.v1.WatchDocumentResponse.\n * Use `create(WatchDocumentResponseSchema)` to create a new message.\n */\nexport const WatchDocumentResponseSchema: GenMessage<WatchDocumentResponse> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 22);\n\n/**\n * @generated from message yorkie.v1.WatchDocumentResponse.Initialization\n */\nexport type WatchDocumentResponse_Initialization = Message<\"yorkie.v1.WatchDocumentResponse.Initialization\"> & {\n  /**\n   * @generated from field: repeated string client_ids = 1;\n   */\n  clientIds: string[];\n};\n\n/**\n * Describes the message yorkie.v1.WatchDocumentResponse.Initialization.\n * Use `create(WatchDocumentResponse_InitializationSchema)` to create a new message.\n */\nexport const WatchDocumentResponse_InitializationSchema: GenMessage<WatchDocumentResponse_Initialization> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 22, 0);\n\n/**\n * Deprecated: Use WatchRequest instead.\n *\n * @generated from message yorkie.v1.WatchChannelRequest\n */\nexport type WatchChannelRequest = Message<\"yorkie.v1.WatchChannelRequest\"> & {\n  /**\n   * @generated from field: string client_id = 1;\n   */\n  clientId: string;\n\n  /**\n   * @generated from field: string channel_key = 2;\n   */\n  channelKey: string;\n};\n\n/**\n * Describes the message yorkie.v1.WatchChannelRequest.\n * Use `create(WatchChannelRequestSchema)` to create a new message.\n */\nexport const WatchChannelRequestSchema: GenMessage<WatchChannelRequest> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 23);\n\n/**\n * Deprecated: Use WatchResponse instead.\n *\n * @generated from message yorkie.v1.WatchChannelResponse\n */\nexport type WatchChannelResponse = Message<\"yorkie.v1.WatchChannelResponse\"> & {\n  /**\n   * @generated from oneof yorkie.v1.WatchChannelResponse.body\n   */\n  body: {\n    /**\n     * @generated from field: yorkie.v1.WatchChannelInitialized initialized = 1;\n     */\n    value: WatchChannelInitialized;\n    case: \"initialized\";\n  } | {\n    /**\n     * @generated from field: yorkie.v1.ChannelEvent event = 2;\n     */\n    value: ChannelEvent;\n    case: \"event\";\n  } | { case: undefined; value?: undefined };\n};\n\n/**\n * Describes the message yorkie.v1.WatchChannelResponse.\n * Use `create(WatchChannelResponseSchema)` to create a new message.\n */\nexport const WatchChannelResponseSchema: GenMessage<WatchChannelResponse> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 24);\n\n/**\n * Deprecated: Use ChannelInit instead.\n *\n * @generated from message yorkie.v1.WatchChannelInitialized\n */\nexport type WatchChannelInitialized = Message<\"yorkie.v1.WatchChannelInitialized\"> & {\n  /**\n   * @generated from field: int64 session_count = 1;\n   */\n  sessionCount: bigint;\n\n  /**\n   * @generated from field: int64 seq = 2;\n   */\n  seq: bigint;\n};\n\n/**\n * Describes the message yorkie.v1.WatchChannelInitialized.\n * Use `create(WatchChannelInitializedSchema)` to create a new message.\n */\nexport const WatchChannelInitializedSchema: GenMessage<WatchChannelInitialized> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 25);\n\n/**\n * @generated from message yorkie.v1.RemoveDocumentRequest\n */\nexport type RemoveDocumentRequest = Message<\"yorkie.v1.RemoveDocumentRequest\"> & {\n  /**\n   * @generated from field: string client_id = 1;\n   */\n  clientId: string;\n\n  /**\n   * @generated from field: string document_id = 2;\n   */\n  documentId: string;\n\n  /**\n   * @generated from field: yorkie.v1.ChangePack change_pack = 3;\n   */\n  changePack?: ChangePack;\n};\n\n/**\n * Describes the message yorkie.v1.RemoveDocumentRequest.\n * Use `create(RemoveDocumentRequestSchema)` to create a new message.\n */\nexport const RemoveDocumentRequestSchema: GenMessage<RemoveDocumentRequest> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 26);\n\n/**\n * @generated from message yorkie.v1.RemoveDocumentResponse\n */\nexport type RemoveDocumentResponse = Message<\"yorkie.v1.RemoveDocumentResponse\"> & {\n  /**\n   * @generated from field: yorkie.v1.ChangePack change_pack = 1;\n   */\n  changePack?: ChangePack;\n};\n\n/**\n * Describes the message yorkie.v1.RemoveDocumentResponse.\n * Use `create(RemoveDocumentResponseSchema)` to create a new message.\n */\nexport const RemoveDocumentResponseSchema: GenMessage<RemoveDocumentResponse> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 27);\n\n/**\n * @generated from message yorkie.v1.PushPullChangesRequest\n */\nexport type PushPullChangesRequest = Message<\"yorkie.v1.PushPullChangesRequest\"> & {\n  /**\n   * @generated from field: string client_id = 1;\n   */\n  clientId: string;\n\n  /**\n   * @generated from field: string document_id = 2;\n   */\n  documentId: string;\n\n  /**\n   * @generated from field: yorkie.v1.ChangePack change_pack = 3;\n   */\n  changePack?: ChangePack;\n\n  /**\n   * @generated from field: bool push_only = 4;\n   */\n  pushOnly: boolean;\n\n  /**\n   * disable_gc declares that this PushPull will not produce or consume\n   * tombstones. The server skips minVV tracking and omits the response\n   * VersionVector. Clients that attached with disable_gc=true must keep\n   * setting this on every subsequent PushPullChanges. See\n   * docs/design/disable-gc-on-attach.md.\n   *\n   * @generated from field: bool disable_gc = 5;\n   */\n  disableGc: boolean;\n};\n\n/**\n * Describes the message yorkie.v1.PushPullChangesRequest.\n * Use `create(PushPullChangesRequestSchema)` to create a new message.\n */\nexport const PushPullChangesRequestSchema: GenMessage<PushPullChangesRequest> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 28);\n\n/**\n * @generated from message yorkie.v1.PushPullChangesResponse\n */\nexport type PushPullChangesResponse = Message<\"yorkie.v1.PushPullChangesResponse\"> & {\n  /**\n   * @generated from field: yorkie.v1.ChangePack change_pack = 1;\n   */\n  changePack?: ChangePack;\n};\n\n/**\n * Describes the message yorkie.v1.PushPullChangesResponse.\n * Use `create(PushPullChangesResponseSchema)` to create a new message.\n */\nexport const PushPullChangesResponseSchema: GenMessage<PushPullChangesResponse> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 29);\n\n/**\n * @generated from message yorkie.v1.CreateRevisionRequest\n */\nexport type CreateRevisionRequest = Message<\"yorkie.v1.CreateRevisionRequest\"> & {\n  /**\n   * @generated from field: string client_id = 1;\n   */\n  clientId: string;\n\n  /**\n   * @generated from field: string document_id = 2;\n   */\n  documentId: string;\n\n  /**\n   * @generated from field: string label = 3;\n   */\n  label: string;\n\n  /**\n   * @generated from field: string description = 4;\n   */\n  description: string;\n};\n\n/**\n * Describes the message yorkie.v1.CreateRevisionRequest.\n * Use `create(CreateRevisionRequestSchema)` to create a new message.\n */\nexport const CreateRevisionRequestSchema: GenMessage<CreateRevisionRequest> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 30);\n\n/**\n * @generated from message yorkie.v1.CreateRevisionResponse\n */\nexport type CreateRevisionResponse = Message<\"yorkie.v1.CreateRevisionResponse\"> & {\n  /**\n   * @generated from field: yorkie.v1.RevisionSummary revision = 1;\n   */\n  revision?: RevisionSummary;\n};\n\n/**\n * Describes the message yorkie.v1.CreateRevisionResponse.\n * Use `create(CreateRevisionResponseSchema)` to create a new message.\n */\nexport const CreateRevisionResponseSchema: GenMessage<CreateRevisionResponse> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 31);\n\n/**\n * @generated from message yorkie.v1.GetRevisionRequest\n */\nexport type GetRevisionRequest = Message<\"yorkie.v1.GetRevisionRequest\"> & {\n  /**\n   * @generated from field: string client_id = 1;\n   */\n  clientId: string;\n\n  /**\n   * @generated from field: string document_id = 2;\n   */\n  documentId: string;\n\n  /**\n   * @generated from field: string revision_id = 3;\n   */\n  revisionId: string;\n};\n\n/**\n * Describes the message yorkie.v1.GetRevisionRequest.\n * Use `create(GetRevisionRequestSchema)` to create a new message.\n */\nexport const GetRevisionRequestSchema: GenMessage<GetRevisionRequest> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 32);\n\n/**\n * @generated from message yorkie.v1.GetRevisionResponse\n */\nexport type GetRevisionResponse = Message<\"yorkie.v1.GetRevisionResponse\"> & {\n  /**\n   * @generated from field: yorkie.v1.RevisionSummary revision = 1;\n   */\n  revision?: RevisionSummary;\n};\n\n/**\n * Describes the message yorkie.v1.GetRevisionResponse.\n * Use `create(GetRevisionResponseSchema)` to create a new message.\n */\nexport const GetRevisionResponseSchema: GenMessage<GetRevisionResponse> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 33);\n\n/**\n * @generated from message yorkie.v1.ListRevisionsRequest\n */\nexport type ListRevisionsRequest = Message<\"yorkie.v1.ListRevisionsRequest\"> & {\n  /**\n   * @generated from field: string client_id = 1;\n   */\n  clientId: string;\n\n  /**\n   * @generated from field: string document_id = 2;\n   */\n  documentId: string;\n\n  /**\n   * @generated from field: int32 page_size = 3;\n   */\n  pageSize: number;\n\n  /**\n   * @generated from field: int32 offset = 4;\n   */\n  offset: number;\n\n  /**\n   * @generated from field: bool is_forward = 5;\n   */\n  isForward: boolean;\n};\n\n/**\n * Describes the message yorkie.v1.ListRevisionsRequest.\n * Use `create(ListRevisionsRequestSchema)` to create a new message.\n */\nexport const ListRevisionsRequestSchema: GenMessage<ListRevisionsRequest> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 34);\n\n/**\n * @generated from message yorkie.v1.ListRevisionsResponse\n */\nexport type ListRevisionsResponse = Message<\"yorkie.v1.ListRevisionsResponse\"> & {\n  /**\n   * @generated from field: repeated yorkie.v1.RevisionSummary revisions = 1;\n   */\n  revisions: RevisionSummary[];\n};\n\n/**\n * Describes the message yorkie.v1.ListRevisionsResponse.\n * Use `create(ListRevisionsResponseSchema)` to create a new message.\n */\nexport const ListRevisionsResponseSchema: GenMessage<ListRevisionsResponse> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 35);\n\n/**\n * @generated from message yorkie.v1.RestoreRevisionRequest\n */\nexport type RestoreRevisionRequest = Message<\"yorkie.v1.RestoreRevisionRequest\"> & {\n  /**\n   * @generated from field: string client_id = 1;\n   */\n  clientId: string;\n\n  /**\n   * @generated from field: string document_id = 2;\n   */\n  documentId: string;\n\n  /**\n   * @generated from field: string revision_id = 4;\n   */\n  revisionId: string;\n};\n\n/**\n * Describes the message yorkie.v1.RestoreRevisionRequest.\n * Use `create(RestoreRevisionRequestSchema)` to create a new message.\n */\nexport const RestoreRevisionRequestSchema: GenMessage<RestoreRevisionRequest> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 36);\n\n/**\n * @generated from message yorkie.v1.RestoreRevisionResponse\n */\nexport type RestoreRevisionResponse = Message<\"yorkie.v1.RestoreRevisionResponse\"> & {\n};\n\n/**\n * Describes the message yorkie.v1.RestoreRevisionResponse.\n * Use `create(RestoreRevisionResponseSchema)` to create a new message.\n */\nexport const RestoreRevisionResponseSchema: GenMessage<RestoreRevisionResponse> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 37);\n\n/**\n * @generated from message yorkie.v1.AttachChannelRequest\n */\nexport type AttachChannelRequest = Message<\"yorkie.v1.AttachChannelRequest\"> & {\n  /**\n   * @generated from field: string client_id = 1;\n   */\n  clientId: string;\n\n  /**\n   * @generated from field: string channel_key = 2;\n   */\n  channelKey: string;\n};\n\n/**\n * Describes the message yorkie.v1.AttachChannelRequest.\n * Use `create(AttachChannelRequestSchema)` to create a new message.\n */\nexport const AttachChannelRequestSchema: GenMessage<AttachChannelRequest> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 38);\n\n/**\n * @generated from message yorkie.v1.AttachChannelResponse\n */\nexport type AttachChannelResponse = Message<\"yorkie.v1.AttachChannelResponse\"> & {\n  /**\n   * @generated from field: string session_id = 1;\n   */\n  sessionId: string;\n\n  /**\n   * @generated from field: int64 session_count = 2;\n   */\n  sessionCount: bigint;\n};\n\n/**\n * Describes the message yorkie.v1.AttachChannelResponse.\n * Use `create(AttachChannelResponseSchema)` to create a new message.\n */\nexport const AttachChannelResponseSchema: GenMessage<AttachChannelResponse> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 39);\n\n/**\n * @generated from message yorkie.v1.DetachChannelRequest\n */\nexport type DetachChannelRequest = Message<\"yorkie.v1.DetachChannelRequest\"> & {\n  /**\n   * @generated from field: string client_id = 1;\n   */\n  clientId: string;\n\n  /**\n   * @generated from field: string channel_key = 2;\n   */\n  channelKey: string;\n\n  /**\n   * @generated from field: string session_id = 3;\n   */\n  sessionId: string;\n};\n\n/**\n * Describes the message yorkie.v1.DetachChannelRequest.\n * Use `create(DetachChannelRequestSchema)` to create a new message.\n */\nexport const DetachChannelRequestSchema: GenMessage<DetachChannelRequest> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 40);\n\n/**\n * @generated from message yorkie.v1.DetachChannelResponse\n */\nexport type DetachChannelResponse = Message<\"yorkie.v1.DetachChannelResponse\"> & {\n  /**\n   * @generated from field: int64 session_count = 1;\n   */\n  sessionCount: bigint;\n};\n\n/**\n * Describes the message yorkie.v1.DetachChannelResponse.\n * Use `create(DetachChannelResponseSchema)` to create a new message.\n */\nexport const DetachChannelResponseSchema: GenMessage<DetachChannelResponse> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 41);\n\n/**\n * @generated from message yorkie.v1.RefreshChannelRequest\n */\nexport type RefreshChannelRequest = Message<\"yorkie.v1.RefreshChannelRequest\"> & {\n  /**\n   * @generated from field: string client_id = 1;\n   */\n  clientId: string;\n\n  /**\n   * @generated from field: string channel_key = 2;\n   */\n  channelKey: string;\n\n  /**\n   * @generated from field: string session_id = 3;\n   */\n  sessionId: string;\n\n  /**\n   * client_key and metadata are used only on the first call (when session_id\n   * is empty). The server activates the client and attaches it to the channel\n   * before refreshing, collapsing ActivateClient + AttachChannel + RefreshChannel\n   * into a single round trip.\n   *\n   * @generated from field: string client_key = 4;\n   */\n  clientKey: string;\n\n  /**\n   * @generated from field: map<string, string> metadata = 5;\n   */\n  metadata: { [key: string]: string };\n};\n\n/**\n * Describes the message yorkie.v1.RefreshChannelRequest.\n * Use `create(RefreshChannelRequestSchema)` to create a new message.\n */\nexport const RefreshChannelRequestSchema: GenMessage<RefreshChannelRequest> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 42);\n\n/**\n * @generated from message yorkie.v1.RefreshChannelResponse\n */\nexport type RefreshChannelResponse = Message<\"yorkie.v1.RefreshChannelResponse\"> & {\n  /**\n   * @generated from field: int64 session_count = 1;\n   */\n  sessionCount: bigint;\n\n  /**\n   * client_id and session_id are populated only when the request was a\n   * first-call (i.e. session_id was empty). Subsequent heartbeats leave\n   * these empty.\n   *\n   * @generated from field: string client_id = 2;\n   */\n  clientId: string;\n\n  /**\n   * @generated from field: string session_id = 3;\n   */\n  sessionId: string;\n};\n\n/**\n * Describes the message yorkie.v1.RefreshChannelResponse.\n * Use `create(RefreshChannelResponseSchema)` to create a new message.\n */\nexport const RefreshChannelResponseSchema: GenMessage<RefreshChannelResponse> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 43);\n\n/**\n * PeekChannel reads the current session_count of a channel without creating\n * a session on the server. Use this when a client only needs to display the\n * count (e.g. \"N people writing\") without contributing to it and without\n * receiving broadcasts. Caller polls on its own cadence.\n *\n * @generated from message yorkie.v1.PeekChannelRequest\n */\nexport type PeekChannelRequest = Message<\"yorkie.v1.PeekChannelRequest\"> & {\n  /**\n   * @generated from field: string channel_key = 1;\n   */\n  channelKey: string;\n};\n\n/**\n * Describes the message yorkie.v1.PeekChannelRequest.\n * Use `create(PeekChannelRequestSchema)` to create a new message.\n */\nexport const PeekChannelRequestSchema: GenMessage<PeekChannelRequest> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 44);\n\n/**\n * @generated from message yorkie.v1.PeekChannelResponse\n */\nexport type PeekChannelResponse = Message<\"yorkie.v1.PeekChannelResponse\"> & {\n  /**\n   * @generated from field: int64 session_count = 1;\n   */\n  sessionCount: bigint;\n};\n\n/**\n * Describes the message yorkie.v1.PeekChannelResponse.\n * Use `create(PeekChannelResponseSchema)` to create a new message.\n */\nexport const PeekChannelResponseSchema: GenMessage<PeekChannelResponse> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 45);\n\n/**\n * @generated from message yorkie.v1.BroadcastRequest\n */\nexport type BroadcastRequest = Message<\"yorkie.v1.BroadcastRequest\"> & {\n  /**\n   * @generated from field: string client_id = 1;\n   */\n  clientId: string;\n\n  /**\n   * @generated from field: string channel_key = 2;\n   */\n  channelKey: string;\n\n  /**\n   * @generated from field: string topic = 3;\n   */\n  topic: string;\n\n  /**\n   * @generated from field: bytes payload = 4;\n   */\n  payload: Uint8Array;\n};\n\n/**\n * Describes the message yorkie.v1.BroadcastRequest.\n * Use `create(BroadcastRequestSchema)` to create a new message.\n */\nexport const BroadcastRequestSchema: GenMessage<BroadcastRequest> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 46);\n\n/**\n * @generated from message yorkie.v1.BroadcastResponse\n */\nexport type BroadcastResponse = Message<\"yorkie.v1.BroadcastResponse\"> & {\n};\n\n/**\n * Describes the message yorkie.v1.BroadcastResponse.\n * Use `create(BroadcastResponseSchema)` to create a new message.\n */\nexport const BroadcastResponseSchema: GenMessage<BroadcastResponse> = /*@__PURE__*/\n  messageDesc(file_yorkie_v1_yorkie, 47);\n\n/**\n * Yorkie is a service that provides an API for SDKs.\n *\n * @generated from service yorkie.v1.YorkieService\n */\nexport const YorkieService: GenService<{\n  /**\n   * @generated from rpc yorkie.v1.YorkieService.ActivateClient\n   */\n  activateClient: {\n    methodKind: \"unary\";\n    input: typeof ActivateClientRequestSchema;\n    output: typeof ActivateClientResponseSchema;\n  },\n  /**\n   * @generated from rpc yorkie.v1.YorkieService.DeactivateClient\n   */\n  deactivateClient: {\n    methodKind: \"unary\";\n    input: typeof DeactivateClientRequestSchema;\n    output: typeof DeactivateClientResponseSchema;\n  },\n  /**\n   * @generated from rpc yorkie.v1.YorkieService.AttachDocument\n   */\n  attachDocument: {\n    methodKind: \"unary\";\n    input: typeof AttachDocumentRequestSchema;\n    output: typeof AttachDocumentResponseSchema;\n  },\n  /**\n   * @generated from rpc yorkie.v1.YorkieService.DetachDocument\n   */\n  detachDocument: {\n    methodKind: \"unary\";\n    input: typeof DetachDocumentRequestSchema;\n    output: typeof DetachDocumentResponseSchema;\n  },\n  /**\n   * @generated from rpc yorkie.v1.YorkieService.RemoveDocument\n   */\n  removeDocument: {\n    methodKind: \"unary\";\n    input: typeof RemoveDocumentRequestSchema;\n    output: typeof RemoveDocumentResponseSchema;\n  },\n  /**\n   * @generated from rpc yorkie.v1.YorkieService.PushPullChanges\n   */\n  pushPullChanges: {\n    methodKind: \"unary\";\n    input: typeof PushPullChangesRequestSchema;\n    output: typeof PushPullChangesResponseSchema;\n  },\n  /**\n   * @generated from rpc yorkie.v1.YorkieService.Watch\n   */\n  watch: {\n    methodKind: \"server_streaming\";\n    input: typeof WatchRequestSchema;\n    output: typeof WatchResponseSchema;\n  },\n  /**\n   * Deprecated: Use Watch with ResourceDescriptor instead.\n   *\n   * @generated from rpc yorkie.v1.YorkieService.WatchDocument\n   */\n  watchDocument: {\n    methodKind: \"server_streaming\";\n    input: typeof WatchDocumentRequestSchema;\n    output: typeof WatchDocumentResponseSchema;\n  },\n  /**\n   * Deprecated: Use Watch with ResourceDescriptor instead.\n   *\n   * @generated from rpc yorkie.v1.YorkieService.WatchChannel\n   */\n  watchChannel: {\n    methodKind: \"server_streaming\";\n    input: typeof WatchChannelRequestSchema;\n    output: typeof WatchChannelResponseSchema;\n  },\n  /**\n   * @generated from rpc yorkie.v1.YorkieService.CreateRevision\n   */\n  createRevision: {\n    methodKind: \"unary\";\n    input: typeof CreateRevisionRequestSchema;\n    output: typeof CreateRevisionResponseSchema;\n  },\n  /**\n   * @generated from rpc yorkie.v1.YorkieService.GetRevision\n   */\n  getRevision: {\n    methodKind: \"unary\";\n    input: typeof GetRevisionRequestSchema;\n    output: typeof GetRevisionResponseSchema;\n  },\n  /**\n   * @generated from rpc yorkie.v1.YorkieService.ListRevisions\n   */\n  listRevisions: {\n    methodKind: \"unary\";\n    input: typeof ListRevisionsRequestSchema;\n    output: typeof ListRevisionsResponseSchema;\n  },\n  /**\n   * @generated from rpc yorkie.v1.YorkieService.RestoreRevision\n   */\n  restoreRevision: {\n    methodKind: \"unary\";\n    input: typeof RestoreRevisionRequestSchema;\n    output: typeof RestoreRevisionResponseSchema;\n  },\n  /**\n   * @generated from rpc yorkie.v1.YorkieService.AttachChannel\n   */\n  attachChannel: {\n    methodKind: \"unary\";\n    input: typeof AttachChannelRequestSchema;\n    output: typeof AttachChannelResponseSchema;\n  },\n  /**\n   * @generated from rpc yorkie.v1.YorkieService.DetachChannel\n   */\n  detachChannel: {\n    methodKind: \"unary\";\n    input: typeof DetachChannelRequestSchema;\n    output: typeof DetachChannelResponseSchema;\n  },\n  /**\n   * @generated from rpc yorkie.v1.YorkieService.RefreshChannel\n   */\n  refreshChannel: {\n    methodKind: \"unary\";\n    input: typeof RefreshChannelRequestSchema;\n    output: typeof RefreshChannelResponseSchema;\n  },\n  /**\n   * @generated from rpc yorkie.v1.YorkieService.PeekChannel\n   */\n  peekChannel: {\n    methodKind: \"unary\";\n    input: typeof PeekChannelRequestSchema;\n    output: typeof PeekChannelResponseSchema;\n  },\n  /**\n   * @generated from rpc yorkie.v1.YorkieService.Broadcast\n   */\n  broadcast: {\n    methodKind: \"unary\";\n    input: typeof BroadcastRequestSchema;\n    output: typeof BroadcastResponseSchema;\n  },\n}> = /*@__PURE__*/\n  serviceDesc(file_yorkie_v1_yorkie, 0);\n\n","// Copyright 2025 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n// @generated by protoc-gen-es v2.10.1 with parameter \"import_extension=js\"\n// @generated from file google/rpc/error_details.proto (package google.rpc, syntax proto3)\n/* eslint-disable */\n\nimport { fileDesc, messageDesc } from \"@bufbuild/protobuf/codegenv2\";\nimport { file_google_protobuf_duration } from \"@bufbuild/protobuf/wkt\";\n\n/**\n * Describes the file google/rpc/error_details.proto.\n */\nexport const file_google_rpc_error_details = /*@__PURE__*/\n  fileDesc(\"Ch5nb29nbGUvcnBjL2Vycm9yX2RldGFpbHMucHJvdG8SCmdvb2dsZS5ycGMikwEKCUVycm9ySW5mbxIOCgZyZWFzb24YASABKAkSDgoGZG9tYWluGAIgASgJEjUKCG1ldGFkYXRhGAMgAygLMiMuZ29vZ2xlLnJwYy5FcnJvckluZm8uTWV0YWRhdGFFbnRyeRovCg1NZXRhZGF0YUVudHJ5EgsKA2tleRgBIAEoCRINCgV2YWx1ZRgCIAEoCToCOAEiOwoJUmV0cnlJbmZvEi4KC3JldHJ5X2RlbGF5GAEgASgLMhkuZ29vZ2xlLnByb3RvYnVmLkR1cmF0aW9uIjIKCURlYnVnSW5mbxIVCg1zdGFja19lbnRyaWVzGAEgAygJEg4KBmRldGFpbBgCIAEoCSKPAwoMUXVvdGFGYWlsdXJlEjYKCnZpb2xhdGlvbnMYASADKAsyIi5nb29nbGUucnBjLlF1b3RhRmFpbHVyZS5WaW9sYXRpb24axgIKCVZpb2xhdGlvbhIPCgdzdWJqZWN0GAEgASgJEhMKC2Rlc2NyaXB0aW9uGAIgASgJEhMKC2FwaV9zZXJ2aWNlGAMgASgJEhQKDHF1b3RhX21ldHJpYxgEIAEoCRIQCghxdW90YV9pZBgFIAEoCRJRChBxdW90YV9kaW1lbnNpb25zGAYgAygLMjcuZ29vZ2xlLnJwYy5RdW90YUZhaWx1cmUuVmlvbGF0aW9uLlF1b3RhRGltZW5zaW9uc0VudHJ5EhMKC3F1b3RhX3ZhbHVlGAcgASgDEh8KEmZ1dHVyZV9xdW90YV92YWx1ZRgIIAEoA0gAiAEBGjYKFFF1b3RhRGltZW5zaW9uc0VudHJ5EgsKA2tleRgBIAEoCRINCgV2YWx1ZRgCIAE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ration]);\n\n/**\n * Describes the message google.rpc.ErrorInfo.\n * Use `create(ErrorInfoSchema)` to create a new message.\n */\nexport const ErrorInfoSchema = /*@__PURE__*/\n  messageDesc(file_google_rpc_error_details, 0);\n\n/**\n * Describes the message google.rpc.RetryInfo.\n * Use `create(RetryInfoSchema)` to create a new message.\n */\nexport const RetryInfoSchema = /*@__PURE__*/\n  messageDesc(file_google_rpc_error_details, 1);\n\n/**\n * Describes the message google.rpc.DebugInfo.\n * Use `create(DebugInfoSchema)` to create a new message.\n */\nexport const DebugInfoSchema = /*@__PURE__*/\n  messageDesc(file_google_rpc_error_details, 2);\n\n/**\n * Describes the message google.rpc.QuotaFailure.\n * Use `create(QuotaFailureSchema)` to create a new message.\n */\nexport const QuotaFailureSchema = /*@__PURE__*/\n  messageDesc(file_google_rpc_error_details, 3);\n\n/**\n * Describes the message google.rpc.QuotaFailure.Violation.\n * Use `create(QuotaFailure_ViolationSchema)` to create a new message.\n */\nexport const QuotaFailure_ViolationSchema = /*@__PURE__*/\n  messageDesc(file_google_rpc_error_details, 3, 0);\n\n/**\n * Describes the message google.rpc.PreconditionFailure.\n * Use `create(PreconditionFailureSchema)` to create a new message.\n */\nexport const PreconditionFailureSchema = /*@__PURE__*/\n  messageDesc(file_google_rpc_error_details, 4);\n\n/**\n * Describes the message google.rpc.PreconditionFailure.Violation.\n * Use `create(PreconditionFailure_ViolationSchema)` to create a new message.\n */\nexport const PreconditionFailure_ViolationSchema = /*@__PURE__*/\n  messageDesc(file_google_rpc_error_details, 4, 0);\n\n/**\n * Describes the message google.rpc.BadRequest.\n * Use `create(BadRequestSchema)` to create a new message.\n */\nexport const BadRequestSchema = /*@__PURE__*/\n  messageDesc(file_google_rpc_error_details, 5);\n\n/**\n * Describes the message google.rpc.BadRequest.FieldViolation.\n * Use `create(BadRequest_FieldViolationSchema)` to create a new message.\n */\nexport const BadRequest_FieldViolationSchema = /*@__PURE__*/\n  messageDesc(file_google_rpc_error_details, 5, 0);\n\n/**\n * Describes the message google.rpc.RequestInfo.\n * Use `create(RequestInfoSchema)` to create a new message.\n */\nexport const RequestInfoSchema = /*@__PURE__*/\n  messageDesc(file_google_rpc_error_details, 6);\n\n/**\n * Describes the message google.rpc.ResourceInfo.\n * Use `create(ResourceInfoSchema)` to create a new message.\n */\nexport const ResourceInfoSchema = /*@__PURE__*/\n  messageDesc(file_google_rpc_error_details, 7);\n\n/**\n * Describes the message google.rpc.Help.\n * Use `create(HelpSchema)` to create a new message.\n */\nexport const HelpSchema = /*@__PURE__*/\n  messageDesc(file_google_rpc_error_details, 8);\n\n/**\n * Describes the message google.rpc.Help.Link.\n * Use `create(Help_LinkSchema)` to create a new message.\n */\nexport const Help_LinkSchema = /*@__PURE__*/\n  messageDesc(file_google_rpc_error_details, 8, 0);\n\n/**\n * Describes the message google.rpc.LocalizedMessage.\n * Use `create(LocalizedMessageSchema)` to create a new message.\n */\nexport const LocalizedMessageSchema = /*@__PURE__*/\n  messageDesc(file_google_rpc_error_details, 9);\n\n","/*\n * Copyright 2020 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport enum Code {\n  // Ok is returned when the operation completed successfully.\n  Ok = 'ok',\n\n  // ErrClientNotActivated is returned when the client is not active.\n  ErrClientNotActivated = 'ErrClientNotActivated',\n\n  // ErrClientNotFound is returned when the client is not found.\n  ErrClientNotFound = 'ErrClientNotFound',\n\n  // ErrUnimplemented is returned when the operation is not implemented.\n  ErrUnimplemented = 'ErrUnimplemented',\n\n  // ErrInvalidType is returned when the type is invalid.\n  ErrInvalidType = 'ErrInvalidType',\n\n  // ErrDummy is used to verify errors for testing purposes.\n  ErrDummy = 'ErrDummy',\n\n  // ErrNotAttached is returned when the resource is not attached.\n  ErrNotAttached = 'ErrNotAttached',\n\n  // ErrNotDetached is returned when the resource is not detached.\n  ErrNotDetached = 'ErrNotDetached',\n\n  // ErrAlreadyAttached is returned when a document with the same key is\n  // already attached (or being attached) to this client.\n  ErrAlreadyAttached = 'ErrAlreadyAttached',\n\n  // ErrSessionNotFound is returned when the server no longer recognises a\n  // channel session_id (e.g. reclaimed after TTL). Callers should treat this\n  // as \"session expired\" and retry as a first-call (empty session_id).\n  ErrSessionNotFound = 'ErrSessionNotFound',\n\n  // ErrDocumentRemoved is returned when the document is removed.\n  ErrDocumentRemoved = 'ErrDocumentRemoved',\n\n  // ErrDocumentSizeExceedsLimit is returned when the document size exceeds the limit.\n  ErrDocumentSizeExceedsLimit = 'ErrDocumentSizeExceedsLimit',\n\n  // ErrChangeTooLarge is returned when a single change is too large to store.\n  ErrChangeTooLarge = 'ErrChangeTooLarge',\n\n  // ErrDocumentSchemaValidationFailed is returned when the document schema validation failed.\n  ErrDocumentSchemaValidationFailed = 'ErrDocumentSchemaValidationFailed',\n\n  // InvalidObjectKey is returned when the object key is invalid.\n  ErrInvalidObjectKey = 'ErrInvalidObjectKey',\n\n  // ErrInvalidArgument is returned when the argument is invalid.\n  ErrInvalidArgument = 'ErrInvalidArgument',\n\n  // ErrNotInitialized is returned when required initialization has not been completed.\n  ErrNotInitialized = 'ErrNotInitialized',\n\n  // ErrNotReady is returned when execution of following actions is not ready.\n  ErrNotReady = 'ErrNotReady',\n\n  // ErrRefused is returned when the execution is rejected.\n  ErrRefused = 'ErrRefused',\n\n  // ErrContextNotProvided is returned when a required React context is missing\n  ErrContextNotProvided = 'ErrContextNotProvided',\n\n  // ErrPermissionDenied is returned when the authorization webhook denies the request.\n  ErrPermissionDenied = 'ErrPermissionDenied',\n\n  // ErrUnauthenticated is returned when the request does not have valid authentication credentials.\n  ErrUnauthenticated = 'ErrUnauthenticated',\n\n  // ErrTooManySubscribers is returned when the number of subscribers exceeds the limit.\n  ErrTooManySubscribers = 'ErrTooManySubscribers',\n\n  // ErrTooManyAttachments is returned when the number of attachments exceeds the limit.\n  ErrTooManyAttachments = 'ErrTooManyAttachments',\n\n  // ErrEpochMismatch is returned when the document has been compacted\n  // and the client's epoch no longer matches the server's epoch.\n  ErrEpochMismatch = 'ErrEpochMismatch',\n\n  // ErrDocumentOpenElsewhere is returned when an offline-persistence attach\n  // cannot take the single-active-session lock because another session — in\n  // practice another tab of the same client — already holds it for this\n  // document. It is its own code so a consumer can fall back to a\n  // non-persisting client on exactly this condition without matching on\n  // message text.\n  ErrDocumentOpenElsewhere = 'ErrDocumentOpenElsewhere',\n\n  // ErrChangeApplyFailed is returned when a change cannot be applied to a\n  // document. The checkpoint only advances after the changes in a pack have\n  // been applied, so the server redelivers a pack whose change throws: the\n  // document stops making progress until the cause is fixed. This code names\n  // that condition so it is diagnosable instead of surfacing as whatever the\n  // failing operation happened to throw.\n  ErrChangeApplyFailed = 'ErrChangeApplyFailed',\n\n  // ErrPresenceBaseUnavailable is returned when the server has no base to fold\n  // a presence patch into, because it was evicted from the cache or never\n  // reached this server. Nothing in the pack was stored: the client resends it\n  // with the patch replaced by a full put. It is an expected signal rather\n  // than a failure.\n  ErrPresenceBaseUnavailable = 'ErrPresenceBaseUnavailable',\n\n  // ErrWatchStreamIdle is reported when a watch stream stays silent for longer\n  // than the heartbeat interval the server advertised allows, which is how a\n  // half-open connection is told from a quiet document.\n  ErrWatchStreamIdle = 'ErrWatchStreamIdle',\n}\n\n/**\n * `YorkieError` is an error returned by a Yorkie operation.\n */\nexport class YorkieError extends Error {\n  name = 'YorkieError';\n  stack?: string;\n\n  constructor(\n    readonly code: Code,\n    readonly message: string,\n  ) {\n    super(message);\n    this.toString = (): string => `[code=${this.code}]: ${this.message}`;\n  }\n}\n\n/**\n * `ChangeApplyDetail` describes which change, and which operation of it,\n * could not be applied. `docKey` is unknown at the throw site inside the\n * change itself and is filled in by the document; `opIndex` and `operation`\n * are absent when the failure was not raised by a single operation.\n *\n * `operation` names the operation — its type and the element it targets —\n * and MUST NOT carry the operation's payload: this detail is spliced into a\n * message that is thrown to application code and logged at the default level,\n * so a payload there would publish plaintext document content.\n */\nexport type ChangeApplyDetail = {\n  docKey?: string;\n  changeID: string;\n  opIndex?: number;\n  operation?: string;\n  cause: unknown;\n};\n\n/**\n * `ChangeApplyError` is thrown when a change cannot be applied to a document.\n *\n * It names the document, the change and the operation that failed, and keeps\n * the original error in `cause`. Without it the only signal is whatever the\n * operation threw, which says nothing about which change is stuck — and\n * because the checkpoint does not advance past a change that throws, the\n * server keeps redelivering it.\n */\nexport class ChangeApplyError extends YorkieError {\n  name = 'ChangeApplyError';\n\n  readonly docKey?: string;\n  readonly changeID: string;\n  readonly opIndex?: number;\n  readonly operation?: string;\n  readonly cause: unknown;\n\n  constructor(detail: ChangeApplyDetail) {\n    const { docKey, changeID, opIndex, operation, cause } = detail;\n    const where = docKey === undefined ? '' : ` of document \"${docKey}\"`;\n    const which =\n      opIndex === undefined ? '' : ` at operation ${opIndex} (${operation})`;\n    const reason = cause instanceof Error ? cause.message : String(cause);\n    super(\n      Code.ErrChangeApplyFailed,\n      `failed to apply change ${changeID}${where}${which}: ${reason}`,\n    );\n\n    this.docKey = docKey;\n    this.changeID = changeID;\n    this.opIndex = opIndex;\n    this.operation = operation;\n    this.cause = cause;\n  }\n\n  /**\n   * `withDocKey` returns this error named with the given document key. The\n   * change knows which operation failed but not which document it belongs\n   * to, so the document adds its key as the error passes through.\n   */\n  public withDocKey(docKey: string): ChangeApplyError {\n    if (this.docKey === docKey) {\n      return this;\n    }\n\n    return new ChangeApplyError({\n      docKey,\n      changeID: this.changeID,\n      opIndex: this.opIndex,\n      operation: this.operation,\n      cause: this.cause,\n    });\n  }\n}\n","/*\n * Copyright 2023 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Indexable } from '@yorkie-js/sdk/src/document/document';\n\n/**\n * `deepcopy` returns a deep copy of the given object.\n */\nexport function deepcopy<T>(object: T): T {\n  if (object instanceof Map) {\n    const pairs = Array.from(object);\n    return new Map(JSON.parse(JSON.stringify(pairs))) as unknown as T;\n  }\n\n  return JSON.parse(JSON.stringify(object));\n}\n\n/**\n `isEmpty` returns whether parameter object is empty or not \n */\nexport const isEmpty = (object: object) => {\n  if (!object) {\n    return true;\n  }\n\n  return Object.entries(object).length === 0;\n};\n\n/**\n * `stringifyObjectValues` makes values of attributes to JSON parsable string.\n */\nexport const stringifyObjectValues = <A extends Indexable>(\n  attributes: A,\n): Record<string, string> => {\n  const attrs: Record<string, string> = {};\n  for (const [key, value] of Object.entries(attributes)) {\n    // A string that is not itself a JSON document is stored as-is, which is\n    // what the Go SDK stores for the same attribute: its `Style` takes\n    // map[string]string and holds what it is given. `color=\"red\"` therefore\n    // puts the same three bytes on the wire from either SDK.\n    //\n    // A string that IS a JSON document keeps its quotes, because raw storage\n    // could not tell it from the value it encodes: '1' would come back as the\n    // number 1 and 'true' as the boolean. Those keep the encoding that\n    // preserves their type, at the cost of still differing from Go -- which\n    // cannot express the distinction at all.\n    attrs[key] =\n      typeof value === 'string' && !isJSONDocument(value)\n        ? value\n        : JSON.stringify(value);\n  }\n  return attrs;\n};\n\n/**\n `parseObjectValues` returns the JSON parsable string values to the origin states.\n */\nexport const parseObjectValues = <A extends Indexable>(\n  attrs: Record<string, string>,\n): A => {\n  const attributes: Record<string, unknown> = {};\n  for (const [key, value] of Object.entries(attrs)) {\n    attributes[key] = parseAttrValue(value);\n  }\n  return attributes as A;\n};\n\n/**\n * `isJSONDocument` reports whether the given string would parse as JSON, and\n * so could not be told apart from the value it encodes if it were stored raw.\n */\nconst isJSONDocument = (value: string): boolean => {\n  try {\n    JSON.parse(value);\n    return true;\n  } catch {\n    return false;\n  }\n};\n\n/**\n * `parseAttrValue` decodes one stored attribute value, tolerating one written\n * by a peer that stores values RAW.\n *\n * The Go SDK's `Style` takes `map[string]string` and stores what it is given,\n * so `color=\"red\"` arrives here as the three characters `red`, which is not a\n * JSON document. Parsing it unguarded threw `SyntaxError` out of\n * `applyChangePack` before the checkpoint advanced, so the server redelivered\n * the same change forever and the client could never open the document.\n *\n * Falling back to the raw string is lossless: it is exactly what the peer\n * wrote. It cannot change how a JS-authored value reads, because everything\n * this SDK writes goes through `JSON.stringify` and is valid JSON by\n * construction, so the fallback is unreachable for those.\n */\nexport const parseAttrValue = (value: string): unknown => {\n  try {\n    return JSON.parse(value);\n  } catch {\n    return value;\n  }\n};\n","/*\n * Copyright 2025 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Indexable } from '@yorkie-js/sdk/src/document/document';\n\n/**\n * `PresencePatchCapability` is the name the server advertises in\n * `ChangePack.capabilities` when it can fold a `Patch` into the presence base\n * it holds. Absence means the server does not take patches.\n */\nexport const PresencePatchCapability = 'presence-patch';\n\n/**\n * `PresenceChangeType` represents the type of presence change.\n */\nexport enum PresenceChangeType {\n  Put = 'put',\n  Clear = 'clear',\n  Patch = 'patch',\n}\n\n/**\n * `PresenceChange` represents the change of presence.\n *\n * A `Patch` carries only the top-level keys that changed, so it is cheaper to\n * upload than the whole presence. It is normally produced locally: the server\n * folds each patch into a full `Put` before storing, so a pulled pack does not\n * usually carry one. A peer that echoes one back anyway is still decoded --\n * see `fromPresenceChange` -- rather than failing the whole pack.\n *\n * `full` is the whole presence as of the patch. It never goes on the wire, so\n * only a locally minted patch has it. It is what `Change.execute` applies\n * locally -- a local patch has no base to merge into on this side -- and what\n * a `ErrPresenceBaseUnavailable` fallback turns the patch back into. A patch\n * decoded off the wire has none, and is merged onto the presence already held\n * for its actor instead.\n */\nexport type PresenceChange<P extends Indexable> =\n  | { type: PresenceChangeType.Put; presence: P }\n  | { type: PresenceChangeType.Patch; presence: Partial<P>; full?: P }\n  | { type: PresenceChangeType.Clear };\n","/*\n * Copyright 2020 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * `ActorID` is used to identify who is making changes to the document.\n * It is a hexadecimal string and should be generated by a unique value.\n */\nexport type ActorID = string;\n\n/**\n * `InitialActorID` is the initial value of ActorID.\n */\nexport const InitialActorID = '000000000000000000000000';\n\n/**\n * `MaxActorID` is the maximum value of ActorID.\n */\nexport const MaxActorID = 'FFFFFFFFFFFFFFFFFFFFFFFF';\n","/*\n * Copyright 2020 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Comparator } from '@yorkie-js/sdk/src/util/comparator';\nimport {\n  ActorID,\n  InitialActorID,\n  MaxActorID,\n} from '@yorkie-js/sdk/src/document/time/actor_id';\n\nexport const TicketComparator: Comparator<TimeTicket> = (\n  p1: TimeTicket,\n  p2: TimeTicket,\n) => {\n  return p1.compare(p2);\n};\n\n/**\n * `TimeTicketStruct` is a structure represents the meta data of the ticket.\n * It is used to serialize and deserialize the ticket.\n */\nexport type TimeTicketStruct = {\n  lamport: string;\n  delimiter: number;\n  actorID: ActorID;\n};\n\n/**\n * TimeTicketSize is the size of the ticket in bytes.\n * lamport(int64) + delimiter(uint32) + actorID(12 bytes)\n */\nexport const TimeTicketSize = 8 + 4 + 12;\n\n/**\n * `TimeTicket` is a timestamp of the logical clock. Ticket is immutable.\n * It is created by `ChangeID`.\n */\nexport class TimeTicket {\n  private lamport: bigint;\n  private delimiter: number;\n  private actorID: ActorID;\n\n  constructor(lamport: bigint, delimiter: number, actorID: string) {\n    this.lamport = lamport;\n    this.delimiter = delimiter;\n    this.actorID = actorID;\n  }\n\n  /**\n   * `of` creates an instance of Ticket.\n   */\n  public static of(\n    lamport: bigint,\n    delimiter: number,\n    actorID: string,\n  ): TimeTicket {\n    return new TimeTicket(lamport, delimiter, actorID);\n  }\n\n  /**\n   * `fromStruct` creates an instance of Ticket from the struct.\n   */\n  public static fromStruct(struct: TimeTicketStruct): TimeTicket {\n    return TimeTicket.of(\n      BigInt(struct.lamport),\n      struct.delimiter,\n      struct.actorID,\n    );\n  }\n\n  /**\n   * `toIDString` returns the lamport string for this Ticket.\n   */\n  public toIDString(): string {\n    return `${this.lamport.toString()}:${this.actorID}:${this.delimiter}`;\n  }\n\n  /**\n   * `toStruct` returns the structure of this Ticket.\n   */\n  public toStruct(): TimeTicketStruct {\n    return {\n      lamport: this.getLamportAsString(),\n      delimiter: this.getDelimiter(),\n      actorID: this.getActorID(),\n    };\n  }\n\n  /**\n   * `toTestString` returns a string containing the meta data of the ticket\n   * for debugging purpose.\n   */\n  public toTestString(): string {\n    return `${this.lamport.toString()}:${this.actorID.slice(-2)}:${\n      this.delimiter\n    }`;\n  }\n\n  /**\n   * `setActor` creates a new instance of Ticket with the given actorID.\n   */\n  public setActor(actorID: ActorID): TimeTicket {\n    return new TimeTicket(this.lamport, this.delimiter, actorID);\n  }\n\n  /**\n   * `getLamportAsString` returns the lamport string.\n   */\n  public getLamportAsString(): string {\n    return this.lamport.toString();\n  }\n\n  /**\n   * `getLamport` returns the lamport.\n   */\n  public getLamport(): bigint {\n    return this.lamport;\n  }\n\n  /**\n   * `getDelimiter` returns delimiter.\n   */\n  public getDelimiter(): number {\n    return this.delimiter;\n  }\n\n  /**\n   * `getActorID` returns actorID.\n   */\n  public getActorID(): string {\n    return this.actorID;\n  }\n\n  /**\n   * `after` returns whether the given ticket was created later.\n   */\n  public after(other: TimeTicket): boolean {\n    return this.compare(other) > 0;\n  }\n\n  /**\n   * `equals` returns whether the given ticket was created.\n   */\n  public equals(other: TimeTicket): boolean {\n    return this.compare(other) === 0;\n  }\n\n  /**\n   * `compare` returns an integer comparing two Ticket.\n   *  The result will be 0 if id==other, -1 if `id < other`, and +1 if `id > other`.\n   *  If the receiver or argument is nil, it would panic at runtime.\n   */\n  public compare(other: TimeTicket): number {\n    if (this.lamport > other.lamport) {\n      return 1;\n    } else if (other.lamport > this.lamport) {\n      return -1;\n    }\n\n    const compare = this.actorID.localeCompare(other.actorID);\n    if (compare !== 0) {\n      return compare;\n    }\n\n    if (this.delimiter > other.delimiter) {\n      return 1;\n    } else if (other.delimiter > this.delimiter) {\n      return -1;\n    }\n\n    return 0;\n  }\n}\n\nexport const InitialLamport = 0n;\nexport const InitialDelimiter = 0;\nexport const MaxDelimiter = 4294967295; // UInt32 MAX_VALUE\nexport const MaxLamport = 9223372036854775807n; // Int64 MAX_VALUE\n\nexport const InitialTimeTicket = new TimeTicket(\n  InitialLamport,\n  InitialDelimiter,\n  InitialActorID,\n);\n\nexport const MaxTimeTicket = new TimeTicket(\n  MaxLamport,\n  MaxDelimiter,\n  MaxActorID,\n);\n","/*\n * Copyright 2022 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, YorkieError } from '@yorkie-js/sdk/src/util/error';\n\n/**\n * `EscapeString` escapes the given string.\n */\nexport function escapeString(str: string): string {\n  return str.replace(/[\"'\\\\\\n\\r\\f\\b\\t\\u2028\\u2029]/g, function (character) {\n    switch (character) {\n      case '\"':\n      case '\\\\':\n        return '\\\\' + character;\n      case '\\n':\n        return '\\\\n';\n      case '\\r':\n        return '\\\\r';\n      case '\\f':\n        return '\\\\f';\n      case '\\b':\n        return '\\\\b';\n      case '\\t':\n        return '\\\\t';\n      case '\\u2028':\n        return '\\\\u2028';\n      case '\\u2029':\n        return '\\\\u2029';\n      default:\n        return character;\n    }\n  });\n}\n\n/**\n * `splitsSurrogatePair` reports whether a boundary between the code units\n * `before` and `after` falls inside a surrogate pair. A missing unit (NaN,\n * what `charCodeAt` returns past either end) never pairs.\n */\nexport function splitsSurrogatePair(before: number, after: number): boolean {\n  return (\n    before >= 0xd800 && before <= 0xdbff && after >= 0xdc00 && after <= 0xdfff\n  );\n}\n\n/**\n * `isUTF16Boundary` reports whether `offset`, counted in UTF-16 code units, is\n * a valid boundary in `value`, i.e. it does not fall between the high and the\n * low surrogate of a pair.\n */\nexport function isUTF16Boundary(value: string, offset: number): boolean {\n  return !splitsSurrogatePair(\n    value.charCodeAt(offset - 1),\n    value.charCodeAt(offset),\n  );\n}\n\n/**\n * `ensureUTF16Boundary` throws when a local index between the code units\n * `before` and `after` splits a surrogate pair. An index there would split\n * the node mid-pair, and the SDKs store the lone halves differently: Go\n * turns each into U+FFFD, JS keeps the raw code unit. Rejecting it keeps the\n * same operation from leaving different text on different replicas.\n */\nexport function ensureUTF16Boundary(before: number, after: number): void {\n  if (splitsSurrogatePair(before, after)) {\n    throw new YorkieError(\n      Code.ErrInvalidArgument,\n      'index must not split a UTF-16 surrogate pair',\n    );\n  }\n}\n\n/**\n * `ensureNoLoneSurrogate` throws when `value` holds a surrogate code unit that\n * is not part of a pair. Rejecting the index that would split a pair is only\n * half of the contract: content carrying a lone half has the same divergence\n * (Go stores U+FFFD, JS the raw code unit), and once stored it also pairs up\n * with whatever code unit it lands against, so the index at that seam becomes\n * one `ensureUTF16Boundary` refuses for as long as the text lives. Refusing\n * the content keeps a local edit from manufacturing either.\n */\nexport function ensureNoLoneSurrogate(value: string): void {\n  for (let i = 0; i < value.length; i++) {\n    const code = value.charCodeAt(i);\n    if (code < 0xd800 || code > 0xdfff) {\n      continue;\n    }\n    // A high surrogate followed by a low one is a whole character; step over\n    // both. Anything else reaching here is a half on its own.\n    if (splitsSurrogatePair(code, value.charCodeAt(i + 1))) {\n      i++;\n      continue;\n    }\n\n    throw new YorkieError(\n      Code.ErrInvalidArgument,\n      'content must not contain a lone UTF-16 surrogate',\n    );\n  }\n}\n","/*\n * Copyright 2020 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n  TimeTicket,\n  TimeTicketSize,\n} from '@yorkie-js/sdk/src/document/time/ticket';\nimport type * as Devtools from '@yorkie-js/sdk/src/devtools/types';\nimport { DataSize } from '@yorkie-js/sdk/src/util/resource';\n\n/**\n * `CRDTElement` represents an element that has `TimeTicket`s.\n */\nexport abstract class CRDTElement {\n  private createdAt: TimeTicket;\n  private movedAt?: TimeTicket;\n  private removedAt?: TimeTicket;\n\n  constructor(createdAt: TimeTicket) {\n    this.createdAt = createdAt;\n  }\n\n  /**\n   * `getCreatedAt` returns the creation time of this element.\n   */\n  public getCreatedAt(): TimeTicket {\n    return this.createdAt;\n  }\n\n  /**\n   * `getID` returns the creation time of this element.\n   */\n  public getID(): TimeTicket {\n    return this.createdAt;\n  }\n\n  /**\n   * `getMovedAt` returns the move time of this element.\n   */\n  public getMovedAt(): TimeTicket | undefined {\n    return this.movedAt;\n  }\n\n  /**\n   * `getRemovedAt` returns the removal time of this element.\n   */\n  public getRemovedAt(): TimeTicket | undefined {\n    return this.removedAt;\n  }\n\n  /**\n   * `getPositionedAt` returns the time of this element when it was positioned\n   * in the document by undo/redo or move operation.\n   */\n  public getPositionedAt(): TimeTicket {\n    if (!this.movedAt) {\n      return this.createdAt;\n    }\n\n    return this.movedAt;\n  }\n\n  /**\n   * `setCreatedAt` sets the creation time of this element manually.\n   */\n  public setCreatedAt(createdAt: TimeTicket) {\n    this.createdAt = createdAt;\n  }\n\n  /**\n   * `setMovedAt` sets the move time of this element.\n   */\n  public setMovedAt(movedAt?: TimeTicket): boolean {\n    if (!this.movedAt || (movedAt && movedAt.after(this.movedAt))) {\n      this.movedAt = movedAt;\n      return true;\n    }\n\n    return false;\n  }\n\n  /**\n   * `setRemovedAt` sets the remove time of this element.\n   */\n  public setRemovedAt(removedAt?: TimeTicket): void {\n    this.removedAt = removedAt;\n  }\n\n  /**\n   * `remove` removes this element.\n   */\n  public remove(removedAt?: TimeTicket): boolean {\n    if (\n      removedAt &&\n      removedAt.after(this.createdAt) &&\n      (!this.removedAt || removedAt.after(this.removedAt))\n    ) {\n      // NOTE(chacha912): If it's a CRDTContainer, removedAt is marked only on\n      // the top-level element, without marking all descendant elements. This\n      // enhances the speed of deletion.\n      this.removedAt = removedAt;\n      return true;\n    }\n\n    return false;\n  }\n\n  /**\n   * `isRemoved` check if this element was removed.\n   */\n  public isRemoved(): boolean {\n    return !!this.removedAt;\n  }\n\n  /**\n   * `getMetaUsage` returns the meta usage of this element.\n   */\n  public getMetaUsage(): number {\n    let meta = 0;\n\n    if (this.getCreatedAt()) {\n      meta += TimeTicketSize;\n    }\n\n    if (this.getMovedAt()) {\n      meta += TimeTicketSize;\n    }\n    if (this.getRemovedAt()) {\n      meta += TimeTicketSize;\n    }\n\n    return meta;\n  }\n\n  /**\n   * `getDataSize` returns the data usage of this element.\n   */\n  abstract getDataSize(): DataSize;\n\n  abstract toJSON(): string;\n  abstract toSortedJSON(): string;\n  abstract toJSForTest(): Devtools.JSONElement;\n  abstract deepcopy(): CRDTElement;\n}\n\n/**\n *\n * `CRDTContainer` represents CRDTArray or CRDtObject.\n */\nexport abstract class CRDTContainer extends CRDTElement {\n  constructor(createdAt: TimeTicket) {\n    super(createdAt);\n  }\n\n  /**\n   * `subPathOf` returns the sub path of the given element.\n   */\n  abstract subPathOf(createdAt: TimeTicket): string | undefined;\n\n  abstract purge(element: CRDTElement): void;\n\n  /**\n   * `purgeBarrierAt` is the element-side form of `GCParent.purgeBarrierAt`,\n   * for a container whose purge unlinks a node of its RGA order (`CRDTArray`).\n   */\n  purgeBarrierAt?(element: CRDTElement): TimeTicket | undefined;\n\n  abstract delete(createdAt: TimeTicket, executedAt: TimeTicket): CRDTElement;\n\n  abstract getDescendants(\n    callback: (elem: CRDTElement, parent: CRDTContainer) => boolean,\n  ): void;\n\n  /**\n   * `get` returns the element of the given key or index. This method is called\n   * by users. So it should return undefined if the element is removed.\n   */\n  abstract get(keyOrIndex: string | number): CRDTElement | undefined;\n\n  /**\n   * `getByID` returns the element of the given creation time. This method is\n   * called by internal. So it should return the element even if the element is\n   * removed.\n   */\n  abstract getByID(createdAt: TimeTicket): CRDTElement | undefined;\n}\n","/*\n * Copyright 2023 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TimeTicket } from '@yorkie-js/sdk/src/document/time/ticket';\nimport { CRDTElement } from '@yorkie-js/sdk/src/document/crdt/element';\nimport { YorkieError, Code } from '@yorkie-js/sdk/src/util/error';\n\n/**\n * `ElementRHTNode` is a node of ElementRHT.\n */\nexport class ElementRHTNode {\n  private strKey: string;\n  private value: CRDTElement;\n\n  constructor(strKey: string, value: CRDTElement) {\n    this.strKey = strKey;\n    this.value = value;\n  }\n\n  /**\n   * `of` creates a instance of ElementRHTNode.\n   */\n  public static of(strKey: string, value: CRDTElement): ElementRHTNode {\n    return new ElementRHTNode(strKey, value);\n  }\n\n  /**\n   * `isRemoved` checks whether this value was removed.\n   */\n  public isRemoved(): boolean {\n    return this.value.isRemoved();\n  }\n\n  /**\n   * `getStrKey` returns the key of this node.\n   */\n  public getStrKey(): string {\n    return this.strKey;\n  }\n\n  /**\n   * `getValue` return the value(element) of this node\n   */\n  public getValue(): CRDTElement {\n    return this.value;\n  }\n\n  /**\n   * `remove` removes a value base on removing time.\n   */\n  public remove(removedAt: TimeTicket): boolean {\n    return this.value.remove(removedAt);\n  }\n}\n\n/**\n * ElementRHT is a hashtable with logical clock(Replicated hashtable)\n *\n */\nexport class ElementRHT {\n  private nodeMapByKey: Map<string, ElementRHTNode>;\n  private nodeMapByCreatedAt: Map<string, ElementRHTNode>;\n\n  constructor() {\n    this.nodeMapByKey = new Map();\n    this.nodeMapByCreatedAt = new Map();\n  }\n\n  /**\n   * `create` creates an instance of ElementRHT.\n   */\n  public static create(): ElementRHT {\n    return new ElementRHT();\n  }\n\n  /**\n   * `set` sets the value of the given key. An existing occupant is removed\n   * only when the incoming value wins the LWW comparison; when it loses, the\n   * occupant stays and the incoming value is marked removed instead.\n   *\n   * Both the win/lose decision and the eviction of the previous occupant are\n   * anchored on the occupant's `positionedAt` (its `movedAt`, falling back to\n   * its `createdAt`). Anchoring them on different tickets lets them disagree:\n   * `CRDTElement.remove` gates on the raw `createdAt`, so for an occupant\n   * whose `createdAt < executedAt < positionedAt` — which is what an undo/redo\n   * restore produces, since it re-places the original element under a fresh\n   * ticket — the eviction fires and tombstones the occupant, while the winner\n   * check decides the incoming value must NOT replace it. The occupant is then\n   * tombstoned but still linked as the key's value, the incoming value is\n   * dropped without being registered as removed, and `get` reports the key as\n   * absent although no operation ever removed it.\n   *\n   * The inner `node.remove(executedAt)` gate is therefore redundant once the\n   * eviction sits inside the winner branch — that branch already guarantees\n   * `executedAt > positionedAt >= createdAt`, which is what\n   * `CRDTElement.remove` checks. It is kept so this reads as the mirror of Go\n   * that it is.\n   *\n   * The losing branch marks the incoming value removed only when it is not\n   * removed already. The marking exists solely to keep a duplicate out of\n   * `ownKeys`, and a value that arrives removed is already out; but\n   * `CRDTElement.remove` accepts any ticket later than the one it holds, so\n   * without the guard it is not a no-op. `converter.fromObject` replays a\n   * decoded object through here, and a decoded tombstone that sorts after the\n   * live occupant would have its `removedAt` bumped from the ticket of the\n   * removal that actually happened to the occupant's `positionedAt` — making\n   * GC on this replica wait on the wrong ticket, and its re-serialized\n   * snapshots and `docSize.gc` disagree with replicas that never reloaded.\n   *\n   * That made rebuilding an object from a snapshot depend on the order its\n   * members happened to arrive in — see\n   * `test/unit/document/crdt/element_rht_order_test.ts`, and\n   * `ElementRHT.SetWithExecutedAt` in `yorkie/pkg/document/crdt/element_rht.go`,\n   * whose anchoring this now mirrors.\n   */\n  public set(\n    key: string,\n    value: CRDTElement,\n    executedAt: TimeTicket,\n  ): CRDTElement | undefined {\n    let removed;\n    const node = this.nodeMapByKey.get(key);\n\n    const newNode = ElementRHTNode.of(key, value);\n    this.nodeMapByCreatedAt.set(value.getCreatedAt().toIDString(), newNode);\n    if (!node || executedAt.after(node.getValue().getPositionedAt())) {\n      if (!!node && !node.isRemoved() && node.remove(executedAt)) {\n        removed = node.getValue();\n      }\n      this.nodeMapByKey.set(key, newNode);\n      value.setMovedAt(executedAt);\n    } else if (!value.isRemoved()) {\n      // A live incoming node that loses the LWW conflict must be removed even\n      // when the current occupant is already a tombstone.\n      value.remove(node.getValue().getPositionedAt());\n    }\n    return removed;\n  }\n\n  /**\n   * `delete` deletes the Element of the given key.\n   */\n  public delete(createdAt: TimeTicket, executedAt: TimeTicket): CRDTElement {\n    if (!this.nodeMapByCreatedAt.has(createdAt.toIDString())) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `fail to find ${createdAt.toIDString()}`,\n      );\n    }\n\n    const node = this.nodeMapByCreatedAt.get(createdAt.toIDString())!;\n    node.remove(executedAt);\n    return node.getValue();\n  }\n\n  /**\n   * `subPathOf` returns the sub path of the given element.\n   */\n  public subPathOf(createdAt: TimeTicket): string | undefined {\n    const node = this.nodeMapByCreatedAt.get(createdAt.toIDString());\n    if (!node) {\n      return;\n    }\n\n    return node.getStrKey();\n  }\n\n  /**\n   * `purge` physically purge child element.\n   */\n  public purge(element: CRDTElement): void {\n    const node = this.nodeMapByCreatedAt.get(\n      element.getCreatedAt().toIDString(),\n    );\n    if (!node) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `fail to find ${element.getCreatedAt().toIDString()}`,\n      );\n    }\n\n    // The slot names a creation time, not an element. Undo of a remove\n    // re-inserts a copy under the original createdAt and `set` re-points this\n    // map at it, so unlinking whatever the key answers with would delete a live\n    // member on a tombstone's behalf. The tombstone is already off both maps by\n    // then, so there is nothing left to unlink.\n    //\n    // A genuinely missing key still throws above: that is a mis-registration\n    // worth reporting, and this guard is only about a slot that has been taken\n    // over.\n    if (node.getValue() !== element) {\n      return;\n    }\n\n    const nodeByKey = this.nodeMapByKey.get(node.getStrKey());\n    if (node === nodeByKey) {\n      this.nodeMapByKey.delete(nodeByKey.getStrKey());\n    }\n\n    this.nodeMapByCreatedAt.delete(node.getValue().getCreatedAt().toIDString());\n  }\n\n  /**\n   * `deleteByKey` deletes the Element of the given key and removed time.\n   */\n  public deleteByKey(\n    key: string,\n    removedAt: TimeTicket,\n  ): CRDTElement | undefined {\n    const node = this.nodeMapByKey.get(key);\n    if (!node) {\n      return;\n    }\n\n    if (!node.remove(removedAt)) {\n      return;\n    }\n\n    return node.getValue();\n  }\n\n  /**\n   * `has` returns whether the element exists of the given key or not.\n   */\n  public has(key: string): boolean {\n    const node = this.nodeMapByKey.get(key);\n    if (!node) {\n      return false;\n    }\n    return !node.isRemoved();\n  }\n\n  /**\n   * `getByID` returns the node of the given createdAt.\n   */\n  public getByID(createdAt: TimeTicket): ElementRHTNode | undefined {\n    return this.nodeMapByCreatedAt.get(createdAt.toIDString());\n  }\n\n  /**\n   * `get` returns the node of the given key.\n   */\n  public get(key: string): ElementRHTNode | undefined {\n    const node = this.nodeMapByKey.get(key);\n    if (!node || node.isRemoved()) {\n      return;\n    }\n\n    return node;\n  }\n\n  /**\n   * `deepcopy` creates a deep copy of this ElementRHT.\n   */\n  public deepcopy(): ElementRHT {\n    const clone = ElementRHT.create();\n    for (const [, node] of this.nodeMapByCreatedAt) {\n      clone.nodeMapByCreatedAt.set(\n        node.getValue().getCreatedAt().toIDString(),\n        ElementRHTNode.of(node.getStrKey(), node.getValue().deepcopy()),\n      );\n    }\n\n    for (const [key, node] of this.nodeMapByKey) {\n      clone.nodeMapByKey.set(\n        key,\n        clone.nodeMapByCreatedAt.get(\n          node.getValue().getCreatedAt().toIDString(),\n        )!,\n      );\n    }\n\n    return clone;\n  }\n\n  // eslint-disable-next-line jsdoc/require-jsdoc\n  public *[Symbol.iterator](): IterableIterator<ElementRHTNode> {\n    for (const [, node] of this.nodeMapByCreatedAt) {\n      yield node;\n    }\n  }\n}\n","/*\n * Copyright 2023 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { escapeString } from '@yorkie-js/sdk/src/document/json/strings';\nimport { TimeTicket } from '@yorkie-js/sdk/src/document/time/ticket';\nimport {\n  CRDTContainer,\n  CRDTElement,\n} from '@yorkie-js/sdk/src/document/crdt/element';\nimport { ElementRHT } from '@yorkie-js/sdk/src/document/crdt/element_rht';\nimport type * as Devtools from '@yorkie-js/sdk/src/devtools/types';\nimport { DataSize } from '@yorkie-js/sdk/src/util/resource';\n\n/**\n * `CRDTObject` represents an object data type, but unlike regular JSON,\n * it has `TimeTicket`s which are created by logical clock.\n *\n */\nexport class CRDTObject extends CRDTContainer {\n  private memberNodes: ElementRHT;\n\n  constructor(createdAt: TimeTicket, memberNodes: ElementRHT) {\n    super(createdAt);\n    this.memberNodes = memberNodes;\n  }\n\n  /**\n   * `create` creates a new instance of CRDTObject.\n   */\n  public static create(\n    createdAt: TimeTicket,\n    value?: { [key: string]: CRDTElement },\n  ): CRDTObject {\n    if (!value) {\n      return new CRDTObject(createdAt, ElementRHT.create());\n    }\n\n    const memberNodes = ElementRHT.create();\n    for (const [k, v] of Object.entries(value)) {\n      memberNodes.set(k, v.deepcopy(), v.getCreatedAt());\n    }\n    return new CRDTObject(createdAt, memberNodes);\n  }\n\n  /**\n   * `subPathOf` returns the sub path of the given element.\n   */\n  public subPathOf(createdAt: TimeTicket): string | undefined {\n    return this.memberNodes.subPathOf(createdAt);\n  }\n\n  /**\n   * `purge` physically purges the given element.\n   */\n  public purge(value: CRDTElement): void {\n    this.memberNodes.purge(value);\n  }\n\n  /**\n   * `set` sets the given element of the given key.\n   */\n  public set(\n    key: string,\n    value: CRDTElement,\n    executedAt: TimeTicket,\n  ): CRDTElement | undefined {\n    return this.memberNodes.set(key, value, executedAt);\n  }\n\n  /**\n   * `delete` deletes the element of the given key.\n   */\n  public delete(createdAt: TimeTicket, executedAt: TimeTicket): CRDTElement {\n    return this.memberNodes.delete(createdAt, executedAt);\n  }\n\n  /**\n   * `deleteByKey` deletes the element of the given key and execution time.\n   */\n  public deleteByKey(\n    key: string,\n    executedAt: TimeTicket,\n  ): CRDTElement | undefined {\n    return this.memberNodes.deleteByKey(key, executedAt);\n  }\n\n  /**\n   * `get` returns the value of the given key.\n   */\n  public get(key: string): CRDTElement | undefined {\n    const node = this.memberNodes.get(key);\n    return node?.getValue();\n  }\n\n  /**\n   * `getByID` returns the element of the given createAt.\n   */\n  public getByID(createdAt: TimeTicket): CRDTElement | undefined {\n    const node = this.memberNodes.getByID(createdAt);\n    return node?.getValue();\n  }\n\n  /**\n   * `has` returns whether the element exists of the given key or not.\n   */\n  public has(key: string): boolean {\n    return this.memberNodes.has(key);\n  }\n\n  /**\n   * `getDataSize` returns the data usage of this element.\n   */\n  public getDataSize(): DataSize {\n    return {\n      data: 0,\n      meta: this.getMetaUsage(),\n    };\n  }\n\n  /**\n   * `toJSON` returns the JSON encoding of this object.\n   */\n  public toJSON(): string {\n    const json = [];\n    for (const [key, value] of this) {\n      json.push(`\"${escapeString(key)}\":${value.toJSON()}`);\n    }\n    return `{${json.join(',')}}`;\n  }\n\n  /**\n   * `toJS` returns the JavaScript object of this object.\n   */\n  public toJS(): any {\n    return JSON.parse(this.toJSON());\n  }\n\n  /**\n   * `toJSForTest` returns value with meta data for testing.\n   */\n  public toJSForTest(): Devtools.JSONElement {\n    const values: Devtools.ContainerValue = {};\n    for (const [key, elem] of this) {\n      const { createdAt, value, type } = elem.toJSForTest();\n      values[key] = {\n        key,\n        createdAt,\n        value,\n        type,\n      };\n    }\n    return {\n      createdAt: this.getCreatedAt().toTestString(),\n      value: values,\n      type: 'YORKIE_OBJECT',\n    };\n  }\n\n  /**\n   * `getKeys` returns array of keys in this object.\n   */\n  public getKeys(): Array<string> {\n    const keys = Array<string>();\n    for (const [key] of this) {\n      keys.push(key);\n    }\n\n    return keys;\n  }\n\n  /**\n   * `toSortedJSON` returns the sorted JSON encoding of this object.\n   */\n  public toSortedJSON(): string {\n    const keys = new Set<string>();\n    for (const [key] of this) {\n      keys.add(key);\n    }\n\n    const json = [];\n    for (const key of Array.from(keys).sort()) {\n      const node = this.memberNodes.get(key)?.getValue();\n      json.push(`\"${escapeString(key)}\":${node!.toSortedJSON()}`);\n    }\n\n    return `{${json.join(',')}}`;\n  }\n\n  /**\n   * `getRHT` RHTNodes returns the RHTPQMap nodes.\n   */\n  public getRHT(): ElementRHT {\n    return this.memberNodes;\n  }\n\n  /**\n   * `deepcopy` copies itself deeply.\n   */\n  public deepcopy(): CRDTObject {\n    const clone = CRDTObject.create(this.getCreatedAt());\n    clone.memberNodes = this.memberNodes.deepcopy();\n    clone.setRemovedAt(this.getRemovedAt());\n    clone.setMovedAt(this.getMovedAt());\n    return clone;\n  }\n\n  /**\n   * `getDescendants` returns the descendants of this object by traversing.\n   */\n  public getDescendants(\n    callback: (elem: CRDTElement, parent: CRDTContainer) => boolean,\n  ): void {\n    for (const node of this.memberNodes) {\n      const element = node.getValue();\n      if (callback(element, this)) {\n        return;\n      }\n\n      if (element instanceof CRDTContainer) {\n        element.getDescendants(callback);\n      }\n    }\n  }\n\n  /**\n   * `[Symbol.iterator]` returns an iterator for the entries in this object.\n   */\n  public *[Symbol.iterator](): IterableIterator<[string, CRDTElement]> {\n    for (const node of this.memberNodes) {\n      if (node.isRemoved()) {\n        continue;\n      }\n\n      yield [node.getStrKey(), node.getValue()];\n    }\n  }\n}\n","/*\n * Copyright 2020 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ActorID } from '@yorkie-js/sdk/src/document/time/actor_id';\nimport { TimeTicket } from '@yorkie-js/sdk/src/document/time/ticket';\nimport { VersionVector } from '@yorkie-js/sdk/src/document/time/version_vector';\nimport { TreeNode } from '@yorkie-js/sdk/src/document/crdt/tree';\nimport { CRDTRoot } from '@yorkie-js/sdk/src/document/crdt/root';\nimport { Indexable } from '@yorkie-js/sdk/src/document/document';\nimport { Code, YorkieError } from '@yorkie-js/sdk/src/util/error';\n\n/**\n * `OpSource` represents the source of the operation. It is used to handle\n * corner cases in the operations created by undo/redo allow the removed\n * elements when executing them.\n */\nexport enum OpSource {\n  Local = 'local',\n  Remote = 'remote',\n  UndoRedo = 'undoredo',\n}\n\n/**\n * `OpInfo` represents the information of an operation.\n * It is used to inform to the user what kind of operation was executed.\n */\nexport type OpInfo =\n  | TextOpInfo\n  | CounterOpInfo\n  | ArrayOpInfo\n  | ObjectOpInfo\n  | TreeOpInfo;\n\n/**\n * `TextOpInfo` represents the OperationInfo for the yorkie.Text.\n */\nexport type TextOpInfo = EditOpInfo | StyleOpInfo;\n\n/**\n * `CounterOpInfo` represents the OperationInfo for the yorkie.Counter.\n */\nexport type CounterOpInfo = IncreaseOpInfo;\n\n/**\n * `ArrayOpInfo` represents the OperationInfo for the JSONArray.\n */\nexport type ArrayOpInfo =\n  | AddOpInfo\n  | RemoveOpInfo\n  | MoveOpInfo\n  | ArraySetOpInfo;\n\n/**\n * `ObjectOpInfo` represents the OperationInfo for the JSONObject.\n */\nexport type ObjectOpInfo = SetOpInfo | RemoveOpInfo;\n\n/**\n * `TreeOpInfo` represents the OperationInfo for the yorkie.Tree.\n */\nexport type TreeOpInfo = TreeEditOpInfo | TreeStyleOpInfo;\n\n/**\n * `AddOpInfo` represents the information of the add operation.\n */\nexport type AddOpInfo = {\n  type: 'add';\n  path: string;\n  index: number;\n};\n\n/**\n * `MoveOpInfo` represents the information of the move operation.\n */\nexport type MoveOpInfo = {\n  type: 'move';\n  path: string;\n  previousIndex: number;\n  index: number;\n};\n\n/**\n * `SetOpInfo` represents the information of the set operation.\n */\nexport type SetOpInfo = {\n  type: 'set';\n  path: string;\n  key: string;\n};\n\n/**\n * `ArraySetOpInfo` represents the information of the array set operation.\n */\nexport type ArraySetOpInfo = {\n  type: 'array-set';\n  path: string;\n};\n\n/**\n * `RemoveOpInfo` represents the information of the remove operation.\n */\nexport type RemoveOpInfo = {\n  type: 'remove';\n  path: string;\n  key?: string;\n  index?: number;\n};\n\n/**\n * `IncreaseOpInfo` represents the information of the increase operation.\n */\nexport type IncreaseOpInfo = {\n  type: 'increase';\n  path: string;\n  value: number;\n};\n\n/**\n * `EditOpInfo` represents the information of the edit operation.\n */\nexport type EditOpInfo = {\n  type: 'edit';\n  path: string;\n  from: number;\n  to: number;\n  value: {\n    attributes: Indexable;\n    content: string;\n  };\n};\n\n/**\n * `StyleOpInfo` represents the information of the style operation.\n */\nexport type StyleOpInfo = {\n  type: 'style';\n  path: string;\n  from: number;\n  to: number;\n  value: {\n    attributes: Indexable;\n  };\n};\n\n/**\n * `TreeEditOpInfo` represents the information of the tree edit operation.\n */\nexport type TreeEditOpInfo = {\n  type: 'tree-edit';\n  path: string;\n  from: number;\n  to: number;\n  value?: Array<TreeNode>;\n  splitLevel?: number;\n  fromPath: Array<number>;\n  toPath: Array<number>;\n};\n\n/**\n * `TreeStyleOpInfo` represents the information of the tree style operation.\n */\nexport type TreeStyleOpInfo = {\n  type: 'tree-style';\n  path: string;\n  from: number;\n  to: number;\n  fromPath: Array<number>;\n  toPath: Array<number>;\n  value: {\n    attributes?: Indexable;\n    attributesToRemove?: Array<string>;\n  };\n};\n\n/**\n * `ExecutionResult` represents the result of operation execution.\n */\nexport type ExecutionResult = {\n  opInfos: Array<OpInfo>;\n  // TODO(chacha912): After implementing all of the reverseOperation,\n  // we change the type to non-optional.\n  reverseOp?: Operation;\n};\n\n/**\n * `Operation` represents an operation to be executed on a document.\n */\nexport abstract class Operation {\n  private parentCreatedAt: TimeTicket;\n  // NOTE(Hyemmie): `executedAt` variable is undefined if this operation is not executed yet.\n  private executedAt?: TimeTicket;\n\n  constructor(parentCreatedAt: TimeTicket, executedAt?: TimeTicket) {\n    this.parentCreatedAt = parentCreatedAt;\n    this.executedAt = executedAt;\n  }\n\n  /**\n   * `getParentCreatedAt` returns the creation time of the target element to\n   * execute the operation.\n   */\n  public getParentCreatedAt(): TimeTicket {\n    return this.parentCreatedAt;\n  }\n\n  /**\n   * `getExecutedAt` returns execution time of this operation.\n   */\n  public getExecutedAt(): TimeTicket {\n    // NOTE(chacha912): When an operation is in the undo/redo stack,\n    // it doesn't have an executedAt yet. The executedAt is set when\n    // the operation is executed through undo or redo.\n    if (!this.executedAt) {\n      throw new YorkieError(Code.ErrNotReady, 'executedAt is not set yet');\n    }\n    return this.executedAt;\n  }\n\n  /**\n   * `setActor` sets the given actor to this operation.\n   */\n  public setActor(actorID: ActorID): void {\n    if (this.executedAt) {\n      this.executedAt = this.executedAt.setActor(actorID);\n    }\n  }\n\n  /**\n   * `setExecutedAt` sets the executedAt.\n   */\n  public setExecutedAt(executedAt: TimeTicket): void {\n    this.executedAt = executedAt;\n  }\n\n  /**\n   * `getEffectedCreatedAt` returns the creation time of the effected element.\n   */\n  public abstract getEffectedCreatedAt(): TimeTicket;\n\n  /**\n   * `toTestString` returns a string containing the meta data for debugging purpose.\n   */\n  public abstract toTestString(): string;\n\n  /**\n   * `execute` executes this operation on the given `CRDTRoot`.\n   */\n  public abstract execute(\n    root: CRDTRoot,\n    source: OpSource,\n    versionVector?: VersionVector,\n  ): ExecutionResult | undefined;\n}\n","/*\n * Copyright 2026 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, YorkieError } from './error';\n\n/**\n * `TreeListValue` represents the data stored in the nodes of TreeList.\n */\nexport interface TreeListValue {\n  isRemoved(): boolean;\n  toString(): string;\n}\n\n/**\n * `TreeListNode` is a node of TreeList.\n *\n * It tracks two aggregates over its subtree:\n *   - weight: number of non-removed (live) nodes (logical index)\n *   - count: total nodes including tombstones (structural index)\n */\nexport class TreeListNode<V extends TreeListValue> {\n  private value: V;\n\n  private left?: TreeListNode<V>;\n  private right?: TreeListNode<V>;\n  private parent?: TreeListNode<V>;\n\n  private weight: number;\n  private count: number;\n\n  private red: boolean;\n\n  constructor(value: V) {\n    this.value = value;\n    this.red = true;\n    this.weight = this.size();\n    this.count = 1;\n  }\n\n  /**\n   * `getValue` returns the value of this node.\n   */\n  public getValue(): V {\n    return this.value;\n  }\n\n  /**\n   * `size` returns 1 if the node is live, 0 if removed (tombstone).\n   */\n  public size(): number {\n    return this.value.isRemoved() ? 0 : 1;\n  }\n\n  /**\n   * `getLeft` returns the left child.\n   */\n  public getLeft(): TreeListNode<V> | undefined {\n    return this.left;\n  }\n\n  /**\n   * `setLeft` sets the left child.\n   */\n  public setLeft(node: TreeListNode<V> | undefined): void {\n    this.left = node;\n  }\n\n  /**\n   * `getRight` returns the right child.\n   */\n  public getRight(): TreeListNode<V> | undefined {\n    return this.right;\n  }\n\n  /**\n   * `setRight` sets the right child.\n   */\n  public setRight(node: TreeListNode<V> | undefined): void {\n    this.right = node;\n  }\n\n  /**\n   * `getParent` returns the parent.\n   */\n  public getParent(): TreeListNode<V> | undefined {\n    return this.parent;\n  }\n\n  /**\n   * `setParent` sets the parent.\n   */\n  public setParent(node: TreeListNode<V> | undefined): void {\n    this.parent = node;\n  }\n\n  /**\n   * `getWeight` returns the cached live-node weight of this subtree.\n   */\n  public getWeight(): number {\n    return this.weight;\n  }\n\n  /**\n   * `setWeight` sets the cached live-node weight of this subtree.\n   */\n  public setWeight(w: number): void {\n    this.weight = w;\n  }\n\n  /**\n   * `getCount` returns the cached total node count of this subtree.\n   */\n  public getCount(): number {\n    return this.count;\n  }\n\n  /**\n   * `setCount` sets the cached total node count of this subtree.\n   */\n  public setCount(c: number): void {\n    this.count = c;\n  }\n\n  /**\n   * `isRed` reports whether this node is colored red.\n   */\n  public isRed(): boolean {\n    return this.red;\n  }\n\n  /**\n   * `setRed` sets the color of this node.\n   */\n  public setRed(red: boolean): void {\n    this.red = red;\n  }\n\n  /**\n   * `leftWeight` returns the live-node weight of the left subtree, or 0 if absent.\n   */\n  public leftWeight(): number {\n    return this.left ? this.left.weight : 0;\n  }\n\n  /**\n   * `rightWeight` returns the live-node weight of the right subtree, or 0 if absent.\n   */\n  public rightWeight(): number {\n    return this.right ? this.right.weight : 0;\n  }\n\n  /**\n   * `leftCount` returns the total node count of the left subtree, or 0 if absent.\n   */\n  public leftCount(): number {\n    return this.left ? this.left.count : 0;\n  }\n\n  /**\n   * `rightCount` returns the total node count of the right subtree, or 0 if absent.\n   */\n  public rightCount(): number {\n    return this.right ? this.right.count : 0;\n  }\n}\n\n/**\n * `isRed` reports whether the given node is a red link. An undefined node is\n * treated as black, matching the standard LLRB convention.\n */\nfunction isRed<V extends TreeListValue>(\n  node: TreeListNode<V> | undefined,\n): boolean {\n  return !!node && node.isRed();\n}\n\n/**\n * `updateNode` recomputes the cached weight and count aggregates of node from\n * its children. Call this whenever the structure or liveness of a child\n * changes.\n */\nfunction updateNode<V extends TreeListValue>(node: TreeListNode<V>): void {\n  node.setWeight(node.leftWeight() + node.size() + node.rightWeight());\n  node.setCount(node.leftCount() + 1 + node.rightCount());\n}\n\n/**\n * `rotateLeft` performs a standard LLRB left rotation around node, promoting\n * its right child. Parent pointers and aggregate counters are refreshed and\n * the new subtree root is returned.\n */\nfunction rotateLeft<V extends TreeListValue>(\n  node: TreeListNode<V>,\n): TreeListNode<V> {\n  const right = node.getRight()!;\n\n  node.setRight(right.getLeft());\n  if (node.getRight()) {\n    node.getRight()!.setParent(node);\n  }\n\n  right.setLeft(node);\n  right.setParent(node.getParent());\n  node.setParent(right);\n\n  right.setRed(node.isRed());\n  node.setRed(true);\n\n  updateNode(node);\n  updateNode(right);\n  return right;\n}\n\n/**\n * `rotateRight` performs a standard LLRB right rotation around node, promoting\n * its left child. Parent pointers and aggregate counters are refreshed and\n * the new subtree root is returned.\n */\nfunction rotateRight<V extends TreeListValue>(\n  node: TreeListNode<V>,\n): TreeListNode<V> {\n  const left = node.getLeft()!;\n\n  node.setLeft(left.getRight());\n  if (node.getLeft()) {\n    node.getLeft()!.setParent(node);\n  }\n\n  left.setRight(node);\n  left.setParent(node.getParent());\n  node.setParent(left);\n\n  left.setRed(node.isRed());\n  node.setRed(true);\n\n  updateNode(node);\n  updateNode(left);\n  return left;\n}\n\n/**\n * `flipColors` toggles the colors of node and both of its children, used\n * during LLRB splits and merges.\n */\nfunction flipColors<V extends TreeListValue>(node: TreeListNode<V>): void {\n  node.setRed(!node.isRed());\n  node.getLeft()!.setRed(!node.getLeft()!.isRed());\n  node.getRight()!.setRed(!node.getRight()!.isRed());\n}\n\n/**\n * `moveRedLeft` ensures the left child or one of its children is red so a\n * deletion descending to the left can proceed without violating LLRB\n * invariants. The new subtree root is returned.\n */\nfunction moveRedLeft<V extends TreeListValue>(\n  node: TreeListNode<V>,\n): TreeListNode<V> {\n  flipColors(node);\n  if (isRed(node.getRight()!.getLeft())) {\n    node.setRight(rotateRight(node.getRight()!));\n    node.getRight()!.setParent(node);\n    node = rotateLeft(node);\n    flipColors(node);\n  }\n  return node;\n}\n\n/**\n * `moveRedRight` ensures the right child or one of its children is red so a\n * deletion descending to the right can proceed without violating LLRB\n * invariants. The new subtree root is returned.\n */\nfunction moveRedRight<V extends TreeListValue>(\n  node: TreeListNode<V>,\n): TreeListNode<V> {\n  flipColors(node);\n  if (isRed(node.getLeft()!.getLeft())) {\n    node = rotateRight(node);\n    flipColors(node);\n  }\n  return node;\n}\n\n/**\n * `removeMin` removes the minimum (left-most) node from the subtree rooted at\n * node and returns the rebalanced subtree root. Used by Delete when splicing\n * in the in-order successor.\n */\nfunction removeMin<V extends TreeListValue>(\n  node: TreeListNode<V>,\n): TreeListNode<V> | undefined {\n  if (!node.getLeft()) {\n    return undefined;\n  }\n\n  if (!isRed(node.getLeft()) && !isRed(node.getLeft()!.getLeft())) {\n    node = moveRedLeft(node);\n  }\n\n  node.setLeft(removeMin(node.getLeft()!));\n  if (node.getLeft()) {\n    node.getLeft()!.setParent(node);\n  }\n\n  return fixUp(node);\n}\n\n/**\n * `minNode` returns the left-most node of the subtree rooted at node, which\n * is the in-order successor used during deletion.\n */\nfunction minNode<V extends TreeListValue>(\n  node: TreeListNode<V>,\n): TreeListNode<V> {\n  while (node.getLeft()) {\n    node = node.getLeft()!;\n  }\n  return node;\n}\n\n/**\n * `fixUp` restores LLRB invariants on the way back up after an insertion or\n * deletion: it leans right-red links left, splits 4-nodes, and refreshes the\n * node's aggregate counters.\n */\nfunction fixUp<V extends TreeListValue>(\n  node: TreeListNode<V>,\n): TreeListNode<V> {\n  if (isRed(node.getRight()) && !isRed(node.getLeft())) {\n    node = rotateLeft(node);\n  }\n  if (isRed(node.getLeft()) && isRed(node.getLeft()!.getLeft())) {\n    node = rotateRight(node);\n  }\n  if (isRed(node.getLeft()) && isRed(node.getRight())) {\n    flipColors(node);\n  }\n  updateNode(node);\n  return node;\n}\n\n/**\n * `traverseInOrder` walks the subtree rooted at node in left-root-right\n * order, invoking cb on every node (live and tombstoned).\n */\nfunction traverseInOrder<V extends TreeListValue>(\n  node: TreeListNode<V> | undefined,\n  cb: (n: TreeListNode<V>) => void,\n): void {\n  if (!node) {\n    return;\n  }\n  traverseInOrder(node.getLeft(), cb);\n  cb(node);\n  traverseInOrder(node.getRight(), cb);\n}\n\n/**\n * `TreeList` is an order-statistic tree based on Left-leaning Red-Black Tree.\n * It is used by RGATreeList to support index-based operations on a list with\n * tombstones, guaranteeing O(log N) worst-case for all operations.\n *\n * It maintains two weights per node:\n *   - weight: count of non-removed nodes (for index-based lookup)\n *   - count: total nodes including tombstones (for structural operations)\n */\nexport class TreeList<V extends TreeListValue> {\n  private root?: TreeListNode<V>;\n\n  constructor(root?: TreeListNode<V>) {\n    if (root) {\n      root.setRed(false);\n    }\n    this.root = root;\n  }\n\n  /**\n   * `length` returns the number of non-removed (live) nodes.\n   */\n  public get length(): number {\n    return this.root ? this.root.getWeight() : 0;\n  }\n\n  /**\n   * `insertAfter` inserts the target node right after prev in the in-order\n   * traversal. It uses structural (count-based) indexing to correctly handle\n   * tombstone nodes.\n   */\n  public insertAfter(prev: TreeListNode<V>, target: TreeListNode<V>): void {\n    if (!prev || !target) {\n      return;\n    }\n\n    target.setLeft(undefined);\n    target.setRight(undefined);\n    target.setParent(undefined);\n    target.setRed(true);\n    target.setWeight(target.size());\n    target.setCount(1);\n\n    const idx = this.structuralIndexOf(prev);\n    this.root = this.insertByCount(this.root, idx + 1, target);\n    this.root!.setRed(false);\n    this.root!.setParent(undefined);\n  }\n\n  /**\n   * `insertByCount` inserts newNode at the given structural index within the\n   * subtree rooted at node, descending the tree using each node's left count\n   * (tombstones included) and rebalancing on the way back up.\n   */\n  private insertByCount(\n    node: TreeListNode<V> | undefined,\n    index: number,\n    newNode: TreeListNode<V>,\n  ): TreeListNode<V> {\n    if (!node) {\n      return newNode;\n    }\n\n    if (index <= node.leftCount()) {\n      node.setLeft(this.insertByCount(node.getLeft(), index, newNode));\n      node.getLeft()!.setParent(node);\n    } else {\n      node.setRight(\n        this.insertByCount(\n          node.getRight(),\n          index - node.leftCount() - 1,\n          newNode,\n        ),\n      );\n      node.getRight()!.setParent(node);\n    }\n\n    return fixUp(node);\n  }\n\n  /**\n   * `find` returns the node at the given logical index (among non-removed\n   * nodes). Throws when the index is out of range.\n   */\n  public find(index: number): TreeListNode<V> {\n    if (!this.root || index < 0 || index >= this.length) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `out of index: tree size ${this.length}, index ${index}`,\n      );\n    }\n\n    let node = this.root;\n    for (;;) {\n      if (index < node.leftWeight()) {\n        node = node.getLeft()!;\n      } else if (index < node.leftWeight() + node.size()) {\n        break;\n      } else {\n        index -= node.leftWeight() + node.size();\n        node = node.getRight()!;\n      }\n    }\n    return node;\n  }\n\n  /**\n   * `delete` physically removes a node from the tree. Unlike tombstoning,\n   * this completely removes the node from the tree structure. It uses\n   * structural (count-based) indexing and swaps the node structure (not\n   * values) with its successor to preserve node identity.\n   */\n  public delete(node: TreeListNode<V>): void {\n    if (!node || !this.root) {\n      return;\n    }\n\n    if (!isRed(this.root.getLeft()) && !isRed(this.root.getRight())) {\n      this.root.setRed(true);\n    }\n\n    const idx = this.structuralIndexOf(node);\n    this.root = this.deleteByCount(this.root, idx);\n\n    if (this.root) {\n      this.root.setRed(false);\n      this.root.setParent(undefined);\n    }\n  }\n\n  /**\n   * `deleteByCount` removes the node at the given structural index within the\n   * subtree rooted at node. When deleting an internal node, it swaps in the\n   * in-order successor by re-parenting rather than copying values so external\n   * references to the surviving node remain valid.\n   */\n  private deleteByCount(\n    node: TreeListNode<V>,\n    index: number,\n  ): TreeListNode<V> | undefined {\n    if (index < node.leftCount()) {\n      if (!isRed(node.getLeft()) && !isRed(node.getLeft()!.getLeft())) {\n        node = moveRedLeft(node);\n      }\n      node.setLeft(this.deleteByCount(node.getLeft()!, index));\n      if (node.getLeft()) {\n        node.getLeft()!.setParent(node);\n      }\n    } else {\n      if (isRed(node.getLeft())) {\n        node = rotateRight(node);\n      }\n\n      if (index === node.leftCount() && !node.getRight()) {\n        return undefined;\n      }\n\n      if (!isRed(node.getRight()) && !isRed(node.getRight()!.getLeft())) {\n        node = moveRedRight(node);\n      }\n\n      if (index === node.leftCount()) {\n        // Swap the successor into this position instead of copying values.\n        // This preserves node identity so external references remain valid.\n        const successor = minNode(node.getRight()!);\n        const newRight = removeMin(node.getRight()!);\n\n        successor.setLeft(node.getLeft());\n        successor.setRight(newRight);\n        successor.setRed(node.isRed());\n        if (successor.getLeft()) {\n          successor.getLeft()!.setParent(successor);\n        }\n        if (successor.getRight()) {\n          successor.getRight()!.setParent(successor);\n        }\n\n        node.setLeft(undefined);\n        node.setRight(undefined);\n        node.setParent(undefined);\n\n        node = successor;\n      } else {\n        node.setRight(\n          this.deleteByCount(node.getRight()!, index - node.leftCount() - 1),\n        );\n        if (node.getRight()) {\n          node.getRight()!.setParent(node);\n        }\n      }\n    }\n\n    return fixUp(node);\n  }\n\n  /**\n   * `updateWeight` propagates weight changes from the given node up to the\n   * root. Call this after a node's isRemoved() status changes (i.e., after\n   * tombstoning).\n   */\n  public updateWeight(node: TreeListNode<V>): void {\n    for (\n      let cur: TreeListNode<V> | undefined = node;\n      cur !== undefined;\n      cur = cur.getParent()\n    ) {\n      cur.setWeight(cur.leftWeight() + cur.size() + cur.rightWeight());\n    }\n  }\n\n  /**\n   * `toTestString` returns a string containing the metadata of the node for\n   * debugging purpose.\n   */\n  public toTestString(): string {\n    let s = '';\n    traverseInOrder(this.root, (node) => {\n      s += `[${node.getWeight()},${node.size()}]${node.getValue().toString()}`;\n    });\n    return s;\n  }\n\n  /**\n   * `indexOf` returns the logical (live-node) index of the given node, or -1\n   * if the node is a tombstone.\n   */\n  public indexOf(node: TreeListNode<V>): number {\n    if (node.size() === 0) {\n      return -1;\n    }\n    let index = node.leftWeight();\n    for (\n      let cur: TreeListNode<V> = node;\n      cur.getParent() !== undefined;\n      cur = cur.getParent()!\n    ) {\n      if (cur === cur.getParent()!.getRight()) {\n        index += cur.getParent()!.leftWeight() + cur.getParent()!.size();\n      }\n    }\n    return index;\n  }\n\n  /**\n   * `structuralIndexOf` returns the structural position of the node, counting\n   * all nodes including tombstones.\n   */\n  private structuralIndexOf(node: TreeListNode<V>): number {\n    let index = node.leftCount();\n    for (\n      let cur: TreeListNode<V> = node;\n      cur.getParent() !== undefined;\n      cur = cur.getParent()!\n    ) {\n      if (cur === cur.getParent()!.getRight()) {\n        index += cur.getParent()!.leftCount() + 1;\n      }\n    }\n    return index;\n  }\n}\n","/*\n * Copyright 2020 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport enum LogLevel {\n  Trivial,\n  Debug,\n  Info,\n  Warn,\n  Error,\n  Fatal,\n}\n\nlet level = LogLevel.Warn;\n\n/**\n * `setLogLevel` sets log level.\n */\nexport function setLogLevel(l: LogLevel): void {\n  level = l;\n}\n\nexport const logger = {\n  trivial: (...messages: Array<unknown>): void => {\n    if (level > LogLevel.Trivial) {\n      return;\n    }\n\n    if (typeof console != 'undefined') {\n      console.log('YORKIE T:', ...messages);\n    }\n  },\n\n  debug: (...messages: Array<unknown>): void => {\n    if (level > LogLevel.Debug) {\n      return;\n    }\n\n    if (typeof console != 'undefined') {\n      console.log('YORKIE D:', ...messages);\n    }\n  },\n\n  info: (...messages: Array<unknown>): void => {\n    if (level > LogLevel.Info) {\n      return;\n    }\n\n    if (typeof console != 'undefined') {\n      console.log('YORKIE I:', ...messages);\n    }\n  },\n\n  warn: (...messages: Array<unknown>): void => {\n    if (level > LogLevel.Warn) {\n      return;\n    }\n\n    if (typeof console != 'undefined') {\n      if (typeof console.warn !== 'undefined') {\n        console.warn('YORKIE W:', ...messages);\n      } else {\n        console.log('YORKIE W:', ...messages);\n      }\n    }\n  },\n\n  error: (...messages: Array<unknown>): void => {\n    if (level > LogLevel.Error) {\n      return;\n    }\n\n    if (typeof console != 'undefined') {\n      if (typeof console.error !== 'undefined') {\n        console.error('YORKIE E:', ...messages);\n      } else {\n        console.log('YORKIE E:', ...messages);\n      }\n    }\n  },\n\n  fatal: (...messages: Array<unknown>): void => {\n    if (typeof console != 'undefined') {\n      if (typeof console.error !== 'undefined') {\n        console.error('YORKIE F:', ...messages);\n      } else {\n        console.log('YORKIE F:', ...messages);\n      }\n    }\n  },\n\n  isEnabled: (l: LogLevel): boolean => {\n    return level <= l;\n  },\n};\n","/*\n * Copyright 2023 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * `removeDecimal` returns a number with the decimal part removed.\n */\nexport const removeDecimal = (number: number) =>\n  number < 0 ? Math.ceil(number) : Math.floor(number);\n\n/**\n * `MaxInt64` is the maximum value of a signed 64-bit integer (2^63 - 1).\n */\nexport const MaxInt64 = 2n ** 63n - 1n;\n\n/**\n * `MinInt64` is the minimum value of a signed 64-bit integer (-2^63).\n */\nexport const MinInt64 = -(2n ** 63n);\n\n/**\n * `isWithinInt64Range` reports whether the given bigint fits in a signed\n * 64-bit integer. Values outside this range cannot be stored as a Long\n * without silently wrapping, so callers should reject them.\n */\nexport function isWithinInt64Range(value: bigint): boolean {\n  return value >= MinInt64 && value <= MaxInt64;\n}\n\n/**\n * `bigintToBytesLE` converts a signed 64-bit bigint to 8 bytes (little-endian).\n */\nexport function bigintToBytesLE(value: bigint): Uint8Array {\n  const buf = new Uint8Array(8);\n  // Interpret as unsigned 64-bit to handle negative values correctly.\n  let v = BigInt.asUintN(64, value);\n  for (let i = 0; i < 8; i++) {\n    buf[i] = Number(v & 0xffn);\n    v >>= 8n;\n  }\n  return buf;\n}\n\n/**\n * `uint64FromBytesLE` reads the first 8 bytes (little-endian) of the given\n * array as an unsigned 64-bit bigint.\n *\n * These bytes come off the wire, so their length is whatever a remote peer\n * sent. A byte the payload does not carry reads as zero rather than as\n * `undefined`, which `BigInt()` would reject with a raw TypeError: a truncated\n * payload would then abort the whole snapshot or change decode for every\n * client of the document. Zero padding matches how the other fixed-width\n * primitives read a short payload.\n */\nfunction uint64FromBytesLE(bytes: Uint8Array): bigint {\n  let v = 0n;\n  for (let i = 7; i >= 0; i--) {\n    v = (v << 8n) | BigInt(bytes[i] ?? 0);\n  }\n  return v;\n}\n\n/**\n * `bigintFromBytesLE` reads a signed 64-bit bigint from 8 bytes (little-endian).\n */\nexport function bigintFromBytesLE(bytes: Uint8Array): bigint {\n  return BigInt.asIntN(64, uint64FromBytesLE(bytes));\n}\n\n/**\n * `bigintFromBytesLEUnsigned` reads an unsigned 64-bit bigint from 8 bytes (little-endian).\n */\nexport function bigintFromBytesLEUnsigned(bytes: Uint8Array): bigint {\n  return uint64FromBytesLE(bytes);\n}\n\n/**\n * `bigintToInt32` truncates a bigint to a signed 32-bit integer.\n */\nexport function bigintToInt32(value: bigint): number {\n  return Number(BigInt.asIntN(32, value));\n}\n","/*\n * Copyright 2020 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, YorkieError } from '@yorkie-js/sdk/src/util/error';\nimport { logger } from '@yorkie-js/sdk/src/util/logger';\nimport { TimeTicket } from '@yorkie-js/sdk/src/document/time/ticket';\nimport { CRDTElement } from '@yorkie-js/sdk/src/document/crdt/element';\nimport { escapeString } from '@yorkie-js/sdk/src/document/json/strings';\nimport type * as Devtools from '@yorkie-js/sdk/src/devtools/types';\nimport { DataSize } from '@yorkie-js/sdk/src/util/resource';\nimport {\n  bigintToBytesLE,\n  bigintFromBytesLE,\n  bigintFromBytesLEUnsigned,\n  isWithinInt64Range,\n} from '@yorkie-js/sdk/src/util/number';\n\nexport enum PrimitiveType {\n  Null,\n  Boolean,\n  Integer,\n  Long,\n  Double,\n  String,\n  Bytes,\n  Date,\n}\n\n/**\n * `PrimitiveValue` represents a value of primitive type. Only values of type\n * included in `PrimitiveValue` can be set to the document.\n */\nexport type PrimitiveValue =\n  // eslint-disable-next-line @typescript-eslint/no-restricted-types\n  null | boolean | number | bigint | string | Uint8Array | Date;\n\n/**\n * `Primitive` represents primitive data type including logical clock.\n * It has a type and a value.\n */\nexport class Primitive extends CRDTElement {\n  private valueType: PrimitiveType;\n  private value: PrimitiveValue;\n\n  constructor(value: PrimitiveValue, createdAt: TimeTicket) {\n    super(createdAt);\n    this.valueType = Primitive.getPrimitiveType(value)!;\n    if (this.valueType === PrimitiveType.Long) {\n      // Both the number path (promoted from out-of-int32 integers) and the\n      // bigint path converge here. Reject magnitudes outside the int64 range\n      // instead of silently wrapping them in `bigintToBytesLE`, since the SDK\n      // has no wider lossless integer type to promote them to.\n      const longValue =\n        typeof value === 'number' ? BigInt(value) : (value as bigint);\n      if (!isWithinInt64Range(longValue)) {\n        throw new YorkieError(\n          Code.ErrInvalidArgument,\n          `${value} is out of the int64 range and cannot be stored as Long`,\n        );\n      }\n      if (typeof value === 'number') {\n        logger.warn(\n          `number exceeds int32 range and will be stored as Long (bigint): ${value}`,\n        );\n      }\n      this.value = longValue;\n    } else {\n      this.value = value === undefined ? null : value;\n    }\n  }\n\n  /**\n   * `of` creates a new instance of Primitive.\n   */\n  public static of(value: PrimitiveValue, createdAt: TimeTicket): Primitive {\n    return new Primitive(value, createdAt);\n  }\n\n  /**\n   * `valueFromBytes` parses the given bytes into value.\n   */\n  public static valueFromBytes(\n    primitiveType: PrimitiveType,\n    bytes: Uint8Array,\n  ): PrimitiveValue {\n    switch (primitiveType) {\n      case PrimitiveType.Null:\n        return null;\n      case PrimitiveType.Boolean:\n        return bytes[0] ? true : false;\n      case PrimitiveType.Integer:\n        return bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24);\n      case PrimitiveType.Double: {\n        // NOTE(chacha912): The bytes are copied into a buffer of this value's\n        // own before being read. The earlier code copied them to offset 0 of\n        // the *underlying* buffer and read them back from there, which\n        // answered correctly and wrote through to whatever else was sharing\n        // that buffer: a snapshot arrives as one buffer the decoder hands out\n        // as views, so reading a double out of a document overwrote the first\n        // eight bytes of the snapshot itself.\n        //\n        // Reading in place would fix that but would also make a payload\n        // shorter than eight bytes throw, where it used to answer. The copy\n        // keeps both: nothing outside this value is written, and a short\n        // payload reads as the zero-padded value it would have been.\n        const buffer = new Uint8Array(8);\n        buffer.set(bytes.subarray(0, 8));\n        return new DataView(buffer.buffer).getFloat64(0, true);\n      }\n      case PrimitiveType.String:\n        return new TextDecoder('utf-8').decode(bytes);\n      case PrimitiveType.Long:\n        return bigintFromBytesLE(bytes);\n      case PrimitiveType.Bytes:\n        // NOTE(chacha912): Copied for the same reason as the Double case above:\n        // the decoder hands out views into one snapshot buffer, and returning\n        // this one would hand the application a window onto the rest of that\n        // buffer, which a later decode is free to write through.\n        return bytes.slice();\n      case PrimitiveType.Date:\n        return new Date(Number(bigintFromBytesLEUnsigned(bytes)));\n      default:\n        throw new YorkieError(\n          Code.ErrUnimplemented,\n          `unimplemented type: ${primitiveType}`,\n        );\n    }\n  }\n\n  /**\n   * `getValueSize` returns the size of the value. The size is similar to\n   * the size of primitives in JavaScript.\n   */\n  private getValueSize(): number {\n    switch (this.valueType) {\n      case PrimitiveType.Null:\n        // Word Size in 64-bit system.\n        return 8;\n      case PrimitiveType.Boolean:\n        return 4;\n      case PrimitiveType.Integer:\n        return 4;\n      case PrimitiveType.Long:\n        return 8;\n      case PrimitiveType.Double:\n        return 8;\n      case PrimitiveType.String:\n        // string is UTF-16 encoded.\n        return (this.value as string).length * 2;\n      case PrimitiveType.Bytes:\n        return (this.value as Uint8Array).length;\n      case PrimitiveType.Date:\n        return 8;\n      default:\n        throw new YorkieError(\n          Code.ErrUnimplemented,\n          `unimplemented type: ${this.valueType}`,\n        );\n    }\n  }\n\n  /**\n   * `getDataSize` returns the data usage of this element.\n   */\n  public getDataSize(): DataSize {\n    return {\n      data: this.getValueSize(),\n      meta: this.getMetaUsage(),\n    };\n  }\n\n  /**\n   * `toJSON` returns the JSON encoding of the value.\n   */\n  public toJSON(): string {\n    if (this.valueType === PrimitiveType.String) {\n      return `\"${escapeString(this.value as string)}\"`;\n    }\n    if (this.valueType === PrimitiveType.Bytes) {\n      const bytes = this.value as Uint8Array;\n      return `\"${btoa(String.fromCharCode(...bytes))}\"`;\n    }\n    if (this.valueType === PrimitiveType.Date) {\n      return `\"${(this.value as Date).toISOString()}\"`;\n    }\n\n    return `${this.value}`;\n  }\n\n  /**\n   * `toSortedJSON` returns the sorted JSON encoding of the value.\n   */\n  public toSortedJSON(): string {\n    return this.toJSON();\n  }\n\n  /**\n   * `toJSForTest` returns value with meta data for testing.\n   */\n  public toJSForTest(): Devtools.JSONElement {\n    return {\n      createdAt: this.getCreatedAt().toTestString(),\n      value: this.value,\n      type: 'YORKIE_PRIMITIVE',\n    };\n  }\n\n  /**\n   * `deepcopy` copies itself deeply.\n   */\n  public deepcopy(): Primitive {\n    const primitive = Primitive.of(this.value, this.getCreatedAt());\n    primitive.setMovedAt(this.getMovedAt());\n    primitive.setRemovedAt(this.getRemovedAt());\n    return primitive;\n  }\n\n  /**\n   * `getType` returns the type of the value.\n   */\n  public getType(): PrimitiveType {\n    return this.valueType!;\n  }\n\n  /**\n   * `getPrimitiveType` returns the primitive type of the value.\n   */\n  public static getPrimitiveType(value: unknown): PrimitiveType | undefined {\n    switch (typeof value) {\n      case 'undefined':\n        return PrimitiveType.Null;\n      case 'boolean':\n        return PrimitiveType.Boolean;\n      case 'number':\n        if (this.isInteger(value)) {\n          if (value > Math.pow(2, 31) - 1 || value < -Math.pow(2, 31)) {\n            return PrimitiveType.Long;\n          }\n          return PrimitiveType.Integer;\n        }\n        return PrimitiveType.Double;\n      case 'bigint':\n        return PrimitiveType.Long;\n      case 'string':\n        return PrimitiveType.String;\n      case 'object':\n        if (value === null) {\n          return PrimitiveType.Null;\n        } else if (value instanceof Uint8Array) {\n          return PrimitiveType.Bytes;\n        } else if (value instanceof Date) {\n          return PrimitiveType.Date;\n        }\n    }\n\n    return;\n  }\n\n  /**\n   * `isSupport` check if the given value is supported type.\n   */\n  public static isSupport(value: unknown): boolean {\n    const primitiveType = Primitive.getPrimitiveType(value);\n    if (primitiveType === undefined) {\n      return false;\n    }\n    return true;\n  }\n\n  /**\n   * `isInteger` checks if the given number is integer.\n   */\n  public static isInteger(num: number): boolean {\n    return num % 1 === 0;\n  }\n\n  /**\n   * `isNumericType` checks numeric type by JSONPrimitive\n   */\n  public isNumericType(): boolean {\n    const t = this.valueType;\n    return (\n      t === PrimitiveType.Integer ||\n      t === PrimitiveType.Long ||\n      t === PrimitiveType.Double\n    );\n  }\n\n  /**\n   * `getValue` returns the value of Primitive.\n   */\n  public getValue(): PrimitiveValue {\n    return this.value;\n  }\n\n  /**\n   * `toBytes` creates an array representing the value.\n   */\n  public toBytes(): Uint8Array {\n    switch (this.valueType) {\n      case PrimitiveType.Null: {\n        return new Uint8Array();\n      }\n      case PrimitiveType.Boolean: {\n        const boolVal = this.value as boolean;\n        return boolVal ? new Uint8Array([1]) : new Uint8Array([0]);\n      }\n      case PrimitiveType.Integer: {\n        const intVal = this.value as number;\n        return new Uint8Array([\n          intVal & 0xff,\n          (intVal >> 8) & 0xff,\n          (intVal >> 16) & 0xff,\n          (intVal >> 24) & 0xff,\n        ]);\n      }\n      case PrimitiveType.Double: {\n        const doubleVal = this.value as number;\n        const uint8Array = new Uint8Array(8);\n        const view = new DataView(uint8Array.buffer);\n        view.setFloat64(0, doubleVal, true);\n        return uint8Array;\n      }\n      case PrimitiveType.String: {\n        return new TextEncoder().encode(this.value as string);\n      }\n      case PrimitiveType.Long: {\n        return bigintToBytesLE(this.value as bigint);\n      }\n      case PrimitiveType.Bytes: {\n        const bytesVal = this.value as Uint8Array;\n        return bytesVal;\n      }\n      case PrimitiveType.Date: {\n        const dateVal = this.value as Date;\n        return bigintToBytesLE(BigInt(dateVal.getTime()));\n      }\n      default:\n        throw new YorkieError(\n          Code.ErrUnimplemented,\n          `unimplemented type: ${this.valueType}`,\n        );\n    }\n  }\n}\n","/*\n * Copyright 2020 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n  TreeList,\n  TreeListNode,\n  TreeListValue,\n} from '@yorkie-js/sdk/src/util/treelist';\nimport {\n  InitialTimeTicket,\n  TimeTicket,\n  TimeTicketSize,\n} from '@yorkie-js/sdk/src/document/time/ticket';\nimport { CRDTElement } from '@yorkie-js/sdk/src/document/crdt/element';\nimport { GCChild, GCParent } from '@yorkie-js/sdk/src/document/crdt/gc';\nimport { Primitive } from '@yorkie-js/sdk/src/document/crdt/primitive';\nimport { Code, YorkieError } from '@yorkie-js/sdk/src/util/error';\nimport { DataSize } from '@yorkie-js/sdk/src/util/resource';\n\n/**\n * `ElementEntry` is the stable identity of an element in the RGATreeList.\n * It holds the element value and tracks which position node currently owns\n * it.\n */\nexport class ElementEntry {\n  public elem: CRDTElement;\n  public positionNode!: RGATreeListNode;\n  public posMovedAt?: TimeTicket;\n\n  constructor(elem: CRDTElement) {\n    this.elem = elem;\n  }\n}\n\n/**\n * `RGATreeListMove` is what an `RGATreeList.moveAfter` reports back.\n */\nexport type RGATreeListMove = {\n  /**\n   * `deadNode` is the position node the move abandoned, for GC registration.\n   * Absent when the move was discarded by LWW and its position node already\n   * existed.\n   */\n  deadNode?: RGATreeListNode;\n\n  /**\n   * `movedDiff` is the size the move added to the MOVED ELEMENT -- one ticket\n   * for the `movedAt` stamp, and only the first time it is stamped. It is not\n   * the dead position node's size: that node was never in live, and the caller\n   * books it through a `gcOnlySize` pair instead.\n   */\n  movedDiff: DataSize;\n};\n\n/**\n * `RGATreeListNode` is a position slot in the RGA linked list.\n * When `elementEntry` is undefined, it is a dead slot abandoned by a move.\n */\nexport class RGATreeListNode implements GCChild, TreeListValue {\n  public indexNode!: TreeListNode<RGATreeListNode>;\n  private _elementEntry?: ElementEntry;\n  private _createdAt: TimeTicket;\n  private _removedAt?: TimeTicket;\n\n  private prev?: RGATreeListNode;\n  private next?: RGATreeListNode;\n\n  private constructor(createdAt: TimeTicket) {\n    this._createdAt = createdAt;\n  }\n\n  /**\n   * `createWithElement` creates a new node that owns an element.\n   */\n  public static createWithElement(elem: CRDTElement): RGATreeListNode {\n    const entry = new ElementEntry(elem);\n    const node = new RGATreeListNode(elem.getCreatedAt());\n    node._elementEntry = entry;\n    entry.positionNode = node;\n    node.indexNode = new TreeListNode(node);\n    return node;\n  }\n\n  /**\n   * `createBarePosition` creates a position node without an element\n   * (used for move).\n   */\n  public static createBarePosition(createdAt: TimeTicket): RGATreeListNode {\n    const node = new RGATreeListNode(createdAt);\n    node.indexNode = new TreeListNode(node);\n    return node;\n  }\n\n  /**\n   * `createAfter` creates a new node with the given element after\n   * the given prev node.\n   */\n  public static createAfter(\n    prev: RGATreeListNode,\n    elem: CRDTElement,\n  ): RGATreeListNode {\n    const newNode = RGATreeListNode.createWithElement(elem);\n    RGATreeListNode.insertNodeAfter(prev, newNode);\n    return newNode;\n  }\n\n  /**\n   * `insertNodeAfter` inserts a node after the given prev node.\n   */\n  public static insertNodeAfter(\n    prev: RGATreeListNode,\n    newNode: RGATreeListNode,\n  ): void {\n    const prevNext = prev.next;\n    prev.next = newNode;\n    newNode.prev = prev;\n    newNode.next = prevNext;\n    if (prevNext) {\n      prevNext.prev = newNode;\n    }\n  }\n\n  /**\n   * `remove` removes the element based on removing time.\n   */\n  public remove(removedAt: TimeTicket): boolean {\n    if (!this._elementEntry) {\n      return false;\n    }\n    return this._elementEntry.elem.remove(removedAt);\n  }\n\n  /**\n   * `getCreatedAt` returns the creation time. For live nodes with\n   * elements, returns the element's createdAt for backward\n   * compatibility.\n   */\n  public getCreatedAt(): TimeTicket {\n    if (this._elementEntry) {\n      return this._elementEntry.elem.getCreatedAt();\n    }\n    return this._createdAt;\n  }\n\n  /**\n   * `getPositionedAt` returns the time this element was positioned.\n   * For live nodes, the position register (posMovedAt) is the source\n   * of truth. For dead nodes (no element), the position node's own\n   * createdAt is used.\n   */\n  public getPositionedAt(): TimeTicket {\n    if (this._elementEntry) {\n      if (this._elementEntry.posMovedAt) {\n        return this._elementEntry.posMovedAt;\n      }\n      return this._elementEntry.elem.getCreatedAt();\n    }\n    return this._createdAt;\n  }\n\n  /**\n   * `release` releases prev and next node.\n   */\n  public release(): void {\n    if (this.prev) {\n      this.prev.next = this.next;\n    }\n    if (this.next) {\n      this.next.prev = this.prev;\n    }\n    this.prev = undefined;\n    this.next = undefined;\n  }\n\n  /**\n   * `toString` returns a string representation of this node's value, used by\n   * TreeList for debugging.\n   */\n  public toString(): string {\n    if (!this._elementEntry) {\n      return '';\n    }\n    return this._elementEntry.elem.toJSON();\n  }\n\n  /**\n   * `getPrev` returns a previous node.\n   */\n  public getPrev(): RGATreeListNode | undefined {\n    return this.prev;\n  }\n\n  /**\n   * `getNext` returns a next node.\n   */\n  public getNext(): RGATreeListNode | undefined {\n    return this.next;\n  }\n\n  /**\n   * `getValue` returns the element value.\n   */\n  public getValue(): CRDTElement {\n    return this._elementEntry!.elem;\n  }\n\n  /**\n   * `getElement` returns the element or undefined if dead position.\n   */\n  public getElement(): CRDTElement | undefined {\n    return this._elementEntry?.elem;\n  }\n\n  /**\n   * `isRemoved` checks if the value was removed.\n   */\n  public isRemoved(): boolean {\n    if (!this._elementEntry) {\n      return true;\n    }\n    return this._elementEntry.elem.isRemoved();\n  }\n\n  /**\n   * `getElementEntry` returns the element entry.\n   */\n  public getElementEntry(): ElementEntry | undefined {\n    return this._elementEntry;\n  }\n\n  /**\n   * `setElementEntry` sets the element entry.\n   */\n  public setElementEntry(entry: ElementEntry | undefined): void {\n    this._elementEntry = entry;\n  }\n\n  /**\n   * `getPositionCreatedAt` returns the position node's own createdAt.\n   */\n  public getPositionCreatedAt(): TimeTicket {\n    return this._createdAt;\n  }\n\n  /**\n   * `getPositionMovedAt` returns the LWW timestamp of the element's\n   * move into this position. Undefined for insert-created positions.\n   */\n  public getPositionMovedAt(): TimeTicket | undefined {\n    if (!this._elementEntry) {\n      return undefined;\n    }\n    return this._elementEntry.posMovedAt;\n  }\n\n  /**\n   * `getRemovedAt` returns the time this dead position node was\n   * removed (for GC).\n   */\n  public getRemovedAt(): TimeTicket | undefined {\n    return this._removedAt;\n  }\n\n  /**\n   * `setRemovedAt` sets the removal time of this position node.\n   */\n  public setRemovedAt(removedAt: TimeTicket): void {\n    this._removedAt = removedAt;\n  }\n\n  /**\n   * `toIDString` returns a unique identifier for this position node\n   * (for GC).\n   */\n  public toIDString(): string {\n    return this._createdAt.toIDString();\n  }\n\n  /**\n   * `getDataSize` returns the data size of this position node\n   * (for GC).\n   */\n  public getDataSize(): DataSize {\n    let meta = TimeTicketSize;\n    if (this._removedAt) {\n      meta += TimeTicketSize;\n    }\n    return { data: 0, meta };\n  }\n}\n\n/**\n * `RGATreeList` is a replicated growable array with LWW position\n * register semantics for moves.\n */\nexport class RGATreeList implements GCParent {\n  private dummyHead: RGATreeListNode;\n  private last: RGATreeListNode;\n  private nodeMapByIndex: TreeList<RGATreeListNode>;\n  private nodeMapByCreatedAt: Map<string, RGATreeListNode>;\n  private elementMapByCreatedAt: Map<string, ElementEntry>;\n\n  constructor() {\n    const dummyValue = Primitive.of(0, InitialTimeTicket);\n    dummyValue.setRemovedAt(InitialTimeTicket);\n    this.dummyHead = RGATreeListNode.createWithElement(dummyValue);\n    this.last = this.dummyHead;\n    this.nodeMapByIndex = new TreeList<RGATreeListNode>(\n      this.dummyHead.indexNode,\n    );\n    this.nodeMapByCreatedAt = new Map();\n    this.elementMapByCreatedAt = new Map();\n\n    this.nodeMapByCreatedAt.set(\n      this.dummyHead.getCreatedAt().toIDString(),\n      this.dummyHead,\n    );\n  }\n\n  /**\n   * `create` creates instance of RGATreeList.\n   */\n  public static create(): RGATreeList {\n    return new RGATreeList();\n  }\n\n  /**\n   * `length` returns size of RGATreeList.\n   */\n  public get length(): number {\n    return this.nodeMapByIndex.length;\n  }\n\n  /**\n   * `findNextBeforeExecutedAt` walks forward from the given node,\n   * skipping nodes positioned after executedAt (RGA insertion rule).\n   */\n  private findNextBeforeExecutedAt(\n    node: RGATreeListNode,\n    executedAt: TimeTicket,\n  ): RGATreeListNode {\n    while (\n      node.getNext() &&\n      node.getNext()!.getPositionedAt().after(executedAt)\n    ) {\n      node = node.getNext()!;\n    }\n    return node;\n  }\n\n  private release(node: RGATreeListNode): void {\n    if (this.last === node) {\n      this.last = node.getPrev()!;\n    }\n\n    node.release();\n    this.nodeMapByIndex.delete(node.indexNode);\n    this.nodeMapByCreatedAt.delete(node.getPositionCreatedAt().toIDString());\n  }\n\n  /**\n   * `insertAfter` adds a new node with the value after the given\n   * position. prevCreatedAt is a position node identity. Looks up\n   * nodeMapByCreatedAt first, then elementMapByCreatedAt for backward\n   * compatibility.\n   */\n  public insertAfter(\n    prevCreatedAt: TimeTicket,\n    value: CRDTElement,\n    executedAt: TimeTicket = value.getCreatedAt(),\n  ): RGATreeListNode {\n    let startNode = this.nodeMapByCreatedAt.get(prevCreatedAt.toIDString());\n    if (!startNode) {\n      const entry = this.elementMapByCreatedAt.get(prevCreatedAt.toIDString());\n      if (entry) {\n        startNode = entry.positionNode;\n      }\n    }\n    if (!startNode) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `cant find the given node: ${prevCreatedAt.toIDString()}`,\n      );\n    }\n\n    const prevNode = this.findNextBeforeExecutedAt(startNode, executedAt);\n    const newNode = RGATreeListNode.createAfter(prevNode, value);\n    if (prevNode === this.last) {\n      this.last = newNode;\n    }\n\n    this.nodeMapByIndex.insertAfter(prevNode.indexNode, newNode.indexNode);\n    this.nodeMapByCreatedAt.set(value.getCreatedAt().toIDString(), newNode);\n    this.elementMapByCreatedAt.set(\n      value.getCreatedAt().toIDString(),\n      newNode.getElementEntry()!,\n    );\n    return newNode;\n  }\n\n  /**\n   * `insertPositionAfter` creates a bare position node after\n   * resolving position via forward skip (RGA insertion rule).\n   * Used by moveAfter. prevCreatedAt is a POSITION node identity.\n   */\n  private insertPositionAfter(\n    prevCreatedAt: TimeTicket,\n    executedAt: TimeTicket,\n  ): RGATreeListNode {\n    const startNode = this.nodeMapByCreatedAt.get(prevCreatedAt.toIDString());\n    if (!startNode) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `cant find the given node: ${prevCreatedAt.toIDString()}`,\n      );\n    }\n\n    const prevNode = this.findNextBeforeExecutedAt(startNode, executedAt);\n\n    const newNode = RGATreeListNode.createBarePosition(executedAt);\n    RGATreeListNode.insertNodeAfter(prevNode, newNode);\n    if (prevNode === this.last) {\n      this.last = newNode;\n    }\n\n    this.nodeMapByIndex.insertAfter(prevNode.indexNode, newNode.indexNode);\n    this.nodeMapByCreatedAt.set(executedAt.toIDString(), newNode);\n    return newNode;\n  }\n\n  /**\n   * `moveAfter` moves the given `createdAt` element after the\n   * `prevCreatedAt` element using LWW position register semantics.\n   * Returns the dead position node (if any) for GC registration, and the size\n   * the move added to the element itself.\n   */\n  public moveAfter(\n    prevCreatedAt: TimeTicket,\n    createdAt: TimeTicket,\n    executedAt: TimeTicket,\n  ): RGATreeListMove {\n    if (!this.nodeMapByCreatedAt.has(prevCreatedAt.toIDString())) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `cant find the given node: ${prevCreatedAt.toIDString()}`,\n      );\n    }\n\n    const entry = this.elementMapByCreatedAt.get(createdAt.toIDString());\n    if (!entry) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `cant find the given node: ${createdAt.toIDString()}`,\n      );\n    }\n\n    // LWW check: if a newer move already won, this move is\n    // discarded. But we still create the position node so that\n    // operations referencing this move's position can find it.\n    if (entry.posMovedAt && !executedAt.after(entry.posMovedAt)) {\n      if (this.nodeMapByCreatedAt.has(executedAt.toIDString())) {\n        return { movedDiff: { data: 0, meta: 0 } };\n      }\n\n      const deadPosNode = this.insertPositionAfter(prevCreatedAt, executedAt);\n      deadPosNode.setRemovedAt(executedAt);\n      this.nodeMapByIndex.updateWeight(deadPosNode.indexNode);\n      return { deadNode: deadPosNode, movedDiff: { data: 0, meta: 0 } };\n    }\n\n    // `setMovedAt` below makes `getMetaUsage` count one more ticket, but only\n    // the first time: a re-move overwrites a ticket already charged, and\n    // charging it again would walk `docSize` up without bound on a list the\n    // user reorders repeatedly.\n    const firstStamp = entry.elem.getMovedAt() === undefined;\n\n    // Create a new position node after the target position.\n    const newPosNode = this.insertPositionAfter(prevCreatedAt, executedAt);\n\n    // Mark old position as dead.\n    const oldPosNode = entry.positionNode;\n    oldPosNode.setElementEntry(undefined);\n    oldPosNode.setRemovedAt(executedAt);\n    this.nodeMapByIndex.updateWeight(oldPosNode.indexNode);\n\n    // Attach element to new position.\n    newPosNode.setElementEntry(entry);\n    entry.positionNode = newPosNode;\n    entry.posMovedAt = executedAt;\n    entry.elem.setMovedAt(executedAt);\n\n    this.nodeMapByIndex.updateWeight(newPosNode.indexNode);\n\n    return {\n      deadNode: oldPosNode,\n      movedDiff: {\n        data: 0,\n        meta: firstStamp ? TimeTicketSize : 0,\n      },\n    };\n  }\n\n  /**\n   * `insert` adds the given element after the last node.\n   *\n   * The anchor must be the last node's POSITION identity\n   * (`getLastCreatedAt`), not its element identity (`last.getCreatedAt`).\n   * When the last element was moved here, the two differ: `insertAfter`\n   * resolves `nodeMapByCreatedAt` first, where the element's createdAt still\n   * keys its now-dead original position node (dead positions are retained as\n   * stable anchors). Anchoring on element identity would therefore append\n   * after that stale dead slot instead of the tail, and since each appended\n   * element carries the newest ticket the RGA forward-skip never advances —\n   * so every append lands immediately after the same anchor, reversing the\n   * appended run (yorkie#1948). `fromArray` is the only caller, so this was\n   * seen solely via snapshot restore.\n   */\n  public insert(value: CRDTElement): void {\n    this.insertAfter(this.getLastCreatedAt(), value);\n  }\n\n  /**\n   * `getByID` returns the node of the given creation time.\n   * Checks elementMapByCreatedAt first (for moved elements whose\n   * position node createdAt differs), then nodeMapByCreatedAt.\n   */\n  public getByID(createdAt: TimeTicket): RGATreeListNode | undefined {\n    const entry = this.elementMapByCreatedAt.get(createdAt.toIDString());\n    if (entry) {\n      return entry.positionNode;\n    }\n    return this.nodeMapByCreatedAt.get(createdAt.toIDString());\n  }\n\n  /**\n   * `subPathOf` returns the sub path of the given element.\n   */\n  public subPathOf(createdAt: TimeTicket): string | undefined {\n    const entry = this.elementMapByCreatedAt.get(createdAt.toIDString());\n    if (!entry) {\n      // Fall back to nodeMapByCreatedAt for position node lookup.\n      const node = this.nodeMapByCreatedAt.get(createdAt.toIDString());\n      if (!node) {\n        return;\n      }\n      return String(this.nodeMapByIndex.indexOf(node.indexNode));\n    }\n    return String(this.nodeMapByIndex.indexOf(entry.positionNode.indexNode));\n  }\n\n  /**\n   * `purgeBarrierAt` implements `GCParent.purgeBarrierAt`: the ticket that must be covered\n   * before the given child may be unlinked is the one\n   * `findNextBeforeExecutedAt` would read in its place. It handles the same\n   * two kinds of child `purge` does: a dead position node a move left behind,\n   * and a removed element, reached through the position node holding it.\n   */\n  public purgeBarrierAt(child: GCChild | CRDTElement): TimeTicket | undefined {\n    if (child instanceof RGATreeListNode) {\n      return successorBarrierAt(child);\n    }\n\n    const element = child as CRDTElement;\n    const entry = this.elementMapByCreatedAt.get(\n      element.getCreatedAt().toIDString(),\n    );\n    // Same identity guard as `purge`: an entry now holding a different\n    // element is not this element's position, and `purge` declines anyway.\n    if (!entry || entry.elem !== element) {\n      return;\n    }\n    return successorBarrierAt(entry.positionNode);\n  }\n\n  /**\n   * `purge` physically purges the given child. Handles both dead\n   * position nodes (GCChild from GCParent path) and CRDTElements\n   * (from CRDTContainer path).\n   */\n  public purge(child: GCChild | CRDTElement): void {\n    if (child instanceof RGATreeListNode) {\n      // GC of a dead position node.\n      this.release(child);\n      return;\n    }\n\n    // GC of an element.\n    const element = child as CRDTElement;\n    const entry = this.elementMapByCreatedAt.get(\n      element.getCreatedAt().toIDString(),\n    );\n    if (!entry) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `fail to find the given createdAt: ${element\n          .getCreatedAt()\n          .toIDString()}`,\n      );\n    }\n\n    // Same guard as `ElementRHT.purge`: releasing the position node of an entry\n    // that now holds a different element would unlink a live one on a\n    // tombstone's behalf. A genuinely missing entry still throws above.\n    if (entry.elem !== element) {\n      return;\n    }\n\n    const node = entry.positionNode;\n    this.elementMapByCreatedAt.delete(element.getCreatedAt().toIDString());\n    this.release(node);\n  }\n\n  /**\n   * `getByIndex` returns node of the given index.\n   */\n  public getByIndex(idx: number): RGATreeListNode | undefined {\n    if (idx >= this.length) {\n      return;\n    }\n\n    return this.nodeMapByIndex.find(idx).getValue();\n  }\n\n  /**\n   * `findPrevCreatedAt` returns the position node's createdAt of the\n   * previous element. This returns a position identity suitable for\n   * use as prevCreatedAt in moveAfter.\n   */\n  public findPrevCreatedAt(createdAt: TimeTicket): TimeTicket {\n    const entry = this.elementMapByCreatedAt.get(createdAt.toIDString());\n    if (!entry) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `cant find the given node: ${createdAt.toIDString()}`,\n      );\n    }\n\n    let node: RGATreeListNode = entry.positionNode;\n    do {\n      node = node.getPrev()!;\n      // Skip dead position nodes (no element).\n      if (!node.getElementEntry()) {\n        continue;\n      }\n      if (this.dummyHead === node || !node.isRemoved()) {\n        break;\n      }\n    } while (node);\n\n    // Return position node's createdAt (stable identity).\n    return node.getPositionCreatedAt();\n  }\n\n  /**\n   * `getPrevCreatedAt` returns the position node's createdAt of the\n   * previous element. Delegates to findPrevCreatedAt.\n   */\n  public getPrevCreatedAt(createdAt: TimeTicket): TimeTicket {\n    return this.findPrevCreatedAt(createdAt);\n  }\n\n  /**\n   * `delete` deletes the node of the given creation time.\n   */\n  public delete(createdAt: TimeTicket, editedAt: TimeTicket): CRDTElement {\n    const entry = this.elementMapByCreatedAt.get(createdAt.toIDString());\n    if (!entry) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `cant find the given node: ${createdAt.toIDString()}`,\n      );\n    }\n\n    const node = entry.positionNode;\n    const alreadyRemoved = node.isRemoved();\n    if (entry.elem.remove(editedAt) && !alreadyRemoved) {\n      this.nodeMapByIndex.updateWeight(node.indexNode);\n    }\n    return entry.elem;\n  }\n\n  /**\n   * `set` sets the given element at the given creation time.\n   */\n  public set(\n    createdAt: TimeTicket,\n    element: CRDTElement,\n    executedAt: TimeTicket,\n  ): CRDTElement {\n    if (!this.elementMapByCreatedAt.has(createdAt.toIDString())) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `cant find the given node: ${createdAt.toIDString()}`,\n      );\n    }\n\n    this.insertAfter(createdAt, element, executedAt);\n    return this.delete(createdAt, executedAt);\n  }\n\n  /**\n   * `deleteByIndex` deletes the node of the given index.\n   */\n  public deleteByIndex(\n    index: number,\n    editedAt: TimeTicket,\n  ): CRDTElement | undefined {\n    const node = this.getByIndex(index);\n    if (!node) {\n      return;\n    }\n\n    if (node.remove(editedAt)) {\n      this.nodeMapByIndex.updateWeight(node.indexNode);\n    }\n    return node.getValue();\n  }\n\n  /**\n   * `getHead` returns the value of head elements.\n   */\n  public getHead(): CRDTElement {\n    return this.dummyHead.getValue();\n  }\n\n  /**\n   * `getLast` returns the value of last elements. Skips bare position nodes\n   * (created by moveAfter/addDeadPosition) that have no element.\n   */\n  public getLast(): CRDTElement {\n    let node: RGATreeListNode = this.last;\n    while (!node.getElementEntry() && node !== this.dummyHead) {\n      node = node.getPrev()!;\n    }\n    return node.getValue();\n  }\n\n  /**\n   * `getLastCreatedAt` returns the position node's createdAt of the\n   * last node in the linked list. This is a position identity\n   * suitable for use as prevCreatedAt.\n   */\n  public getLastCreatedAt(): TimeTicket {\n    return this.last.getPositionCreatedAt();\n  }\n\n  /**\n   * `posCreatedAt` returns the createdAt of the position node\n   * currently holding the element. Used to convert element identity\n   * to position identity.\n   */\n  public posCreatedAt(elemCreatedAt: TimeTicket): TimeTicket {\n    const entry = this.elementMapByCreatedAt.get(elemCreatedAt.toIDString());\n    if (!entry) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `cant find the given node: ${elemCreatedAt.toIDString()}`,\n      );\n    }\n    return entry.positionNode.getPositionCreatedAt();\n  }\n\n  /**\n   * `addDeadPosition` appends a dead position node during snapshot\n   * restoration.\n   */\n  public addDeadPosition(\n    posCreatedAt: TimeTicket,\n    removedAt: TimeTicket,\n  ): void {\n    const node = RGATreeListNode.createBarePosition(posCreatedAt);\n    node.setRemovedAt(removedAt);\n    const prevNode = this.last;\n    RGATreeListNode.insertNodeAfter(prevNode, node);\n    this.last = node;\n    this.nodeMapByIndex.insertAfter(prevNode.indexNode, node.indexNode);\n    this.nodeMapByCreatedAt.set(posCreatedAt.toIDString(), node);\n  }\n\n  /**\n   * `addMovedElement` appends an element with explicit position\n   * identity during snapshot restoration.\n   */\n  public addMovedElement(\n    elem: CRDTElement,\n    posCreatedAt: TimeTicket,\n    posMovedAt: TimeTicket,\n  ): void {\n    const entry = new ElementEntry(elem);\n    entry.posMovedAt = posMovedAt;\n\n    const node = RGATreeListNode.createBarePosition(posCreatedAt);\n    node.setElementEntry(entry);\n    entry.positionNode = node;\n\n    const prevNode = this.last;\n    RGATreeListNode.insertNodeAfter(prevNode, node);\n    this.last = node;\n\n    this.nodeMapByIndex.insertAfter(prevNode.indexNode, node.indexNode);\n    this.nodeMapByCreatedAt.set(posCreatedAt.toIDString(), node);\n    this.elementMapByCreatedAt.set(elem.getCreatedAt().toIDString(), entry);\n  }\n\n  /**\n   * `allNodes` returns all nodes including dead position nodes.\n   */\n  public allNodes(): Array<RGATreeListNode> {\n    const nodes: Array<RGATreeListNode> = [];\n    let current = this.dummyHead.getNext();\n    while (current) {\n      nodes.push(current);\n      current = current.getNext();\n    }\n    return nodes;\n  }\n\n  /**\n   * `toTestString` returns a String containing the meta data of the\n   * node id for debugging purpose.\n   */\n  public toTestString(): string {\n    const json = [];\n\n    for (const node of this) {\n      if (!node.getElementEntry()) {\n        continue;\n      }\n      const elem = `${node.getCreatedAt().toIDString()}:${node\n        .getValue()\n        .toJSON()}`;\n      if (node.isRemoved()) {\n        json.push(`{${elem}}`);\n      } else {\n        json.push(`[${elem}]`);\n      }\n    }\n\n    return json.join('');\n  }\n\n  // eslint-disable-next-line jsdoc/require-jsdoc\n  public *[Symbol.iterator](): IterableIterator<RGATreeListNode> {\n    let node = this.dummyHead.getNext();\n    while (node) {\n      yield node;\n      node = node.getNext();\n    }\n  }\n}\n\n/**\n * `successorBarrierAt` returns the positioning ticket of the node that would\n * take over as `findNextBeforeExecutedAt`'s stopping point once the given node\n * is unlinked. Undefined at the tail: with nothing behind it, unlinking cannot\n * send an insert past anything.\n */\nfunction successorBarrierAt(node: RGATreeListNode): TimeTicket | undefined {\n  return node.getNext()?.getPositionedAt();\n}\n","/*\n * Copyright 2020 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TimeTicket } from '@yorkie-js/sdk/src/document/time/ticket';\nimport {\n  CRDTContainer,\n  CRDTElement,\n} from '@yorkie-js/sdk/src/document/crdt/element';\nimport {\n  RGATreeList,\n  RGATreeListMove,\n  RGATreeListNode,\n} from '@yorkie-js/sdk/src/document/crdt/rga_tree_list';\nimport * as Devtools from '@yorkie-js/sdk/src/devtools/types';\nimport { DataSize } from '@yorkie-js/sdk/src/util/resource';\n\n/**\n * `CRDTArray` represents an array data type containing `CRDTElement`s.\n */\nexport class CRDTArray extends CRDTContainer {\n  private elements: RGATreeList;\n\n  constructor(createdAt: TimeTicket, elements: RGATreeList) {\n    super(createdAt);\n    this.elements = elements;\n  }\n\n  /**\n   * `create` creates a new instance of Array.\n   */\n  public static create(\n    createdAt: TimeTicket,\n    value?: Array<CRDTElement>,\n  ): CRDTArray {\n    if (!value) {\n      return new CRDTArray(createdAt, RGATreeList.create());\n    }\n\n    const elements = RGATreeList.create();\n    for (const v of value) {\n      elements.insertAfter(elements.getLastCreatedAt(), v.deepcopy());\n    }\n    return new CRDTArray(createdAt, elements);\n  }\n\n  /**\n   * `subPathOf` returns the sub path of the given element.\n   */\n  public subPathOf(createdAt: TimeTicket): string | undefined {\n    return this.elements.subPathOf(createdAt);\n  }\n\n  /**\n   * `purgeBarrierAt` implements `CRDTContainer.purgeBarrierAt`: purging an element unlinks the\n   * position node holding it, so the array's order decides when that is safe.\n   */\n  public purgeBarrierAt(element: CRDTElement): TimeTicket | undefined {\n    return this.elements.purgeBarrierAt(element);\n  }\n\n  /**\n   * `purge` physically purge the given element.\n   */\n  public purge(element: CRDTElement): void {\n    this.elements.purge(element);\n  }\n\n  /**\n   * `insertAfter` adds a new node after the the given node.\n   */\n  public insertAfter(\n    prevCreatedAt: TimeTicket,\n    value: CRDTElement,\n    executedAt?: TimeTicket,\n  ): void {\n    this.elements.insertAfter(prevCreatedAt, value, executedAt);\n  }\n\n  /**\n   * `moveAfter` moves the given `createdAt` element after the\n   * `prevCreatedAt`. Returns the dead position node for GC and the size the\n   * move added to the moved element.\n   */\n  public moveAfter(\n    prevCreatedAt: TimeTicket,\n    createdAt: TimeTicket,\n    executedAt: TimeTicket,\n  ): RGATreeListMove {\n    return this.elements.moveAfter(prevCreatedAt, createdAt, executedAt);\n  }\n\n  /**\n   * `get` returns the element of the given index.\n   */\n  public get(index: number): CRDTElement | undefined {\n    const node = this.elements.getByIndex(index);\n    return node?.getValue();\n  }\n\n  /**\n   * `getByID` returns the element of the given createAt.\n   */\n  public getByID(createdAt: TimeTicket): CRDTElement | undefined {\n    const node = this.elements.getByID(createdAt);\n    return node?.getValue();\n  }\n\n  /**\n   * `getHead` returns dummy head element.\n   */\n  public getHead(): CRDTElement {\n    return this.elements.getHead();\n  }\n\n  /**\n   * `getLast` returns last element.\n   */\n  public getLast(): CRDTElement {\n    return this.elements.getLast();\n  }\n\n  /**\n   * `getPrevCreatedAt` returns the creation time of the previous\n   * node.\n   */\n  public getPrevCreatedAt(createdAt: TimeTicket): TimeTicket {\n    return this.elements.getPrevCreatedAt(createdAt);\n  }\n\n  /**\n   * `posCreatedAt` returns the createdAt of the position node\n   * currently holding the element. Used to convert element identity\n   * to position identity for moves.\n   */\n  public posCreatedAt(elemCreatedAt: TimeTicket): TimeTicket {\n    return this.elements.posCreatedAt(elemCreatedAt);\n  }\n\n  /**\n   * `delete` deletes the element of the given creation time.\n   */\n  public delete(createdAt: TimeTicket, editedAt: TimeTicket): CRDTElement {\n    return this.elements.delete(createdAt, editedAt);\n  }\n\n  /**\n   * `deleteByIndex` deletes the element of given index and editedAt.\n   */\n  public deleteByIndex(\n    index: number,\n    editedAt: TimeTicket,\n  ): CRDTElement | undefined {\n    return this.elements.deleteByIndex(index, editedAt);\n  }\n\n  /**\n   * `set` sets the given element at the given position of the\n   * creation time.\n   */\n  public set(\n    createdAt: TimeTicket,\n    value: CRDTElement,\n    executedAt: TimeTicket,\n  ): CRDTElement {\n    return this.elements.set(createdAt, value, executedAt);\n  }\n\n  /**\n   * `getLastCreatedAt` get last created element.\n   */\n  public getLastCreatedAt(): TimeTicket {\n    return this.elements.getLastCreatedAt();\n  }\n\n  /**\n   * `length` returns length of this elements.\n   */\n  public get length(): number {\n    return this.elements.length;\n  }\n\n  /**\n   * `[Symbol.iterator]` returns an iterator for the elements in\n   * this array.\n   */\n  public *[Symbol.iterator](): IterableIterator<CRDTElement> {\n    for (const node of this.elements) {\n      if (node.isRemoved()) {\n        continue;\n      }\n      yield node.getValue();\n    }\n  }\n\n  /**\n   * `toTestString` returns a String containing the meta data of\n   * this value for debugging purpose.\n   */\n  public toTestString(): string {\n    return this.elements.toTestString();\n  }\n\n  /**\n   * `getDescendants` traverse the descendants of this array.\n   */\n  public getDescendants(\n    callback: (elem: CRDTElement, parent: CRDTContainer) => boolean,\n  ): void {\n    for (const node of this.elements) {\n      if (!node.getElementEntry()) {\n        continue;\n      }\n      const element = node.getValue();\n      if (callback(element, this)) {\n        return;\n      }\n\n      if (element instanceof CRDTContainer) {\n        element.getDescendants(callback);\n      }\n    }\n  }\n\n  /**\n   * `getDataSize` returns the data usage of this element.\n   */\n  public getDataSize(): DataSize {\n    return {\n      data: 0,\n      meta: this.getMetaUsage(),\n    };\n  }\n\n  /**\n   * `toJSON` returns the JSON encoding of this array.\n   */\n  public toJSON(): string {\n    const json = [];\n    for (const value of this) {\n      json.push(value.toJSON());\n    }\n    return `[${json.join(',')}]`;\n  }\n\n  /**\n   * `toJS` return the javascript object of this array.\n   */\n  public toJS(): any {\n    return JSON.parse(this.toJSON());\n  }\n\n  /**\n   * `toJSForTest` returns value with meta data for testing.\n   */\n  public toJSForTest(): Devtools.JSONElement {\n    const values: Devtools.ContainerValue = {};\n    for (let i = 0; i < this.length; i++) {\n      const { createdAt, value, type } = this.get(i)!.toJSForTest();\n      values[i] = {\n        key: String(i),\n        createdAt,\n        value,\n        type,\n      };\n    }\n    return {\n      createdAt: this.getCreatedAt().toTestString(),\n      value: values,\n      type: 'YORKIE_ARRAY',\n    };\n  }\n\n  /**\n   * `toSortedJSON` returns the sorted JSON encoding of this array.\n   */\n  public toSortedJSON(): string {\n    return this.toJSON();\n  }\n\n  /**\n   * `getElements` returns the underlying RGATreeList.\n   */\n  public getElements(): RGATreeList {\n    return this.elements;\n  }\n\n  /**\n   * `getRGATreeList` returns the underlying RGATreeList (GCParent\n   * for dead positions).\n   */\n  public getRGATreeList(): RGATreeList {\n    return this.elements;\n  }\n\n  /**\n   * `getAllRGANodes` returns all RGA nodes including dead position\n   * nodes.\n   */\n  public getAllRGANodes(): Array<RGATreeListNode> {\n    return this.elements.allNodes();\n  }\n\n  /**\n   * `deepcopy` copies itself deeply.\n   */\n  public deepcopy(): CRDTArray {\n    const clone = CRDTArray.create(this.getCreatedAt());\n    for (const node of this.elements) {\n      if (!node.getElementEntry()) {\n        // Dead position node (abandoned by a move).\n        const removedAt = node.getRemovedAt();\n        if (removedAt) {\n          clone.elements.addDeadPosition(\n            node.getPositionCreatedAt(),\n            removedAt,\n          );\n        }\n        continue;\n      }\n\n      const value = node.getValue().deepcopy();\n      const posMovedAt = node.getPositionMovedAt();\n      if (posMovedAt) {\n        clone.elements.addMovedElement(\n          value,\n          node.getPositionCreatedAt(),\n          posMovedAt,\n        );\n      } else {\n        clone.elements.insertAfter(clone.getLastCreatedAt(), value);\n      }\n    }\n    clone.setRemovedAt(this.getRemovedAt());\n    clone.setMovedAt(this.getMovedAt());\n    return clone;\n  }\n}\n","/*\n * Copyright 2020 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TimeTicket } from '@yorkie-js/sdk/src/document/time/ticket';\nimport { CRDTElement } from '@yorkie-js/sdk/src/document/crdt/element';\nimport { CRDTRoot } from '@yorkie-js/sdk/src/document/crdt/root';\nimport { CRDTArray } from '@yorkie-js/sdk/src/document/crdt/array';\nimport {\n  Operation,\n  ExecutionResult,\n} from '@yorkie-js/sdk/src/document/operation/operation';\nimport { RemoveOperation } from '@yorkie-js/sdk/src/document/operation/remove_operation';\nimport { Code, YorkieError } from '@yorkie-js/sdk/src/util/error';\n\n/**\n * `AddOperation` is an operation representing adding an element to an Array.\n */\nexport class AddOperation extends Operation {\n  private prevCreatedAt: TimeTicket;\n  private value: CRDTElement;\n\n  constructor(\n    parentCreatedAt: TimeTicket,\n    prevCreatedAt: TimeTicket,\n    value: CRDTElement,\n    executedAt?: TimeTicket,\n  ) {\n    super(parentCreatedAt, executedAt);\n    this.prevCreatedAt = prevCreatedAt;\n    this.value = value;\n  }\n\n  /**\n   * `create` creates a new instance of AddOperation.\n   */\n  public static create(\n    parentCreatedAt: TimeTicket,\n    prevCreatedAt: TimeTicket,\n    value: CRDTElement,\n    executedAt?: TimeTicket,\n  ): AddOperation {\n    return new AddOperation(parentCreatedAt, prevCreatedAt, value, executedAt);\n  }\n\n  /**\n   * `execute` executes this operation on the given `CRDTRoot`.\n   */\n  public execute(root: CRDTRoot): ExecutionResult {\n    const parentObject = root.findByCreatedAt(this.getParentCreatedAt());\n    if (!parentObject) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `fail to find ${this.getParentCreatedAt()}`,\n      );\n    }\n    if (!(parentObject instanceof CRDTArray)) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `fail to execute, only array can execute add`,\n      );\n    }\n    const array = parentObject as CRDTArray;\n    const value = this.value.deepcopy();\n    array.insertAfter(this.prevCreatedAt, value, this.getExecutedAt());\n    root.registerElement(value, array);\n\n    return {\n      opInfos: [\n        {\n          type: 'add',\n          path: root.createPath(this.getParentCreatedAt()),\n          index: Number(array.subPathOf(this.getEffectedCreatedAt())),\n        },\n      ],\n      reverseOp: this.toReverseOperation(),\n    };\n  }\n\n  private toReverseOperation(): Operation {\n    // NOTE(KMSstudio): executedAt is assigned just before execution, when Document.undo() is called.\n    const reverseOp = RemoveOperation.create(\n      this.getParentCreatedAt(),\n      this.value.getCreatedAt(),\n    );\n\n    return reverseOp;\n  }\n\n  /**\n   * `getEffectedCreatedAt` returns the creation time of the effected element.\n   */\n  public getEffectedCreatedAt(): TimeTicket {\n    return this.value.getCreatedAt();\n  }\n\n  /**\n   * `toTestString` returns a string containing the meta data.\n   */\n  public toTestString(): string {\n    return `${this.getParentCreatedAt().toTestString()}.ADD.${this.value.toJSON()}`;\n  }\n\n  /**\n   * `getPrevCreatedAt` returns the creation time of previous element.\n   */\n  public getPrevCreatedAt(): TimeTicket {\n    return this.prevCreatedAt;\n  }\n\n  /**\n   * `getValue` returns the value of this operation.\n   */\n  public getValue(): CRDTElement {\n    return this.value;\n  }\n\n  /**\n   * `setPrevCreatedAt` sets the creation time of the previous element.\n   */\n  public setPrevCreatedAt(createdAt: TimeTicket) {\n    this.prevCreatedAt = createdAt;\n  }\n}\n","/*\n * Copyright 2020 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TimeTicket } from '@yorkie-js/sdk/src/document/time/ticket';\nimport { CRDTRoot } from '@yorkie-js/sdk/src/document/crdt/root';\nimport {\n  OpSource,\n  Operation,\n  OpInfo,\n  ExecutionResult,\n} from '@yorkie-js/sdk/src/document/operation/operation';\nimport {\n  CRDTContainer,\n  CRDTElement,\n} from '@yorkie-js/sdk/src/document/crdt/element';\nimport { CRDTObject } from '@yorkie-js/sdk/src/document/crdt/object';\nimport { CRDTArray } from '@yorkie-js/sdk/src/document/crdt/array';\nimport { SetOperation } from '@yorkie-js/sdk/src/document/operation/set_operation';\nimport { AddOperation } from '@yorkie-js/sdk/src/document/operation/add_operation';\nimport { Code, YorkieError } from '@yorkie-js/sdk/src/util/error';\n\n/**\n * `RemoveOperation` is an operation that removes an element from `CRDTContainer`.\n */\nexport class RemoveOperation extends Operation {\n  private createdAt: TimeTicket;\n\n  constructor(\n    parentCreatedAt: TimeTicket,\n    createdAt: TimeTicket,\n    executedAt?: TimeTicket,\n  ) {\n    super(parentCreatedAt, executedAt);\n    this.createdAt = createdAt;\n  }\n\n  /**\n   * `create` creates a new instance of RemoveOperation.\n   */\n  public static create(\n    parentCreatedAt: TimeTicket,\n    createdAt: TimeTicket,\n    executedAt?: TimeTicket,\n  ): RemoveOperation {\n    return new RemoveOperation(parentCreatedAt, createdAt, executedAt);\n  }\n\n  /**\n   * `execute` executes this operation on the given `CRDTRoot`.\n   */\n  public execute(\n    root: CRDTRoot,\n    source: OpSource,\n  ): ExecutionResult | undefined {\n    const container = root.findByCreatedAt(\n      this.getParentCreatedAt(),\n    ) as CRDTContainer;\n    if (!container) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `fail to find ${this.getParentCreatedAt()}`,\n      );\n    }\n    if (!(container instanceof CRDTContainer)) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `only object and array can execute remove: ${container}`,\n      );\n    }\n\n    // NOTE(chacha912): Handle cases where operation cannot be executed during undo and redo.\n    if (source === OpSource.UndoRedo) {\n      let parent: CRDTElement | undefined = container.getByID(this.createdAt);\n      while (parent) {\n        if (parent.getRemovedAt()) {\n          return;\n        }\n        parent = root.findElementPairByCreatedAt(parent.getCreatedAt())?.parent;\n      }\n    }\n    const key = container.subPathOf(this.createdAt);\n    // NOTE(KMSstudio): Both `toReverseOperation` and `container.delete` internally\n    // look up the CRDTElement using `createdAt`.\n    const reverseOp = this.toReverseOperation(container);\n\n    const elem = container.delete(this.createdAt, this.getExecutedAt());\n    root.registerRemovedElement(elem);\n\n    const opInfos: Array<OpInfo> =\n      container instanceof CRDTArray\n        ? [\n            {\n              type: 'remove',\n              path: root.createPath(this.getParentCreatedAt()),\n              index: Number(key),\n            },\n          ]\n        : [\n            {\n              type: 'remove',\n              path: root.createPath(this.getParentCreatedAt()),\n              key,\n            },\n          ];\n\n    return { opInfos, reverseOp };\n  }\n\n  /**\n   * `toReverseOperation` returns the reverse operation of this operation.\n   */\n  private toReverseOperation(\n    parentObject: CRDTContainer,\n  ): Operation | undefined {\n    if (parentObject instanceof CRDTArray) {\n      const value = parentObject.getByID(this.createdAt);\n      if (value !== undefined) {\n        const prevCreatedAt: TimeTicket = parentObject.getPrevCreatedAt(\n          this.createdAt,\n        );\n        // NOTE(KMSstudio): executedAt is assigned just before execution, when Document.undo() is called.\n        return AddOperation.create(\n          this.getParentCreatedAt(),\n          prevCreatedAt,\n          value.deepcopy(),\n        );\n      }\n    }\n    if (parentObject instanceof CRDTObject) {\n      const key = parentObject.subPathOf(this.createdAt);\n      if (key !== undefined) {\n        const value = parentObject.get(key);\n        if (value !== undefined) {\n          return SetOperation.create(\n            key,\n            value.deepcopy(),\n            this.getParentCreatedAt(),\n          );\n        }\n      }\n    }\n  }\n\n  /**\n   * `getEffectedCreatedAt` returns the creation time of the effected element.\n   */\n  public getEffectedCreatedAt(): TimeTicket {\n    return this.getParentCreatedAt();\n  }\n\n  /**\n   * `toTestString` returns a string containing the meta data.\n   */\n  public toTestString(): string {\n    return `${this.getParentCreatedAt().toTestString()}.REMOVE.${this.createdAt.toTestString()}`;\n  }\n\n  /**\n   * `getCreatedAt` returns the creation time of the target element.\n   */\n  public getCreatedAt(): TimeTicket {\n    return this.createdAt;\n  }\n\n  /**\n   * `setCreatedAt` sets the creation time of the target element.\n   */\n  public setCreatedAt(createdAt: TimeTicket) {\n    this.createdAt = createdAt;\n  }\n}\n","/*\n * Copyright 2020 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TimeTicket } from '@yorkie-js/sdk/src/document/time/ticket';\nimport { CRDTElement } from '@yorkie-js/sdk/src/document/crdt/element';\nimport { CRDTRoot } from '@yorkie-js/sdk/src/document/crdt/root';\nimport { CRDTObject } from '@yorkie-js/sdk/src/document/crdt/object';\nimport {\n  OpSource,\n  Operation,\n  ExecutionResult,\n} from '@yorkie-js/sdk/src/document/operation/operation';\nimport { RemoveOperation } from '@yorkie-js/sdk/src/document/operation/remove_operation';\nimport { Code, YorkieError } from '@yorkie-js/sdk/src/util/error';\n\n/**\n * `SetOperation` represents an operation that stores the value corresponding to the\n * given key in the Object.\n */\nexport class SetOperation extends Operation {\n  private key: string;\n  private value: CRDTElement;\n\n  constructor(\n    key: string,\n    value: CRDTElement,\n    parentCreatedAt: TimeTicket,\n    executedAt?: TimeTicket,\n  ) {\n    super(parentCreatedAt, executedAt);\n    this.key = key;\n    this.value = value;\n  }\n\n  /**\n   * `create` creates a new instance of SetOperation.\n   */\n  public static create(\n    key: string,\n    value: CRDTElement,\n    parentCreatedAt: TimeTicket,\n    executedAt?: TimeTicket,\n  ): SetOperation {\n    return new SetOperation(key, value, parentCreatedAt, executedAt);\n  }\n\n  /**\n   * `execute` executes this operation on the given `CRDTRoot`.\n   */\n  public execute(\n    root: CRDTRoot,\n    source: OpSource,\n  ): ExecutionResult | undefined {\n    const obj = root.findByCreatedAt(this.getParentCreatedAt()) as CRDTObject;\n    if (!obj) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `fail to find ${this.getParentCreatedAt()}`,\n      );\n    }\n    if (!(obj instanceof CRDTObject)) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `fail to execute, only object can execute set`,\n      );\n    }\n\n    // NOTE(chacha912): Handle cases where operation cannot be executed during undo and redo.\n    if (source === OpSource.UndoRedo) {\n      let parent: CRDTElement | undefined = obj;\n      while (parent) {\n        if (parent.getRemovedAt()) {\n          return;\n        }\n        parent = root.findElementPairByCreatedAt(parent.getCreatedAt())?.parent;\n      }\n    }\n    const previousValue = obj.get(this.key);\n    const reverseOp = this.toReverseOperation(previousValue);\n\n    const value = this.value.deepcopy();\n    const removed = obj.set(this.key, value, this.getExecutedAt());\n    // NOTE(chacha912): When resetting elements with the pre-existing createdAt\n    // during undo/redo, it's essential to handle previously tombstoned elements.\n    // In non-GC languages, there may be a need to execute both deregister and purge.\n    //\n    // NOTE(hackerwins): A set can restore an element under a createdAt that a\n    // tombstone already answers to -- undoing a remove re-inserts the removed\n    // element under its original identity, and `obj.set` above has just handed\n    // that identity to the restored copy in the object's `nodeMapByCreatedAt`.\n    //\n    // The entry that has to follow is the one in `gcElementSetByCreatedAt`.\n    // Collection resolves it through the index that was just re-pointed, so\n    // leaving it makes the next pass reach live data.\n    //\n    // Retiring that entry is the whole job, so retire only that entry. The\n    // tombstone's other registrations are deliberately left alone: its\n    // descendant set can be a strict superset of the restored copy's, since a\n    // peer may have added a child into the container after the undoing replica\n    // took its copy, and tearing the subtree out of\n    // `elementPairMapByCreatedAt` would take those extra descendants with it,\n    // with nothing to put them back -- so a later change addressed at one of\n    // them throws inside `applyChangePack`. See\n    // `CRDTRoot.unregisterRemovedElementPair`.\n    //\n    // This is a condition on the state of the tree, not on who is applying:\n    // peers apply the undo with `OpSource.Remote`, and the Go server replays\n    // it to build a snapshot, and every one of them has the same stale entry.\n    // Gating it on `OpSource.UndoRedo` spared only the replica that performed\n    // the undo; the Go SDK gates the same call and loses the member outright\n    // there, which is the data loss yorkie#1978 fixes alongside this.\n    //\n    // An ordinary set carries a freshly issued createdAt, so the lookup\n    // normally misses and costs one map read.\n    root.unregisterRemovedElementPair(value.getCreatedAt());\n    root.registerElement(value, obj);\n    if (removed) {\n      root.registerRemovedElement(removed);\n    }\n    // NOTE(hackerwins): A value that lost the set is marked removed by\n    // `obj.set` above, before it was registered. `registerElement` is what\n    // books it into gc, and registering it as removed a second time here would\n    // refund a ticket live is holding on the one path where `registerElement`\n    // leaves it in live.\n\n    return {\n      opInfos: [\n        {\n          type: 'set',\n          path: root.createPath(this.getParentCreatedAt()),\n          key: this.key,\n        },\n      ],\n      reverseOp,\n    };\n  }\n\n  /**\n   * `toReverseOperation` returns the reverse operation of this operation.\n   */\n  private toReverseOperation(value: CRDTElement | undefined): Operation {\n    let reverseOp: SetOperation | RemoveOperation = RemoveOperation.create(\n      this.getParentCreatedAt(),\n      this.value.getCreatedAt(),\n    );\n\n    if (value !== undefined && !value.isRemoved()) {\n      reverseOp = SetOperation.create(\n        this.key,\n        value.deepcopy(),\n        this.getParentCreatedAt(),\n      );\n    }\n    return reverseOp;\n  }\n\n  /**\n   * `getEffectedCreatedAt` returns the creation time of the effected element.\n   */\n  public getEffectedCreatedAt(): TimeTicket {\n    return this.value.getCreatedAt();\n  }\n\n  /**\n   * `toTestString` returns a string containing the meta data.\n   */\n  public toTestString(): string {\n    return `${this.getParentCreatedAt().toTestString()}.SET.${\n      this.key\n    }=${this.value.toSortedJSON()}`;\n  }\n\n  /**\n   * `getKey` returns the key of this operation.\n   */\n  public getKey(): string {\n    return this.key;\n  }\n\n  /**\n   * `getValue` returns the value of this operation.\n   */\n  public getValue(): CRDTElement {\n    return this.value;\n  }\n}\n","/*\n * Copyright 2020 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TimeTicket } from '@yorkie-js/sdk/src/document/time/ticket';\nimport { CRDTRoot } from '@yorkie-js/sdk/src/document/crdt/root';\nimport { CRDTArray } from '@yorkie-js/sdk/src/document/crdt/array';\nimport {\n  Operation,\n  ExecutionResult,\n} from '@yorkie-js/sdk/src/document/operation/operation';\nimport { Code, YorkieError } from '@yorkie-js/sdk/src/util/error';\n\n/**\n * `MoveOperation` is an operation representing moving an element to\n * an Array.\n */\nexport class MoveOperation extends Operation {\n  private prevCreatedAt: TimeTicket;\n  private createdAt: TimeTicket;\n\n  constructor(\n    parentCreatedAt: TimeTicket,\n    prevCreatedAt: TimeTicket,\n    createdAt: TimeTicket,\n    executedAt?: TimeTicket,\n  ) {\n    super(parentCreatedAt, executedAt);\n    this.prevCreatedAt = prevCreatedAt;\n    this.createdAt = createdAt;\n  }\n\n  /**\n   * `create` creates a new instance of MoveOperation.\n   */\n  public static create(\n    parentCreatedAt: TimeTicket,\n    prevCreatedAt: TimeTicket,\n    createdAt: TimeTicket,\n    executedAt?: TimeTicket,\n  ): MoveOperation {\n    return new MoveOperation(\n      parentCreatedAt,\n      prevCreatedAt,\n      createdAt,\n      executedAt,\n    );\n  }\n\n  /**\n   * `execute` executes this operation on the given `CRDTRoot`.\n   */\n  public execute(root: CRDTRoot): ExecutionResult {\n    const parentObject = root.findByCreatedAt(this.getParentCreatedAt());\n    if (!parentObject) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `fail to find ${this.getParentCreatedAt()}`,\n      );\n    }\n    if (!(parentObject instanceof CRDTArray)) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `fail to execute, only array can execute move`,\n      );\n    }\n    const array = parentObject as CRDTArray;\n    const reverseOp = this.toReverseOperation(array);\n\n    const previousIndex = Number(array.subPathOf(this.createdAt));\n    const { deadNode, movedDiff } = array.moveAfter(\n      this.prevCreatedAt,\n      this.createdAt,\n      this.getExecutedAt(),\n    );\n\n    // The `movedAt` stamp is part of the moved element's size; see\n    // `CRDTRoot.accMovedElement` for why it cannot simply go to live.\n    root.accMovedElement(root.findByCreatedAt(this.createdAt)!, movedDiff);\n\n    if (deadNode) {\n      // See `json/array.ts`: a dead position node was never in live.\n      root.registerGCPair({\n        parent: array.getRGATreeList(),\n        child: deadNode,\n        gcOnlySize: deadNode.getDataSize(),\n      });\n    }\n\n    const index = Number(array.subPathOf(this.createdAt));\n    return {\n      opInfos: [\n        {\n          type: 'move',\n          path: root.createPath(this.getParentCreatedAt()),\n          index,\n          previousIndex,\n        },\n      ],\n      reverseOp,\n    };\n  }\n\n  private toReverseOperation(array: CRDTArray): Operation {\n    const preservePrevCreatedAt = array.getPrevCreatedAt(this.createdAt);\n    // NOTE(KMSstudio): executedAt is assigned just before execution,\n    // when Document.undo() is called.\n    return MoveOperation.create(\n      this.getParentCreatedAt(),\n      preservePrevCreatedAt,\n      this.createdAt,\n    );\n  }\n\n  /**\n   * `getEffectedCreatedAt` returns the creation time of the\n   * effected element.\n   */\n  public getEffectedCreatedAt(): TimeTicket {\n    return this.createdAt;\n  }\n\n  /**\n   * `toTestString` returns a string containing the meta data.\n   */\n  public toTestString(): string {\n    return `${this.getParentCreatedAt().toTestString()}.MOVE`;\n  }\n\n  /**\n   * `getPrevCreatedAt` returns the creation time of previous\n   * element.\n   */\n  public getPrevCreatedAt(): TimeTicket {\n    return this.prevCreatedAt;\n  }\n\n  /**\n   * `getCreatedAt` returns the creation time of the target element.\n   */\n  public getCreatedAt(): TimeTicket {\n    return this.createdAt;\n  }\n\n  /**\n   * `setPrevCreatedAt` sets the creation time of the previous\n   * element.\n   */\n  public setPrevCreatedAt(createdAt: TimeTicket) {\n    this.prevCreatedAt = createdAt;\n  }\n\n  /**\n   * `setCreatedAt` sets the creation time of the target element.\n   */\n  public setCreatedAt(createdAt: TimeTicket) {\n    this.createdAt = createdAt;\n  }\n}\n","/*\n * Copyright 2020 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, YorkieError } from './error';\n\n/**\n * `SplayNode` is a node of SplayTree.\n */\nexport abstract class SplayNode<V> {\n  protected value: V;\n\n  private left?: SplayNode<V>;\n  private right?: SplayNode<V>;\n  private parent?: SplayNode<V>;\n  private weight!: number;\n\n  constructor(value: V) {\n    this.value = value;\n    this.initWeight();\n  }\n\n  abstract getLength(): number;\n\n  /**\n   * `getNodeString` returns a string of weight and value of this node.\n   */\n  public getNodeString(): string {\n    return `${this.weight}${this.value}`;\n  }\n\n  /**\n   * `getValue` returns value of this node.\n   */\n  public getValue(): V {\n    return this.value;\n  }\n\n  /**\n   * `getLeftWeight` returns left weight of this node.\n   */\n  public getLeftWeight(): number {\n    return !this.hasLeft() ? 0 : this.left!.getWeight();\n  }\n\n  /**\n   * `getRightWeight` returns right weight of this node.\n   */\n  public getRightWeight(): number {\n    return !this.hasRight() ? 0 : this.right!.getWeight();\n  }\n\n  /**\n   * `getWeight` returns weight of this node.\n   */\n  public getWeight(): number {\n    return this.weight;\n  }\n\n  /**\n   * `getLeft` returns a left node.\n   */\n  public getLeft(): SplayNode<V> | undefined {\n    return this.left;\n  }\n\n  /**\n   * `getRight` returns a right node.\n   */\n  public getRight(): SplayNode<V> | undefined {\n    return this.right;\n  }\n\n  /**\n   * `getParent` returns parent of this node.\n   */\n  public getParent(): SplayNode<V> | undefined {\n    return this.parent;\n  }\n\n  /**\n   * `hasLeft` check if the left node exists\n   */\n  public hasLeft(): boolean {\n    return !!this.left;\n  }\n\n  /**\n   * `hasRight` check if the right node exists\n   */\n  public hasRight(): boolean {\n    return !!this.right;\n  }\n\n  /**\n   * `hasParent` check if the parent node exists\n   */\n  public hasParent(): boolean {\n    return !!this.parent;\n  }\n\n  /**\n   * `setLeft` sets a left node.\n   */\n  public setLeft(left?: SplayNode<V>): void {\n    this.left = left;\n  }\n\n  /**\n   * `setRight` sets a right node.\n   */\n  public setRight(right?: SplayNode<V>): void {\n    this.right = right;\n  }\n\n  /**\n   * `setParent` sets a parent node.\n   */\n  public setParent(parent?: SplayNode<V>): void {\n    this.parent = parent;\n  }\n\n  /**\n   * `unlink` unlink parent, right and left node.\n   */\n  public unlink(): void {\n    this.parent = undefined;\n    this.right = undefined;\n    this.left = undefined;\n  }\n\n  /**\n   * `hasLinks` checks if parent, right and left node exists.\n   */\n  public hasLinks(): boolean {\n    return this.hasParent() || this.hasLeft() || this.hasRight();\n  }\n\n  /**\n   * `increaseWeight` increases weight.\n   */\n  public increaseWeight(weight: number): void {\n    this.weight! += weight;\n  }\n\n  /**\n   * `initWeight` sets initial weight of this node.\n   */\n  public initWeight(): void {\n    this.weight = this.getLength();\n  }\n}\n\n/**\n * SplayTree is weighted binary search tree which is based on Splay tree.\n * original paper on Splay Trees:\n * @see https://www.cs.cmu.edu/~sleator/papers/self-adjusting.pdf\n */\nexport class SplayTree<V> {\n  private root?: SplayNode<V>;\n\n  constructor(root?: SplayNode<V>) {\n    this.root = root;\n  }\n\n  /**\n   * `length` returns the size of this tree.\n   */\n  public get length(): number {\n    return this.root ? this.root.getWeight() : 0;\n  }\n\n  /**\n   * `findForText` returns the Node and offset of the given position (cursor).\n   * Used for Text where cursor placed between characters.\n   */\n  public findForText(pos: number): [SplayNode<V> | undefined, number] {\n    if (!this.root || pos < 0) {\n      return [undefined, 0];\n    }\n\n    let node = this.root;\n    for (;;) {\n      if (node.hasLeft() && pos <= node.getLeftWeight()) {\n        node = node.getLeft()!;\n      } else if (\n        node.hasRight() &&\n        node.getLeftWeight() + node.getLength() < pos\n      ) {\n        pos -= node.getLeftWeight() + node.getLength();\n        node = node.getRight()!;\n      } else {\n        pos -= node.getLeftWeight();\n        break;\n      }\n    }\n    if (pos > node.getLength()) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `out of index range: pos: ${pos} > node.length: ${node.getLength()}`,\n      );\n    }\n    this.splayNode(node);\n    return [node, pos];\n  }\n\n  /**\n   * `findForArray` returns the Node of the given position (index).\n   * Used for Array where index points to the element.\n   */\n  public findForArray(idx: number): SplayNode<V> | undefined {\n    if (!this.root) {\n      return undefined;\n    }\n    if (idx < 0 || idx >= this.length) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `out of index range: idx: ${idx}, length: ${this.length}`,\n      );\n    }\n\n    let node = this.root;\n    for (;;) {\n      if (node.hasLeft() && idx < node.getLeftWeight()) {\n        node = node.getLeft()!;\n      } else if (\n        node.hasRight() &&\n        node.getLeftWeight() + node.getLength() <= idx\n      ) {\n        idx -= node.getLeftWeight() + node.getLength();\n        node = node.getRight()!;\n      } else {\n        break;\n      }\n    }\n    this.splayNode(node);\n    return node;\n  }\n\n  /**\n   * Find the index of the given node in BST.\n   *\n   * @param node - the given node\n   * @returns the index of given node\n   */\n  public indexOf(node: SplayNode<V>): number {\n    if (!node || (node !== this.root && !node.hasLinks())) {\n      return -1;\n    }\n\n    this.splayNode(node);\n    return this.root!.getLeftWeight();\n  }\n\n  /**\n   * `getRoot` returns root of this tree.\n   */\n  public getRoot(): SplayNode<V> {\n    return this.root!;\n  }\n\n  /**\n   * `insert` inserts the node at the last.\n   */\n  public insert(newNode: SplayNode<V>): SplayNode<V> {\n    return this.insertAfter(this.root, newNode);\n  }\n\n  /**\n   * `insertAfter` inserts the node after the given previous node.\n   */\n  public insertAfter(\n    target: SplayNode<V> | undefined,\n    newNode: SplayNode<V>,\n  ): SplayNode<V> {\n    // TODO(Eithea): Consider moving the code below to insert()\n    if (!target) {\n      this.root = newNode;\n      return newNode;\n    }\n\n    this.splayNode(target);\n    this.root = newNode;\n    newNode.setRight(target.getRight());\n    if (target.hasRight()) {\n      target.getRight()!.setParent(newNode);\n    }\n    newNode.setLeft(target);\n    target.setParent(newNode);\n    target.setRight();\n    this.updateWeight(target);\n    this.updateWeight(newNode);\n\n    return newNode;\n  }\n\n  /**\n   * `updateWeight` recalculates the weight of this node with the value and children.\n   */\n  public updateWeight(node: SplayNode<V>): void {\n    node.initWeight();\n\n    if (node.hasLeft()) {\n      node.increaseWeight(node.getLeftWeight());\n    }\n    if (node.hasRight()) {\n      node.increaseWeight(node.getRightWeight());\n    }\n  }\n\n  private updateTreeWeight(node: SplayNode<V>): void {\n    while (node) {\n      this.updateWeight(node);\n      node = node.getParent()!;\n    }\n  }\n\n  /**\n   * `splayNode` moves the given node to the root.\n   */\n  public splayNode(node: SplayNode<V> | undefined): void {\n    if (!node) {\n      return;\n    }\n\n    for (;;) {\n      if (this.isLeftChild(node.getParent()) && this.isRightChild(node)) {\n        // zig-zag\n        this.rotateLeft(node);\n        this.rotateRight(node);\n      } else if (\n        this.isRightChild(node.getParent()) &&\n        this.isLeftChild(node)\n      ) {\n        // zig-zag\n        this.rotateRight(node);\n        this.rotateLeft(node);\n      } else if (this.isLeftChild(node.getParent()) && this.isLeftChild(node)) {\n        // zig-zig\n        this.rotateRight(node.getParent()!);\n        this.rotateRight(node);\n      } else if (\n        this.isRightChild(node.getParent()) &&\n        this.isRightChild(node)\n      ) {\n        // zig-zig\n        this.rotateLeft(node.getParent()!);\n        this.rotateLeft(node);\n      } else {\n        // zig\n        if (this.isLeftChild(node)) {\n          this.rotateRight(node);\n        } else if (this.isRightChild(node)) {\n          this.rotateLeft(node);\n        }\n        this.updateWeight(node);\n        return;\n      }\n    }\n  }\n\n  /**\n   * `delete` deletes target node of this tree.\n   */\n  public delete(node: SplayNode<V>): void {\n    this.splayNode(node);\n\n    const leftTree = new SplayTree(node.getLeft());\n    if (leftTree.root) {\n      leftTree.root.setParent();\n    }\n\n    const rightTree = new SplayTree(node.getRight());\n    if (rightTree.root) {\n      rightTree.root.setParent();\n    }\n\n    if (leftTree.root) {\n      const rightmostNode = leftTree.getRightmost();\n      leftTree.splayNode(rightmostNode);\n      leftTree.root.setRight(rightTree.root);\n      if (rightTree.root) {\n        rightTree.root.setParent(leftTree.root);\n      }\n      this.root = leftTree.root;\n    } else {\n      this.root = rightTree.root;\n    }\n\n    node.unlink();\n    if (this.root) {\n      this.updateWeight(this.root);\n    }\n  }\n\n  /**\n   * `deleteRange` separates the range between given 2 boundaries from this Tree.\n   * This function separates the range to delete as a subtree\n   * by splaying outer boundary nodes.\n   * leftBoundary must exist because of 0-indexed initial dummy node of tree,\n   * but rightBoundary can be nil means range to delete includes the end of tree.\n   * Refer to the design document in https://github.com/yorkie-team/yorkie/tree/main/design\n   */\n  public deleteRange(\n    leftBoundary: SplayNode<V>,\n    rightBoundary: SplayNode<V> | undefined,\n  ): void {\n    if (!rightBoundary) {\n      this.splayNode(leftBoundary);\n      this.cutOffRight(leftBoundary);\n      return;\n    }\n    this.splayNode(leftBoundary);\n    this.splayNode(rightBoundary);\n    if (rightBoundary.getLeft() != leftBoundary) {\n      this.rotateRight(leftBoundary);\n    }\n    this.cutOffRight(leftBoundary);\n  }\n\n  private cutOffRight(root: SplayNode<V>): void {\n    const nodesToFreeWeight: Array<SplayNode<V>> = [];\n    this.traversePostorder(root.getRight(), nodesToFreeWeight);\n    for (const node of nodesToFreeWeight) {\n      node.initWeight();\n    }\n    this.updateTreeWeight(root);\n  }\n\n  /**\n   * `toTestString` returns a string containing the meta data of the Node\n   * for debugging purpose.\n   */\n  public toTestString(): string {\n    const metaString: Array<SplayNode<V>> = [];\n    this.traverseInorder(this.root!, metaString);\n    return metaString\n      .map((n) => `[${n.getWeight()},${n.getLength()}]${n.getValue() || ''}`)\n      .join('');\n  }\n\n  /**\n   * `checkWeight` returns false when there is an incorrect weight node.\n   * for debugging purpose.\n   */\n  public checkWeight(): boolean {\n    const nodes: Array<SplayNode<V>> = [];\n    this.traverseInorder(this.root!, nodes);\n    for (const node of nodes) {\n      if (\n        node.getWeight() !=\n        node.getLength() + node.getLeftWeight() + node.getRightWeight()\n      ) {\n        return false;\n      }\n    }\n    return true;\n  }\n\n  private getRightmost(): SplayNode<V> {\n    let node = this.root!;\n    while (node.hasRight()) {\n      node = node.getRight()!;\n    }\n    return node;\n  }\n\n  private traverseInorder(\n    node: SplayNode<V> | undefined,\n    stack: Array<SplayNode<V>>,\n  ): void {\n    if (!node) {\n      return;\n    }\n\n    this.traverseInorder(node.getLeft(), stack);\n    stack.push(node);\n    this.traverseInorder(node.getRight(), stack);\n  }\n\n  private traversePostorder(\n    node: SplayNode<V> | undefined,\n    stack: Array<SplayNode<V>>,\n  ): void {\n    if (!node) {\n      return;\n    }\n\n    this.traversePostorder(node.getLeft(), stack);\n    this.traversePostorder(node.getRight(), stack);\n    stack.push(node);\n  }\n\n  private rotateLeft(pivot: SplayNode<V>): void {\n    const root = pivot.getParent()!;\n    if (root.hasParent()) {\n      if (root === root.getParent()!.getLeft()) {\n        root.getParent()!.setLeft(pivot);\n      } else {\n        root.getParent()!.setRight(pivot);\n      }\n    } else {\n      this.root = pivot;\n    }\n    pivot.setParent(root.getParent());\n\n    root.setRight(pivot.getLeft());\n    if (root.hasRight()) {\n      root.getRight()!.setParent(root);\n    }\n\n    pivot.setLeft(root);\n    pivot.getLeft()!.setParent(pivot);\n\n    this.updateWeight(root);\n    this.updateWeight(pivot);\n  }\n\n  private rotateRight(pivot: SplayNode<V>): void {\n    const root = pivot.getParent()!;\n    if (root.hasParent()) {\n      if (root === root.getParent()!.getLeft()) {\n        root.getParent()!.setLeft(pivot);\n      } else {\n        root.getParent()!.setRight(pivot);\n      }\n    } else {\n      this.root = pivot;\n    }\n    pivot.setParent(root.getParent());\n\n    root.setLeft(pivot.getRight());\n    if (root.hasLeft()) {\n      root.getLeft()!.setParent(root);\n    }\n\n    pivot.setRight(root);\n    pivot.getRight()!.setParent(pivot);\n\n    this.updateWeight(root);\n    this.updateWeight(pivot);\n  }\n\n  private isLeftChild(node?: SplayNode<V>): boolean {\n    if (node && node.hasParent()) {\n      return node.getParent()!.getLeft() === node;\n    }\n    return false;\n  }\n\n  private isRightChild(node?: SplayNode<V>): boolean {\n    if (node && node.hasParent()) {\n      return node.getParent()!.getRight() === node;\n    }\n    return false;\n  }\n}\n","/*\n * Copyright 2020 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport type Comparator<K> = (keyA: K, keyB: K) => number;\n\nexport const DefaultComparator = (a: any, b: any): number => {\n  if (a === b) {\n    return 0;\n  } else if (a < b) {\n    return -1;\n  } else {\n    return 1;\n  }\n};\n","/*\n * Copyright 2020 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n  Comparator,\n  DefaultComparator,\n} from '@yorkie-js/sdk/src/util/comparator';\n\ninterface Entry<K, V> {\n  key: K;\n  value: V;\n}\n\n/**\n * `LLRBNode` is node of LLRBTree.\n */\nclass LLRBNode<K, V> {\n  public key: K;\n  public value: V;\n  public left?: LLRBNode<K, V>;\n  public right?: LLRBNode<K, V>;\n  public isRed: boolean;\n\n  constructor(key: K, value: V, isRed: boolean) {\n    this.key = key;\n    this.value = value;\n    this.isRed = isRed;\n  }\n}\n\n/**\n * `SortedMapIterator` is a interator for traversing LLRBTree.\n */\nexport class SortedMapIterator<K, V> {\n  public stack: Array<Entry<K, V>>;\n\n  constructor(root: LLRBNode<K, V>) {\n    this.stack = [];\n    this.traverseInorder(root);\n  }\n\n  // TODO: Replace with iterative approach, if we encounter performance problem.\n  private traverseInorder(node: LLRBNode<K, V>): void {\n    if (!node) {\n      return;\n    }\n\n    this.traverseInorder(node.left!);\n    this.stack.push({\n      key: node.key,\n      value: node.value,\n    });\n    this.traverseInorder(node.right!);\n  }\n}\n\n/**\n * LLRBTree is an implementation of Left-learning Red-Black Tree.\n *\n * Original paper on Left-leaning Red-Black Trees:\n * @see http://www.cs.princeton.edu/~rs/talks/LLRB/LLRB.pdf\n *\n * Invariant 1: No red node has a red child\n * Invariant 2: Every leaf path has the same number of black nodes\n * Invariant 3: Only the left child can be red (left leaning)\n */\nexport class LLRBTree<K, V> {\n  private root?: LLRBNode<K, V>;\n  private comparator: Comparator<K>;\n  private counter: number;\n\n  constructor(comparator?: Comparator<K>) {\n    this.comparator =\n      typeof comparator !== 'undefined' ? comparator : DefaultComparator;\n    this.counter = 0;\n  }\n\n  /**\n   * `put` puts the value of the given key.\n   */\n  public put(key: K, value: V): V {\n    this.root = this.putInternal(key, value, this.root);\n    this.root.isRed = false;\n    return value;\n  }\n\n  /**\n   * `get` gets a value of the given key.\n   */\n  public get(key: K): V | undefined {\n    const node = this.getInternal(key, this.root);\n    return node ? node.value : undefined;\n  }\n\n  /**\n   * `remove` removes a element of key.\n   */\n  public remove(key: K): void {\n    if (!this.isRed(this.root!.left!) && !this.isRed(this.root!.right!)) {\n      this.root!.isRed = true;\n    }\n\n    this.root = this.removeInternal(this.root!, key);\n    if (this.root) {\n      this.root.isRed = false;\n    }\n  }\n\n  /**\n   * `getIterator` returns a new instance of SortedMapIterator.\n   */\n  public getIterator(): SortedMapIterator<K, V> {\n    return new SortedMapIterator(this.root!);\n  }\n\n  /**\n   * `values` returns value array of LLRBTree.\n   */\n  public values(): Array<V> {\n    const values = [];\n    for (const entry of this.getIterator().stack) {\n      values.push(entry.value);\n    }\n    return values;\n  }\n\n  /**\n   * `floorEntry` returns the entry for the greatest key less than or equal to the\n   *  given key. If there is no such key, returns `undefined`.\n   */\n  public floorEntry(key: K): Entry<K, V> | undefined {\n    let node = this.root;\n    let result: LLRBNode<K, V> | undefined = undefined;\n\n    while (node) {\n      const compare = this.comparator(key, node.key);\n      if (compare === 0) {\n        return node;\n      } else if (compare < 0) {\n        node = node.left;\n      } else {\n        result = node;\n        node = node.right;\n      }\n    }\n\n    return result;\n  }\n\n  /**\n   * `ceilingEntry` returns the entry for the least key greater than or equal\n   * to the given key. If there is no such key, returns `undefined`.\n   */\n  public ceilingEntry(key: K): Entry<K, V> | undefined {\n    let node = this.root;\n    let result: LLRBNode<K, V> | undefined = undefined;\n\n    while (node) {\n      const compare = this.comparator(key, node.key);\n      if (compare === 0) {\n        return node;\n      } else if (compare < 0) {\n        result = node;\n        node = node.left;\n      } else {\n        node = node.right;\n      }\n    }\n\n    return result;\n  }\n\n  /**\n   * `lastEntry` returns last entry of LLRBTree.\n   */\n  public lastEntry(): Entry<K, V> | undefined {\n    if (!this.root) {\n      return this.root;\n    }\n\n    let node = this.root;\n    while (node.right) {\n      node = node.right;\n    }\n    return node;\n  }\n\n  /**\n   * `size` is a size of LLRBTree.\n   */\n  public size(): number {\n    return this.counter;\n  }\n\n  /**\n   * `isEmpty` checks if size is empty.\n   */\n  public isEmpty(): boolean {\n    return this.counter === 0;\n  }\n\n  private getInternal(\n    key: K,\n    node?: LLRBNode<K, V>,\n  ): LLRBNode<K, V> | undefined {\n    while (node) {\n      const compare = this.comparator(key, node.key);\n      if (compare === 0) {\n        return node;\n      } else if (compare < 0) {\n        node = node.left!;\n      } else if (compare > 0) {\n        node = node.right!;\n      }\n    }\n\n    return;\n  }\n\n  private putInternal(key: K, value: V, node?: LLRBNode<K, V>): LLRBNode<K, V> {\n    if (!node) {\n      this.counter += 1;\n      return new LLRBNode(key, value, true);\n    }\n\n    const compare = this.comparator(key, node.key);\n    if (compare < 0) {\n      node.left = this.putInternal(key, value, node.left);\n    } else if (compare > 0) {\n      node.right = this.putInternal(key, value, node.right);\n    } else {\n      node.value = value;\n    }\n\n    if (this.isRed(node.right!) && !this.isRed(node.left!)) {\n      node = this.rotateLeft(node);\n    }\n\n    if (this.isRed(node.left!) && this.isRed(node.left!.left!)) {\n      node = this.rotateRight(node);\n    }\n\n    if (this.isRed(node.left!) && this.isRed(node.right!)) {\n      this.flipColors(node);\n    }\n\n    return node;\n  }\n\n  private removeInternal(\n    node: LLRBNode<K, V>,\n    key: K,\n  ): LLRBNode<K, V> | undefined {\n    if (this.comparator(key, node.key) < 0) {\n      if (!this.isRed(node.left!) && !this.isRed(node.left!.left!)) {\n        node = this.moveRedLeft(node);\n      }\n      node.left = this.removeInternal(node.left!, key);\n    } else {\n      if (this.isRed(node.left!)) {\n        node = this.rotateRight(node);\n      }\n\n      if (this.comparator(key, node.key) === 0 && !node.right) {\n        this.counter -= 1;\n        return;\n      }\n\n      if (!this.isRed(node.right!) && !this.isRed(node.right!.left!)) {\n        node = this.moveRedRight(node);\n      }\n\n      if (this.comparator(key, node.key) === 0) {\n        this.counter -= 1;\n        const smallest = this.min(node.right!);\n        node.value = smallest.value;\n        node.key = smallest.key;\n        node.right = this.removeMin(node.right!);\n      } else {\n        node.right = this.removeInternal(node.right!, key);\n      }\n    }\n\n    return this.fixUp(node);\n  }\n\n  private min(node: LLRBNode<K, V>): LLRBNode<K, V> {\n    if (!node.left) {\n      return node;\n    } else {\n      return this.min(node.left);\n    }\n  }\n\n  private removeMin(node: LLRBNode<K, V>): LLRBNode<K, V> | undefined {\n    if (!node.left) {\n      return;\n    }\n\n    if (!this.isRed(node.left) && !this.isRed(node.left!.left!)) {\n      node = this.moveRedLeft(node);\n    }\n\n    node.left = this.removeMin(node.left!);\n    return this.fixUp(node);\n  }\n\n  private fixUp(node: LLRBNode<K, V>): LLRBNode<K, V> {\n    if (this.isRed(node.right!)) {\n      node = this.rotateLeft(node);\n    }\n\n    if (this.isRed(node.left!) && this.isRed(node.left!.left!)) {\n      node = this.rotateRight(node);\n    }\n\n    if (this.isRed(node.left!) && this.isRed(node.right!)) {\n      this.flipColors(node);\n    }\n\n    return node;\n  }\n\n  private moveRedLeft(node: LLRBNode<K, V>): LLRBNode<K, V> {\n    this.flipColors(node);\n    if (this.isRed(node.right!.left!)) {\n      node.right = this.rotateRight(node.right!);\n      node = this.rotateLeft(node);\n      this.flipColors(node);\n    }\n    return node;\n  }\n\n  private moveRedRight(node: LLRBNode<K, V>): LLRBNode<K, V> {\n    this.flipColors(node);\n    if (this.isRed(node.left!.left!)) {\n      node = this.rotateRight(node);\n      this.flipColors(node);\n    }\n    return node;\n  }\n\n  private isRed(node: LLRBNode<K, V>): boolean {\n    return node && node.isRed;\n  }\n\n  private rotateLeft(node: LLRBNode<K, V>): LLRBNode<K, V> {\n    const x = node.right!;\n    node.right = x.left;\n    x.left = node;\n    x.isRed = x.left.isRed;\n    x.left.isRed = true;\n    return x;\n  }\n\n  private rotateRight(node: LLRBNode<K, V>): LLRBNode<K, V> {\n    const x = node.left!;\n    node.left = x.right;\n    x.right = node;\n    x.isRed = x.right.isRed;\n    x.right.isRed = true;\n    return x;\n  }\n\n  private flipColors(node: LLRBNode<K, V>): void {\n    node.isRed = !node.isRed!;\n    node.left!.isRed = !node.left!.isRed;\n    node.right!.isRed = !node.right!.isRed;\n  }\n}\n","/*\n * Copyright 2024 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TimeTicket } from './ticket';\n\n/**\n * `VersionVector` is a vector clock that is used to detect the relationship\n * between changes whether they are causally related or concurrent. It is\n * similar to vector clocks, but it is synced with lamport timestamp of the\n * change.\n */\nexport class VersionVector {\n  private vector: Map<string, bigint>;\n\n  constructor(vector?: Map<string, bigint>) {\n    this.vector = vector || new Map();\n  }\n\n  /**\n   * `set` sets the lamport timestamp of the given actor.\n   */\n  public set(actorID: string, lamport: bigint): void {\n    this.vector.set(actorID, lamport);\n  }\n\n  /**\n   * `unset` removes the version for the given actor from the VersionVector.\n   */\n  public unset(actorID: string): void {\n    this.vector.delete(actorID);\n  }\n\n  /**\n   * `get` gets the lamport timestamp of the given actor.\n   */\n  public get(actorID: string): bigint | undefined {\n    return this.vector.get(actorID);\n  }\n\n  /**\n   * `has` checks if the given actor exists in the VersionVector.\n   */\n  public has(actorID: string): boolean {\n    return this.vector.has(actorID);\n  }\n\n  /**\n   * `maxLamport` returns max lamport value from vector\n   */\n  public maxLamport() {\n    let max = BigInt(0);\n\n    for (const [, lamport] of this) {\n      if (lamport > max) {\n        max = lamport;\n      }\n    }\n\n    return max;\n  }\n\n  /**\n   * `max` returns new version vector which consists of max value of each vector\n   */\n  public max(other: VersionVector): VersionVector {\n    const maxVector = new Map<string, bigint>();\n\n    for (const [actorID, lamport] of other) {\n      const currentLamport = this.vector.get(actorID);\n      const maxLamport = currentLamport\n        ? currentLamport > lamport\n          ? currentLamport\n          : lamport\n        : lamport;\n\n      maxVector.set(actorID, maxLamport);\n    }\n\n    for (const [actorID, lamport] of this) {\n      const otherLamport = other.get(actorID);\n      const maxLamport = otherLamport\n        ? otherLamport > lamport\n          ? otherLamport\n          : lamport\n        : lamport;\n\n      maxVector.set(actorID, maxLamport);\n    }\n\n    return new VersionVector(maxVector);\n  }\n\n  /**\n   * `afterOrEqual` returns vector[other.actorID] is greaterOrEqual than given ticket's lamport\n   */\n  public afterOrEqual(other: TimeTicket) {\n    const lamport = this.vector.get(other.getActorID());\n\n    if (lamport === undefined) {\n      return false;\n    }\n\n    return lamport >= other.getLamport();\n  }\n\n  /**\n   * `deepcopy` returns a deep copy of this `VersionVector`.\n   */\n  public deepcopy(): VersionVector {\n    const copied = new Map<string, bigint>();\n    for (const [key, value] of this.vector) {\n      copied.set(key, value);\n    }\n    return new VersionVector(copied);\n  }\n\n  /**\n   * `filter` returns new version vector consist of filter's actorID.\n   */\n  public filter(versionVector: VersionVector) {\n    const filtered = new Map<string, bigint>();\n\n    for (const [actorID] of versionVector) {\n      const lamport = this.vector.get(actorID);\n\n      if (lamport !== undefined) {\n        filtered.set(actorID, lamport);\n      }\n    }\n\n    return new VersionVector(filtered);\n  }\n\n  /**\n   * `size` returns size of version vector\n   */\n  public size(): number {\n    return this.vector.size;\n  }\n\n  // eslint-disable-next-line jsdoc/require-jsdoc\n  public *[Symbol.iterator](): IterableIterator<[string, bigint]> {\n    for (const [key, value] of this.vector) {\n      yield [key, value];\n    }\n  }\n}\n\n/**\n * `InitialVersionVector` is the initial version vector.\n */\nexport const InitialVersionVector = new VersionVector(new Map());\n\n/**\n * `ticketKnown` returns true if the given ticket is causally known to the\n * editor, i.e. the editor's version vector covers the ticket's lamport\n * clock for the same actor. For local operations (an undefined or empty\n * version vector), all tickets are considered known.\n */\nexport function ticketKnown(\n  vv: VersionVector | undefined,\n  ticket: TimeTicket,\n): boolean {\n  // An empty vector is a local change, the same way the server reads\n  // `len(vv) == 0` -- not just an absent one. The two have to agree or the\n  // same operation is causally known on one side and not the other.\n  if (vv === undefined || vv.size() === 0) {\n    return true;\n  }\n\n  const l = vv.get(ticket.getActorID());\n  return l !== undefined && l >= ticket.getLamport();\n}\n","/*\n * Copyright 2025 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * `DocSize` represents the size of a document in bytes.\n */\nexport type DocSize = {\n  /**\n   * `live` is the size of the document in bytes.\n   */\n  live: DataSize;\n\n  /**\n   * `gc` is the size of the garbage collected data in bytes.\n   */\n  gc: DataSize;\n};\n\n/**\n * `totalDocSize` calculates the total size of a document.\n */\nexport function totalDocSize(d: DocSize | undefined): number {\n  if (!d) return 0;\n  return totalDataSize(d.live) + totalDataSize(d.gc);\n}\n\n/**\n * `DataSize` represents the size of a resource in bytes.\n */\nconst textEncoder = new TextEncoder();\n\n/**\n * `utf8Length` returns the number of UTF-8 bytes in the given string, which is\n * what Go's `len()` counts. A size charged in UTF-16 units instead agrees only\n * for ASCII, and the two SDKs enforce the document size limit client-side\n * against their own accounting, so they have to measure the same way.\n */\nexport function utf8Length(s: string): number {\n  return textEncoder.encode(s).length;\n}\n\nexport type DataSize = {\n  /**\n   * `data` is the size of the data in bytes.\n   */\n  data: number;\n\n  /**\n   * `meta` is the size of the metadata in bytes.\n   */\n  meta: number;\n};\n\n/**\n * `totalDataSize` calculates the total size of a resource.\n */\nexport function totalDataSize(d: DataSize): number {\n  return d.data + d.meta;\n}\n\n/**\n * `addDataSizes` adds the size of a resource to the target resource.\n */\nexport function addDataSizes(\n  target: DataSize,\n  ...others: Array<DataSize>\n): void {\n  for (const other of others) {\n    target.data += other.data;\n    target.meta += other.meta;\n  }\n}\n\n/**\n * `subDataSize` subtracts the size of a resource from the target resource.\n */\nexport function subDataSize(target: DataSize, other: DataSize): void {\n  target.data -= other.data;\n  target.meta -= other.meta;\n}\n","/*\n * Copyright 2020 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ActorID } from '@yorkie-js/sdk/src/document/time/actor_id';\nimport { Comparator } from '@yorkie-js/sdk/src/util/comparator';\nimport { SplayNode, SplayTree } from '@yorkie-js/sdk/src/util/splay_tree';\nimport { LLRBTree } from '@yorkie-js/sdk/src/util/llrb_tree';\nimport {\n  InitialTimeTicket,\n  TimeTicket,\n  TimeTicketSize,\n  TimeTicketStruct,\n} from '@yorkie-js/sdk/src/document/time/ticket';\nimport {\n  VersionVector,\n  ticketKnown,\n} from '@yorkie-js/sdk/src/document/time/version_vector';\nimport { GCChild, GCPair, GCParent } from '@yorkie-js/sdk/src/document/crdt/gc';\nimport { Code, YorkieError } from '@yorkie-js/sdk/src/util/error';\nimport {\n  DataSize,\n  addDataSizes,\n  subDataSize,\n} from '@yorkie-js/sdk/src/util/resource';\n\nexport interface ValueChange<T> {\n  actor: ActorID;\n  from: number;\n  to: number;\n  value?: T;\n}\n\nexport interface RGATreeSplitValue {\n  length: number;\n  substring(indexStart: number, indexEnd?: number): RGATreeSplitValue;\n\n  /**\n   * `truncate` shortens this value in place, keeping the object identity.\n   *\n   * A split has to keep the LEFT node's value object, because `CRDTRoot.keyOf`\n   * identifies a GC pair's parent by object identity. Replacing it orphans\n   * every pair already registered against it: purge is then called on an\n   * object nothing references, so the tombstone survives while the ledger says\n   * it was collected. The Go implementation splits in place for the same\n   * reason.\n   */\n  truncate(offset: number): void;\n\n  getDataSize(): DataSize;\n\n  /**\n   * `getGCPairs` returns the pairs for the tombstones this value carries, for\n   * a value that has any (`CRDTTextValue`'s removed attributes).\n   */\n  getGCPairs?(): Array<GCPair>;\n}\n\n/**\n * `RGATreeSplitPosStruct` is a structure represents the meta data of the node pos.\n * It is used to serialize and deserialize the node pos.\n */\nexport type RGATreeSplitPosStruct = {\n  id: RGATreeSplitNodeIDStruct;\n  relativeOffset: number;\n};\n\n/**\n * `RGATreeSplitNodeIDStruct` is a structure represents the meta data of the node id.\n * It is used to serialize and deserialize the node id.\n */\nexport type RGATreeSplitNodeIDStruct = {\n  createdAt: TimeTicketStruct;\n  offset: number;\n};\n\n/**\n * `RGATreeSplitNodeID` is an ID of RGATreeSplitNode.\n */\nexport class RGATreeSplitNodeID {\n  private createdAt: TimeTicket;\n  private offset: number;\n\n  constructor(createdAt: TimeTicket, offset: number) {\n    this.createdAt = createdAt;\n    this.offset = offset;\n  }\n\n  /**\n   * `of` creates a instance of RGATreeSplitNodeID.\n   */\n  public static of(createdAt: TimeTicket, offset: number): RGATreeSplitNodeID {\n    return new RGATreeSplitNodeID(createdAt, offset);\n  }\n\n  /**\n   * `fromStruct` creates a instance of RGATreeSplitNodeID from the struct.\n   */\n  public static fromStruct(\n    struct: RGATreeSplitNodeIDStruct,\n  ): RGATreeSplitNodeID {\n    return RGATreeSplitNodeID.of(\n      TimeTicket.fromStruct(struct.createdAt),\n      struct.offset,\n    );\n  }\n\n  /**\n   * `getCreatedAt` returns the creation time of this ID.\n   */\n  public getCreatedAt(): TimeTicket {\n    return this.createdAt;\n  }\n\n  /**\n   * `getOffset` returns returns the offset of this ID.\n   */\n  public getOffset(): number {\n    return this.offset;\n  }\n\n  /**\n   * `equals` returns whether given ID equals to this ID or not.\n   */\n  public equals(other: RGATreeSplitNodeID): boolean {\n    return (\n      this.createdAt.compare(other.createdAt) === 0 &&\n      this.offset === other.offset\n    );\n  }\n\n  /**\n   * `hasSameCreatedAt` returns whether given ID has same creation time with this ID.\n   */\n  public hasSameCreatedAt(other: RGATreeSplitNodeID): boolean {\n    return this.createdAt.compare(other.createdAt) === 0;\n  }\n\n  /**\n   * `split` creates a new ID with an offset from this ID.\n   */\n  public split(offset: number): RGATreeSplitNodeID {\n    return new RGATreeSplitNodeID(this.createdAt, this.offset + offset);\n  }\n\n  /**\n   * `toStruct` returns the structure of this node id.\n   */\n  public toStruct(): RGATreeSplitNodeIDStruct {\n    return {\n      createdAt: this.createdAt.toStruct(),\n      offset: this.offset,\n    };\n  }\n\n  /**\n   * `toTestString` returns a String containing\n   * the meta data of the node id for debugging purpose.\n   */\n  public toTestString(): string {\n    return `${this.createdAt.toTestString()}:${this.offset}`;\n  }\n\n  /**\n   * `toIDString` returns a string that can be used as an ID for this node id.\n   */\n  public toIDString(): string {\n    return `${this.createdAt.toIDString()}:${this.offset}`;\n  }\n}\n\n/**\n * `InitialRGATreeSplitNodeID` is the ID of the head node of every\n * RGATreeSplit.\n */\nexport const InitialRGATreeSplitNodeID = RGATreeSplitNodeID.of(\n  InitialTimeTicket,\n  0,\n);\n\n/**\n * `RGATreeSplitPos` is the position of the text inside the node.\n */\nexport class RGATreeSplitPos {\n  private id: RGATreeSplitNodeID;\n  private relativeOffset: number;\n\n  constructor(id: RGATreeSplitNodeID, relativeOffset: number) {\n    this.id = id;\n    this.relativeOffset = relativeOffset;\n  }\n\n  /**\n   * `of` creates a instance of RGATreeSplitPos.\n   */\n  public static of(\n    id: RGATreeSplitNodeID,\n    relativeOffset: number,\n  ): RGATreeSplitPos {\n    return new RGATreeSplitPos(id, relativeOffset);\n  }\n\n  /**\n   * `fromStruct` creates a instance of RGATreeSplitPos from the struct.\n   */\n  public static fromStruct(struct: RGATreeSplitPosStruct): RGATreeSplitPos {\n    const id = RGATreeSplitNodeID.fromStruct(struct.id);\n    return RGATreeSplitPos.of(id, struct.relativeOffset);\n  }\n\n  /**\n   * `getID` returns the ID of this RGATreeSplitPos.\n   */\n  public getID(): RGATreeSplitNodeID {\n    return this.id;\n  }\n\n  /**\n   * `getRelativeOffset` returns the relative offset of this RGATreeSplitPos.\n   */\n  public getRelativeOffset(): number {\n    return this.relativeOffset;\n  }\n\n  /**\n   * `getAbsoluteID` returns the absolute id of this RGATreeSplitPos.\n   */\n  public getAbsoluteID(): RGATreeSplitNodeID {\n    return RGATreeSplitNodeID.of(\n      this.id.getCreatedAt(),\n      this.id.getOffset() + this.relativeOffset,\n    );\n  }\n\n  /**\n   *`toTestString` returns a String containing\n   * the meta data of the position for debugging purpose.\n   */\n  public toTestString(): string {\n    return `${this.id.toTestString()}:${this.relativeOffset}`;\n  }\n\n  /**\n   * `toStruct` returns the structure of this node pos.\n   */\n  public toStruct(): RGATreeSplitPosStruct {\n    return {\n      id: this.id.toStruct(),\n      relativeOffset: this.relativeOffset,\n    };\n  }\n\n  /**\n   * `equals` returns whether given pos equal to this pos or not.\n   */\n  public equals(other: RGATreeSplitPos): boolean {\n    if (!this.id.equals(other.id)) {\n      return false;\n    }\n\n    return this.relativeOffset === other.relativeOffset;\n  }\n}\n\nexport type RGATreeSplitPosRange = [RGATreeSplitPos, RGATreeSplitPos];\n\n/**\n * `RestoreSpan` identifies a run of characters from a single original\n * insertion: the absolute-offset interval [start, end) of the insertion\n * created at `createdAt`. `value` is a deep copy of the removed content,\n * carried so that purged nodes can be recreated (GC-safe).\n */\nexport type RestoreSpan<T extends RGATreeSplitValue> = {\n  createdAt: TimeTicket;\n  start: number;\n  end: number;\n  value: T;\n};\n\n/**\n * `LedgerCancel` is an undo that cancelled one deletion of a node.\n */\nexport type LedgerCancel = {\n  deletion: TimeTicket;\n  cancelledAt: TimeTicket;\n};\n\n/**\n * `LedgerEntry` is one deletion of a removal ledger beside the cancel that\n * covers it, if an undo cancelled it.\n */\ntype LedgerEntry = {\n  removal: TimeTicket;\n  cancelledAt?: TimeTicket;\n};\n\n/**\n * `LedgerIndex` is the reading of a removal ledger every walk of it needs:\n * each deletion with its cancel, those entries by deletion, the deletions no\n * cancel covers, and the cancels by the deletion each one cancels -- which\n * covers the cancel of a deletion the ledger itself does not hold.\n */\ntype LedgerIndex = {\n  entries: Array<LedgerEntry>;\n  byKey: Map<string, LedgerEntry>;\n  live: Array<TimeTicket>;\n  cancelled: Map<string, TimeTicket>;\n};\n\n/**\n * `RGATreeSplitNode` is a node of RGATreeSplit.\n */\nexport class RGATreeSplitNode<T extends RGATreeSplitValue>\n  extends SplayNode<T>\n  implements GCChild\n{\n  private id: RGATreeSplitNodeID;\n  private removedAt?: TimeTicket;\n  // The removal ledger. `dels` are the deletions that removed this node\n  // while it was live in the deleter's view; `cancels` are the deletions undo\n  // cancelled. `removedAt` is the latest uncancelled deletion. `!ledgered`\n  // means the ledger is just `removedAt`.\n  private ledgered = false;\n  private dels?: Array<TimeTicket>;\n  private cancels?: Array<LedgerCancel>;\n  // The reading of the ledger above, kept because a ledger grows a pair per\n  // delete-and-undo cycle and rebuilding it on every walk makes churning one\n  // quadratic. Every write of the ledger either drops it or updates it.\n  private index?: LedgerIndex;\n\n  private prev?: RGATreeSplitNode<T>;\n  private next?: RGATreeSplitNode<T>;\n  private insPrev?: RGATreeSplitNode<T>;\n  private insNext?: RGATreeSplitNode<T>;\n\n  constructor(id: RGATreeSplitNodeID, value?: T, removedAt?: TimeTicket) {\n    super(value!);\n    this.id = id;\n    this.removedAt = removedAt;\n  }\n\n  /**\n   * `create` creates a instance of RGATreeSplitNode.\n   */\n  public static create<T extends RGATreeSplitValue>(\n    id: RGATreeSplitNodeID,\n    value?: T,\n  ): RGATreeSplitNode<T> {\n    return new RGATreeSplitNode(id, value);\n  }\n\n  /**\n   * `createComparator` creates a function to compare two RGATreeSplitNodeID.\n   */\n  public static createComparator(): Comparator<RGATreeSplitNodeID> {\n    return (p1: RGATreeSplitNodeID, p2: RGATreeSplitNodeID): number => {\n      const compare = p1.getCreatedAt().compare(p2.getCreatedAt());\n      if (compare !== 0) {\n        return compare;\n      }\n\n      if (p1.getOffset() > p2.getOffset()) {\n        return 1;\n      } else if (p1.getOffset() < p2.getOffset()) {\n        return -1;\n      }\n      return 0;\n    };\n  }\n\n  /**\n   * `getID` returns the ID of this RGATreeSplitNode.\n   */\n  public getID(): RGATreeSplitNodeID {\n    return this.id;\n  }\n\n  /**\n   * `getCreatedAt` returns creation time of the Id of RGATreeSplitNode.\n   */\n  public getCreatedAt(): TimeTicket {\n    return this.id.getCreatedAt();\n  }\n\n  /**\n   * `getLength` returns the length of this node.\n   */\n  public getLength(): number {\n    if (this.removedAt) {\n      return 0;\n    }\n    return this.getContentLength();\n  }\n\n  /**\n   * `getContentLength` returns the length of this value.\n   */\n  public getContentLength(): number {\n    return (this.value && this.value.length) || 0;\n  }\n\n  /**\n   * `getPrev` returns a previous node of this node.\n   */\n  public getPrev(): RGATreeSplitNode<T> | undefined {\n    return this.prev;\n  }\n\n  /**\n   * `getNext` returns a next node of this node.\n   */\n  public getNext(): RGATreeSplitNode<T> | undefined {\n    return this.next;\n  }\n\n  /**\n   * `getInsPrev` returns a previous node of this node insertion.\n   */\n  public getInsPrev(): RGATreeSplitNode<T> | undefined {\n    return this.insPrev;\n  }\n\n  /**\n   * `getInsNext` returns a next node of this node insertion.\n   */\n  public getInsNext(): RGATreeSplitNode<T> | undefined {\n    return this.insNext;\n  }\n\n  /**\n   * `getInsPrevID` returns a ID of previous node insertion.\n   */\n  public getInsPrevID(): RGATreeSplitNodeID {\n    return this.insPrev!.getID();\n  }\n\n  /**\n   * `setPrev` sets previous node of this node.\n   */\n  public setPrev(node?: RGATreeSplitNode<T>): void {\n    this.prev = node;\n    if (node) {\n      node.next = this;\n    }\n  }\n\n  /**\n   * `setNext` sets next node of this node.\n   */\n  public setNext(node?: RGATreeSplitNode<T>): void {\n    this.next = node;\n    if (node) {\n      node.prev = this;\n    }\n  }\n\n  /**\n   * `setInsPrev` sets previous node of this node insertion.\n   */\n  public setInsPrev(node?: RGATreeSplitNode<T>): void {\n    this.insPrev = node;\n    if (node) {\n      node.insNext = this;\n    }\n  }\n\n  /**\n   * `setInsNext` sets next node of this node insertion.\n   */\n  public setInsNext(node?: RGATreeSplitNode<T>): void {\n    this.insNext = node;\n    if (node) {\n      node.insPrev = this;\n    }\n  }\n\n  /**\n   * `hasNext` checks if next node exists.\n   */\n  public hasNext(): boolean {\n    return !!this.next;\n  }\n\n  /**\n   * `hasInsPrev` checks if previous insertion node exists.\n   */\n  public hasInsPrev(): boolean {\n    return !!this.insPrev;\n  }\n\n  /**\n   * `isRemoved` checks if removed time exists.\n   */\n  public isRemoved(): boolean {\n    return !!this.removedAt;\n  }\n\n  /**\n   * `getRemovedAt` returns the remove time of this node.\n   */\n  public getRemovedAt(): TimeTicket | undefined {\n    return this.removedAt;\n  }\n\n  /**\n   * `split` creates a new split node of the given offset.\n   */\n  public split(offset: number): RGATreeSplitNode<T> {\n    const node = new RGATreeSplitNode(\n      this.id.split(offset),\n      this.splitValue(offset),\n      this.removedAt,\n    );\n    node.copyLedger(this);\n    return node;\n  }\n\n  private copyLedger(other: RGATreeSplitNode<T>): void {\n    this.ledgered = other.ledgered;\n    this.dels = other.dels?.slice();\n    this.cancels = other.cancels?.slice();\n    this.index = undefined;\n  }\n\n  /**\n   * `getLedger` returns the removal ledger: whether there is one, the\n   * deletions and the cancels.\n   */\n  public getLedger(): [boolean, Array<TimeTicket>, Array<LedgerCancel>] {\n    return [this.ledgered, this.dels ?? [], this.cancels ?? []];\n  }\n\n  /**\n   * `hasCancels` tells whether the ledger holds a cancel, the only thing\n   * `pruneStable` can drop.\n   */\n  public hasCancels(): boolean {\n    return !!this.cancels?.length;\n  }\n\n  /**\n   * `removals` returns the deletions in the ledger without building one: a\n   * node without a ledger was removed by `removedAt` alone, if at all.\n   */\n  private removals(): Array<TimeTicket> {\n    if (this.ledgered) {\n      return this.dels ?? [];\n    }\n    return this.removedAt ? [this.removedAt] : [];\n  }\n\n  private ledger(): Array<TimeTicket> {\n    if (!this.ledgered) {\n      this.ledgered = true;\n      this.dels = this.removedAt ? [this.removedAt] : [];\n      this.index = undefined;\n    }\n    return this.dels!;\n  }\n\n  /**\n   * `ledgerIndex` reads the ledger into the form every walk of it wants, and\n   * keeps that reading until the ledger is written again. A deletion is\n   * cancelled at most once (`cancelRemoval` and `setRemovalEvents` both pair\n   * one to one), so a cancel is indexed by the deletion it cancels.\n   *\n   * Every walk of the ledger takes this index rather than scanning the\n   * cancels per deletion: the ledger of a decoded node is as long as whoever\n   * sent it made it, and a scan per deletion would make reading one quadratic\n   * in that length.\n   */\n  private ledgerIndex(): LedgerIndex {\n    if (!this.index) {\n      const cancelled = new Map<string, TimeTicket>();\n      for (const c of this.cancels ?? []) {\n        cancelled.set(c.deletion.toIDString(), c.cancelledAt);\n      }\n      const entries: Array<LedgerEntry> = [];\n      const byKey = new Map<string, LedgerEntry>();\n      const live: Array<TimeTicket> = [];\n      for (const d of this.removals()) {\n        const key = d.toIDString();\n        if (byKey.has(key)) {\n          continue;\n        }\n        const entry: LedgerEntry = {\n          removal: d,\n          cancelledAt: cancelled.get(key),\n        };\n        entries.push(entry);\n        byKey.set(key, entry);\n        if (!entry.cancelledAt) {\n          live.push(d);\n        }\n      }\n      this.index = { entries, byKey, live, cancelled };\n    }\n    return this.index;\n  }\n\n  private recompute(): void {\n    let latest: TimeTicket | undefined;\n    for (const d of this.ledgerIndex().live) {\n      if (!latest || d.after(latest)) {\n        latest = d;\n      }\n    }\n    this.removedAt = latest;\n  }\n\n  /**\n   * `recordRemoval` adds a deletion to the ledger. A node's first removal is\n   * just `removedAt`; the ledger is built only when a second removal or a\n   * cancel needs it.\n   */\n  public recordRemoval(removedAt: TimeTicket): void {\n    if (!this.ledgered && !this.removedAt) {\n      this.removedAt = removedAt;\n      this.index = undefined;\n      return;\n    }\n    this.ledger();\n    // An actor removes a piece only while it is live in its view, so it never\n    // holds two uncancelled removals; a change whose vector leaves out its own\n    // earlier removal is not honest, and recording it would break the pairing\n    // `removal_events` relies on and grow the ledger.\n    const mine = this.uncancelledRemovalBy(removedAt.getActorID());\n    if (mine && !mine.equals(removedAt)) {\n      return;\n    }\n    const index = this.ledgerIndex();\n    const key = removedAt.toIDString();\n    if (!mine && !index.byKey.has(key)) {\n      this.dels!.push(removedAt);\n      const entry: LedgerEntry = { removal: removedAt };\n      index.entries.push(entry);\n      index.byKey.set(key, entry);\n      index.live.push(removedAt);\n    }\n    this.recompute();\n  }\n\n  /**\n   * `cancelRemoval` cancels one deletion (an undo of it). Returns whether the\n   * node is live afterwards.\n   */\n  public cancelRemoval(deletion: TimeTicket, at: TimeTicket): boolean {\n    this.ledger();\n    this.cancels = this.cancels ?? [];\n    const index = this.ledgerIndex();\n    const key = deletion.toIDString();\n    if (!index.cancelled.has(key)) {\n      this.cancels.push({ deletion, cancelledAt: at });\n      index.cancelled.set(key, at);\n      const entry = index.byKey.get(key);\n      if (entry) {\n        entry.cancelledAt = at;\n        const live = index.live.findIndex((d) => d.equals(deletion));\n        if (live !== -1) {\n          index.live.splice(live, 1);\n        }\n      }\n    }\n    this.recompute();\n    return !this.removedAt;\n  }\n\n  /**\n   * `pruneStable` drops each removal whose cancel is known to every replica,\n   * with that cancel. A change that arrives later knows both, so the pair\n   * never decides `isRemovedInView` again, and dropping it keeps an\n   * undo-heavy text from carrying every removal it ever had. A removal is\n   * older than its cancel by the same actor, so the cancel being known is\n   * enough. What is left is the default ledger once `removedAt` alone says\n   * it.\n   */\n  public pruneStable(vector: VersionVector): void {\n    const cancels: Array<LedgerCancel> = [];\n    const dropped = new Set<string>();\n    for (const c of this.cancels ?? []) {\n      if (!vector.afterOrEqual(c.cancelledAt)) {\n        cancels.push(c);\n        continue;\n      }\n      dropped.add(c.deletion.toIDString());\n    }\n    let dels = this.dels;\n    if (dropped.size && dels) {\n      dels = dels.filter((d) => !dropped.has(d.toIDString()));\n    }\n    this.dels = dels;\n    this.cancels = cancels;\n    this.index = undefined;\n    if (\n      !cancels.length &&\n      (!dels?.length ||\n        (dels.length === 1 &&\n          !!this.removedAt &&\n          dels[0].equals(this.removedAt)))\n    ) {\n      this.ledgered = false;\n      this.dels = undefined;\n      this.cancels = undefined;\n    }\n  }\n\n  /**\n   * `uncancelledRemovalBy` returns the removal by `actor` no undo cancelled,\n   * if any.\n   */\n  public uncancelledRemovalBy(actor: ActorID): TimeTicket | undefined {\n    for (const d of this.ledgerIndex().live) {\n      if (d.getActorID() === actor) {\n        return d;\n      }\n    }\n    return;\n  }\n\n  /**\n   * `heldFromPurge` tells whether GC must keep this tombstone under `vector`,\n   * the versions every replica has seen. A node removed by two or more\n   * deletions no undo cancelled stays: an undo of one of them must find it\n   * still held by the others, and a purged node could not say so. A node\n   * whose ledger is not yet stable stays too: every deletion and every cancel\n   * in it must be known to all replicas, so any change that arrives after the\n   * purge already knew them, and a node a restore recreates with only the\n   * removal it cancels answers `isRemovedInView` as the full ledger would.\n   * Once that holds and a single removal is left, a restore that finds the\n   * piece gone can only be cancelling that removal, and recreates it.\n   */\n  public heldFromPurge(vector: VersionVector): boolean {\n    if (!this.ledgered) {\n      return false;\n    }\n    // A cancelled deletion is older than its cancel by the same actor, so a\n    // stable cancel makes it stable too; an uncancelled one is `removedAt`,\n    // which GC checks first, or one of two that keep the node anyway.\n    const n = this.ledgerIndex().live.length;\n    for (const c of this.cancels ?? []) {\n      if (!vector.afterOrEqual(c.cancelledAt)) {\n        return true;\n      }\n    }\n    return n >= 2;\n  }\n\n  /**\n   * `isRemovedInView` tells whether the node was removed in the view of the\n   * given version vector: a deletion it knew that no undo it knew cancelled.\n   */\n  public isRemovedInView(vector: VersionVector): boolean {\n    for (const { removal, cancelledAt } of this.ledgerIndex().entries) {\n      if (!ticketKnown(vector, removal)) {\n        continue;\n      }\n      if (cancelledAt && ticketKnown(vector, cancelledAt)) {\n        continue;\n      }\n      return true;\n    }\n    return false;\n  }\n\n  /**\n   * `getRemovalEvents` returns the ledger as one list: every removal and\n   * every cancel's ticket except `removedAt`, in ticket order. Empty when\n   * `removedAt` says it all. An actor's events alternate in ticket order --\n   * it removes a piece only while the piece is live in its view, and its\n   * undo cancels its one uncancelled removal -- so `setRemovalEvents` can\n   * tell them apart by place.\n   */\n  public getRemovalEvents(): Array<TimeTicket> {\n    if (!this.ledgered) {\n      return [];\n    }\n    const events: Array<TimeTicket> = [];\n    for (const d of this.dels ?? []) {\n      if (!this.removedAt || !d.equals(this.removedAt)) {\n        events.push(d);\n      }\n    }\n    for (const c of this.cancels ?? []) {\n      events.push(c.cancelledAt);\n    }\n    return events.sort((a, b) => a.compare(b));\n  }\n\n  /**\n   * `setRemovalEvents` rebuilds the ledger from `removedAt` and the events\n   * `getRemovalEvents` returned: per actor, in ticket order, a removal then\n   * the cancel of it. It throws on a repeated ticket, which would pair a\n   * cancel with a removal that is not older, and when the result does not\n   * reproduce `removedAt`, and leaves the node as it was.\n   */\n  public setRemovalEvents(events: Array<TimeTicket>): void {\n    if (!events.length) {\n      return;\n    }\n    const removedAt = this.removedAt;\n    const all = events.slice();\n    if (removedAt) {\n      all.push(removedAt);\n    }\n    all.sort((a, b) => a.compare(b));\n    for (let i = 1; i < all.length; i++) {\n      if (all[i].equals(all[i - 1])) {\n        throw new YorkieError(\n          Code.ErrInvalidArgument,\n          'removal events repeat a ticket',\n        );\n      }\n    }\n\n    const dels: Array<TimeTicket> = [];\n    const cancels: Array<LedgerCancel> = [];\n    const open = new Map<ActorID, TimeTicket>();\n    for (const t of all) {\n      const d = open.get(t.getActorID());\n      if (d) {\n        cancels.push({ deletion: d, cancelledAt: t });\n        open.delete(t.getActorID());\n        continue;\n      }\n      dels.push(t);\n      open.set(t.getActorID(), t);\n    }\n\n    this.ledgered = true;\n    this.dels = dels;\n    this.cancels = cancels;\n    this.index = undefined;\n    this.recompute();\n    if (\n      !removedAt !== !this.removedAt ||\n      (removedAt && !removedAt.equals(this.removedAt!))\n    ) {\n      this.removedAt = removedAt;\n      this.ledgered = false;\n      this.dels = undefined;\n      this.cancels = undefined;\n      this.index = undefined;\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        'removal events do not reproduce removed_at',\n      );\n    }\n  }\n\n  /**\n   * `canDelete` checks if node is able to delete.\n   */\n  public canRemove(\n    editedAt: TimeTicket,\n    creationKnown: boolean,\n    tombstoneKnown: boolean,\n  ): boolean {\n    // NOTE(hackerwins): Skip if the node's creation was not visible to this\n    // operation.\n    if (!creationKnown) {\n      return false;\n    }\n\n    if (!this.removedAt) {\n      return true;\n    }\n\n    // NOTE(hackerwins): Overwrite only if prior tombstone was not known\n    // (concurrent or unseen) and newer. This enables LWW for concurrent deletions.\n    if (!tombstoneKnown && editedAt?.after(this.removedAt)) {\n      return true;\n    }\n    return false;\n  }\n\n  /**\n   * `canStyle` checks if node is able to set style.\n   *\n   * The only question is whether the styling change knew this node existed.\n   * It deliberately does NOT ask whether the node has since been removed, and\n   * that is a convergence requirement rather than a preference: a style is\n   * applied unconditionally on the replica that issues it — the node is live\n   * there, or the range would not have reached it — and can never be\n   * retracted afterwards. Every other replica has to apply it too.\n   *\n   * Any rule that reads `removedAt` is delivery-order dependent, because\n   * `removedAt` is last-writer-wins and MUTABLE: `canRemove` lets a removal\n   * the node has not seen overwrite it, while a style is evaluated once, when\n   * it arrives. Two clients deleting the same run concurrently plus a third\n   * styling over it is enough to make replicas disagree, and no single stored\n   * ticket fixes it — the replica cannot know which of the concurrent\n   * removals the styler had seen. The predicate has to not depend on removal\n   * state at all.\n   *\n   * The cost is that a style covers text the same client had already deleted,\n   * invisibly, so undoing the style and then the deletion brings the text back\n   * without the attributes it carried. That is the price of the replicas\n   * agreeing.\n   */\n  public canStyle(versionVector?: VersionVector): boolean {\n    return ticketKnown(versionVector, this.getCreatedAt());\n  }\n\n  /**\n   * `setRemovedAt` sets the remove time of this node. It drops the ledger.\n   */\n  public setRemovedAt(removedAt?: TimeTicket): void {\n    this.removedAt = removedAt;\n    this.ledgered = false;\n    this.dels = undefined;\n    this.cancels = undefined;\n    this.index = undefined;\n  }\n\n  /**\n   * `createRange` creates ranges of RGATreeSplitPos.\n   */\n  public createPosRange(): RGATreeSplitPosRange {\n    return [\n      RGATreeSplitPos.of(this.id, 0),\n      RGATreeSplitPos.of(this.id, this.getLength()),\n    ];\n  }\n\n  /**\n   * `getData` returns the data of this node.\n   */\n  public getDataSize(): DataSize {\n    const dataSize = this.value.getDataSize();\n\n    if (this.id) {\n      dataSize.meta += TimeTicketSize;\n    }\n\n    if (this.removedAt) {\n      dataSize.meta += TimeTicketSize;\n    }\n\n    return dataSize;\n  }\n\n  /**\n   * `deepcopy` returns a new instance of this RGATreeSplitNode without structural info.\n   */\n  public deepcopy(): RGATreeSplitNode<T> {\n    // The value has to be copied, not shared. `Document.ensureClone` builds\n    // the clone from the root, and every operation is applied to both; a\n    // shared value means the clone's split or style mutates the root as a\n    // side effect, and the root's own application then sees an already-mutated\n    // value. Go has always copied here.\n    const node = new RGATreeSplitNode(\n      this.id,\n      this.value.substring(0, this.value.length) as T,\n      this.removedAt,\n    );\n    node.copyLedger(this);\n    return node;\n  }\n\n  /**\n   * `toTestString` returns a String containing\n   * the meta data of the node for debugging purpose.\n   */\n  public toTestString(): string {\n    return `${this.id.toTestString()} ${this.value ? this.value : ''}`;\n  }\n\n  private splitValue(offset: number): T {\n    // Take the right part first -- `substring` deep-copies the attributes --\n    // then shorten this value IN PLACE rather than replacing it, so the GC\n    // pairs registered against it keep pointing at a live object.\n    const right = this.value.substring(offset, this.value.length) as T;\n    this.value.truncate(offset);\n    return right;\n  }\n\n  /**\n   * `toIDString` returns a string that can be used as an ID for this position.\n   */\n  public toIDString(): string {\n    return this.id.toIDString();\n  }\n}\n\n/**\n * `RGATreeSplit` is a block-based list with improved index-based lookup in RGA.\n * The difference from RGATreeList is that it has data on a block basis to\n * reduce the size of CRDT metadata. When an edit occurs on a block,\n * the block is split.\n *\n */\nexport class RGATreeSplit<T extends RGATreeSplitValue> implements GCParent {\n  private head: RGATreeSplitNode<T>;\n  private treeByIndex: SplayTree<T>;\n  private treeByID: LLRBTree<RGATreeSplitNodeID, RGATreeSplitNode<T>>;\n\n  /**\n   * `pendingGCPairs` buffers GC pairs for garbage that no `remove()` call\n   * produced: nodes created already-tombstoned by splitting a removed node,\n   * and attribute tombstones duplicated by a value copy (a split, or\n   * `restore` recreating a purged piece; see `bookCopiedAttrTombstones`).\n   * Either would otherwise never be registered for GC. Callers that split or\n   * restore nodes (`edit`, `CRDTText.setStyle`, `CRDTText.removeStyle`,\n   * `restore`) drain this buffer into their returned GC pairs.\n   */\n  private pendingGCPairs: Array<GCPair>;\n\n  /**\n   * `cancelled` holds the nodes whose ledger has a cancel, the only ones\n   * `pruneLedgers` can drop anything from. Undefined until first needed: a\n   * tree decoded from a snapshot or deep-copied fills it with one scan.\n   */\n  private cancelled?: Set<RGATreeSplitNode<T>>;\n\n  /**\n   * `trackCancelled` records that the ledger of `node` has a cancel.\n   */\n  private trackCancelled(node: RGATreeSplitNode<T>): void {\n    if (!this.cancelled) {\n      this.scanCancelled();\n    }\n    this.cancelled!.add(node);\n  }\n\n  private scanCancelled(): void {\n    this.cancelled = new Set();\n    for (let node: RGATreeSplitNode<T> | undefined = this.head; node; ) {\n      if (node.hasCancels()) {\n        this.cancelled.add(node);\n      }\n      node = node.getNext();\n    }\n  }\n\n  /**\n   * `hasCancelledRemovals` reports whether any node's ledger holds a cancel.\n   */\n  public hasCancelledRemovals(): boolean {\n    if (!this.cancelled) {\n      this.scanCancelled();\n    }\n    return this.cancelled!.size > 0;\n  }\n\n  /**\n   * `pruneLedgers` drops, from every node's ledger, the removals whose\n   * cancels the given vector covers (see `RGATreeSplitNode.pruneStable`). It\n   * returns how many nodes still hold a cancel.\n   */\n  public pruneLedgers(vector: VersionVector): number {\n    if (!this.cancelled) {\n      this.scanCancelled();\n    }\n    for (const node of this.cancelled!) {\n      node.pruneStable(vector);\n      if (!node.hasCancels()) {\n        this.cancelled!.delete(node);\n      }\n    }\n    return this.cancelled!.size;\n  }\n\n  constructor() {\n    this.head = RGATreeSplitNode.create(InitialRGATreeSplitNodeID);\n    this.treeByIndex = new SplayTree();\n    this.treeByID = new LLRBTree(RGATreeSplitNode.createComparator());\n    this.pendingGCPairs = [];\n\n    this.treeByIndex.insert(this.head);\n    this.treeByID.put(this.head.getID(), this.head);\n  }\n\n  /**\n   * `create` creates a instance RGATreeSplit.\n   */\n  public static create<T extends RGATreeSplitValue>(): RGATreeSplit<T> {\n    return new RGATreeSplit();\n  }\n\n  /**\n   * `edit` does following steps\n   * 1. split nodes with from and to\n   * 2. delete between from and to\n   * 3. insert a new node\n   * 4. add removed node\n   * @param range - range of RGATreeSplitNode\n   * @param editedAt - edited time\n   * @param value - value\n   * @returns `[RGATreeSplitPos, Array<GCPair>, DataSize, Array<ValueChange<T>>, Array<T>]`\n   */\n  public edit(\n    range: RGATreeSplitPosRange,\n    editedAt: TimeTicket,\n    value?: T,\n    versionVector?: VersionVector,\n  ): [\n    RGATreeSplitPos,\n    Array<GCPair>,\n    DataSize,\n    Array<ValueChange<T>>,\n    Array<T>,\n    Array<RestoreSpan<T>>,\n  ] {\n    const diff = { data: 0, meta: 0 };\n\n    // 01. split nodes with from and to\n    const [toLeft, diffTo, toRight] = this.findNodeWithSplit(\n      range[1],\n      editedAt,\n    );\n    const [fromLeft, diffFrom, fromRight] = this.findNodeWithSplit(\n      range[0],\n      editedAt,\n    );\n\n    addDataSizes(diff, diffTo, diffFrom);\n\n    // 02. delete between from and to\n    const nodesToDelete = this.findBetween(fromRight, toRight);\n    const [changes, removedNodes, alreadyRemovedIDs] = this.deleteNodes(\n      nodesToDelete,\n      editedAt,\n      versionVector,\n    );\n\n    const caretID = toRight ? toRight.getID() : toLeft.getID();\n    let caretPos = RGATreeSplitPos.of(caretID, 0);\n\n    // 03. insert a new node\n    if (value) {\n      const idx = this.posToIndex(fromLeft.createPosRange()[1], true);\n\n      const inserted = this.insertAfter(\n        fromLeft,\n        RGATreeSplitNode.create(RGATreeSplitNodeID.of(editedAt, 0), value),\n      );\n      addDataSizes(diff, inserted.getDataSize());\n\n      if (changes.length && changes[changes.length - 1].from === idx) {\n        changes[changes.length - 1].value = value;\n      } else {\n        changes.push({\n          actor: editedAt.getActorID(),\n          from: idx,\n          to: idx,\n          value,\n        });\n      }\n\n      caretPos = RGATreeSplitPos.of(\n        inserted.getID(),\n        inserted.getContentLength(),\n      );\n    }\n\n    // 04. add removed node\n    const pairs: Array<GCPair> = [];\n    const removedValues: Array<T> = [];\n    const removedSpans: Array<RestoreSpan<T>> = []; // NEW\n    for (const [id, removedNode] of removedNodes) {\n      // NOTE: Nodes that were already tombstoned keep their existing GC\n      // pair (the pair reads `removedAt` from the node at collection\n      // time); re-registering would toggle the pair off and leak the node.\n      if (!alreadyRemovedIDs.has(id)) {\n        pairs.push({ parent: this, child: removedNode });\n      }\n      removedValues.push(removedNode.getValue());\n      // NEW: capture split-invariant character identities. substring(0)\n      // deep-copies the value so later splits of the tombstone cannot\n      // mutate the captured content.\n      removedSpans.push({\n        createdAt: removedNode.getCreatedAt(),\n        start: removedNode.getID().getOffset(),\n        end: removedNode.getID().getOffset() + removedNode.getContentLength(),\n        value: removedNode.getValue().substring(0) as T,\n      });\n    }\n\n    pairs.push(...this.drainPendingGCPairs());\n\n    return [caretPos, pairs, diff, changes, removedValues, removedSpans];\n  }\n\n  /**\n   * `restore` re-establishes the characters described by `spans` under\n   * their ORIGINAL identities. For each span, per overlapping region:\n   *   - live piece exists       → skip (idempotent; another undo restored it)\n   *   - tombstoned piece exists → cancel the undoing actor's own removal; the\n   *                               piece revives unless another removal holds\n   *                               it\n   *   - no piece exists (GC'd)  → recreate a node with the original ID\n   *\n   * Returns [untombstonedNodes, recreatedNodes, changes, liveDiff,\n   * pendingGCPairs]. `changes` describes the revived content as insertions\n   * (ascending index) so editor bindings and remote sync can be driven\n   * the same way as a normal edit.\n   *\n   * The caller must, in order: (1) register every pair in `pendingGCPairs`\n   * — fragments `splitNode` buffered while isolating a target range out of\n   * a larger tombstoned piece, and attribute tombstones copied into split or\n   * recreated values (see `drainPendingGCPairs`);\n   * (2) unregister GC pairs for `untombstonedNodes`. Registering first is\n   * required for `untombstonedNodes` entries whose node was itself one of\n   * those split-born fragments (a target isolated from the interior of a\n   * tombstone) — such a node was never registered under its own id, so\n   * step (1) creates the entry that step (2) then correctly walks from gc\n   * back to live; entries that remain tombstoned (siblings of the\n   * restored target) simply stay registered. Finally, `root.acc(liveDiff)`\n   * accounts the size of any nodes recreated from scratch (the GC'd-away\n   * case), which `splitNode`'s buffering does not cover.\n   */\n  public restore(\n    spans: Array<RestoreSpan<T>>,\n    executedAt: TimeTicket,\n    fallbackAnchor?: RGATreeSplitPos,\n  ): [\n    Array<RGATreeSplitNode<T>>,\n    Array<RGATreeSplitNode<T>>,\n    Array<ValueChange<T>>,\n    DataSize,\n    Array<GCPair>,\n  ] {\n    const untombstoned: Array<RGATreeSplitNode<T>> = [];\n    const recreated: Array<RGATreeSplitNode<T>> = [];\n    const liveDiff = { data: 0, meta: 0 };\n\n    // The last node placed at the current cursor (un-tombstoned or recreated),\n    // in document order. When a recreated fragment has no surviving same-\n    // insertion anchor, chaining after this keeps a multi-fragment run in\n    // left-to-right order instead of each fragment prepending at the same fixed\n    // fallback anchor — which would rebuild the run reversed. Spans arrive in\n    // document order, so this is always the recreated fragment's left neighbour.\n    let chainAnchor: RGATreeSplitNode<T> | undefined;\n    for (const span of spans) {\n      const pieces = this.findPiecesOverlapping(\n        span.createdAt,\n        span.start,\n        span.end,\n      );\n\n      let cursor = span.start;\n      let pieceIdx = 0;\n      while (cursor < span.end) {\n        const piece = pieces[pieceIdx];\n        const pieceStart = piece ? piece.getID().getOffset() : Infinity;\n        const pieceEnd = piece\n          ? pieceStart + piece.getContentLength()\n          : Infinity;\n\n        if (piece && pieceStart <= cursor) {\n          // Covered by an existing piece.\n          const overlapEnd = Math.min(pieceEnd, span.end);\n          if (piece.isRemoved()) {\n            const [target] = this.isolateRange(piece, cursor, overlapEnd);\n            // An undo reverses its own actor's change, so the removal it\n            // cancels is the one uncancelled removal by that actor: one actor\n            // cannot remove a piece already removed in its view. No other\n            // removal holds it if there is none.\n            let live = false;\n            const d = target.uncancelledRemovalBy(executedAt.getActorID());\n            if (d) {\n              live = target.cancelRemoval(d, executedAt);\n              this.trackCancelled(target);\n            }\n            if (live) {\n              // Repair splay weights on the path to root (length 0 → len).\n              this.treeByIndex.splayNode(target);\n              untombstoned.push(target);\n            }\n            chainAnchor = target;\n          } else {\n            chainAnchor = piece;\n          }\n          cursor = overlapEnd;\n          if (overlapEnd >= pieceEnd) {\n            pieceIdx++;\n          }\n        } else {\n          // Gap: recreate [cursor, gapEnd) with its original ID. A purged\n          // piece had a single uncancelled removal, stable on every replica\n          // (see `heldFromPurge`), so this restore can only be cancelling that\n          // one.\n          const gapEnd = Math.min(pieceStart, span.end);\n          const value = span.value.substring(\n            cursor - span.start,\n            gapEnd - span.start,\n          ) as T;\n          const newNode = RGATreeSplitNode.create(\n            RGATreeSplitNodeID.of(span.createdAt, cursor),\n            value,\n          );\n          // The purged removal was known to every replica before the purge,\n          // so every change that can arrive later knows it. A stand-in removal\n          // by the same actor at lamport 0, which every such change's vector\n          // covers, keeps that answer for `isRemovedInView`, with this cancel.\n          // The pair is dropped once the cancel is known everywhere\n          // (`pruneStable`); until then snapshots carry it, as Go records the\n          // same.\n          const stable = TimeTicket.of(0n, 0, executedAt.getActorID());\n          newNode.recordRemoval(stable);\n          newNode.cancelRemoval(stable, executedAt);\n          this.trackCancelled(newNode);\n          // `substring` deep-copied the span's attributes, tombstones\n          // included, exactly as a split does. Book them here for the same\n          // reason `splitNode` does -- see `bookCopiedAttrTombstones`. The\n          // buffer is drained below into this call's returned pairs.\n          this.bookCopiedAttrTombstones(value);\n          addDataSizes(liveDiff, newNode.getDataSize());\n          const prev = this.findRestoreAnchor(\n            span.createdAt,\n            cursor,\n            gapEnd,\n            executedAt,\n            fallbackAnchor,\n            chainAnchor,\n          );\n          this.insertAfter(prev, newNode);\n          // `insertAfter` only maintains the physical prev/next chain. Relink\n          // the separate insertion chain (`insPrev`/`insNext`) too, the same\n          // way `splitNode` does, so a recreated interior fragment is not\n          // skipped by the surviving same-insertion neighbours. Otherwise a\n          // later edit whose boundary lands on this fragment resolves through\n          // a stale insertion pointer in `findFloorNodePreferToLeft` and\n          // miscomputes its offset (yorkie-team/yorkie-js-sdk#1327).\n          //\n          // The neighbours are the nearest surviving pieces, not just the\n          // ones covering the adjacent offsets: with the piece before the gap\n          // purged too, the one before that would keep pointing past the new\n          // fragment, and purging it later would hand the piece after the gap\n          // an `insPrev` that skips the fragment.\n          if (cursor > 0) {\n            const prevID = RGATreeSplitNodeID.of(span.createdAt, cursor - 1);\n            const insPrev = this.treeByID.floorEntry(prevID);\n            if (insPrev && insPrev.key.hasSameCreatedAt(prevID)) {\n              newNode.setInsPrev(insPrev.value);\n            }\n          }\n          const nextID = RGATreeSplitNodeID.of(span.createdAt, gapEnd);\n          const insNext = this.treeByID.ceilingEntry(nextID);\n          if (insNext && insNext.key.hasSameCreatedAt(nextID)) {\n            newNode.setInsNext(insNext.value);\n          }\n          recreated.push(newNode);\n          chainAnchor = newNode;\n          cursor = gapEnd;\n        }\n      }\n    }\n\n    const pendingGCPairs = this.drainPendingGCPairs();\n\n    // Revived nodes are now live; report each as an insertion at its final\n    // index. Ascending order keeps the indices valid when applied in\n    // sequence (each earlier insertion is already present).\n    const changes: Array<ValueChange<T>> = [];\n    for (const node of [...untombstoned, ...recreated]) {\n      const [from] = this.findIndexesFromRange(node.createPosRange());\n      changes.push({\n        actor: executedAt.getActorID(),\n        from,\n        to: from,\n        value: node.getValue(),\n      });\n    }\n    changes.sort((a, b) => a.from - b.from);\n\n    return [untombstoned, recreated, changes, liveDiff, pendingGCPairs];\n  }\n\n  /**\n   * `retombstone` re-deletes the characters described by `spans` (redo of\n   * an identity-preserving undo). Only pieces live in the redo's view are\n   * affected: a piece removed in that view, or purged, is skipped\n   * (idempotent), and a piece removed here by a deletion the redo never saw\n   * records the redo without being re-tombstoned.\n   *\n   * Returns [pairs, changes, diff, recorded]: GCPairs for the newly\n   * tombstoned nodes and the born-dead remainders the splits left behind,\n   * the removed regions as deletions so editor bindings and remote sync can\n   * be driven the same way as a normal edit, the metadata-size overhead from\n   * splitting the (live) pieces to isolate the target range, and the pieces\n   * the removal was recorded on, which the reverse has to name. The caller\n   * must `root.acc(diff)` before registering `pairs`, mirroring how a normal\n   * edit's boundary splits are accounted before its resulting tombstones are\n   * registered. Indices are captured before each removal, so applying them\n   * in emission order stays consistent.\n   */\n  public retombstone(\n    spans: Array<RestoreSpan<T>>,\n    executedAt: TimeTicket,\n    versionVector?: VersionVector,\n  ): [Array<GCPair>, Array<ValueChange<T>>, DataSize, Array<RestoreSpan<T>>] {\n    const pairs: Array<GCPair> = [];\n    const changes: Array<ValueChange<T>> = [];\n    const diff = { data: 0, meta: 0 };\n    // The pieces the removal was recorded on, which the reverse names: a\n    // restore never reaches a piece that holds no removal by its actor.\n    const recorded: Array<RestoreSpan<T>> = [];\n    const record = (span: RestoreSpan<T>, target: RGATreeSplitNode<T>) => {\n      const start = target.getID().getOffset();\n      const end = start + target.getContentLength();\n      recorded.push({\n        createdAt: span.createdAt,\n        start,\n        end,\n        value: span.value.substring(start - span.start, end - span.start) as T,\n      });\n    };\n\n    for (const span of spans) {\n      const pieces = this.findPiecesOverlapping(\n        span.createdAt,\n        span.start,\n        span.end,\n      );\n      for (const piece of pieces) {\n        if (piece.isRemoved()) {\n          // A piece live in the redo's view but removed here by a deletion\n          // the redo never saw still records the redo's deletion, so a later\n          // undo of that other deletion keeps it removed.\n          if (\n            versionVector &&\n            versionVector.size() &&\n            !piece.isRemovedInView(versionVector)\n          ) {\n            const pieceStart = piece.getID().getOffset();\n            const pieceEnd = pieceStart + piece.getContentLength();\n            const [target] = this.isolateRange(\n              piece,\n              Math.max(pieceStart, span.start),\n              Math.min(pieceEnd, span.end),\n            );\n            target.recordRemoval(executedAt);\n            record(span, target);\n          }\n          continue;\n        }\n        // A piece live here but removed in the redo's view (by a deletion\n        // whose undo the redo never saw) is left alone, as the redoing\n        // replica left it: like a deletion, a redo removes only what was\n        // live in its view.\n        if (\n          versionVector &&\n          versionVector.size() &&\n          piece.isRemovedInView(versionVector)\n        ) {\n          continue;\n        }\n        const pieceStart = piece.getID().getOffset();\n        const pieceEnd = pieceStart + piece.getContentLength();\n        const [target, splitDiff] = this.isolateRange(\n          piece,\n          Math.max(pieceStart, span.start),\n          Math.min(pieceEnd, span.end),\n        );\n        // `piece` was live, so the split overhead belongs to the live\n        // bucket, same as a normal edit's boundary splits.\n        addDataSizes(diff, splitDiff);\n        // Capture the visible range while `target` is still live.\n        const [from, to] = this.findIndexesFromRange(target.createPosRange());\n        target.recordRemoval(executedAt);\n        record(span, target);\n        this.treeByIndex.splayNode(target);\n        pairs.push({ parent: this, child: target });\n        if (from < to) {\n          changes.push({ actor: executedAt.getActorID(), from, to });\n        }\n      }\n    }\n\n    // Isolating a range inside an already-tombstoned piece buffers born-dead\n    // remainders, and a split books the attribute tombstones it copies. Hand\n    // them to the caller with the rest: unregistered, they would never be\n    // purged and their size would stay uncharged.\n    pairs.push(...this.drainPendingGCPairs());\n\n    return [pairs, changes, diff, recorded];\n  }\n\n  /**\n   * `refreshSpans` re-snapshots `spans` against the content they address as it\n   * stands now, returning an equivalent span set (same insertion identities,\n   * same overall intervals) whose values carry the current attributes. A span\n   * is captured when the edit it reverses runs, so attributes applied to the\n   * run afterwards — a peer's style, which `canStyle` admits even on a\n   * tombstone — are missing from it; a replica that purged the run would then\n   * recreate it with the stale snapshot while a replica that still holds the\n   * tombstone revives the live attributes, and the two diverge.\n   *\n   * Regions covered by a surviving piece (live or tombstoned) are taken from\n   * that piece, so a span crossing several pieces splits into one span per\n   * piece. Regions with no surviving piece keep the original snapshot — it is\n   * all this replica knows about them. Read-only: the copies it makes are\n   * payload, never inserted, so they book no attribute tombstones.\n   */\n  public refreshSpans(spans: Array<RestoreSpan<T>>): Array<RestoreSpan<T>> {\n    const refreshed: Array<RestoreSpan<T>> = [];\n    const fromSnapshot = (span: RestoreSpan<T>, start: number, end: number) =>\n      refreshed.push({\n        createdAt: span.createdAt,\n        start,\n        end,\n        value: span.value.substring(start - span.start, end - span.start) as T,\n      });\n\n    for (const span of spans) {\n      const pieces = this.findPiecesOverlapping(\n        span.createdAt,\n        span.start,\n        span.end,\n      );\n      let cursor = span.start;\n      for (const piece of pieces) {\n        const pieceStart = piece.getID().getOffset();\n        const start = Math.max(pieceStart, cursor);\n        const end = Math.min(pieceStart + piece.getContentLength(), span.end);\n        if (end <= start) {\n          continue;\n        }\n        if (start > cursor) {\n          fromSnapshot(span, cursor, start);\n        }\n        refreshed.push({\n          createdAt: span.createdAt,\n          start,\n          end,\n          value: piece\n            .getValue()\n            .substring(start - pieceStart, end - pieceStart) as T,\n        });\n        cursor = end;\n      }\n      if (cursor < span.end) {\n        fromSnapshot(span, cursor, span.end);\n      }\n    }\n\n    return refreshed;\n  }\n\n  /**\n   * `findPiecesOverlapping` collects existing nodes (live or tombstoned)\n   * belonging to the insertion `createdAt` that overlap the absolute-offset\n   * interval [start, end), in ascending offset order. Works by descending\n   * floorEntry probes over treeByID.\n   */\n  private findPiecesOverlapping(\n    createdAt: TimeTicket,\n    start: number,\n    end: number,\n  ): Array<RGATreeSplitNode<T>> {\n    const pieces: Array<RGATreeSplitNode<T>> = [];\n    let probe = end - 1;\n\n    while (probe >= 0) {\n      const key = RGATreeSplitNodeID.of(createdAt, probe);\n      const entry = this.treeByID.floorEntry(key);\n      if (!entry || !entry.key.hasSameCreatedAt(key)) {\n        break;\n      }\n      const node = entry.value;\n      const nodeStart = node.getID().getOffset();\n      const nodeEnd = nodeStart + node.getContentLength();\n      if (nodeEnd <= start) {\n        break;\n      }\n      if (nodeStart < end && nodeEnd > start) {\n        pieces.push(node);\n      }\n      if (nodeStart <= start) {\n        break;\n      }\n      probe = nodeStart - 1;\n    }\n\n    return pieces.reverse();\n  }\n\n  /**\n   * `findPieceCovering` returns the node of insertion `createdAt` whose\n   * absolute-offset range covers `offset`, if present.\n   */\n  private findPieceCovering(\n    createdAt: TimeTicket,\n    offset: number,\n  ): RGATreeSplitNode<T> | undefined {\n    const key = RGATreeSplitNodeID.of(createdAt, offset);\n    const entry = this.treeByID.floorEntry(key);\n    if (!entry || !entry.key.hasSameCreatedAt(key)) {\n      return;\n    }\n    const node = entry.value;\n    const nodeStart = node.getID().getOffset();\n    const nodeEnd = nodeStart + node.getContentLength();\n    if (nodeStart <= offset && offset < nodeEnd) {\n      return node;\n    }\n    return;\n  }\n\n  /**\n   * `findRestoreAnchor` returns the physical node to insert a recreated\n   * fragment [gapStart, gapEnd) of insertion `createdAt` AFTER.\n   *\n   * Resolution ladder (all rules key on op-carried data + ID lookups only):\n   *  (a) a piece covering gapEnd exists → directly before it\n   *      (originally-adjacent successor; exact original slot)\n   *  (b) nearest surviving piece of the same insertion left of gapStart\n   *      → directly after it\n   *  (c) nearest surviving piece of the same insertion at or after gapEnd\n   *      → directly before it\n   *  (d) chain anchor: the previously placed fragment of this same restore\n   *      (document order) → after it, so a purged multi-fragment run is\n   *      rebuilt left-to-right rather than reversed\n   *  (e) the operation's fallback anchor (refined) — same exposure as the\n   *      current implementation's fromPos; see design-doc caveat\n   *  (f) head (deterministic last resort)\n   */\n  private findRestoreAnchor(\n    createdAt: TimeTicket,\n    gapStart: number,\n    gapEnd: number,\n    executedAt: TimeTicket,\n    fallbackAnchor?: RGATreeSplitPos,\n    chainAnchor?: RGATreeSplitNode<T>,\n  ): RGATreeSplitNode<T> {\n    const succ = this.findPieceCovering(createdAt, gapEnd);\n    if (succ) {\n      return succ.getPrev()!;\n    }\n\n    if (gapStart > 0) {\n      const key = RGATreeSplitNodeID.of(createdAt, gapStart - 1);\n      const entry = this.treeByID.floorEntry(key);\n      if (entry && entry.key.hasSameCreatedAt(key)) {\n        return entry.value;\n      }\n    }\n\n    // The nearest surviving piece of the insertion after the gap, not the\n    // rightmost one: anchoring before a later piece would place the gap after\n    // the pieces in between, and a deletion that later spans from the gap to\n    // one of them would run from its start to the end of the text.\n    const afterKey = RGATreeSplitNodeID.of(createdAt, gapEnd);\n    const after = this.treeByID.ceilingEntry(afterKey);\n    if (after && after.key.hasSameCreatedAt(afterKey)) {\n      return after.value.getPrev()!;\n    }\n\n    // (d) No surviving piece of this insertion anchors the fragment. When the\n    // whole run was purged, every fragment lands here; anchoring after the\n    // fragment placed just before it (document order) keeps the run forward.\n    if (chainAnchor) {\n      return chainAnchor;\n    }\n\n    if (fallbackAnchor) {\n      try {\n        const refined = this.refinePos(fallbackAnchor);\n        const [left] = this.findNodeWithSplit(refined, executedAt);\n        return left;\n      } catch {\n        // anchor fully purged — fall through to (e)\n      }\n    }\n\n    return this.head;\n  }\n\n  /**\n   * `isolateRange` splits `piece` so that a node exactly covering the\n   * absolute-offset interval [from, to) exists, and returns it along with\n   * the net metadata-size overhead the split(s) introduced.\n   *\n   * When `piece` is live, this overhead is a normal live-bucket cost (same\n   * as any other boundary split) and the caller should `root.acc` it.\n   * When `piece` is tombstoned, `splitNode` itself buffers the overhead of\n   * any born-removed fragment via `pendingGCPairs` (see `drainPendingGCPairs`),\n   * so the returned diff is zero in that case — the caller must still\n   * drain and register those pairs.\n   *\n   * Requires: pieceStart <= from < to <= pieceEnd.\n   */\n  private isolateRange(\n    piece: RGATreeSplitNode<T>,\n    from: number,\n    to: number,\n  ): [RGATreeSplitNode<T>, DataSize] {\n    const diff = { data: 0, meta: 0 };\n    let node = piece;\n    const nodeStart = node.getID().getOffset();\n    if (from > nodeStart) {\n      const [right, splitDiff] = this.splitNode(node, from - nodeStart);\n      addDataSizes(diff, splitDiff);\n      node = right as RGATreeSplitNode<T>;\n    }\n    const newStart = node.getID().getOffset();\n    if (to < newStart + node.getContentLength()) {\n      const [, splitDiff] = this.splitNode(node, to - newStart);\n      addDataSizes(diff, splitDiff);\n    }\n    return [node, diff];\n  }\n\n  /**\n   * `indexToPos` finds RGATreeSplitPos of given offset.\n   */\n  public indexToPos(idx: number): RGATreeSplitPos {\n    const [node, offset] = this.treeByIndex.findForText(idx);\n    const splitNode = node as RGATreeSplitNode<T>;\n    return RGATreeSplitPos.of(splitNode.getID(), offset);\n  }\n\n  /**\n   * `findIndexesFromRange` finds indexes based on range.\n   */\n  public findIndexesFromRange(range: RGATreeSplitPosRange): [number, number] {\n    const [fromPos, toPos] = range;\n    return [this.posToIndex(fromPos, false), this.posToIndex(toPos, true)];\n  }\n\n  /**\n   * `posToIndex` converts the given position to index.\n   */\n  public posToIndex(pos: RGATreeSplitPos, preferToLeft: boolean): number {\n    const absoluteID = pos.getAbsoluteID();\n    const node = preferToLeft\n      ? this.findFloorNodePreferToLeft(absoluteID)\n      : this.findFloorNode(absoluteID);\n    if (!node) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `the node of the given id should be found: ${absoluteID.toTestString()}`,\n      );\n    }\n    const index = this.treeByIndex.indexOf(node!);\n    const offset = node!.isRemoved()\n      ? 0\n      : absoluteID.getOffset() - node!.getID().getOffset();\n    return index + offset;\n  }\n\n  /**\n   * `findNode` finds node of given id.\n   */\n  public findNode(id: RGATreeSplitNodeID): RGATreeSplitNode<T> {\n    return this.findFloorNode(id)!;\n  }\n\n  /**\n   * `length` returns size of RGATreeSplit.\n   */\n  public get length(): number {\n    return this.treeByIndex.length;\n  }\n\n  /**\n   * `getTreeByIndex` returns the tree by index for debugging purpose.\n   */\n  public getTreeByIndex(): SplayTree<T> {\n    return this.treeByIndex;\n  }\n\n  /**\n   * `getTreeByID` returns the tree by ID for debugging purpose.\n   */\n  public getTreeByID(): LLRBTree<RGATreeSplitNodeID, RGATreeSplitNode<T>> {\n    return this.treeByID;\n  }\n\n  /**\n   * `toString` returns the string encoding of this RGATreeSplit.\n   */\n  public toString(): string {\n    const str = [];\n\n    for (const node of this) {\n      if (!node.isRemoved()) {\n        str.push(node.getValue());\n      }\n    }\n\n    return str.join('');\n  }\n\n  // eslint-disable-next-line jsdoc/require-jsdoc\n  public *[Symbol.iterator](): IterableIterator<RGATreeSplitNode<T>> {\n    let node = this.head.getNext();\n    while (node) {\n      yield node;\n      node = node.getNext();\n    }\n  }\n\n  /**\n   * `getHead` returns head of RGATreeSplitNode.\n   */\n  public getHead(): RGATreeSplitNode<T> {\n    return this.head;\n  }\n\n  /**\n   * `deepcopy` copies itself deeply.\n   */\n  public deepcopy(): RGATreeSplit<T> {\n    const clone = new RGATreeSplit<T>();\n\n    let node = this.head.getNext();\n\n    let prev = clone.head;\n    let current;\n    while (node) {\n      current = clone.insertAfter(prev, node.deepcopy());\n      if (node.hasInsPrev()) {\n        const insPrevNode = clone.findNode(node.getInsPrevID());\n        current.setInsPrev(insPrevNode);\n      }\n\n      prev = current;\n      node = node.getNext();\n    }\n\n    return clone;\n  }\n\n  /**\n   * `normalizePos` converts a local position `(id, rel)` into a single\n   * absolute offset measured from the head `(0:0)` of the physical chain.\n   *\n   * The offset is the live length of every node before the floor node of\n   * `id`, plus `rel`. It used to be summed over the `prev` chain; it is now\n   * read from `treeByIndex`, which holds the same sum: every node on the\n   * chain is in it, in chain order, weighted by its live length (a tombstone\n   * stays in with weight zero; only `purge` takes a node out, and `purge`\n   * unlinks it from the chain and from `treeByID` too). Every Edit execution\n   * calls this, so a linear walk here makes typing a document quadratic.\n   *\n   * This is a one-to-one port of the Go implementation (yorkie#2107), and the\n   * result is the chain walk's result for every input, including a floor\n   * lookup that lands on an earlier piece: `rel` is added in the id space of\n   * the floor node, not resolved through `getAbsoluteID`. Resolution stays\n   * the same on purpose - `Document.applyChangeInternal` reconciles the undo\n   * stacks against these offsets, so they must agree with what every other\n   * replica, Go included, computes.\n   */\n  public normalizePos(pos: RGATreeSplitPos): RGATreeSplitPos {\n    const node = this.findFloorNode(pos.getID());\n    if (!node) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `the node of the given id should be found: ${pos.getID().toTestString()}`,\n      );\n    }\n\n    // A node `findFloorNode` returns is always in `treeByIndex` (see above),\n    // so `indexOf` cannot answer -1 here. Go rejects it the same way.\n    const index = this.treeByIndex.indexOf(node);\n    if (index < 0) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `the node of the given id should be indexed: ${pos.getID().toTestString()}`,\n      );\n    }\n\n    return RGATreeSplitPos.of(\n      this.head.getID(),\n      index + pos.getRelativeOffset(),\n    );\n  }\n\n  /**\n   * `refinePos` remaps the given pos to the current split chain.\n   *\n   * - Traverses the physical `next` chain (not `insNext`).\n   * - Counts only live characters: removed nodes are treated as length 0.\n   * - If the given offset exceeds the length of the current node,\n   *   it moves forward through `next` nodes, subtracting lengths,\n   *   until the offset fits in a live node.\n   * - If it runs out of nodes, it snaps to the end of the last node.\n   *\n   * Example:\n   *   Before split: [\"12345\"](1:2:0), pos = (1:2:0, rel=5)\n   *   After split : [\"1\"](1:2:0) - [\"23\"](1:2:1) - [\"45\"](1:2:3)\n   *   refinePos(pos) -> (1:2:3, rel=2)\n   *\n   * Example:\n   *   [\"12\"](1:2:0, live) and pos = (1:2:0, rel=4)\n   *   refinePos(pos) -> points two chars after \"12\",\n   *   i.e. advances into following nodes, skipping removed ones.\n   */\n  public refinePos(pos: RGATreeSplitPos): RGATreeSplitPos {\n    let node = this.findFloorNode(pos.getID());\n    if (!node) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `the node of the given id should be found: ${pos.getID().toTestString()}`,\n      );\n    }\n\n    let offsetInPart = pos.getRelativeOffset();\n    let partLen = node.getContentLength();\n\n    while (offsetInPart > partLen) {\n      offsetInPart -= partLen;\n      const next: RGATreeSplitNode<T> | undefined = node!.getNext();\n\n      if (!next) {\n        return RGATreeSplitPos.of(node.getID(), partLen);\n      }\n\n      node = next;\n      partLen = node.getLength();\n    }\n\n    return RGATreeSplitPos.of(node.getID(), offsetInPart);\n  }\n\n  /**\n   * `toTestString` returns a String containing the meta data of the node\n   * for debugging purpose.\n   */\n  public toTestString(): string {\n    const result = [];\n\n    let node: RGATreeSplitNode<T> | undefined = this.head;\n    while (node) {\n      if (node.isRemoved()) {\n        result.push(`{${node.toTestString()}}`);\n      } else {\n        result.push(`[${node.toTestString()}]`);\n      }\n\n      node = node.getNext();\n    }\n\n    return result.join('');\n  }\n\n  /**\n   * `insertAfter` inserts the given node after the given previous node.\n   */\n  public insertAfter(\n    prevNode: RGATreeSplitNode<T>,\n    newNode: RGATreeSplitNode<T>,\n  ): RGATreeSplitNode<T> {\n    const next = prevNode.getNext();\n    newNode.setPrev(prevNode);\n    if (next) {\n      next.setPrev(newNode);\n    }\n\n    this.treeByID.put(newNode.getID(), newNode);\n    this.treeByIndex.insertAfter(prevNode, newNode);\n\n    return newNode;\n  }\n\n  /**\n   * `findNodeWithSplit` splits and return nodes of the given position.\n   */\n  public findNodeWithSplit(\n    pos: RGATreeSplitPos,\n    editedAt: TimeTicket,\n  ): [RGATreeSplitNode<T>, DataSize, RGATreeSplitNode<T>] {\n    const absoluteID = pos.getAbsoluteID();\n    let node = this.findFloorNodePreferToLeft(absoluteID);\n    const relativeOffset = absoluteID.getOffset() - node.getID().getOffset();\n\n    const [, diff] = this.splitNode(node, relativeOffset);\n\n    while (node.hasNext() && node.getNext()!.getCreatedAt().after(editedAt)) {\n      node = node.getNext()!;\n    }\n\n    return [node, diff, node.getNext()!];\n  }\n\n  private findFloorNodePreferToLeft(\n    id: RGATreeSplitNodeID,\n  ): RGATreeSplitNode<T> {\n    let node = this.findFloorNode(id);\n    if (!node) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `the node of the given id should be found: ${id.toTestString()}`,\n      );\n    }\n\n    if (id.getOffset() > 0 && node!.getID().getOffset() == id.getOffset()) {\n      // NOTE: InsPrev may not be present due to GC.\n      if (!node!.hasInsPrev()) {\n        return node!;\n      }\n      node = node!.getInsPrev();\n    }\n\n    return node!;\n  }\n\n  private findFloorNode(\n    id: RGATreeSplitNodeID,\n  ): RGATreeSplitNode<T> | undefined {\n    const entry = this.treeByID.floorEntry(id);\n    if (!entry) {\n      return;\n    }\n\n    if (!entry.key.equals(id) && !entry.key.hasSameCreatedAt(id)) {\n      return;\n    }\n\n    return entry.value;\n  }\n\n  /**\n   * `findBetween` returns nodes between fromNode and toNode.\n   */\n  public findBetween(\n    fromNode: RGATreeSplitNode<T>,\n    toNode: RGATreeSplitNode<T>,\n  ): Array<RGATreeSplitNode<T>> {\n    const nodes = [];\n\n    let current: RGATreeSplitNode<T> | undefined = fromNode;\n    while (current && current !== toNode) {\n      nodes.push(current);\n      current = current.getNext();\n    }\n\n    return nodes;\n  }\n\n  private splitNode(\n    node: RGATreeSplitNode<T>,\n    offset: number,\n  ): [RGATreeSplitNode<T> | undefined, DataSize] {\n    const diff = { data: 0, meta: 0 };\n\n    // A negative offset is as out of range as one past the end, and is\n    // rejected the same way. `findNodeWithSplit` derives the offset by\n    // subtracting the node's own offset from the position's, so a position\n    // resolved through an `insPrev` link into a node of a HIGHER offset --\n    // which only a forged link can produce, since every link points at an\n    // earlier piece of the same insertion -- arrives here negative. `split`\n    // would not notice: `substring`/`truncate` clamp a negative to zero, which\n    // empties the live node and inserts a duplicate of it under a rolled-back\n    // id, diverging this replica from the others in silence.\n    if (offset < 0 || offset > node.getContentLength()) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `offset should be between 0 and the length of the node`,\n      );\n    }\n\n    if (offset === 0) {\n      return [node, diff];\n    } else if (offset === node.getContentLength()) {\n      return [node.getNext(), diff];\n    }\n\n    const prvSize = node.getDataSize();\n\n    const splitNode = node.split(offset);\n    if (splitNode.hasCancels()) {\n      this.cancelled?.add(splitNode);\n    }\n    this.treeByIndex.updateWeight(splitNode);\n    this.insertAfter(node, splitNode);\n\n    const insNext = node.getInsNext();\n    if (insNext) {\n      insNext.setInsPrev(splitNode);\n    }\n    splitNode.setInsPrev(node);\n\n    // NOTE(hackerwins): Calculate data size after node splitting:\n    // Take the sum of the two split nodes(left and right) minus the size of\n    // the original node. This calculates the net metadata overhead added by\n    // the split operation.\n    addDataSizes(diff, node.getDataSize(), splitNode.getDataSize());\n    subDataSize(diff, prvSize);\n\n    // A split deep-copies the value's attributes, so every tombstone among\n    // them is duplicated under the new node.\n    this.bookCopiedAttrTombstones(splitNode.getValue());\n\n    // NOTE: A piece split off an already-tombstoned node inherits\n    // `removedAt` without going through `remove()`, so no GC pair is\n    // created for it in the normal deletion path. Buffer one here so it\n    // can be purged; otherwise it stays in the list forever. The piece\n    // was never live, so the net-new size created by the split goes\n    // straight to docSize.gc when the pair is registered; report a zero\n    // diff to the caller (which accounts diffs to docSize.live).\n    if (splitNode.isRemoved()) {\n      this.pendingGCPairs.push({\n        parent: this,\n        child: splitNode,\n        gcOnlySize: diff,\n      });\n      return [splitNode, { data: 0, meta: 0 }];\n    }\n\n    return [splitNode, diff];\n  }\n\n  /**\n   * `bookCopiedAttrTombstones` registers the attribute tombstones a freshly\n   * copied value has just duplicated. `CRDTTextValue.substring` -- which both\n   * `splitNode` and `restore`'s recreate path go through -- deep-copies the\n   * whole RHT, tombstones included; it has to, or a piece would resolve a\n   * concurrent style differently from a replica that never split or never lost\n   * it. Each copy is a fresh piece of garbage under a new parent with no\n   * registration of its own: the original's pair names the original's parent,\n   * so without this the copy sits in the RHT forever, uncounted and\n   * unpurgeable. The copy was never in `docSize.live` -- `getDataSize` excludes\n   * removed attributes -- so `gcOnlySize` charges it to gc alone, and `purge`\n   * subtracts the same size back out.\n   */\n  private bookCopiedAttrTombstones(value: T): void {\n    this.pendingGCPairs.push(...(value.getGCPairs?.() ?? []));\n  }\n\n  /**\n   * `drainPendingGCPairs` returns the GC pairs buffered in `pendingGCPairs`\n   * and clears the buffer.\n   */\n  public drainPendingGCPairs(): Array<GCPair> {\n    const pairs = this.pendingGCPairs;\n    this.pendingGCPairs = [];\n    return pairs;\n  }\n\n  private deleteNodes(\n    candidates: Array<RGATreeSplitNode<T>>,\n    editedAt: TimeTicket,\n    vector?: VersionVector,\n  ): [Array<ValueChange<T>>, Map<string, RGATreeSplitNode<T>>, Set<string>] {\n    if (!candidates.length) {\n      return [[], new Map(), new Set()];\n    }\n\n    const isLocal = vector === undefined || vector.size() === 0;\n\n    // 01. Collect nodes to remove and keep.\n    const nodesToRemove: Array<RGATreeSplitNode<T>> = [];\n    const nodesToKeep: Array<RGATreeSplitNode<T> | undefined> = [];\n    const [leftEdge, rightEdge] = this.findEdgesOfCandidates(candidates);\n    nodesToKeep.push(leftEdge);\n    for (const node of candidates) {\n      let creationKnown = false;\n      if (isLocal) {\n        creationKnown = true;\n      } else {\n        const createdAtVV = vector?.get(node.getCreatedAt().getActorID());\n        if (createdAtVV && createdAtVV >= node.getCreatedAt().getLamport()) {\n          creationKnown = true;\n        }\n      }\n\n      let tombstoneKnown = false;\n      if (node.getRemovedAt()) {\n        const removedAtVV = vector?.get(node.getRemovedAt()!.getActorID());\n        if (isLocal) {\n          tombstoneKnown = true;\n        } else if (\n          removedAtVV &&\n          removedAtVV >= node.getRemovedAt()!.getLamport()\n        ) {\n          tombstoneKnown = true;\n        }\n      }\n\n      // Once a tombstone can be cancelled by an undo, \"the deleter knew the\n      // node\" is not enough -- the node has to have been LIVE in the\n      // deleter's view. A node the deleter saw removed and an undo revived\n      // here has to survive the deletion on every replica.\n      const liveInView = isLocal\n        ? !node.isRemoved()\n        : creationKnown && !node.isRemovedInView(vector!);\n      if (\n        liveInView &&\n        node.canRemove(editedAt, creationKnown, tombstoneKnown)\n      ) {\n        nodesToRemove.push(node);\n      } else {\n        // A node this deletion saw live but someone else removed\n        // concurrently records the deletion all the same. Otherwise an undo\n        // of the other deletion revives it on replicas that applied the two\n        // in one order and not in the other.\n        if (!isLocal && liveInView && node.isRemoved()) {\n          node.recordRemoval(editedAt);\n        }\n        nodesToKeep.push(node);\n      }\n    }\n    nodesToKeep.push(rightEdge);\n\n    // 02. Create value changes with previous indexes before deletion.\n    const changes = this.makeChanges(nodesToKeep, editedAt);\n\n    // 03. Mark tombstones for removal. Nodes that were already removed\n    // (concurrent LWW overwrite of an existing tombstone) are tracked\n    // separately: they already have a registered GC pair, and registering\n    // a second one would toggle-unregister the first.\n    const removedNodes = new Map();\n    const alreadyRemovedIDs = new Set<string>();\n    for (const node of nodesToRemove) {\n      const id = node.getID().toIDString();\n      if (node.isRemoved()) {\n        alreadyRemovedIDs.add(id);\n      }\n      removedNodes.set(id, node);\n      node.recordRemoval(editedAt);\n    }\n\n    // 04. Clear the index tree of the given deletion boundaries.\n    this.deleteIndexNodes(nodesToKeep);\n\n    return [changes, removedNodes, alreadyRemovedIDs];\n  }\n\n  /**\n   * `findEdgesOfCandidates` finds the edges outside `candidates`,\n   * (which has not already been deleted, or be undefined but not yet implemented)\n   * right edge is undefined means `candidates` contains the end of text.\n   */\n  private findEdgesOfCandidates(\n    candidates: Array<RGATreeSplitNode<T>>,\n  ): [RGATreeSplitNode<T>, RGATreeSplitNode<T> | undefined] {\n    return [\n      candidates[0].getPrev()!,\n      candidates[candidates.length - 1].getNext(),\n    ];\n  }\n\n  private makeChanges(\n    boundaries: Array<RGATreeSplitNode<T> | undefined>,\n    editedAt: TimeTicket,\n  ): Array<ValueChange<T>> {\n    const changes: Array<ValueChange<T>> = [];\n    let fromIdx: number, toIdx: number;\n\n    for (let i = 0; i < boundaries.length - 1; i++) {\n      const leftBoundary = boundaries[i];\n      const rightBoundary = boundaries[i + 1];\n\n      if (leftBoundary!.getNext() == rightBoundary) {\n        continue;\n      }\n\n      [fromIdx] = this.findIndexesFromRange(\n        leftBoundary!.getNext()!.createPosRange(),\n      );\n      if (rightBoundary) {\n        [, toIdx] = this.findIndexesFromRange(\n          rightBoundary.getPrev()!.createPosRange(),\n        );\n      } else {\n        toIdx = this.treeByIndex.length;\n      }\n\n      if (fromIdx < toIdx) {\n        changes.push({\n          actor: editedAt.getActorID(),\n          from: fromIdx,\n          to: toIdx,\n        });\n      }\n    }\n\n    return changes.reverse();\n  }\n\n  /**\n   * `deleteIndexNodes` clears the index nodes of the given deletion boundaries.\n   * The boundaries mean the nodes that will not be deleted in the range.\n   */\n  private deleteIndexNodes(\n    boundaries: Array<RGATreeSplitNode<T> | undefined>,\n  ): void {\n    for (let i = 0; i < boundaries.length - 1; i++) {\n      const leftBoundary = boundaries[i];\n      const rightBoundary = boundaries[i + 1];\n      // If there is no node to delete between boundaries, do notting.\n      if (leftBoundary!.getNext() != rightBoundary) {\n        this.treeByIndex.deleteRange(leftBoundary!, rightBoundary);\n      }\n    }\n  }\n\n  /**\n   * `purgeBarrierAt` implements `GCParent.purgeBarrierAt`. `findNodeWithSplit` skips forward\n   * while the next node was created after the incoming edit, so a tombstone\n   * whose createdAt precedes the edit stops that walk. Unlinking it hands the\n   * next node the stopping decision, which is only the same decision once\n   * that node is causally stable.\n   */\n  public purgeBarrierAt(child: GCChild): TimeTicket | undefined {\n    if (!(child instanceof RGATreeSplitNode)) {\n      return;\n    }\n    return child.getNext()?.getCreatedAt();\n  }\n\n  /**\n   * `purge` physically purges the given node from RGATreeSplit.\n   */\n  public purge(node: RGATreeSplitNode<T>): void {\n    this.cancelled?.delete(node);\n    this.treeByIndex.delete(node);\n    this.treeByID.remove(node.getID());\n\n    const prev = node.getPrev();\n    const next = node.getNext();\n    const insPrev = node.getInsPrev();\n    const insNext = node.getInsNext();\n\n    if (prev) {\n      prev.setNext(next);\n    }\n    if (next) {\n      next.setPrev(prev);\n    }\n\n    node.setPrev(undefined);\n    node.setNext(undefined);\n\n    if (insPrev) {\n      insPrev.setInsNext(insNext);\n    }\n\n    if (insNext) {\n      insNext.setInsPrev(insPrev);\n    }\n\n    node.setInsPrev(undefined);\n    node.setInsNext(undefined);\n  }\n}\n","/*\n * Copyright 2020 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n  TimeTicket,\n  TimeTicketSize,\n} from '@yorkie-js/sdk/src/document/time/ticket';\nimport { escapeString } from '@yorkie-js/sdk/src/document/json/strings';\nimport { GCChild } from '@yorkie-js/sdk/src/document/crdt/gc';\nimport { DataSize, utf8Length } from '@yorkie-js/sdk/src/util/resource';\n\n/**\n * `RHTNode` is a node of RHT(Replicated Hashtable).\n */\n/**\n * `RHTWrite` is what an `RHT.set` reports back. See `RHT.set`.\n */\nexport type RHTWrite = {\n  /**\n   * `installed` is the node this write put in the map, absent when the write\n   * lost LWW and changed nothing. Its size is what enters docSize.live.\n   */\n  installed?: RHTNode;\n\n  /**\n   * `revived` is a tombstone this write replaced. It was registered as garbage\n   * when it was removed, so the caller re-registers the pair to cancel that\n   * registration: it is no longer collectable, it is simply gone.\n   */\n  revived?: RHTNode;\n\n  /**\n   * `superseded` is a LIVE node this write replaced. RHT overrides immutably,\n   * so the old node is dropped with no tombstone and nothing to collect, but\n   * its bytes were counted in docSize.live and have to leave it.\n   */\n  superseded?: RHTNode;\n};\n\n/**\n * `RHTNode` is a node of RHT(Replicated Hashtable).\n */\n/**\n * `logicalValue` returns the attribute value as a peer storing values raw\n * would hold it: a JSON-encoded string yields the string itself, anything else\n * yields the stored text unchanged. A value written by such a peer does not\n * parse at all and is already raw, so it passes straight through.\n */\nfunction logicalValue(stored: string): string {\n  try {\n    const parsed = JSON.parse(stored);\n    return typeof parsed === 'string' ? parsed : stored;\n  } catch {\n    return stored;\n  }\n}\n\n/**\n * `valueSize` returns the `DataSize.data` bytes an attribute value of the\n * given stored form contributes, on the same terms as `RHTNode.getDataSize`.\n */\nfunction valueSize(stored: string): number {\n  return utf8Length(logicalValue(stored)) * 2;\n}\n\n/**\n * `RHTRemoval` is what an `RHT.remove` reports back.\n */\nexport type RHTRemoval = {\n  /**\n   * `gcNodes` are the tombstones this removal made collectable.\n   */\n  gcNodes: Array<RHTNode>;\n\n  /**\n   * `valueDropped` is the size of the value the removal stopped charging for,\n   * which no node's `getDataSize` accounts for any more. The caller subtracts\n   * it from whichever side of the ledger was holding it: `live` for an\n   * attribute that was live on a live node, `gc` for one on a node that is\n   * itself a tombstone. Zero when the attribute was already a tombstone, since\n   * a tombstone's value was not being charged in the first place.\n   */\n  valueDropped: DataSize;\n};\n\n/**\n * `RHTNode` is a node of RHT(Replicated Hashtable).\n */\nexport class RHTNode implements GCChild {\n  private key: string;\n  private value: string;\n  private updatedAt: TimeTicket;\n  private _isRemoved: boolean;\n\n  constructor(\n    key: string,\n    value: string,\n    updatedAt: TimeTicket,\n    isRemoved: boolean,\n  ) {\n    this.key = key;\n    this.value = value;\n    this.updatedAt = updatedAt;\n    this._isRemoved = isRemoved;\n  }\n\n  /**\n   * `of` creates a new instance of RHTNode.\n   */\n  public static of(\n    key: string,\n    value: string,\n    createdAt: TimeTicket,\n    isRemoved: boolean,\n  ): RHTNode {\n    return new RHTNode(key, value, createdAt, isRemoved);\n  }\n\n  /**\n   * `getKey` returns a key of node.\n   */\n  public getKey(): string {\n    return this.key;\n  }\n\n  /**\n   * `getValue` returns a value of node.\n   */\n  public getValue(): string {\n    return this.value;\n  }\n\n  /**\n   * `getUpdatedAt` returns updated time of node.\n   */\n  public getUpdatedAt(): TimeTicket {\n    return this.updatedAt;\n  }\n\n  /**\n   * `isRemoved` returns whether the node has been removed or not.\n   */\n  public isRemoved(): boolean {\n    return this._isRemoved;\n  }\n\n  /**\n   * `toIDString` returns the IDString of this node.\n   */\n  public toIDString(): string {\n    return `${this.updatedAt.toIDString()}:${this.key}`;\n  }\n\n  /**\n   * `getRemovedAt` returns the time when this node was removed.\n   */\n  public getRemovedAt(): TimeTicket | undefined {\n    if (this._isRemoved) {\n      return this.updatedAt;\n    }\n\n    return undefined;\n  }\n\n  /**\n   * `getDataSize` returns the size of this node.\n   *\n   * A tombstone charges its key only. The value it still carries is dead\n   * weight: nothing reads it -- `has`, `toJSON` and `toObject` all gate on\n   * `isRemoved` -- and charging it made the running `docSize` disagree with a\n   * rebuild of the same document, which replays the same removals. The value\n   * is left on the node rather than cleared so that what this SDK stores and\n   * serializes for a tombstone is byte-for-byte what it was, and what a peer\n   * sends us is kept verbatim: the convergence fix belongs in the accounting,\n   * not in the wire format.\n   */\n  public getDataSize(): DataSize {\n    // Charge the LOGICAL value in UTF-8 bytes, which is what the Go SDK\n    // stores and charges.\n    //\n    // Two things diverged. This SDK JSON-encodes values, so `color=\"red\"` is\n    // stored as the five characters `\"red\"` where Go stores three. And\n    // `.length` counts UTF-16 units where Go's `len()` counts UTF-8 bytes, so\n    // the gap did not even have a consistent sign: measured, `color=\"red\"`\n    // made JS 4 bytes heavier and `color=\"빨강\"` made it 4 bytes LIGHTER.\n    // The document size limit is enforced client-side against each SDK's own\n    // accounting, so the same document had a different allowance per SDK.\n    //\n    // Sizing the logical value converges both without touching what is\n    // stored, what is sent, or how a value reads back -- storing strings raw\n    // would converge too, but it makes a JS caller's string '1' read back as\n    // the number 1.\n    return {\n      data:\n        utf8Length(this.key) * 2 +\n        (this._isRemoved ? 0 : valueSize(this.value)),\n      meta: TimeTicketSize,\n    };\n  }\n}\n\n/**\n * RHT is replicated hash table by creation time.\n * For more details about RHT: @see http://csl.skku.edu/papers/jpdc11.pdf\n */\nexport class RHT {\n  private nodeMapByKey: Map<string, RHTNode>;\n  private numberOfRemovedElement: number;\n\n  constructor() {\n    this.nodeMapByKey = new Map();\n    this.numberOfRemovedElement = 0;\n  }\n\n  /**\n   * `create` creates a new instance of RHT.\n   */\n  public static create(): RHT {\n    return new RHT();\n  }\n\n  /**\n   * `getNodeMapByKey` returns the hashtable of RHT.\n   */\n  public getNodeMapByKey(): Map<string, RHTNode> {\n    return this.nodeMapByKey;\n  }\n\n  /**\n   * `set` sets the value of the given key.\n   */\n  /**\n   * `RHTWrite` reports what a `set` did, so the caller can keep docSize honest\n   * without inspecting the map afterwards. Reading the map cannot tell a write\n   * that installed a node from one that lost LWW and left the incumbent in\n   * place, and charging live for the latter makes the running size depend on\n   * delivery order.\n   */\n  public set(key: string, value: string, executedAt: TimeTicket): RHTWrite {\n    const prev = this.nodeMapByKey.get(key);\n\n    if (prev !== undefined && !executedAt.after(prev.getUpdatedAt())) {\n      return {};\n    }\n\n    if (prev !== undefined && prev.isRemoved()) {\n      this.numberOfRemovedElement -= 1;\n    }\n\n    const installed = RHTNode.of(key, value, executedAt, false);\n    this.nodeMapByKey.set(key, installed);\n\n    if (prev === undefined) {\n      return { installed };\n    }\n    if (prev.isRemoved()) {\n      return { installed, revived: prev };\n    }\n\n    return { installed, superseded: prev };\n  }\n\n  /**\n   * SetInternal sets the value of the given key internally.\n   *\n   * This is the route a snapshot and a `deepcopy` both take, and it keeps what\n   * it is given verbatim, tombstones included: a peer's bytes are not this\n   * SDK's to rewrite, and a tombstone's value costs nothing either way because\n   * `RHTNode.getDataSize` does not charge it.\n   */\n  public setInternal(\n    key: string,\n    value: string,\n    executedAt: TimeTicket,\n    removed: boolean,\n  ) {\n    const node = RHTNode.of(key, value, executedAt, removed);\n    this.nodeMapByKey.set(key, node);\n\n    if (removed) {\n      this.numberOfRemovedElement++;\n    }\n  }\n\n  /**\n   * `remove` removes the Element of the given key.\n   *\n   * The tombstone still STORES the value -- what goes on the wire is unchanged\n   * -- but stops being CHARGED for it, because `RHTNode.getDataSize` skips a\n   * removed node's value. `valueDropped` is what the caller has to take back\n   * out of whichever side of the ledger was holding those bytes; see\n   * `attrGCPair` for which side that is.\n   */\n  public remove(key: string, executedAt: TimeTicket): RHTRemoval {\n    const prev = this.nodeMapByKey.get(key);\n\n    const gcNodes: Array<RHTNode> = [];\n    const valueDropped: DataSize = { data: 0, meta: 0 };\n    if (prev === undefined || executedAt.after(prev.getUpdatedAt())) {\n      if (prev === undefined) {\n        this.numberOfRemovedElement += 1;\n        const node = RHTNode.of(key, '', executedAt, true);\n        this.nodeMapByKey.set(key, node);\n\n        gcNodes.push(node);\n        return { gcNodes, valueDropped };\n      }\n\n      const alreadyRemoved = prev.isRemoved();\n      if (!alreadyRemoved) {\n        this.numberOfRemovedElement += 1;\n        valueDropped.data = valueSize(prev.getValue());\n      }\n\n      if (alreadyRemoved) {\n        gcNodes.push(prev);\n      }\n\n      const node = RHTNode.of(key, prev.getValue(), executedAt, true);\n      this.nodeMapByKey.set(key, node);\n      gcNodes.push(node);\n\n      return { gcNodes, valueDropped };\n    }\n\n    return { gcNodes, valueDropped };\n  }\n\n  /**\n   * `has` returns whether the element exists of the given key or not.\n   */\n  public has(key: string): boolean {\n    if (this.nodeMapByKey.has(key)) {\n      const node = this.nodeMapByKey.get(key);\n      return node !== undefined && !node.isRemoved();\n    }\n    return false;\n  }\n\n  /**\n   * `get` returns the value of the given key.\n   */\n  public get(key: string): string | undefined {\n    if (!this.nodeMapByKey.has(key)) {\n      return;\n    }\n\n    return this.nodeMapByKey.get(key)!.getValue();\n  }\n\n  /**\n   * `deepcopy` copies itself deeply.\n   */\n  public deepcopy(): RHT {\n    const rht = new RHT();\n    for (const [, node] of this.nodeMapByKey) {\n      rht.setInternal(\n        node.getKey(),\n        node.getValue(),\n        node.getUpdatedAt(),\n        node.isRemoved(),\n      );\n    }\n    return rht;\n  }\n\n  /**\n   * `toJSON` returns the JSON encoding of this hashtable.\n   */\n  public toJSON(): string {\n    if (!this.size()) {\n      return '{}';\n    }\n\n    const items = [];\n    for (const [key, node] of this.nodeMapByKey) {\n      if (!node.isRemoved()) {\n        items.push(`\"${escapeString(key)}\":\"${escapeString(node.getValue())}\"`);\n      }\n    }\n    return `{${items.join(',')}}`;\n  }\n\n  /**\n   * `size` returns the size of RHT\n   */\n  public size(): number {\n    return this.nodeMapByKey.size - this.numberOfRemovedElement;\n  }\n\n  /**\n   * `toObject` returns the object of this hashtable.\n   */\n  public toObject(): Record<string, string> {\n    const obj: Record<string, string> = {};\n    for (const [key, node] of this.nodeMapByKey) {\n      if (!node.isRemoved()) {\n        obj[key] = node.getValue();\n      }\n    }\n\n    return obj;\n  }\n\n  // eslint-disable-next-line jsdoc/require-jsdoc\n  public *[Symbol.iterator](): IterableIterator<RHTNode> {\n    for (const [, node] of this.nodeMapByKey) {\n      yield node as RHTNode;\n    }\n  }\n\n  /**\n   * `purge` purges the given child node.\n   */\n  public purge(child: RHTNode) {\n    const node = this.nodeMapByKey.get(child.getKey());\n    if (node == undefined || node.toIDString() != child.toIDString()) {\n      // TODO(hackerwins): Should we return an error when the child is not found?\n      return;\n    }\n\n    this.nodeMapByKey.delete(child.getKey());\n    this.numberOfRemovedElement--;\n  }\n}\n","/*\n * Copyright 2023 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TimeTicket, VersionVector } from '../yorkie';\nimport { Code, YorkieError } from './error';\nimport {\n  DataSize,\n  addDataSizes,\n  subDataSize,\n} from '@yorkie-js/sdk/src/util/resource';\n\n/**\n * About `index`, `path`, `size` and `TreePos` in crdt.IndexTree.\n *\n * `index` of crdt.IndexTree represents a absolute position of a node in the tree.\n * `size` is used to calculate the relative index of nodes in the tree.\n * `index` in yorkie.IndexTree inspired by ProseMirror's index.\n *\n * For example, empty paragraph's size is 0 and index 0 is the position of the:\n *    0\n * <p> </p>,                                p.size = 0\n *\n * If a paragraph has <i>, its size becomes 2 and there are 3 indexes:\n *     0   1    2\n *  <p> <i> </i> </p>                       p.size = 2, i.size = 0\n *\n * If the paragraph has <i> and <b>, its size becomes 4:\n *     0   1    2   3   4\n *  <p> <i> </i> <b> </b> </p>              p.size = 4, i.size = 0, b.size = 0\n *     0   1    2   3    4    5   6\n *  <p> <i> </i> <b> </b> <s> </s> </p>     p.size = 6, i.size = 0, b.size = 0, s.size = 0\n *\n * If a paragraph has text, its size becomes length of the characters:\n *     0 1 2 3\n *  <p> A B C </p>                          p.size = 3,   text.size = 3\n *\n * So the size of a node is the sum of the size and type of its children:\n *  `size = children(element type).length * 2 + children.reduce((child, acc) => child.size + acc, 0)`\n *\n * `TreePos` is also used to represent the position in the tree. It contains node and offset.\n * `TreePos` can be converted to `index` and vice versa.\n *\n * For example, if a paragraph has <i>, there are 3 indexes:\n *     0   1    2\n *  <p> <i> </i> </p>                       p.size = 2, i.size = 0\n *\n * In this case, index of TreePos(p, 0) is 0, index of TreePos(p, 1) is 2.\n * Index 1 can be converted to TreePos(i, 0).\n *\n * `path` of crdt.IndexTree represents a position like `index` in crdt.IndexTree.\n * It contains offsets of each node from the root node as elements except the last.\n * The last element of the path represents the position in the parent node.\n *\n * Let's say we have a tree like this:\n *                     0 1 2\n * <p> <i> a b </i> <b> c d </b> </p>\n *\n * The path of the position between 'c' and 'd' is [1, 1]. The first element of the\n * path is the offset of the <b> in <p> and the second element represents the position\n * between 'c' and 'd' in <b>.\n */\n\n/**\n * `ElementPaddingSize` is the size of an element node as a child of another element node.\n * Because an element node could be considered as a pair of open and close tags.\n */\nexport const ElementPaddingSize = 2;\n\n/**\n * `DefaultRootType` is the default type of the root node.\n * It is used when the type of the root node is not specified.\n */\nexport const DefaultRootType = 'root';\n\n/**\n * `DefaultTextType` is the default type of the text node.\n * It is used when the type of the text node is not specified.\n */\nexport const DefaultTextType = 'text';\n\n/**\n * `NoteType` is the type of a node in the tree.\n */\nexport type TreeNodeType = string;\n\n/**\n * `addSizeOfLeftSiblings` returns the size of left siblings of the given offset.\n * If includeRemoved is true, it includes removed nodes in the calculation.\n */\nexport function addSizeOfLeftSiblings<T extends IndexTreeNode<T>>(\n  parent: T,\n  offset: number,\n  includeRemoved: boolean = false,\n): number {\n  let acc = 0;\n  const siblings = includeRemoved ? parent.allChildren : parent.children;\n\n  for (let i = 0; i < offset; i++) {\n    const leftSibling = siblings[i];\n\n    if (!leftSibling || (!includeRemoved && leftSibling.isRemoved)) {\n      continue;\n    }\n\n    acc += leftSibling.paddedSize(includeRemoved);\n  }\n\n  return acc;\n}\n\n/**\n * `IndexTreeNode` is the node of IndexTree. It is used to represent the\n * document of text-based editors.\n */\nexport abstract class IndexTreeNode<T extends IndexTreeNode<T>> {\n  type: TreeNodeType;\n  parent?: T;\n  _children: Array<T>;\n  visibleSize: number;\n  totalSize: number;\n\n  constructor(type: TreeNodeType, children: Array<T> = []) {\n    this.type = type;\n    this.visibleSize = 0;\n    this.totalSize = 0;\n    this._children = children;\n\n    if (this.isText && this._children.length > 0) {\n      throw new YorkieError(Code.ErrRefused, 'Text node cannot have children');\n    }\n  }\n\n  /**\n   * `updateAncestorsSize` updates the size of the ancestors.\n   * It is used when the size of the node is changed.\n   * If includeRemoved is true, it updates ancestors totalSize including removed nodes.\n   */\n  updateAncestorsSize(delta: number, includeRemoved: boolean = false): void {\n    let parent: T | undefined = this.parent;\n\n    while (parent) {\n      if (includeRemoved) {\n        parent.totalSize += delta;\n      } else {\n        parent.visibleSize += delta;\n        // NOTE(hackerwins): If a parent node is removed (tombstone),\n        // it is not visible to the user, and its children are also not visible.\n        // Therefore, there is no need to update the visibleSize above the removed parent.\n        if (parent.isRemoved) {\n          break;\n        }\n      }\n\n      parent = parent.parent;\n    }\n  }\n\n  /**\n   * `UpdateDescendantsSize` updates the size of the descendants. It is used when\n   * the tree is newly created and the size of the descendants is not calculated.\n   * If includeRemoved is true, it includes removed nodes in the calculation.\n   */\n  updateDescendantsSize(includeRemoved: boolean = false): number {\n    let size = 0;\n    for (const child of this._children) {\n      const childSize = child.updateDescendantsSize(includeRemoved);\n      if (!includeRemoved && child.isRemoved) {\n        continue;\n      }\n\n      size += childSize;\n    }\n\n    if (includeRemoved) {\n      this.totalSize += size;\n    } else {\n      this.visibleSize += size;\n    }\n\n    return this.paddedSize(includeRemoved);\n  }\n\n  /**\n   * `isText` returns true if the node is a text node.\n   */\n  get isText(): boolean {\n    // TODO(hackerwins): We need to get the type of text node from user.\n    // Consider the use schema to get the type of text node.\n    return this.type === DefaultTextType;\n  }\n\n  /**\n   * `paddedSize` returns the length of the node including padding.\n   * If includeRemoved is true, it includes removed nodes in the calculation.\n   */\n  paddedSize(includeRemoved: boolean = false): number {\n    let size = this.visibleSize;\n    if (includeRemoved) {\n      size = this.totalSize;\n    }\n    if (!this.isText) {\n      size += ElementPaddingSize;\n    }\n    return size;\n  }\n\n  /**\n   * `isAncenstorOf` returns true if the node is an ancestor of the given node.\n   */\n  isAncestorOf(node: T): boolean {\n    return ancestorOf(this as any, node);\n  }\n\n  /**\n   * `nextSibling` returns the next sibling of the node.\n   */\n  get nextSibling(): T | undefined {\n    const offset = this.parent!.findOffset(this as any);\n    const sibling = this.parent!.children[offset + 1];\n    if (sibling) {\n      return sibling;\n    }\n\n    return undefined;\n  }\n\n  /**\n   * `prevSibling` returns the previous sibling of the node.\n   */\n  get prevSibling(): T | undefined {\n    const offset = this.parent!.findOffset(this as any);\n    const sibling = this.parent!.children[offset - 1];\n    if (sibling) {\n      return sibling;\n    }\n\n    return undefined;\n  }\n\n  /**\n   * `isRemoved` returns true if the node is removed.\n   */\n  abstract get isRemoved(): boolean;\n\n  /**\n   * `cloneText` clones the text node with the given id and value.\n   */\n  abstract cloneText(offset: number): T;\n\n  /**\n   * `cloneElement` clones the element node with the given issueTimeTicket\n   * function and value.\n   */\n  abstract cloneElement(issueTimeTicket: () => TimeTicket): T;\n\n  /**\n   * `value` returns the value of the node.\n   */\n  abstract get value();\n\n  /**\n   * `value` sets the value of the node.\n   */\n  abstract set value(v: string);\n\n  /**\n   * `getDataSize` returns the size of the node.\n   */\n  abstract getDataSize(): DataSize;\n\n  /**\n   * `splitText` splits the given node at the given offset.\n   */\n  splitText(offset: number, absOffset: number): [T | undefined, DataSize] {\n    const diff = { data: 0, meta: 0 };\n\n    if (offset === 0 || offset === this.visibleSize) {\n      return [undefined, diff];\n    }\n\n    // A position that anchors past the end of this node cannot be resolved\n    // here. `slice` would quietly hand back an empty right value and the split\n    // would look like a no-op, leaving the edit at the wrong position.\n    if (offset < 0 || offset > this.visibleSize) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `split at ${offset} of ${this.visibleSize}: offset out of range`,\n      );\n    }\n\n    const leftValue = this.value.slice(0, offset);\n    const rightValue = this.value.slice(offset);\n\n    if (!rightValue.length) {\n      return [undefined, diff];\n    }\n\n    const prvSize = this.getDataSize();\n\n    this.value = leftValue;\n\n    const rightNode = this.cloneText(offset + absOffset);\n    rightNode.value = rightValue;\n\n    this.parent!.insertAfterInternal(rightNode, this as any);\n\n    // NOTE(hackerwins): Calculate data size after node splitting:\n    // Take the sum of the two split nodes(left and right) minus the size of\n    // the original node. This calculates the net metadata overhead added by\n    // the split operation.\n    addDataSizes(diff, this.getDataSize(), rightNode.getDataSize());\n    subDataSize(diff, prvSize);\n\n    return [rightNode, diff];\n  }\n\n  /**\n   * `children` returns the children of the node.\n   */\n  get children(): Array<T> {\n    // Tombstone nodes remain awhile in the tree during editing.\n    // They will be removed after the editing is done.\n    // So, we need to filter out the tombstone nodes to get the real children.\n    return this._children.filter((child) => !child.isRemoved);\n  }\n\n  /**\n   * `allChildren` returns all the children of the node including tombstone nodes.\n   * It returns the shallow copy of the children.\n   */\n  get allChildren(): Array<T> {\n    return [...this._children];\n  }\n\n  /**\n   * `hasTextChild` returns true if the node's children consist of only text children.\n   */\n  hasTextChild(): boolean {\n    return (\n      this.children.length > 0 && this.children.every((child) => child.isText)\n    );\n  }\n\n  /**\n   * `getChildrenText` returns text value of all text type children.\n   */\n  getChildrenText(): string {\n    if (this.isText) {\n      return this.value;\n    }\n    if (this.hasTextChild()) {\n      return this.children.map((child) => child.value).join('');\n    }\n    return '';\n  }\n\n  /**\n   * `append` appends the given nodes to the children.\n   */\n  append(...newNode: Array<T>): void {\n    if (this.isText) {\n      throw new YorkieError(Code.ErrRefused, 'Text node cannot have children');\n    }\n\n    this._children.push(...newNode);\n    for (const node of newNode) {\n      node.parent = this as any;\n      node.updateAncestorsSize(node.paddedSize());\n      node.updateAncestorsSize(node.paddedSize(true), true);\n    }\n  }\n\n  /**\n   * `prepend` prepends the given nodes to the children. It is only used\n   * for creating a new node from snapshot.\n   */\n  prepend(...newNode: Array<T>): void {\n    if (this.isText) {\n      throw new YorkieError(Code.ErrRefused, 'Text node cannot have children');\n    }\n\n    this._children.unshift(...newNode);\n    for (const node of newNode) {\n      node.parent = this as any;\n    }\n  }\n\n  /**\n   * `insertBefore` inserts the given node before the given child.\n   */\n  insertBefore(newNode: T, referenceNode: T): void {\n    if (this.isText) {\n      throw new YorkieError(Code.ErrRefused, 'Text node cannot have children');\n    }\n\n    const offset = this._children.indexOf(referenceNode);\n    if (offset === -1) {\n      throw new YorkieError(Code.ErrInvalidArgument, 'child not found');\n    }\n\n    this.insertAtInternal(newNode, offset);\n    newNode.updateAncestorsSize(newNode.paddedSize());\n    newNode.updateAncestorsSize(newNode.paddedSize(true), true);\n  }\n\n  /**\n   * `insertAfter` inserts the given node after the given child.\n   */\n  insertAfter(newNode: T, referenceNode: T): void {\n    if (this.isText) {\n      throw new YorkieError(Code.ErrRefused, 'Text node cannot have children');\n    }\n\n    const offset = this._children.indexOf(referenceNode);\n    if (offset === -1) {\n      throw new YorkieError(Code.ErrInvalidArgument, 'child not found');\n    }\n\n    this.insertAtInternal(newNode, offset + 1);\n    newNode.updateAncestorsSize(newNode.paddedSize());\n    newNode.updateAncestorsSize(newNode.paddedSize(true), true);\n  }\n\n  /**\n   * `insertAt` inserts the given node at the given offset.\n   */\n  insertAt(newNode: T, offset: number): void {\n    if (this.isText) {\n      throw new YorkieError(Code.ErrRefused, 'Text node cannot have children');\n    }\n\n    this.insertAtInternal(newNode, offset);\n    newNode.updateAncestorsSize(newNode.paddedSize());\n    newNode.updateAncestorsSize(newNode.paddedSize(true), true);\n  }\n\n  /**\n   * `removeChild` removes the given child.\n   * In this method, the child is physically removed from the tree.\n   */\n  removeChild(child: T) {\n    if (this.isText) {\n      throw new YorkieError(Code.ErrRefused, 'Text node cannot have children');\n    }\n\n    const offset = this._children.indexOf(child);\n    if (offset === -1) {\n      // When a child has been detached by a prior merge operation,\n      // removeChild during GC purge may not find it. This is safe to\n      // skip since the child is already physically removed.\n      return;\n    }\n\n    this._children.splice(offset, 1);\n    // NOTE(hackerwins): Decrease totalSize including removed nodes\n    // since this node is being purged (physically removed from tree).\n    child.updateAncestorsSize(-child.paddedSize(true), true);\n    child.parent = undefined;\n  }\n\n  /**\n   * `detachChild` removes the given child from this node's children list\n   * and updates both visibleSize and totalSize. Unlike `removeChild` which\n   * is used for GC purge of tombstoned nodes, `detachChild` is used for\n   * moving alive nodes between parents.\n   */\n  detachChild(child: T) {\n    if (this.isText) {\n      throw new YorkieError(Code.ErrRefused, 'Text node cannot have children');\n    }\n\n    const offset = this._children.indexOf(child);\n    if (offset === -1) {\n      throw new YorkieError(Code.ErrInvalidArgument, 'child not found');\n    }\n\n    this._children.splice(offset, 1);\n    child.updateAncestorsSize(-child.paddedSize());\n    child.updateAncestorsSize(-child.paddedSize(true), true);\n    child.parent = undefined;\n  }\n\n  /**\n   * `moveChild` detaches the given child from its current parent (if any)\n   * and appends it to this node, preserving both size dimensions on both\n   * parents. Unlike `detachChild` followed by `append`, it is correct for\n   * tombstoned children: a removed node contributes no visibleSize to\n   * either parent (removal already excluded it from its ancestors), so only\n   * the include-removed totalSize is relocated. It is used by merge to move\n   * tombstones as RGA anchors without corrupting index positions.\n   */\n  moveChild(child: T): void {\n    if (this.isText) {\n      throw new YorkieError(Code.ErrRefused, 'Text node cannot have children');\n    }\n\n    const removed = this.detachForMove(child);\n    this._children.push(child);\n    child.parent = this as any;\n    this.attachAfterMove(child, removed);\n  }\n\n  /**\n   * `moveChildBefore` detaches the given child from its current parent (if\n   * any) and inserts it before `reference` among this node's children,\n   * preserving both size dimensions on both parents. It is `moveChild` with a\n   * position: see there for why a removed child relocates only its\n   * include-removed size.\n   *\n   * Both failures are decided before anything moves, so a refused move leaves\n   * the tree exactly as it was rather than holding a child that belongs to no\n   * parent. The reference's offset is still read after the detach, since\n   * removing the child can shift it when the two share a parent.\n   */\n  moveChildBefore(child: T, reference: T): void {\n    if (this.isText) {\n      throw new YorkieError(Code.ErrRefused, 'Text node cannot have children');\n    }\n    // Already where it is being asked to go, and the detach below would make\n    // the reference impossible to find again.\n    if (child === reference) {\n      return;\n    }\n    if (this._children.indexOf(reference) === -1) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        'reference is not a child',\n      );\n    }\n\n    const removed = this.detachForMove(child);\n    this._children.splice(this._children.indexOf(reference), 0, child);\n    child.parent = this as any;\n    this.attachAfterMove(child, removed);\n  }\n\n  /**\n   * `detachForMove` takes the child off its current parent, if it has one,\n   * subtracting its sizes from that parent's ancestors, and reports whether\n   * the child is a tombstone — which the re-attachment needs to know too.\n   *\n   * A tombstone moves only its include-removed size: it contributes no\n   * visibleSize to either parent, because removal already took it out of its\n   * ancestors. Splitting the move into this pair and `attachAfterMove` keeps\n   * that rule in one place; stating it once per call site is how the two\n   * dimensions drift apart.\n   */\n  private detachForMove(child: T): boolean {\n    const removed = child.isRemoved;\n    if (!child.parent) {\n      return removed;\n    }\n\n    const offset = child.parent._children.indexOf(child);\n    // The child may already have been spliced out of its parent's list by a\n    // concurrent operation (e.g. cascade delete of a split sibling), which\n    // already reconciled the old ancestors' size. In that case only\n    // re-parent; otherwise detach with size accounting.\n    if (offset !== -1) {\n      child.parent._children.splice(offset, 1);\n      if (!removed) {\n        child.updateAncestorsSize(-child.paddedSize());\n      }\n      child.updateAncestorsSize(-child.paddedSize(true), true);\n    }\n    child.parent = undefined;\n\n    return removed;\n  }\n\n  /**\n   * `attachAfterMove` adds the child's sizes to its new parent's ancestors,\n   * the mirror of `detachForMove`. `removed` is what that call reported.\n   */\n  private attachAfterMove(child: T, removed: boolean): void {\n    if (!removed) {\n      child.updateAncestorsSize(child.paddedSize());\n    }\n    child.updateAncestorsSize(child.paddedSize(true), true);\n  }\n\n  /**\n   * `splitElement` splits the given element at the given offset.\n   */\n  splitElement(\n    offset: number,\n    issueTimeTicket: () => TimeTicket,\n    versionVector?: VersionVector,\n  ): [T | undefined, DataSize] {\n    const diff = { data: 0, meta: 0 };\n\n    const prvSize = this.getDataSize();\n\n    /**\n     * TODO(hackerwins): Define ID of split node for concurrent editing.\n     * Text has fixed content and its split nodes could have limited offset\n     * range. But element node could have arbitrary children and its split\n     * nodes could have arbitrary offset range. So, id could be duplicated\n     * and its order could be broken when concurrent editing happens.\n     * Currently, we use the similar ID of split element with the split text.\n     */\n    const clone = this.cloneElement(issueTimeTicket);\n    this.parent!.insertAfterInternal(clone, this as any);\n    // A piece born tombstoned -- split off a node a concurrent deletion has\n    // already removed -- is not visible, so it must not lengthen its live\n    // ancestors. `remove` holds the same invariant from the other side,\n    // subtracting a node's padded size from its ancestors as it becomes a\n    // tombstone. The include-removed size counts tombstones and grows either\n    // way.\n    if (!clone.isRemoved) {\n      clone.updateAncestorsSize(clone.paddedSize());\n    }\n    clone.updateAncestorsSize(clone.paddedSize(true), true);\n\n    const left = this._children.slice(0, offset);\n    const right = this._children.slice(offset);\n\n    // Fix 8: Handle concurrent merge-moved children during split.\n    // When a child was merge-moved from a source that is itself a child\n    // of the node being split, the content was local to this level and\n    // should stay in the original (left) node. When the source is\n    // external (e.g., a sibling element that was merged), the content\n    // should flow naturally to the split (right) node.\n    const allChildren = [...left, ...right];\n    const actualRight: Array<T> = [];\n    for (const child of right) {\n      if (\n        'mergedFrom' in child &&\n        (child as any).mergedFrom != null &&\n        'mergedAt' in child &&\n        (child as any).mergedAt != null\n      ) {\n        if (versionVector) {\n          const mergedAt = (child as any).mergedAt as TimeTicket;\n          if (!versionVector.afterOrEqual(mergedAt)) {\n            // Check if the merge source is a child of this node.\n            const mergedFrom = (child as any).mergedFrom;\n            const sourceIsChild = allChildren.some(\n              (sibling) =>\n                'id' in sibling && (sibling as any).id.equals(mergedFrom),\n            );\n            if (sourceIsChild) {\n              left.push(child);\n              continue;\n            }\n          }\n        }\n      }\n      actualRight.push(child);\n    }\n\n    // §7.3 Boundary Insert Migration: Move concurrent inserts at the\n    // split boundary to the left. Element split siblings (with insPrevID)\n    // are skipped — they are split products handled by §7.4.\n    if (versionVector) {\n      const movedToLeft: Array<T> = [];\n      const remaining: Array<T> = [];\n      let boundaryReached = false;\n      for (const child of actualRight) {\n        if (!boundaryReached) {\n          // Skip element split siblings — they are split products,\n          // not concurrent inserts. Text split siblings have\n          // deterministic IDs and act as normal boundary markers.\n          if (\n            (child as any).insPrevID !== undefined &&\n            !(child as any).isText\n          ) {\n            remaining.push(child);\n            continue;\n          }\n          const actorID = (child as any).id.getCreatedAt().getActorID();\n          const knownLamport = versionVector.get(actorID);\n          if (\n            knownLamport === undefined ||\n            knownLamport < (child as any).id.getCreatedAt().getLamport()\n          ) {\n            movedToLeft.push(child);\n            continue;\n          }\n        }\n        boundaryReached = true;\n        remaining.push(child);\n      }\n      if (movedToLeft.length > 0) {\n        left.push(...movedToLeft);\n        actualRight.length = 0;\n        actualRight.push(...remaining);\n      }\n    }\n\n    this._children = left;\n    clone._children = actualRight;\n    this.visibleSize = this._children.reduce(\n      (acc, child) => acc + (child.isRemoved ? 0 : child.paddedSize()),\n      0,\n    );\n    this.totalSize = this._children.reduce(\n      (acc, child) => acc + child.paddedSize(true),\n      0,\n    );\n    clone.visibleSize = clone._children.reduce(\n      (acc, child) => acc + (child.isRemoved ? 0 : child.paddedSize()),\n      0,\n    );\n    clone.totalSize = clone._children.reduce(\n      (acc, child) => acc + child.paddedSize(true),\n      0,\n    );\n    for (const child of clone._children) {\n      child.parent = clone;\n    }\n\n    // NOTE(hackerwins): Calculate data size after node splitting:\n    // Take the sum of the two split nodes(left and right) minus the size of\n    // the original node. This calculates the net metadata overhead added by\n    // the split operation.\n    addDataSizes(diff, this.getDataSize(), clone.getDataSize());\n    subDataSize(diff, prvSize);\n\n    return [clone, diff];\n  }\n\n  /**\n   * `insertAfterInternal` inserts the given node after the given child.\n   * This method does not update the size of the ancestors.\n   */\n  insertAfterInternal(newNode: T, referenceNode: T): void {\n    if (this.isText) {\n      throw new YorkieError(Code.ErrRefused, 'Text node cannot have children');\n    }\n\n    const offset = this._children.indexOf(referenceNode);\n    if (offset === -1) {\n      throw new YorkieError(Code.ErrInvalidArgument, 'child not found');\n    }\n\n    this.insertAtInternal(newNode, offset + 1);\n  }\n\n  /**\n   * `insertAtInternal` inserts the given node at the given index.\n   * This method does not update the size of the ancestors.\n   */\n  insertAtInternal(newNode: T, offset: number): void {\n    if (this.isText) {\n      throw new YorkieError(Code.ErrRefused, 'Text node cannot have children');\n    }\n\n    this._children.splice(offset, 0, newNode);\n    newNode.parent = this as any;\n  }\n\n  /**\n   * findOffset returns the offset of the given node in the children.\n   * If includeRemoved is true, it includes removed nodes in the calculation.\n   */\n  findOffset(node: T, includeRemoved: boolean = false): number {\n    if (this.isText) {\n      throw new YorkieError(Code.ErrRefused, 'Text node cannot have children');\n    }\n\n    if (includeRemoved) {\n      return this._children.indexOf(node);\n    }\n\n    if (node.isRemoved) {\n      const index = this._children.indexOf(node);\n\n      // If nodes are removed, the offset of the removed node is the number of\n      // nodes before the node excluding the removed nodes.\n      const refined = this.allChildren\n        .splice(0, index)\n        .filter((node) => !node.isRemoved).length;\n\n      return refined;\n    }\n\n    return this.children.indexOf(node);\n  }\n\n  /**\n   * `findBranchOffset` returns offset of the given descendant node in this node.\n   * If the given node is not a descendant of this node, it returns -1.\n   */\n  findBranchOffset(node: T): number {\n    if (this.isText) {\n      throw new YorkieError(Code.ErrRefused, 'Text node cannot have children');\n    }\n\n    let current: T | undefined = node;\n    while (current) {\n      const offset = this._children.indexOf(current);\n      if (offset !== -1) {\n        return offset;\n      }\n\n      current = current.parent;\n    }\n\n    return -1;\n  }\n}\n\n/**\n * `TreePos` is the position of a node in the tree.\n *\n * `offset` is the position of node's token. For example, if the node is an\n * element node, the offset is the index of the child node. If the node is a\n * text node, the offset is the index of the character.\n */\nexport type TreePos<T extends IndexTreeNode<T>> = {\n  node: T;\n  offset: number;\n};\n\n/**\n * `ancestorOf` returns true if the given node is an ancestor of the other node.\n */\nfunction ancestorOf<T extends IndexTreeNode<T>>(ancestor: T, node: T): boolean {\n  if (ancestor === node) {\n    return false;\n  }\n\n  while (node.parent) {\n    if (node.parent === ancestor) {\n      return true;\n    }\n    node = node.parent;\n  }\n  return false;\n}\n\n/**\n * `TokenType` represents the type of token in XML representation.\n */\nexport enum TokenType {\n  /**\n   * `Start` represents that the start token type.\n   */\n  Start = 'Start',\n\n  /**\n   * `End` represents that the end token type.\n   */\n  End = 'End',\n\n  /**\n   * `Text` represents that the text token type.\n   */\n  Text = 'Text',\n}\n\n/**\n * `TreeToken` represents the token of the tree in XML representation.\n */\nexport type TreeToken<T> = [T, TokenType];\n\n/**\n * `tokensBetween` iterates the tokens between the given range.\n *\n * For example, if the tree is <p><i>abc</i></p>, the tokens are\n * [p, Start], [i, Start], [abc, Text], [i, End], [p, End].\n *\n * If the given range is collapsed, the callback is not called.\n * It traverses the tree based on the concept of token.\n * NOTE(sejongk): Nodes should not be removed in callback, because it leads wrong behaviors.\n */\nfunction tokensBetween<T extends IndexTreeNode<T>>(\n  root: T,\n  from: number,\n  to: number,\n  callback: (token: TreeToken<T>, ended: boolean) => void,\n  includeRemoved: boolean = false,\n) {\n  if (from > to) {\n    throw new YorkieError(\n      Code.ErrInvalidArgument,\n      `from is greater than to: ${from} > ${to}`,\n    );\n  }\n\n  const rootSize = includeRemoved ? root.totalSize : root.visibleSize;\n  if (from > rootSize) {\n    throw new YorkieError(\n      Code.ErrInvalidArgument,\n      `from is out of range: ${from} > ${rootSize}`,\n    );\n  }\n  if (to > rootSize) {\n    throw new YorkieError(\n      Code.ErrInvalidArgument,\n      `to is out of range: ${to} > ${rootSize}`,\n    );\n  }\n\n  if (from === to) {\n    return;\n  }\n\n  let pos = 0;\n  const children = includeRemoved ? root._children : root.children;\n  for (const child of children) {\n    // If the child is an element node, the size of the child.\n    if (from - child.paddedSize(includeRemoved) < pos && pos < to) {\n      // If the child is an element node, the range of the child\n      // is from - 1 to to - 1. Because the range of the element node is from\n      // the open tag to the close tag.\n      const fromChild = child.isText ? from - pos : from - pos - 1;\n      const toChild = child.isText ? to - pos : to - pos - 1;\n\n      // If the range spans outside the child,\n      // the callback is called with the child.\n      const childSize = includeRemoved ? child.totalSize : child.visibleSize;\n      const startContained = !child.isText && fromChild < 0;\n      const endContained = !child.isText && toChild > childSize;\n      if (child.isText || startContained) {\n        callback(\n          [child, child.isText ? TokenType.Text : TokenType.Start],\n          endContained,\n        );\n      }\n      tokensBetween(\n        child,\n        Math.max(0, fromChild),\n        Math.min(toChild, childSize),\n        callback,\n        includeRemoved,\n      );\n      if (endContained) {\n        callback([child, TokenType.End], endContained);\n      }\n    }\n    pos += child.paddedSize(includeRemoved);\n  }\n}\n\n/**\n * `traverse` traverses the tree with postorder traversal.\n */\nexport function traverse<T extends IndexTreeNode<T>>(\n  node: T,\n  callback: (node: T, depth: number) => void,\n  depth = 0,\n) {\n  for (const child of node.children) {\n    traverse(child, callback, depth + 1);\n  }\n  callback(node, depth);\n}\n\n/**\n * `traverseAll` traverses the whole tree (include tombstones) with postorder traversal.\n */\nexport function traverseAll<T extends IndexTreeNode<T>>(\n  node: T,\n  callback: (node: T, depth: number) => void,\n  depth = 0,\n) {\n  for (const child of node._children) {\n    traverseAll(child, callback, depth + 1);\n  }\n  callback(node, depth);\n}\n\n/**\n * `findTreePos` finds the position of the given index in the given node.\n */\nfunction findTreePos<T extends IndexTreeNode<T>>(\n  node: T,\n  index: number,\n  preferText = true,\n): TreePos<T> {\n  if (index > node.visibleSize) {\n    throw new YorkieError(\n      Code.ErrInvalidArgument,\n      `index is out of range: ${index} > ${node.visibleSize}`,\n    );\n  }\n\n  if (node.isText) {\n    return { node, offset: index };\n  }\n\n  // offset is the index of the child node.\n  // pos is the window of the index in the given node.\n  let offset = 0;\n  let pos = 0;\n  for (const child of node.children) {\n    // The pos is in bothsides of the text node, we should traverse\n    // inside of the text node if preferText is true.\n    if (preferText && child.isText && child.visibleSize >= index - pos) {\n      return findTreePos(child, index - pos, preferText);\n    }\n\n    // The position is in leftside of the element node.\n    if (index === pos) {\n      return { node, offset };\n    }\n\n    // The position is in rightside of the element node and preferText is false.\n    if (!preferText && child.paddedSize() === index - pos) {\n      return { node, offset: offset + 1 };\n    }\n\n    // The position is in middle the element node.\n    if (child.paddedSize() > index - pos) {\n      // If we traverse inside of the element node, we should skip the open.\n      const skipOpenSize = 1;\n      return findTreePos(child, index - pos - skipOpenSize, preferText);\n    }\n\n    pos += child.paddedSize();\n    offset += 1;\n  }\n\n  // The position is in rightmost of the given node.\n  return { node, offset };\n}\n\n/**\n * `getAncestors` returns the ancestors of the given node.\n */\nexport function getAncestors<T extends IndexTreeNode<T>>(node: T): Array<T> {\n  const ancestors: Array<T> = [];\n  let parent = node.parent;\n  while (parent) {\n    ancestors.unshift(parent);\n    parent = parent.parent;\n  }\n  return ancestors;\n}\n\n/**\n * `findCommonAncestor` finds the lowest common ancestor of the given nodes.\n */\nexport function findCommonAncestor<T extends IndexTreeNode<T>>(\n  nodeA: T,\n  nodeB: T,\n): T | undefined {\n  if (nodeA === nodeB) {\n    return nodeA;\n  }\n\n  const ancestorsOfA = getAncestors(nodeA);\n  const ancestorsOfB = getAncestors(nodeB);\n\n  let commonAncestor: T | undefined;\n  for (let i = 0; i < ancestorsOfA.length; i++) {\n    const ancestorOfA = ancestorsOfA[i];\n    const ancestorOfB = ancestorsOfB[i];\n\n    if (ancestorOfA !== ancestorOfB) {\n      break;\n    }\n\n    commonAncestor = ancestorOfA;\n  }\n\n  return commonAncestor;\n}\n\n/**\n * `findLeftmost` finds the leftmost node of the given tree.\n */\nexport function findLeftmost<T extends IndexTreeNode<T>>(node: T): T {\n  if (node.isText || node.children.length === 0) {\n    return node;\n  }\n\n  return findLeftmost(node.children[0]);\n}\n\n/**\n * `findTextPos` returns the tree position of the given path element.\n */\nfunction findTextPos<T extends IndexTreeNode<T>>(node: T, pathElement: number) {\n  if (node.visibleSize < pathElement) {\n    throw new YorkieError(Code.ErrInvalidArgument, 'unacceptable path');\n  }\n\n  for (let i = 0; i < node.children.length; i++) {\n    const child = node.children[i];\n\n    if (child.visibleSize < pathElement) {\n      pathElement -= child.visibleSize;\n    } else {\n      node = child;\n\n      break;\n    }\n  }\n\n  return { node, offset: pathElement };\n}\n\n/**\n * `IndexTree` is a tree structure for linear indexing.\n */\nexport class IndexTree<T extends IndexTreeNode<T>> {\n  private root: T;\n\n  constructor(root: T) {\n    this.root = root;\n  }\n\n  /**\n   * `tokensBetween` returns the tokens between the given range.\n   * If includeRemoved is true, it includes removed nodes in the calculation.\n   */\n  tokensBetween(\n    from: number,\n    to: number,\n    callback: (token: TreeToken<T>, ended: boolean) => void,\n    includeRemoved: boolean = false,\n  ): void {\n    tokensBetween<T>(this.root, from, to, callback, includeRemoved);\n  }\n\n  /**\n   * `traverse` traverses the tree with postorder traversal.\n   */\n  traverse(callback: (node: T) => void): void {\n    traverse(this.root, callback, 0);\n  }\n\n  /**\n   * `traverseAll` traverses the whole tree (include tombstones) with postorder traversal.\n   */\n  traverseAll(callback: (node: T) => void): void {\n    traverseAll(this.root, callback, 0);\n  }\n\n  /**\n   * findTreePos finds the position of the given index in the tree.\n   */\n  public findTreePos(index: number, preferText = true): TreePos<T> {\n    return findTreePos(this.root, index, preferText);\n  }\n\n  /**\n   * `treePosToPath` returns path from given treePos\n   */\n  public treePosToPath(treePos: TreePos<T>) {\n    const path = [];\n    let node = treePos.node;\n\n    if (node.isText) {\n      const offset = node.parent!.findOffset(node);\n      if (offset === -1) {\n        throw new YorkieError(Code.ErrInvalidArgument, 'invalid treePos');\n      }\n\n      const sizeOfLeftSiblings = addSizeOfLeftSiblings(\n        node.parent! as T,\n        offset,\n      );\n      path.push(sizeOfLeftSiblings + treePos.offset);\n      node = node.parent!;\n    } else if (node.hasTextChild()) {\n      // TODO(hackerwins): The function does not consider the situation\n      // where Element and Text nodes are mixed in the Element's Children.\n      const sizeOfLeftSiblings = addSizeOfLeftSiblings(\n        node! as T,\n        treePos.offset,\n      );\n      path.push(sizeOfLeftSiblings);\n    } else {\n      path.push(treePos.offset);\n    }\n\n    while (node.parent) {\n      const offset = node.parent.findOffset(node);\n      if (offset === -1) {\n        throw new YorkieError(Code.ErrInvalidArgument, 'invalid treePos');\n      }\n\n      path.push(offset);\n      node = node.parent;\n    }\n\n    return path.reverse();\n  }\n\n  /**\n   * `pathToIndex` returns index from given path\n   */\n  public pathToIndex(path: Array<number>): number {\n    const treePos = this.pathToTreePos(path);\n\n    return this.indexOf(treePos);\n  }\n\n  /**\n   * `pathToTreePos` returns treePos from given path\n   */\n  public pathToTreePos(path: Array<number>): TreePos<T> {\n    if (!path.length) {\n      throw new YorkieError(Code.ErrInvalidArgument, 'unacceptable path');\n    }\n\n    // Only the upper bound is checked below: a child index past the end stops\n    // at the missing child, and `findTextPos` compares against the content\n    // length. A negative element passes both tests, so reject it here and\n    // keep every caller of the resolver on the same contract.\n    if (path.some((pathElement) => pathElement < 0)) {\n      throw new YorkieError(Code.ErrInvalidArgument, 'unacceptable path');\n    }\n\n    let node = this.root;\n    for (let i = 0; i < path.length - 1; i++) {\n      const pathElement = path[i];\n      node = node.children[pathElement];\n\n      if (!node) {\n        throw new YorkieError(Code.ErrInvalidArgument, 'unacceptable path');\n      }\n    }\n\n    if (node.hasTextChild()) {\n      return findTextPos(node, path[path.length - 1]);\n    }\n\n    if (node.children.length < path[path.length - 1]) {\n      throw new YorkieError(Code.ErrInvalidArgument, 'unacceptable path');\n    }\n\n    return {\n      node,\n      offset: path[path.length - 1],\n    };\n  }\n\n  /**\n   * `getRoot` returns the root node of the tree.\n   */\n  public getRoot(): T {\n    return this.root;\n  }\n\n  /**\n   * `getSize` returns the size of the tree.\n   */\n  public get size(): number {\n    return this.root.visibleSize;\n  }\n\n  /**\n   * `findPostorderRight` finds right node of the given tree position with\n   *  postorder traversal.\n   */\n  public findPostorderRight(treePos: TreePos<T>): T | undefined {\n    const { node, offset } = treePos;\n\n    if (node.isText) {\n      if (node.visibleSize === offset) {\n        const nextSibling = node.nextSibling;\n        if (nextSibling) {\n          return nextSibling;\n        }\n\n        return node.parent;\n      }\n\n      return node;\n    }\n\n    if (node.children.length === offset) {\n      return node;\n    }\n\n    return findLeftmost(node.children[offset]);\n  }\n\n  /**\n   * `indexOf` returns the index of the given tree position.\n   * If includeRemoved is true, it includes removed nodes in the calculation.\n   */\n  public indexOf(pos: TreePos<T>, includeRemoved: boolean = false): number {\n    let { node } = pos;\n    const { offset } = pos;\n\n    let size = 0;\n    let depth = 1;\n    if (node.isText) {\n      size += offset;\n\n      const parent = node.parent! as T;\n      const offsetOfNode = parent.findOffset(node, includeRemoved);\n      if (offsetOfNode === -1) {\n        throw new YorkieError(Code.ErrInvalidArgument, 'invalid pos');\n      }\n\n      size += addSizeOfLeftSiblings(parent, offsetOfNode, includeRemoved);\n\n      node = node.parent!;\n    } else {\n      size += addSizeOfLeftSiblings(node, offset, includeRemoved);\n    }\n\n    while (node?.parent) {\n      const parent = node.parent;\n      const offsetOfNode = parent.findOffset(node, includeRemoved);\n      if (offsetOfNode === -1) {\n        throw new YorkieError(Code.ErrInvalidArgument, 'invalid pos');\n      }\n\n      size += addSizeOfLeftSiblings(parent, offsetOfNode, includeRemoved);\n      depth++;\n      node = node.parent;\n    }\n\n    return size + depth - 1;\n  }\n\n  /**\n   * `indexToPath` returns the path of the given index.\n   */\n  public indexToPath(index: number): Array<number> {\n    const treePos = this.findTreePos(index);\n    return this.treePosToPath(treePos);\n  }\n}\n","/*\n * Copyright 2023 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n  TimeTicket,\n  TimeTicketSize,\n  TimeTicketStruct,\n} from '@yorkie-js/sdk/src/document/time/ticket';\nimport {\n  VersionVector,\n  ticketKnown,\n} from '@yorkie-js/sdk/src/document/time/version_vector';\nimport { CRDTElement } from '@yorkie-js/sdk/src/document/crdt/element';\n\nimport type {\n  TreeNodeType,\n  TreeToken,\n} from '@yorkie-js/sdk/src/util/index_tree';\nimport {\n  DefaultTextType,\n  IndexTree,\n  IndexTreeNode,\n  TokenType,\n  traverseAll,\n  TreePos,\n} from '@yorkie-js/sdk/src/util/index_tree';\nimport { RHT, RHTNode, RHTWrite } from './rht';\nimport { ActorID } from './../time/actor_id';\nimport { LLRBTree } from '@yorkie-js/sdk/src/util/llrb_tree';\nimport { Comparator } from '@yorkie-js/sdk/src/util/comparator';\nimport {\n  parseAttrValue,\n  parseObjectValues,\n} from '@yorkie-js/sdk/src/util/object';\nimport { Indexable } from '@yorkie-js/sdk/src/document/document';\nimport type * as Devtools from '@yorkie-js/sdk/src/devtools/types';\nimport { ensureUTF16Boundary } from '@yorkie-js/sdk/src/document/json/strings';\nimport { GCChild, GCPair, GCParent } from '@yorkie-js/sdk/src/document/crdt/gc';\nimport { Code, YorkieError } from '@yorkie-js/sdk/src/util/error';\nimport { logger } from '@yorkie-js/sdk/src/util/logger';\nimport {\n  DataSize,\n  DocSize,\n  addDataSizes,\n  subDataSize,\n} from '../../util/resource';\n\n/**\n * `TreeNode` represents a node in the tree.\n */\nexport type TreeNode = TextNode | ElementNode;\n\n/**\n * `ElementNode` represents an element node. It has an attributes and children.\n */\nexport type ElementNode<A extends Indexable = Indexable> = {\n  type: TreeNodeType;\n  attributes?: A;\n  children: Array<TreeNode>;\n};\n\n/**\n * `TextNode` represents a text node. It has a string value.\n */\nexport type TextNode = {\n  type: typeof DefaultTextType;\n  value: string;\n};\n\n/**\n * `TreeNodeForTest` represents the JSON representation of a node in the tree.\n * It is used for testing.\n */\nexport type TreeNodeForTest = TreeNode & {\n  children?: Array<TreeNodeForTest>;\n  visibleSize: number;\n  isRemoved: boolean;\n};\n\n/**\n * `TreeChangeType` represents the type of change in the tree.\n */\nexport enum TreeChangeType {\n  Content = 'content',\n  Style = 'style',\n  RemoveStyle = 'removeStyle',\n}\n\n/**\n * `TreeChange` represents the change in the tree.\n */\nexport type TreeChange =\n  | {\n      actor: ActorID;\n      type: TreeChangeType.Content;\n      from: number;\n      to: number;\n      fromPath: Array<number>;\n      toPath: Array<number>;\n      value?: Array<TreeNode>;\n      splitLevel?: number;\n    }\n  | {\n      actor: ActorID;\n      type: TreeChangeType.Style;\n      from: number;\n      to: number;\n      fromPath: Array<number>;\n      toPath: Array<number>;\n      value: { [key: string]: string };\n      splitLevel?: number;\n    }\n  | {\n      actor: ActorID;\n      type: TreeChangeType.RemoveStyle;\n      from: number;\n      to: number;\n      fromPath: Array<number>;\n      toPath: Array<number>;\n      value?: Array<string>;\n      splitLevel?: number;\n    };\n\n/**\n * `TreeVisibleEdit` is a content change an identity-preserving restore or\n * retombstone made, paired with the visible size it inserted (zero for a\n * deletion). The change alone does not carry that size — an insertion reports\n * a collapsed range — and undo-stack reconciliation cannot shift the pending\n * indices without it.\n */\nexport type TreeVisibleEdit = {\n  change: TreeChange;\n  insertedSize: number;\n};\n\n/**\n * `CRDTTreePos` represent a position in the tree. It is used to identify a\n * position in the tree. It is composed of the parent ID and the left sibling\n * ID. If there's no left sibling in parent's children, then left sibling is\n * parent.\n */\nexport class CRDTTreePos {\n  private parentID: CRDTTreeNodeID;\n  private leftSiblingID: CRDTTreeNodeID;\n\n  constructor(parentID: CRDTTreeNodeID, leftSiblingID: CRDTTreeNodeID) {\n    this.parentID = parentID;\n    this.leftSiblingID = leftSiblingID;\n  }\n\n  /**\n   * `of` creates a new instance of CRDTTreePos.\n   */\n  public static of(parentID: CRDTTreeNodeID, leftSiblingID: CRDTTreeNodeID) {\n    return new CRDTTreePos(parentID, leftSiblingID);\n  }\n\n  /**\n   * `fromTreePos` creates a new instance of CRDTTreePos from the given TreePos.\n   */\n  public static fromTreePos(pos: TreePos<CRDTTreeNode>): CRDTTreePos {\n    const { offset } = pos;\n    let { node } = pos;\n    let leftNode;\n\n    if (node.isText) {\n      if (offset === 0) {\n        // A text at offset 0 cannot anchor on itself: a left sibling means\n        // \"after it\", so the edit would land after the whole text. Anchor on\n        // what precedes the text instead -- the previous visible sibling, or\n        // the parent when the text is the first visible child.\n        //\n        // That sibling is always an element: findTreePos resolves a boundary\n        // between two texts to the end of the left one, so a text reached at\n        // offset 0 never has a text right before it.\n        leftNode = node.prevSibling ?? node.parent!;\n      } else {\n        leftNode = node;\n      }\n\n      node = node.parent!;\n    } else {\n      if (offset === 0) {\n        leftNode = node;\n      } else {\n        leftNode = node.children[offset - 1];\n      }\n    }\n\n    return CRDTTreePos.of(\n      node.id,\n      CRDTTreeNodeID.of(leftNode.getCreatedAt(), leftNode.getOffset() + offset),\n    );\n  }\n\n  /**\n   * `getParentID` returns the parent ID.\n   */\n  public getParentID() {\n    return this.parentID;\n  }\n\n  /**\n   * `fromStruct` creates a new instance of CRDTTreeNodeID from the given struct.\n   */\n  public static fromStruct(struct: CRDTTreePosStruct): CRDTTreePos {\n    return CRDTTreePos.of(\n      CRDTTreeNodeID.of(\n        TimeTicket.fromStruct(struct.parentID.createdAt),\n        struct.parentID.offset,\n      ),\n      CRDTTreeNodeID.of(\n        TimeTicket.fromStruct(struct.leftSiblingID.createdAt),\n        struct.leftSiblingID.offset,\n      ),\n    );\n  }\n\n  /**\n   * `toStruct` returns the structure of this position.\n   */\n  public toStruct(): CRDTTreePosStruct {\n    return {\n      parentID: {\n        createdAt: this.getParentID().getCreatedAt().toStruct(),\n        offset: this.getParentID().getOffset(),\n      },\n      leftSiblingID: {\n        createdAt: this.getLeftSiblingID().getCreatedAt().toStruct(),\n        offset: this.getLeftSiblingID().getOffset(),\n      },\n    };\n  }\n\n  /**\n   * `toTreeNodePair` converts the pos to parent and left sibling nodes.\n   * If the position points to the middle of a node, then the left sibling node\n   * is the node that contains the position. Otherwise, the left sibling node is\n   * the node that is located at the left of the position.\n   */\n  public toTreeNodePair(tree: CRDTTree): TreeNodePair {\n    const parentID = this.getParentID();\n    const leftSiblingID = this.getLeftSiblingID();\n    const parentNode = tree.findFloorNode(parentID);\n    let leftNode = tree.findFloorNode(leftSiblingID);\n    if (!parentNode || !leftNode) {\n      throw new YorkieError(\n        Code.ErrRefused,\n        `cannot find node of CRDTTreePos(${parentID.toTestString()}, ${leftSiblingID.toTestString()})`,\n      );\n    }\n\n    /**\n     * NOTE(hackerwins): If the left node and the parent node are the same,\n     * it means that the position is the left-most of the parent node.\n     * We need to skip finding the left of the position.\n     */\n    if (\n      !leftSiblingID.equals(parentID) &&\n      leftSiblingID.getOffset() > 0 &&\n      leftSiblingID.getOffset() === leftNode.id.getOffset() &&\n      leftNode.insPrevID\n    ) {\n      leftNode = tree.findFloorNode(leftNode.insPrevID)!;\n    }\n\n    return [parentNode, leftNode];\n  }\n\n  /**\n   * `getLeftSiblingID` returns the left sibling ID.\n   */\n  public getLeftSiblingID() {\n    return this.leftSiblingID;\n  }\n\n  /**\n   * `equals` returns whether the given pos equals to this or not.\n   */\n  public equals(other: CRDTTreePos): boolean {\n    return (\n      this.getParentID()\n        .getCreatedAt()\n        .equals(other.getParentID().getCreatedAt()) &&\n      this.getParentID().getOffset() === other.getParentID().getOffset() &&\n      this.getLeftSiblingID()\n        .getCreatedAt()\n        .equals(other.getLeftSiblingID().getCreatedAt()) &&\n      this.getLeftSiblingID().getOffset() ===\n        other.getLeftSiblingID().getOffset()\n    );\n  }\n\n  /**\n   * `replaceNodeID` returns this position with `prev` replaced by `curr`\n   * wherever it names the parent or the left sibling, or this position\n   * itself when it names neither.\n   */\n  public replaceNodeID(\n    prev: CRDTTreeNodeID,\n    curr: CRDTTreeNodeID,\n  ): CRDTTreePos {\n    const parentID = replaceTreeNodeID(this.parentID, prev, curr);\n    const leftSiblingID = replaceTreeNodeID(this.leftSiblingID, prev, curr);\n\n    return parentID === this.parentID && leftSiblingID === this.leftSiblingID\n      ? this\n      : CRDTTreePos.of(parentID, leftSiblingID);\n  }\n}\n\n/**\n * `replaceTreeNodeID` returns `id` re-pointed from the node `prev` names to\n * the node `curr` names, or `id` itself when it names a different node.\n *\n * The match is on the creation ticket alone, and the offset is carried over\n * rather than taken from `curr`: a node id names a node by its creation\n * ticket, while the offset says WHERE in that node the reference lands --\n * the child index when a position names an element as its left sibling\n * (`CRDTTreePos.fromTreePos`), the character offset inside a text node.\n * Comparing the offset too, as `CRDTTreeNodeID.equals` does, would miss every\n * reference that is not to the node's own head.\n */\nexport function replaceTreeNodeID(\n  id: CRDTTreeNodeID,\n  prev: CRDTTreeNodeID,\n  curr: CRDTTreeNodeID,\n): CRDTTreeNodeID {\n  if (id.getCreatedAt().compare(prev.getCreatedAt()) !== 0) {\n    return id;\n  }\n\n  return CRDTTreeNodeID.of(curr.getCreatedAt(), id.getOffset());\n}\n\n/**\n * `CRDTTreeNodeID` represent an ID of a node in the tree. It is used to\n * identify a node in the tree. It is composed of the creation time of the node\n * and the offset from the beginning of the node if the node is split.\n *\n * Some of replicas may have nodes that are not split yet. In this case, we can\n * use `map.floorEntry()` to find the adjacent node.\n */\nexport class CRDTTreeNodeID {\n  /**\n   * `createdAt` is the creation time of the node.\n   */\n  private createdAt: TimeTicket;\n\n  /**\n   * `offset` is the distance from the beginning of the node if the node is\n   * split.\n   */\n  private offset: number;\n\n  constructor(createdAt: TimeTicket, offset: number) {\n    this.createdAt = createdAt;\n    this.offset = offset;\n  }\n\n  /**\n   * `of` creates a new instance of CRDTTreeNodeID.\n   */\n  public static of(createdAt: TimeTicket, offset: number): CRDTTreeNodeID {\n    return new CRDTTreeNodeID(createdAt, offset);\n  }\n\n  /**\n   * `fromStruct` creates a new instance of CRDTTreeNodeID from the given struct.\n   */\n  public static fromStruct(struct: CRDTTreeNodeIDStruct): CRDTTreeNodeID {\n    return CRDTTreeNodeID.of(\n      TimeTicket.fromStruct(struct.createdAt),\n      struct.offset,\n    );\n  }\n\n  /**\n   * `createComparator` creates a comparator for CRDTTreeNodeID.\n   */\n  public static createComparator(): Comparator<CRDTTreeNodeID> {\n    return (idA: CRDTTreeNodeID, idB: CRDTTreeNodeID) => {\n      const compare = idA.getCreatedAt().compare(idB.getCreatedAt());\n      if (compare !== 0) {\n        return compare;\n      }\n      if (idA.getOffset() > idB.getOffset()) {\n        return 1;\n      } else if (idA.getOffset() < idB.getOffset()) {\n        return -1;\n      }\n      return 0;\n    };\n  }\n\n  /**\n   * `getCreatedAt` returns the creation time of the node.\n   */\n  public getCreatedAt(): TimeTicket {\n    return this.createdAt;\n  }\n\n  /**\n   * `equals` returns whether given ID equals to this ID or not.\n   */\n  public equals(other: CRDTTreeNodeID): boolean {\n    return (\n      this.createdAt.compare(other.createdAt) === 0 &&\n      this.offset === other.offset\n    );\n  }\n\n  /**\n   * `getOffset` returns returns the offset of the node.\n   */\n  public getOffset(): number {\n    return this.offset;\n  }\n\n  /**\n   * `setOffset` sets the offset of the node.\n   */\n  public setOffset(offset: number): void {\n    this.offset = offset;\n  }\n\n  /**\n   * `toStruct` returns the structure of this position.\n   */\n  public toStruct(): CRDTTreeNodeIDStruct {\n    return {\n      createdAt: this.createdAt.toStruct(),\n      offset: this.offset,\n    };\n  }\n\n  /**\n   * `toIDString` returns a string that can be used as an ID for this position.\n   */\n  public toIDString(): string {\n    return `${this.createdAt.toIDString()}:${this.offset}`;\n  }\n\n  /**\n   * `toTestString` returns a string containing the meta data of the ticket\n   * for debugging purpose.\n   */\n  public toTestString(): string {\n    return `${this.createdAt.toTestString()}/${this.offset}`;\n  }\n}\n\n/**\n * `CRDTTreePosStruct` represents the structure of CRDTTreePos.\n */\nexport type CRDTTreePosStruct = {\n  parentID: CRDTTreeNodeIDStruct;\n  leftSiblingID: CRDTTreeNodeIDStruct;\n};\n\n/**\n * `CRDTTreeNodeIDStruct` represents the structure of CRDTTreeNodeID.\n * It is used to serialize and deserialize the CRDTTreeNodeID.\n */\nexport type CRDTTreeNodeIDStruct = {\n  createdAt: TimeTicketStruct;\n  offset: number;\n};\n\n/**\n * `TreePosRange` represents a pair of CRDTTreePos.\n */\nexport type TreePosRange = [CRDTTreePos, CRDTTreePos];\n\n/**\n * `TreeNodePair` represents a pair of CRDTTreeNode. It represents the position\n * of the node in the tree with the left and parent nodes.\n */\ntype TreeNodePair = [CRDTTreeNode, CRDTTreeNode];\n\n/**\n * `TreePosStructRange` represents the structure of TreeRange.\n * It is used to serialize and deserialize the TreeRange.\n */\nexport type TreePosStructRange = [CRDTTreePosStruct, CRDTTreePosStruct];\n\n/**\n * `TreeRestoreSpan` identifies a node this edit transitioned\n * visible → tombstoned, for identity-preserving Tree undo/redo. For text\n * nodes the span is the absolute-offset interval [id.offset, id.offset +\n * length) of the original insertion (split-invariant); for element nodes it\n * is the whole node. `value`/`attrs` are deep-copied so a GC-purged node can\n * be recreated. `leftSiblingID`/`rightSiblingID` are the deleted run's\n * external boundary anchors captured at tombstone time — redundant on\n * purpose: since a run's spans are carried together, restore can rebuild the\n * run's internal order from the op itself and needs only ONE surviving\n * boundary to place it (id-order is not sibling-order in a tree).\n */\nexport type TreeRestoreSpan = {\n  id: CRDTTreeNodeID;\n  nodeType: string;\n  isText: boolean;\n  length: number; // text length; 0 for elements\n  value?: string; // text content copy\n  attrs?: RHT; // element attribute snapshot\n  parentID?: CRDTTreeNodeID;\n  leftSiblingID?: CRDTTreeNodeID; // undefined → was first child\n  rightSiblingID?: CRDTTreeNodeID; // undefined → was last child\n};\n\n/**\n * `restoreSpanKindAgrees` reports whether the span's `isText` flag matches its\n * `nodeType`, as it always does on a span an honest replica captured. A span\n * that disagrees would recreate a node of the wrong kind -- an element\n * carrying a value is then invisible to the text lookup, so the same span\n * applied again inserts a second node under one ID. Decoding cannot reject it:\n * stored changes go through the same decoder and must stay loadable, so\n * `restore` and `retombstone` skip it instead. The kind is part of the span\n * itself, so every replica skips it alike. Mirrors Go's\n * `TreeRestoreSpan.kindAgrees` (yorkie#2168).\n */\nfunction restoreSpanKindAgrees(span: TreeRestoreSpan): boolean {\n  return span.isText === (span.nodeType === DefaultTextType);\n}\n\n/**\n * `CRDTTreeNode` is a node of CRDTTree. It includes the logical clock and\n * links to other nodes to resolve conflicts.\n */\nexport class CRDTTreeNode\n  extends IndexTreeNode<CRDTTreeNode>\n  implements GCParent, GCChild\n{\n  id: CRDTTreeNodeID;\n  removedAt?: TimeTicket;\n  attrs?: RHT;\n\n  /**\n   * `insPrevID` is the previous node id of this node after the node is split.\n   */\n  insPrevID?: CRDTTreeNodeID;\n\n  /**\n   * `insNextID` is the previous node id of this node after the node is split.\n   */\n  insNextID?: CRDTTreeNodeID;\n\n  /**\n   * `mergedFrom` records the parent this node logically belongs to when\n   * a merge relocated it into the merge target: the source parent it was\n   * moved out of, or the declared parent of an insert redirected by the\n   * §9.4 intended-parent stamp. Persisted in the snapshot encoding as\n   * the witness of the merge relationship.\n   */\n  mergedFrom?: CRDTTreeNodeID;\n\n  /**\n   * `mergedAt` records the immutable ticket of the merge operation.\n   * Persisted alongside `mergedFrom` because the source parent's\n   * `removedAt` may be overwritten by later LWW tombstones and thus\n   * cannot serve as the merge-time causal boundary for splitElement's\n   * Fix 8 version-vector check.\n   */\n  mergedAt?: TimeTicket;\n\n  /**\n   * `mergedInto` is a runtime cache set on the source parent pointing\n   * at the merge target. Set locally during merge execution and rebuilt\n   * from `mergedFrom` on snapshot load — on both paths only while the\n   * source is a tombstone, so `unremove` drops it again. Used for the fast\n   * \"is this tombstoned parent a merge source?\" check in\n   * `FindTreeNodesWithSplitText`; the alternative (scanning\n   * `nodeMapByID` on every position resolution) would be too expensive.\n   */\n  mergedInto?: CRDTTreeNodeID;\n\n  _value = '';\n\n  constructor(\n    id: CRDTTreeNodeID,\n    type: string,\n    opts?: string | Array<CRDTTreeNode>,\n    attributes?: RHT,\n    removedAt?: TimeTicket,\n  ) {\n    super(type);\n    this.id = id;\n    this.removedAt = removedAt;\n    if (attributes) {\n      this.attrs = attributes;\n    }\n\n    if (typeof opts === 'string') {\n      this.value = opts;\n    } else if (Array.isArray(opts)) {\n      this._children = opts;\n    }\n  }\n\n  /**\n   * `toIDString` returns the IDString of this node.\n   */\n  toIDString(): string {\n    return this.id.toIDString();\n  }\n\n  /**\n   * `getRemovedAt` returns the time when this node was removed.\n   */\n  getRemovedAt(): TimeTicket | undefined {\n    return this.removedAt;\n  }\n\n  /**\n   * `create` creates a new instance of CRDTTreeNode.\n   */\n  static create(\n    id: CRDTTreeNodeID,\n    type: string,\n    opts?: string | Array<CRDTTreeNode>,\n    attributes?: RHT,\n  ) {\n    return new CRDTTreeNode(id, type, opts, attributes);\n  }\n\n  /**\n   * `deepcopy` copies itself deeply.\n   */\n  deepcopy(): CRDTTreeNode {\n    const clone = new CRDTTreeNode(this.id, this.type);\n    clone.removedAt = this.removedAt;\n    clone._value = this._value;\n    clone.visibleSize = this.visibleSize;\n    clone.totalSize = this.totalSize;\n    clone.attrs = this.attrs?.deepcopy();\n    clone._children = this._children.map((child) => {\n      const childClone = child.deepcopy();\n      childClone.parent = clone;\n      return childClone;\n    });\n    clone.insPrevID = this.insPrevID;\n    clone.insNextID = this.insNextID;\n    clone.mergedFrom = this.mergedFrom;\n    clone.mergedAt = this.mergedAt;\n    clone.mergedInto = this.mergedInto;\n    return clone;\n  }\n\n  /**\n   * `value` returns the value of the node.\n   */\n  get value() {\n    if (!this.isText) {\n      throw new YorkieError(\n        Code.ErrInvalidType,\n        `cannot get value of element node: ${this.type}`,\n      );\n    }\n\n    return this._value;\n  }\n\n  /**\n   * `value` sets the value of the node.\n   */\n  set value(v: string) {\n    if (!this.isText) {\n      throw new YorkieError(\n        Code.ErrInvalidType,\n        `cannot set value of element node: ${this.type}`,\n      );\n    }\n\n    this._value = v;\n    this.visibleSize = v.length;\n    this.totalSize = v.length;\n  }\n\n  /**\n   * `dropSplitLinks` clears the split-sibling links on this node and every one\n   * of its descendants.\n   *\n   * insPrevID/insNextID name positions in a split chain and only\n   * `splitElement` may create them. A node arriving as operation content is\n   * freshly created by the editing client, so it can never legitimately be a\n   * split product — but the wire format carries the links regardless, and the\n   * walks that read them treat them as trusted structural pointers.\n   *\n   * The merge lineage is deliberately left alone here: unlike operation\n   * content, an element payload can be a deep copy of real document state\n   * (the reverse of a Remove restores the tree as it stood, merges and all),\n   * and erasing mergedFrom/mergedAt would switch off the §1.1 insert redirect\n   * and the §6.2 propagation skip for a tree that legitimately earned them.\n   * Only `dropEngineOnlyLinks`, which runs on content no merge can have\n   * touched, clears those.\n   */\n  public dropSplitLinks(): void {\n    traverseAll(this as CRDTTreeNode, (node: CRDTTreeNode) => {\n      node.insPrevID = undefined;\n      node.insNextID = undefined;\n    });\n  }\n\n  /**\n   * `dropEngineOnlyLinks` clears the engine-only links on this node and every\n   * one of its descendants: the split-sibling chain and the merge lineage.\n   *\n   * It is the operation-content counterpart of `dropSplitLinks`.\n   * `mergedFrom`/`mergedAt` name the parent a node was moved out of and only\n   * a merge may stamp them (`edit` restamps them on the content it inserts,\n   * from the merge parent it resolves locally), so content arriving on a\n   * TreeEdit -- always freshly created by the editing client, never a copy of\n   * live state -- can never legitimately carry them, while the §1.1 redirect\n   * and §6.2 propagation read them as trusted structural pointers.\n   * `mergedInto` goes with them: the decoder derives it from `mergedFrom`, so\n   * leaving it would keep a source pointing at a destination no field records\n   * any more.\n   */\n  public dropEngineOnlyLinks(): void {\n    traverseAll(this as CRDTTreeNode, (node: CRDTTreeNode) => {\n      node.insPrevID = undefined;\n      node.insNextID = undefined;\n      node.mergedFrom = undefined;\n      node.mergedAt = undefined;\n      node.mergedInto = undefined;\n    });\n  }\n\n  /**\n   * `clearTombstones` clears the tombstone on this node and every one of its\n   * descendants, restoring the sizes a decoded tombstone suppressed.\n   *\n   * Like the engine-only links, `removedAt` is carried by the wire format on\n   * every tree node yet operation content can never legitimately hold it: a\n   * TreeEdit's content is freshly created by the editing client, so a node\n   * arriving tombstoned is a crafted one. Left in place, `edit` counts it\n   * into the live data size and registers no GC pair for it under a live\n   * parent, while `isRemoved` hides it from every later edit.\n   *\n   * Cleared via `unremove` so each node's padded size is given back to its\n   * ancestors. `traverseAll` is post-order, so a child is revived before its\n   * parent, and the parent's own size already includes the child when the\n   * parent hands it further up.\n   *\n   * A node's attribute table carries tombstones of its own, and those are\n   * deliberately NOT cleared here. Unlike `removedAt` on the node, a removed\n   * RHT entry on content can be genuine: the undo copy-reinsert path re-sends\n   * a `deepcopy` of nodes a real `removeStyle` tombstoned, and it has to, or\n   * the reinserted node would stop rejecting the stale styles the original\n   * rejects. Stripping them on decode would also make this replica disagree\n   * with every other producer of the same bytes -- an older yorkie-js-sdk, the\n   * Go SDK, and the snapshot the server rebuilds from this very operation --\n   * which is divergence, not hardening. A crafted one is instead made\n   * harmless the way every other decode path already makes it harmless:\n   * `edit` books it into gc through `CRDTTreeNode.getGCPairs`, the same\n   * routing the snapshot and the Set/Add element payload take through\n   * `CRDTTree.getGCPairs`.\n   */\n  public clearTombstones(): void {\n    traverseAll(this as CRDTTreeNode, (node: CRDTTreeNode) => {\n      node.unremove();\n    });\n  }\n\n  /**\n   * `isRemoved` returns whether the node is removed or not.\n   */\n  get isRemoved(): boolean {\n    return !!this.removedAt;\n  }\n\n  /**\n   * `remove` marks the node as removed.\n   */\n  remove(removedAt: TimeTicket): boolean {\n    if (!this.removedAt) {\n      this.removedAt = removedAt;\n      // NOTE(hackerwins): Decrease only visibleSize because\n      // this node marked as tombstone, not purged.\n      this.updateAncestorsSize(-this.paddedSize());\n      return true;\n    }\n\n    // NOTE(sigmaith): Overwrite if newer tombstone.\n    // This enables LWW for concurrent deletions.\n    if (removedAt.after(this.removedAt)) {\n      this.removedAt = removedAt;\n    }\n    return false;\n  }\n\n  /**\n   * `unremove` clears the tombstone of this node (identity-preserving\n   * restore). Mirrors `remove()`'s ancestor-size bookkeeping so the node\n   * becomes visible again in place.\n   *\n   * The forwarding pointer goes with the tombstone: both writers of\n   * `mergedInto` (the merge in `edit` and `rebuildMergeState`) only ever set\n   * it on a source that is already removed, so a live node holding one is a\n   * pointer a snapshot-loading replica would not rebuild. `CRDTTree.restore`\n   * drops the matching `mergedFrom` stamps on the children the merge moved,\n   * so nothing is left for a later re-remove to derive it from either.\n   */\n  unremove(): void {\n    if (!this.removedAt) {\n      return;\n    }\n    this.removedAt = undefined;\n    this.mergedInto = undefined;\n    this.updateAncestorsSize(this.paddedSize());\n  }\n\n  /**\n   * `cloneText` clones this text node with the given offset.\n   */\n  cloneText(offset: number): CRDTTreeNode {\n    const clone = new CRDTTreeNode(\n      CRDTTreeNodeID.of(this.id.getCreatedAt(), offset),\n      this.type,\n      undefined,\n      undefined,\n      this.removedAt,\n    );\n    clone.mergedFrom = this.mergedFrom;\n    clone.mergedAt = this.mergedAt;\n    return clone;\n  }\n\n  /**\n   * `cloneElement` clones this element node with the given issueTimeTicket function.\n   */\n  cloneElement(issueTimeTicket: () => TimeTicket): CRDTTreeNode {\n    const clone = new CRDTTreeNode(\n      CRDTTreeNodeID.of(issueTimeTicket(), 0),\n      this.type,\n      undefined,\n      this.attrs?.deepcopy(),\n      this.removedAt,\n    );\n    // The split product holds the other half of the same moved node, so\n    // it carries the same merge stamp (as cloneText does).\n    clone.mergedFrom = this.mergedFrom;\n    clone.mergedAt = this.mergedAt;\n    return clone;\n  }\n\n  /**\n   * `split` splits the given offset of this node.\n   */\n  public split(\n    tree: CRDTTree,\n    offset: number,\n    issueTimeTicket?: () => TimeTicket,\n    versionVector?: VersionVector,\n  ): [CRDTTreeNode | undefined, DataSize] {\n    const [split, diff] = this.isText\n      ? this.splitText(offset, this.id.getOffset())\n      : this.splitElement(offset, issueTimeTicket!, versionVector);\n\n    if (split) {\n      split.insPrevID = this.id;\n      if (this.insNextID) {\n        const insNext = tree.findFloorNode(this.insNextID);\n        split.insNextID = this.insNextID;\n\n        if (insNext) {\n          insNext.insPrevID = split.id;\n\n          // §7.4 Empty Sibling Re-Parenting: When the existing\n          // InsNext sibling is in a different parent (due to a prior\n          // parent-level split), move the new empty split sibling to\n          // that parent. VV-independent for clone/root consistency.\n          // Skip when insNext has been tombstoned (e.g. by an undo\n          // boundary deletion): re-parenting into a removed element\n          // would make the new split sibling invisible.\n          if (\n            !this.isText &&\n            insNext.parent &&\n            !insNext.isRemoved &&\n            insNext.parent !== split.parent &&\n            split.allChildren.length === 0\n          ) {\n            // Moved rather than detached and re-inserted: a split born\n            // tombstoned contributes no visibleSize to either parent, so\n            // detaching would take its tokens off the source that it never\n            // held and re-inserting would give the destination tokens it must\n            // not have. `moveChildBefore` carries the same tombstone-aware\n            // semantics `moveChild` documents.\n            insNext.parent.moveChildBefore(split, insNext);\n          }\n        }\n      }\n      this.insNextID = split.id;\n      tree.registerNode(split);\n\n      // NOTE: `splitElement` deep-copies the node's attributes, tombstones\n      // included -- it has to, or the two halves of what was one node would\n      // resolve a concurrent style differently and never reconverge. Each\n      // copied tombstone is a distinct piece of garbage that no removal path\n      // produced, so buffer a registration for it; otherwise it sits in the\n      // split's RHT forever, uncounted and unpurgeable.\n      //\n      // `getDataSize` skips removed attributes, so the split's diff never\n      // charged these to docSize.live -- `gcOnlySize` sends each straight to\n      // docSize.gc, and purge subtracts the same amount back. This is the\n      // same routing `getGCPairs` already uses for the tombstones a snapshot\n      // rebuild finds.\n      for (const pair of split.getGCPairs()) {\n        tree.pushPendingGCPair(pair);\n      }\n\n      // NOTE: A piece split off an already-tombstoned node inherits\n      // `removedAt` without going through `remove()`, so no GC pair is\n      // created for it in the normal deletion path. Register it here so\n      // it can be purged; otherwise it stays in the tree forever.\n      // The piece was never live, so its size goes straight to docSize.gc\n      // when the pair is registered; report a zero diff to the caller\n      // (which accounts diffs to docSize.live).\n      if (split.removedAt) {\n        tree.registerPendingGCPair(split, diff);\n        return [split, { data: 0, meta: 0 }];\n      }\n    }\n    return [split, diff];\n  }\n\n  /**\n   * `getCreatedAt` returns the creation time of this element.\n   */\n  public getCreatedAt(): TimeTicket {\n    return this.id.getCreatedAt();\n  }\n\n  /**\n   * `getOffset` returns the offset of a pos.\n   */\n  public getOffset(): number {\n    return this.id.getOffset();\n  }\n\n  /**\n   * `canDelete` checks if node is able to delete.\n   */\n  public canDelete(\n    editedAt: TimeTicket,\n    creationKnown: boolean,\n    tombstoneKnown: boolean,\n  ): boolean {\n    // NOTE(sigmaith): Skip if the node's creation was not visible to this operation.\n    if (!creationKnown) {\n      return false;\n    }\n\n    if (!this.removedAt) {\n      return true;\n    }\n\n    // NOTE(sigmaith): Overwrite only if prior tombstone was not known\n    // (concurrent or unseen) and newer. This enables LWW for concurrent deletions.\n    if (!tombstoneKnown && editedAt?.after(this.removedAt)) {\n      return true;\n    }\n    return false;\n  }\n\n  /**\n   * `canStyle` checks if node is able to style. It answers the same question\n   * as `RGATreeSplitNode.canStyle`, the same way — see the contract there.\n   */\n  public canStyle(versionVector?: VersionVector): boolean {\n    return !this.isText && ticketKnown(versionVector, this.getCreatedAt());\n  }\n\n  /**\n   * `setAttrs` sets the attributes of the node.\n   */\n  public setAttrs(\n    attrs: { [key: string]: string },\n    editedAt: TimeTicket,\n  ): Array<RHTWrite> {\n    if (!this.attrs) {\n      this.attrs = new RHT();\n    }\n\n    const writes: Array<RHTWrite> = [];\n    for (const [key, value] of Object.entries(attrs)) {\n      writes.push(this.attrs.set(key, value, editedAt));\n    }\n\n    return writes;\n  }\n\n  /**\n   * `purge` purges the given child node.\n   */\n  public purge(node: RHTNode): void {\n    if (this.attrs) {\n      this.attrs.purge(node);\n    }\n  }\n\n  /**\n   * `getDataSize` returns the data size of the node.\n   */\n  public getDataSize(): DataSize {\n    const dataSize = { data: 0, meta: 0 };\n\n    if (this.isText) {\n      dataSize.data += this.visibleSize * 2;\n    }\n\n    if (this.id) {\n      dataSize.meta += TimeTicketSize;\n    }\n\n    if (this.removedAt) {\n      dataSize.meta += TimeTicketSize;\n    }\n\n    if (this.attrs) {\n      for (const node of this.attrs) {\n        if (node.getRemovedAt()) {\n          continue;\n        }\n\n        const size = node.getDataSize();\n        dataSize.meta += size.meta;\n        dataSize.data += size.data;\n      }\n    }\n\n    return dataSize;\n  }\n\n  /**\n   * `getGCPairs` returns the pairs of GC.\n   */\n  public getGCPairs(): Array<GCPair> {\n    const pairs: Array<GCPair> = [];\n    if (!this.attrs) {\n      return pairs;\n    }\n\n    // NOTE: Removed attribute nodes are skipped by `getDataSize`, so they\n    // were never counted into docSize.live — hence `gcOnlySize`.\n    for (const node of this.attrs) {\n      if (node.getRemovedAt()) {\n        pairs.push({\n          parent: this,\n          child: node,\n          gcOnlySize: node.getDataSize(),\n        });\n      }\n    }\n\n    return pairs;\n  }\n}\n\n/**\n * `attrGCPair` builds the GC pair for an RHT node a style edit turned into\n * garbage, deciding which half of the ledger it moves through. Three cases,\n * because the NODE holding the attribute may itself be a tombstone —\n * `canStyle` admits one removed concurrently with the change:\n *\n * - live attr on a live node — in live, so move live → gc the usual way.\n * - live attr on a REMOVED node — the container skips a removed node\n *   (`CRDTText.getDataSize`, `CRDTTree.getDataSize`; the per-NODE functions\n *   count a live attribute either way), so it is not in live; its bytes are\n *   already inside the gc charge taken when the node was removed, and\n *   removing the attribute shrinks that charge by exactly them. Charging them\n *   again doubles them, so the pair carries exactly zero.\n * - attr that was already a tombstone — never in live, and not inside the\n *   node's charge either, so it carries its own size.\n *\n * Charging case 2 or 3 to live walked the live size down by the attribute's\n * size on every such edit, without bound — a rich-text editor toggling one key\n * is exactly that loop — and drove it negative, at which point the document\n * size limit stops applying.\n *\n * Shared by the tree and the text halves: both hold attributes in an RHT and\n * must answer this the same way, which they historically did not (#1341).\n */\nexport function attrGCPair(\n  parent: GCParent,\n  child: RHTNode,\n  attrWasLive: boolean,\n  nodeIsLive: boolean,\n): GCPair {\n  if (attrWasLive && nodeIsLive) {\n    return { parent, child };\n  }\n\n  // A live attribute on a removed node is already counted inside that node's\n  // gc charge.\n  const gcOnlySize = attrWasLive ? { data: 0, meta: 0 } : child.getDataSize();\n  return { parent, child, gcOnlySize };\n}\n\n/**\n * `accAttrWrite` books one attribute write into the ledger. It reads only what\n * the write reported, never the map: a write that lost LWW installed nothing,\n * so it must charge nothing, and a node visited twice in one traversal (once\n * as Start and once as End) loses LWW on the second visit and is naturally\n * deduped. Deciding from the map instead made live depend on delivery order\n * and, where a token guard suppressed only one half, drove it negative.\n */\nexport function accAttrWrite(\n  write: RHTWrite,\n  parent: GCParent,\n  nodeIsLive: boolean,\n  pairs: Array<GCPair>,\n  size: DocSize,\n): void {\n  if (write.revived !== undefined) {\n    pairs.push(attrGCPair(parent, write.revived, false, nodeIsLive));\n  }\n\n  // `nodeIsLive` is false when the container does not count this node's\n  // attributes in live at all -- a tombstoned node, which `CRDTText\n  // .getDataSize` and `CRDTTree.getDataSize` both skip. (The per-NODE\n  // functions do NOT skip; the exclusion lives in the container.) Booking\n  // either half to live there drifts it by the SIGNED difference between the\n  // two values' sizes, and a shrinking overwrite takes it negative.\n  //\n  // The bytes are not nowhere, though: they are inside the gc charge the\n  // node's removal took, and collection subtracts the node's size as it\n  // stands when it is purged. So the same delta goes to gc, or registration\n  // and purge stop agreeing about that one node -- which a style concurrent\n  // with a removal reaches on the replica that receives it, see `canStyle`.\n  const target = nodeIsLive ? size.live : size.gc;\n\n  if (write.superseded !== undefined) {\n    subDataSize(target, write.superseded.getDataSize());\n  }\n  if (write.installed !== undefined) {\n    addDataSizes(target, write.installed.getDataSize());\n  }\n}\n\n/**\n * `toTreeNode` converts the given CRDTTreeNode to TreeNode.\n */\nfunction toTreeNode(node: CRDTTreeNode): TreeNode {\n  if (node.isText) {\n    const currentNode = node;\n    return {\n      type: currentNode.type,\n      value: currentNode.value,\n    } as TextNode;\n  }\n\n  const treeNode: TreeNode = {\n    type: node.type,\n    children: node.children.map(toTreeNode),\n  };\n\n  if (node.attrs) {\n    treeNode.attributes = parseObjectValues(node.attrs?.toObject());\n  }\n\n  return treeNode;\n}\n\nconst xmlEscapes: Record<string, string> = {\n  '&': '&amp;',\n  '<': '&lt;',\n  '>': '&gt;',\n  '\"': '&quot;',\n  \"'\": '&apos;',\n};\n\n/**\n * `escapeXMLAttr` escapes a name or a value for interpolation into a\n * double-quoted XML attribute.\n *\n * Both halves are peer-chosen: the key is whatever `Style` was called with,\n * and the value is what `parseAttrValue` read back -- including, for a peer\n * that stores values raw, the raw string itself. Interpolated unescaped, a\n * `\"` closes the attribute and a `<` opens an element, so an attribute could\n * forge structure in the markup `toXML` builds. This is the same forging\n * `CRDTTextValue.toJSON` closes for the JSON encoding of a Text attribute.\n */\nfunction escapeXMLAttr(value: string): string {\n  return value.replace(/[&<>\"']/g, (character) => xmlEscapes[character]);\n}\n\n/**\n * `toXML` converts the given CRDTNode to XML string.\n */\nexport function toXML(node: CRDTTreeNode): string {\n  if (node.isText) {\n    const currentNode = node;\n    return currentNode.value;\n  }\n\n  let attrs = '';\n  if (node.attrs && node.attrs.size()) {\n    attrs =\n      ' ' +\n      Array.from(node.attrs)\n        .filter((n) => !n.isRemoved())\n        .sort((a, b) => a.getKey().localeCompare(b.getKey()))\n        .map((n) => {\n          // See `parseAttrValue`: a peer that stores values raw writes ones\n          // this cannot parse, and rendering must not throw on them. The raw\n          // string it falls back to is rendered as the value; anything else\n          // keeps the JSON form it is stored as.\n          const obj = parseAttrValue(n.getValue());\n          const value = typeof obj === 'string' ? obj : n.getValue();\n          return `${escapeXMLAttr(n.getKey())}=\"${escapeXMLAttr(value)}\"`;\n        })\n        .join(' ');\n  }\n\n  return `<${node.type}${attrs}>${node.children\n    .map((child) => toXML(child))\n    .join('')}</${node.type}>`;\n}\n\n/**\n * `toTestTreeNode` converts the given CRDTNode JSON for debugging.\n */\nfunction toTestTreeNode(node: CRDTTreeNode): TreeNodeForTest {\n  if (node.isText) {\n    const currentNode = node;\n    return {\n      type: currentNode.type,\n      value: currentNode.value,\n      visibleSize: currentNode.visibleSize,\n      isRemoved: currentNode.isRemoved,\n    } as TreeNodeForTest;\n  }\n\n  return {\n    type: node.type,\n    children: node.children.map(toTestTreeNode),\n    visibleSize: node.visibleSize,\n    isRemoved: node.isRemoved,\n  };\n}\n\n/**\n * `InsNextWalker` bounds a walk of an insNextID chain.\n *\n * insNextID is a structural pointer that only `splitElement` is supposed to\n * set, but it also arrives verbatim from client-supplied bytes, so a chain\n * that loops back on itself would spin the applying task forever. Every\n * chain walk runs through one of these.\n */\nclass InsNextWalker {\n  private seen: Set<CRDTTreeNode> = new Set();\n\n  /**\n   * `visit` records `node` and reports whether this walk had not already\n   * passed through it. A false result means the chain is cyclic; stop\n   * following it.\n   */\n  public visit(node: CRDTTreeNode): boolean {\n    if (this.seen.has(node)) {\n      return false;\n    }\n    this.seen.add(node);\n\n    return true;\n  }\n}\n\n/**\n * `DeclaredLineage` answers, for one change, the two questions `styleTargets`\n * asks of every node it visits: is this node the element a position declared\n * as its parent (or an ancestor of it), matched through the split lineage.\n *\n * Both questions used to be answered per node by walking the declared parent's\n * whole current ancestry and, for each ancestor, its `insPrevID` chain --\n * pointers a peer controls, so one style message over a wide range bought\n * O(range x depth x chain) work, with a fresh cycle-guard set per step, on\n * every replica that applied it. Nothing in those walks depends on the node\n * being asked about, so they run once per change here: `covers` is then a set\n * lookup, and `coversEitherWay`'s one remaining direction is memoized per\n * node, so each node costs its own chain at most once.\n */\ninterface DeclaredLineage {\n  /**\n   * `covers` reports whether `node` is one of the declared ancestors, or a\n   * piece a split cut off one of them.\n   */\n  covers(node: CRDTTreeNode): boolean;\n\n  /**\n   * `coversEitherWay` is `covers` plus the opposite direction: it also matches\n   * when a declared ancestor is a piece a split cut off `node`.\n   */\n  coversEitherWay(node: CRDTTreeNode): boolean;\n}\n\n/**\n * `CRDTTree` is a CRDT implementation of a tree.\n */\nexport class CRDTTree extends CRDTElement implements GCParent {\n  private indexTree: IndexTree<CRDTTreeNode>;\n  private nodeMapByID: LLRBTree<CRDTTreeNodeID, CRDTTreeNode>;\n\n  /**\n   * `pendingGCPairs` buffers GC pairs for nodes that were created\n   * already-tombstoned by splitting a removed node. Such pieces inherit\n   * `removedAt` without ever passing through `remove()`, so they would\n   * otherwise never be registered for GC. `edit` and `style` drain this\n   * buffer into their returned GC pairs.\n   */\n  private pendingGCPairs: Array<GCPair>;\n\n  constructor(root: CRDTTreeNode, createdAt: TimeTicket) {\n    super(createdAt);\n    this.indexTree = new IndexTree<CRDTTreeNode>(root);\n    this.nodeMapByID = new LLRBTree(CRDTTreeNodeID.createComparator());\n    this.pendingGCPairs = [];\n\n    // Registering every node is the cost of loading a document, so it runs\n    // without the duplicate check: a plain put per node, then one comparison\n    // to see whether any ID was claimed twice. Only a tree that carries\n    // duplicates pays for resolving them.\n    let nodeCount = 0;\n    this.indexTree.traverseAll((node) => {\n      this.nodeMapByID.put(node.id, node);\n      nodeCount++;\n    });\n    if (this.nodeMapByID.size() !== nodeCount) {\n      this.indexTree.traverseAll((node) => {\n        this.registerNode(node);\n      });\n    }\n\n    // Rebuild runtime merge state from the persisted `mergedFrom`\n    // field. Only `mergedFrom` and `mergedAt` are written to the\n    // snapshot encoding; `mergedInto` is a cache reconstructed here\n    // so replicas loaded from a snapshot can still handle concurrent\n    // ops that target merged-away parents (Fix 3 redirect, Fix 5\n    // propagation, Fix 8 split skip).\n    this.rebuildMergeState();\n  }\n\n  /**\n   * `rebuildMergeState` reconstructs the `mergedInto` cache on source\n   * parents from the persisted `mergedFrom` field on moved children.\n   * For snapshots written before `mergedAt` was added to the proto,\n   * it also falls back to the source's `removedAt` — an approximation\n   * that may be wrong if the source was later overwritten by a\n   * concurrent delete, but this is the best we can do without the\n   * persisted merge ticket.\n   */\n  private rebuildMergeState(): void {\n    this.indexTree.traverseAll((node) => {\n      if (!node.mergedFrom || !node.parent) {\n        return;\n      }\n      // `findMergeNode`, not `findFloorNode`: `mergedFrom` is client-supplied\n      // on an element payload (Set/Add/ArraySet), so the source it names has\n      // to be the node it names exactly, and an element.\n      const src = this.findMergeNode(node.mergedFrom);\n      if (!src) {\n        return;\n      }\n\n      // A merge moves children under an element parent, so a child sitting\n      // under a text node cannot be one a merge moved. Only a snapshot is\n      // guaranteed well-formed here: an element payload passes through this\n      // same reader and keeps its `mergedFrom`, because the reverse of a\n      // Remove legitimately carries the merges the tree really underwent.\n      // Deriving a forwarding pointer at a text node from a crafted one would\n      // hand a later insert a parent that can hold no children.\n      if (node.parent.isText) {\n        return;\n      }\n\n      // A merge only ever names a source the merge itself removed: the\n      // boundary element is tombstoned in step 02 of `edit` before its\n      // children are moved in step 03, so a live element is never a merge\n      // source. `mergedFrom` is client-supplied on an element payload, so\n      // without this check a crafted one plants a forwarding pointer on a\n      // live, unrelated element -- arming the §1.1 position redirect and the\n      // §6.2 delete cascade to fire on that element's own live children the\n      // moment some later, innocent edit removes it.\n      if (!src.removedAt) {\n        return;\n      }\n\n      // Back-compat: older snapshots lack mergedAt on moved children.\n      if (!node.mergedAt) {\n        node.mergedAt = src.removedAt;\n      }\n\n      if (!src.mergedInto) {\n        src.mergedInto = node.parent.id;\n      }\n    });\n  }\n\n  /**\n   * `create` creates a new instance of `CRDTTree`.\n   */\n  public static create(root: CRDTTreeNode, ticket: TimeTicket): CRDTTree {\n    return new CRDTTree(root, ticket);\n  }\n\n  /**\n   * `findFloorNode` finds node of given id.\n   */\n  public findFloorNode(id: CRDTTreeNodeID): CRDTTreeNode | undefined {\n    const entry = this.nodeMapByID.floorEntry(id);\n    if (!entry || !entry.key.getCreatedAt().equals(id.getCreatedAt())) {\n      return;\n    }\n\n    return entry.value;\n  }\n\n  /**\n   * `findMergeNode` returns the element whose id is exactly `id`, or\n   * undefined. Unlike `findFloorNode` it refuses a floor-only match (a split\n   * product this replica does not hold) and a text node: a merge pointer\n   * names an element, so either would hand merge logic a node the pointer\n   * never named.\n   *\n   * Every merge-lineage read goes through here, not only the decode that\n   * first sees a pointer: `mergedFrom` is retained on an element payload\n   * (Set/Add/ArraySet), persists on the node inside the live document, and\n   * `mergedInto` is derived from it. Otherwise a made-up offset becomes a\n   * forwarding pointer planted on an unrelated node, which a later, innocent\n   * delete follows to tombstone that node's live children.\n   */\n  private findMergeNode(id?: CRDTTreeNodeID): CRDTTreeNode | undefined {\n    if (!id) {\n      return;\n    }\n    const node = this.findFloorNode(id);\n    if (!node || !node.id.equals(id) || node.isText) {\n      return;\n    }\n    return node;\n  }\n\n  /**\n   * `declaredBoundaries` returns the elements the edit's own positions named\n   * as boundaries: the element each position declared as its parent, and\n   * every ancestor of that element. A range stops at those rather than\n   * covering them -- the edit asks to merge their remaining content away, not\n   * to delete it -- so a concurrent merge that already moved their children\n   * where this edit would have put them did this edit's work rather than\n   * something it now has to undo.\n   *\n   * The declared parent is resolved with `findMergeNode`, not a floor lookup:\n   * a floor lookup matches on createdAt alone, so a parentID naming a split\n   * product this replica does not hold would land on the offset-0 element and\n   * hand the skip to a node the position never named.\n   *\n   * The walk upward prefers `mergedFrom` over the physical parent: a prior\n   * merge moves a node under the merge target, so the parent no longer names\n   * the element that enclosed it when the position was declared. The set\n   * doubles as the seen set, guarding against a cycle in a client-supplied\n   * `mergedFrom` chain. Mirrors yorkie's `declaredBoundaries` (yorkie#2042).\n   */\n  private declaredBoundaries(\n    ...positions: Array<CRDTTreePos>\n  ): Set<CRDTTreeNode> {\n    const boundaries = new Set<CRDTTreeNode>();\n    for (const pos of positions) {\n      let current = this.findMergeNode(pos.getParentID());\n      while (current && !boundaries.has(current)) {\n        boundaries.add(current);\n        current =\n          this.findMergeNode(current.mergedFrom) ??\n          (current.parent as CRDTTreeNode | undefined);\n      }\n    }\n    return boundaries;\n  }\n\n  /**\n   * `tombstoneSubtree` tombstones `node` and every live node below it with\n   * `editedAt`, returning the nodes it actually tombstoned, in post-order. A\n   * node already removed keeps its own `removedAt` and is not reported again,\n   * which also keeps the result disjoint from the nodes step 02 removed.\n   */\n  private tombstoneSubtree(\n    node: CRDTTreeNode,\n    editedAt: TimeTicket,\n  ): Array<CRDTTreeNode> {\n    const removed: Array<CRDTTreeNode> = [];\n    traverseAll(node, (n) => {\n      if (n.removedAt) {\n        return;\n      }\n      if (n.remove(editedAt)) {\n        removed.push(n);\n      }\n    });\n    return removed;\n  }\n\n  /**\n   * `resolveMergeTarget` follows the `mergedInto` forwarding chain from the\n   * given node while the current node is a merge-away tombstone, returning\n   * the final live target. When a merge lands on a parent that a prior\n   * concurrent merge already merged away (a chained merge P->Q->R, applied\n   * Q->R before this P->Q), the children must flow to that parent's final\n   * destination so the merge chain stays flat (P->R, not P->Q) and both\n   * replicas converge. The seen set guards against cycles from a concurrent\n   * mutual merge.\n   *\n   * Each link is resolved through `findMergeNode`, so a text node or a\n   * floor-only match cuts the chain: `mergedInto` is derived from the\n   * `mergedFrom` an element payload keeps, so a crafted one can name either,\n   * and the merge hands what this returns straight to `moveChild`.\n   */\n  private resolveMergeTarget(node: CRDTTreeNode): CRDTTreeNode {\n    let target = node;\n    const seen = new Set<CRDTTreeNode>([target]);\n    while (target.isRemoved && target.mergedInto) {\n      const next = this.findMergeNode(target.mergedInto);\n      if (!next || seen.has(next)) {\n        break;\n      }\n      seen.add(next);\n      target = next;\n    }\n    return target;\n  }\n\n  /**\n   * `mergeSourceOf` returns the id of the removed element whose children a\n   * split has just taken back, or undefined when the split re-creates\n   * nothing.\n   *\n   * A merge moves a boundary element's children into the merge target and\n   * tombstones the element, stamping each moved child with `mergedFrom`\n   * naming it. Reversing that merge is a split, which mints a BRAND-NEW\n   * element -- it cannot revive the tombstone, whose id belongs to a change\n   * every replica already applied -- and moves the stamped children into it.\n   * So a split product holding children stamped for a removed element is the\n   * replacement for that element, and anything recorded against the element\n   * has to follow (#1425).\n   *\n   * Derived from the tree rather than carried on the operation because a peer\n   * has to reach the same conclusion from the change alone: the operation\n   * encodes only the split's tickets, never what they replace.\n   *\n   * Narrow on purpose. A split that merely happens to cut through a merge\n   * target keeps some of the source's children on the left, and its product\n   * is a new sibling rather than the source's stand-in -- re-pointing at it\n   * would move references onto a node holding only part of what they named.\n   * Only a split that takes the source's children back WHOLE reverses the\n   * merge, so `splitTarget` is checked for leftovers.\n   */\n  private mergeSourceOf(\n    splitNode: CRDTTreeNode,\n    splitTarget: CRDTTreeNode,\n  ): CRDTTreeNodeID | undefined {\n    const stampedFor = (node: CRDTTreeNode, id: CRDTTreeNodeID) =>\n      node.allChildren.some(\n        (child) =>\n          child.mergedFrom &&\n          child.mergedFrom.getCreatedAt().compare(id.getCreatedAt()) === 0,\n      );\n\n    for (const child of splitNode.allChildren) {\n      const mergedFrom = child.mergedFrom;\n      if (!mergedFrom) {\n        continue;\n      }\n      // The product carries its own `mergedFrom` copied off the node it split\n      // (`cloneElement`); a child stamped for that same element was merged in\n      // one level up and is not what this split re-created.\n      if (\n        splitNode.mergedFrom &&\n        mergedFrom\n          .getCreatedAt()\n          .compare(splitNode.mergedFrom.getCreatedAt()) === 0\n      ) {\n        continue;\n      }\n      const source = this.findFloorNode(mergedFrom);\n      if (\n        source &&\n        source.isRemoved &&\n        source.id.getCreatedAt().compare(mergedFrom.getCreatedAt()) === 0 &&\n        !stampedFor(splitTarget, source.id)\n      ) {\n        return source.id;\n      }\n    }\n\n    return undefined;\n  }\n\n  /**\n   * `mergedAnchorInterloperGuard` prepares the §9.4 per-node filter for a\n   * style range whose end position was declared inside a parent that a\n   * merge unknown to the styling client removed. The moved anchor child\n   * resolves in the merge target, so the traversal covers nodes sitting\n   * between the merge-source tombstone and the moved children — nodes the\n   * styling client saw outside its range, after the then-live parent. The\n   * predicate skips exactly those interlopers.\n   */\n  private mergedAnchorInterloperGuard(\n    pos: CRDTTreePos,\n    versionVector?: VersionVector,\n  ):\n    | {\n        isInterloper: (node: CRDTTreeNode) => boolean;\n        declaredParent: CRDTTreeNode;\n        target: CRDTTreeNode;\n      }\n    | undefined {\n    if (versionVector === undefined) {\n      return;\n    }\n    const [declaredParent] = pos.toTreeNodePair(this);\n    if (\n      !declaredParent.isRemoved ||\n      !declaredParent.mergedInto ||\n      !declaredParent.removedAt ||\n      ticketKnown(versionVector, declaredParent.removedAt)\n    ) {\n      return;\n    }\n    const target = this.resolveMergeTarget(declaredParent);\n    // Restricted to the shape where the tombstone sits directly under the\n    // merge target; in other shapes the resolved range already excludes\n    // the interlopers.\n    if (target === declaredParent || declaredParent.parent !== target) {\n      return;\n    }\n    // Collect the target's children positioned after the merge-source\n    // tombstone in one pass, so the predicate is O(depth) per node.\n    const afterTombstone = new Set<CRDTTreeNode>();\n    let seenTombstone = false;\n    for (const child of target.allChildren) {\n      if (child === declaredParent) {\n        seenTombstone = true;\n        continue;\n      }\n      if (seenTombstone) {\n        afterTombstone.add(child);\n      }\n    }\n    return {\n      isInterloper: (node: CRDTTreeNode): boolean => {\n        // Judge by the node's highest ancestor directly under the merge\n        // target, so an interloper's descendants are skipped with it.\n        let top = node;\n        while (top.parent && top.parent !== target) {\n          top = top.parent as CRDTTreeNode;\n        }\n        if (top.parent !== target) {\n          return false;\n        }\n        // Fail open on any merge stamp: an earlier merge keeps the\n        // ORIGINAL source in mergedFrom (first-move stamp rule), so\n        // stamp equality cannot prove the node was outside the styled\n        // range. Only stamp-free nodes are positively interlopers.\n        if (top.mergedFrom) {\n          return false;\n        }\n        return afterTombstone.has(top);\n      },\n      declaredParent,\n      target,\n    };\n  }\n\n  /**\n   * `reversedFromAnchorRecovery` prepares the §9.4 from-side counterpart of\n   * `mergedAnchorInterloperGuard` for a style range whose start position was\n   * declared inside a parent that a merge unknown to the styling client\n   * removed. The resolved range then collapses (start past end) and the\n   * traversal misses nodes the styling client covered. The recovery\n   * re-anchors the traversal start just after the last live sibling before\n   * the merge-source tombstone; the caller must style only nodes the\n   * returned predicate positively identifies as interlopers. Stamped nodes\n   * in the span stay out of reach and fail open unstyled — see the §9.4\n   * known limitations in yorkie's concurrent-merge-split design doc.\n   */\n  private reversedFromAnchorRecovery(\n    from: CRDTTreePos,\n    to: CRDTTreePos,\n    fromParent: CRDTTreeNode,\n    fromLeft: CRDTTreeNode,\n    toParent: CRDTTreeNode,\n    toLeft: CRDTTreeNode,\n    versionVector?: VersionVector,\n  ):\n    | {\n        fromParent: CRDTTreeNode;\n        fromLeft: CRDTTreeNode;\n        isInterloper: (node: CRDTTreeNode) => boolean;\n      }\n    | undefined {\n    const guard = this.mergedAnchorInterloperGuard(from, versionVector);\n    if (!guard) {\n      return;\n    }\n    // Only a range that actually collapsed needs recovery: when both\n    // anchors moved with the merge, the resolved range stays ordered and\n    // still covers what the styling client covered. A range that resolved\n    // empty counts as collapsed too -- the merge can leave the start anchor\n    // exactly on the end one, and covering nothing loses the client's range\n    // just as completely as covering it backwards. Unless the client's own\n    // range was empty, in which case covering nothing is right.\n    const fromIdx = this.toIndex(fromParent, fromLeft);\n    const toIdx = this.toIndex(toParent, toLeft);\n    if (fromIdx < toIdx || (fromIdx === toIdx && from.equals(to))) {\n      return;\n    }\n    const { declaredParent, target } = guard;\n    let anchorLeft: CRDTTreeNode = target;\n    for (const child of target.allChildren) {\n      if (child === declaredParent) {\n        break;\n      }\n      if (!child.isRemoved) {\n        anchorLeft = child;\n      }\n    }\n    return {\n      fromParent: target,\n      fromLeft: anchorLeft,\n      isInterloper: guard.isInterloper,\n    };\n  }\n\n  /**\n   * `styleSkipPredicate` builds the per-token skip checks shared by style\n   * and removeStyle, as two predicates over the same state.\n   *\n   * `skipReached` answers \"did the change reach this node at all\": the\n   * End-token unknown-split-sibling exclusion (§9.1), the §9.6 range-start\n   * guard and the §9.4 merged-anchor interloper filter for the range-end\n   * position. It is about the change, so it holds for every node a style\n   * writes to, however that node was found.\n   *\n   * `skipToken` adds the one restriction that belongs to the index traversal\n   * alone -- the §9.4 from-side recovery re-anchors the traversal start over\n   * nodes the change never covered, so a recovered traversal may touch only\n   * the interlopers the recovery positively identified. Nodes derived from\n   * the change's own positions are not in that widened span and answer to\n   * `skipReached` only.\n   *\n   * `beganInside` is the set of elements THIS replica's resolved range begins\n   * inside -- the resolved from-parent and its ancestors, the only elements a\n   * token traversal reaches through their End token alone.\n   */\n  private styleSkipPredicate(\n    from: CRDTTreePos,\n    to: CRDTTreePos,\n    fromParent: CRDTTreeNode,\n    versionVector?: VersionVector,\n    recoveredInterloper?: (node: CRDTTreeNode) => boolean,\n  ): {\n    skipToken: (token: TreeToken<CRDTTreeNode>) => boolean;\n    skipReached: (token: TreeToken<CRDTTreeNode>) => boolean;\n    declaredTo: DeclaredLineage | undefined;\n    declaredFrom: DeclaredLineage | undefined;\n  } {\n    const isVersionVectorEmpty = !versionVector || versionVector.size() === 0;\n    const anchorGuard = this.mergedAnchorInterloperGuard(to, versionVector);\n    // Resolved once and handed back to `styleTargets`: the lineage walks are\n    // over peer-supplied pointers and depend only on the change's positions.\n    const declaredTo = this.declaredLineage(to);\n    const declaredFrom = this.declaredLineage(from);\n\n    const beganInside = new Set<CRDTTreeNode>();\n    for (\n      let current: CRDTTreeNode | undefined = fromParent;\n      current;\n      current = current.parent as CRDTTreeNode | undefined\n    ) {\n      beganInside.add(current);\n    }\n\n    const skipReached = ([node, tokenType]: TreeToken<CRDTTreeNode>) => {\n      // §9.1: skip styling via the End token when the node has an unknown\n      // split sibling AND the change's range ended inside the node. Only\n      // then is the End token in the range solely because a concurrent\n      // split extended the range into the sibling. When the range ran past\n      // the node's end the End token was in it before any split existed.\n      if (\n        tokenType === TokenType.End &&\n        !isVersionVectorEmpty &&\n        (!declaredTo || declaredTo.covers(node)) &&\n        this.hasUnknownSplitSibling(node, versionVector!)\n      ) {\n        return true;\n      }\n      // §9.6, the mirror of §9.1 on the range-start side. This replica's\n      // range begins inside the node, so only its End token is in the\n      // range; the change reached it that way only if the change's own\n      // range-start position was declared inside it. A merge that removes a\n      // paragraph's opening tag moves its children, and the start anchor\n      // with them, into an element the change never entered.\n      if (\n        tokenType === TokenType.End &&\n        !isVersionVectorEmpty &&\n        beganInside.has(node) &&\n        declaredFrom &&\n        !declaredFrom.coversEitherWay(node)\n      ) {\n        return true;\n      }\n      // §9.4: the node is in the range only because an unknown merge\n      // pulled the range-end anchor past it.\n      return !!anchorGuard && anchorGuard.isInterloper(node);\n    };\n\n    const skipToken = (token: TreeToken<CRDTTreeNode>) => {\n      if (skipReached(token)) {\n        return true;\n      }\n      // §9.4 from-side: a recovered traversal may only touch nodes the\n      // collapsed range lost, the positively identified interlopers.\n      return !!recoveredInterloper && !recoveredInterloper(token[0]);\n    };\n\n    return { skipToken, skipReached, declaredTo, declaredFrom };\n  }\n\n  /**\n   * `beginsAtOrBefore` reports whether the change's declared range-start sits\n   * at or before `node`'s Start token in document order, both measured with\n   * removed nodes included so a concurrent removal between the two moves\n   * neither. A position that does not resolve answers no, as Go's\n   * `beginsAtOrInside` does.\n   */\n  private beginsAtOrBefore(node: CRDTTreeNode, from: CRDTTreePos): boolean {\n    if (!node.parent) {\n      return false;\n    }\n    try {\n      const [parent, left] = from.toTreeNodePair(this);\n      // A concurrent merge can move the left sibling out of the declared\n      // parent. Go's FindOffset fails there; findOffset here returns -1 and\n      // toTreePos would resolve offset 0, so the case is refused explicitly.\n      if (left !== parent && left.parent !== parent) {\n        return false;\n      }\n      const offset = node.parent.findOffset(node, true);\n      const nodeIdx = this.indexTree.indexOf(\n        { node: node.parent, offset },\n        true,\n      );\n      const declaredIdx = this.toIndex(parent, left, true);\n      return declaredIdx >= 0 && declaredIdx <= nodeIdx;\n    } catch {\n      return false;\n    }\n  }\n\n  /**\n   * `declaredParentOf` returns the element a position named as its parent,\n   * or undefined when this replica cannot resolve the position.\n   */\n  private declaredParentOf(pos: CRDTTreePos): CRDTTreeNode | undefined {\n    const parent = this.findFloorNode(pos.getParentID());\n    if (!parent || !this.findFloorNode(pos.getLeftSiblingID())) {\n      return;\n    }\n    return parent;\n  }\n\n  /**\n   * `splitOriginsOf` walks back along `insPrevID` from `node`, feeding each\n   * element it passes to `visit` and stopping when `visit` returns false.\n   * Only `splitElement` sets `insPrevID` on an element, so the chain is\n   * exactly the split lineage; the walker stops a crafted chain that loops\n   * back on itself, and a text link cuts it.\n   */\n  private splitOriginsOf(\n    node: CRDTTreeNode,\n    visit: (origin: CRDTTreeNode) => boolean,\n  ): void {\n    const walker = new InsNextWalker();\n    let current: CRDTTreeNode | undefined = node;\n    walker.visit(current);\n    while (current && visit(current)) {\n      if (!current.insPrevID) {\n        return;\n      }\n      const prev = this.findFloorNode(current.insPrevID);\n      if (!prev || prev.isText || !walker.visit(prev)) {\n        return;\n      }\n      current = prev;\n    }\n  }\n\n  /**\n   * `declaredLineageOf` resolves, once for a change, everything\n   * `DeclaredLineage` answers about the element a position declared as its\n   * parent: the element's current ancestry, and the split lineage of each\n   * ancestor.\n   */\n  private declaredLineageOf(declaredParent: CRDTTreeNode): DeclaredLineage {\n    // Every element a declared ancestor was split from. `endsInside` asked\n    // this one ancestor at a time; the union answers all of them at once, and\n    // a chain already walked needs no second walk because the chain back from\n    // an element is fixed.\n    const ancestors = new Set<CRDTTreeNode>();\n    const products = new Set<CRDTTreeNode>();\n    for (\n      let ancestor: CRDTTreeNode | undefined = declaredParent;\n      ancestor;\n      ancestor = ancestor.parent as CRDTTreeNode | undefined\n    ) {\n      ancestors.add(ancestor);\n      this.splitOriginsOf(ancestor, (origin) => {\n        if (products.has(origin)) {\n          return false;\n        }\n        products.add(origin);\n\n        return true;\n      });\n    }\n\n    // The opposite direction -- a declared ancestor is a piece split off the\n    // node being asked about -- cannot be precomputed, since it starts from\n    // that node. Memoize it instead: the answer for a node is the answer for\n    // every node whose chain runs through it, so one walk settles the whole\n    // prefix it passed.\n    const reversed = new Map<CRDTTreeNode, boolean>();\n    const reaches = (node: CRDTTreeNode): boolean => {\n      const cached = reversed.get(node);\n      if (cached !== undefined) {\n        return cached;\n      }\n      const walked: Array<CRDTTreeNode> = [];\n      let found = false;\n      this.splitOriginsOf(node, (origin) => {\n        if (ancestors.has(origin)) {\n          found = true;\n\n          return false;\n        }\n        const memo = reversed.get(origin);\n        if (memo !== undefined) {\n          found = memo;\n\n          return false;\n        }\n        walked.push(origin);\n\n        return true;\n      });\n      for (const visited of walked) {\n        reversed.set(visited, found);\n      }\n\n      return found;\n    };\n\n    return {\n      covers: (node: CRDTTreeNode): boolean => products.has(node),\n      coversEitherWay: (node: CRDTTreeNode): boolean =>\n        products.has(node) || reaches(node),\n    };\n  }\n\n  /**\n   * `declaredAncestryHas` walks the CURRENT ancestry of the element a\n   * position named as its parent, up to the root, and reports whether any of\n   * them matches.\n   */\n  private declaredAncestryHas(\n    declaredParent: CRDTTreeNode,\n    match: (ancestor: CRDTTreeNode) => boolean,\n  ): boolean {\n    for (\n      let current: CRDTTreeNode | undefined = declaredParent;\n      current;\n      current = current.parent as CRDTTreeNode | undefined\n    ) {\n      if (match(current)) {\n        return true;\n      }\n    }\n    return false;\n  }\n\n  /**\n   * `declaredLineage` is `declaredLineageOf` for the element `pos` named as\n   * its parent, or undefined when this replica cannot resolve the position.\n   *\n   * `covers` on the result is \"the change's range ended inside this node\":\n   * whether the node is the element the position named, or an ancestor of it.\n   * The ancestry is the current one, and a concurrent split moves the children\n   * after the split point into the new right half, so each ancestor is matched\n   * through its split lineage: every product of splitting the node stands for\n   * the node.\n   *\n   * `coversEitherWay` is the same question for the range-start position\n   * (§9.6), matching in BOTH directions along the split lineage: a split of\n   * the element the range began inside leaves the start anchor in whichever\n   * half holds it, and both halves are the element the change began inside.\n   * For the range-end side the extra matches would make a guard that excludes\n   * nodes fail open, so that side uses `covers`.\n   */\n  private declaredLineage(pos: CRDTTreePos): DeclaredLineage | undefined {\n    const declaredParent = this.declaredParentOf(pos);\n\n    return declaredParent ? this.declaredLineageOf(declaredParent) : undefined;\n  }\n\n  /**\n   * `unknownSplitSiblings` returns the elements a split concurrent with the\n   * change produced from `node`: its `insNextID` chain, stopped at the first\n   * sibling the change already knew about. A style that covered `node`\n   * covered these too, because the change resolved its range while `node`\n   * was still one piece.\n   */\n  private unknownSplitSiblings(\n    node: CRDTTreeNode,\n    versionVector?: VersionVector,\n  ): Array<CRDTTreeNode> {\n    const siblings: Array<CRDTTreeNode> = [];\n    const walker = new InsNextWalker();\n    let current = node;\n    walker.visit(current);\n    while (current.insNextID) {\n      const next = this.findFloorNode(current.insNextID);\n      if (!next || next.isText) {\n        break;\n      }\n      // Stop on a chain that loops back on itself; see InsNextWalker.\n      if (!walker.visit(next)) {\n        break;\n      }\n      if (ticketKnown(versionVector, next.id.getCreatedAt())) {\n        break;\n      }\n      siblings.push(next);\n      current = next;\n    }\n    return siblings;\n  }\n\n  /**\n   * `splitFamilyOf` walks back along `insPrevID` from an element whose\n   * creation the change did not know, collecting the products a concurrent\n   * split made of a node it did know. It returns the family in document\n   * order, that known node first, or an empty array when the chain reaches\n   * no such node -- a node simply new to the change.\n   */\n  private splitFamilyOf(\n    node: CRDTTreeNode,\n    versionVector?: VersionVector,\n  ): Array<CRDTTreeNode> {\n    const reversed = [node];\n    const walker = new InsNextWalker();\n    let current = node;\n    walker.visit(current);\n    while (current.insPrevID) {\n      const prev = this.findFloorNode(current.insPrevID);\n      if (!prev || prev.isText || !walker.visit(prev)) {\n        return [];\n      }\n      reversed.push(prev);\n      if (prev.canStyle(versionVector)) {\n        return reversed.reverse();\n      }\n      current = prev;\n    }\n    return [];\n  }\n\n  /**\n   * `boundaryRangeCovers` reports whether the change declared a range that\n   * covers at least one element, so that reconstructing its boundary\n   * elements is repair rather than invention. A range whose two positions\n   * are equal covers nothing on any replica. A range that resolves\n   * backwards covers nothing here either; only a removal collapses a range,\n   * so an inversion with a live declared ancestry on both ends is the\n   * caller's own and gets nothing.\n   */\n  private boundaryRangeCovers(\n    from: CRDTTreePos,\n    to: CRDTTreePos,\n    fromParent: CRDTTreeNode,\n    fromLeft: CRDTTreeNode,\n    toParent: CRDTTreeNode,\n    toLeft: CRDTTreeNode,\n  ): boolean {\n    if (from.equals(to)) {\n      return false;\n    }\n    if (this.toIndex(fromParent, fromLeft) <= this.toIndex(toParent, toLeft)) {\n      return true;\n    }\n    return (\n      this.declaredAncestryRemoved(from) || this.declaredAncestryRemoved(to)\n    );\n  }\n\n  /**\n   * `declaredAncestryRemoved` reports whether the element a position named\n   * as its parent, or any ancestor of it, has been removed -- the only way a\n   * range declared forwards can resolve backwards here.\n   */\n  private declaredAncestryRemoved(pos: CRDTTreePos): boolean {\n    const parent = this.declaredParentOf(pos);\n    return !!parent && this.declaredAncestryHas(parent, (n) => n.isRemoved);\n  }\n\n  /**\n   * `boundaryElements` returns the elements the change reached through a\n   * single token on the replica that issued it: the ancestors of the\n   * range-start position, whose End tokens the range ran past, and the\n   * ancestors of the range-end position, whose Start tokens it ran past --\n   * each chain stopping below the common ancestor of the two. Each element is\n   * returned with the token the range ran past, so the caller can put it\n   * through the same per-token skip checks the traversal applies.\n   *\n   * These come from the positions the change carries, which never move, so\n   * every replica computes the same set whatever a concurrent merge did to\n   * the index space.\n   */\n  private boundaryElements(\n    from: CRDTTreePos,\n    to: CRDTTreePos,\n  ): Array<TreeToken<CRDTTreeNode>> {\n    const fromParent = this.declaredParentOf(from);\n    const toParent = this.declaredParentOf(to);\n    if (!fromParent || !toParent) {\n      return [];\n    }\n\n    const fromAncestors = new Set<CRDTTreeNode>();\n    for (\n      let current: CRDTTreeNode | undefined = fromParent;\n      current;\n      current = current.parent as CRDTTreeNode | undefined\n    ) {\n      fromAncestors.add(current);\n    }\n\n    // The common ancestor is the first ancestor of the range-end position\n    // that also sits above the range-start position.\n    let common: CRDTTreeNode | undefined;\n    const startTokens: Array<TreeToken<CRDTTreeNode>> = [];\n    for (\n      let current: CRDTTreeNode | undefined = toParent;\n      current;\n      current = current.parent as CRDTTreeNode | undefined\n    ) {\n      if (fromAncestors.has(current)) {\n        common = current;\n        break;\n      }\n      startTokens.push([current, TokenType.Start]);\n    }\n    if (!common) {\n      return [];\n    }\n\n    const elements: Array<TreeToken<CRDTTreeNode>> = [];\n    for (\n      let current: CRDTTreeNode | undefined = fromParent;\n      current && current !== common;\n      current = current.parent as CRDTTreeNode | undefined\n    ) {\n      elements.push([current, TokenType.End]);\n    }\n    return elements.concat(startTokens);\n  }\n\n  /**\n   * `styleTargets` resolves the nodes a style or removeStyle applies to,\n   * without repeats, along with the size the boundary text splits added to\n   * live. Traversed nodes come in document order; boundary elements\n   * recovered from the change's positions follow them, as in Go.\n   *\n   * The two operations are one range resolution asked to write two\n   * different things, so the resolution lives here once. A node is reported\n   * at most once even though a fully covered element is visited on both its\n   * Start and End tokens; the second write was already a no-op, since RHT\n   * rejects a ticket that is not after the one it holds.\n   *\n   * NOTE(cross-implementation): the set this returns is a replicated\n   * contract -- every SDK and the server have to reach the same nodes for\n   * the same change. It mirrors yorkie's `styleTargets`; the rules are the\n   * \"Port specification\" in yorkie's docs/design/concurrent-merge-split.md.\n   */\n  private styleTargets(\n    from: CRDTTreePos,\n    to: CRDTTreePos,\n    editedAt: TimeTicket,\n    versionVector?: VersionVector,\n  ): [Array<CRDTTreeNode>, DataSize] {\n    const diff = { data: 0, meta: 0 };\n    const [[resolvedFromParent, fromLeftRaw], diffFrom] =\n      this.findNodesAndSplitText(from, editedAt, 'range');\n    const [[toParent, toLeftRaw], diffTo] = this.findNodesAndSplitText(\n      to,\n      editedAt,\n      'range',\n    );\n    addDataSizes(diff, diffTo, diffFrom);\n\n    // skipActorID for the same reason as edit's Phase 2: a same-boundary\n    // empty run has to resolve here the way the split loop resolves it.\n    const styleActorID = editedAt.getActorID();\n    let fromParent = resolvedFromParent;\n    let fromLeft =\n      fromLeftRaw !== fromParent\n        ? this.advancePastUnknownSplitSiblings(\n            fromLeftRaw,\n            versionVector,\n            false,\n            styleActorID,\n          )\n        : fromLeftRaw;\n    const toLeft =\n      toLeftRaw !== toParent\n        ? this.advancePastUnknownSplitSiblings(\n            toLeftRaw,\n            versionVector,\n            false,\n            styleActorID,\n          )\n        : toLeftRaw;\n\n    const isVersionVectorEmpty = !versionVector || versionVector.size() === 0;\n    const recovery = this.reversedFromAnchorRecovery(\n      from,\n      to,\n      fromParent,\n      fromLeft,\n      toParent,\n      toLeft,\n      versionVector,\n    );\n    if (recovery) {\n      fromParent = recovery.fromParent;\n      fromLeft = recovery.fromLeft;\n    }\n    const { skipToken, skipReached, declaredTo, declaredFrom } =\n      this.styleSkipPredicate(\n        from,\n        to,\n        fromParent,\n        versionVector,\n        recovery?.isInterloper,\n      );\n\n    const targets: Array<CRDTTreeNode> = [];\n    const seen = new Set<CRDTTreeNode>();\n    const add = (node: CRDTTreeNode) => {\n      if (!seen.has(node)) {\n        seen.add(node);\n        targets.push(node);\n      }\n    };\n\n    this.traverseInPosRange(fromParent, fromLeft, toParent, toLeft, (token) => {\n      const [node, tokenType] = token;\n      // A fully covered element arrives twice, on its Start token and on\n      // its End token. Everything below depends only on the node, so the\n      // second visit would redo the lineage walks for nothing.\n      if (seen.has(node) || skipToken(token)) {\n        return;\n      }\n\n      if (node.canStyle(versionVector)) {\n        add(node);\n        // Carry the style onto split products the change could not have\n        // known, so a range resolved before the split still covers the piece\n        // the split cut off. Which token reached the node does not decide\n        // this: a node the range covered whole arrives on its Start token,\n        // or on its End token alone when the range began inside it.\n        for (const sibling of this.unknownSplitSiblings(node, versionVector)) {\n          add(sibling);\n        }\n        return;\n      }\n\n      // The change did not know this node was created, so it cannot have\n      // named it -- unless a concurrent split produced it from one the\n      // change did name. An End token the range genuinely ran past says the\n      // change styled that element while it was still one piece, so the\n      // whole split family carries the style, including the half the change\n      // knew and the traversal no longer reaches.\n      if (\n        tokenType === TokenType.End &&\n        !isVersionVectorEmpty &&\n        declaredTo &&\n        !declaredTo.covers(node)\n      ) {\n        const family = this.splitFamilyOf(node, versionVector);\n        // The family is reached only through the node the change knew, which\n        // is the one the End-token guard judges. When that guard excludes\n        // it, re-adding the family would style the very node it skipped.\n        //\n        // The change must also have begun at or inside that node. A split of\n        // more than one level carries the right half into a new parent, past\n        // a range that began right after the known node, and its End token\n        // then enters the range with nothing to do with the change. A range\n        // that began BEFORE the known node covered it whole, however the\n        // traversal lost it, and keeps the closure. This is rule 2(c) of the\n        // Port specification in yorkie's concurrent-merge-split design doc\n        // (§9.2 Fix 27, yorkie#2070).\n        if (\n          family.length &&\n          !skipToken([family[0], TokenType.End]) &&\n          declaredFrom &&\n          (declaredFrom.coversEitherWay(family[0]) ||\n            this.beginsAtOrBefore(family[0], from))\n        ) {\n          family.forEach(add);\n        }\n      }\n    });\n\n    // Add back the boundary elements the change itself reached. Without a\n    // concurrent merge the traversal has already found every one of them;\n    // with one, they are the nodes the resolved range can no longer see.\n    if (\n      this.boundaryRangeCovers(from, to, fromParent, fromLeft, toParent, toLeft)\n    ) {\n      for (const token of this.boundaryElements(from, to)) {\n        // The §9.4 interloper filters and the End-token split guard are\n        // about which nodes the change reached, not about how the traversal\n        // found them, so a boundary element answers to them too.\n        if (!skipReached(token) && token[0].canStyle(versionVector)) {\n          add(token[0]);\n        }\n      }\n    }\n\n    return [targets, diff];\n  }\n\n  /**\n   * `orderSameBoundarySplit` decides which node a split at `offset` of\n   * `parent` actually splits, so that concurrent splits of one node at one\n   * boundary land in the same order on every replica.\n   *\n   * `splitElement` places its product directly after the node it splits.\n   * When a concurrent split of the same boundary has already been applied,\n   * that puts the products in arrival order, which differs per replica. The\n   * XML still matches (all but the last product are empty) but position-based\n   * operations that follow do not.\n   *\n   * Order them by ticket instead, newest first, as RGA orders concurrent\n   * inserts after the same node: skip the unknown split siblings with a newer\n   * ticket and split the last of them at its start. The right half lives in\n   * that sibling on this replica, so it moves into our product exactly as it\n   * would have moved out of `parent` on a replica that applied us first.\n   */\n  private orderSameBoundarySplit(\n    parent: CRDTTreeNode,\n    offset: number,\n    editedAt: TimeTicket,\n    versionVector?: VersionVector,\n  ): [CRDTTreeNode, number] {\n    // A concurrent split of the same boundary took everything to the right of\n    // it, so only a split at the end of `parent` can be one.\n    if (!versionVector || offset !== parent.allChildren.length) {\n      return [parent, offset];\n    }\n\n    let target = parent;\n    const walker = new InsNextWalker();\n    walker.visit(target);\n    while (target.insNextID) {\n      const next = this.findFloorNode(target.insNextID);\n      if (!next || next.isText || !next.parent) {\n        break;\n      }\n\n      // Stop on a chain that loops back on itself; see InsNextWalker.\n      if (!walker.visit(next)) {\n        break;\n      }\n\n      // The sibling has to belong to target's own split family. The strict\n      // parent-equality check §7.5 uses is too strong here — at a\n      // multi-level split the sibling may already sit under the next level's\n      // product — but dropping it entirely would let an insNextID that did\n      // not come from `splitElement` redirect this split onto an arbitrary\n      // element elsewhere in the tree.\n      if (!this.sharesSplitFamilyParent(target, next)) {\n        break;\n      }\n\n      // Splitting a tombstoned sibling would make our product born\n      // tombstoned, which a replica that applied us before the concurrent\n      // split never does. Fall back to splitting parent, as that replica\n      // did, rather than diverge on liveness.\n      if (next.isRemoved) {\n        break;\n      }\n\n      const createdAt = next.id.getCreatedAt();\n      if (createdAt.getActorID() === editedAt.getActorID()) {\n        break;\n      }\n      const knownLamport = versionVector.get(createdAt.getActorID());\n      if (\n        knownLamport !== undefined &&\n        knownLamport >= createdAt.getLamport()\n      ) {\n        break;\n      }\n      if (!createdAt.after(editedAt)) {\n        break;\n      }\n\n      target = next;\n    }\n\n    return target === parent ? [parent, offset] : [target, 0];\n  }\n\n  /**\n   * `sharesSplitFamilyParent` reports whether `next` sits under `node`'s\n   * parent, or under a split product of that parent. A multi-level split\n   * moves a sibling under the next level's product, so the two parents\n   * legitimately differ — but only within one split family. Anything beyond\n   * that is not a split sibling of `node`, whatever its insNextID claims.\n   */\n  private sharesSplitFamilyParent(\n    node: CRDTTreeNode,\n    next: CRDTTreeNode,\n  ): boolean {\n    if (!node.parent || !next.parent) {\n      return false;\n    }\n    if (node.parent === next.parent) {\n      return true;\n    }\n\n    const walker = new InsNextWalker();\n    let current: CRDTTreeNode | undefined = node.parent as CRDTTreeNode;\n    while (current && walker.visit(current)) {\n      if (current === next.parent) {\n        return true;\n      }\n      if (!current.insNextID) {\n        return false;\n      }\n      current = this.findFloorNode(current.insNextID);\n    }\n\n    return false;\n  }\n\n  /**\n   * `advancePastUnknownSplitSiblings` follows the insNextID chain of the\n   * given node, advancing past element-type split siblings that the editing\n   * client did not know about (not in versionVector).\n   */\n  private advancePastUnknownSplitSiblings(\n    node: CRDTTreeNode,\n    versionVector?: VersionVector,\n    relaxParentCheck = false,\n    skipActorID?: string,\n  ): CRDTTreeNode {\n    if (!versionVector || !node) {\n      return node;\n    }\n\n    let current = node;\n    const walker = new InsNextWalker();\n    walker.visit(current);\n    while (current.insNextID) {\n      const next = this.findFloorNode(current.insNextID);\n      if (!next || next.isText) {\n        break;\n      }\n\n      // Stop on a chain that loops back on itself; see InsNextWalker.\n      if (!walker.visit(next)) {\n        break;\n      }\n\n      // §7.5: Skip parent check when relaxParentCheck is true — at\n      // ancestor iterations of the split loop, a concurrent recursive\n      // split may have moved the sibling to a different parent.\n      if (!relaxParentCheck && next.parent !== current.parent) {\n        break;\n      }\n\n      const actorID = next.id.getCreatedAt().getActorID();\n\n      // §7.7: Stop at siblings created by the current operation's\n      // actor. They are our own split products, not concurrent ones.\n      if (skipActorID !== undefined && actorID === skipActorID) {\n        break;\n      }\n\n      const knownLamport = versionVector.get(actorID);\n      if (\n        knownLamport !== undefined &&\n        knownLamport >= next.id.getCreatedAt().getLamport()\n      ) {\n        break;\n      }\n\n      // Empty unknown siblings standing right before our own product are\n      // concurrent splits of the same boundary, ordered ahead of ours by\n      // `orderSameBoundarySplit`. They are not content the editor meant to\n      // keep on its left; a replica that applied them later re-parented them\n      // after the boundary (§7.4), so stay in front of them here as well.\n      if (\n        skipActorID !== undefined &&\n        this.emptyRunReachesActor(next, skipActorID, versionVector)\n      ) {\n        break;\n      }\n\n      current = next;\n    }\n\n    return current;\n  }\n\n  /**\n   * `collectUnknownSplitSiblings` appends to `out` the split siblings of the\n   * deleted element `node` that the editor did not know, with their\n   * subtrees (§4.1 of yorkie's docs/design/concurrent-merge-split.md).\n   *\n   * The walk passes a sibling the editor knew only if the editor saw it\n   * gone: removed by a change the editor knew (merged back into `node`,\n   * say), or enclosed whole by this delete. What lies past it was then\n   * inside `node` or inside the deleted range for the editor too. Any other\n   * known sibling ends the walk. The chain is in document order and a split\n   * product lands right after the node it was split off (or, under §7.8,\n   * after the same-boundary products ordered ahead of it), so an unknown\n   * sibling past such a sibling holds content the editor saw inside that\n   * sibling, not inside `node`. Walking on tombstoned it: after a split at\n   * offset 0 and a delete of the empty left piece, the concurrent\n   * same-boundary product that holds the moved content sits right after the\n   * editor's own product (#1408).\n   */\n  private collectUnknownSplitSiblings(\n    node: CRDTTreeNode,\n    versionVector: VersionVector | undefined,\n    enclosed: (node: CRDTTreeNode) => boolean,\n    out: Array<CRDTTreeNode>,\n  ): void {\n    const walker = new InsNextWalker();\n    walker.visit(node);\n    let next = node.insNextID ? this.findFloorNode(node.insNextID) : undefined;\n    // Stop on a chain that loops back on itself; see InsNextWalker.\n    // Unbounded here would also grow `out` without limit.\n    while (next && walker.visit(next)) {\n      if (ticketKnown(versionVector, next.id.getCreatedAt())) {\n        const seenGone =\n          !!next.removedAt && ticketKnown(versionVector, next.removedAt);\n        if (!seenGone && !enclosed(next)) {\n          break;\n        }\n      } else {\n        out.push(next);\n        // Cascade through the full subtree, not just immediate children.\n        const sibling = next;\n        traverseAll(sibling, (n) => {\n          if (n !== sibling) {\n            out.push(n);\n          }\n        });\n      }\n      if (!next.insNextID) break;\n      next = this.findFloorNode(next.insNextID);\n    }\n  }\n\n  /**\n   * `emptyRunReachesActor` reports whether the insNextID chain starting at\n   * `node` runs through empty, unknown element split siblings only and then\n   * reaches a node created by `actorID`.\n   */\n  private emptyRunReachesActor(\n    node: CRDTTreeNode,\n    actorID: string,\n    versionVector: VersionVector,\n  ): boolean {\n    const walker = new InsNextWalker();\n    let current: CRDTTreeNode | undefined = node;\n    while (current && !current.isText && walker.visit(current)) {\n      const createdAt = current.id.getCreatedAt();\n      if (createdAt.getActorID() === actorID) {\n        return current !== node;\n      }\n      const knownLamport = versionVector.get(createdAt.getActorID());\n      if (\n        current.allChildren.length > 0 ||\n        (knownLamport !== undefined && knownLamport >= createdAt.getLamport())\n      ) {\n        return false;\n      }\n      current = current.insNextID\n        ? this.findFloorNode(current.insNextID)\n        : undefined;\n    }\n    return false;\n  }\n\n  /**\n   * `hasUnknownSplitSibling` checks whether the given element node has a\n   * split sibling (via insNextID) whose creation the editor did not know\n   * about. Used to prevent styling via End tokens when a concurrent split\n   * extended the range into the split sibling.\n   */\n  private hasUnknownSplitSibling(\n    node: CRDTTreeNode,\n    versionVector: VersionVector,\n  ): boolean {\n    if (!node.insNextID) {\n      return false;\n    }\n\n    const next = this.findFloorNode(node.insNextID);\n    if (!next || next.isText) {\n      return false;\n    }\n\n    // NOTE: Unlike advancePastUnknownSplitSiblings, we intentionally omit\n    // the parent-equality check. In multi-level splits (splitLevel>=2),\n    // the split sibling may have been moved to a different parent by the\n    // recursive ancestor split. The End-token guard must still fire because\n    // the node WAS split — insNextID is only set by SplitElement.\n    const actorID = next.id.getCreatedAt().getActorID();\n    const knownLamport = versionVector.get(actorID);\n\n    return (\n      knownLamport === undefined ||\n      knownLamport < next.id.getCreatedAt().getLamport()\n    );\n  }\n\n  /**\n   * `registerNode` registers the given node to the tree, keeping a live node\n   * over a tombstone when both claim the same ID.\n   *\n   * Documents written by older clients can carry two nodes under one ID (an\n   * undo that re-inserted a deleted piece by copy). A plain `put` lets the\n   * winner depend on the order the nodes were registered — operation order on\n   * a live document, document order on one rebuilt from a snapshot — so after\n   * a reload the same position resolves to a different node and its offset can\n   * fall outside that node. Keeping the live one makes both orders agree for a\n   * live/tombstone pair, which is the shape those documents carry.\n   *\n   * Two nodes in the same state keep the last-registered-wins behavior, and\n   * stay order-dependent: element IDs issued for a split can legitimately\n   * collide with an inserted node's ID (see the delimiter note in\n   * `TreeEditOperation`), and that resolution order is what the rest of the\n   * tree already assumes.\n   *\n   * A node this refuses stays in the index tree while another node answers for\n   * its ID, so it is reachable by traversal but not by lookup. That is the\n   * intended trade for a duplicate: the alternative is unregistering a node\n   * that positions still resolve through.\n   */\n  public registerNode(node: CRDTTreeNode): void {\n    const entry = this.nodeMapByID.floorEntry(node.id);\n    if (\n      entry &&\n      entry.value !== node &&\n      entry.key.equals(node.id) &&\n      node.isRemoved &&\n      !entry.value.isRemoved\n    ) {\n      return;\n    }\n\n    this.nodeMapByID.put(node.id, node);\n  }\n\n  /**\n   * `dropDuplicateContents` returns the contents that would not put a second\n   * node under an ID already in the tree.\n   *\n   * Content created by an edit carries that edit's lamport and actor, so a\n   * content node whose ID names another change is a copy of a node that\n   * already exists — what the copy-reinsert undo path sends when it reverses a\n   * deletion. Inserting it would leave two nodes under one identity, so the\n   * copy is dropped and the rest of the edit applies.\n   *\n   * Content from this edit's own change is kept even when its ID collides: the\n   * delimiters an element split consumes are simulated rather than replayed,\n   * so an ID issued here can legitimately collide, and dropping it would lose\n   * a node the client already inserted.\n   *\n   * Dropping rather than failing is deliberate: such changes are already in\n   * the history of existing documents, and a change that cannot be replayed is\n   * a document that can never be loaded again. A collision anywhere in a\n   * content node's subtree drops that whole subtree, on the grounds that a\n   * copy is copied whole.\n   */\n  public dropDuplicateContents(\n    contents: Array<CRDTTreeNode>,\n    editedAt: TimeTicket,\n  ): Array<CRDTTreeNode> {\n    return contents.filter((content) => {\n      let reused = false;\n      traverseAll(content, (node) => {\n        const createdAt = node.id.getCreatedAt();\n        if (\n          createdAt.getLamport() === editedAt.getLamport() &&\n          createdAt.getActorID() === editedAt.getActorID()\n        ) {\n          return;\n        }\n\n        const entry = this.nodeMapByID.floorEntry(node.id);\n        if (entry && entry.key.equals(node.id)) {\n          reused = true;\n        }\n      });\n\n      return !reused;\n    });\n  }\n\n  /**\n   * `registerPendingGCPair` buffers a GC pair for a node that was born\n   * tombstoned (split off an already-removed node). The pair is picked up\n   * by the next `edit` or `style` call via `drainPendingGCPairs`. `size`\n   * is the net-new size created by the split; it is accounted to\n   * docSize.gc at registration since the node was never live.\n   */\n  public registerPendingGCPair(node: CRDTTreeNode, size: DataSize): void {\n    this.pendingGCPairs.push({ parent: this, child: node, gcOnlySize: size });\n  }\n\n  /**\n   * `pushPendingGCPair` buffers an already-built pair, for garbage whose\n   * parent is not this tree -- an attribute tombstone belongs to the node\n   * holding it, not to the tree.\n   */\n  public pushPendingGCPair(pair: GCPair): void {\n    this.pendingGCPairs.push(pair);\n  }\n\n  /**\n   * `drainPendingGCPairs` returns the buffered GC pairs and clears the\n   * buffer.\n   */\n  public drainPendingGCPairs(): Array<GCPair> {\n    const pairs = this.pendingGCPairs;\n    this.pendingGCPairs = [];\n    return pairs;\n  }\n\n  /**\n   * `findNodesAndSplitText` finds `TreePos` of the given `CRDTTreeNodeID` and\n   * splits nodes if the position is in the middle of a text node.\n   *\n   * The ids of the given `pos` are the ids of the node in the CRDT perspective.\n   * This is different from `TreePos` which is a position of the tree in the\n   * physical perspective.\n   *\n   * If `editedAt` is given, then it is used to find the appropriate left node\n   * for concurrent insertion.\n   *\n   * `boundary` selects how a position inside a merged-away parent resolves:\n   * `insert` places it at the insertion boundary in the merge target (before\n   * the first moved child, so RGA ordering breaks ties), while `range` places\n   * it right after the merge-source tombstone so a style range neither grows\n   * over nor shrinks past nodes concurrently inserted at that anchor.\n   */\n  public findNodesAndSplitText(\n    pos: CRDTTreePos,\n    editedAt?: TimeTicket,\n    boundary: 'insert' | 'range' = 'insert',\n  ): [TreeNodePair, DataSize] {\n    const diff = { data: 0, meta: 0 };\n\n    // 01. Find the parent and left sibling node of the given position.\n    const [parent, leftSibling] = pos.toTreeNodePair(this);\n    let leftNode = leftSibling;\n\n    // 02. Determine whether the position is left-most and the exact parent\n    // in the current tree.\n    const isLeftMost = parent === leftNode;\n    const realParent =\n      leftNode.parent && !isLeftMost ? leftNode.parent : parent;\n\n    // 02-1. If the parent has been tombstoned by a merge, redirect to the\n    // merge destination using the forwarding pointer. The insertion\n    // boundary is the first child in the target whose `mergedFrom`\n    // points back at the tombstoned parent (i.e. the first child moved\n    // by the merge, in target child order).\n    if (realParent.isRemoved && isLeftMost && realParent.mergedInto) {\n      // §9.3 Range Boundary at Merged-Away Anchors: a range boundary\n      // resolves to the position right after the merge-source tombstone,\n      // not the insertion boundary below. The insertion boundary sits\n      // before the first moved child, so it would extend a style range\n      // over nodes concurrently inserted between the tombstone and the\n      // moved children — nodes the styling client saw outside its range\n      // (after the then-live parent).\n      if (boundary === 'range' && realParent.parent) {\n        return [[realParent.parent as CRDTTreeNode, realParent], diff];\n      }\n      // `findMergeNode`, not `findFloorNode`: a text node is never a merge\n      // destination, and neither is a node the pointer merely floors onto.\n      // The pointer can come from a client -- `mergedInto` is derived from\n      // the `mergedFrom` an element payload keeps -- and returned as the\n      // insertion parent it would fail every later edit that resolves\n      // through this tombstone, on every replica. Falling through to the\n      // normal path treats the crafted lineage as the absent one it is.\n      const mergeTarget = this.findMergeNode(realParent.mergedInto);\n      if (mergeTarget && !mergeTarget.isRemoved) {\n        const allCh = mergeTarget.allChildren;\n        for (let i = 0; i < allCh.length; i++) {\n          const targetChild = allCh[i];\n          if (\n            !targetChild.mergedFrom ||\n            !targetChild.mergedFrom.equals(realParent.id)\n          ) {\n            continue;\n          }\n          if (i === 0) {\n            return [[mergeTarget, mergeTarget], diff];\n          }\n          return [[mergeTarget, allCh[i - 1]], diff];\n        }\n        // Fallback: insert at leftmost of merge target.\n        return [[mergeTarget, mergeTarget], diff];\n      }\n    }\n\n    // 03. Split text node if the left node is a text node.\n    if (leftNode.isText) {\n      const [, splitedDiff] = leftNode.split(\n        this,\n        pos.getLeftSiblingID().getOffset() - leftNode.id.getOffset(),\n      );\n      // Accumulated, not assigned: `diff` is provably empty here today, but\n      // assigning is the same trap that left the split phase unaccounted.\n      addDataSizes(diff, splitedDiff);\n    }\n\n    // 04. Find the appropriate left node. If some nodes are inserted at the\n    // same position concurrently, then we need to find the appropriate left\n    // node. This is similar to RGA.\n    if (editedAt) {\n      const allChildren = realParent.allChildren;\n      const index = isLeftMost ? 0 : allChildren.indexOf(leftNode) + 1;\n\n      for (let i = index; i < allChildren.length; i++) {\n        const next = allChildren[i];\n        if (!next.id.getCreatedAt().after(editedAt)) {\n          break;\n        }\n\n        leftNode = next;\n      }\n    }\n\n    return [[realParent, leftNode], diff];\n  }\n\n  /**\n   * `style` applies the given attributes of the given range.\n   */\n  public style(\n    range: [CRDTTreePos, CRDTTreePos],\n    attributes: { [key: string]: string } | undefined,\n    editedAt: TimeTicket,\n    versionVector?: VersionVector,\n  ): [\n    Array<GCPair>,\n    Array<TreeChange>,\n    DocSize,\n    Map<string, string>,\n    Array<string>,\n  ] {\n    const size = { live: { data: 0, meta: 0 }, gc: { data: 0, meta: 0 } };\n    const [targets, diff] = this.styleTargets(\n      range[0],\n      range[1],\n      editedAt,\n      versionVector,\n    );\n    addDataSizes(size.live, diff);\n\n    const changes: Array<TreeChange> = [];\n    const pairs: Array<GCPair> = [];\n    const prevAttributes = new Map<string, string>();\n    const newAttrKeys: Array<string> = [];\n    if (attributes) {\n      const attrs: { [key: string]: any } = parseObjectValues(attributes);\n      targets.forEach((node, i) => {\n        // Capture previous attribute values from the first styled node for\n        // the reverse operation (undo).\n        if (i === 0) {\n          for (const key of Object.keys(attributes)) {\n            if (node.attrs?.has(key)) {\n              prevAttributes.set(key, node.attrs.get(key)!);\n            } else {\n              newAttrKeys.push(key);\n            }\n          }\n        }\n\n        const writes = node.setAttrs(attributes, editedAt);\n        const affectedAttrs: { [key: string]: string } = {};\n        for (const write of writes) {\n          if (write.installed) {\n            const key = write.installed.getKey();\n            affectedAttrs[key] = attrs[key];\n          }\n          accAttrWrite(write, node, !node.isRemoved, pairs, size);\n        }\n\n        // A tombstoned node is not part of the rendered document, and\n        // `toIndex` on one yields a zero-width range that means nothing to\n        // an editor. The text half makes the same exclusion.\n        if (Object.keys(affectedAttrs).length > 0 && !node.isRemoved) {\n          const range = this.styleChangeRange(node);\n          if (range) {\n            changes.push({\n              type: TreeChangeType.Style,\n              ...range,\n              actor: editedAt.getActorID(),\n              value: affectedAttrs,\n            });\n          }\n        }\n      });\n    }\n\n    pairs.push(...this.drainPendingGCPairs());\n\n    return [pairs, changes, size, prevAttributes, newAttrKeys];\n  }\n\n  /**\n   * `removeStyle` removes the given attributes of the given range.\n   */\n  public removeStyle(\n    range: [CRDTTreePos, CRDTTreePos],\n    attributesToRemove: Array<string>,\n    editedAt: TimeTicket,\n    versionVector?: VersionVector,\n  ): [Array<GCPair>, Array<TreeChange>, DocSize, Map<string, string>] {\n    const size = { live: { data: 0, meta: 0 }, gc: { data: 0, meta: 0 } };\n    const [targets, diff] = this.styleTargets(\n      range[0],\n      range[1],\n      editedAt,\n      versionVector,\n    );\n    addDataSizes(size.live, diff);\n\n    const changes: Array<TreeChange> = [];\n    const pairs: Array<GCPair> = [];\n    const prevAttributes = new Map<string, string>();\n    if (attributesToRemove) {\n      targets.forEach((node, i) => {\n        if (!node.attrs) {\n          node.attrs = new RHT();\n        }\n\n        // Capture previous attribute values from the first styled node for\n        // the reverse operation (undo).\n        if (i === 0) {\n          for (const key of attributesToRemove) {\n            if (node.attrs.has(key)) {\n              prevAttributes.set(key, node.attrs.get(key)!);\n            }\n          }\n        }\n\n        // `canStyle` admits a node removed concurrently with this change,\n        // so `nodeIsLive` is the third question `attrGCPair` asks.\n        const nodeIsLive = !node.isRemoved;\n        let removedAny = false;\n        for (const key of attributesToRemove) {\n          let wasLive = node.attrs.has(key);\n          const { gcNodes, valueDropped } = node.attrs.remove(key, editedAt);\n          removedAny = removedAny || gcNodes.length > 0;\n\n          // The tombstone is not charged for its value; those bytes leave\n          // whichever side was holding them. See `attrGCPair` for the split.\n          subDataSize(nodeIsLive ? size.live : size.gc, valueDropped);\n\n          for (const rhtNode of gcNodes) {\n            pairs.push(attrGCPair(node, rhtNode, wasLive, nodeIsLive));\n            // Only the node replacing the live value takes a size out of\n            // live; a second one in the same call is the tombstone it\n            // superseded.\n            wasLive = false;\n          }\n        }\n\n        // See `style`: a tombstoned node reports no change to editors, and\n        // neither does a node that held none of the attributes -- the\n        // `style` half reports only what it actually wrote, so a removal\n        // that took nothing off is the same no-op and stays silent.\n        if (nodeIsLive && removedAny) {\n          const range = this.styleChangeRange(node);\n          if (range) {\n            changes.push({\n              type: TreeChangeType.RemoveStyle,\n              ...range,\n              actor: editedAt.getActorID(),\n              value: attributesToRemove,\n            });\n          }\n        }\n      });\n    }\n\n    pairs.push(...this.drainPendingGCPairs());\n\n    return [pairs, changes, size, prevAttributes];\n  }\n\n  /**\n   * `styleChangeRange` returns the index and path range a style change on\n   * the given node reports to editors, or undefined when the node is not in\n   * the document.\n   *\n   * The targets come from walks over ids -- split families, merge lineage --\n   * so one can be a node that is live by `isRemoved` but detached from the\n   * tree, with no parent. `prevSibling` dereferences `parent!` and would\n   * throw on it; a node with no parent has no place in the rendered\n   * document to report either, so the caller reports nothing.\n   */\n  private styleChangeRange(node: CRDTTreeNode) {\n    const parent = node.parent;\n    if (!parent) {\n      return undefined;\n    }\n\n    const previous = node.prevSibling || parent;\n    return {\n      from: this.toIndex(parent, previous),\n      to: this.toIndex(node, node),\n      fromPath: this.toPath(parent, previous),\n      toPath: this.toPath(node, node),\n    };\n  }\n\n  /**\n   * `edit` edits the tree with the given range and content.\n   * If the content is undefined, the range will be removed.\n   */\n  public edit(\n    range: [CRDTTreePos, CRDTTreePos],\n    contents: Array<CRDTTreeNode> | undefined,\n    splitLevel: number,\n    editedAt: TimeTicket,\n    issueTimeTicket: (() => TimeTicket) | undefined,\n    versionVector?: VersionVector,\n  ): [\n    Array<TreeChange>,\n    Array<GCPair>,\n    DataSize,\n    Array<CRDTTreeNode>,\n    number,\n    number,\n    Set<string>,\n    Array<TreeRestoreSpan>,\n    Array<TreeRestoreSpan>,\n    number,\n    number,\n    Array<CRDTTreeNode>,\n    Array<[CRDTTreeNodeID, CRDTTreeNodeID]>,\n    Array<CRDTTreeNode>,\n  ] {\n    const diff = { data: 0, meta: 0 };\n\n    // 01. find nodes from the given range and split nodes.\n    const [[fromParent, fromLeftRaw], diffFrom] = this.findNodesAndSplitText(\n      range[0],\n      editedAt,\n    );\n    const [[toParent, toLeftRaw], diffTo] = this.findNodesAndSplitText(\n      range[1],\n      editedAt,\n    );\n\n    addDataSizes(diff, diffTo, diffFrom);\n\n    // 01-1. Advance past split siblings unknown to the editing client.\n    // When a concurrent SplitElement created siblings linked via insNextID,\n    // the editor's position was computed against the unsplit tree. Advance\n    // past siblings the editor could not have seen so that the range\n    // starts/ends after all concurrent split products.\n    // Skip when leftNode == parent (leftmost child position).\n    // §7.7: pass the editing actor so a same-boundary empty run resolves\n    // here exactly as the split loop resolves it; without it the two sides\n    // would place the same boundary differently.\n    const editActorID = editedAt.getActorID();\n    const fromLeft =\n      fromLeftRaw !== fromParent\n        ? this.advancePastUnknownSplitSiblings(\n            fromLeftRaw,\n            versionVector,\n            false,\n            editActorID,\n          )\n        : fromLeftRaw;\n    const toLeft =\n      toLeftRaw !== toParent\n        ? this.advancePastUnknownSplitSiblings(\n            toLeftRaw,\n            versionVector,\n            false,\n            editActorID,\n          )\n        : toLeftRaw;\n\n    // Phase 3: Range Narrowing — when fromLeft and toLeft are in\n    // different parents (due to a concurrent element split), follow\n    // fromLeft's insNextID chain to find a split sibling in toParent\n    // and narrow the traversal range. The original fromParent/fromLeft\n    // are preserved for merge, split, and insert steps.\n    // VV-independent for clone/root consistency.\n    let collectFromParent: CRDTTreeNode = fromParent;\n    let collectFromLeft: CRDTTreeNode = fromLeft;\n    if (fromLeft !== fromParent && fromParent !== toParent) {\n      let current: CRDTTreeNode = fromLeft;\n      const walker = new InsNextWalker();\n      walker.visit(current);\n      while (current.insNextID) {\n        const next = this.findFloorNode(current.insNextID);\n        if (!next || next.isText) {\n          break;\n        }\n        // Stop on a chain that loops back on itself; see InsNextWalker.\n        if (!walker.visit(next)) {\n          break;\n        }\n        if (next.parent && next.parent === toParent) {\n          // Skip narrowing when toLeft === toParent (leftmost child\n          // position, offset 0). The narrowed collectFromLeft would be\n          // a child at offset >= 1, producing a backwards range that\n          // suppresses the intended merge.\n          if (toLeft !== toParent) {\n            collectFromLeft = next;\n            collectFromParent = toParent;\n          }\n          break;\n        }\n        current = next;\n      }\n    }\n\n    const fromIdx = this.toIndex(fromParent, fromLeft);\n    const fromPath = this.toPath(fromParent, fromLeft);\n\n    const nodesToBeRemoved: Array<CRDTTreeNode> = [];\n    const tokensToBeRemoved: Array<TreeToken<CRDTTreeNode>> = [];\n    const toBeMovedToFromParents: Array<CRDTTreeNode> = [];\n    const toBeMergedNodes: Array<CRDTTreeNode> = [];\n    const preTombstoned = new Set<string>();\n\n    // `enclosed` reports whether the range covers the element whole, start\n    // and end tokens both. Collected on first use; most deletes never ask.\n    let enclosedNodes: Set<CRDTTreeNode> | undefined;\n    const enclosed = (n: CRDTTreeNode): boolean => {\n      if (!enclosedNodes) {\n        const found = new Set<CRDTTreeNode>();\n        this.traverseInPosRange(\n          collectFromParent,\n          collectFromLeft,\n          toParent,\n          toLeft,\n          ([token, tokenType], ended) => {\n            if (tokenType === TokenType.Start && ended) {\n              found.add(token);\n            }\n          },\n          true,\n        );\n        enclosedNodes = found;\n      }\n      return enclosedNodes.has(n);\n    };\n\n    this.traverseInPosRange(\n      collectFromParent,\n      collectFromLeft,\n      toParent,\n      toLeft,\n      ([node, tokenType], ended) => {\n        // NOTE(hackerwins): If the node overlaps as a start tag with the\n        // range then we need to move the remaining children to fromParent.\n        if (tokenType === TokenType.Start && !ended) {\n          // Fix 9: Skip merge for elements created by concurrent\n          // operations. The editor didn't know about this element,\n          // so crossing into it is an artifact of a concurrent split,\n          // not an intentional merge.\n          if (ticketKnown(versionVector, node.id.getCreatedAt())) {\n            toBeMergedNodes.push(node);\n            // Include removed children (allChildren) so tombstones move\n            // with the merge and survive as RGA anchors; a concurrent\n            // insert referencing one then resolves in the merge target\n            // and orders via the RGA tie-break.\n            for (const child of node.allChildren) {\n              toBeMovedToFromParents.push(child);\n            }\n          }\n        }\n\n        // NOTE(sigmaith): Determine if the node's creation event was visible.\n        const creationKnown = ticketKnown(\n          versionVector,\n          node.id.getCreatedAt(),\n        );\n\n        // NOTE(sigmaith): Determine if existing tombstone was already causally known.\n        const tombstoneKnown =\n          !!node.removedAt && ticketKnown(versionVector, node.removedAt);\n\n        // NOTE(sejongk): If the node is removable or its parent is going to\n        // be removed, then this node should be removed.\n        // Do not cascade-delete children of merge-boundary nodes\n        // (toBeMergedNodes), because those children are moved rather than\n        // deleted.\n        if (\n          node.canDelete(editedAt, creationKnown, tombstoneKnown) ||\n          (nodesToBeRemoved.includes(node.parent!) &&\n            !toBeMergedNodes.includes(node.parent!))\n        ) {\n          // NOTE(hackerwins): If the node overlaps as an end token with the\n          // range then we need to keep the node.\n          if (tokenType === TokenType.Text || tokenType === TokenType.Start) {\n            // Track nodes already tombstoned before this edit so the\n            // reverse operation does not accidentally resurrect them.\n            if (node.isRemoved) {\n              preTombstoned.add(node.id.toIDString());\n            }\n            nodesToBeRemoved.push(node);\n\n            // §4.1 Cascade delete to split siblings created by concurrent\n            // SplitElement. Only for element nodes.\n            if (\n              !node.isText &&\n              node.insNextID &&\n              !toBeMergedNodes.includes(node)\n            ) {\n              this.collectUnknownSplitSiblings(\n                node,\n                versionVector,\n                enclosed,\n                nodesToBeRemoved,\n              );\n            }\n          }\n          tokensToBeRemoved.push([node, tokenType]);\n        }\n      },\n      true,\n    );\n\n    // NOTE(hackerwins): If concurrent deletion happens, we need to separate the\n    // range(from, to) into multiple ranges.\n    const changes: Array<TreeChange> = this.makeDeletionChanges(\n      tokensToBeRemoved,\n      editedAt,\n    );\n\n    // 01-2. Count merged nodes before children are moved (step 03).\n    // The undo system uses this count to generate a split reverse op\n    // instead of re-inserting empty shells.\n    const mergeLevel = toBeMergedNodes.length;\n    // Track how many GC pairs exist right after the plain-delete loop; if the\n    // merge phases (steps 03/03-1) add more, this edit involved merge-child\n    // propagation and its captured spans are NOT a complete description of the\n    // deletion — the op layer then falls back to the copy-reinsert reverse.\n    let deletePairCount = 0;\n\n    // 02. Delete: delete the nodes that are marked as removed.\n    const pairs: Array<GCPair> = [];\n    // Attribute tombstones ridden in on the inserted content. Held aside and\n    // appended only after `spansComplete` is decided: that test reads\n    // `pairs.length` as \"did anything beyond the plain deletes produce\n    // garbage\", and these say nothing about whether the captured spans\n    // describe the deletion.\n    const contentAttrPairs: Array<GCPair> = [];\n    const removedSpans: Array<TreeRestoreSpan> = [];\n    // Captured in the insert phase: identity spans of the nodes this edit\n    // inserts, so an undo re-removes them by identity (not by index, which\n    // would clobber concurrently-restored content) and a redo revives them.\n    const insertedSpans: Array<TreeRestoreSpan> = [];\n    for (const node of nodesToBeRemoved) {\n      if (node.remove(editedAt)) {\n        pairs.push({ parent: this, child: node });\n        // Identity-preserving undo: capture one span per node THIS edit\n        // transitioned visible → tombstoned. `remove()` returning true is\n        // exactly that transition, so pre-tombstoned nodes and LWW overwrites\n        // are excluded automatically. `nodesToBeRemoved` is in traversal\n        // order → parents precede children, which `restore()` relies on when\n        // recreating purged subtrees.\n        const parent = node.parent as CRDTTreeNode | undefined;\n        let leftSiblingID: CRDTTreeNodeID | undefined;\n        let rightSiblingID: CRDTTreeNodeID | undefined;\n        if (parent) {\n          const siblings = parent.allChildren;\n          const idx = siblings.indexOf(node);\n          if (idx > 0) {\n            leftSiblingID = this.leftAnchorID(siblings[idx - 1]);\n          }\n          if (idx >= 0 && idx < siblings.length - 1) {\n            rightSiblingID = siblings[idx + 1].id;\n          }\n        }\n        removedSpans.push({\n          id: node.id,\n          nodeType: node.type,\n          isText: node.isText,\n          length: node.isText ? node.value.length : 0,\n          value: node.isText ? node.value : undefined,\n          attrs: node.attrs?.deepcopy(),\n          parentID: parent?.id,\n          leftSiblingID,\n          rightSiblingID,\n        });\n      }\n    }\n    deletePairCount = pairs.length;\n\n    // 03. Merge: move the nodes that are marked as moved. Only\n    // `mergedFrom` and `mergedAt` are written on the moved child —\n    // both are persisted in the snapshot encoding. `mergedAt` must be\n    // captured explicitly here (not read from source.removedAt at use\n    // time) because the source's `removedAt` is mutated by LWW when a\n    // later concurrent tombstone targets the same node.\n    //\n    // §6.3 Chained-Merge Flattening (Fix 20): a merge chain P->Q->R is\n    // kept flat so runtime state matches what `rebuildMergeState` derives\n    // from a snapshot (which can only ever represent the compressed chain,\n    // because it records one `mergedFrom` pointer per child and reads the\n    // child's final physical parent). The destination is resolved through\n    // `resolveMergeTarget`, so children merged into an already-merged-away\n    // parent forward to the final live target instead of piling up under\n    // the removed intermediate.\n    const dest = this.resolveMergeTarget(fromParent);\n    // The nodes the cycle guard below tombstones in place instead of moving,\n    // in post-order. Each gets a GC pair, and the operation layer counts them\n    // toward the size this edit removed (Go's `RemovedSize`).\n    const stranded: Array<CRDTTreeNode> = [];\n    // Set once the guard tombstones a subtree that contains dest. The\n    // destination is resolved once, before the loop, but the list can hold\n    // several merge sources' children, so entries remain after the guard\n    // fires. dest is inside the subtree just tombstoned, so moving those\n    // remaining children there would put live nodes under a tombstone. They\n    // are stranded too.\n    let destTombstoned = false;\n    for (const node of toBeMovedToFromParents) {\n      // A moved child must have a source parent to record; skip otherwise\n      // rather than append an untracked node (a node without `mergedFrom`\n      // is invisible to the merge-delete propagation and rebuild logic).\n      if (!node.parent) {\n        continue;\n      }\n      // A destination that is the node itself or lies inside it can only\n      // come from a forged lineage: `mergedInto` is derived from the\n      // `mergedFrom` an element payload keeps, so a crafted one can aim the\n      // destination's forwarding chain at a child this merge moves, or at a\n      // node inside one. Moving the node there would close a parent cycle in\n      // the index tree, and every later ancestor walk would spin forever.\n      // The check reads only the tree the change lands on, so replicas\n      // holding the same tree decide alike.\n      //\n      // Left live, it would stay under the source step 02 just tombstoned,\n      // whose eventual purge detaches the subtree while it stays registered\n      // in `nodeMapByID` and charged as live (#2008). So it is tombstoned\n      // where it stands, with its descendants, the way the §6.2 cascade\n      // tombstones a merge-moved child whose source this edit deletes.\n      if (node === dest || node.isAncestorOf(dest)) {\n        destTombstoned = true;\n        stranded.push(...this.tombstoneSubtree(node, editedAt));\n        continue;\n      }\n      if (destTombstoned) {\n        stranded.push(...this.tombstoneSubtree(node, editedAt));\n        continue;\n      }\n      // Tombstoned children are moved too (kept removed): they stay as RGA\n      // anchors so a concurrent insert referencing one resolves in the\n      // merge target and orders via the RGA tie-break, converging with the\n      // replica that inserted before the merge. `moveChild` keeps the size\n      // accounting correct for both live and tombstoned children\n      // (visible-neutral for the latter), so index positions stay correct.\n      //\n      // `mergedFrom` and `mergedAt` are stamped together, only on the\n      // first move, so a child carried through a chained merge keeps its\n      // original source P and the original P->Q merge ticket (Fix 20).\n      // Stamping `mergedAt` on every move would diverge: a replica that\n      // applied P->Q then Q->R would record the Q->R ticket, while a\n      // replica where Q was already merged records the P->Q ticket on the\n      // single forwarded move.\n      if (!node.mergedFrom) {\n        node.mergedFrom = node.parent.id;\n        node.mergedAt = editedAt;\n      }\n      dest.moveChild(node);\n      // Point this child's original source at the resolved destination,\n      // path-compressing a transitive source (a prior merge whose children\n      // were just relocated again) from the now-removed intermediate to the\n      // final target. This runtime cache is rebuilt from `mergedFrom` on\n      // snapshot load. Deriving `mergedInto` from a *moved* child — one that\n      // had a parent above — mirrors `rebuildMergeState`, which likewise\n      // skips parentless children, so runtime and snapshot agree. (A\n      // parentless child, detached by a concurrent split cascade, is\n      // `continue`d above and must not repoint its source here.)\n      //\n      // `mergedInto` is set solely from moved children (never from the\n      // merge-source list directly), so it is set only when\n      // `rebuildMergeState` can reconstruct it — a source with no moved child\n      // of its own (e.g. an intermediate that only relayed another source's\n      // children) is left unset on both paths, keeping runtime and snapshot\n      // consistent.\n      //\n      // Resolved through `findMergeNode` for the same reason\n      // `rebuildMergeState` resolves it there: `mergedFrom` is stamped here\n      // only when the node carries none, so a node that arrived on an element\n      // payload keeps the client's value, and this is where that value is\n      // read again long after the decode that first saw it.\n      //\n      // The source must also already be a tombstone, the same requirement\n      // `rebuildMergeState` enforces: a boundary element is removed in step 02\n      // above before its children move here, so a live element named by a\n      // client-supplied `mergedFrom` is not a source this merge created.\n      // Checking it on only one of the two paths would make a loaded snapshot\n      // disagree with the replica that applied the op.\n      const src = this.findMergeNode(node.mergedFrom);\n      if (src && src.removedAt) {\n        src.mergedInto = dest.id;\n      }\n    }\n\n    for (const node of stranded) {\n      pairs.push({ parent: this, child: node });\n    }\n\n    // 03-1. Propagate deletes to children moved by prior merges.\n    // When a merge-source node is fully deleted (not a merge boundary),\n    // its former children in the merge target should also be deleted.\n    // Compare against the resolved `dest`, not `fromParent`: the forwarding\n    // pointers above point at the flattened target (§6.3), so a chained\n    // merge (dest !== fromParent) must recognize a concurrent-merge boundary\n    // by `dest`. The list of moved children is recomputed on the fly from\n    // the merge target's children filtered by `mergedFrom`.\n    //\n    // The boundaries the edit's own positions name are resolved lazily: §1.1\n    // redirects a position away from a merged-away parent, so fromParent\n    // and toParent no longer say which boundaries the edit asked for.\n    let declared: Set<CRDTTreeNode> | undefined;\n    for (const node of nodesToBeRemoved) {\n      if (!node.mergedInto || toBeMergedNodes.includes(node)) {\n        continue;\n      }\n      // A source whose children already sit in this edit's own destination\n      // stands for a merge the edit itself asks for only when one of the\n      // edit's positions named that source: the range then stops at the\n      // source instead of covering it, and keeping the children is what\n      // makes the two replicas agree (§6.2). A source the range merely spans\n      // is a plain delete of everything that was inside it, so its children\n      // are tombstoned wherever the concurrent merge left them.\n      if (node.mergedInto.equals(dest.id)) {\n        declared ??= this.declaredBoundaries(range[0], range[1]);\n        if (declared.has(node)) {\n          continue;\n        }\n      }\n      // The destination has to be the node `mergedInto` names exactly, and an\n      // element: this loop tombstones that node's children, so a floor lookup\n      // landing on a neighbour is the cascade reaching live nodes no merge\n      // ever moved.\n      const mergeTarget = this.findMergeNode(node.mergedInto);\n      if (!mergeTarget) {\n        continue;\n      }\n      for (const targetChild of mergeTarget.allChildren) {\n        if (\n          !targetChild.mergedFrom ||\n          !targetChild.mergedFrom.equals(node.id)\n        ) {\n          continue;\n        }\n        if (targetChild.removedAt) {\n          continue;\n        }\n        if (targetChild.remove(editedAt)) {\n          pairs.push({ parent: this, child: targetChild });\n        }\n        // Also tombstone descendants if the moved child is an element.\n        traverseAll(targetChild, (n) => {\n          if (n !== targetChild && !n.removedAt) {\n            if (n.remove(editedAt)) {\n              pairs.push({ parent: this, child: n });\n            }\n          }\n        });\n      }\n    }\n\n    // 04. Split: split the element nodes for the given split level.\n    //\n    // The boundaries it opens grow the visible index, which nothing else in\n    // this method reports: they are not content, so `insertedContentSize`\n    // below does not see them, and they remove nothing, so the removed range\n    // does not either. Measured off the tree rather than computed as\n    // 2 * splitLevel, so a split whose product is born tombstoned, or one the\n    // tree has no room for, reports the growth it really produced.\n    const sizeBeforeSplit = this.getSize();\n    // The `[removed element, its replacement]` pairs this split produced —\n    // see `mergeSourceOf`. Reported so a replica applying the split, its own\n    // or a peer's, can re-point whatever it recorded against the removed one.\n    const splitRecreatedIDs: Array<[CRDTTreeNodeID, CRDTTreeNodeID]> = [];\n    if (splitLevel > 0) {\n      let splitCount = 0;\n      let parent = fromParent;\n      let left: CRDTTreeNode = fromLeft;\n      // Where the split is reported. `fromIdx`/`fromPath` say where the\n      // editor asked for it, but the split itself decides where it opens on\n      // this replica: concurrent inserts at the boundary stay on its left\n      // (§7.3), and the per-iteration advance below can move past unknown\n      // split siblings (§7.5). Reporting the requested position then tells a\n      // binding to move those nodes into the new element, which this tree\n      // did not do. So the first level is measured once it has split, at the\n      // end of what stayed in the node: the split only adds to the right of\n      // it, so that is also its index and path before the split.\n      //\n      // That holds while what stayed is a prefix of the node's children. When\n      // §7.3 keeps an insert that sat after a split sibling, the split also\n      // reorders them, and no single split position describes that -- at the\n      // first level or at an ancestor one. `tree_split_opinfo_test.ts` keeps\n      // an `it.fails` case for the ancestor variant, and `splitBoundaryIdx`\n      // below reports the levels disagreeing so the gap is visible in a log\n      // rather than only in that test.\n      //\n      // The measurement is taken on the tree as it stands once the split has\n      // run, i.e. after step 02 tombstoned the deleted nodes and step 03\n      // moved the merged children, so it is NOT in the pre-edit space\n      // `fromIdx` was measured in. That is deliberate: the deletion changes\n      // built above are pushed before this one and a subscriber applies them\n      // in order, so by the time it reads this position its model already\n      // has the deletions and the merge applied -- the same space `toIndex`\n      // measures in, since it does not count tombstones. (The weaker claim\n      // that nothing removed sits left of the split position does not hold:\n      // the deleted range starts at `fromIdx`, and §7.3/§7.5 can put the\n      // split boundary to its right, past deleted nodes. What makes the two\n      // agree is the replay order, not the absence of deletions.)\n      //\n      // The insert change at the end of step 05 keeps `fromIdx`: the content\n      // lands at the requested position, which a migrated boundary moves\n      // away from. So once this position differs the two stop coinciding and\n      // that change is emitted separately rather than merged onto this one.\n      let splitFromIdx = fromIdx;\n      let splitFromPath = fromPath;\n      // The first level that measured a boundary, and which level it was, so\n      // the levels above can be checked against it.\n      let splitBoundaryIdx: number | undefined;\n      let splitBoundaryLevel = 0;\n      while (splitCount < splitLevel) {\n        // §7.5 Per-Iteration Advance: advance past unknown element\n        // split siblings at the current ancestor level. skipActorID\n        // (§7.7) prevents advancing past own split products.\n        if (left !== parent) {\n          left = this.advancePastUnknownSplitSiblings(\n            left,\n            versionVector,\n            true,\n            editedAt.getActorID(),\n          );\n          // If the advance moved left to a node under a different\n          // parent, update parent to match.\n          if (left.parent && left.parent !== parent) {\n            parent = left.parent as CRDTTreeNode;\n          }\n        }\n\n        if (!parent.parent) {\n          break;\n        }\n\n        // The metadata the new element adds belongs in docSize.live, the\n        // same as every other `split` caller books it. Dropping it here left\n        // live without the elements a split mints, so a split and the merge\n        // that undoes it did not cancel out and the live size walked down by\n        // a ticket per cycle, without bound.\n        const [target, offset] = this.orderSameBoundarySplit(\n          parent,\n          left !== parent ? parent.findOffset(left, true) + 1 : 0,\n          editedAt,\n          versionVector,\n        );\n        const [splitNode, splitDiff] = target.split(\n          this,\n          offset,\n          issueTimeTicket,\n          versionVector,\n        );\n        addDataSizes(diff, splitDiff);\n        const recreated = splitNode && this.mergeSourceOf(splitNode, target);\n        if (recreated) {\n          splitRecreatedIDs.push([recreated, splitNode!.id]);\n        }\n\n        // `parent`, not `target`: when `orderSameBoundarySplit` redirects to\n        // a concurrent split product, the split is at the end of `parent`\n        // (it only redirects there), and the next level splits after\n        // `parent` too, so that is where a binding has to split.\n        if (splitNode) {\n          // Live children only. A tombstone takes no room in the index, so\n          // the last live child measures the same boundary, while\n          // `toIndex`/`toPath` on a removed node is a position the walk\n          // cannot resolve.\n          const children = parent.children;\n          const last = children.length ? children[children.length - 1] : parent;\n          // This measurement only refines a position the change already has:\n          // `fromIdx`/`fromPath` are valid, just the requested boundary\n          // rather than the one the split opened. So the pair is computed\n          // first and published only once both calls returned -- a half\n          // assignment would emit an index and a path describing different\n          // positions, which is worse than the un-refined pair -- and a\n          // throw degrades to that pair.\n          //\n          // `toIndex`/`toPath` throw on a tree they cannot walk (`invalid\n          // pos`, `out of index range`), and `last` is picked by the\n          // heuristic above rather than handed to us, so this is a plausible\n          // failure even where the edit itself is sound. Catching is right\n          // *here* because there is a correct fallback and the value is a\n          // courtesy to subscribers, not part of convergence; the\n          // load-bearing `toIndex`/`toPath` at the top of this method have\n          // no fallback to degrade to -- the edit cannot proceed without\n          // them -- so they stay unguarded and are not made safe by this.\n          // `visibleRangeOf` guards its calls on the same \"there is a\n          // correct degradation\" ground: it reports no range at all.\n          try {\n            const idx = this.toIndex(parent, last);\n            const path = this.toPath(parent, last);\n            if (splitCount === 0) {\n              splitFromIdx = idx;\n              splitFromPath = path;\n            }\n            if (splitBoundaryIdx === undefined) {\n              splitBoundaryIdx = idx;\n              splitBoundaryLevel = splitCount;\n            } else if (\n              idx !==\n              splitBoundaryIdx + (splitCount - splitBoundaryLevel)\n            ) {\n              // Nesting alone moves the boundary one to the right per level\n              // (the close tag of the level below). Anything else means this\n              // level split somewhere the level below did not -- §7.3 kept a\n              // concurrent insert on its left, or §7.5 advanced past a split\n              // sibling -- and the levels describe different boundaries. The\n              // change carries one position, so it still reports the first\n              // level's and a binding replaying it moves the nodes this\n              // level left behind. Expressing it would need the change to\n              // carry a move; until then, say so.\n              logger.warn(\n                `[TR] split level ${splitCount} opened at ${idx}, not at ${\n                  splitBoundaryIdx + (splitCount - splitBoundaryLevel)\n                } as level ${splitBoundaryLevel} implies; the reported split position describes the inner level only`,\n              );\n            }\n          } catch (err) {\n            logger.warn(`[TR] failed to measure split position: ${err}`);\n          }\n        }\n\n        left = parent;\n        parent = parent.parent! as CRDTTreeNode;\n        splitCount++;\n      }\n      changes.push({\n        type: TreeChangeType.Content,\n        from: splitFromIdx,\n        to: splitFromIdx,\n        fromPath: splitFromPath,\n        toPath: splitFromPath,\n        actor: editedAt.getActorID(),\n      });\n    }\n    const splitSize = this.getSize() - sizeBeforeSplit;\n\n    // 05. Insert: insert the given nodes at the given position.\n    //\n    // The identity check runs here rather than on entry: resolving the range\n    // above splits text nodes, and a split can create the very ID a content\n    // node carries. Checking before that would let the copy through and leave\n    // two nodes under one ID. `insertedContentSize` is measured now, while the\n    // content is still detached — inserting under a removed parent tombstones\n    // it and shrinks what its size reads back as.\n    if (contents) {\n      contents = this.dropDuplicateContents(contents, editedAt);\n    }\n    const insertedContentSize = contents\n      ? contents.reduce((sum, node) => sum + node.paddedSize(), 0)\n      : 0;\n\n    if (contents?.length) {\n      // §9.4: When the insert position was declared inside a parent that a\n      // concurrent merge removed, the content physically lands in the merge\n      // target. Stamp it as merged-from the declared parent so it stays\n      // distinguishable from nodes that were never inside that parent —\n      // style-range resolution and merge-delete propagation key on this.\n      const [declaredFromParent] = range[0].toTreeNodePair(this);\n      const intendedParent =\n        declaredFromParent !== fromParent &&\n        declaredFromParent.isRemoved &&\n        declaredFromParent.mergedInto &&\n        this.resolveMergeTarget(declaredFromParent) === fromParent\n          ? declaredFromParent\n          : undefined;\n      let intendedMergedAt: TimeTicket | undefined;\n      if (intendedParent) {\n        // Take the merge ticket from a sibling the merge moved; the parent's\n        // own removedAt may have been overwritten by a later LWW tombstone.\n        for (const child of fromParent.allChildren) {\n          if (child.mergedFrom?.equals(intendedParent.id) && child.mergedAt) {\n            intendedMergedAt = child.mergedAt;\n            break;\n          }\n        }\n        intendedMergedAt ??= intendedParent.removedAt;\n      }\n\n      const aliveContents: Array<CRDTTreeNode> = [];\n      let leftInChildren = fromLeft; // tree\n      for (const content of contents) {\n        // 05-1. Insert the content nodes to the tree.\n        if (leftInChildren === fromParent) {\n          // 05-1-1. when there's no leftSibling, then insert content into very front of parent's children.\n          fromParent.insertAt(content, 0);\n        } else {\n          // 05-1-2. insert after leftSibling\n          fromParent.insertAfter(content, leftInChildren);\n        }\n\n        if (intendedParent) {\n          content.mergedFrom = intendedParent.id;\n          content.mergedAt = intendedMergedAt;\n        }\n\n        leftInChildren = content;\n        traverseAll(content, (node) => {\n          // If insertion happens during concurrent editing and parent node has been removed,\n          // make new nodes as tombstone immediately.\n          if (fromParent.isRemoved) {\n            node.remove(editedAt);\n\n            // The node is born dead: this branch adds nothing to `diff`, so\n            // its bytes never entered docSize.live. A pair without\n            // `gcOnlySize` would debit live for them anyway, driving live\n            // below the tree's real size until purge. Register the\n            // post-`remove` size (tombstone ticket included) so gc is\n            // charged exactly what `purge` later gives back, and leave live\n            // untouched -- the same routing the attribute tombstones a few\n            // lines below use.\n            pairs.push({\n              parent: this,\n              child: node,\n              gcOnlySize: node.getDataSize(),\n            });\n          } else {\n            addDataSizes(diff, node.getDataSize());\n          }\n\n          this.registerNode(node);\n\n          // NOTE: Content can arrive carrying attribute tombstones. The undo\n          // copy-reinsert path legitimately produces them -- it re-sends a\n          // `deepcopy` of nodes a `removeStyle` tombstoned, tombstones\n          // included, so the reinserted node keeps rejecting the stale styles\n          // the original rejects -- and a crafted payload can invent them,\n          // since `fromRHT` decodes `isRemoved` verbatim. Either way they are\n          // garbage this insert created in this tree: no removal path ran for\n          // them here, so without this nothing would ever collect them.\n          //\n          // `getDataSize` skips removed attributes, so these bytes never\n          // entered live and `gcOnlySize` (inside `CRDTTreeNode.getGCPairs`)\n          // sends them straight to docSize.gc, which purge gives back. This is\n          // the same routing a split (`splitElement`), a snapshot load and a\n          // Set/Add element payload (`CRDTTree.getGCPairs`) already use; the\n          // pair map keys on the parent's identity, so a clone wearing the\n          // original's RHTNode ids is a distinct pair, not a cancellation.\n          for (const attrPair of node.getGCPairs()) {\n            contentAttrPairs.push(attrPair);\n          }\n\n          // Capture this inserted node's identity span (parent-before-child\n          // via traverseAll) for identity-preserving insert undo/redo.\n          const p = node.parent as CRDTTreeNode | undefined;\n          let leftSiblingID: CRDTTreeNodeID | undefined;\n          let rightSiblingID: CRDTTreeNodeID | undefined;\n          if (p) {\n            const sibs = p.allChildren;\n            const idx = sibs.indexOf(node);\n            if (idx > 0) leftSiblingID = this.leftAnchorID(sibs[idx - 1]);\n            if (idx >= 0 && idx < sibs.length - 1) {\n              rightSiblingID = sibs[idx + 1].id;\n            }\n          }\n          insertedSpans.push({\n            id: node.id,\n            nodeType: node.type,\n            isText: node.isText,\n            length: node.isText ? node.value.length : 0,\n            value: node.isText ? node.value : undefined,\n            attrs: node.attrs?.deepcopy(),\n            parentID: p?.id,\n            leftSiblingID,\n            rightSiblingID,\n          });\n        });\n\n        if (!content.isRemoved) {\n          aliveContents.push(content);\n        }\n      }\n      if (aliveContents.length) {\n        const value = aliveContents.map((content) => toTreeNode(content));\n        // `fromIdx`, not the split position: the content was inserted at\n        // `fromParent`/`fromLeft` above, i.e. where the edit asked for it,\n        // which is where a migrated split boundary moves away from. The\n        // comparison below is what keeps the two apart -- when the split\n        // reported a different boundary it no longer matches, and the insert\n        // is emitted as its own change instead of being merged onto a split\n        // that happened somewhere else.\n        if (changes.length && changes[changes.length - 1].from === fromIdx) {\n          changes[changes.length - 1].value = value;\n        } else {\n          changes.push({\n            type: TreeChangeType.Content,\n            from: fromIdx,\n            to: fromIdx,\n            fromPath,\n            toPath: fromPath,\n            actor: editedAt.getActorID(),\n            value,\n          });\n        }\n      }\n    }\n\n    pairs.push(...this.drainPendingGCPairs());\n\n    // Identity-preserving restore only covers plain deletions. If this edit\n    // merged nodes or its merge propagation removed extra nodes, the captured\n    // spans don't fully describe the deletion → signal the op layer (empty\n    // spans) to keep the copy-reinsert reverse.\n    const spansComplete = mergeLevel === 0 && pairs.length === deletePairCount;\n    pairs.push(...contentAttrPairs);\n\n    return [\n      changes,\n      pairs,\n      diff,\n      nodesToBeRemoved,\n      fromIdx,\n      mergeLevel,\n      preTombstoned,\n      spansComplete ? removedSpans : [],\n      // `traverseAll` is post-order (children before parent), so reverse to get\n      // parent-before-child — the order `restore()` needs to recreate a purged\n      // subtree top-down (a child's recreate resolves its parent by identity).\n      spansComplete ? insertedSpans.reverse() : [],\n      insertedContentSize,\n      splitSize,\n      // The merge-boundary elements this edit removed — the ones whose\n      // children it moved into the merge target, and so the ones a split\n      // reversing it has to re-create. A strict subset of `nodesToBeRemoved`,\n      // which also holds whole elements deleted inside the range, their\n      // cascade-deleted descendants and nodes already tombstoned.\n      toBeMergedNodes,\n      splitRecreatedIDs,\n      // The subtrees the merge's cycle guard tombstoned in place. Not in\n      // `nodesToBeRemoved` -- the merge had collected them to move -- yet the\n      // range this edit consumed includes them.\n      stranded,\n    ];\n  }\n\n  /**\n   * `editT` edits the given range with the given value.\n   * This method uses indexes instead of a pair of TreePos for testing.\n   */\n  public editT(\n    range: [number, number],\n    contents: Array<CRDTTreeNode> | undefined,\n    splitLevel: number,\n    editedAt: TimeTicket,\n    issueTimeTicket: () => TimeTicket,\n  ): [\n    Array<TreeChange>,\n    Array<GCPair>,\n    DataSize,\n    Array<CRDTTreeNode>,\n    number,\n    number,\n    Set<string>,\n    Array<TreeRestoreSpan>,\n    Array<TreeRestoreSpan>,\n    number,\n    number,\n    Array<CRDTTreeNode>,\n    Array<[CRDTTreeNodeID, CRDTTreeNodeID]>,\n    Array<CRDTTreeNode>,\n  ] {\n    const fromPos = this.findPos(range[0]);\n    const toPos = this.findPos(range[1]);\n    return this.edit(\n      [fromPos, toPos],\n      contents,\n      splitLevel,\n      editedAt,\n      issueTimeTicket,\n    );\n  }\n\n  /**\n   * `move` move the given source range to the given target range.\n   */\n  public move(\n    target: [number, number],\n    source: [number, number],\n    ticket: TimeTicket,\n  ): void {\n    // TODO(hackerwins, easylogic): Implement this with keeping references of the nodes.\n    throw new YorkieError(\n      Code.ErrUnimplemented,\n      `not implemented: ${target}, ${source}, ${ticket}`,\n    );\n  }\n\n  /**\n   * `pathToTreePos` converts the given path of the node to the TreePos.\n   */\n  public pathToTreePos(\n    path: Array<number>,\n  ): ReturnType<typeof this.indexTree.pathToTreePos> {\n    return this.indexTree.pathToTreePos(path);\n  }\n\n  /**\n   * `purgeBarrierAt` implements `GCParent.purgeBarrierAt`. `findNodesAndSplitText` walks the\n   * parent's children, removed ones included, advancing while the next sibling\n   * was created after the incoming edit; a tombstoned sibling with an older\n   * ticket ends that walk. Purging detaches it from the parent, so the next\n   * sibling inherits the decision and must be causally stable first.\n   */\n  public purgeBarrierAt(node: GCChild): TimeTicket | undefined {\n    if (!(node instanceof CRDTTreeNode) || !node.parent) {\n      return;\n    }\n\n    // Read the children in place: `allChildren` copies, and this runs once\n    // per stable tombstone on every collection pass.\n    const siblings = node.parent._children;\n    const offset = siblings.indexOf(node);\n    if (offset < 0) {\n      return;\n    }\n    return siblings[offset + 1]?.id.getCreatedAt();\n  }\n\n  /**\n   * `purge` physically purges the given node.\n   */\n  public purge(node: CRDTTreeNode): void {\n    node.parent?.removeChild(node);\n    // `nodeMapByID` is keyed by ID, so an unconditional remove would also\n    // unregister a different node that shares this one's ID — see\n    // `registerNode`. Only drop the entry this node actually holds.\n    const entry = this.nodeMapByID.floorEntry(node.id);\n    if (entry && entry.value === node && entry.key.equals(node.id)) {\n      this.nodeMapByID.remove(node.id);\n    }\n\n    const insPrevID = node.insPrevID;\n    const insNextID = node.insNextID;\n\n    // NOTE: findFloorNode may return undefined when the insertion neighbor was\n    // already purged (restore/recreate reorders GC so a neighbor can be\n    // collected first). Guard both derefs rather than assuming survival.\n    if (insPrevID) {\n      const insPrev = this.findFloorNode(insPrevID);\n      if (insPrev) {\n        insPrev.insNextID = insNextID;\n      }\n    }\n\n    if (insNextID) {\n      const insNext = this.findFloorNode(insNextID);\n      if (insNext) {\n        insNext.insPrevID = insPrevID;\n      }\n    }\n\n    node.insPrevID = undefined;\n    node.insNextID = undefined;\n  }\n\n  /**\n   * `dissolveMerge` erases the merge lineage a node about to be revived\n   * leaves behind: the forwarding pointer on the source and the\n   * `mergedFrom`/`mergedAt` stamps on the children that merge moved into the\n   * destination.\n   *\n   * `mergedInto` is derivable only for a source that is already a tombstone —\n   * `rebuildMergeState` and the merge in `edit` both require it — so a revived\n   * source that kept either half of the lineage makes the replica running the\n   * undo disagree with one loading a snapshot: keeping `mergedInto` gives the\n   * undoing replica a pointer the snapshot no longer rebuilds, and keeping the\n   * children's `mergedFrom` lets the snapshot rebuild one the moment a redo\n   * (`retombstone`) tombstones the source again. Clearing both leaves nothing\n   * either path can derive, in either direction.\n   *\n   * The destination is resolved through `findMergeNode` for the same reason\n   * the §6.2 cascade does: `mergedInto` is derived from a `mergedFrom` an\n   * element payload may carry, so only an exact element match names a node the\n   * pointer really meant. The source's own pointer is dropped regardless of\n   * whether that lookup succeeds — it is the half that is never persisted.\n   */\n  private dissolveMerge(src: CRDTTreeNode): void {\n    if (!src.mergedInto) {\n      return;\n    }\n    const dest = this.findMergeNode(src.mergedInto);\n    src.mergedInto = undefined;\n    if (!dest) {\n      return;\n    }\n\n    for (const child of dest.allChildren) {\n      if (child.mergedFrom?.equals(src.id)) {\n        child.mergedFrom = undefined;\n        child.mergedAt = undefined;\n      }\n    }\n  }\n\n  /**\n   * `restore` re-establishes the nodes described by `spans` under their\n   * ORIGINAL identities (identity-preserving Tree undo): live → skip\n   * (idempotent), tombstoned → unremove in place, purged → recreate. A span\n   * whose kind does not agree with itself is skipped outright (see\n   * `restoreSpanKindAgrees`), as it is in `retombstone`. Spans must be in\n   * parent-before-child order (`edit()` captures them that way).\n   *\n   * Returns `[untombstoned, recreated, pairs, diff]`:\n   * - `untombstoned`: nodes revived in place (caller unregisters their GC pairs);\n   * - `recreated`: brand-new nodes rebuilt for purged ranges (caller adds their\n   *   size to Live);\n   * - `pairs`: pending GC pairs for born-removed remainders split off a removed\n   *   straddler (caller registers them BEFORE unregistering the untombstoned);\n   * - `diff`: the metadata overhead of splitting live straddlers (caller `acc`s\n   *   it to Live);\n   * - `edits`: one insertion per node that became visible, in the order it\n   *   did. Each is measured right after its node comes back, so applying them\n   *   one after another reproduces the result.\n   */\n  public restore(\n    spans: Array<TreeRestoreSpan>,\n    editedAt: TimeTicket,\n  ): [\n    Array<CRDTTreeNode>,\n    Array<CRDTTreeNode>,\n    Array<GCPair>,\n    DataSize,\n    Array<TreeVisibleEdit>,\n  ] {\n    const untombstoned: Array<CRDTTreeNode> = [];\n    const recreated: Array<CRDTTreeNode> = [];\n    const diff: DataSize = { data: 0, meta: 0 };\n    const changes: Array<TreeVisibleEdit> = [];\n    const revived = (node: CRDTTreeNode) => {\n      const change = this.makeInsertionChange(node, editedAt);\n      if (change) {\n        changes.push(change);\n      }\n    };\n\n    for (const span of spans) {\n      if (!restoreSpanKindAgrees(span)) {\n        continue;\n      }\n      if (!span.isText) {\n        const node = this.findFloorNode(span.id);\n        if (node && node.id.equals(span.id)) {\n          if (node.isRemoved) {\n            this.dissolveMerge(node);\n            node.unremove();\n            untombstoned.push(node);\n            revived(node);\n          }\n          continue;\n        }\n        const created = this.recreateFromSpan(\n          span,\n          span.id.getOffset(),\n          span.length,\n        );\n        if (created) {\n          recreated.push(created);\n          revived(created);\n        }\n        continue;\n      }\n\n      // Text: pieces may be split finer than the span, and a concurrent op or\n      // a post-GC recreate can leave pieces whose boundaries straddle it.\n      // Isolate the exact [start, end) sub-range out of every overlapping\n      // piece — splitting at the span boundaries, live or removed — so all\n      // replicas converge on identical text-node segmentation (the tree\n      // analogue of RGATreeSplit.isolateRange). Then revive the removed parts\n      // and recreate the purged gaps.\n      const start = span.id.getOffset();\n      const end = start + span.length;\n      const pieces = this.findPiecesOverlapping(\n        span.id.getCreatedAt(),\n        start,\n        end,\n      );\n\n      let cursor = start;\n      let pieceIdx = 0;\n      while (cursor < end) {\n        const piece = pieces[pieceIdx];\n        const pieceStart = piece ? piece.id.getOffset() : Infinity;\n        const pieceEnd = piece ? pieceStart + piece.value.length : Infinity;\n\n        if (piece && pieceStart <= cursor) {\n          const overlapEnd = Math.min(pieceEnd, end);\n          const target = this.isolateTextRange(piece, cursor, overlapEnd, diff);\n          if (target.isRemoved) {\n            target.unremove();\n            untombstoned.push(target);\n            revived(target);\n          }\n          cursor = overlapEnd;\n          if (overlapEnd >= pieceEnd) pieceIdx++;\n        } else {\n          const gapEnd = Math.min(pieceStart, end);\n          const created = this.recreateFromSpan(span, cursor, gapEnd - cursor);\n          if (created) {\n            recreated.push(created);\n            revived(created);\n          }\n          cursor = gapEnd;\n        }\n      }\n    }\n\n    // Splitting a removed straddler buffers born-removed remainders as pending\n    // GC pairs (see CRDTTreeNode.split). The caller registers these BEFORE\n    // unregistering the un-tombstoned targets, so a target that was itself a\n    // split-born piece is walked gc->live correctly (mirrors the Text path).\n    const pairs = this.drainPendingGCPairs();\n    return [untombstoned, recreated, pairs, diff, changes];\n  }\n\n  /**\n   * `isolateTextRange` splits `piece` so that a node exactly covering the\n   * absolute-offset interval [from, to) of its insertion exists, and returns\n   * it. Splitting at the caller's boundaries — rather than skipping a piece\n   * that straddles them — is what lets concurrent restores converge on the\n   * same text-node segmentation across replicas (the tree analogue of\n   * RGATreeSplit.isolateRange). A live split's metadata overhead is added to\n   * `diff`; a removed split buffers a pending GC pair internally (contributing\n   * zero here). Requires pieceStart <= from < to <= pieceEnd.\n   */\n  private isolateTextRange(\n    piece: CRDTTreeNode,\n    from: number,\n    to: number,\n    diff: DataSize,\n  ): CRDTTreeNode {\n    let node = piece;\n    if (from > node.id.getOffset()) {\n      const [right, splitDiff] = node.split(this, from - node.id.getOffset());\n      addDataSizes(diff, splitDiff);\n      node = right!;\n    }\n    if (to < node.id.getOffset() + node.value.length) {\n      const [, splitDiff] = node.split(this, to - node.id.getOffset());\n      addDataSizes(diff, splitDiff);\n    }\n    return node;\n  }\n\n  /**\n   * `retombstone` re-deletes the nodes described by `spans` (redo of an\n   * identity-preserving undo). Live pieces only; idempotent. A piece that\n   * straddles a span boundary is split at that boundary so only the in-span\n   * range is re-removed (symmetric with restore's isolate, so undo/redo stay\n   * mirror images and segmentation stays convergent). A span whose kind does\n   * not agree with itself is skipped, exactly as `restore` skips it, so\n   * neither direction acts on what the other ignores. Returns the GC pairs for\n   * the newly tombstoned nodes, the live-split metadata overhead, and one\n   * deletion per visible node it removed, each measured right before the\n   * removal so they apply one after another.\n   */\n  public retombstone(\n    spans: Array<TreeRestoreSpan>,\n    executedAt: TimeTicket,\n  ): [Array<GCPair>, DataSize, Array<TreeVisibleEdit>] {\n    const pairs: Array<GCPair> = [];\n    const diff: DataSize = { data: 0, meta: 0 };\n    const changes: Array<TreeVisibleEdit> = [];\n    for (const span of spans) {\n      if (!restoreSpanKindAgrees(span)) {\n        continue;\n      }\n      const start = span.id.getOffset();\n      const end = start + Math.max(span.length, 1);\n      const pieces = span.isText\n        ? this.findPiecesOverlapping(span.id.getCreatedAt(), start, end)\n        : [this.findFloorNode(span.id)].filter(\n            (n): n is CRDTTreeNode => !!n && n.id.equals(span.id),\n          );\n      for (const piece of pieces) {\n        if (piece.isRemoved) continue;\n        let target = piece;\n        if (piece.isText) {\n          const from = Math.max(piece.id.getOffset(), start);\n          const to = Math.min(piece.id.getOffset() + piece.value.length, end);\n          target = this.isolateTextRange(piece, from, to, diff);\n        }\n        // Measure while `target` is still visible.\n        const range = this.visibleRangeOf(target);\n        if (target.remove(executedAt)) {\n          pairs.push({ parent: this, child: target });\n          if (range) {\n            const [from, to, fromPath, toPath] = range;\n            changes.push({\n              change: {\n                type: TreeChangeType.Content,\n                from,\n                to,\n                fromPath,\n                toPath,\n                actor: executedAt.getActorID(),\n              },\n              insertedSize: 0,\n            });\n          }\n        }\n      }\n    }\n    return [pairs, diff, changes];\n  }\n\n  /**\n   * `visibleRangeOf` returns the index range `node` covers and its paths, or\n   * undefined when it or one of its ancestors is removed and so takes no room\n   * in the index.\n   */\n  private visibleRangeOf(\n    node: CRDTTreeNode,\n  ): [number, number, Array<number>, Array<number>] | undefined {\n    for (let n: CRDTTreeNode | undefined = node; n; n = n.parent) {\n      if (n.isRemoved) {\n        return;\n      }\n    }\n    if (!node.parent) {\n      return;\n    }\n\n    // `toIndex`/`indexToPath` throw on a tree they cannot walk (`invalid pos`,\n    // `out of index range`). Both run here inside `TreeEditOperation.execute`,\n    // which for a remote pack is driven from `Change.execute` off spans that\n    // arrived from the wire: a throw there aborts the pack, the checkpoint\n    // never advances, and the document is wedged for good on every replica\n    // that receives it. Reporting the range is a courtesy to subscribers, not\n    // part of convergence -- the CRDT state is already settled by the time we\n    // measure -- so a tree we cannot measure degrades to \"no position\n    // reported\", exactly as a node under a removed ancestor does above.\n    try {\n      const to = this.toIndex(node.parent, node);\n      const from = to - node.paddedSize();\n      return [from, to, this.indexToPath(from), this.indexToPath(to)];\n    } catch (err) {\n      logger.warn(`[TR] failed to measure restored node: ${err}`);\n      return;\n    }\n  }\n\n  /**\n   * `makeInsertionChange` describes `node` becoming visible as an insertion\n   * at its current position. A node still hidden under a removed ancestor\n   * produces nothing.\n   */\n  private makeInsertionChange(\n    node: CRDTTreeNode,\n    editedAt: TimeTicket,\n  ): TreeVisibleEdit | undefined {\n    const range = this.visibleRangeOf(node);\n    if (!range) {\n      return;\n    }\n\n    const [from, to, path] = range;\n    return {\n      change: {\n        type: TreeChangeType.Content,\n        from,\n        to: from,\n        fromPath: path,\n        toPath: path,\n        actor: editedAt.getActorID(),\n        value: [toTreeNode(node)],\n      },\n      // The change reports a collapsed range, as every insertion does, so the\n      // size it added is not readable from it; reconciliation needs it.\n      insertedSize: to - from,\n    };\n  }\n\n  /**\n   * `findPiecesOverlapping` collects surviving pieces (live or tombstoned) of\n   * the text insertion `createdAt` overlapping [start, end), in ascending\n   * offset order, via descending floorEntry probes.\n   */\n  private findPiecesOverlapping(\n    createdAt: TimeTicket,\n    start: number,\n    end: number,\n  ): Array<CRDTTreeNode> {\n    const pieces: Array<CRDTTreeNode> = [];\n    let probe = end - 1;\n    while (probe >= 0) {\n      const node = this.findFloorNode(CRDTTreeNodeID.of(createdAt, probe));\n      if (!node || !node.isText) break;\n      const nodeStart = node.id.getOffset();\n      const nodeEnd = nodeStart + node.value.length;\n      if (nodeEnd <= start) break;\n      if (nodeStart < end && nodeEnd > start) pieces.push(node);\n      if (nodeStart <= start) break;\n      probe = nodeStart - 1;\n    }\n    return pieces.reverse();\n  }\n\n  /**\n   * `recreateParent` resolves the node a recreated span hangs under, or\n   * undefined when the span must be left unplaced (B1). Three shapes are\n   * unplaceable. The parent is genuinely absent (purged and not part of this\n   * restore). The parent is a text node, which cannot hold children. Or the\n   * identity being recreated, `id`, is one a surviving node already holds --\n   * exactly, or inside a surviving text run of the same insertion -- in which\n   * case recreating would put a second node under one identity, and\n   * `registerNode` overwrites the live registration of the node that holds\n   * it, leaving every later change that addresses it unapplicable (#1471).\n   *\n   * No honest span is any of these: spans come from the wire, and the server\n   * stores a change before applying it, so throwing here would fail every\n   * later apply of the document. Each test reads only state that never\n   * changes afterwards (node kind, identity ownership), and a replica that\n   * does hold the named node resolves the span through restore's un-tombstone\n   * branch instead, so the replicas converge either way. Mirrors Go's\n   * `Tree.recreateParent` (yorkie#2168).\n   */\n  private recreateParent(\n    span: TreeRestoreSpan,\n    id: CRDTTreeNodeID,\n  ): CRDTTreeNode | undefined {\n    if (!span.parentID) {\n      return;\n    }\n    const parent = this.findFloorNode(span.parentID);\n    if (!parent || !parent.id.equals(span.parentID) || parent.isText) {\n      return;\n    }\n\n    const holder = this.findFloorNode(id);\n    if (\n      holder &&\n      (holder.id.getOffset() === id.getOffset() ||\n        (holder.isText &&\n          holder.id.getOffset() + holder.value.length > id.getOffset()))\n    ) {\n      return;\n    }\n\n    return parent;\n  }\n\n  /**\n   * `recreateFromSpan` rebuilds a purged node (or purged text sub-range)\n   * under its original identity and attaches it. Anchor ladder, each rung\n   * doing floor-lookup + parent-identity check:\n   *   (a) same-insertion successor/predecessor piece (text) → exact slot;\n   *   (b) captured left boundary sibling still under this parent → after it;\n   *   (c) captured right boundary sibling still under this parent → before it;\n   *   (d) deterministic id-order fallback: insert among the parent's current\n   *       children at the first position whose id compares greater than the\n   *       node's id (pure function of ids → identical on every replica).\n   * A span `recreateParent` refuses is skipped (B1): the node stays\n   * unplaced/invisible. Go's `Tree.recreateFromSpan` applies the same rules.\n   * Parent present but TOMBSTONED → the node is placed but born tombstoned,\n   * stamped with the parent's `removedAt`, and returned as undefined (see\n   * `attach` below).\n   */\n  private recreateFromSpan(\n    span: TreeRestoreSpan,\n    offset: number,\n    length: number,\n  ): CRDTTreeNode | undefined {\n    const id = CRDTTreeNodeID.of(span.id.getCreatedAt(), offset);\n    const parent = this.recreateParent(span, id);\n    if (!parent) {\n      return;\n    }\n\n    const node = span.isText\n      ? new CRDTTreeNode(\n          id,\n          span.nodeType,\n          span.value!.substring(\n            offset - span.id.getOffset(),\n            offset - span.id.getOffset() + length,\n          ),\n        )\n      : new CRDTTreeNode(\n          span.id,\n          span.nodeType,\n          undefined,\n          span.attrs?.deepcopy(),\n        );\n\n    // The span's attributes are a deep copy of the node's RHT, tombstones\n    // included -- they have to be, or a recreated node would resolve a\n    // concurrent style differently from a replica that never lost it. Each\n    // copied tombstone is a fresh piece of garbage that no removal path\n    // produced: without a registration it sits in the RHT forever, uncounted\n    // and unpurgeable, and `getDataSize` excludes it so the node's own charge\n    // does not cover it either. `getGCPairs` marks each `gcOnlySize`, which is\n    // what sends it to gc alone. Booked by `attach` for both a live and a\n    // removed parent, as Go's `recreateFromSpan` does.\n    const recreatedAttrPairs = span.isText ? [] : node.getGCPairs();\n\n    const siblings = parent.allChildren;\n\n    // `attach` finishes every anchor rung below: register the node, then decide\n    // whether it is born live or born tombstoned.\n    //\n    // The parent may have been tombstoned since this node was purged, in which\n    // case the node is born tombstoned rather than live. This mirrors the\n    // convention the concurrent-insert path already states (\"if insertion\n    // happens during concurrent editing and parent node has been removed, make\n    // new nodes as tombstone immediately\"). Recreating it live would leave a\n    // node that the next purge of the parent unlinks but never unregisters --\n    // reachable from nothing, still in nodeMapByID -- which is what sends\n    // toTreePos off the top of a detached subtree (#2008).\n    //\n    // The stamp is the PARENT's removedAt, not the restoring operation's\n    // ticket: that is the ticket the removal already wrote onto every sibling\n    // it swept, so the node rejoins them carrying what it would have carried\n    // had it never been purged, and it agrees with a replica that recreated it\n    // live and then had the removal sweep it. Stamping the restoring op's\n    // ticket makes those two disagree, and removedAt feeds canDelete, so they\n    // would then collect on different passes. The stamp only has to be\n    // overwritable by the eventual LWW winner, and it is: a later concurrent\n    // removal with a higher ticket reaches the tombstoned node and overwrites\n    // it (see CRDTTreeNode.remove).\n    //\n    // Accounting: the node is garbage the moment it is born, and its size was\n    // never in `docSize.live` -- it was purged before this restore, and\n    // returning undefined keeps it out of `restore`'s `recreated` list, which\n    // is the only thing that books a recreated node into live. So the pair\n    // carries `gcOnlySize`: charge the size to `docSize.gc` only and leave live\n    // alone. Subtracting from live, as a pair without `gcOnlySize` would, drives\n    // live negative by exactly this node's size.\n    // Go's `RegisterGCPair` takes the same `GCOnlySize`, so both SDKs reach\n    // the same numbers the same way. `purge` subtracts `child.getDataSize()`\n    // from gc, so charging exactly that nets gc back to zero on collection.\n    const attach = (): CRDTTreeNode | undefined => {\n      this.registerNode(node);\n      for (const pair of recreatedAttrPairs) {\n        this.pendingGCPairs.push(pair);\n      }\n      if (parent.isRemoved) {\n        node.remove(parent.removedAt!);\n        this.pendingGCPairs.push({\n          parent: this,\n          child: node,\n          gcOnlySize: node.getDataSize(),\n        });\n        return undefined;\n      }\n      return node;\n    };\n\n    // (a) same-insertion successor / predecessor piece (text): exact slot.\n    if (span.isText) {\n      const succ = this.findFloorNode(\n        CRDTTreeNodeID.of(span.id.getCreatedAt(), offset + length),\n      );\n      if (\n        succ &&\n        succ.isText &&\n        succ.parent === parent &&\n        succ.id.getOffset() === offset + length\n      ) {\n        parent.insertAt(node, siblings.indexOf(succ));\n        return attach();\n      }\n      if (offset > span.id.getOffset() || offset > 0) {\n        const pred = this.findFloorNode(\n          CRDTTreeNodeID.of(span.id.getCreatedAt(), offset - 1),\n        );\n        if (pred && pred.isText && pred.parent === parent) {\n          parent.insertAfter(node, pred);\n          return attach();\n        }\n      }\n    }\n\n    // (b) captured left boundary sibling, if it still exists under this parent.\n    if (span.leftSiblingID) {\n      const left = this.findFloorNode(span.leftSiblingID);\n      if (left && left.parent === parent) {\n        parent.insertAfter(node, left);\n        return attach();\n      }\n    }\n\n    // (c) captured right boundary sibling (redundant anchor): insert before it.\n    if (span.rightSiblingID) {\n      const right = this.findFloorNode(span.rightSiblingID);\n      if (right && right.parent === parent) {\n        const rightIdx = siblings.indexOf(right);\n        parent.insertAt(node, rightIdx);\n        return attach();\n      }\n    }\n\n    // (d) deterministic id-order fallback: first slot whose child id > node id.\n    let insertIdx = siblings.length;\n    for (let i = 0; i < siblings.length; i++) {\n      if (this.compareNodeID(siblings[i].id, node.id) > 0) {\n        insertIdx = i;\n        break;\n      }\n    }\n    parent.insertAt(node, insertIdx);\n    return attach();\n  }\n\n  /**\n   * `leftAnchorID` returns the id to store as a restore span's left-sibling\n   * anchor. For a text node the anchor is its LAST character's offset, not its\n   * start: a concurrent delete may later split the left neighbor, and only the\n   * last-char offset floor-resolves to the rightmost fragment (the true left\n   * neighbor of the restored node). For elements (never split by offset) the\n   * node's own id is exact. Right-sibling anchors always use the start offset,\n   * which floor-resolves to the leftmost fragment — the true right neighbor.\n   */\n  private leftAnchorID(sibling: CRDTTreeNode): CRDTTreeNodeID {\n    // A text node with no characters has no last character to anchor on, and\n    // `value.length - 1` would put the anchor one code unit before the node's\n    // own start — offset -1 for a node at offset 0. Local edits cannot create\n    // one (`validateTextNode`), but a remote peer's contents are decoded\n    // without that check. The node's own ID floor-resolves to the same node.\n    if (!sibling.isText || sibling.value.length === 0) {\n      return sibling.id;\n    }\n    return CRDTTreeNodeID.of(\n      sibling.id.getCreatedAt(),\n      sibling.id.getOffset() + sibling.value.length - 1,\n    );\n  }\n\n  /**\n   * `compareNodeID` totally orders two ids: createdAt (lamport, then actorID)\n   * then offset. Used by the deterministic id-order restore fallback so a\n   * recreated node lands in the same slot on every replica.\n   */\n  private compareNodeID(a: CRDTTreeNodeID, b: CRDTTreeNodeID): number {\n    const c = a.getCreatedAt().compare(b.getCreatedAt());\n    if (c !== 0) return c;\n    return a.getOffset() - b.getOffset();\n  }\n\n  /**\n   * `getGCPairs` returns the pairs of GC.\n   */\n  public getGCPairs(): Array<GCPair> {\n    const pairs: Array<GCPair> = [];\n    // NOTE: `traverse` only visits visible children, which never includes\n    // removed nodes. `traverseAll` is required to register tombstones\n    // (including pieces split off a tombstoned node) when the tree is\n    // registered: snapshot load, a Set/Add/ArraySet payload, an undo re-set.\n    // These pairs carry `gcOnlySize` because the tree's registered live size\n    // only counted visible nodes.\n    this.indexTree.traverseAll((node) => {\n      // The walk includes the root, and purging is detachment from a parent,\n      // which the root does not have. It is never legitimately removed, but a\n      // crafted Set/Add payload can mark it so; leave it unbooked, as Go does.\n      if (node.getRemovedAt() && node.parent) {\n        pairs.push({\n          parent: this,\n          child: node,\n          gcOnlySize: node.getDataSize(),\n        });\n      }\n\n      for (const p of node.getGCPairs()) {\n        pairs.push(p);\n      }\n    });\n\n    return pairs;\n  }\n\n  /**\n   * `findPos` finds the position of the given index in the tree. It rejects\n   * an index inside a UTF-16 surrogate pair.\n   */\n  public findPos(index: number, preferText = true): CRDTTreePos {\n    const treePos = this.indexTree.findTreePos(index, preferText);\n    if (treePos.node.isText) {\n      this.validateUTF16Boundary(treePos);\n    }\n\n    return CRDTTreePos.fromTreePos(treePos);\n  }\n\n  /**\n   * `validateUTF16Boundary` throws when the given text position splits a\n   * surrogate pair. At either end of the node it reads the neighbouring text\n   * node: converting a position back to an index splits text nodes with no\n   * operation, so a pair can sit in two nodes on this replica while it is\n   * one node on every other, and an index at that seam is still inside it.\n   */\n  private validateUTF16Boundary({ node, offset }: TreePos<CRDTTreeNode>) {\n    const value = node.value;\n    let before = value.charCodeAt(offset - 1);\n    let after = value.charCodeAt(offset);\n    if (offset === 0) {\n      const prev = node.prevSibling;\n      before = prev?.isText\n        ? prev.value.charCodeAt(prev.value.length - 1)\n        : NaN;\n    }\n    if (offset === value.length) {\n      const next = node.nextSibling;\n      after = next?.isText ? next.value.charCodeAt(0) : NaN;\n    }\n\n    ensureUTF16Boundary(before, after);\n  }\n\n  /**\n   * `findPosUnchecked` is `findPos` without the surrogate pair check. It is\n   * for indexes the document computed itself, such as an undo range\n   * reconciled against a remote edit, which can land inside a pair through no\n   * fault of the caller. Refusing such an index would only drop the undo, so\n   * it resolves the way it did before the check existed.\n   */\n  public findPosUnchecked(index: number, preferText = true): CRDTTreePos {\n    const treePos = this.indexTree.findTreePos(index, preferText);\n    return CRDTTreePos.fromTreePos(treePos);\n  }\n\n  /**\n   * `pathToPosRange` converts the given path of the node to the range of the position.\n   *\n   * The end index is derived here rather than supplied by the caller, so it\n   * goes through `findPosUnchecked`: the caller named a node by path, and\n   * refusing the range because the index one past that node happens to land\n   * inside a surrogate pair would reject a request that is valid as given.\n   *\n   * The path has to name an existing node or character, because the derived\n   * range is one index wide around it. `pathToTreePos` is laxer: it accepts\n   * the offset one past the parent's content, which is where an insertion\n   * goes. For an element parent that offset is the parent's closing tag, and\n   * for a text-only parent it is the end of the last character, which\n   * resolves to the same closing tag; either way the derived range would\n   * cover the parent and style it instead of failing.\n   */\n  public pathToPosRange(path: Array<number>): [CRDTTreePos, CRDTTreePos] {\n    const treePos = this.indexTree.pathToTreePos(path);\n    const { node, offset } = treePos;\n    // A path into a text-only parent names a character offset rather than a\n    // node, so it is bounded by the text node's own length. The offset at the\n    // end of one text node still names the first character of the next one,\n    // so it is only out of range once there is no following sibling.\n    // A negative offset is already rejected by `pathToTreePos`, which every\n    // path-taking entry point shares, so only the upper bound is left here.\n    const pastTheEnd = node.isText\n      ? offset >= node.visibleSize && !node.nextSibling\n      : offset >= node.children.length;\n    if (pastTheEnd) {\n      throw new YorkieError(Code.ErrInvalidArgument, 'unacceptable path');\n    }\n\n    const fromIdx = this.indexTree.indexOf(treePos);\n    return [this.findPos(fromIdx), this.findPosUnchecked(fromIdx + 1)];\n  }\n\n  /**\n   * `pathToPos` finds the position of the given index in the tree by path.\n   */\n  public pathToPos(path: Array<number>): CRDTTreePos {\n    const index = this.indexTree.pathToIndex(path);\n    return this.findPos(index);\n  }\n\n  /**\n   * `getRoot` returns the root node of the tree.\n   */\n  public getRoot(): CRDTTreeNode {\n    return this.indexTree.getRoot();\n  }\n\n  /**\n   * `getSize` returns the size of the tree.\n   */\n  public getSize(): number {\n    return this.indexTree.size;\n  }\n\n  /**\n   * `getNodeSize` returns the size of the LLRBTree.\n   */\n  public getNodeSize(): number {\n    return this.nodeMapByID.size();\n  }\n\n  /**\n   * `getIndexTree` returns the index tree.\n   */\n  public getIndexTree(): IndexTree<CRDTTreeNode> {\n    return this.indexTree;\n  }\n\n  /**\n   * toXML returns the XML encoding of this tree.\n   */\n  public toXML(): string {\n    return toXML(this.indexTree.getRoot());\n  }\n\n  /**\n   * `getDataSize` returns the data usage of this element.\n   */\n  public getDataSize(): DataSize {\n    const dataSize = { data: 0, meta: 0 };\n\n    this.indexTree.traverse((node) => {\n      if (node.getRemovedAt()) {\n        return;\n      }\n\n      const size = node.getDataSize();\n      dataSize.data += size.data;\n      dataSize.meta += size.meta;\n    });\n\n    return {\n      data: dataSize.data,\n      meta: dataSize.meta + this.getMetaUsage(),\n    };\n  }\n\n  /**\n   * `toJSON` returns the JSON encoding of this tree.\n   */\n  public toJSON(): string {\n    return JSON.stringify(this.getRootTreeNode());\n  }\n\n  /**\n   * `toJSForTest` returns value with meta data for testing.\n   */\n  public toJSForTest(): Devtools.JSONElement {\n    return {\n      createdAt: this.getCreatedAt().toTestString(),\n      value: JSON.parse(this.toJSON()),\n      type: 'YORKIE_TREE',\n    };\n  }\n\n  /**\n   * `toJSInfoForTest` returns detailed TreeNode information for use in Devtools.\n   */\n  public toJSInfoForTest(): Devtools.TreeNodeInfo {\n    const rootNode = this.indexTree.getRoot();\n\n    const toTreeNodeInfo = (\n      node: CRDTTreeNode,\n      parentNode: CRDTTreeNode | undefined = undefined,\n      leftChildNode: CRDTTreeNode | undefined = undefined,\n      depth = 0,\n    ): Devtools.TreeNodeInfo => {\n      let index, path, pos;\n\n      const treePos = node.isText\n        ? { node, offset: 0 }\n        : parentNode && leftChildNode\n          ? this.toTreePos(parentNode, leftChildNode)\n          : null;\n\n      if (treePos) {\n        index = this.indexTree.indexOf(treePos);\n        path = this.indexTree.treePosToPath(treePos);\n        pos = CRDTTreePos.fromTreePos(treePos).toStruct();\n      }\n\n      const nodeInfo: Devtools.TreeNodeInfo = {\n        type: node.type,\n        parent: parentNode?.id.toTestString(),\n        size: node.visibleSize,\n        id: node.id.toTestString(),\n        removedAt: node.removedAt?.toTestString(),\n        insPrev: node.insPrevID?.toTestString(),\n        insNext: node.insNextID?.toTestString(),\n        value: node.isText ? node.value : undefined,\n        isRemoved: node.isRemoved,\n        children: [] as Array<Devtools.TreeNodeInfo>,\n        depth,\n        attributes: node.attrs\n          ? parseObjectValues(node.attrs?.toObject())\n          : undefined,\n        index,\n        path,\n        pos,\n      };\n\n      for (let i = 0; i < node.allChildren.length; i++) {\n        const leftChildNode = i === 0 ? node : node.allChildren[i - 1];\n        nodeInfo.children.push(\n          toTreeNodeInfo(node.allChildren[i], node, leftChildNode, depth + 1),\n        );\n      }\n\n      return nodeInfo;\n    };\n\n    return toTreeNodeInfo(rootNode);\n  }\n\n  /**\n   * `getRootTreeNode` returns the converted value of this tree to TreeNode.\n   */\n  public getRootTreeNode(): TreeNode {\n    return toTreeNode(this.indexTree.getRoot());\n  }\n\n  /**\n   * `toTestTreeNode` returns the JSON of this tree for debugging.\n   */\n  public toTestTreeNode(): TreeNodeForTest {\n    return toTestTreeNode(this.indexTree.getRoot());\n  }\n\n  /**\n   * `toSortedJSON` returns the sorted JSON encoding of this tree.\n   */\n  public toSortedJSON(): string {\n    return this.toJSON();\n  }\n\n  /**\n   * `deepcopy` copies itself deeply.\n   */\n  public deepcopy(): CRDTTree {\n    const root = this.getRoot();\n    const tree = new CRDTTree(root.deepcopy(), this.getCreatedAt());\n    tree.setRemovedAt(this.getRemovedAt());\n    tree.setMovedAt(this.getMovedAt());\n    return tree;\n  }\n\n  /**\n   * `toPath` converts the given CRDTTreeNodeID to the path of the tree.\n   */\n  public toPath(\n    parentNode: CRDTTreeNode,\n    leftNode: CRDTTreeNode,\n  ): Array<number> {\n    const treePos = this.toTreePos(parentNode, leftNode);\n    if (!treePos) {\n      return [];\n    }\n\n    return this.indexTree.treePosToPath(treePos);\n  }\n\n  /**\n   * `toIndex` converts the given CRDTTreeNodeID to the index of the tree.\n   * If includeRemoved is true, it includes removed nodes in the calculation.\n   */\n  public toIndex(\n    parentNode: CRDTTreeNode,\n    leftNode: CRDTTreeNode,\n    includeRemoved: boolean = false,\n  ): number {\n    const treePos = this.toTreePos(parentNode, leftNode, includeRemoved);\n    if (!treePos) {\n      return -1;\n    }\n\n    return this.indexTree.indexOf(treePos, includeRemoved);\n  }\n\n  /**\n   * `indexToPath` converts the given tree index to path.\n   */\n  public indexToPath(index: number): Array<number> {\n    return this.indexTree.indexToPath(index);\n  }\n\n  /**\n   * `pathToIndex` converts the given path to index.\n   */\n  public pathToIndex(path: Array<number>): number {\n    return this.indexTree.pathToIndex(path);\n  }\n\n  /**\n   * `indexRangeToPosRange` returns the position range from the given index range.\n   * It converts a selection, not an edit range, so it skips the surrogate pair\n   * check.\n   */\n  public indexRangeToPosRange(range: [number, number]): TreePosRange {\n    const fromPos = this.findPosUnchecked(range[0]);\n    if (range[0] === range[1]) {\n      return [fromPos, fromPos];\n    }\n    return [fromPos, this.findPosUnchecked(range[1])];\n  }\n\n  /**\n   * `indexRangeToPosStructRange` converts the integer index range into the Tree position range structure.\n   * Like `indexRangeToPosRange`, it is for selections and skips the surrogate\n   * pair check.\n   */\n  public indexRangeToPosStructRange(\n    range: [number, number],\n  ): TreePosStructRange {\n    const [fromIdx, toIdx] = range;\n    const fromPos = this.findPosUnchecked(fromIdx);\n    if (fromIdx === toIdx) {\n      return [fromPos.toStruct(), fromPos.toStruct()];\n    }\n\n    return [fromPos.toStruct(), this.findPosUnchecked(toIdx).toStruct()];\n  }\n\n  /**\n   * `posRangeToPathRange` converts the given position range to the path range.\n   */\n  public posRangeToPathRange(\n    range: TreePosRange,\n  ): [Array<number>, Array<number>] {\n    const [[fromParent, fromLeft]] = this.findNodesAndSplitText(range[0]);\n    const [[toParent, toLeft]] = this.findNodesAndSplitText(range[1]);\n    return [this.toPath(fromParent, fromLeft), this.toPath(toParent, toLeft)];\n  }\n\n  /**\n   * `posRangeToIndexRange` converts the given position range to the path range.\n   */\n  public posRangeToIndexRange(range: TreePosRange): [number, number] {\n    const [[fromParent, fromLeft]] = this.findNodesAndSplitText(range[0]);\n    const [[toParent, toLeft]] = this.findNodesAndSplitText(range[1]);\n    return [this.toIndex(fromParent, fromLeft), this.toIndex(toParent, toLeft)];\n  }\n\n  /**\n   * `traverseInPosRange` traverses the tree in the given position range.\n   * If includeRemoved is true, it includes removed nodes in the calculation.\n   */\n  private traverseInPosRange(\n    fromParent: CRDTTreeNode,\n    fromLeft: CRDTTreeNode,\n    toParent: CRDTTreeNode,\n    toLeft: CRDTTreeNode,\n    callback: (token: TreeToken<CRDTTreeNode>, ended: boolean) => void,\n    includeRemoved: boolean = false,\n  ): void {\n    const fromIdx = this.toIndex(fromParent, fromLeft, includeRemoved);\n    const toIdx = this.toIndex(toParent, toLeft, includeRemoved);\n    // When a concurrent merge redirects the to-position into an earlier\n    // part of the tree, the range becomes empty (prior merge handled it).\n    if (fromIdx > toIdx) {\n      return;\n    }\n    this.indexTree.tokensBetween(fromIdx, toIdx, callback, includeRemoved);\n  }\n\n  /**\n   * `toTreePos` converts the given nodes to the position of the IndexTree.\n   * If includeRemoved is true, it includes removed nodes in the calculation.\n   */\n  private toTreePos(\n    parentNode: CRDTTreeNode,\n    leftNode: CRDTTreeNode,\n    includeRemoved: boolean = false,\n  ): TreePos<CRDTTreeNode> | undefined {\n    if (!parentNode || !leftNode) {\n      return;\n    }\n\n    if (!includeRemoved && parentNode.isRemoved) {\n      // If parentNode is removed, treePos is the position of its least alive ancestor.\n      let childNode: CRDTTreeNode;\n      while (parentNode.isRemoved) {\n        childNode = parentNode;\n        // If the subtree has been detached by garbage collection, the walk\n        // can run off the top of it. Report it instead of dereferencing\n        // undefined. Throwing rather than returning undefined is deliberate:\n        // toIndex turns undefined into -1, which would go on to resolve a\n        // bogus position and edit the wrong range.\n        if (!childNode.parent) {\n          throw new YorkieError(\n            Code.ErrInvalidArgument,\n            `least alive ancestor of ${childNode.id.toIDString()}: node not found`,\n          );\n        }\n        parentNode = childNode.parent;\n      }\n\n      const offset = parentNode.findOffset(childNode!, includeRemoved);\n      return {\n        node: parentNode,\n        offset,\n      };\n    }\n\n    if (parentNode === leftNode) {\n      return {\n        node: parentNode,\n        offset: 0,\n      };\n    }\n\n    // Find the closest existing leftSibling node.\n    let offset = parentNode.findOffset(leftNode, includeRemoved);\n    if (includeRemoved || !leftNode.isRemoved) {\n      if (leftNode.isText) {\n        return {\n          node: leftNode,\n          offset: leftNode.paddedSize(includeRemoved),\n        };\n      }\n\n      offset++;\n    }\n\n    return {\n      node: parentNode,\n      offset,\n    };\n  }\n\n  /**\n   * `makeDeletionChanges` converts nodes to be deleted to deletion changes.\n   */\n  private makeDeletionChanges(\n    candidates: Array<TreeToken<CRDTTreeNode>>,\n    editedAt: TimeTicket,\n  ): Array<TreeChange> {\n    const changes: Array<TreeChange> = [];\n    const ranges: Array<Array<TreeToken<CRDTTreeNode>>> = [];\n\n    // Generate ranges by accumulating consecutive nodes.\n    let start = null;\n    let end = null;\n    for (let i = 0; i < candidates.length; i++) {\n      const cur = candidates[i];\n      const next = candidates[i + 1];\n      if (!start) {\n        start = cur;\n      }\n      end = cur;\n\n      const rightToken = this.findRightToken(cur);\n      if (\n        !rightToken ||\n        !next ||\n        rightToken[0] !== next[0] ||\n        rightToken[1] !== next[1]\n      ) {\n        ranges.push([start, end]);\n        start = null;\n        end = null;\n      }\n    }\n\n    // Convert each range to a deletion change.\n    for (const range of ranges) {\n      const [start, end] = range;\n      const [fromLeft, fromLeftTokenType] = this.findLeftToken(start);\n      const [toLeft, toLeftTokenType] = end;\n      const fromParent =\n        fromLeftTokenType === TokenType.Start ? fromLeft : fromLeft.parent!;\n      const toParent =\n        toLeftTokenType === TokenType.Start ? toLeft : toLeft.parent!;\n\n      const fromIdx = this.toIndex(fromParent, fromLeft);\n      const toIdx = this.toIndex(toParent, toLeft);\n      if (fromIdx < toIdx) {\n        // When the range is overlapped with the previous one, compact them.\n        if (changes.length > 0 && fromIdx === changes[changes.length - 1].to) {\n          changes[changes.length - 1].to = toIdx;\n          changes[changes.length - 1].toPath = this.toPath(toParent, toLeft);\n        } else {\n          changes.push({\n            type: TreeChangeType.Content,\n            from: fromIdx,\n            to: toIdx,\n            fromPath: this.toPath(fromParent, fromLeft),\n            toPath: this.toPath(toParent, toLeft),\n            actor: editedAt.getActorID(),\n          });\n        }\n      }\n    }\n    return changes.reverse();\n  }\n\n  /**\n   * `findRightToken` returns the token to the right of the given token in the tree.\n   */\n  private findRightToken([\n    node,\n    tokenType,\n  ]: TreeToken<CRDTTreeNode>): TreeToken<CRDTTreeNode> {\n    if (tokenType === TokenType.Start) {\n      const children = node.allChildren;\n      if (children.length > 0) {\n        return [\n          children[0],\n          children[0].isText ? TokenType.Text : TokenType.Start,\n        ];\n      }\n      return [node, TokenType.End];\n    }\n\n    const parent = node.parent!;\n    const siblings = parent.allChildren;\n    const offset = siblings.indexOf(node);\n    if (parent && offset === siblings.length - 1) {\n      return [parent, TokenType.End];\n    }\n\n    const next = siblings[offset + 1];\n    return [next, next.isText ? TokenType.Text : TokenType.Start];\n  }\n\n  /**\n   * `findLeftToken` returns the token to the left of the given token in the tree.\n   */\n  private findLeftToken([\n    node,\n    tokenType,\n  ]: TreeToken<CRDTTreeNode>): TreeToken<CRDTTreeNode> {\n    if (tokenType === TokenType.End) {\n      const children = node.allChildren;\n      if (children.length > 0) {\n        const lastChild = children[children.length - 1];\n        return [lastChild, lastChild.isText ? TokenType.Text : TokenType.End];\n      }\n\n      return [node, TokenType.Start];\n    }\n\n    const parent = node.parent!;\n    const siblings = parent.allChildren;\n    const offset = siblings.indexOf(node);\n    if (parent && offset === 0) {\n      return [parent, TokenType.Start];\n    }\n\n    const prev = siblings[offset - 1];\n    return [prev, prev.isText ? TokenType.Text : TokenType.End];\n  }\n}\n","/*\n * Copyright 2020 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TimeTicket } from '@yorkie-js/sdk/src/document/time/ticket';\nimport { VersionVector } from '@yorkie-js/sdk/src/document/time/version_vector';\nimport { Indexable } from '@yorkie-js/sdk/src/document/document';\nimport { RHT, RHTNode, RHTWrite } from '@yorkie-js/sdk/src/document/crdt/rht';\nimport { CRDTElement } from '@yorkie-js/sdk/src/document/crdt/element';\nimport {\n  RGATreeSplit,\n  RGATreeSplitNode,\n  RGATreeSplitNodeID,\n  RGATreeSplitPos,\n  RGATreeSplitPosRange,\n  RestoreSpan,\n  ValueChange,\n} from '@yorkie-js/sdk/src/document/crdt/rga_tree_split';\nimport {\n  ensureNoLoneSurrogate,\n  ensureUTF16Boundary,\n  escapeString,\n} from '@yorkie-js/sdk/src/document/json/strings';\nimport {\n  parseAttrValue,\n  parseObjectValues,\n} from '@yorkie-js/sdk/src/util/object';\nimport type * as Devtools from '@yorkie-js/sdk/src/devtools/types';\nimport { GCChild, GCPair } from '@yorkie-js/sdk/src/document/crdt/gc';\nimport {\n  accAttrWrite,\n  attrGCPair,\n} from '@yorkie-js/sdk/src/document/crdt/tree';\nimport { SplayTree } from '@yorkie-js/sdk/src/util/splay_tree';\nimport { LLRBTree } from '@yorkie-js/sdk/src/util/llrb_tree';\nimport {\n  DataSize,\n  DocSize,\n  addDataSizes,\n  subDataSize,\n} from '@yorkie-js/sdk/src/util/resource';\n\n/**\n * `TextChangeType` is the type of TextChange.\n *\n */\nenum TextChangeType {\n  Content = 'content',\n  Style = 'style',\n}\n\n/**\n * `TextValueType` is a value of Text\n * which has a attributes that expresses the text style.\n */\nexport interface TextValueType<A> {\n  attributes?: A;\n  content?: string;\n}\n\n/**\n * `TextChange` represents the changes to the text\n * when executing the edit, setstyle methods.\n */\ninterface TextChange<A = Indexable> extends ValueChange<TextValueType<A>> {\n  type: TextChangeType;\n}\n\n/**\n * `CRDTTextValue` is a value of Text\n * which has a attributes that expresses the text style.\n * Attributes are represented by RHT.\n *\n */\nexport class CRDTTextValue {\n  private attributes: RHT;\n  private content: string;\n\n  constructor(content: string) {\n    this.attributes = RHT.create();\n    this.content = content;\n  }\n\n  /**\n   * `create` creates a instance of CRDTTextValue.\n   */\n  public static create(content: string): CRDTTextValue {\n    return new CRDTTextValue(content);\n  }\n\n  /**\n   * `length` returns the length of value.\n   */\n  public get length(): number {\n    return this.content.length;\n  }\n\n  /**\n   * `substring` returns a sub-string value of the given range.\n   */\n  public substring(indexStart: number, indexEnd: number): CRDTTextValue {\n    const value = new CRDTTextValue(\n      this.content.substring(indexStart, indexEnd),\n    );\n    value.attributes = this.attributes.deepcopy();\n    return value;\n  }\n\n  /**\n   * `truncate` shortens this value in place, keeping the object identity so\n   * that GC pairs registered against it are not orphaned. See\n   * `RGATreeSplitValue.truncate`.\n   */\n  public truncate(offset: number): void {\n    this.content = this.content.substring(0, offset);\n  }\n\n  /**\n   * `setAttr` sets attribute of the given key, updated time and value.\n   */\n  public setAttr(\n    key: string,\n    content: string,\n    updatedAt: TimeTicket,\n  ): RHTWrite {\n    return this.attributes.set(key, content, updatedAt);\n  }\n\n  /**\n   * `getAttr` returns the attributes of this value.\n   */\n  public getAttrs(): RHT {\n    return this.attributes;\n  }\n\n  /**\n   * `toString` returns the string representation of this value.\n   */\n  public toString(): string {\n    return this.content;\n  }\n\n  /**\n   * `getDataSize` returns the data usage of this value.\n   */\n  public getDataSize(): DataSize {\n    const dataSize = { data: 0, meta: 0 };\n    dataSize.data += this.content.length * 2;\n\n    for (const node of this.attributes) {\n      // A removed attribute belongs to docSize.gc, not to live.\n      // `CRDTTreeNode.getDataSize` makes the same exclusion; the two halves\n      // have to answer this the same way or a document's size stops being a\n      // function of its content.\n      if (node.isRemoved()) {\n        continue;\n      }\n\n      const size = node.getDataSize();\n      dataSize.meta += size.meta;\n      dataSize.data += size.data;\n    }\n\n    return dataSize;\n  }\n\n  /**\n   * `toJSON` returns the JSON encoding of this value.\n   */\n  public toJSON(): string {\n    const content = escapeString(this.content);\n    const attrsObj = this.attributes.toObject();\n    const attrs = [];\n    for (const [key, v] of Object.entries(attrsObj)) {\n      // See `parseAttrValue`: a peer that stores values raw writes ones this\n      // cannot parse, and rendering must not throw on them.\n      const value = parseAttrValue(v);\n      // A non-string is re-encoded, never interpolated: `String(value)` on an\n      // object or array emits `[object Object]` and on a parsed string-shaped\n      // value emits it unquoted, either of which breaks out of the JSON this\n      // builds and lets a peer-chosen attribute forge structure in\n      // `Document.toJSON`.\n      const item =\n        typeof value === 'string'\n          ? `\"${escapeString(key)}\":\"${escapeString(value)}\"`\n          : `\"${escapeString(key)}\":${JSON.stringify(value)}`;\n      attrs.push(item);\n    }\n    attrs.sort();\n    if (attrs.length === 0) {\n      return `{\"val\":\"${content}\"}`;\n    }\n    return `{\"attrs\":{${attrs.join(',')}},\"val\":\"${content}\"}`;\n  }\n\n  /**\n   * `getAttributes` returns the attributes of this value.\n   */\n  public getAttributes(): Record<string, string> {\n    return this.attributes.toObject();\n  }\n\n  /**\n   * `getContent` returns the internal content.\n   */\n  public getContent(): string {\n    return this.content;\n  }\n\n  /**\n   * `purge` purges the given child node.\n   */\n  public purge(node: GCChild): void {\n    if (this.attributes && node instanceof RHTNode) {\n      this.attributes.purge(node);\n    }\n  }\n\n  /**\n   * `getGCPairs` returns the pairs of GC.\n   */\n  public getGCPairs(): Array<GCPair> {\n    const pairs = [];\n\n    for (const node of this.attributes) {\n      if (node.getRemovedAt()) {\n        // `getDataSize` skips removed attributes, so a tombstoned attribute\n        // is not part of the live size this root was built with. Registering\n        // it without `gcOnlySize` would debit live for bytes it never held.\n        pairs.push({\n          parent: this,\n          child: node,\n          gcOnlySize: node.getDataSize(),\n        });\n      }\n    }\n\n    return pairs;\n  }\n}\n\n/**\n * `indexedContent` returns the text the given node contributes to the index:\n * empty for the head node, which holds no value, and for a tombstone, whose\n * text the index no longer counts.\n */\nfunction indexedContent(node: RGATreeSplitNode<CRDTTextValue>): string {\n  const value: CRDTTextValue | undefined = node.getValue();\n  return node.isRemoved() || !value ? '' : value.getContent();\n}\n\n/**\n * `neighborContent` returns the content of the nearest node on the given side\n * that still contributes text, or an empty string when there is none.\n */\nfunction neighborContent(\n  node: RGATreeSplitNode<CRDTTextValue>,\n  step: (\n    n: RGATreeSplitNode<CRDTTextValue>,\n  ) => RGATreeSplitNode<CRDTTextValue> | undefined,\n): string {\n  for (let n = step(node); n; n = step(n)) {\n    const content = indexedContent(n);\n    if (content) {\n      return content;\n    }\n  }\n\n  return '';\n}\n\n/**\n *  `CRDTText` is a custom CRDT data type to represent the contents of text editors.\n *\n */\nexport class CRDTText<A extends Indexable = Indexable> extends CRDTElement {\n  private rgaTreeSplit: RGATreeSplit<CRDTTextValue>;\n\n  constructor(\n    rgaTreeSplit: RGATreeSplit<CRDTTextValue>,\n    createdAt: TimeTicket,\n  ) {\n    super(createdAt);\n    this.rgaTreeSplit = rgaTreeSplit;\n  }\n\n  /**\n   * `create` a instance of Text.\n   */\n  public static create<A extends Indexable>(\n    rgaTreeSplit: RGATreeSplit<CRDTTextValue>,\n    createdAt: TimeTicket,\n  ): CRDTText<A> {\n    return new CRDTText<A>(rgaTreeSplit, createdAt);\n  }\n\n  /**\n   * `edit` edits the given range with the given value and attributes.\n   */\n  public edit(\n    range: RGATreeSplitPosRange,\n    content: string,\n    editedAt: TimeTicket,\n    attributes?: Record<string, string>,\n    versionVector?: VersionVector,\n  ): [\n    Array<TextChange<A>>,\n    Array<GCPair>,\n    DataSize,\n    RGATreeSplitPosRange,\n    Array<CRDTTextValue>,\n    Array<RestoreSpan<CRDTTextValue>>,\n  ] {\n    const crdtTextValue = content ? CRDTTextValue.create(content) : undefined;\n    if (crdtTextValue && attributes) {\n      for (const [k, v] of Object.entries(attributes)) {\n        crdtTextValue.setAttr(k, v, editedAt);\n      }\n    }\n\n    const [caretPos, pairs, diff, valueChanges, removedValues, removedSpans] =\n      this.rgaTreeSplit.edit(range, editedAt, crdtTextValue, versionVector);\n\n    const changes: Array<TextChange<A>> = valueChanges.map((change) => ({\n      ...change,\n      value: change.value\n        ? {\n            attributes: parseObjectValues<A>(change.value.getAttributes()),\n            content: change.value.getContent(),\n          }\n        : {\n            attributes: undefined,\n            content: '',\n          },\n      type: TextChangeType.Content,\n    }));\n\n    return [\n      changes,\n      pairs,\n      diff,\n      [caretPos, caretPos],\n      removedValues,\n      removedSpans,\n    ];\n  }\n\n  /**\n   * `restore` re-establishes removed characters under their original\n   * identities (identity-preserving undo of a deletion).\n   */\n  public restore(\n    spans: Array<RestoreSpan<CRDTTextValue>>,\n    executedAt: TimeTicket,\n    fallbackAnchor?: RGATreeSplitPos,\n  ): [\n    Array<RGATreeSplitNode<CRDTTextValue>>,\n    Array<RGATreeSplitNode<CRDTTextValue>>,\n    Array<TextChange<A>>,\n    DataSize,\n    Array<GCPair>,\n  ] {\n    const [untombstoned, recreated, valueChanges, liveDiff, pendingGCPairs] =\n      this.rgaTreeSplit.restore(spans, executedAt, fallbackAnchor);\n    return [\n      untombstoned,\n      recreated,\n      this.toTextChanges(valueChanges),\n      liveDiff,\n      pendingGCPairs,\n    ];\n  }\n\n  /**\n   * `retombstone` re-deletes previously restored characters (redo).\n   */\n  public retombstone(\n    spans: Array<RestoreSpan<CRDTTextValue>>,\n    executedAt: TimeTicket,\n    versionVector?: VersionVector,\n  ): [\n    Array<GCPair>,\n    Array<TextChange<A>>,\n    DataSize,\n    Array<RestoreSpan<CRDTTextValue>>,\n  ] {\n    const [pairs, valueChanges, diff, recorded] = this.rgaTreeSplit.retombstone(\n      spans,\n      executedAt,\n      versionVector,\n    );\n    return [pairs, this.toTextChanges(valueChanges), diff, recorded];\n  }\n\n  /**\n   * `hasCancelledRemovals` reports whether any piece's removal ledger holds a\n   * cancel that `pruneLedgers` may drop later.\n   */\n  public hasCancelledRemovals(): boolean {\n    return this.rgaTreeSplit.hasCancelledRemovals();\n  }\n\n  /**\n   * `pruneLedgers` drops the removals whose cancels the given vector covers\n   * from the pieces' ledgers, and returns how many pieces still hold a\n   * cancel.\n   */\n  public pruneLedgers(vector: VersionVector): number {\n    return this.rgaTreeSplit.pruneLedgers(vector);\n  }\n\n  /**\n   * `toTextChanges` wraps raw RGATreeSplit value changes into `TextChange`s,\n   * mirroring the mapping used by `edit`.\n   */\n  private toTextChanges(\n    valueChanges: Array<ValueChange<CRDTTextValue>>,\n  ): Array<TextChange<A>> {\n    return valueChanges.map((change) => ({\n      ...change,\n      value: change.value\n        ? {\n            attributes: parseObjectValues<A>(change.value.getAttributes()),\n            content: change.value.getContent(),\n          }\n        : {\n            attributes: undefined,\n            content: '',\n          },\n      type: TextChangeType.Content,\n    }));\n  }\n\n  /**\n   * `setStyle` applies the style of the given range.\n   * 01. split nodes with from and to\n   * 02. style nodes between from and to\n   *\n   * @param range - range of RGATreeSplitNode\n   * @param attributes - style attributes\n   * @param editedAt - edited time\n   */\n  public setStyle(\n    range: RGATreeSplitPosRange,\n    attributes: Record<string, string>,\n    editedAt: TimeTicket,\n    versionVector?: VersionVector,\n  ): [\n    Array<GCPair>,\n    DocSize,\n    Array<TextChange<A>>,\n    Map<string, string>,\n    Array<string>,\n  ] {\n    const size = { live: { data: 0, meta: 0 }, gc: { data: 0, meta: 0 } };\n\n    // 01. split nodes with from and to\n    const [, diffTo, toRight] = this.rgaTreeSplit.findNodeWithSplit(\n      range[1],\n      editedAt,\n    );\n    const [, diffFrom, fromRight] = this.rgaTreeSplit.findNodeWithSplit(\n      range[0],\n      editedAt,\n    );\n\n    addDataSizes(size.live, diffTo, diffFrom);\n\n    // 02. style nodes between from and to\n    const changes: Array<TextChange<A>> = [];\n    const nodes = this.rgaTreeSplit.findBetween(fromRight, toRight);\n    const toBeStyleds: Array<RGATreeSplitNode<CRDTTextValue>> = [];\n\n    for (const node of nodes) {\n      if (node.canStyle(versionVector)) {\n        toBeStyleds.push(node);\n      }\n    }\n\n    // Capture previous attribute values from the first styled node for reverse op\n    const prevAttributes = new Map<string, string>();\n    const attributesToRemove: Array<string> = [];\n    let capturedPrev = false;\n\n    // The reverse operation restores what the VISIBLE text held, so the prior\n    // values come from the first LIVE node in the range. `canStyle` now admits\n    // tombstones, and the first node in the range can be one -- capturing from\n    // it made an undo write an attribute onto text that never carried it, out\n    // of a run the user had already deleted. The fallback to the first node\n    // keeps an all-tombstone range undoable.\n    const captureFrom =\n      toBeStyleds.find((n) => !n.isRemoved()) ?? toBeStyleds[0];\n\n    const pairs: Array<GCPair> = [];\n    for (const node of toBeStyleds) {\n      // `canStyle` admits a node removed CONCURRENTLY with this style, which\n      // has to be styled for the replicas to agree. It is not part of the\n      // rendered text, though, so it reports no change to editors and its\n      // bytes move through gc rather than live.\n      const nodeIsLive = !node.isRemoved();\n\n      if (!capturedPrev && node === captureFrom) {\n        for (const key of Object.keys(attributes)) {\n          const attrs = node.getValue().getAttrs();\n          if (attrs.has(key)) {\n            prevAttributes.set(key, attrs.get(key)!);\n          } else {\n            attributesToRemove.push(key);\n          }\n        }\n        capturedPrev = true;\n      }\n\n      if (nodeIsLive) {\n        const [fromIdx, toIdx] = this.rgaTreeSplit.findIndexesFromRange(\n          node.createPosRange(),\n        );\n        changes.push({\n          type: TextChangeType.Style,\n          actor: editedAt.getActorID(),\n          from: fromIdx,\n          to: toIdx,\n          value: {\n            attributes: parseObjectValues(attributes) as A,\n          },\n        });\n      }\n\n      for (const [key, value] of Object.entries(attributes)) {\n        accAttrWrite(\n          node.getValue().setAttr(key, value, editedAt),\n          node.getValue(),\n          nodeIsLive,\n          pairs,\n          size,\n        );\n      }\n    }\n\n    pairs.push(...this.rgaTreeSplit.drainPendingGCPairs());\n\n    return [pairs, size, changes, prevAttributes, attributesToRemove];\n  }\n\n  /**\n   * `removeStyle` removes the style attributes of the given range.\n   * Returns previous attribute values (from first styled node) for reverse operation.\n   */\n  public removeStyle(\n    range: RGATreeSplitPosRange,\n    attributesToRemove: Array<string>,\n    editedAt: TimeTicket,\n    versionVector?: VersionVector,\n  ): [Array<GCPair>, DocSize, Array<TextChange<A>>, Map<string, string>] {\n    const size = { live: { data: 0, meta: 0 }, gc: { data: 0, meta: 0 } };\n\n    // 01. split nodes with from and to\n    const [, diffTo, toRight] = this.rgaTreeSplit.findNodeWithSplit(\n      range[1],\n      editedAt,\n    );\n    const [, diffFrom, fromRight] = this.rgaTreeSplit.findNodeWithSplit(\n      range[0],\n      editedAt,\n    );\n\n    addDataSizes(size.live, diffTo, diffFrom);\n\n    // 02. find nodes to remove style from\n    const changes: Array<TextChange<A>> = [];\n    const nodes = this.rgaTreeSplit.findBetween(fromRight, toRight);\n    const toBeStyleds: Array<RGATreeSplitNode<CRDTTextValue>> = [];\n\n    for (const node of nodes) {\n      if (node.canStyle(versionVector)) {\n        toBeStyleds.push(node);\n      }\n    }\n\n    // Capture previous attribute values from the first styled node for reverse op\n    const prevAttributes = new Map<string, string>();\n    let capturedPrev = false;\n\n    // The reverse operation restores what the VISIBLE text held, so the prior\n    // values come from the first LIVE node in the range. `canStyle` now admits\n    // tombstones, and the first node in the range can be one -- capturing from\n    // it made an undo restore a value the visible text never held. The fallback to the first node\n    // keeps an all-tombstone range undoable.\n    const captureFrom =\n      toBeStyleds.find((n) => !n.isRemoved()) ?? toBeStyleds[0];\n\n    const pairs: Array<GCPair> = [];\n    for (const node of toBeStyleds) {\n      // See setStyle: a node removed concurrently with this change is styled\n      // but is not part of the rendered text.\n      const nodeIsLive = !node.isRemoved();\n\n      if (!capturedPrev && node === captureFrom) {\n        for (const key of attributesToRemove) {\n          const attrs = node.getValue().getAttrs();\n          if (attrs.has(key)) {\n            prevAttributes.set(key, attrs.get(key)!);\n          }\n        }\n        capturedPrev = true;\n      }\n\n      if (nodeIsLive) {\n        const [fromIdx, toIdx] = this.rgaTreeSplit.findIndexesFromRange(\n          node.createPosRange(),\n        );\n\n        const removedAttributes: Record<string, any> = {};\n        for (const key of attributesToRemove) {\n          removedAttributes[key] = null; // null signals attribute removal to editors (e.g., Quill)\n        }\n        changes.push({\n          type: TextChangeType.Style,\n          actor: editedAt.getActorID(),\n          from: fromIdx,\n          to: toIdx,\n          value: {\n            attributes: removedAttributes as A,\n          },\n        });\n      }\n\n      for (const key of attributesToRemove) {\n        // `canStyle` admits a node removed concurrently with this change, so\n        // the NODE holding the attribute may itself be a tombstone -- the\n        // third case `attrGCPair` asks about.\n        let attrWasLive = node.getValue().getAttrs().has(key);\n        const { gcNodes, valueDropped } = node\n          .getValue()\n          .getAttrs()\n          .remove(key, editedAt);\n\n        // The tombstone is not charged for its value, so those bytes leave\n        // whichever side was holding them: live for a live attribute on a live\n        // node, and the node's own gc charge when the node is a tombstone --\n        // the container skips a removed node, so live never held it. The same\n        // split `attrGCPair` makes just below.\n        subDataSize(nodeIsLive ? size.live : size.gc, valueDropped);\n\n        for (const rhtNode of gcNodes) {\n          pairs.push(\n            attrGCPair(node.getValue(), rhtNode, attrWasLive, nodeIsLive),\n          );\n          // Only the node that replaces the live value settles the live\n          // value's bytes; a second one in the same call is the tombstone it\n          // superseded, which was never in live.\n          attrWasLive = false;\n        }\n      }\n    }\n\n    pairs.push(...this.rgaTreeSplit.drainPendingGCPairs());\n\n    return [pairs, size, changes, prevAttributes];\n  }\n\n  /**\n   * `indexRangeToPosRange` returns the position range of the given index range.\n   */\n  public indexRangeToPosRange(\n    fromIdx: number,\n    toIdx: number,\n  ): RGATreeSplitPosRange {\n    const fromPos = this.rgaTreeSplit.indexToPos(fromIdx);\n    if (fromIdx === toIdx) {\n      return [fromPos, fromPos];\n    }\n\n    return [fromPos, this.rgaTreeSplit.indexToPos(toIdx)];\n  }\n\n  /**\n   * `createRange` returns the position range of the given index range for a\n   * local edit or style. Unlike `indexRangeToPosRange`, it rejects an index\n   * that splits a UTF-16 surrogate pair.\n   *\n   * `content` is given for an edit and omitted for a style. It is checked for\n   * lone surrogates: storing one diverges across SDKs on its own, and the half\n   * then pairs with whatever code unit it is stored next to, which would turn\n   * the index at that seam into one `validateUTF16Boundary` refuses for the\n   * lifetime of the text. A peer running an SDK without this check can still\n   * send such content — the guard is a local-edit contract, not a trust\n   * boundary — but nothing a client of this SDK does can create it.\n   */\n  public createRange(\n    fromIdx: number,\n    toIdx: number,\n    content?: string,\n  ): RGATreeSplitPosRange {\n    if (content) {\n      ensureNoLoneSurrogate(content);\n    }\n\n    const range = this.indexRangeToPosRange(fromIdx, toIdx);\n    this.validateUTF16Boundary(range[0]);\n    if (fromIdx !== toIdx) {\n      this.validateUTF16Boundary(range[1]);\n    }\n\n    return range;\n  }\n\n  /**\n   * `validateUTF16Boundary` throws when the given position splits a surrogate\n   * pair. At either end of the node it reads the neighbouring node: an edit or\n   * a style carrying a mid-pair offset splits the node there, so a pair can\n   * sit in two nodes on this replica while it is one node on every other, and\n   * an index at that seam is still inside it. `indexToPos` resolves a seam to\n   * the node on its left, so the `offset === content.length` side is the one\n   * an index normally reaches.\n   */\n  private validateUTF16Boundary(pos: RGATreeSplitPos): void {\n    const node = this.rgaTreeSplit.findNode(pos.getID());\n    const offset = pos.getRelativeOffset();\n    const content = indexedContent(node);\n\n    let before = content.charCodeAt(offset - 1);\n    let after = content.charCodeAt(offset);\n    if (offset === 0) {\n      const prev = neighborContent(node, (n) => n.getPrev());\n      before = prev.charCodeAt(prev.length - 1);\n    }\n    if (offset === content.length) {\n      after = neighborContent(node, (n) => n.getNext()).charCodeAt(0);\n    }\n\n    ensureUTF16Boundary(before, after);\n  }\n\n  /**\n   * `length` returns size of RGATreeList.\n   */\n  public get length(): number {\n    return this.rgaTreeSplit.length;\n  }\n\n  /**\n   * `getTreeByIndex` returns the tree by index for debugging.\n   */\n  public getTreeByIndex(): SplayTree<CRDTTextValue> {\n    return this.rgaTreeSplit.getTreeByIndex();\n  }\n\n  /**\n   * `getTreeByID` returns the tree by ID for debugging.\n   */\n  public getTreeByID(): LLRBTree<\n    RGATreeSplitNodeID,\n    RGATreeSplitNode<CRDTTextValue>\n  > {\n    return this.rgaTreeSplit.getTreeByID();\n  }\n\n  /**\n   * `refinePos` refines the given RGATreeSplitPos.\n   */\n  public refinePos(pos: RGATreeSplitPos): RGATreeSplitPos {\n    return this.rgaTreeSplit.refinePos(pos);\n  }\n\n  /**\n   * `normalizePos` normalizes the given RGATreeSplitPos.\n   */\n  public normalizePos(pos: RGATreeSplitPos): RGATreeSplitPos {\n    return this.rgaTreeSplit.normalizePos(pos);\n  }\n\n  /**\n   * `getDataSize` returns the data usage of this element.\n   */\n  public getDataSize(): DataSize {\n    const dataSize = { data: 0, meta: 0 };\n    for (const node of this.rgaTreeSplit) {\n      if (node.isRemoved()) {\n        continue;\n      }\n\n      const size = node.getDataSize();\n      dataSize.data += size.data;\n      dataSize.meta += size.meta;\n    }\n\n    return {\n      data: dataSize.data,\n      meta: dataSize.meta + this.getMetaUsage(),\n    };\n  }\n\n  /**\n   * `toJSON` returns the JSON encoding of this text.\n   */\n  public toJSON(): string {\n    const json = [];\n\n    for (const node of this.rgaTreeSplit) {\n      if (!node.isRemoved()) {\n        json.push(node.getValue().toJSON());\n      }\n    }\n\n    return `[${json.join(',')}]`;\n  }\n\n  /**\n   * `toSortedJSON` returns the sorted JSON encoding of this text.\n   */\n  public toSortedJSON(): string {\n    return this.toJSON();\n  }\n\n  /**\n   * `toJSForTest` returns value with meta data for testing.\n   */\n  public toJSForTest(): Devtools.JSONElement {\n    return {\n      createdAt: this.getCreatedAt().toTestString(),\n      value: JSON.parse(this.toJSON()),\n      type: 'YORKIE_TEXT',\n    };\n  }\n\n  /**\n   * `toString` returns the string representation of this text.\n   */\n  public toString(): string {\n    return this.rgaTreeSplit.toString();\n  }\n\n  /**\n   * `values` returns the content-attributes pair array of this text.\n   */\n  public values(): Array<TextValueType<A>> {\n    const values = [];\n\n    for (const node of this.rgaTreeSplit) {\n      if (!node.isRemoved()) {\n        const value = node.getValue();\n        values.push({\n          attributes: parseObjectValues<A>(value.getAttributes()),\n          content: value.getContent(),\n        });\n      }\n    }\n\n    return values;\n  }\n\n  /**\n   * `getRGATreeSplit` returns rgaTreeSplit.\n   */\n  public getRGATreeSplit(): RGATreeSplit<CRDTTextValue> {\n    return this.rgaTreeSplit;\n  }\n\n  /**\n   * `toTestString` returns a String containing the meta data of this value\n   * for debugging purpose.\n   */\n  public toTestString(): string {\n    return this.rgaTreeSplit.toTestString();\n  }\n\n  /**\n   * `deepcopy` copies itself deeply.\n   */\n  public deepcopy(): CRDTText<A> {\n    const clone = new CRDTText<A>(\n      this.rgaTreeSplit.deepcopy(),\n      this.getCreatedAt(),\n    );\n    clone.setRemovedAt(this.getRemovedAt());\n    clone.setMovedAt(this.getMovedAt());\n    return clone;\n  }\n\n  /**\n   * `findIndexesFromRange` returns pair of integer offsets of the given range.\n   */\n  public findIndexesFromRange(range: RGATreeSplitPosRange): [number, number] {\n    return this.rgaTreeSplit.findIndexesFromRange(range);\n  }\n\n  /**\n   * `posToIndex` converts the given position to index.\n   */\n  public posToIndex(\n    pos: RGATreeSplitPos,\n    preferToLeft: boolean = false,\n  ): number {\n    return this.rgaTreeSplit.posToIndex(pos, preferToLeft);\n  }\n\n  /**\n   * `getGCPairs` returns the pairs of GC.\n   */\n  public getGCPairs(): Array<GCPair> {\n    const pairs: Array<GCPair> = [];\n    // NOTE: Called when the text is registered (snapshot load, a Set/Add/\n    // ArraySet payload, an undo re-set), where docSize.live counted visible\n    // nodes only. Tombstoned nodes (and the\n    // attribute tombstones inside them) were never part of live, so their\n    // pairs carry `gcOnlySize`. So do the attribute tombstones of visible\n    // nodes: `CRDTTextValue.getDataSize` skips removed attributes, matching\n    // the tree half, so those bytes are not in live either.\n    for (const node of this.rgaTreeSplit) {\n      if (node.getRemovedAt()) {\n        pairs.push({\n          parent: this.rgaTreeSplit,\n          child: node,\n          gcOnlySize: node.getDataSize(),\n        });\n      }\n\n      for (const p of node.getValue().getGCPairs()) {\n        pairs.push(\n          node.getRemovedAt() ? { ...p, gcOnlySize: p.child.getDataSize() } : p,\n        );\n      }\n    }\n\n    return pairs;\n  }\n}\n","/*\n * Copyright 2020 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TimeTicket } from '@yorkie-js/sdk/src/document/time/ticket';\nimport { VersionVector } from '@yorkie-js/sdk/src/document/time/version_vector';\nimport { CRDTRoot } from '@yorkie-js/sdk/src/document/crdt/root';\nimport {\n  InitialRGATreeSplitNodeID,\n  RGATreeSplitPos,\n  RestoreSpan,\n} from '@yorkie-js/sdk/src/document/crdt/rga_tree_split';\nimport { CRDTText, CRDTTextValue } from '@yorkie-js/sdk/src/document/crdt/text';\nimport {\n  Operation,\n  OpInfo,\n  ExecutionResult,\n  OpSource,\n} from '@yorkie-js/sdk/src/document/operation/operation';\nimport { Indexable } from '../document';\nimport { Code, YorkieError } from '@yorkie-js/sdk/src/util/error';\nimport { addDataSizes, DataSize } from '@yorkie-js/sdk/src/util/resource';\n\n/**\n * `RestoreMode` selects the identity-preserving path for undo/redo of\n * pure deletions: 'restore' revives spans, 'retombstone' re-deletes them.\n */\nexport type RestoreMode = 'restore' | 'retombstone';\n\n/**\n * `EditOperation` is an operation representing editing Text. Most of the same as\n * Edit, but with additional style properties, attributes.\n */\nexport class EditOperation extends Operation {\n  private fromPos: RGATreeSplitPos;\n  private toPos: RGATreeSplitPos;\n  private content: string;\n  private attributes: Map<string, string>;\n  private isUndoOp: boolean | undefined;\n\n  private restoreSpans?: Array<RestoreSpan<CRDTTextValue>>;\n  private restoreMode?: RestoreMode;\n  // `retombstoneSpans` is the companion span set for an identity-preserving\n  // reverse op. `restoreSpans` describes content the reversed edit removed;\n  // `retombstoneSpans` describes content the reversed edit inserted (non-empty\n  // only for the reverse of a replace). `restoreMode` picks the direction:\n  // 'restore' revives restoreSpans and re-removes retombstoneSpans; a\n  // 'retombstone' op (the redo) does the opposite. Reversing an edit that both\n  // inserts and deletes as two identity operations — rather than\n  // copy-reinserting the deleted text as a fresh node — keeps a later revived\n  // neighbour in its original relative order.\n  private retombstoneSpans?: Array<RestoreSpan<CRDTTextValue>>;\n\n  constructor(\n    parentCreatedAt: TimeTicket,\n    fromPos: RGATreeSplitPos,\n    toPos: RGATreeSplitPos,\n    content: string,\n    attributes: Map<string, string>,\n    executedAt?: TimeTicket,\n    isUndoOp?: boolean,\n    restoreSpans?: Array<RestoreSpan<CRDTTextValue>>,\n    restoreMode?: RestoreMode,\n    retombstoneSpans?: Array<RestoreSpan<CRDTTextValue>>,\n  ) {\n    super(parentCreatedAt, executedAt);\n    this.fromPos = fromPos;\n    this.toPos = toPos;\n    this.content = content;\n    this.attributes = attributes;\n    this.isUndoOp = isUndoOp;\n    this.restoreSpans = restoreSpans;\n    this.restoreMode = restoreMode;\n    this.retombstoneSpans = retombstoneSpans;\n  }\n\n  /**\n   * `create` creates a new instance of EditOperation.\n   */\n  public static create(\n    parentCreatedAt: TimeTicket,\n    fromPos: RGATreeSplitPos,\n    toPos: RGATreeSplitPos,\n    content: string,\n    attributes: Map<string, string>,\n    executedAt?: TimeTicket,\n    isUndoOp?: boolean,\n    restoreSpans?: Array<RestoreSpan<CRDTTextValue>>,\n    restoreMode?: RestoreMode,\n    retombstoneSpans?: Array<RestoreSpan<CRDTTextValue>>,\n  ): EditOperation {\n    return new EditOperation(\n      parentCreatedAt,\n      fromPos,\n      toPos,\n      content,\n      attributes,\n      executedAt,\n      isUndoOp,\n      restoreSpans,\n      restoreMode,\n      retombstoneSpans,\n    );\n  }\n\n  /**\n   * `execute` executes this operation on the given `CRDTRoot`.\n   */\n  public execute<A extends Indexable>(\n    root: CRDTRoot,\n    source: OpSource,\n    versionVector?: VersionVector,\n  ): ExecutionResult {\n    const parentObject = root.findByCreatedAt(this.getParentCreatedAt());\n    if (!parentObject) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `fail to find ${this.getParentCreatedAt()}`,\n      );\n    }\n    if (!(parentObject instanceof CRDTText)) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `fail to execute, only Text can execute edit`,\n      );\n    }\n\n    const text = parentObject as CRDTText<A>;\n\n    // The identity-preserving path is selected by the mode, not by the spans\n    // being present: a reverse whose span sets both came out empty is still\n    // an identity op and must run as a no-op here. Falling through to the\n    // positional path below would read its positions as an ordinary edit\n    // range.\n    if (this.restoreMode) {\n      // Identity-preserving reverse op. `restoreMode` picks the direction:\n      // an undo ('restore') revives `restoreSpans` and re-removes\n      // `retombstoneSpans`; the redo ('retombstone') does the opposite. Both\n      // sets are revived/removed by their original identity, never re-inserted\n      // as fresh nodes, so relative order is preserved across chained undo.\n      const isRetombstone = this.restoreMode === 'retombstone';\n      const toRestore =\n        (isRetombstone ? this.retombstoneSpans : this.restoreSpans) ?? [];\n      const toRetombstone =\n        (isRetombstone ? this.restoreSpans : this.retombstoneSpans) ?? [];\n\n      const opInfos: Array<OpInfo> = [];\n      const totalDiff: DataSize = { data: 0, meta: 0 };\n      const toOpInfo = (c: { from: number; to: number; value?: unknown }) =>\n        ({\n          type: 'edit',\n          from: c.from,\n          to: c.to,\n          value: c.value,\n          path: root.createPath(this.getParentCreatedAt()),\n        }) as OpInfo;\n\n      // The spans about to be re-tombstoned are what the reverse op will have\n      // to restore, and a replica that purged them rebuilds the nodes from\n      // that payload alone. Re-snapshot them against the live content first:\n      // the span set was captured when the reversed edit ran, so an attribute\n      // applied to the run since is missing from it and a purged replica would\n      // recreate the run without it while a replica that un-tombstones keeps\n      // it. Taken before the removal below, and only when the reverse is kept:\n      // a remote change discards it.\n      const refreshed =\n        source !== OpSource.Remote && toRetombstone.length\n          ? text.getRGATreeSplit().refreshSpans(toRetombstone)\n          : undefined;\n\n      // 1. Remove the content the reversed edit inserted (by identity). The\n      // reverse names only the pieces the removal was recorded on: naming it\n      // on a piece someone else removed would cancel a removal that piece\n      // never had, and a replica that purged the piece could not tell.\n      let recorded: Array<RestoreSpan<CRDTTextValue>> | undefined;\n      if (toRetombstone.length) {\n        const [pairs, changes, diff, spans] = text.retombstone(\n          refreshed ?? toRetombstone,\n          this.getExecutedAt(),\n          versionVector,\n        );\n        recorded = spans;\n        addDataSizes(totalDiff, diff);\n        for (const pair of pairs) {\n          root.registerGCPair(pair);\n        }\n        for (const c of changes) {\n          opInfos.push(toOpInfo(c));\n        }\n      }\n\n      // 2. Revive the content the reversed edit removed (by identity).\n      if (toRestore.length) {\n        const [untombstoned, , changes, liveDiff, pendingGCPairs] =\n          text.restore(toRestore, this.getExecutedAt(), this.fromPos);\n        if (text.hasCancelledRemovals()) {\n          root.registerLedgerHolder(text);\n        }\n        // Register first: a `pendingGCPairs` entry whose child ended up in\n        // `untombstoned` was never registered under its own id (it was born\n        // by splitting a larger tombstone), so the unregister loop below can\n        // only walk its size from gc back to live if it's registered here\n        // first.\n        for (const pair of pendingGCPairs) {\n          root.registerGCPair(pair);\n        }\n        for (const node of untombstoned) {\n          root.unregisterGCPair({\n            parent: text.getRGATreeSplit(),\n            child: node,\n          });\n        }\n        addDataSizes(totalDiff, liveDiff);\n        for (const c of changes) {\n          opInfos.push(toOpInfo(c));\n        }\n      }\n\n      root.acc(totalDiff);\n      return {\n        opInfos,\n        // Reverse keeps the same span sets and flips the direction.\n        reverseOp: this.identityReverse(\n          // The re-removed set is the pieces the removal was recorded on,\n          // taken from the spans refreshed against live attributes (a purged\n          // replica rebuilds from them).\n          isRetombstone && recorded ? recorded : this.restoreSpans,\n          isRetombstone ? 'restore' : 'retombstone',\n          !isRetombstone && recorded ? recorded : this.retombstoneSpans,\n        ),\n      };\n    }\n\n    if (this.isUndoOp) {\n      // An undo edit that inserts nothing changes nothing wherever it sits,\n      // but its position can name an offset the text no longer has: stacked\n      // entries are reconciled against remote positional edits, not against\n      // remote undos and redos, which change the text by identity. Run it as\n      // the no-op it is, moved to the head so the copy that goes out to other\n      // replicas resolves on every one of them.\n      if (!this.content) {\n        this.fromPos = headPos();\n        this.toPos = headPos();\n        return {\n          opInfos: [],\n          reverseOp:\n            source === OpSource.Remote ? undefined : this.emptyReverse(),\n        };\n      }\n\n      // A reverse's positions were recorded against the chain as it stood\n      // when the reverse was built; splits since then have moved them.\n      this.fromPos = text.refinePos(this.fromPos);\n      this.toPos = text.refinePos(this.toPos);\n    }\n\n    const [changes, pairs, diff, , removedValues, removedSpans] = text.edit(\n      [this.fromPos, this.toPos],\n      this.content,\n      this.getExecutedAt(),\n      Object.fromEntries(this.attributes),\n      versionVector,\n    );\n\n    const reverseOp = this.toReverseOperation(\n      removedValues,\n      text.normalizePos(this.fromPos),\n      removedSpans,\n    );\n    root.acc(diff);\n\n    for (const pair of pairs) {\n      root.registerGCPair(pair);\n    }\n\n    return {\n      opInfos: changes.map(({ from, to, value }) => {\n        return {\n          type: 'edit',\n          from,\n          to,\n          value,\n          path: root.createPath(this.getParentCreatedAt()),\n        } as OpInfo;\n      }),\n      reverseOp,\n    };\n  }\n\n  /**\n   * `identityReverse` builds the reverse of an identity-preserving edit, or\n   * -- when both of its span sets came out empty -- an ordinary no-op edit\n   * anchored at the text's head.\n   *\n   * A reverse with no spans has nothing to revive and nothing to re-remove,\n   * but it still has to exist: dropping it would leave the undo stack one\n   * entry short of the redo stack, so a later redo would replay the wrong\n   * entry. It cannot be kept in identity form either -- the converter writes\n   * a restore mode only with spans, so it would go out as a positional edit\n   * of its stale range -- so it degrades to the same shape an edit that\n   * removed and inserted nothing reverses to.\n   */\n  private identityReverse(\n    restoreSpans: Array<RestoreSpan<CRDTTextValue>> | undefined,\n    restoreMode: RestoreMode,\n    retombstoneSpans: Array<RestoreSpan<CRDTTextValue>> | undefined,\n  ): EditOperation {\n    if (!restoreSpans?.length && !retombstoneSpans?.length) {\n      return this.emptyReverse();\n    }\n    return EditOperation.create(\n      this.getParentCreatedAt(),\n      this.fromPos,\n      this.toPos,\n      '',\n      new Map(),\n      undefined,\n      true,\n      restoreSpans,\n      restoreMode,\n      retombstoneSpans,\n    );\n  }\n\n  /**\n   * `emptyReverse` returns an empty undo edit at the head of this op's text:\n   * the reverse of an edit that changes nothing.\n   */\n  private emptyReverse(): EditOperation {\n    return EditOperation.create(\n      this.getParentCreatedAt(),\n      headPos(),\n      headPos(),\n      '',\n      new Map(),\n      undefined,\n      true,\n    );\n  }\n\n  private toReverseOperation(\n    removedValues: Array<CRDTTextValue>,\n    fromPos: RGATreeSplitPos,\n    removedSpans: Array<RestoreSpan<CRDTTextValue>>,\n  ): Operation {\n    if (removedSpans.length || this.content?.length) {\n      // Reverse any edit by identity: revive what it removed (restoreSpans)\n      // and re-remove what it inserted (retombstoneSpans), both by original\n      // identity, rather than copy-reinserting or position-deleting. A fresh\n      // copy-reinserted node sorts ahead of an as-yet-unrevived neighbour and\n      // corrupts order across chained undo/redo; a position-based delete of\n      // the inserted range reconciles onto the wrong node under a concurrent\n      // remote edit (e.g. two clients concurrently insert and delete, then\n      // undo). Identity addressing avoids both.\n      let insertedSpans: Array<RestoreSpan<CRDTTextValue>> | undefined;\n      if (this.content?.length) {\n        const value = CRDTTextValue.create(this.content);\n        // Carry the attributes the edit applied, stamped with the same ticket\n        // `CRDTText.edit` used. The undo only re-tombstones this span, so its\n        // value is unread there -- but the redo flips `restoreMode` and the\n        // span becomes the content to restore. A replica that purged the node\n        // rebuilds it from this value alone, so an empty attribute map here\n        // makes it diverge from a replica that still un-tombstones the\n        // original.\n        for (const [key, attrValue] of this.getAttributes()) {\n          value.setAttr(key, attrValue, this.getExecutedAt());\n        }\n        insertedSpans = [\n          {\n            createdAt: this.getExecutedAt(),\n            start: 0,\n            end: value.length,\n            value,\n          },\n        ];\n      }\n      return EditOperation.create(\n        this.getParentCreatedAt(),\n        fromPos,\n        fromPos,\n        '',\n        new Map(),\n        undefined,\n        true,\n        removedSpans.length ? removedSpans : undefined,\n        'restore',\n        insertedSpans,\n      );\n    }\n\n    const content = removedValues?.length\n      ? removedValues.map((v) => v.getContent()).join('')\n      : '';\n\n    let attrs: Array<[string, string]> | undefined;\n    if (removedValues.length === 1) {\n      const attrsObj = removedValues[0].getAttributes();\n      if (attrsObj) {\n        attrs = Array.from(Object.entries(attrsObj as any));\n      }\n    }\n\n    return EditOperation.create(\n      this.getParentCreatedAt(),\n      fromPos,\n      RGATreeSplitPos.of(\n        fromPos.getID(),\n        fromPos.getRelativeOffset() + (this.content?.length ?? 0),\n      ),\n      content,\n      attrs ? new Map(attrs) : new Map(),\n      undefined,\n      true,\n    );\n  }\n\n  /**\n   * `normalizePos` normalizes the position of the edit operation.\n   */\n  public normalizePos<A extends Indexable>(root: CRDTRoot): [number, number] {\n    const parentObject = root.findByCreatedAt(this.getParentCreatedAt());\n\n    if (!parentObject) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `fail to find ${this.getParentCreatedAt()}`,\n      );\n    }\n\n    if (!(parentObject instanceof CRDTText)) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `only Text can normalize edit`,\n      );\n    }\n\n    const text = parentObject as CRDTText<A>;\n    const rangeFrom = text.normalizePos(this.fromPos).getRelativeOffset();\n    const rangeTo = text.normalizePos(this.toPos).getRelativeOffset();\n\n    return [rangeFrom, rangeTo];\n  }\n\n  /**\n   * `reconcileOperation` reconciles the position when remote edits occur.\n   *\n   * @param remoteFrom - Start position of the remote edit\n   * @param remoteTo - End position of the remote edit\n   * @param contentLen - Length of content inserted by the remote edit\n   *\n   * @example\n   * // Text: \"0123456789\"\n   * // Undo range: [4, 6) (trying to restore \"45\")\n   * // Remote edit: delete [2, 4) and insert \"XY\"\n   * // Result: Undo range adjusted to [2, 4) to restore at correct position\n   */\n  public reconcileOperation(\n    remoteFrom: number,\n    remoteTo: number,\n    contentLen: number,\n  ): void {\n    if (!this.isUndoOp) {\n      return;\n    }\n    // NOTE: restoreSpans ops address content by identity (createdAt +\n    // offset), so `fromPos`/`toPos` are never used to locate the restored\n    // range itself. But `fromPos` is also passed as the fallback anchor for\n    // when every related piece has been GC'd (see findRestoreAnchor), so it\n    // still needs to track concurrent remote edits like any other undo\n    // position — only the identity payload (`restoreSpans`) must stay\n    // untouched, which the reconciliation below never reads.\n    if (remoteFrom > remoteTo) {\n      return;\n    }\n\n    const remoteRangeLen = remoteTo - remoteFrom;\n    const localFrom = this.fromPos.getRelativeOffset();\n    const localTo = this.toPos.getRelativeOffset();\n\n    // Helper function to apply new position offsets\n    const apply = (na: number, nb: number) => {\n      this.fromPos = RGATreeSplitPos.of(this.fromPos.getID(), Math.max(0, na));\n      this.toPos = RGATreeSplitPos.of(this.toPos.getID(), Math.max(0, nb));\n    };\n\n    // Case 1: Remote edit is to the left of undo range\n    // [--remote--]  [--undo--]\n    if (remoteTo <= localFrom) {\n      apply(\n        localFrom - remoteRangeLen + contentLen,\n        localTo - remoteRangeLen + contentLen,\n      );\n      return;\n    }\n\n    // Case 2: Remote edit is to the right of undo range\n    // [--undo--]  [--remote--]\n    if (localTo <= remoteFrom) {\n      return;\n    }\n\n    // Case 3: Undo range is contained within remote range\n    // [-------remote-------]\n    //      [--undo--]\n    if (\n      remoteFrom <= localFrom &&\n      localTo <= remoteTo &&\n      remoteFrom !== remoteTo\n    ) {\n      apply(remoteFrom, remoteFrom);\n      return;\n    }\n\n    // Case 4: Remote range is contained within undo range\n    //      [--remote--]\n    // [---------undo---------]\n    if (\n      localFrom <= remoteFrom &&\n      remoteTo <= localTo &&\n      localFrom !== localTo\n    ) {\n      apply(localFrom, localTo - remoteRangeLen + contentLen);\n      return;\n    }\n\n    // Case 5: Remote range overlaps the start of undo range\n    // [---remote---]\n    //      [---undo---]\n    if (remoteFrom < localFrom && localFrom < remoteTo && remoteTo < localTo) {\n      apply(remoteFrom, remoteFrom + (localTo - remoteTo));\n      return;\n    }\n\n    // Case 6: Remote range overlaps the end of undo range\n    //      [---remote---]\n    // [---undo---]\n    if (localFrom < remoteFrom && remoteFrom < localTo && localTo < remoteTo) {\n      apply(localFrom, remoteFrom);\n      return;\n    }\n  }\n\n  /**\n   * `getEffectedCreatedAt` returns the creation time of the effected element.\n   */\n  public getEffectedCreatedAt(): TimeTicket {\n    return this.getParentCreatedAt();\n  }\n\n  /**\n   * `toTestString` returns a string containing the meta data.\n   */\n  public toTestString(): string {\n    const parent = this.getParentCreatedAt().toTestString();\n    const fromPos = this.fromPos.toTestString();\n    const toPos = this.toPos.toTestString();\n    const content = this.content;\n    return `${parent}.EDIT(${fromPos},${toPos},${content})`;\n  }\n\n  /**\n   * `getFromPos` returns the start point of the editing range.\n   */\n  public getFromPos(): RGATreeSplitPos {\n    return this.fromPos;\n  }\n\n  /**\n   * `getToPos` returns the end point of the editing range.\n   */\n  public getToPos(): RGATreeSplitPos {\n    return this.toPos;\n  }\n\n  /**\n   * `getContent` returns the content of Edit.\n   */\n  public getContent(): string {\n    return this.content;\n  }\n\n  /**\n   * `getAttributes` returns the attributes of this Edit.\n   */\n  public getAttributes(): Map<string, string> {\n    return this.attributes || new Map();\n  }\n\n  /**\n   * `getRestoreSpans` returns the identity-preserving restore payload, if\n   * this is a restore/retombstone operation.\n   */\n  public getRestoreSpans(): Array<RestoreSpan<CRDTTextValue>> | undefined {\n    return this.restoreSpans;\n  }\n\n  /**\n   * `getRestoreMode` returns the identity-preserving mode of this Edit.\n   */\n  public getRestoreMode(): RestoreMode | undefined {\n    return this.restoreMode;\n  }\n\n  /**\n   * `getRetombstoneSpans` returns the companion span set (content the reversed\n   * edit inserted) for an identity-preserving reverse op, if any.\n   */\n  public getRetombstoneSpans(): Array<RestoreSpan<CRDTTextValue>> | undefined {\n    return this.retombstoneSpans;\n  }\n}\n\n/**\n * `headPos` returns the position at the start of the head node, the one node\n * of a text GC never purges.\n */\nfunction headPos(): RGATreeSplitPos {\n  return RGATreeSplitPos.of(InitialRGATreeSplitNodeID, 0);\n}\n","/*\n * Copyright 2020 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TimeTicket } from '@yorkie-js/sdk/src/document/time/ticket';\nimport { VersionVector } from '@yorkie-js/sdk/src/document/time/version_vector';\nimport { CRDTRoot } from '@yorkie-js/sdk/src/document/crdt/root';\nimport { GCPair } from '@yorkie-js/sdk/src/document/crdt/gc';\nimport { RGATreeSplitPos } from '@yorkie-js/sdk/src/document/crdt/rga_tree_split';\nimport { CRDTText } from '@yorkie-js/sdk/src/document/crdt/text';\nimport {\n  Operation,\n  OpInfo,\n  ExecutionResult,\n  OpSource,\n} from '@yorkie-js/sdk/src/document/operation/operation';\nimport { Indexable } from '../document';\nimport { Code, YorkieError } from '@yorkie-js/sdk/src/util/error';\nimport { addDataSizes } from '@yorkie-js/sdk/src/util/resource';\n\n/**\n *  `StyleOperation` is an operation applies the style of the given range to Text.\n */\nexport class StyleOperation extends Operation {\n  private fromPos: RGATreeSplitPos;\n  private toPos: RGATreeSplitPos;\n  private attributes: Map<string, string>;\n  private attributesToRemove: Array<string>;\n\n  constructor(\n    parentCreatedAt: TimeTicket,\n    fromPos: RGATreeSplitPos,\n    toPos: RGATreeSplitPos,\n    attributes: Map<string, string>,\n    attributesToRemove: Array<string>,\n    executedAt?: TimeTicket,\n  ) {\n    super(parentCreatedAt, executedAt);\n    this.fromPos = fromPos;\n    this.toPos = toPos;\n    this.attributes = attributes;\n    this.attributesToRemove = attributesToRemove;\n  }\n\n  /**\n   * `create` creates a new instance of StyleOperation.\n   */\n  public static create(\n    parentCreatedAt: TimeTicket,\n    fromPos: RGATreeSplitPos,\n    toPos: RGATreeSplitPos,\n    attributes: Map<string, string>,\n    executedAt?: TimeTicket,\n  ): StyleOperation {\n    return new StyleOperation(\n      parentCreatedAt,\n      fromPos,\n      toPos,\n      attributes,\n      [],\n      executedAt,\n    );\n  }\n\n  /**\n   * `createRemoveStyleOperation` creates a new instance of StyleOperation for style removal.\n   */\n  public static createRemoveStyleOperation(\n    parentCreatedAt: TimeTicket,\n    fromPos: RGATreeSplitPos,\n    toPos: RGATreeSplitPos,\n    attributesToRemove: Array<string>,\n    executedAt?: TimeTicket,\n  ): StyleOperation {\n    return new StyleOperation(\n      parentCreatedAt,\n      fromPos,\n      toPos,\n      new Map(),\n      attributesToRemove,\n      executedAt,\n    );\n  }\n\n  /**\n   * `execute` executes this operation on the given `CRDTRoot`.\n   */\n  public execute<A extends Indexable>(\n    root: CRDTRoot,\n    _: OpSource,\n    versionVector?: VersionVector,\n  ): ExecutionResult {\n    const parentObject = root.findByCreatedAt(this.getParentCreatedAt());\n    if (!parentObject) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `fail to find ${this.getParentCreatedAt()}`,\n      );\n    }\n    if (!(parentObject instanceof CRDTText)) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `fail to execute, only Text can execute edit`,\n      );\n    }\n    const text = parentObject as CRDTText<A>;\n\n    const allPairs: Array<GCPair> = [];\n    const allChanges: Array<{ from: number; to: number; value?: unknown }> = [];\n    const allSize = { live: { data: 0, meta: 0 }, gc: { data: 0, meta: 0 } };\n    const reversePrevAttributes = new Map<string, string>();\n    const reverseAttrsToRemove: Array<string> = [];\n\n    // 01. Handle attributesToRemove (remove style attributes)\n    if (this.attributesToRemove.length > 0) {\n      const [pairs, size, changes, prevAttributes] = text.removeStyle(\n        [this.fromPos, this.toPos],\n        this.attributesToRemove,\n        this.getExecutedAt(),\n        versionVector,\n      );\n\n      addDataSizes(allSize.live, size.live);\n      addDataSizes(allSize.gc, size.gc);\n      allPairs.push(...pairs);\n      allChanges.push(...changes);\n\n      // Capture previous values for reverse op\n      for (const [key, value] of prevAttributes) {\n        reversePrevAttributes.set(key, value);\n      }\n    }\n\n    // 02. Handle attributes (set style attributes)\n    if (this.attributes.size > 0) {\n      const [pairs, size, changes, prevAttributes, attrsToRemove] =\n        text.setStyle(\n          [this.fromPos, this.toPos],\n          Object.fromEntries(this.attributes),\n          this.getExecutedAt(),\n          versionVector,\n        );\n\n      addDataSizes(allSize.live, size.live);\n      addDataSizes(allSize.gc, size.gc);\n      allPairs.push(...pairs);\n      allChanges.push(...changes);\n\n      // Capture previous values and new keys for reverse op\n      for (const [key, value] of prevAttributes) {\n        reversePrevAttributes.set(key, value);\n      }\n      reverseAttrsToRemove.push(...attrsToRemove);\n    }\n\n    root.acc(allSize.live);\n    root.accGC(allSize.gc);\n    for (const pair of allPairs) {\n      root.registerGCPair(pair);\n    }\n\n    // Build reverse operation\n    let reverseOp: Operation | undefined;\n    if (reversePrevAttributes.size > 0 || reverseAttrsToRemove.length > 0) {\n      if (reversePrevAttributes.size > 0 && reverseAttrsToRemove.length > 0) {\n        reverseOp = new StyleOperation(\n          this.getParentCreatedAt(),\n          this.fromPos,\n          this.toPos,\n          reversePrevAttributes,\n          reverseAttrsToRemove,\n        );\n      } else if (reverseAttrsToRemove.length > 0) {\n        reverseOp = StyleOperation.createRemoveStyleOperation(\n          this.getParentCreatedAt(),\n          this.fromPos,\n          this.toPos,\n          reverseAttrsToRemove,\n        );\n      } else {\n        reverseOp = StyleOperation.create(\n          this.getParentCreatedAt(),\n          this.fromPos,\n          this.toPos,\n          reversePrevAttributes,\n        );\n      }\n    }\n\n    return {\n      opInfos: allChanges.map(({ from, to, value }) => {\n        return {\n          type: 'style',\n          from,\n          to,\n          value,\n          path: root.createPath(this.getParentCreatedAt()),\n        } as OpInfo;\n      }),\n      reverseOp,\n    };\n  }\n\n  /**\n   * `getEffectedCreatedAt` returns the creation time of the effected element.\n   */\n  public getEffectedCreatedAt(): TimeTicket {\n    return this.getParentCreatedAt();\n  }\n\n  /**\n   * `toTestString` returns a string containing the meta data.\n   */\n  public toTestString(): string {\n    const parent = this.getParentCreatedAt().toTestString();\n    const fromPos = this.fromPos.toTestString();\n    const toPos = this.toPos.toTestString();\n    const attributes = this.attributes;\n    return `${parent}.STYL(${fromPos},${toPos},${JSON.stringify(attributes)})`;\n  }\n\n  /**\n   * `getFromPos` returns the start point of the editing range.\n   */\n  public getFromPos(): RGATreeSplitPos {\n    return this.fromPos;\n  }\n\n  /**\n   * `getToPos` returns the end point of the editing range.\n   */\n  public getToPos(): RGATreeSplitPos {\n    return this.toPos;\n  }\n\n  /**\n   * `getAttributes` returns the attributes of this operation.\n   */\n  public getAttributes(): Map<string, string> {\n    return this.attributes;\n  }\n\n  /**\n   * `getAttributesToRemove` returns the attributes to remove.\n   */\n  public getAttributesToRemove(): Array<string> {\n    return this.attributesToRemove;\n  }\n}\n","/*\n * Copyright 2023 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ActorID } from '@yorkie-js/sdk/src/document/time/actor_id';\nimport { TimeTicket } from '@yorkie-js/sdk/src/document/time/ticket';\nimport { VersionVector } from '@yorkie-js/sdk/src/document/time/version_vector';\nimport { CRDTRoot } from '@yorkie-js/sdk/src/document/crdt/root';\nimport {\n  CRDTTree,\n  CRDTTreeNode,\n  CRDTTreeNodeID,\n  CRDTTreePos,\n  TreeRestoreSpan,\n  replaceTreeNodeID,\n  toXML,\n} from '@yorkie-js/sdk/src/document/crdt/tree';\nimport { RestoreMode } from '@yorkie-js/sdk/src/document/operation/edit_operation';\nimport {\n  Operation,\n  OpInfo,\n  ExecutionResult,\n  OpSource,\n} from '@yorkie-js/sdk/src/document/operation/operation';\nimport { Code, YorkieError } from '@yorkie-js/sdk/src/util/error';\nimport { traverseAll } from '@yorkie-js/sdk/src/util/index_tree';\nimport { addDataSizes } from '@yorkie-js/sdk/src/util/resource';\n\n/**\n * `cloneAndDropPreTombstoned` deep-copies `node` and drops descendants\n * whose ID is in `preTombstoned` — i.e., descendants that were already\n * tombstoned before this edit ran. Those descendants represent the\n * user's earlier delete intent and must not be resurrected by undoing\n * this edit.\n *\n * For nodes kept in the clone, `removedAt` is cleared so the redo\n * re-inserts them as live.\n */\nfunction cloneAndDropPreTombstoned(\n  node: CRDTTreeNode,\n  preTombstoned: Set<string>,\n): CRDTTreeNode {\n  const clone = node.deepcopy();\n  filterChildren(clone, preTombstoned);\n  // Post-order: clear tombstone on every survivor and recompute size from\n  // its (already-resized) children. The deepcopy carried the original\n  // node's size; after `filterChildren` dropped descendants, that size\n  // is stale and must be recomputed bottom-up. Element nodes derive size\n  // from children's `paddedSize`; text nodes use their value length.\n  traverseAll(clone, (n) => {\n    n.removedAt = undefined;\n    // NOTE: The attribute tombstones are deliberately kept. They record real\n    // `removeStyle` intent, and the reinserted node has to keep rejecting the\n    // same stale styles the original rejects. They survive the wire intact\n    // (`fromRHT` decodes `isRemoved` verbatim, and `clearTombstones` clears\n    // only the node tombstone), so sender and receiver hold the same RHT, and\n    // `CRDTTree.edit` books each one into gc on both sides.\n    if (n.isText) {\n      n.visibleSize = n.value.length;\n      n.totalSize = n.value.length;\n      return;\n    }\n    let size = 0;\n    for (const child of n._children) size += child.paddedSize();\n    n.visibleSize = size;\n    n.totalSize = size;\n  });\n  return clone;\n}\n\n/**\n * `filterChildren` walks `node._children` and drops descendants whose\n * IDs are in `preTombstoned`. Used by `cloneAndDropPreTombstoned` to\n * keep only nodes that this edit actually transitioned from visible\n * to tombstoned.\n */\nfunction filterChildren(node: CRDTTreeNode, preTombstoned: Set<string>): void {\n  const all = node._children;\n  if (!all) return;\n  const kept: Array<CRDTTreeNode> = [];\n  for (const child of all) {\n    if (preTombstoned.has(child.id.toIDString())) {\n      // Already tombstoned before this edit — drop from reverseOp.\n      continue;\n    }\n    filterChildren(child, preTombstoned);\n    kept.push(child);\n  }\n  node._children = kept;\n}\n\n/**\n * `mergedAwayIDs` returns the ids of the elements a merge removed, innermost\n * first -- the order a split re-creating them issues tickets in, since it\n * splits from the innermost level out.\n *\n * `mergedNodes` is the merge-boundary set `CRDTTree.edit` reports, NOT every\n * node the edit tombstoned: the split reversing the merge re-creates exactly\n * one element per boundary it crossed, so anything else in the removed set --\n * a whole element deleted inside the range, a cascade-deleted descendant, a\n * node already tombstoned -- would shift the positional pairing with the\n * split's tickets and bind an unrelated element to one of them.\n */\nfunction mergedAwayIDs(\n  mergedNodes: Array<CRDTTreeNode>,\n): Array<CRDTTreeNodeID> {\n  const depth = (node: CRDTTreeNode) => {\n    let d = 0;\n    for (let n = node.parent; n; n = n.parent) d++;\n    return d;\n  };\n  return mergedNodes\n    .filter((node) => !node.isText)\n    .map((node) => ({ node, depth: depth(node) }))\n    .sort((a, b) => b.depth - a.depth)\n    .map(({ node }) => node.id);\n}\n\n/**\n * `TreeEditOperation` is an operation representing Tree editing.\n */\nexport class TreeEditOperation extends Operation {\n  private fromPos: CRDTTreePos;\n  private toPos: CRDTTreePos;\n  private contents: Array<CRDTTreeNode> | undefined;\n  private splitLevel: number;\n  private isUndoOp?: boolean;\n  private fromIdx?: number;\n  private toIdx?: number;\n  private lastFromIdx?: number;\n  private lastToIdx?: number;\n  private insertedContentSize?: number;\n  /**\n   * `executedRanges` is what the identity-preserving restore/retombstone path\n   * changed the last time it ran: one `[from, to, insertedSize]` per node that\n   * left or came back, in the order it did, each measured against the tree as\n   * it stood at that moment. Only that path sets it; every other edit reports\n   * its single range through `normalizePos`/`getContentSize`.\n   */\n  private executedRanges?: Array<[number, number, number]>;\n\n  /**\n   * `splitSize` is the visible-index size the boundaries THIS execution's\n   * forward `edit` opened: two tokens per element it split, zero for a split\n   * with no visible effect. A split creates boundaries rather than inserting\n   * nodes, so `insertedContentSize` above never sees them; reconciliation\n   * needs both, and reads their sum through `getContentSize`.\n   */\n  private splitSize?: number;\n  /**\n   * `redoSplitLevel` is set on boundary-deletion undo ops that were generated\n   * to reverse a split. When this op executes (as undo), `toReverseOperation`\n   * uses this value to generate a proper split op for redo, rather than\n   * re-inserting the raw tombstoned boundary nodes as content.\n   */\n  private redoSplitLevel?: number;\n  // Identity-preserving Tree undo/redo (mirrors EditOperation): a reverse op\n  // carries the deleted nodes' spans and a mode. `restore` revives\n  // `restoreSpans` and re-removes `retombstoneSpans`; `retombstone` (the redo)\n  // does the opposite. Nodes are revived/removed by original identity, never\n  // copy-reinserted, so concurrent undos converge. Empty/undefined for\n  // ordinary edits and for the copy-reinsert reverse of merge/split edits.\n  /**\n   * `splitTickets` carries the tickets the originating replica issued for the\n   * nodes an element split creates, in issue order. A replica applying the\n   * operation consumes them instead of reconstructing them, so neither side\n   * depends on the other's allocation staying in step. Empty for a change\n   * written before the field existed, which falls back to the reconstruction.\n   */\n  private splitTickets: Array<TimeTicket> = [];\n  /**\n   * `replacedIDs` is set on a split that re-creates elements a merge removed\n   * -- the redo of a split, or the undo of a merge. It names those elements,\n   * innermost first, in the order the split mints their replacements. The\n   * replacements get new ids (see `setSplitTickets`), so whoever runs this\n   * split re-points every recorded operation at them. Local to the replica\n   * that recorded it; never encoded.\n   */\n  private replacedIDs: Array<CRDTTreeNodeID> = [];\n  /**\n   * `consumedSplitTickets` is how many of `splitTickets` the current\n   * execution has handed to the tree — fewer than `splitLevel` when the\n   * split loop ran out of ancestors, and zero before it starts. Doubles as\n   * the index reported to `splitTicketConsumedHandler`.\n   */\n  private consumedSplitTickets = 0;\n  /**\n   * `splitRecreatedIDs` is what the last execution's split re-created, as\n   * `[removed element, its replacement]` pairs. See `getSplitRecreatedIDs`.\n   */\n  private splitRecreatedIDs: Array<[CRDTTreeNodeID, CRDTTreeNodeID]> = [];\n  /**\n   * `splitTicketConsumedHandler` is notified as each recorded split ticket is\n   * handed to the tree, with its index in `splitTickets`. A split stops as\n   * soon as it runs out of ancestors, so how many elements it really mints is\n   * only knowable from inside the split — and re-pointing anything at a\n   * ticket the split never consumed would leave it naming a node that was\n   * never created. Undo/redo registers a handler here so the re-pointing\n   * happens per minted element, while the operations that follow in the same\n   * change are still waiting to run. Local to the replica that registered it;\n   * never encoded, and never copied to another operation.\n   */\n  private splitTicketConsumedHandler?: (index: number) => void;\n  private restoreSpans?: Array<TreeRestoreSpan>;\n  private restoreMode?: RestoreMode;\n  private retombstoneSpans?: Array<TreeRestoreSpan>;\n\n  constructor(\n    parentCreatedAt: TimeTicket,\n    fromPos: CRDTTreePos,\n    toPos: CRDTTreePos,\n    contents: Array<CRDTTreeNode> | undefined,\n    splitLevel: number,\n    executedAt: TimeTicket,\n    isUndoOp?: boolean,\n    fromIdx?: number,\n    toIdx?: number,\n    restoreSpans?: Array<TreeRestoreSpan>,\n    restoreMode?: RestoreMode,\n    retombstoneSpans?: Array<TreeRestoreSpan>,\n  ) {\n    super(parentCreatedAt, executedAt);\n    this.fromPos = fromPos;\n    this.toPos = toPos;\n    this.contents = contents;\n    this.splitLevel = splitLevel;\n    this.isUndoOp = isUndoOp;\n    this.fromIdx = fromIdx;\n    this.toIdx = toIdx;\n    this.restoreSpans = restoreSpans;\n    this.restoreMode = restoreMode;\n    this.retombstoneSpans = retombstoneSpans;\n  }\n\n  /**\n   * `create` creates a new instance of EditOperation.\n   */\n  public static create(\n    parentCreatedAt: TimeTicket,\n    fromPos: CRDTTreePos,\n    toPos: CRDTTreePos,\n    contents: Array<CRDTTreeNode> | undefined,\n    splitLevel: number,\n    executedAt: TimeTicket,\n    isUndoOp?: boolean,\n    fromIdx?: number,\n    toIdx?: number,\n    restoreSpans?: Array<TreeRestoreSpan>,\n    restoreMode?: RestoreMode,\n    retombstoneSpans?: Array<TreeRestoreSpan>,\n  ): TreeEditOperation {\n    return new TreeEditOperation(\n      parentCreatedAt,\n      fromPos,\n      toPos,\n      contents,\n      splitLevel,\n      executedAt,\n      isUndoOp,\n      fromIdx,\n      toIdx,\n      restoreSpans,\n      restoreMode,\n      retombstoneSpans,\n    );\n  }\n\n  /**\n   * `reissueContentIDs` gives every node this operation inserts a fresh\n   * identity.\n   *\n   * A reverse operation that reverses a deletion by re-inserting a copy of the\n   * removed nodes carries their original ids, so executing it would put two\n   * nodes under one id — the ambiguity that makes a position anchored there\n   * resolve differently on different replicas. Undo already re-identifies a\n   * restored value elsewhere: `ArraySet` and `Add` both take the fresh ticket\n   * in `executeUndoRedo`. This is the tree's counterpart, called from the same\n   * place so the ids come from the change the undo creates.\n   *\n   * A restore-mode reverse is left alone: it revives nodes under their\n   * original identity by design, which is what makes concurrent undos of one\n   * deletion converge rather than duplicate.\n   *\n   * Returns the `[old, new]` pairs it minted, so the caller can re-point\n   * whatever else was recorded against the old ids — the same reconciliation\n   * a split's re-created elements need (`getReplacedIDs`).\n   */\n  public reissueContentIDs(\n    issueTimeTicket: () => TimeTicket,\n  ): Array<[CRDTTreeNodeID, CRDTTreeNodeID]> {\n    const reissued: Array<[CRDTTreeNodeID, CRDTTreeNodeID]> = [];\n    if (!this.contents || this.restoreMode) {\n      return reissued;\n    }\n\n    // The tickets taken here start at `executedAt.delimiter + 1` and run one\n    // per node, while `execute` simulates the tickets an element split\n    // consumes starting at `executedAt.delimiter + contents.length + 1`. The\n    // two ranges overlap as soon as content has descendants, so this only\n    // holds while no content-bearing reverse splits — which is every reverse\n    // `toReverseOperation` builds, all of them `splitLevel: 0`.\n    if (this.splitLevel !== 0) {\n      throw new YorkieError(\n        Code.ErrRefused,\n        `cannot reissue content ids on a splitting edit`,\n      );\n    }\n\n    for (const content of this.contents) {\n      traverseAll(content, (node) => {\n        const prev = node.id;\n        node.id = CRDTTreeNodeID.of(issueTimeTicket(), 0);\n        reissued.push([prev, node.id]);\n        // A fresh identity has to be fresh in every field that names a node.\n        // The copy came from `deepcopy`, which carries the split chain and the\n        // merge lineage of the node it copied: left in place they would splice\n        // this node into a chain it never belonged to, and `purge` relinking\n        // that chain would unlink the real tombstone from it.\n        node.insPrevID = undefined;\n        node.insNextID = undefined;\n        node.mergedFrom = undefined;\n        node.mergedAt = undefined;\n        node.mergedInto = undefined;\n      });\n    }\n\n    return reissued;\n  }\n\n  /**\n   * `getSplitTickets` returns the tickets issued for the nodes an element\n   * split created, in issue order.\n   */\n  public getSplitTickets(): Array<TimeTicket> {\n    return this.splitTickets;\n  }\n\n  /**\n   * `getReplacedIDs` returns the ids of the elements this split re-creates,\n   * innermost first. Empty unless it is the redo of a split or the undo of a\n   * merge.\n   */\n  public getReplacedIDs(): Array<CRDTTreeNodeID> {\n    return this.replacedIDs;\n  }\n\n  /**\n   * `reconcileNodeID` points this operation at `curr` wherever it named\n   * `prev`: its range, and the restore spans an identity-preserving undo\n   * carries. See `TreeStyleOperation.reconcileNodeID`.\n   */\n  public reconcileNodeID(prev: CRDTTreeNodeID, curr: CRDTTreeNodeID): void {\n    this.fromPos = this.fromPos.replaceNodeID(prev, curr);\n    this.toPos = this.toPos.replaceNodeID(prev, curr);\n\n    const replace = (id?: CRDTTreeNodeID) =>\n      id && replaceTreeNodeID(id, prev, curr);\n    // `span.id` too, not just the anchors: it is the identity `restore` and\n    // `retombstone` look the node up by, and the one they RECREATE the node\n    // under when garbage collection has purged it (`CRDTTree.restore`). Left\n    // naming the element the split has just re-minted under a new ticket, an\n    // identity restore would revive nothing and recreate a duplicate under\n    // the stale id.\n    const reconcileSpans = (spans?: Array<TreeRestoreSpan>) =>\n      spans?.map((span) => ({\n        ...span,\n        id: replace(span.id)!,\n        parentID: replace(span.parentID),\n        leftSiblingID: replace(span.leftSiblingID),\n        rightSiblingID: replace(span.rightSiblingID),\n      }));\n    this.restoreSpans = reconcileSpans(this.restoreSpans);\n    this.retombstoneSpans = reconcileSpans(this.retombstoneSpans);\n    this.replacedIDs = this.replacedIDs.map((id) => replace(id)!);\n  }\n\n  /**\n   * `onSplitTicketConsumed` registers `handler`, called with the index of\n   * each recorded split ticket as the split takes it — i.e. once per element\n   * the split really mints, and never for a level it stopped short of. The\n   * operation is executed twice per undo/redo (clone, then root), so the\n   * handler is called twice for the same index and has to be idempotent.\n   * Pass nothing to clear it once both executions are done: the handler\n   * closes over the undo/redo entry, which the operation must not keep alive\n   * -- and must never re-point again from a later execution. See\n   * `splitTicketConsumedHandler`.\n   */\n  public onSplitTicketConsumed(handler?: (index: number) => void): void {\n    this.splitTicketConsumedHandler = handler;\n  }\n\n  /**\n   * `getSplitRecreatedIDs` returns the `[removed element, its replacement]`\n   * pairs the LAST execution's split produced — the elements a merge had\n   * taken away and that this split re-created under new ids. Reset at every\n   * execution, so after a change has been applied it describes the root pass.\n   *\n   * Unlike `replacedIDs` this is derived from the tree the split ran on, not\n   * from the reverse op this replica recorded, so it is available for a PEER's\n   * split too: the operation on the wire says which tickets the split minted,\n   * never what they replace.\n   */\n  public getSplitRecreatedIDs(): Array<[CRDTTreeNodeID, CRDTTreeNodeID]> {\n    return this.splitRecreatedIDs;\n  }\n\n  /**\n   * `getConsumedSplitTicketCount` returns how many of the recorded split\n   * tickets the LAST execution handed to the tree — how many elements that\n   * execution really minted. Fewer than `splitLevel` when the split loop ran\n   * out of ancestors, and zero when this operation never ran.\n   *\n   * The count is reset at the start of every execution, so after an undo/redo\n   * has applied the change it describes the root pass, not the clone pass\n   * that ran first. The two can disagree: the clone and the root are separate\n   * trees, and a remote change applied between the clone's last sync and now\n   * can leave the split with a different number of ancestors to cross. The\n   * handler above fires per execution and cannot tell which; anything that\n   * must reflect what the ROOT tree actually minted has to check this after\n   * the fact.\n   */\n  public getConsumedSplitTicketCount(): number {\n    return this.consumedSplitTickets;\n  }\n\n  /**\n   * `setSplitTickets` records the tickets issued for the nodes an element\n   * split created. The originating replica calls this after executing the\n   * edit, so every other replica can use them instead of reconstructing them.\n   */\n  public setSplitTickets(tickets: Array<TimeTicket>): void {\n    this.splitTickets = tickets;\n  }\n\n  /**\n   * `setActor` sets the given actor to this operation and to the tickets its\n   * split issued.\n   *\n   * A document edited before `client.attach` runs under the initial actor, and\n   * `Document.setActor` re-stamps every pending local change once the real\n   * actor arrives. The base implementation rewrites `executedAt` alone, which\n   * would leave the split tickets recorded at edit time naming the old actor:\n   * they are issued from the change's own context, so every reader -- the\n   * decoder's `fromSplitTickets`, and any replica reasoning about which change\n   * minted a node -- expects them to carry the change's actor. Re-stamp them\n   * here. The lamport and the delimiters are untouched, so their order (and\n   * the identities the split mints) is unchanged.\n   */\n  public setActor(actorID: ActorID): void {\n    super.setActor(actorID);\n    this.splitTickets = this.splitTickets.map((ticket) =>\n      ticket.setActor(actorID),\n    );\n  }\n\n  /**\n   * `getRestoreSpans` returns the identity-preserving restore payload, if any.\n   */\n  public getRestoreSpans(): Array<TreeRestoreSpan> | undefined {\n    return this.restoreSpans;\n  }\n\n  /**\n   * `getRestoreMode` returns the identity-preserving mode of this op.\n   */\n  public getRestoreMode(): RestoreMode | undefined {\n    return this.restoreMode;\n  }\n\n  /**\n   * `getRetombstoneSpans` returns the companion span set, if any.\n   */\n  public getRetombstoneSpans(): Array<TreeRestoreSpan> | undefined {\n    return this.retombstoneSpans;\n  }\n\n  /**\n   * `execute` executes this operation on the given `CRDTRoot`.\n   */\n  public execute(\n    root: CRDTRoot,\n    _: OpSource,\n    versionVector?: VersionVector,\n  ): ExecutionResult {\n    const parentObject = root.findByCreatedAt(this.getParentCreatedAt());\n    if (!parentObject) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `fail to find ${this.getParentCreatedAt()}`,\n      );\n    }\n    if (!(parentObject instanceof CRDTTree)) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `fail to execute, only Tree can execute edit`,\n      );\n    }\n    const editedAt = this.getExecutedAt();\n    const tree = parentObject as CRDTTree;\n\n    // Identity-preserving restore/retombstone path (mirrors EditOperation).\n    // `restoreMode` selects direction; an undo ('restore') revives\n    // restoreSpans and re-removes retombstoneSpans, the redo ('retombstone')\n    // does the opposite. Nodes move by identity, never copy-reinsert.\n    if (this.restoreSpans || this.retombstoneSpans) {\n      const isRetombstone = this.restoreMode === 'retombstone';\n      const toRestore =\n        (isRetombstone ? this.retombstoneSpans : this.restoreSpans) ?? [];\n      const toRetombstone =\n        (isRetombstone ? this.restoreSpans : this.retombstoneSpans) ?? [];\n\n      const diff = { data: 0, meta: 0 };\n      // 1. Re-remove (retombstone) by identity. Isolating a straddling piece\n      // splits it (live-split overhead accounted to `diff`).\n      const [retombstonePairs, retombstoneDiff, retombstoneChanges] =\n        tree.retombstone(toRetombstone, editedAt);\n      addDataSizes(diff, retombstoneDiff);\n      for (const pair of retombstonePairs) {\n        root.registerGCPair(pair);\n      }\n      // 2. Revive (restore) by identity. Isolating a range out of a straddling\n      // piece can split off born-removed remainders as pending GC pairs;\n      // register them FIRST so a split-born un-tombstoned target is walked\n      // gc->live correctly by the unregister below (mirrors the Text path).\n      // Un-tombstoned nodes move gc->live via unregisterGCPair (after removedAt\n      // is cleared, which restore does); recreated nodes are brand new, so add\n      // their size to live, plus any live-split overhead.\n      const [\n        untombstoned,\n        recreated,\n        restorePairs,\n        restoreDiff,\n        restoreChanges,\n      ] = tree.restore(toRestore, editedAt);\n      for (const pair of restorePairs) {\n        root.registerGCPair(pair);\n      }\n      for (const node of untombstoned) {\n        root.unregisterGCPair({ parent: tree, child: node });\n      }\n      addDataSizes(diff, restoreDiff);\n      for (const node of recreated) {\n        addDataSizes(diff, node.getDataSize());\n      }\n      root.acc(diff);\n\n      // One opInfo per node that left or came back, in the order it did, so\n      // an editor can apply them one after another like any other edit. It is\n      // empty when nothing visible changed (e.g. everything stays under a\n      // removed ancestor); the change still propagates, since\n      // Document.executeUndoRedo gates on executed operations, not opInfos.\n      const path = root.createPath(this.getParentCreatedAt());\n      const edits = [...retombstoneChanges, ...restoreChanges];\n      const opInfos: Array<OpInfo> = edits.map(\n        ({ change: { from, to, value, fromPath, toPath } }) =>\n          ({\n            type: 'tree-edit',\n            path,\n            from,\n            to,\n            value,\n            splitLevel: 0,\n            fromPath,\n            toPath,\n          }) as OpInfo,\n      );\n      // Where this execution actually landed, for the undo stack. The stored\n      // `fromIdx`/`toIdx` describe the forward edit this op reverses and never\n      // move (the nodes are addressed by identity), so they would shift the\n      // pending entries by a range this op never touched.\n      this.executedRanges = edits.map(({ change, insertedSize }) => [\n        change.from,\n        change.to,\n        insertedSize,\n      ]);\n\n      return {\n        opInfos,\n        // Reverse keeps the same span sets and flips the direction.\n        reverseOp: TreeEditOperation.create(\n          this.getParentCreatedAt(),\n          this.fromPos,\n          this.toPos,\n          undefined,\n          0,\n          undefined!, // executedAt assigned at (re)undo time\n          true,\n          this.fromIdx,\n          this.toIdx,\n          this.restoreSpans,\n          isRetombstone ? 'restore' : 'retombstone',\n          this.retombstoneSpans,\n        ),\n      };\n    }\n\n    // For undo ops: convert stored integer indices to CRDTTreePos. These are\n    // the document's own indexes, not the caller's: reconciliation and the\n    // edits since can move one inside a surrogate pair, so they resolve\n    // without the pair check that guards caller-supplied indexes.\n    if (\n      this.isUndoOp &&\n      this.fromIdx !== undefined &&\n      this.toIdx !== undefined\n    ) {\n      this.fromPos = tree.findPosUnchecked(this.fromIdx);\n      if (this.fromIdx === this.toIdx) {\n        this.toPos = this.fromPos;\n      } else {\n        this.toPos = tree.findPosUnchecked(this.toIdx);\n      }\n    }\n\n    // The tree drops content that reuses an ID it already holds, and reports\n    // the size of what it accepted. The reverse operation and the undo stack\n    // both read that size rather than the content this operation carried: a\n    // range covering content the tree refused would delete a neighbour on\n    // redo. The delimiter simulation below stays on the original count, since\n    // the server simulates it the same way.\n    const [\n      changes,\n      pairs,\n      diff,\n      removedNodes,\n      preEditFromIdx,\n      mergeLevel,\n      preTombstoned,\n      removedSpans,\n      insertedSpans,\n      insertedContentSize,\n      splitSize,\n      mergedNodes,\n      splitRecreatedIDs,\n      strandedNodes,\n    ] = tree.edit(\n      [this.fromPos, this.toPos],\n      this.contents?.map((content) => content.deepcopy()),\n      this.splitLevel,\n      editedAt,\n      /**\n       * TODO(sejongk): When splitting element nodes, a new nodeID is assigned with a different timeTicket.\n       * In the same change context, the timeTickets share the same lamport and actorID but have different delimiters,\n       * incremented by one for each.\n       * Therefore, it is possible to simulate later timeTickets using `editedAt` and the length of `contents`.\n       * This logic might be unclear; consider refactoring for multi-level concurrent editing in the Tree implementation.\n       */\n      // Splitting an element creates nodes that need tickets. The originating\n      // replica issued them and carries them here, so this hands them back in\n      // the same order. A change written before the field existed carries\n      // none, and falls back to reconstructing them from `executedAt` and the\n      // number of top-level contents — a reconstruction that is wrong as soon\n      // as content has descendants, since each of those consumed a ticket too.\n      (() => {\n        let delimiter = editedAt.getDelimiter();\n        if (this.contents !== undefined) {\n          delimiter += this.contents.length;\n        }\n        this.consumedSplitTickets = 0;\n        const issueTimeTicket = () => {\n          if (this.consumedSplitTickets < this.splitTickets.length) {\n            const index = this.consumedSplitTickets++;\n            // Reported as the ticket leaves, not after the split returns:\n            // the caller re-points the rest of the change at the element\n            // this ticket identifies, and that has to be in place before\n            // those operations run. `splitElement` always inserts the node\n            // it clones under the ticket it took, so a consumed ticket is\n            // an element that exists.\n            this.splitTicketConsumedHandler?.(index);\n            return this.splitTickets[index];\n          }\n\n          return TimeTicket.of(\n            editedAt.getLamport(),\n            ++delimiter,\n            editedAt.getActorID(),\n          );\n        };\n        return issueTimeTicket;\n      })(),\n      versionVector,\n    );\n\n    // Store pre-edit from index (computed inside edit() after text-node splits\n    // but before deletions). Derive toIdx from removed nodes' visible sizes.\n    this.lastFromIdx = preEditFromIdx;\n    // For toIdx: fromIdx + total visible tokens of removed nodes\n    // The merge's stranded subtrees are part of the consumed range too: they\n    // are not in `removedNodes`, yet tombstoning them drained their size out\n    // of the removed source they stay under.\n    const removedSize = [...removedNodes, ...strandedNodes].reduce(\n      (sum, node) => sum + node.paddedSize(),\n      0,\n    );\n    this.lastToIdx = preEditFromIdx + removedSize;\n    this.insertedContentSize = insertedContentSize;\n    this.splitSize = splitSize;\n    this.splitRecreatedIDs = splitRecreatedIDs;\n\n    // Create reverse op for undo\n    let reverseOp: Operation | undefined;\n    const isPureSplit =\n      this.splitLevel > 0 &&\n      !this.contents?.length &&\n      removedNodes.length === 0;\n    if (this.splitLevel === 0) {\n      reverseOp = this.toReverseOperation(\n        tree,\n        removedNodes,\n        preEditFromIdx,\n        preTombstoned,\n        mergeLevel,\n        removedSpans,\n        insertedSpans,\n        mergedNodes,\n      );\n    } else if (isPureSplit) {\n      reverseOp = this.toSplitReverseOperation(tree, preEditFromIdx, splitSize);\n    }\n\n    root.acc(diff);\n\n    for (const pair of pairs) {\n      root.registerGCPair(pair);\n    }\n\n    return {\n      opInfos: changes.map(\n        ({ from, to, value, splitLevel, fromPath, toPath }) => {\n          return {\n            type: 'tree-edit',\n            path: root.createPath(this.getParentCreatedAt()),\n            from,\n            to,\n            value,\n            splitLevel,\n            fromPath,\n            toPath,\n          } as OpInfo;\n        },\n      ),\n      reverseOp,\n    };\n  }\n\n  /**\n   * `toReverseOperation` creates the reverse operation for undo.\n   *\n   * The reverse op stores both CRDTTreePos (for initial use) and integer\n   * indices (for reconciliation adjustment when remote edits arrive).\n   * At undo execution time, the integer indices take precedence and are\n   * converted to CRDTTreePos via tree.findPosUnchecked().\n   *\n   * @param tree - The CRDTTree after the edit has been applied\n   * @param removedNodes - Nodes that were removed by this edit\n   * @param preEditFromIdx - The from index captured BEFORE the edit\n   */\n  private toReverseOperation(\n    tree: CRDTTree,\n    removedNodes: Array<CRDTTreeNode>,\n    preEditFromIdx: number,\n    preTombstoned: Set<string>,\n    mergeLevel?: number,\n    removedSpans?: Array<TreeRestoreSpan>,\n    insertedSpans?: Array<TreeRestoreSpan>,\n    mergedNodes: Array<CRDTTreeNode> = [],\n  ): Operation | undefined {\n    // Identity-preserving reverse: reverse an edit by reviving the nodes it\n    // removed (restoreSpans) AND re-removing the nodes it inserted\n    // (retombstoneSpans), both by ORIGINAL identity instead of copy-reinsert.\n    // edit() only fills these spans when the edit was merge/split-free\n    // (spansComplete), so this never fires for the merge/split cases below; the\n    // redoSplitLevel guard keeps a split's own boundary-deletion undo on the\n    // re-split path (its deletion would otherwise fill removedSpans here).\n    const hasRemoved = !!removedSpans && removedSpans.length > 0;\n    const hasInserted = !!insertedSpans && insertedSpans.length > 0;\n    if (this.redoSplitLevel === undefined && (hasRemoved || hasInserted)) {\n      return TreeEditOperation.create(\n        this.getParentCreatedAt(),\n        this.fromPos,\n        this.toPos,\n        undefined,\n        0,\n        undefined!, // executedAt assigned at undo time\n        true,\n        preEditFromIdx,\n        preEditFromIdx,\n        removedSpans ?? [],\n        'restore',\n        insertedSpans ?? [],\n      );\n    }\n\n    // Special case: this op is a boundary-deletion that was the undo of a\n    // split. Its redo should re-split, not re-insert the tombstoned boundary\n    // nodes as raw content.\n    if (this.redoSplitLevel !== undefined && this.redoSplitLevel > 0) {\n      // After the boundary deletion has been applied, the merged position is\n      // preEditFromIdx. We re-split there.\n      const splitRedoFromPos = tree.findPosUnchecked(preEditFromIdx);\n      const splitRedoOp = TreeEditOperation.create(\n        this.getParentCreatedAt(),\n        splitRedoFromPos,\n        splitRedoFromPos,\n        undefined, // no inserted content\n        this.redoSplitLevel,\n        undefined!, // executedAt assigned at redo time\n        true, // isUndoOp (treated as undo/redo op)\n        preEditFromIdx,\n        preEditFromIdx,\n      );\n      splitRedoOp.replacedIDs = mergedAwayIDs(mergedNodes);\n      return splitRedoOp;\n    }\n\n    // Cross-boundary merge: the reverse is a split, not content re-insertion.\n    // A merge deletes element boundaries (e.g., </p><p>), moving children\n    // into the target. The undo re-creates those boundaries via split.\n    if (mergeLevel && mergeLevel > 0) {\n      const splitFromPos = tree.findPosUnchecked(preEditFromIdx);\n      const splitUndoOp = TreeEditOperation.create(\n        this.getParentCreatedAt(),\n        splitFromPos,\n        splitFromPos,\n        undefined, // no inserted content — split creates boundaries\n        mergeLevel, // splitLevel = number of merged boundaries\n        undefined!, // executedAt assigned at undo time\n        true, // isUndoOp\n        preEditFromIdx,\n        preEditFromIdx,\n      );\n      splitUndoOp.replacedIDs = mergedAwayIDs(mergedNodes);\n      return splitUndoOp;\n    }\n\n    // Inserted content size in tree index tokens, measured before the edit:\n    // these nodes are now in the tree, and one inserted under a concurrently\n    // removed parent is tombstoned on the way in, which shrinks the size read\n    // back here. The guard below relies on that pre-edit size to recognize an\n    // edit that had no effect. What it counts is the content the tree\n    // accepted, not the content this operation carried — a reverse range\n    // covering a dropped copy would delete a neighbour on redo.\n    const insertedContentSize = this.insertedContentSize ?? 0;\n\n    // Guard: if the positions exceed the post-edit tree size,\n    // the edit was a no-op (e.g., concurrent parent deletion where inserted\n    // content was tombstoned). Skip reverse op.\n    const maxNeededIdx = preEditFromIdx + insertedContentSize;\n    if (maxNeededIdx > tree.getSize()) {\n      return undefined;\n    }\n\n    // Filter to top-level removed nodes (whose parent is NOT also removed).\n    // Also exclude nodes that were already tombstoned before this edit ran:\n    // those represent the user's earlier delete intent and must not be\n    // resurrected by a parent-level undo, even at the root of `topLevelRemoved`.\n    const topLevelRemoved = removedNodes.filter(\n      (node) =>\n        !preTombstoned.has(node.id.toIDString()) &&\n        (!node.parent || !removedNodes.includes(node.parent)),\n    );\n\n    // Deep copy for re-insertion on undo, but drop descendants that\n    // were already tombstoned before this edit. Without this filter,\n    // undoing a parent delete would resurrect the user's earlier\n    // independent deletes — causing accumulation across undo/redo\n    // cycles in nested-edit scenarios.\n    const reverseContents =\n      topLevelRemoved.length > 0\n        ? topLevelRemoved.map((n) =>\n            cloneAndDropPreTombstoned(n, preTombstoned),\n          )\n        : undefined;\n\n    // Compute CRDTTreePos for the reverse range on the post-edit tree with\n    // the pre-edit from index. The reverse is built for remote changes too,\n    // from indexes on this replica's tree, so it skips the pair check:\n    // refusing one would refuse a remote change the caller never controlled.\n    const reverseFromPos = tree.findPosUnchecked(preEditFromIdx);\n\n    let reverseToPos: CRDTTreePos;\n    if (insertedContentSize > 0) {\n      reverseToPos = tree.findPosUnchecked(\n        preEditFromIdx + insertedContentSize,\n      );\n    } else {\n      reverseToPos = reverseFromPos;\n    }\n\n    // Integer indices for the reverse op (used by reconciliation)\n    const reverseFromIdx = preEditFromIdx;\n    const reverseToIdx = preEditFromIdx + insertedContentSize;\n\n    return TreeEditOperation.create(\n      this.getParentCreatedAt(),\n      reverseFromPos,\n      reverseToPos,\n      reverseContents,\n      0, // splitLevel always 0\n      undefined!, // executedAt set during undo\n      true, // isUndoOp\n      reverseFromIdx,\n      reverseToIdx,\n    );\n  }\n\n  /**\n   * `toSplitReverseOperation` creates the reverse operation for a split edit.\n   *\n   * A split creates element boundaries (close + open tags). The reverse\n   * is a boundary deletion: a splitLevel=0 edit that removes those tokens,\n   * merging the split elements back together.\n   *\n   * `boundarySize` is how many tokens the split actually opened, not\n   * 2 * splitLevel, which is only how many it asked for: the split loop stops\n   * when it runs out of ancestors to split, and a level the tree has no room\n   * for would size this range over tokens the split never opened. The undo\n   * then deletes live content past its own boundary and merges elements the\n   * split never separated.\n   *\n   * @param tree - The CRDTTree after the split has been applied\n   * @param preEditFromIdx - The from index captured BEFORE the split\n   * @param boundarySize - The visible-index size the split opened\n   */\n  private toSplitReverseOperation(\n    tree: CRDTTree,\n    preEditFromIdx: number,\n    boundarySize: number,\n  ): Operation | undefined {\n    // The split had no visible effect — a concurrent deletion tombstoned the\n    // element it split, so its boundary occupies no visible index, or there\n    // was no ancestor left to split at all. Nothing for an undo to merge.\n    if (boundarySize === 0) {\n      return undefined;\n    }\n\n    const reverseFromIdx = preEditFromIdx;\n    const reverseToIdx = preEditFromIdx + boundarySize;\n\n    // Belt and braces against a range that runs off the end of the tree:\n    // deleting it would take out live content to the right of the boundary.\n    if (reverseToIdx > tree.getSize()) {\n      return undefined;\n    }\n\n    const reverseFromPos = tree.findPosUnchecked(reverseFromIdx);\n    const reverseToPos = tree.findPosUnchecked(reverseToIdx);\n\n    const boundaryDeletionOp = TreeEditOperation.create(\n      this.getParentCreatedAt(),\n      reverseFromPos,\n      reverseToPos,\n      undefined, // no content — this is a deletion\n      0, // splitLevel=0: boundary deletion\n      undefined!, // executedAt assigned at undo time\n      true, // isUndoOp\n      reverseFromIdx,\n      reverseToIdx,\n    );\n    // Tag this op so that its own reverse (the redo) is regenerated as a\n    // proper split rather than a raw node re-insertion.\n    boundaryDeletionOp.redoSplitLevel = this.splitLevel;\n    return boundaryDeletionOp;\n  }\n\n  /**\n   * `normalizePos` returns the visible-index range of this operation.\n   * For undo ops, returns the stored (possibly reconciled) indices.\n   * For forward ops, returns the pre-edit indices captured during execute().\n   */\n  public normalizePos(): [number, number] {\n    if (\n      this.isUndoOp &&\n      this.fromIdx !== undefined &&\n      this.toIdx !== undefined\n    ) {\n      return [this.fromIdx, this.toIdx];\n    }\n\n    if (this.lastFromIdx !== undefined && this.lastToIdx !== undefined) {\n      return [this.lastFromIdx, this.lastToIdx];\n    }\n\n    // Fallback: no indices available\n    return [0, 0];\n  }\n\n  /**\n   * `reconcileOperation` adjusts this undo operation's integer indices\n   * when a remote edit modifies the same tree. Uses the same 6-case\n   * overlap logic as EditOperation.reconcileOperation for Text.\n   */\n  public reconcileOperation(\n    remoteFrom: number,\n    remoteTo: number,\n    contentLen: number,\n  ): void {\n    if (!this.isUndoOp) {\n      return;\n    }\n    // Identity-addressed restore/retombstone ops locate their nodes by\n    // TreeNodeID, not by index, so index reconciliation must not touch them\n    // (mirrors EditOperation for Text).\n    if (this.restoreSpans || this.retombstoneSpans) {\n      return;\n    }\n    if (this.fromIdx === undefined || this.toIdx === undefined) {\n      return;\n    }\n    if (remoteFrom > remoteTo) {\n      return;\n    }\n\n    const remoteRangeLen = remoteTo - remoteFrom;\n    const localFrom = this.fromIdx;\n    const localTo = this.toIdx;\n\n    const apply = (na: number, nb: number) => {\n      this.fromIdx = Math.max(0, na);\n      this.toIdx = Math.max(0, nb);\n    };\n\n    // Case 1: Remote edit is to the left of undo range\n    // [--remote--]  [--undo--]\n    if (remoteTo <= localFrom) {\n      apply(\n        localFrom - remoteRangeLen + contentLen,\n        localTo - remoteRangeLen + contentLen,\n      );\n      return;\n    }\n\n    // Case 2: Remote edit is to the right of undo range\n    // [--undo--]  [--remote--]\n    if (localTo <= remoteFrom) {\n      return;\n    }\n\n    // Case 3: Undo range is contained within remote range\n    // [-------remote-------]\n    //      [--undo--]\n    if (\n      remoteFrom <= localFrom &&\n      localTo <= remoteTo &&\n      remoteFrom !== remoteTo\n    ) {\n      apply(remoteFrom, remoteFrom);\n      return;\n    }\n\n    // Case 4: Remote range is contained within undo range\n    //      [--remote--]\n    // [---------undo---------]\n    if (\n      localFrom <= remoteFrom &&\n      remoteTo <= localTo &&\n      localFrom !== localTo\n    ) {\n      apply(localFrom, localTo - remoteRangeLen + contentLen);\n      return;\n    }\n\n    // Case 5: Remote range overlaps the start of undo range\n    // [---remote---]\n    //      [---undo---]\n    if (remoteFrom < localFrom && localFrom < remoteTo && remoteTo < localTo) {\n      apply(remoteFrom, remoteFrom + (localTo - remoteTo));\n      return;\n    }\n\n    // Case 6: Remote range overlaps the end of undo range\n    //      [---remote---]\n    // [---undo---]\n    if (localFrom < remoteFrom && remoteFrom < localTo && localTo < remoteTo) {\n      apply(localFrom, remoteFrom);\n      return;\n    }\n  }\n\n  /**\n   * `getContentSize` returns the total visible size of this operation's\n   * content (for reconciliation).\n   *\n   * Once the operation has run, this is the size the tree accepted: content\n   * whose ID was already in the tree is dropped, and the undo stack shifts its\n   * stored indices by this size, so counting the dropped copy would move every\n   * index in the stack past content that was never inserted.\n   */\n  public getContentSize(): number {\n    if (this.insertedContentSize !== undefined) {\n      return this.insertedContentSize + (this.splitSize ?? 0);\n    }\n    if (!this.contents) return 0;\n    return this.contents.reduce((sum, node) => sum + node.paddedSize(), 0);\n  }\n\n  /**\n   * `getExecutedRanges` returns the visible ranges this execution replaced,\n   * each with the size it inserted there, in the order they applied — what the\n   * undo stack has to be reconciled against.\n   *\n   * An identity-preserving restore/retombstone reports one entry per node that\n   * came back or left, measured as it happened; every other edit reports its\n   * single normalized range.\n   */\n  public getExecutedRanges(): Array<[number, number, number]> {\n    if (this.executedRanges) {\n      return this.executedRanges;\n    }\n\n    const [from, to] = this.normalizePos();\n    return [[from, to, this.getContentSize()]];\n  }\n\n  /**\n   * `getEffectedCreatedAt` returns the creation time of the effected element.\n   */\n  public getEffectedCreatedAt(): TimeTicket {\n    return this.getParentCreatedAt();\n  }\n\n  /**\n   * `toTestString` returns a string containing the meta data.\n   */\n  public toTestString(): string {\n    const parent = this.getParentCreatedAt().toTestString();\n    const fromPos = `${this.fromPos\n      .getLeftSiblingID()\n      .getCreatedAt()\n      .toTestString()}/${this.fromPos.getLeftSiblingID().getOffset()}`;\n    const toPos = `${this.toPos\n      .getLeftSiblingID()\n      .getCreatedAt()\n      .toTestString()}/${this.toPos.getLeftSiblingID().getOffset()}`;\n    const contents = this.contents || [];\n    return `${parent}.EDIT(${fromPos},${toPos},${contents\n      .map((v) => toXML(v))\n      .join('')})`;\n  }\n\n  /**\n   * `getFromPos` returns the start point of the editing range.\n   */\n  public getFromPos(): CRDTTreePos {\n    return this.fromPos;\n  }\n\n  /**\n   * `getToPos` returns the end point of the editing range.\n   */\n  public getToPos(): CRDTTreePos {\n    return this.toPos;\n  }\n\n  /**\n   * `getContent` returns the content of Edit.\n   */\n  public getContents(): Array<CRDTTreeNode> | undefined {\n    return this.contents;\n  }\n\n  /**\n   * `getSplitLevel` returns the split level of Edit.\n   */\n  public getSplitLevel(): number {\n    return this.splitLevel;\n  }\n}\n","/*\n * Copyright 2020 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n  ActorID,\n  InitialActorID,\n} from '@yorkie-js/sdk/src/document/time/actor_id';\nimport {\n  InitialLamport,\n  TimeTicket,\n} from '@yorkie-js/sdk/src/document/time/ticket';\nimport { InitialVersionVector, VersionVector } from '../time/version_vector';\n\n/**\n * `ChangeID` is for identifying the Change. This is immutable.\n */\nexport class ChangeID {\n  // `clientSeq` is the sequence number of the client that created this change.\n  private clientSeq: number;\n\n  // `serverSeq` is optional and only present for changes stored on the server.\n  private serverSeq?: bigint;\n\n  // `actor` is the creator of this change.\n  private actor: ActorID;\n\n  // `lamport` is the lamport clock of this change. This is used to determine\n  // the order of changes in logical time. It is optional and only present\n  // if the change has operations.\n  private lamport: bigint;\n\n  // `versionVector` is the vector clock of this change. This is used to\n  // determine the relationship is causal or not between changes. It is optional\n  // and only present if the change has operations.\n  private versionVector: VersionVector;\n\n  constructor(\n    clientSeq: number,\n    lamport: bigint,\n    actor: ActorID,\n    vector: VersionVector,\n    serverSeq?: bigint,\n  ) {\n    this.clientSeq = clientSeq;\n    this.serverSeq = serverSeq;\n    this.lamport = lamport;\n    this.versionVector = vector;\n    this.actor = actor;\n  }\n\n  /**\n   * `hasClocks` returns true if this ID has logical clocks.\n   */\n  public hasClocks(): boolean {\n    return this.versionVector.size() > 0 && this.lamport != InitialLamport;\n  }\n\n  /**\n   * `of` creates a new instance of ChangeID.\n   */\n  public static of(\n    clientSeq: number,\n    lamport: bigint,\n    actor: ActorID,\n    vector: VersionVector,\n    serverSeq?: bigint,\n  ): ChangeID {\n    return new ChangeID(clientSeq, lamport, actor, vector, serverSeq);\n  }\n\n  /**\n   * `next` creates a next ID of this ID.\n   */\n  public next(excludeClocks = false): ChangeID {\n    if (excludeClocks) {\n      return new ChangeID(\n        this.clientSeq + 1,\n        this.lamport,\n        this.actor,\n        InitialVersionVector,\n        InitialLamport,\n      );\n    }\n\n    const vector = this.versionVector.deepcopy();\n    vector.set(this.actor, this.lamport + 1n);\n\n    return new ChangeID(\n      this.clientSeq + 1,\n      this.lamport + 1n,\n      this.actor,\n      vector,\n    );\n  }\n\n  /**\n   * `syncClocks` syncs logical clocks with the given ID. If the given ID\n   * doesn't have logical clocks, this ID is returned.\n   */\n  public syncClocks(other: ChangeID): ChangeID {\n    if (!other.hasClocks()) {\n      return this;\n    }\n\n    const lamport =\n      other.lamport > this.lamport ? other.lamport + 1n : this.lamport + 1n;\n\n    const maxVersionVector = this.versionVector.max(other.versionVector);\n    const newID = new ChangeID(\n      this.clientSeq,\n      lamport,\n      this.actor,\n      maxVersionVector,\n    );\n    newID.versionVector.set(this.actor, lamport);\n    return newID;\n  }\n\n  /**\n   * `syncLamport` advances the lamport clock against the given ID without\n   * merging its version vector into the receiver's. It is the counterpart\n   * of `syncClocks` for attachments that have opted out of GC participation\n   * (see docs/design/disable-gc-on-attach.md in the server repo): the\n   * receiver does not need other actors' entries in its VV because it\n   * never produces or consumes tombstones, and dropping them keeps each\n   * subsequent local Change's VV at O(1) instead of O(num_actors).\n   * Lamport must still advance so that TimeTickets produced locally\n   * remain ordered against remote operations.\n   */\n  public syncLamport(other: ChangeID): ChangeID {\n    if (!other.hasClocks()) {\n      return this;\n    }\n\n    const lamport =\n      other.lamport > this.lamport ? other.lamport + 1n : this.lamport + 1n;\n\n    const vector = this.versionVector.deepcopy();\n    vector.set(this.actor, lamport);\n    return new ChangeID(this.clientSeq, lamport, this.actor, vector);\n  }\n\n  /**\n   * `setClocks` sets the given clocks to this ID. This is used when the snapshot\n   * is given from the server.\n   */\n  public setClocks(otherLamport: bigint, vector: VersionVector): ChangeID {\n    const lamport =\n      otherLamport > this.lamport ? otherLamport + 1n : this.lamport + 1n;\n\n    const maxVersionVector = this.versionVector.max(vector);\n    maxVersionVector.set(this.actor, lamport);\n\n    return ChangeID.of(this.clientSeq, lamport, this.actor, maxVersionVector);\n  }\n\n  /**\n   * `createTimeTicket` creates a ticket of the given delimiter.\n   */\n  public createTimeTicket(delimiter: number): TimeTicket {\n    return TimeTicket.of(this.lamport, delimiter, this.actor);\n  }\n\n  /**\n   * `setActor` sets the given actor.\n   */\n  public setActor(actorID: ActorID): ChangeID {\n    return new ChangeID(\n      this.clientSeq,\n      this.lamport,\n      actorID,\n      this.versionVector,\n      this.serverSeq,\n    );\n  }\n\n  /**\n   * `setLamport` sets the given lamport clock.\n   */\n  public setLamport(lamport: bigint): ChangeID {\n    return new ChangeID(\n      this.clientSeq,\n      lamport,\n      this.actor,\n      this.versionVector,\n      this.serverSeq,\n    );\n  }\n\n  /**\n   * `setClientSeq` sets the given client sequence, leaving the logical clocks\n   * alone. The counter and the clocks are independent positions: the counter\n   * names this client's changes to the server, while the clocks order\n   * operations against other actors.\n   */\n  public setClientSeq(clientSeq: number): ChangeID {\n    return new ChangeID(\n      clientSeq,\n      this.lamport,\n      this.actor,\n      this.versionVector,\n      this.serverSeq,\n    );\n  }\n\n  /**\n   * `setVersionVector` sets the given version vector.\n   */\n  public setVersionVector(versionVector: VersionVector): ChangeID {\n    return new ChangeID(\n      this.clientSeq,\n      this.lamport,\n      this.actor,\n      versionVector,\n      this.serverSeq,\n    );\n  }\n\n  /**\n   * `getClientSeq` returns the client sequence of this ID.\n   */\n  public getClientSeq(): number {\n    return this.clientSeq;\n  }\n\n  /**\n   * `getServerSeq` returns the server sequence of this ID.\n   */\n  public getServerSeq(): string {\n    if (this.serverSeq) {\n      return this.serverSeq.toString();\n    }\n    return '';\n  }\n\n  /**\n   * `getLamport` returns the lamport clock of this ID.\n   */\n  public getLamport(): bigint {\n    return this.lamport;\n  }\n\n  /**\n   * `getLamportAsString` returns the lamport clock of this ID as a string.\n   */\n  public getLamportAsString(): string {\n    return this.lamport.toString();\n  }\n\n  /**\n   * `getActorID` returns the actor of this ID.\n   */\n  public getActorID(): string {\n    return this.actor;\n  }\n\n  /**\n   * `getVersionVector` returns the version vector of this ID.\n   */\n  public getVersionVector(): VersionVector {\n    return this.versionVector;\n  }\n\n  /**\n   * `toTestString` returns a string containing the meta data of this ID.\n   */\n  public toTestString(): string {\n    return `${this.lamport.toString()}:${this.actor.slice(-2)}:${\n      this.clientSeq\n    }`;\n  }\n}\n\n/**\n * `InitialChangeID` represents the initial state ID. Usually this is used to\n * represent a state where nothing has been edited.\n */\nexport const InitialChangeID = new ChangeID(\n  0,\n  0n,\n  InitialActorID,\n  InitialVersionVector,\n);\n","/*\n * Copyright 2020 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ActorID } from '@yorkie-js/sdk/src/document/time/actor_id';\nimport {\n  OpSource,\n  Operation,\n  OpInfo,\n} from '@yorkie-js/sdk/src/document/operation/operation';\nimport { CRDTRoot } from '@yorkie-js/sdk/src/document/crdt/root';\nimport { ChangeID } from '@yorkie-js/sdk/src/document/change/change_id';\nimport { Indexable } from '@yorkie-js/sdk/src/document/document';\nimport { converter } from '@yorkie-js/sdk/src/api/converter';\nimport { HistoryOperation } from '@yorkie-js/sdk/src/document/history';\nimport {\n  PresenceChange,\n  PresenceChangeType,\n} from '@yorkie-js/sdk/src/document/presence/change';\nimport { deepcopy } from '@yorkie-js/sdk/src/util/object';\nimport { ChangeApplyError } from '@yorkie-js/sdk/src/util/error';\n\n/**\n * `ChangeStruct` represents the structure of Change.\n * This is used to serialize and deserialize Change.\n */\nexport type ChangeStruct<P extends Indexable> = {\n  changeID: string;\n  message?: string;\n  operations?: Array<string>;\n  // A `Patch` serializes its local-only `full` copy alongside the changed\n  // keys, so a pending patch restored from offline persistence can still be\n  // rewritten into the put it stands for.\n  presenceChange?: {\n    type: PresenceChangeType;\n    presence?: P | Partial<P>;\n    full?: P;\n  };\n  // `undoRedo` marks a change an undo or a redo produced. It is serialized\n  // because a queued change outlives this process -- the offline-persistence\n  // layer writes it and replays it after a reload -- and a replay has to reuse\n  // the source the change originally ran under. See `Change.isUndoRedo`.\n  undoRedo?: boolean;\n};\n\n/**\n * `Change` represents a unit of modification in the document.\n */\nexport class Change<P extends Indexable> {\n  private id: ChangeID;\n\n  // `operations` represent a series of user edits.\n  private operations: Array<Operation>;\n\n  // `presenceChange` represents the presenceChange of the user who made the change.\n  private presenceChange?: PresenceChange<P>;\n\n  // `message` is used to save a description of the change.\n  private message?: string;\n\n  // `undoRedo` records that this change was produced by an undo or a redo, so\n  // it ran with `OpSource.UndoRedo`. That source is the only thing\n  // `SetOperation.execute`/`RemoveOperation.execute` consult to skip an\n  // operation whose target now sits under a removed parent, so anything that\n  // replays a queued change -- `Document.applySnapshot`, `reissueActor`, the\n  // persisted-log replay -- has to execute it under that source again or it\n  // runs an operation that never ran.\n  private undoRedo: boolean;\n\n  constructor({\n    id,\n    operations,\n    presenceChange,\n    message,\n    undoRedo,\n  }: {\n    id: ChangeID;\n    operations?: Array<Operation>;\n    presenceChange?: PresenceChange<P>;\n    message?: string;\n    undoRedo?: boolean;\n  }) {\n    this.id = id;\n    this.operations = operations || [];\n    this.presenceChange = presenceChange;\n    this.message = message;\n    this.undoRedo = undoRedo || false;\n  }\n\n  /**\n   * `create` creates a new instance of Change.\n   */\n  public static create<P extends Indexable>({\n    id,\n    operations,\n    presenceChange,\n    message,\n    undoRedo,\n  }: {\n    id: ChangeID;\n    operations?: Array<Operation>;\n    presenceChange?: PresenceChange<P>;\n    message?: string;\n    undoRedo?: boolean;\n  }): Change<P> {\n    return new Change({ id, operations, presenceChange, message, undoRedo });\n  }\n\n  /**\n   * `getID` returns the ID of this change.\n   */\n  public getID(): ChangeID {\n    return this.id;\n  }\n\n  /**\n   * `getMessage` returns the message of this change.\n   */\n  public getMessage(): string | undefined {\n    return this.message;\n  }\n\n  /**\n   * `hasOperations` returns whether this change has operations or not.\n   */\n  public hasOperations(): boolean {\n    return this.operations.length > 0;\n  }\n\n  /**\n   * `getOperations` returns the operations of this change.\n   */\n  public getOperations(): Array<Operation> {\n    return this.operations;\n  }\n\n  /**\n   * `setActor` sets the given actor.\n   */\n  public setActor(actorID: ActorID): void {\n    for (const operation of this.operations) {\n      operation.setActor(actorID);\n    }\n\n    this.id = this.id.setActor(actorID);\n  }\n\n  /**\n   * `isUndoRedo` returns whether an undo or a redo produced this change, which\n   * is to say whether a replay of it has to use `OpSource.UndoRedo`.\n   */\n  public isUndoRedo(): boolean {\n    return this.undoRedo;\n  }\n\n  /**\n   * `markAsUndoRedo` records that an undo or a redo produced this change.\n   */\n  public markAsUndoRedo(): void {\n    this.undoRedo = true;\n  }\n\n  /**\n   * `hasPresenceChange` returns whether this change has presence change or not.\n   */\n  public hasPresenceChange(): boolean {\n    return this.presenceChange !== undefined;\n  }\n\n  /**\n   * `getPresenceChange` returns the presence change of this change.\n   */\n  public getPresenceChange(): PresenceChange<P> | undefined {\n    return this.presenceChange;\n  }\n\n  /**\n   * `setPresenceChange` replaces the presence change of this change. It is how\n   * a pending patch is rewritten into the full put the server asks for when it\n   * has no base to fold the patch into. The presence it resolves to is the\n   * same either way, so the change this document already applied locally\n   * stands.\n   */\n  public setPresenceChange(presenceChange: PresenceChange<P>): void {\n    this.presenceChange = presenceChange;\n  }\n\n  /**\n   * `execute` executes the operations of this change to the given root.\n   */\n  public execute(\n    root: CRDTRoot,\n    presences: Map<ActorID, P>,\n    source: OpSource,\n  ): {\n    operations: Array<Operation>;\n    opInfos: Array<OpInfo>;\n    reverseOps: Array<HistoryOperation<P>>;\n  } {\n    const changeOpInfos: Array<OpInfo> = [];\n    const changeOperations: Array<Operation> = [];\n    const reverseOps: Array<HistoryOperation<P>> = [];\n\n    for (const [opIndex, operation] of this.operations.entries()) {\n      let executionResult;\n      try {\n        executionResult = operation.execute(\n          root,\n          source,\n          this.id.getVersionVector(),\n        );\n      } catch (cause) {\n        // NOTE: only a remote change is named. The wedged-document problem is\n        // specific to the pull path — the checkpoint does not advance past a\n        // change that throws, so the server redelivers it forever — while a\n        // local `update` or an undo/redo reports the failure straight to the\n        // caller that asked for it. Wrapping those would replace the error\n        // code an operation deliberately threw (`ErrInvalidArgument`,\n        // `ErrInvalidType`, ...) with `ErrChangeApplyFailed` for every\n        // consumer of the public API.\n        if (source !== OpSource.Remote) {\n          throw cause;\n        }\n\n        // NOTE: the failing operation is only identifiable here. Name it now\n        // so the document can report which operation of which change is\n        // stuck; the document key is added as the error passes through\n        // `Document`. The name is the operation's type and target element,\n        // never `toTestString()`: that serializer embeds the operation's\n        // payload, i.e. the plaintext document content, and this message\n        // reaches application code and the console.\n        throw new ChangeApplyError({\n          changeID: this.id.toTestString(),\n          opIndex,\n          operation: `${\n            operation.constructor.name\n          } on ${operation.getParentCreatedAt().toTestString()}`,\n          cause,\n        });\n      }\n      // NOTE(hackerwins): If the element was removed while executing undo/redo,\n      // the operation is not executed and executionResult is undefined.\n      if (!executionResult) continue;\n      const { opInfos, reverseOp } = executionResult;\n      changeOpInfos.push(...opInfos);\n      changeOperations.push(operation);\n      // TODO(hackerwins): This condition should be removed after implementing\n      // all reverse operations.\n      if (reverseOp) {\n        reverseOps.unshift(reverseOp);\n      }\n    }\n\n    if (this.presenceChange) {\n      if (this.presenceChange.type === PresenceChangeType.Put) {\n        presences.set(\n          this.id.getActorID(),\n          deepcopy(this.presenceChange.presence),\n        );\n      } else if (this.presenceChange.type === PresenceChangeType.Patch) {\n        // A patch is an upload-side encoding: only the changed keys go on the\n        // wire. A locally minted one carries the whole presence as of that\n        // change in `full`, so there is nothing to fold -- apply that. One\n        // decoded off the wire has no `full` (it never goes on the wire), so\n        // fold its keys onto the presence already held for that actor, which\n        // is what the server would have done before storing it.\n        const actorID = this.id.getActorID();\n        presences.set(\n          actorID,\n          this.presenceChange.full\n            ? deepcopy(this.presenceChange.full)\n            : ({\n                ...(presences.get(actorID) ?? {}),\n                ...deepcopy(this.presenceChange.presence),\n              } as P),\n        );\n      } else {\n        presences.delete(this.id.getActorID());\n      }\n    }\n\n    return { operations: changeOperations, opInfos: changeOpInfos, reverseOps };\n  }\n\n  /**\n   * `toTestString` returns a string containing the meta data of this change.\n   */\n  public toTestString(): string {\n    return `${this.operations\n      .map((operation) => operation.toTestString())\n      .join(',')}`;\n  }\n\n  /**\n   * `toStruct` returns the structure of this change.\n   */\n  public toStruct(): ChangeStruct<P> {\n    return {\n      changeID: converter.bytesToHex(converter.changeIDToBinary(this.getID())),\n      message: this.getMessage(),\n      operations: this.getOperations().map((op) =>\n        converter.bytesToHex(converter.operationToBinary(op)),\n      ),\n      presenceChange: this.getPresenceChange(),\n      // Written only when set, so a change no undo produced serializes exactly\n      // as it did before this field existed.\n      undoRedo: this.undoRedo || undefined,\n    };\n  }\n\n  /**\n   * `fromStruct` creates a instance of Change from the struct.\n   */\n  public static fromStruct<P extends Indexable>(\n    struct: ChangeStruct<P>,\n  ): Change<P> {\n    const { changeID, operations, presenceChange, message, undoRedo } = struct;\n    return Change.create<P>({\n      id: converter.bytesToChangeID(converter.hexToBytes(changeID)),\n      operations: operations?.map((op) => {\n        return converter.bytesToOperation(converter.hexToBytes(op));\n      }),\n      presenceChange: presenceChange as any,\n      message,\n      undoRedo,\n    });\n  }\n}\n","/*\n * Copyright 2020 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Indexable } from '@yorkie-js/sdk/src/document/document';\nimport { Checkpoint } from '@yorkie-js/sdk/src/document/change/checkpoint';\nimport { Change } from '@yorkie-js/sdk/src/document/change/change';\nimport { VersionVector } from '../time/version_vector';\n\n/**\n * `ChangePack` is a unit for delivering changes in a document to the remote.\n *\n */\nexport class ChangePack<P extends Indexable> {\n  /**\n   * `documentKey` is the key of the document.\n   */\n  private documentKey: string;\n\n  /**\n   * `Checkpoint` is used to determine the client received changes.\n   */\n  private checkpoint: Checkpoint;\n  /**\n   * `isRemoved` is a flag that indicates whether the document is removed.\n   */\n  private isRemoved: boolean;\n\n  private changes: Array<Change<P>>;\n\n  /**\n   * `snapshot` is a byte array that encodes the document.\n   */\n  private snapshot?: Uint8Array;\n\n  /**\n   * `versionVector` is the version vector current document\n   */\n  private versionVector?: VersionVector;\n\n  /**\n   * `epoch` is the document's compaction epoch. It is a bidirectional carrier:\n   * server responses set it to the document's current epoch, and an attach/sync\n   * request presents the client's last-known epoch so the server can detect a\n   * stale-epoch mismatch after a force compaction.\n   */\n  private epoch: bigint;\n\n  /**\n   * `capabilities` are the wire features the server advertises on the pack it\n   * returns. It is the negotiation channel for features a peer may not have:\n   * absence means unsupported, so an old server -- which sets nothing -- is\n   * read as supporting none of them.\n   */\n  private capabilities: Array<string>;\n\n  constructor(\n    key: string,\n    checkpoint: Checkpoint,\n    isRemoved: boolean,\n    changes: Array<Change<P>>,\n    versionVector?: VersionVector,\n    snapshot?: Uint8Array,\n    epoch: bigint = 0n,\n    capabilities: Array<string> = [],\n  ) {\n    this.documentKey = key;\n    this.checkpoint = checkpoint;\n    this.isRemoved = isRemoved;\n    this.changes = changes;\n    this.snapshot = snapshot;\n    this.versionVector = versionVector;\n    this.epoch = epoch;\n    this.capabilities = capabilities;\n  }\n  /**\n   * `create` creates a new instance of ChangePack.\n   */\n  public static create<P extends Indexable>(\n    key: string,\n    checkpoint: Checkpoint,\n    isRemoved: boolean,\n    changes: Array<Change<P>>,\n    versionVector?: VersionVector,\n    snapshot?: Uint8Array,\n    epoch: bigint = 0n,\n    capabilities: Array<string> = [],\n  ): ChangePack<P> {\n    return new ChangePack<P>(\n      key,\n      checkpoint,\n      isRemoved,\n      changes,\n      versionVector,\n      snapshot,\n      epoch,\n      capabilities,\n    );\n  }\n\n  /**\n   * `getDocumentKey` returns the document key of this pack.\n   */\n  public getDocumentKey(): string {\n    return this.documentKey;\n  }\n\n  /**\n   * `getCheckpoint` returns the checkpoint of this pack.\n   */\n  public getCheckpoint(): Checkpoint {\n    return this.checkpoint;\n  }\n\n  /**\n   * `getIsRemoved` returns the whether this document is removed.\n   */\n  public getIsRemoved(): boolean {\n    return this.isRemoved;\n  }\n\n  /**\n   * `getChanges` returns the changes of this pack.\n   */\n  public getChanges(): Array<Change<P>> {\n    return this.changes;\n  }\n\n  /**\n   * `hasChanges` returns the whether this pack has changes or not.\n   */\n  public hasChanges(): boolean {\n    return this.changes.length > 0;\n  }\n\n  /**\n   * `getChangeSize` returns the size of changes this pack has.\n   */\n  public getChangeSize(): number {\n    return this.changes.length;\n  }\n\n  /**\n   * `hasSnapshot` returns the whether this pack has a snapshot or not.\n   */\n  public hasSnapshot(): boolean {\n    return !!this.snapshot && !!this.snapshot.length;\n  }\n\n  /**\n   * `getSnapshot` returns the snapshot of this pack.\n   */\n  public getSnapshot(): Uint8Array | undefined {\n    return this.snapshot;\n  }\n\n  /**\n   * `getVersionVector` returns the document's version vector of this pack\n   */\n  public getVersionVector(): VersionVector | undefined {\n    return this.versionVector;\n  }\n\n  /**\n   * `getEpoch` returns the document's compaction epoch of this pack.\n   */\n  public getEpoch(): bigint {\n    return this.epoch;\n  }\n\n  /**\n   * `hasCapability` returns whether this pack advertises the given wire\n   * feature.\n   */\n  public hasCapability(capability: string): boolean {\n    return this.capabilities.includes(capability);\n  }\n}\n","/*\n * Copyright 2020 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * `Checkpoint` is used to determine the changes sent and received by the\n * client. This is immutable.\n *\n **/\nexport class Checkpoint {\n  private serverSeq: bigint;\n  private clientSeq: number;\n\n  constructor(serverSeq: bigint, clientSeq: number) {\n    this.serverSeq = serverSeq;\n    this.clientSeq = clientSeq;\n  }\n\n  /**\n   * `of` creates a new instance of Checkpoint.\n   */\n  public static of(serverSeq: bigint, clientSeq: number): Checkpoint {\n    return new Checkpoint(serverSeq, clientSeq);\n  }\n\n  /**\n   * `increaseClientSeq` creates a new instance with increased client sequence.\n   */\n  public increaseClientSeq(inc: number): Checkpoint {\n    if (inc === 0) {\n      return this;\n    }\n\n    return new Checkpoint(this.serverSeq, this.clientSeq + inc);\n  }\n\n  /**\n   * `forward` creates a new instance with the given checkpoint if it is\n   * greater than the values of internal properties.\n   */\n  public forward(other: Checkpoint): Checkpoint {\n    if (this.equals(other)) {\n      return this;\n    }\n\n    const serverSeq =\n      this.serverSeq > other.serverSeq ? this.serverSeq : other.serverSeq;\n    const clientSeq = Math.max(this.clientSeq, other.clientSeq);\n    return Checkpoint.of(serverSeq, clientSeq);\n  }\n\n  /**\n   * `getServerSeqAsString` returns the server seq of this checkpoint as a\n   * string.\n   */\n  public getServerSeqAsString(): string {\n    return this.serverSeq.toString();\n  }\n\n  /**\n   * `getClientSeq` returns the client seq of this checkpoint.\n   */\n  public getClientSeq(): number {\n    return this.clientSeq;\n  }\n\n  /**\n   * `getServerSeq` returns the server seq of this checkpoint.\n   */\n  public getServerSeq(): bigint {\n    return this.serverSeq;\n  }\n\n  /**\n   * `equals` returns whether the given checkpoint is equal to this checkpoint\n   * or not.\n   */\n  public equals(other: Checkpoint): boolean {\n    return (\n      this.clientSeq === other.clientSeq && this.serverSeq == other.serverSeq\n    );\n  }\n\n  /**\n   * `toTestString` returns a string containing the meta data of this\n   * checkpoint.\n   */\n  public toTestString(): string {\n    return `serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`;\n  }\n}\n\n/**\n * `InitialCheckpoint` is the initial value of the checkpoint.\n */\nexport const InitialCheckpoint = new Checkpoint(0n, 0);\n","/*\n * Copyright 2026 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n  CRDTContainer,\n  CRDTElement,\n} from '@yorkie-js/sdk/src/document/crdt/element';\nimport { CRDTTree } from '@yorkie-js/sdk/src/document/crdt/tree';\n\n/**\n * `dropSplitLinksInElement` strips the split-sibling links from every tree\n * reachable from `elem`.\n *\n * A Set/Add/SetByIndex payload carries a whole element rather than a position\n * in the document, and the wire format carries insPrevID/insNextID on every\n * tree node it holds. Such a payload is client-supplied and its trees are\n * always freshly created by the editing client, so none of their nodes can be\n * a split product — but the tree follows the links as trusted structural\n * pointers all the same. Drop them, for the same reason\n * `fromTreeNodesWhenEdit` drops them from operation content.\n *\n * Merge stamps (mergedFrom/mergedAt/mergedInto) are left alone: unlike\n * TreeEdit content, an element payload can be a copy of real document state,\n * such as the tree a reverse of Remove restores, and that tree legitimately\n * carries the merges it underwent. See `CRDTTreeNode.dropSplitLinks`.\n *\n * Both ways into the document have to agree: the converter calls this on the\n * element bytes it decodes, and `executeUndoRedo` calls it on the copy a\n * reverse operation captured, which never passes the converter on the replica\n * that runs the undo. Removed members are walked too — they are still\n * registered in nodeMapByID.\n *\n * A Text inside such a payload is deliberately NOT stripped here, even though\n * its `insPrev` links are just as client-supplied. Unlike a tree in an\n * operation's content, a Text payload is routinely a copy of real document\n * state — the Text a reverse of Remove restores — whose split products a later\n * Edit still targets by id, and dropping the links would lose the structure\n * the re-issue and every snapshot depend on. The links are sanitized at the\n * decoder instead: `fromText` resolves each one by exact id against the nodes\n * already decoded and drops any that does not resolve, so no payload can point\n * a node at a link target the encoder never emitted. See `fromText` in\n * api/converter.ts and docs/design/pre-attach-ticket-reissue.md.\n */\nexport function dropSplitLinksInElement(elem: CRDTElement): CRDTElement {\n  if (elem instanceof CRDTTree) {\n    elem.getRoot()?.dropSplitLinks();\n\n    return elem;\n  }\n\n  if (elem instanceof CRDTContainer) {\n    elem.getDescendants((child) => {\n      if (child instanceof CRDTTree) {\n        child.getRoot()?.dropSplitLinks();\n      }\n\n      return false;\n    });\n  }\n\n  return elem;\n}\n","/*\n * Copyright 2026 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst hllPrecision = 14;\nconst hllRegisterCount = 1 << hllPrecision;\n// The largest rho `add` can store: the bits left after the register index,\n// plus one. Anything above it did not come from a HyperLogLog.\nconst maxRegisterValue = 64 - hllPrecision + 1;\n\n// xxhash64 constants\nconst prime64x1 = 0x9e3779b185ebca87n;\nconst prime64x2 = 0xc2b2ae3d27d4eb4fn;\nconst prime64x3 = 0x165667b19e3779f9n;\nconst prime64x4 = 0x85ebca77c2b2ae63n;\nconst prime64x5 = 0x27d4eb2f165667c5n;\nconst mask64 = 0xffffffffffffffffn;\n\n/**\n * `HLL` is a HyperLogLog implementation used for approximate cardinality\n * estimation in Counter dedup mode. It uses xxhash64 hashing (matching the\n * Go server) and precision 14 (16384 registers, ~16KB, ~2% error).\n */\nexport class HLL {\n  private registers: Uint8Array;\n\n  constructor() {\n    this.registers = new Uint8Array(hllRegisterCount);\n  }\n\n  /**\n   * `add` adds a value to the HLL and returns true if the register was updated.\n   */\n  public add(value: string): boolean {\n    const hash = xxhash64(value);\n    const idx = Number(hash >> BigInt(64 - hllPrecision));\n    const remaining =\n      ((hash << BigInt(hllPrecision)) & mask64) |\n      (1n << BigInt(hllPrecision - 1));\n    const rho = countLeadingZeros64(remaining) + 1;\n    if (rho > this.registers[idx]) {\n      this.registers[idx] = rho;\n      return true;\n    }\n    return false;\n  }\n\n  /**\n   * `count` returns the approximate cardinality estimate.\n   */\n  public count(): number {\n    const m = hllRegisterCount;\n    const alpha = 0.7213 / (1.0 + 1.079 / m);\n    let sum = 0;\n    let zeros = 0;\n    for (let i = 0; i < m; i++) {\n      sum += Math.pow(2, -this.registers[i]);\n      if (this.registers[i] === 0) zeros++;\n    }\n    let estimate = (alpha * m * m) / sum;\n    if (estimate <= 2.5 * m && zeros > 0) {\n      estimate = m * Math.log(m / zeros);\n    }\n    return Math.round(estimate);\n  }\n\n  /**\n   * `merge` merges another HLL into this one by taking the max of each register.\n   * This operation is commutative, associative, and idempotent.\n   */\n  public merge(other: HLL): void {\n    for (let i = 0; i < hllRegisterCount; i++) {\n      if (other.registers[i] > this.registers[i]) {\n        this.registers[i] = other.registers[i];\n      }\n    }\n  }\n\n  /**\n   * `toBytes` serializes the HLL registers to a byte array.\n   */\n  public toBytes(): Uint8Array {\n    return new Uint8Array(this.registers);\n  }\n\n  /**\n   * `restore` restores the HLL registers from a byte array, reporting whether\n   * the payload was well-formed. A rejected payload leaves the registers\n   * untouched.\n   *\n   * The payload arrives from a remote peer, so neither its length nor its\n   * contents are ours to trust. A malformed one is rejected without throwing:\n   * throwing tore out of snapshot decode, which has no handler, so one bad\n   * dedup counter stopped every other client from opening the document. But\n   * it is not clamped and applied either -- `count()` over registers the\n   * payload only partly covered, or over bytes no `add` could have written,\n   * is not an approximation of the sender's cardinality but an unrelated\n   * number, and the caller would store it as the counter's value and\n   * re-serialize it to its own peers.\n   */\n  public restore(data: Uint8Array): boolean {\n    if (data.length !== hllRegisterCount) {\n      return false;\n    }\n    for (const register of data) {\n      if (register > maxRegisterValue) {\n        return false;\n      }\n    }\n    this.registers.set(data);\n    return true;\n  }\n}\n\n/**\n * `xxhash64` computes a 64-bit xxHash of the given string with seed 0.\n * This implementation produces identical output to Go's cespare/xxhash/v2.\n */\nfunction xxhash64(input: string): bigint {\n  const buf = new TextEncoder().encode(input);\n  const len = buf.length;\n  let h64: bigint;\n  let offset = 0;\n  const seed = 0n;\n\n  if (len >= 32) {\n    let v1 = (seed + prime64x1 + prime64x2) & mask64;\n    let v2 = (seed + prime64x2) & mask64;\n    let v3 = seed;\n    let v4 = (seed - prime64x1) & mask64;\n\n    while (offset <= len - 32) {\n      v1 = xxRound(v1, readU64LE(buf, offset));\n      offset += 8;\n      v2 = xxRound(v2, readU64LE(buf, offset));\n      offset += 8;\n      v3 = xxRound(v3, readU64LE(buf, offset));\n      offset += 8;\n      v4 = xxRound(v4, readU64LE(buf, offset));\n      offset += 8;\n    }\n\n    h64 =\n      (rotl64(v1, 1n) + rotl64(v2, 7n) + rotl64(v3, 12n) + rotl64(v4, 18n)) &\n      mask64;\n    h64 = xxMergeRound(h64, v1);\n    h64 = xxMergeRound(h64, v2);\n    h64 = xxMergeRound(h64, v3);\n    h64 = xxMergeRound(h64, v4);\n  } else {\n    h64 = (seed + prime64x5) & mask64;\n  }\n\n  h64 = (h64 + BigInt(len)) & mask64;\n\n  while (offset + 8 <= len) {\n    const k1 = xxRound(0n, readU64LE(buf, offset));\n    h64 = (rotl64(h64 ^ k1, 27n) * prime64x1 + prime64x4) & mask64;\n    offset += 8;\n  }\n\n  if (offset + 4 <= len) {\n    h64 = h64 ^ ((readU32LE(buf, offset) * prime64x1) & mask64);\n    h64 = (rotl64(h64, 23n) * prime64x2 + prime64x3) & mask64;\n    offset += 4;\n  }\n\n  while (offset < len) {\n    h64 = h64 ^ ((BigInt(buf[offset]) * prime64x5) & mask64);\n    h64 = (rotl64(h64, 11n) * prime64x1) & mask64;\n    offset++;\n  }\n\n  h64 = ((h64 ^ (h64 >> 33n)) * prime64x2) & mask64;\n  h64 = ((h64 ^ (h64 >> 29n)) * prime64x3) & mask64;\n  h64 = (h64 ^ (h64 >> 32n)) & mask64;\n\n  return h64;\n}\n\n/** `rotl64` rotates a 64-bit value left by r bits. */\nfunction rotl64(x: bigint, r: bigint): bigint {\n  return ((x << r) | (x >> (64n - r))) & mask64;\n}\n\n/** `xxRound` performs a single xxhash64 accumulator round. */\nfunction xxRound(acc: bigint, input: bigint): bigint {\n  acc = (acc + input * prime64x2) & mask64;\n  acc = rotl64(acc, 31n);\n  return (acc * prime64x1) & mask64;\n}\n\n/** `xxMergeRound` merges an accumulator lane into the final hash. */\nfunction xxMergeRound(acc: bigint, val: bigint): bigint {\n  val = xxRound(0n, val);\n  acc = (acc ^ val) & mask64;\n  return (acc * prime64x1 + prime64x4) & mask64;\n}\n\n/** `readU64LE` reads a little-endian 64-bit integer from a byte array. */\nfunction readU64LE(buf: Uint8Array, offset: number): bigint {\n  let val = 0n;\n  for (let i = 7; i >= 0; i--) {\n    val = (val << 8n) | BigInt(buf[offset + i]);\n  }\n  return val;\n}\n\n/** `readU32LE` reads a little-endian 32-bit integer from a byte array. */\nfunction readU32LE(buf: Uint8Array, offset: number): bigint {\n  return (\n    BigInt(buf[offset]) |\n    (BigInt(buf[offset + 1]) << 8n) |\n    (BigInt(buf[offset + 2]) << 16n) |\n    (BigInt(buf[offset + 3]) << 24n)\n  );\n}\n\n/** `countLeadingZeros64` counts the number of leading zero bits in a 64-bit integer. */\nfunction countLeadingZeros64(x: bigint): number {\n  if (x === 0n) return 64;\n  let n = 0;\n  while ((x & (1n << 63n)) === 0n) {\n    n++;\n    x <<= 1n;\n  }\n  return n;\n}\n","/*\n * Copyright 2020 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CRDTElement } from '@yorkie-js/sdk/src/document/crdt/element';\nimport { TimeTicket } from '@yorkie-js/sdk/src/document/time/ticket';\nimport { Code, YorkieError } from '@yorkie-js/sdk/src/util/error';\nimport {\n  Primitive,\n  PrimitiveType,\n} from '@yorkie-js/sdk/src/document/crdt/primitive';\nimport {\n  removeDecimal,\n  bigintFromBytesLE,\n  bigintToBytesLE,\n  bigintToInt32,\n} from '@yorkie-js/sdk/src/util/number';\nimport type * as Devtools from '@yorkie-js/sdk/src/devtools/types';\nimport { DataSize } from '@yorkie-js/sdk/src/util/resource';\nimport { HLL } from '@yorkie-js/sdk/src/document/crdt/hll';\n\nexport enum CounterType {\n  Int,\n  Long,\n  IntDedup,\n}\n\nexport type CounterValue = number | bigint;\n\n/**\n * `CRDTCounter` is a CRDT implementation of a counter. It is used to represent\n * a number that can be incremented or decremented.\n */\nexport class CRDTCounter extends CRDTElement {\n  private valueType: CounterType;\n  private value: CounterValue;\n  private hll?: HLL;\n\n  constructor(\n    valueType: CounterType,\n    value: CounterValue,\n    createdAt: TimeTicket,\n  ) {\n    super(createdAt);\n    this.valueType = valueType;\n    switch (valueType) {\n      case CounterType.IntDedup:\n        this.value = 0;\n        break;\n      case CounterType.Int:\n        if (typeof value === 'number') {\n          if (value > Math.pow(2, 31) - 1 || value < -Math.pow(2, 31)) {\n            this.value = bigintToInt32(BigInt(value));\n          } else {\n            this.value = removeDecimal(value);\n          }\n        } else {\n          this.value = bigintToInt32(value);\n        }\n        break;\n      case CounterType.Long:\n        if (typeof value === 'number') {\n          this.value = BigInt.asIntN(64, BigInt(Math.trunc(value)));\n        } else {\n          this.value = BigInt.asIntN(64, value);\n        }\n        break;\n      default:\n        throw new YorkieError(\n          Code.ErrUnimplemented,\n          `unimplemented type: ${valueType}`,\n        );\n    }\n    if (this.isDedup()) {\n      this.hll ??= new HLL();\n    }\n  }\n\n  /**\n   * `of` creates a new instance of Counter.\n   */\n  public static create(\n    valueType: CounterType,\n    value: CounterValue,\n    createdAt: TimeTicket,\n  ): CRDTCounter {\n    return new CRDTCounter(valueType, value, createdAt);\n  }\n\n  /**\n   * `valueFromBytes` parses the given bytes into value.\n   */\n  public static valueFromBytes(\n    counterType: CounterType,\n    bytes: Uint8Array,\n  ): CounterValue {\n    switch (counterType) {\n      case CounterType.Int:\n      case CounterType.IntDedup:\n        return bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24);\n      case CounterType.Long:\n        return bigintFromBytesLE(bytes);\n      default:\n        throw new YorkieError(\n          Code.ErrUnimplemented,\n          `unimplemented type: ${counterType}`,\n        );\n    }\n  }\n\n  /**\n   * `getDataSize` returns the data usage of this element.\n   */\n  public getDataSize(): DataSize {\n    let data =\n      this.valueType === CounterType.Int ||\n      this.valueType === CounterType.IntDedup\n        ? 4\n        : 8;\n    if (this.isDedup() && this.hll) {\n      data += this.hll.toBytes().length;\n    }\n    return {\n      data,\n      meta: this.getMetaUsage(),\n    };\n  }\n\n  /**\n   * `toJSON` returns the JSON encoding of the value.\n   */\n  public toJSON(): string {\n    return `${this.value}`;\n  }\n\n  /**\n   * `toSortedJSON` returns the sorted JSON encoding of the value.\n   */\n  public toSortedJSON(): string {\n    return this.toJSON();\n  }\n\n  /**\n   * `toJSForTest` returns value with meta data for testing.\n   */\n  public toJSForTest(): Devtools.JSONElement {\n    return {\n      createdAt: this.getCreatedAt().toTestString(),\n      value: this.value,\n      type: 'YORKIE_COUNTER',\n    };\n  }\n\n  /**\n   * `deepcopy` copies itself deeply.\n   */\n  public deepcopy(): CRDTCounter {\n    const clone = CRDTCounter.create(\n      this.valueType,\n      this.value,\n      this.getCreatedAt(),\n    );\n    clone.setRemovedAt(this.getRemovedAt());\n    clone.setMovedAt(this.getMovedAt());\n    if (this.isDedup() && this.hll) {\n      clone.restoreHLL(this.hll.toBytes());\n    }\n    return clone;\n  }\n\n  /**\n   * `getType` returns the type of the value.\n   */\n  public getType(): CounterType {\n    return this.valueType;\n  }\n\n  /**\n   * `getCounterType` returns counter type of given value.\n   */\n  public static getCounterType(value: CounterValue): CounterType | undefined {\n    switch (typeof value) {\n      case 'bigint':\n        return CounterType.Long;\n      case 'number':\n        if (value > Math.pow(2, 31) - 1 || value < -Math.pow(2, 31)) {\n          return CounterType.Long;\n        } else {\n          return CounterType.Int;\n        }\n      default:\n        return;\n    }\n  }\n\n  /**\n   * `isSupport` check if there is a counter type of given value.\n   */\n  public static isSupport(value: CounterValue): boolean {\n    return !!CRDTCounter.getCounterType(value);\n  }\n\n  /**\n   * `isInteger` checks if the num is integer.\n   */\n  public static isInteger(num: number): boolean {\n    return num % 1 === 0;\n  }\n\n  /**\n   * `isNumericType` check numeric type by JSONCounter.\n   */\n  public isNumericType(): boolean {\n    const t = this.valueType;\n    return (\n      t === CounterType.Int ||\n      t === CounterType.Long ||\n      t === CounterType.IntDedup\n    );\n  }\n\n  /**\n   * `getValueType` get counter value type.\n   */\n  public getValueType(): CounterType {\n    return this.valueType;\n  }\n\n  /**\n   * `getValue` get counter value.\n   */\n  public getValue(): CounterValue {\n    return this.value;\n  }\n\n  /**\n   * `toBytes` creates an array representing the value.\n   */\n  public toBytes(): Uint8Array {\n    switch (this.valueType) {\n      case CounterType.Int:\n      case CounterType.IntDedup: {\n        const intVal = this.value as number;\n        return new Uint8Array([\n          intVal & 0xff,\n          (intVal >> 8) & 0xff,\n          (intVal >> 16) & 0xff,\n          (intVal >> 24) & 0xff,\n        ]);\n      }\n      case CounterType.Long: {\n        return bigintToBytesLE(this.value as bigint);\n      }\n      default:\n        throw new YorkieError(\n          Code.ErrUnimplemented,\n          `unimplemented type: ${this.valueType}`,\n        );\n    }\n  }\n\n  /**\n   * `isDedup` returns whether dedup mode is enabled (derived from ValueType).\n   */\n  public isDedup(): boolean {\n    return this.valueType === CounterType.IntDedup;\n  }\n\n  /**\n   * `increaseDedup` increases the counter using HLL-based dedup.\n   * Only updates the value if the actor is new (not seen before).\n   */\n  public increaseDedup(v: Primitive, actor: string): CRDTCounter {\n    if (!this.isDedup() || !this.hll) {\n      return this.increase(v);\n    }\n    if (!this.isNumericType() || !v.isNumericType()) {\n      throw new TypeError(`Unsupported type of value: ${typeof v.getValue()}`);\n    }\n    if (!actor) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        'dedup counter requires actor',\n      );\n    }\n    const val = v.getValue();\n    const isUnit = v.getType() === PrimitiveType.Long ? val === 1n : val === 1;\n    if (!isUnit) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        'dedup counter only supports increment by 1',\n      );\n    }\n    if (this.hll.add(actor)) {\n      this.recomputeValue();\n    }\n    return this;\n  }\n\n  /**\n   * `hllBytes` returns the HLL register bytes, or undefined if not in dedup mode.\n   */\n  public hllBytes(): Uint8Array | undefined {\n    return this.hll?.toBytes();\n  }\n\n  /**\n   * `restoreHLL` restores the HLL state from serialized bytes, returning\n   * whether the bytes were accepted. A rejected payload leaves both the HLL\n   * and the value as they were, because the value it would recompute is\n   * derived from the registers and a malformed payload does not describe a\n   * cardinality.\n   */\n  public restoreHLL(data: Uint8Array): boolean {\n    if (!this.hll) {\n      this.hll = new HLL();\n    }\n    if (!this.hll.restore(data)) {\n      return false;\n    }\n    this.recomputeValue();\n    return true;\n  }\n\n  /**\n   * `recomputeValue` updates the counter value from the HLL cardinality estimate.\n   */\n  private recomputeValue(): void {\n    if (!this.hll) return;\n    this.value = this.hll.count();\n  }\n\n  /**\n   * `increase` increases numeric data.\n   * Dedup counters must use increaseDedup() instead.\n   */\n  public increase(v: Primitive): CRDTCounter {\n    if (this.isDedup()) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        'dedup counter requires actor, use increaseDedup()',\n      );\n    }\n\n    /**\n     * `checkNumericType` checks if the given target is a numeric type.\n     */\n    function checkNumericType(target: Primitive | CRDTCounter): void {\n      if (!target.isNumericType()) {\n        throw new TypeError(\n          `Unsupported type of value: ${typeof target.getValue()}`,\n        );\n      }\n    }\n    checkNumericType(this);\n    checkNumericType(v);\n\n    if (this.valueType === CounterType.Long) {\n      const delta =\n        typeof v.getValue() === 'bigint'\n          ? (v.getValue() as bigint)\n          : BigInt(Math.trunc(v.getValue() as number));\n      this.value = BigInt.asIntN(64, (this.value as bigint) + delta);\n    } else {\n      if (v.getType() === PrimitiveType.Long) {\n        this.value = bigintToInt32(\n          BigInt(this.value as number) + (v.getValue() as bigint),\n        );\n      } else {\n        this.value = bigintToInt32(\n          BigInt(\n            (this.value as number) + removeDecimal(v.getValue() as number),\n          ),\n        );\n      }\n    }\n\n    return this;\n  }\n}\n","/*\n * Copyright 2020 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n  ExecutionResult,\n  Operation,\n  OpSource,\n} from '@yorkie-js/sdk/src/document/operation/operation';\nimport { TimeTicket } from '@yorkie-js/sdk/src/document/time/ticket';\nimport { CRDTElement } from '@yorkie-js/sdk/src/document/crdt/element';\nimport { CRDTRoot } from '@yorkie-js/sdk/src/document/crdt/root';\nimport {\n  Primitive,\n  PrimitiveType,\n} from '@yorkie-js/sdk/src/document/crdt/primitive';\nimport { CRDTCounter } from '@yorkie-js/sdk/src/document/crdt/counter';\nimport { Code, YorkieError } from '@yorkie-js/sdk/src/util/error';\nimport { logger } from '@yorkie-js/sdk/src/util/logger';\n\n/**\n * `skipUnlessLocal` reports a delta that cannot be applied to the caller of a\n * local `update` or an undo/redo, and skips it with a warning on the pull path,\n * as Go does (`pkg/document/operations/increase.go`). A value that is not a\n * primitive (the wire format does not restrict it), a non-numeric delta or a\n * refused dedup increase can never be applied, and a stored change that throws\n * comes back on every pull -- the checkpoint does not advance past it -- so it\n * would wedge the document. Dropping the delta is the same on every replica,\n * so they still converge.\n */\nfunction skipUnlessLocal(source: OpSource | undefined, cause: unknown) {\n  if (source === OpSource.Remote) {\n    logger.warn(\n      `[Increase] skipped a remote increase that cannot apply: ${cause}`,\n    );\n    return undefined;\n  }\n  throw cause;\n}\n\n/**\n * `IncreaseOperation` represents an operation that increments a numeric value to Counter.\n * Among Primitives, numeric types Integer, Long are used as values.\n */\nexport class IncreaseOperation extends Operation {\n  private value: CRDTElement;\n  private actor: string;\n\n  constructor(\n    parentCreatedAt: TimeTicket,\n    value: CRDTElement,\n    executedAt?: TimeTicket,\n    actor?: string,\n  ) {\n    super(parentCreatedAt, executedAt);\n    this.value = value;\n    this.actor = actor || '';\n  }\n\n  /**\n   * `create` creates a new instance of IncreaseOperation.\n   */\n  public static create(\n    parentCreatedAt: TimeTicket,\n    value: CRDTElement,\n    executedAt?: TimeTicket,\n    actor?: string,\n  ): IncreaseOperation {\n    return new IncreaseOperation(parentCreatedAt, value, executedAt, actor);\n  }\n\n  /**\n   * `getActor` returns the actor ID associated with this operation.\n   */\n  public getActor(): string {\n    return this.actor;\n  }\n\n  /**\n   * `execute` executes this operation on the given `CRDTRoot`.\n   */\n  public execute(\n    root: CRDTRoot,\n    source?: OpSource,\n  ): ExecutionResult | undefined {\n    const parentObject = root.findByCreatedAt(this.getParentCreatedAt());\n    if (!parentObject) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `fail to find ${this.getParentCreatedAt()}`,\n      );\n    }\n    if (!(parentObject instanceof CRDTCounter)) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `fail to execute, only Counter can execute increase`,\n      );\n    }\n    const counter = parentObject as CRDTCounter;\n    if (!(this.value instanceof Primitive)) {\n      return skipUnlessLocal(\n        source,\n        new YorkieError(\n          Code.ErrInvalidArgument,\n          `fail to execute, only Primitive can be increased`,\n        ),\n      );\n    }\n    const value = this.value.deepcopy();\n    try {\n      if (counter.isDedup()) {\n        counter.increaseDedup(value, this.actor);\n      } else {\n        counter.increase(value);\n      }\n    } catch (cause) {\n      return skipUnlessLocal(source, cause);\n    }\n    return {\n      opInfos: [\n        {\n          type: 'increase',\n          path: root.createPath(this.getParentCreatedAt()),\n          value: value.getValue() as number,\n        },\n      ],\n      // Dedup counters do not support undo/redo because HLL cannot\n      // remove an actor once added.\n      reverseOp: this.actor ? undefined : this.toReverseOperation(),\n    };\n  }\n\n  /**\n   * `toReverseOperation` returns the reverse operation of this operation.\n   */\n  private toReverseOperation(): Operation {\n    const primitiveValue = this.value.deepcopy() as Primitive;\n\n    const valueType = primitiveValue.getType();\n    const value =\n      valueType === PrimitiveType.Long\n        ? -(primitiveValue.getValue() as bigint)\n        : (primitiveValue.getValue() as number) * -1;\n\n    const reverseOp = IncreaseOperation.create(\n      this.getParentCreatedAt(),\n      Primitive.of(value, primitiveValue.getCreatedAt()),\n    );\n    return reverseOp;\n  }\n\n  /**\n   * `getEffectedCreatedAt` returns the creation time of the effected element.\n   */\n  public getEffectedCreatedAt(): TimeTicket {\n    return this.getParentCreatedAt();\n  }\n\n  /**\n   * `toTestString` returns a string containing the meta data.\n   */\n  public toTestString(): string {\n    return `${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`;\n  }\n\n  /**\n   * `getValue` returns the value of this operation.\n   */\n  public getValue(): CRDTElement {\n    return this.value;\n  }\n}\n","/*\n * Copyright 2023 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TimeTicket } from '@yorkie-js/sdk/src/document/time/ticket';\nimport { VersionVector } from '@yorkie-js/sdk/src/document/time/version_vector';\nimport { CRDTRoot } from '@yorkie-js/sdk/src/document/crdt/root';\nimport {\n  CRDTTree,\n  CRDTTreeNodeID,\n  CRDTTreePos,\n  TreeChange,\n} from '@yorkie-js/sdk/src/document/crdt/tree';\nimport {\n  Operation,\n  OpInfo,\n  ExecutionResult,\n  OpSource,\n} from '@yorkie-js/sdk/src/document/operation/operation';\nimport { GCPair } from '@yorkie-js/sdk/src/document/crdt/gc';\nimport { Code, YorkieError } from '@yorkie-js/sdk/src/util/error';\n\n/**\n * `TreeStyleOperation` represents an operation that modifies the style of the\n * node in the Tree.\n */\nexport class TreeStyleOperation extends Operation {\n  private fromPos: CRDTTreePos;\n  private toPos: CRDTTreePos;\n  private attributes: Map<string, string>;\n  private attributesToRemove: Array<string>;\n\n  constructor(\n    parentCreatedAt: TimeTicket,\n    fromPos: CRDTTreePos,\n    toPos: CRDTTreePos,\n    attributes: Map<string, string>,\n    attributesToRemove: Array<string>,\n    executedAt: TimeTicket,\n  ) {\n    super(parentCreatedAt, executedAt);\n    this.fromPos = fromPos;\n    this.toPos = toPos;\n    this.attributes = attributes;\n    this.attributesToRemove = attributesToRemove;\n  }\n\n  /**\n   * `create` creates a new instance of TreeStyleOperation.\n   */\n  public static create(\n    parentCreatedAt: TimeTicket,\n    fromPos: CRDTTreePos,\n    toPos: CRDTTreePos,\n    attributes: Map<string, string>,\n    executedAt: TimeTicket,\n  ): TreeStyleOperation {\n    return new TreeStyleOperation(\n      parentCreatedAt,\n      fromPos,\n      toPos,\n      attributes,\n      [],\n      executedAt,\n    );\n  }\n\n  /**\n   * `createTreeRemoveStyleOperation` creates a new instance of TreeStyleOperation for style deletion.\n   */\n  public static createTreeRemoveStyleOperation(\n    parentCreatedAt: TimeTicket,\n    fromPos: CRDTTreePos,\n    toPos: CRDTTreePos,\n    attributesToRemove: Array<string>,\n    executedAt: TimeTicket,\n  ): TreeStyleOperation {\n    return new TreeStyleOperation(\n      parentCreatedAt,\n      fromPos,\n      toPos,\n      new Map(),\n      attributesToRemove,\n      executedAt,\n    );\n  }\n\n  /**\n   * `execute` executes this operation on the given `CRDTRoot`.\n   */\n  public execute(\n    root: CRDTRoot,\n    _: OpSource,\n    versionVector: VersionVector,\n  ): ExecutionResult {\n    const parentObject = root.findByCreatedAt(this.getParentCreatedAt());\n    if (!parentObject) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `fail to find ${this.getParentCreatedAt()}`,\n      );\n    }\n    if (!(parentObject instanceof CRDTTree)) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `fail to execute, only Tree can execute edit`,\n      );\n    }\n    const tree = parentObject as CRDTTree;\n    let changes: Array<TreeChange>;\n    let pairs: Array<GCPair>;\n    let size = { live: { data: 0, meta: 0 }, gc: { data: 0, meta: 0 } };\n    const reversePrevAttributes = new Map<string, string>();\n    const reverseAttrsToRemove: Array<string> = [];\n\n    if (this.attributes.size) {\n      const attributes: { [key: string]: any } = {};\n      [...this.attributes].forEach(([key, value]) => (attributes[key] = value));\n\n      let prevAttributes: Map<string, string>;\n      let newAttrKeys: Array<string>;\n      [pairs, changes, size, prevAttributes, newAttrKeys] = tree.style(\n        [this.fromPos, this.toPos],\n        attributes,\n        this.getExecutedAt(),\n        versionVector,\n      );\n\n      for (const [key, value] of prevAttributes) {\n        reversePrevAttributes.set(key, value);\n      }\n      reverseAttrsToRemove.push(...newAttrKeys);\n    } else {\n      const attributesToRemove = this.attributesToRemove;\n\n      let prevAttributes: Map<string, string>;\n      [pairs, changes, size, prevAttributes] = tree.removeStyle(\n        [this.fromPos, this.toPos],\n        attributesToRemove,\n        this.getExecutedAt(),\n        versionVector,\n      );\n\n      for (const [key, value] of prevAttributes) {\n        reversePrevAttributes.set(key, value);\n      }\n    }\n\n    root.acc(size.live);\n    root.accGC(size.gc);\n\n    for (const pair of pairs) {\n      root.registerGCPair(pair);\n    }\n\n    // Build reverse operation for undo.\n    let reverseOp: Operation | undefined;\n    if (reversePrevAttributes.size > 0 && reverseAttrsToRemove.length > 0) {\n      reverseOp = new TreeStyleOperation(\n        this.getParentCreatedAt(),\n        this.fromPos,\n        this.toPos,\n        reversePrevAttributes,\n        reverseAttrsToRemove,\n        undefined!,\n      );\n    } else if (reverseAttrsToRemove.length > 0) {\n      reverseOp = TreeStyleOperation.createTreeRemoveStyleOperation(\n        this.getParentCreatedAt(),\n        this.fromPos,\n        this.toPos,\n        reverseAttrsToRemove,\n        undefined!,\n      );\n    } else if (reversePrevAttributes.size > 0) {\n      reverseOp = TreeStyleOperation.create(\n        this.getParentCreatedAt(),\n        this.fromPos,\n        this.toPos,\n        reversePrevAttributes,\n        undefined!,\n      );\n    }\n\n    return {\n      opInfos: changes.map(({ from, to, value, fromPath, toPath }) => {\n        return {\n          type: 'tree-style',\n          from,\n          to,\n          value: this.attributes.size\n            ? { attributes: value }\n            : { attributesToRemove: value },\n          fromPath,\n          toPath,\n          path: root.createPath(this.getParentCreatedAt()),\n        } as OpInfo;\n      }),\n      reverseOp,\n    };\n  }\n\n  /**\n   * `getEffectedCreatedAt` returns the creation time of the effected element.\n   */\n  public getEffectedCreatedAt(): TimeTicket {\n    return this.getParentCreatedAt();\n  }\n\n  /**\n   * `toTestString` returns a string containing the meta data.\n   */\n  public toTestString(): string {\n    const parent = this.getParentCreatedAt().toTestString();\n    const fromPos = `${this.fromPos\n      .getLeftSiblingID()\n      .getCreatedAt()\n      .toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`;\n    const toPos = `${this.toPos\n      .getLeftSiblingID()\n      .getCreatedAt()\n      .toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;\n\n    return `${parent}.STYLE(${fromPos},${toPos},${Object.entries(\n      this.attributes || {},\n    )\n      .map(([k, v]) => `${k}:\"${v}\"`)\n      .join(' ')})`;\n  }\n\n  /**\n   * `reconcileNodeID` points this operation at `curr` wherever it named\n   * `prev`. An undo or redo that re-splits an element mints the element under\n   * a new id; an operation that was recorded against the old one would\n   * otherwise address a node that may no longer exist.\n   */\n  public reconcileNodeID(prev: CRDTTreeNodeID, curr: CRDTTreeNodeID): void {\n    this.fromPos = this.fromPos.replaceNodeID(prev, curr);\n    this.toPos = this.toPos.replaceNodeID(prev, curr);\n  }\n\n  /**\n   * `getFromPos` returns the start point of the editing range.\n   */\n  public getFromPos(): CRDTTreePos {\n    return this.fromPos;\n  }\n\n  /**\n   * `getToPos` returns the end point of the editing range.\n   */\n  public getToPos(): CRDTTreePos {\n    return this.toPos;\n  }\n\n  /**\n   * `getAttributes` returns the attributes of Style.\n   */\n  public getAttributes(): Map<string, string> {\n    return this.attributes;\n  }\n\n  /**\n   * `getAttributesToRemove` returns the attributes of Style to remove.\n   */\n  public getAttributesToRemove(): Array<string> {\n    return this.attributesToRemove;\n  }\n}\n","/*\n * Copyright 2025 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TimeTicket } from '@yorkie-js/sdk/src/document/time/ticket';\nimport { CRDTElement } from '@yorkie-js/sdk/src/document/crdt/element';\nimport { CRDTRoot } from '@yorkie-js/sdk/src/document/crdt/root';\nimport { CRDTArray } from '@yorkie-js/sdk/src/document/crdt/array';\nimport {\n  Operation,\n  ExecutionResult,\n} from '@yorkie-js/sdk/src/document/operation/operation';\nimport { Code, YorkieError } from '@yorkie-js/sdk/src/util/error';\n\n/**\n * `ArraySetOperation` is an operation representing setting an element in Array.\n */\nexport class ArraySetOperation extends Operation {\n  private createdAt: TimeTicket;\n  private value: CRDTElement;\n\n  constructor(\n    parentCreatedAt: TimeTicket,\n    createdAt: TimeTicket,\n    value: CRDTElement,\n    executedAt?: TimeTicket,\n  ) {\n    super(parentCreatedAt, executedAt);\n    this.createdAt = createdAt;\n    this.value = value;\n  }\n\n  /**\n   * `create` creates a new instance of ArraySetOperation.\n   */\n  public static create(\n    parentCreatedAt: TimeTicket,\n    createdAt: TimeTicket,\n    value: CRDTElement,\n    executedAt?: TimeTicket,\n  ): ArraySetOperation {\n    return new ArraySetOperation(parentCreatedAt, createdAt, value, executedAt);\n  }\n\n  /**\n   * `execute` executes this operation on the given `CRDTRoot`.\n   */\n  public execute(root: CRDTRoot): ExecutionResult {\n    const parentObject = root.findByCreatedAt(this.getParentCreatedAt());\n    if (!parentObject) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `fail to find ${this.getParentCreatedAt()}`,\n      );\n    }\n    if (!(parentObject instanceof CRDTArray)) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `fail to execute, only array can execute set`,\n      );\n    }\n\n    const previousValue = parentObject.getByID(this.createdAt)!.deepcopy();\n    const reverseOp = this.toReverseOperation(this.value, previousValue);\n\n    const value = this.value.deepcopy();\n    parentObject.insertAfter(this.createdAt, value, this.getExecutedAt());\n    const removed = parentObject.delete(this.createdAt, this.getExecutedAt());\n\n    // NOTE(hackerwins): The parent has to be passed. `garbageCollect` reaches\n    // an element through the pair registered here and calls `purge` on its\n    // parent, so a value registered without one cannot be collected -- it\n    // throws there instead, inside `applyChangePack`, and that client stops\n    // syncing for good. No undo is involved: setting an array element, then\n    // removing it, then collecting is enough.\n    root.registerElement(value, parentObject);\n\n    // NOTE(hackerwins): The element this assignment displaced has to be\n    // registered for collection. Discarding it left it charged to\n    // `docSize.live` with nothing able to reach it, so an ordinary\n    // `arr[i] = x` in a loop grew the document without bound and collection\n    // reported nothing to do.\n    //\n    // The old TODO here said the two could not be told apart because they\n    // share a createdAt. They do not: `this.createdAt` names the element being\n    // displaced and `value` carries its own identity. That stopped being true\n    // when `set` became insert-then-remove rather than an in-place swap.\n    if (removed) {\n      root.registerRemovedElement(removed);\n    }\n\n    return {\n      opInfos: [\n        {\n          type: 'array-set',\n          path: root.createPath(this.getParentCreatedAt()),\n        },\n      ],\n      reverseOp,\n    };\n  }\n\n  /**\n   * `toReverseOperation` returns the reverse operation of this operation.\n   */\n  private toReverseOperation(\n    newValue: CRDTElement,\n    prevValue: CRDTElement,\n  ): Operation {\n    const reverseOp: ArraySetOperation = ArraySetOperation.create(\n      this.getParentCreatedAt(),\n      newValue.getCreatedAt(),\n      prevValue,\n    );\n\n    return reverseOp;\n  }\n\n  /**\n   * `getEffectedCreatedAt` returns the creation time of the effected element.\n   */\n  public getEffectedCreatedAt(): TimeTicket {\n    return this.createdAt;\n  }\n\n  /**\n   * `toTestString` returns a string containing the meta data.\n   */\n  public toTestString(): string {\n    return `${this.getParentCreatedAt().toTestString()}.ARRAY_SET.${this.createdAt.toTestString()}=${this.value.toSortedJSON()}`;\n  }\n\n  /**\n   * `getCreatedAt` returns the creation time of the target element.\n   */\n  public getCreatedAt(): TimeTicket {\n    return this.createdAt;\n  }\n\n  /**\n   * `getValue` returns the value of this operation.\n   */\n  public getValue(): CRDTElement {\n    return this.value;\n  }\n\n  /**\n   * `setCreatedAt` sets the creation time of the target element.\n   */\n  public setCreatedAt(createdAt: TimeTicket) {\n    this.createdAt = createdAt;\n  }\n}\n","/*\n * Copyright 2023 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ConnectError } from '@connectrpc/connect';\nimport { create, toBinary, fromBinary } from '@bufbuild/protobuf';\nimport { timestampDate } from '@bufbuild/protobuf/wkt';\nimport { ErrorInfoSchema } from '@buf/googleapis_googleapis.bufbuild_es/google/rpc/error_details_pb';\nimport { Rule } from '@yorkie-js/schema';\nimport { Code, YorkieError } from '@yorkie-js/sdk/src/util/error';\nimport { parseAttrValue } from '@yorkie-js/sdk/src/util/object';\nimport { Indexable } from '@yorkie-js/sdk/src/document/document';\nimport {\n  PresenceChange,\n  PresenceChangeType,\n} from '@yorkie-js/sdk/src/document/presence/change';\nimport {\n  InitialTimeTicket,\n  TimeTicket,\n} from '@yorkie-js/sdk/src/document/time/ticket';\nimport { ActorID } from '@yorkie-js/sdk/src/document/time/actor_id';\nimport { Operation } from '@yorkie-js/sdk/src/document/operation/operation';\nimport { SetOperation } from '@yorkie-js/sdk/src/document/operation/set_operation';\nimport { AddOperation } from '@yorkie-js/sdk/src/document/operation/add_operation';\nimport { MoveOperation } from '@yorkie-js/sdk/src/document/operation/move_operation';\nimport { RemoveOperation } from '@yorkie-js/sdk/src/document/operation/remove_operation';\nimport { EditOperation } from '@yorkie-js/sdk/src/document/operation/edit_operation';\nimport { StyleOperation } from '@yorkie-js/sdk/src/document/operation/style_operation';\nimport { TreeEditOperation } from '@yorkie-js/sdk/src/document/operation/tree_edit_operation';\nimport { ChangeID } from '@yorkie-js/sdk/src/document/change/change_id';\nimport { Change } from '@yorkie-js/sdk/src/document/change/change';\nimport { ChangePack } from '@yorkie-js/sdk/src/document/change/change_pack';\nimport { Checkpoint } from '@yorkie-js/sdk/src/document/change/checkpoint';\nimport { ElementRHT } from '@yorkie-js/sdk/src/document/crdt/element_rht';\nimport { RGATreeList } from '@yorkie-js/sdk/src/document/crdt/rga_tree_list';\nimport { CRDTElement } from '@yorkie-js/sdk/src/document/crdt/element';\nimport { dropSplitLinksInElement } from '@yorkie-js/sdk/src/document/crdt/split_links';\nimport { CRDTObject } from '@yorkie-js/sdk/src/document/crdt/object';\nimport { CRDTArray } from '@yorkie-js/sdk/src/document/crdt/array';\nimport { VersionVector } from '@yorkie-js/sdk/src/document/time/version_vector';\nimport { CRDTTreePos } from './../document/crdt/tree';\nimport {\n  RGATreeSplit,\n  RGATreeSplitNode,\n  RGATreeSplitNodeID,\n  RGATreeSplitPos,\n  RestoreSpan,\n} from '@yorkie-js/sdk/src/document/crdt/rga_tree_split';\nimport { CRDTText, CRDTTextValue } from '@yorkie-js/sdk/src/document/crdt/text';\nimport {\n  Primitive,\n  PrimitiveType,\n} from '@yorkie-js/sdk/src/document/crdt/primitive';\nimport {\n  Change as PbChange,\n  ChangeSchema as PbChangeSchema,\n  ChangeID as PbChangeID,\n  ChangeIDSchema as PbChangeIDSchema,\n  ChangePack as PbChangePack,\n  ChangePackSchema as PbChangePackSchema,\n  Checkpoint as PbCheckpoint,\n  CheckpointSchema as PbCheckpointSchema,\n  Rule as PbRule,\n  JSONElement as PbJSONElement,\n  JSONElementSchema as PbJSONElementSchema,\n  JSONElementSimple as PbJSONElementSimple,\n  JSONElementSimpleSchema as PbJSONElementSimpleSchema,\n  NodeAttr as PbNodeAttr,\n  NodeAttrSchema as PbNodeAttrSchema,\n  Operation as PbOperation,\n  OperationSchema as PbOperationSchema,\n  Presence as PbPresence,\n  PresenceSchema as PbPresenceSchema,\n  PresenceChange as PbPresenceChange,\n  PresenceChangeSchema as PbPresenceChangeSchema,\n  RGANode as PbRGANode,\n  RGANodeSchema as PbRGANodeSchema,\n  RHTNode as PbRHTNode,\n  RHTNodeSchema as PbRHTNodeSchema,\n  SnapshotSchema as PbSnapshotSchema,\n  TextNode as PbTextNode,\n  TextNodeSchema as PbTextNodeSchema,\n  TextNodeID as PbTextNodeID,\n  TextNodeIDSchema as PbTextNodeIDSchema,\n  TextNodePos as PbTextNodePos,\n  TextNodePosSchema as PbTextNodePosSchema,\n  TimeTicket as PbTimeTicket,\n  TimeTicketSchema as PbTimeTicketSchema,\n  TreeNode as PbTreeNode,\n  TreeNodeSchema as PbTreeNodeSchema,\n  TreeNodes as PbTreeNodes,\n  TreeNodesSchema as PbTreeNodesSchema,\n  TreePos as PbTreePos,\n  TreePosSchema as PbTreePosSchema,\n  TreeNodeID as PbTreeNodeID,\n  TreeNodeIDSchema as PbTreeNodeIDSchema,\n  VersionVector as PbVersionVector,\n  VersionVectorSchema as PbVersionVectorSchema,\n  ValueType as PbValueType,\n  JSONElement_Tree as PbJSONElement_Tree,\n  JSONElement_TreeSchema as PbJSONElement_TreeSchema,\n  JSONElement_Text as PbJSONElement_Text,\n  JSONElement_TextSchema as PbJSONElement_TextSchema,\n  JSONElement_Primitive as PbJSONElement_Primitive,\n  JSONElement_PrimitiveSchema as PbJSONElement_PrimitiveSchema,\n  JSONElement_Counter as PbJSONElement_Counter,\n  JSONElement_CounterSchema as PbJSONElement_CounterSchema,\n  JSONElement_JSONObject as PbJSONElement_JSONObject,\n  JSONElement_JSONObjectSchema as PbJSONElement_JSONObjectSchema,\n  JSONElement_JSONArray as PbJSONElement_JSONArray,\n  JSONElement_JSONArraySchema as PbJSONElement_JSONArraySchema,\n  PresenceChange_ChangeType as PbPresenceChange_ChangeType,\n  Operation_SetSchema as PbOperation_SetSchema,\n  Operation_AddSchema as PbOperation_AddSchema,\n  Operation_MoveSchema as PbOperation_MoveSchema,\n  Operation_RemoveSchema as PbOperation_RemoveSchema,\n  Operation_EditSchema as PbOperation_EditSchema,\n  Operation_StyleSchema as PbOperation_StyleSchema,\n  Operation_IncreaseSchema as PbOperation_IncreaseSchema,\n  Operation_TreeEditSchema as PbOperation_TreeEditSchema,\n  Operation_TreeStyleSchema as PbOperation_TreeStyleSchema,\n  Operation_ArraySetSchema as PbOperation_ArraySetSchema,\n  RestoreSpanSchema as PbRestoreSpanSchema,\n  RestoreSpan as PbRestoreSpan,\n  RestoreMode as PbRestoreMode,\n  TreeRestoreSpanSchema as PbTreeRestoreSpanSchema,\n  TreeRestoreSpan as PbTreeRestoreSpan,\n  RevisionSummary as PbRevisionSummary,\n} from '@yorkie-js/sdk/src/api/yorkie/v1/resources_pb';\nimport { IncreaseOperation } from '@yorkie-js/sdk/src/document/operation/increase_operation';\nimport {\n  CounterType,\n  CRDTCounter,\n} from '@yorkie-js/sdk/src/document/crdt/counter';\nimport {\n  CRDTTree,\n  CRDTTreeNode,\n  CRDTTreeNodeID,\n  TreeRestoreSpan,\n} from '@yorkie-js/sdk/src/document/crdt/tree';\nimport { traverseAll } from '../util/index_tree';\nimport { TreeStyleOperation } from '../document/operation/tree_style_operation';\nimport { RHT } from '../document/crdt/rht';\nimport { ArraySetOperation } from '../document/operation/array_set_operation';\nimport { RevisionSummary } from './revision';\nimport { logger } from '@yorkie-js/sdk/src/util/logger';\n\n/**\n * `toPresence` converts the given model to Protobuf format.\n */\nfunction toPresence(presence: Indexable): PbPresence {\n  const pbDataMap: { [key: string]: string } = {};\n  for (const [key, value] of Object.entries(presence)) {\n    pbDataMap[key] = JSON.stringify(value);\n  }\n  return create(PbPresenceSchema, { data: pbDataMap });\n}\n\n/**\n * `toPresenceChange` converts the given model to Protobuf format.\n */\nfunction toPresenceChange(\n  presenceChange: PresenceChange<Indexable>,\n): PbPresenceChange {\n  if (presenceChange.type === PresenceChangeType.Put) {\n    return create(PbPresenceChangeSchema, {\n      type: PbPresenceChange_ChangeType.PUT,\n      presence: toPresence(presenceChange.presence),\n    });\n  }\n  if (presenceChange.type === PresenceChangeType.Patch) {\n    // Only the changed keys go on the wire; the patch's `full` copy is local\n    // state for `Change.execute` and the base-unavailable fallback. The server\n    // folds the patch into the base it holds before storing it.\n    return create(PbPresenceChangeSchema, {\n      type: PbPresenceChange_ChangeType.PATCH,\n      presence: toPresence(presenceChange.presence as Indexable),\n    });\n  }\n  if (presenceChange.type === PresenceChangeType.Clear) {\n    return create(PbPresenceChangeSchema, {\n      type: PbPresenceChange_ChangeType.CLEAR,\n    });\n  }\n\n  throw new YorkieError(Code.ErrUnimplemented, `unimplemented type`);\n}\n\n/**\n * `toCheckpoint` converts the given model to Protobuf format.\n */\nfunction toCheckpoint(checkpoint: Checkpoint): PbCheckpoint {\n  return create(PbCheckpointSchema, {\n    serverSeq: checkpoint.getServerSeq(),\n    clientSeq: checkpoint.getClientSeq(),\n  });\n}\n\n/**\n * `toChangeID` converts the given model to Protobuf format.\n */\nfunction toChangeID(changeID: ChangeID): PbChangeID {\n  return create(PbChangeIDSchema, {\n    clientSeq: changeID.getClientSeq(),\n    lamport: changeID.getLamport(),\n    actorId: toUint8Array(changeID.getActorID()),\n    versionVector: toVersionVector(changeID.getVersionVector()),\n  });\n}\n\n/**\n * `toTimeTicket` converts the given model to Protobuf format.\n */\nfunction toTimeTicket(ticket?: TimeTicket): PbTimeTicket | undefined {\n  if (!ticket) {\n    return;\n  }\n\n  return create(PbTimeTicketSchema, {\n    lamport: ticket.getLamport(),\n    delimiter: ticket.getDelimiter(),\n    actorId: toUint8Array(ticket.getActorID()),\n  });\n}\n\n/**\n * `toVersionVector` converts the given model to Protobuf format.\n */\nfunction toVersionVector(vector?: VersionVector): PbVersionVector | undefined {\n  if (!vector) {\n    return;\n  }\n\n  const pbVector = create(PbVersionVectorSchema);\n  for (const [actorID, lamport] of vector) {\n    const base64ActorID = uint8ArrayToBase64(toUint8Array(actorID));\n    pbVector.vector[base64ActorID] = BigInt(lamport.toString());\n  }\n  return pbVector;\n}\n\n/**\n * `toValueType` converts the given model to Protobuf format.\n */\nfunction toValueType(valueType: PrimitiveType): PbValueType {\n  switch (valueType) {\n    case PrimitiveType.Null:\n      return PbValueType.NULL;\n    case PrimitiveType.Boolean:\n      return PbValueType.BOOLEAN;\n    case PrimitiveType.Integer:\n      return PbValueType.INTEGER;\n    case PrimitiveType.Long:\n      return PbValueType.LONG;\n    case PrimitiveType.Double:\n      return PbValueType.DOUBLE;\n    case PrimitiveType.String:\n      return PbValueType.STRING;\n    case PrimitiveType.Bytes:\n      return PbValueType.BYTES;\n    case PrimitiveType.Date:\n      return PbValueType.DATE;\n    default:\n      throw new YorkieError(\n        Code.ErrInvalidType,\n        `unsupported type: ${valueType}`,\n      );\n  }\n}\n\n/**\n * `toCounterType` converts the given model to Protobuf format.\n */\nfunction toCounterType(valueType: CounterType): PbValueType {\n  switch (valueType) {\n    case CounterType.Int:\n      return PbValueType.INTEGER_CNT;\n    case CounterType.Long:\n      return PbValueType.LONG_CNT;\n    case CounterType.IntDedup:\n      return PbValueType.INTEGER_DEDUP_CNT;\n    default:\n      throw new YorkieError(\n        Code.ErrInvalidType,\n        `unsupported type: ${valueType}`,\n      );\n  }\n}\n\n/**\n * `toElementSimple` converts the given model to Protobuf format.\n */\nfunction toElementSimple(element: CRDTElement): PbJSONElementSimple {\n  if (element instanceof CRDTObject) {\n    return create(PbJSONElementSimpleSchema, {\n      type: PbValueType.JSON_OBJECT,\n      createdAt: toTimeTicket(element.getCreatedAt()),\n      value: objectToBytes(element),\n    });\n  }\n  if (element instanceof CRDTArray) {\n    return create(PbJSONElementSimpleSchema, {\n      type: PbValueType.JSON_ARRAY,\n      createdAt: toTimeTicket(element.getCreatedAt()),\n      value: arrayToBytes(element),\n    });\n  }\n  if (element instanceof CRDTText) {\n    return create(PbJSONElementSimpleSchema, {\n      type: PbValueType.TEXT,\n      createdAt: toTimeTicket(element.getCreatedAt()),\n    });\n  }\n  if (element instanceof Primitive) {\n    return create(PbJSONElementSimpleSchema, {\n      type: toValueType(element.getType()),\n      createdAt: toTimeTicket(element.getCreatedAt()),\n      value: element.toBytes(),\n    });\n  }\n  if (element instanceof CRDTCounter) {\n    return create(PbJSONElementSimpleSchema, {\n      type: toCounterType(element.getType()),\n      createdAt: toTimeTicket(element.getCreatedAt()),\n      value: element.toBytes(),\n    });\n  }\n  if (element instanceof CRDTTree) {\n    return create(PbJSONElementSimpleSchema, {\n      type: PbValueType.TREE,\n      createdAt: toTimeTicket(element.getCreatedAt()),\n      value: treeToBytes(element),\n    });\n  }\n\n  throw new YorkieError(Code.ErrUnimplemented, `unimplemented element`);\n}\n\n/**\n * `toTextNodeID` converts the given model to Protobuf format.\n */\nfunction toTextNodeID(id: RGATreeSplitNodeID): PbTextNodeID {\n  return create(PbTextNodeIDSchema, {\n    createdAt: toTimeTicket(id.getCreatedAt()),\n    offset: id.getOffset(),\n  });\n}\n\n/**\n * `toTextNodePos` converts the given model to Protobuf format.\n */\nfunction toTextNodePos(pos: RGATreeSplitPos): PbTextNodePos {\n  return create(PbTextNodePosSchema, {\n    createdAt: toTimeTicket(pos.getID().getCreatedAt()),\n    offset: pos.getID().getOffset(),\n    relativeOffset: pos.getRelativeOffset(),\n  });\n}\n\n/**\n * `toTreePos` converts the given model to Protobuf format.\n */\nfunction toTreePos(pos: CRDTTreePos): PbTreePos {\n  return create(PbTreePosSchema, {\n    parentId: toTreeNodeID(pos.getParentID()),\n    leftSiblingId: toTreeNodeID(pos.getLeftSiblingID()),\n  });\n}\n\n/**\n * `toTreeNodeID` converts the given model to Protobuf format.\n */\nfunction toTreeNodeID(treeNodeID: CRDTTreeNodeID): PbTreeNodeID {\n  return create(PbTreeNodeIDSchema, {\n    createdAt: toTimeTicket(treeNodeID.getCreatedAt()),\n    offset: treeNodeID.getOffset(),\n  });\n}\n\n/**\n * `toPbTreeRestoreSpan` converts a TreeRestoreSpan to Protobuf format.\n */\nfunction toPbTreeRestoreSpan(span: TreeRestoreSpan): PbTreeRestoreSpan {\n  const pbSpan = create(PbTreeRestoreSpanSchema);\n  pbSpan.id = toTreeNodeID(span.id);\n  pbSpan.nodeType = span.nodeType;\n  pbSpan.isText = span.isText;\n  pbSpan.length = span.length;\n  if (span.value !== undefined) {\n    pbSpan.value = span.value;\n  }\n  if (span.attrs) {\n    pbSpan.attributes = toRHT(span.attrs);\n  }\n  if (span.parentID) {\n    pbSpan.parentId = toTreeNodeID(span.parentID);\n  }\n  if (span.leftSiblingID) {\n    pbSpan.leftSiblingId = toTreeNodeID(span.leftSiblingID);\n  }\n  if (span.rightSiblingID) {\n    pbSpan.rightSiblingId = toTreeNodeID(span.rightSiblingID);\n  }\n  return pbSpan;\n}\n\n/**\n * `fromPbTreeRestoreSpan` converts a Protobuf TreeRestoreSpan to model format.\n * A span addresses content by insertion identity, so every node ID it carries\n * is malformed without a `createdAt`, and the attribute snapshot is malformed\n * without an `updatedAt`. Both are rejected here because the decoders below\n * non-null assert those tickets: `fromTreeNodeID` would yield a\n * CRDTTreeNodeID with an undefined createdAt and `fromRHT` an RHT node with an\n * undefined updatedAt, neither failing until deep inside the restore path.\n * Mirrors the server's `fromTreeRestoreSpans`.\n */\nfunction fromPbTreeRestoreSpan(pbSpan: PbTreeRestoreSpan): TreeRestoreSpan {\n  const anchors = [\n    pbSpan.parentId,\n    pbSpan.leftSiblingId,\n    pbSpan.rightSiblingId,\n  ];\n  if (\n    !pbSpan.id?.createdAt ||\n    anchors.some((anchor) => anchor && !anchor.createdAt) ||\n    Object.values(pbSpan.attributes).some((attr) => !attr.updatedAt)\n  ) {\n    throw new YorkieError(\n      Code.ErrInvalidArgument,\n      'malformed tree restore span: missing timestamp',\n    );\n  }\n  return {\n    id: fromTreeNodeID(pbSpan.id),\n    nodeType: pbSpan.nodeType,\n    isText: pbSpan.isText,\n    length: pbSpan.length,\n    value: pbSpan.isText ? pbSpan.value : undefined,\n    attrs:\n      Object.keys(pbSpan.attributes).length > 0\n        ? fromRHT(pbSpan.attributes)\n        : undefined,\n    parentID: pbSpan.parentId ? fromTreeNodeID(pbSpan.parentId) : undefined,\n    leftSiblingID: pbSpan.leftSiblingId\n      ? fromTreeNodeID(pbSpan.leftSiblingId)\n      : undefined,\n    rightSiblingID: pbSpan.rightSiblingId\n      ? fromTreeNodeID(pbSpan.rightSiblingId)\n      : undefined,\n  };\n}\n\n/**\n * `toOperation` converts the given model to Protobuf format.\n */\nfunction toOperation(operation: Operation): PbOperation {\n  const pbOperation = create(PbOperationSchema);\n\n  if (operation instanceof SetOperation) {\n    const setOperation = operation as SetOperation;\n    const pbSetOperation = create(PbOperation_SetSchema);\n    pbSetOperation.parentCreatedAt = toTimeTicket(\n      setOperation.getParentCreatedAt(),\n    );\n    pbSetOperation.key = setOperation.getKey();\n    pbSetOperation.value = toElementSimple(setOperation.getValue());\n    pbSetOperation.executedAt = toTimeTicket(setOperation.getExecutedAt());\n    pbOperation.body.case = 'set';\n    pbOperation.body.value = pbSetOperation;\n  } else if (operation instanceof AddOperation) {\n    const addOperation = operation as AddOperation;\n    const pbAddOperation = create(PbOperation_AddSchema);\n    pbAddOperation.parentCreatedAt = toTimeTicket(\n      addOperation.getParentCreatedAt(),\n    );\n    pbAddOperation.prevCreatedAt = toTimeTicket(\n      addOperation.getPrevCreatedAt(),\n    );\n    pbAddOperation.value = toElementSimple(addOperation.getValue());\n    pbAddOperation.executedAt = toTimeTicket(addOperation.getExecutedAt());\n    pbOperation.body.case = 'add';\n    pbOperation.body.value = pbAddOperation;\n  } else if (operation instanceof MoveOperation) {\n    const moveOperation = operation as MoveOperation;\n    const pbMoveOperation = create(PbOperation_MoveSchema);\n    pbMoveOperation.parentCreatedAt = toTimeTicket(\n      moveOperation.getParentCreatedAt(),\n    );\n    pbMoveOperation.prevCreatedAt = toTimeTicket(\n      moveOperation.getPrevCreatedAt(),\n    );\n    pbMoveOperation.createdAt = toTimeTicket(moveOperation.getCreatedAt());\n    pbMoveOperation.executedAt = toTimeTicket(moveOperation.getExecutedAt());\n    pbOperation.body.case = 'move';\n    pbOperation.body.value = pbMoveOperation;\n  } else if (operation instanceof RemoveOperation) {\n    const removeOperation = operation as RemoveOperation;\n    const pbRemoveOperation = create(PbOperation_RemoveSchema);\n    pbRemoveOperation.parentCreatedAt = toTimeTicket(\n      removeOperation.getParentCreatedAt(),\n    );\n    pbRemoveOperation.createdAt = toTimeTicket(removeOperation.getCreatedAt());\n    pbRemoveOperation.executedAt = toTimeTicket(\n      removeOperation.getExecutedAt(),\n    );\n    pbOperation.body.case = 'remove';\n    pbOperation.body.value = pbRemoveOperation;\n  } else if (operation instanceof EditOperation) {\n    const editOperation = operation as EditOperation;\n    const pbEditOperation = create(PbOperation_EditSchema);\n    pbEditOperation.parentCreatedAt = toTimeTicket(\n      editOperation.getParentCreatedAt(),\n    );\n    pbEditOperation.from = toTextNodePos(editOperation.getFromPos());\n    pbEditOperation.to = toTextNodePos(editOperation.getToPos());\n    pbEditOperation.content = editOperation.getContent();\n    const pbAttributes = pbEditOperation.attributes;\n    for (const [key, value] of editOperation.getAttributes()) {\n      pbAttributes[key] = value;\n    }\n    pbEditOperation.executedAt = toTimeTicket(editOperation.getExecutedAt());\n    const toPbSpan = (span: RestoreSpan<CRDTTextValue>) => {\n      const pbSpan = create(PbRestoreSpanSchema);\n      pbSpan.createdAt = toTimeTicket(span.createdAt);\n      pbSpan.start = span.start;\n      pbSpan.end = span.end;\n      pbSpan.content = span.value.getContent();\n      const pbSpanAttrs = pbSpan.attributes;\n      for (const [key, value] of Object.entries(span.value.getAttributes())) {\n        pbSpanAttrs[key] = value;\n      }\n      return pbSpan;\n    };\n    const restoreSpans = editOperation.getRestoreSpans();\n    const retombstoneSpans = editOperation.getRetombstoneSpans();\n    if (\n      (restoreSpans && restoreSpans.length) ||\n      (retombstoneSpans && retombstoneSpans.length)\n    ) {\n      pbEditOperation.restoreSpans = (restoreSpans ?? []).map(toPbSpan);\n      pbEditOperation.retombstoneSpans = (retombstoneSpans ?? []).map(toPbSpan);\n      pbEditOperation.restoreMode =\n        editOperation.getRestoreMode() === 'retombstone'\n          ? PbRestoreMode.RETOMBSTONE\n          : PbRestoreMode.RESTORE;\n    }\n    pbOperation.body.case = 'edit';\n    pbOperation.body.value = pbEditOperation;\n  } else if (operation instanceof StyleOperation) {\n    const styleOperation = operation as StyleOperation;\n    const pbStyleOperation = create(PbOperation_StyleSchema);\n    pbStyleOperation.parentCreatedAt = toTimeTicket(\n      styleOperation.getParentCreatedAt(),\n    );\n    pbStyleOperation.from = toTextNodePos(styleOperation.getFromPos());\n    pbStyleOperation.to = toTextNodePos(styleOperation.getToPos());\n\n    const attributesToRemove = styleOperation.getAttributesToRemove();\n    if (attributesToRemove.length > 0) {\n      pbStyleOperation.attributesToRemove = attributesToRemove;\n    }\n    const pbAttributes = pbStyleOperation.attributes;\n    for (const [key, value] of styleOperation.getAttributes()) {\n      pbAttributes[key] = value;\n    }\n    pbStyleOperation.executedAt = toTimeTicket(styleOperation.getExecutedAt());\n    pbOperation.body.case = 'style';\n    pbOperation.body.value = pbStyleOperation;\n  } else if (operation instanceof IncreaseOperation) {\n    const increaseOperation = operation as IncreaseOperation;\n    const pbIncreaseOperation = create(PbOperation_IncreaseSchema);\n    pbIncreaseOperation.parentCreatedAt = toTimeTicket(\n      increaseOperation.getParentCreatedAt(),\n    );\n    pbIncreaseOperation.value = toElementSimple(increaseOperation.getValue());\n    pbIncreaseOperation.executedAt = toTimeTicket(\n      increaseOperation.getExecutedAt(),\n    );\n    pbIncreaseOperation.actor = increaseOperation.getActor();\n    pbOperation.body.case = 'increase';\n    pbOperation.body.value = pbIncreaseOperation;\n  } else if (operation instanceof TreeEditOperation) {\n    const treeEditOperation = operation as TreeEditOperation;\n    const pbTreeEditOperation = create(PbOperation_TreeEditSchema);\n    pbTreeEditOperation.parentCreatedAt = toTimeTicket(\n      treeEditOperation.getParentCreatedAt(),\n    );\n    pbTreeEditOperation.from = toTreePos(treeEditOperation.getFromPos());\n    pbTreeEditOperation.to = toTreePos(treeEditOperation.getToPos());\n    pbTreeEditOperation.contents = toTreeNodesWhenEdit(\n      treeEditOperation.getContents()!,\n    );\n    pbTreeEditOperation.splitLevel = treeEditOperation.getSplitLevel();\n\n    pbTreeEditOperation.executedAt = toTimeTicket(\n      treeEditOperation.getExecutedAt(),\n    );\n    const treeRestoreSpans = treeEditOperation.getRestoreSpans();\n    const treeRetombstoneSpans = treeEditOperation.getRetombstoneSpans();\n    if (\n      (treeRestoreSpans && treeRestoreSpans.length) ||\n      (treeRetombstoneSpans && treeRetombstoneSpans.length)\n    ) {\n      pbTreeEditOperation.restoreSpans = (treeRestoreSpans ?? []).map(\n        toPbTreeRestoreSpan,\n      );\n      pbTreeEditOperation.retombstoneSpans = (treeRetombstoneSpans ?? []).map(\n        toPbTreeRestoreSpan,\n      );\n      pbTreeEditOperation.restoreMode =\n        treeEditOperation.getRestoreMode() === 'retombstone'\n          ? PbRestoreMode.RETOMBSTONE\n          : PbRestoreMode.RESTORE;\n    }\n    pbTreeEditOperation.splitTickets = treeEditOperation\n      .getSplitTickets()\n      .map((ticket) => toTimeTicket(ticket)!);\n    pbOperation.body.case = 'treeEdit';\n    pbOperation.body.value = pbTreeEditOperation;\n  } else if (operation instanceof TreeStyleOperation) {\n    const treeStyleOperation = operation as TreeStyleOperation;\n    const pbTreeStyleOperation = create(PbOperation_TreeStyleSchema);\n    pbTreeStyleOperation.parentCreatedAt = toTimeTicket(\n      treeStyleOperation.getParentCreatedAt(),\n    );\n    pbTreeStyleOperation.from = toTreePos(treeStyleOperation.getFromPos());\n    pbTreeStyleOperation.to = toTreePos(treeStyleOperation.getToPos());\n\n    // Encode both fields, as Go's toTreeStyle does. The reverse of a style\n    // that overwrote some attributes and added others carries both, and\n    // dropping either half would let peers apply something other than what\n    // the undoing client applied.\n    const attributesMap = pbTreeStyleOperation.attributes;\n    for (const [key, value] of treeStyleOperation.getAttributes()) {\n      attributesMap[key] = value;\n    }\n    pbTreeStyleOperation.attributesToRemove = [\n      ...treeStyleOperation.getAttributesToRemove(),\n    ];\n    pbTreeStyleOperation.executedAt = toTimeTicket(\n      treeStyleOperation.getExecutedAt(),\n    );\n    pbOperation.body.case = 'treeStyle';\n    pbOperation.body.value = pbTreeStyleOperation;\n  } else if (operation instanceof ArraySetOperation) {\n    const arraySetOperation = operation as ArraySetOperation;\n    const pbArraySetOperation = create(PbOperation_ArraySetSchema);\n    pbArraySetOperation.parentCreatedAt = toTimeTicket(\n      arraySetOperation.getParentCreatedAt(),\n    );\n    pbArraySetOperation.createdAt = toTimeTicket(\n      arraySetOperation.getCreatedAt(),\n    );\n    pbArraySetOperation.value = toElementSimple(arraySetOperation.getValue());\n    pbArraySetOperation.executedAt = toTimeTicket(\n      arraySetOperation.getExecutedAt(),\n    );\n    pbOperation.body.case = 'arraySet';\n    pbOperation.body.value = pbArraySetOperation;\n  } else {\n    throw new YorkieError(Code.ErrUnimplemented, 'unimplemented operation');\n  }\n\n  return pbOperation;\n}\n\n/**\n * `toOperations` converts the given model to Protobuf format.\n */\nfunction toOperations(operations: Array<Operation>): Array<PbOperation> {\n  const pbOperations = [];\n  for (const operation of operations) {\n    pbOperations.push(toOperation(operation));\n  }\n  return pbOperations;\n}\n\n/**\n * `toChange` converts the given model to Protobuf format.\n */\nfunction toChange(change: Change<Indexable>): PbChange {\n  const pbChange = create(PbChangeSchema, {\n    id: toChangeID(change.getID()),\n    message: change.getMessage(),\n  });\n  if (change.hasOperations()) {\n    pbChange.operations = toOperations(change.getOperations());\n  }\n  if (change.hasPresenceChange()) {\n    pbChange.presenceChange = toPresenceChange(change.getPresenceChange()!);\n  }\n  return pbChange;\n}\n\n/**\n * `toChanges` converts the given model to Protobuf format.\n */\nfunction toChanges(changes: Array<Change<Indexable>>): Array<PbChange> {\n  const pbChanges = [];\n  for (const change of changes) {\n    pbChanges.push(toChange(change));\n  }\n  return pbChanges;\n}\n\n/**\n * `toRHTNodes` converts the given model to Protobuf format.\n */\nfunction toRHTNodes(rht: ElementRHT): Array<PbRHTNode> {\n  const pbRHTNodes = [];\n  for (const rhtNode of rht) {\n    pbRHTNodes.push(\n      create(PbRHTNodeSchema, {\n        key: rhtNode.getStrKey(),\n        element: toElement(rhtNode.getValue()),\n      }),\n    );\n  }\n\n  return pbRHTNodes;\n}\n\n/**\n * `toRGANodes` converts the given model to Protobuf format.\n * Includes both live element nodes and dead position nodes.\n */\nfunction toRGANodes(arr: CRDTArray): Array<PbRGANode> {\n  const pbRGANodes = [];\n  for (const rgaNode of arr.getAllRGANodes()) {\n    if (!rgaNode.getElementEntry()) {\n      // Dead position node (abandoned by a move).\n      pbRGANodes.push(\n        create(PbRGANodeSchema, {\n          positionCreatedAt: toTimeTicket(rgaNode.getPositionCreatedAt()),\n          positionRemovedAt: toTimeTicket(rgaNode.getRemovedAt()),\n        }),\n      );\n      continue;\n    }\n\n    const pbNode = create(PbRGANodeSchema, {\n      element: toElement(rgaNode.getValue()),\n    });\n    if (rgaNode.getPositionMovedAt()) {\n      pbNode.positionMovedAt = toTimeTicket(rgaNode.getPositionMovedAt());\n      pbNode.positionCreatedAt = toTimeTicket(rgaNode.getPositionCreatedAt());\n    }\n    pbRGANodes.push(pbNode);\n  }\n\n  return pbRGANodes;\n}\n\n/**\n * `toTextNodes` converts the given model to Protobuf format.\n */\nfunction toTextNodes(\n  rgaTreeSplit: RGATreeSplit<CRDTTextValue>,\n): Array<PbTextNode> {\n  const pbTextNodes = [];\n  // The decoders resolve `insPrevId` against the nodes they have already\n  // decoded -- the Go one rejects a link it cannot find, and a JS decoder\n  // that floor-matched would link the wrong node -- so a link is written\n  // only when its target has already been emitted in this very iteration.\n  // A split product's `insPrev` always precedes it here, so this drops\n  // nothing the re-issue or a snapshot needs; what it does drop is a\n  // dangling link into a node that is no longer in this split (a purged\n  // tombstone), which no decoder could have resolved.\n  const emitted = new Set<string>();\n\n  for (const textNode of rgaTreeSplit) {\n    const pbTextNode = create(PbTextNodeSchema);\n    pbTextNode.id = toTextNodeID(textNode.getID());\n    pbTextNode.value = textNode.getValue().getContent();\n    pbTextNode.removedAt = toTimeTicket(textNode.getRemovedAt());\n    // The removal ledger beyond removed_at. A node whose removed_at says it\n    // all writes nothing, so a character removed by one deletion and never\n    // restored encodes to the same bytes as before.\n    pbTextNode.removalEvents = textNode\n      .getRemovalEvents()\n      .map((t) => toTimeTicket(t)!);\n    if (\n      textNode.getInsPrev() &&\n      emitted.has(textNode.getInsPrevID().toIDString())\n    ) {\n      pbTextNode.insPrevId = toTextNodeID(textNode.getInsPrevID());\n    }\n    emitted.add(textNode.getID().toIDString());\n\n    const pbNodeAttrsMap = pbTextNode.attributes;\n    const attrs = textNode.getValue().getAttrs();\n    for (const attr of attrs) {\n      const pbNodeAttr = create(PbNodeAttrSchema);\n      pbNodeAttr.value = attr.getValue();\n      pbNodeAttr.updatedAt = toTimeTicket(attr.getUpdatedAt());\n      pbNodeAttr.isRemoved = attr.isRemoved();\n      pbNodeAttrsMap[attr.getKey()] = pbNodeAttr;\n    }\n\n    pbTextNodes.push(pbTextNode);\n  }\n\n  return pbTextNodes;\n}\n\n/**\n * `toTreeNodesWhenEdit` converts the given model to Protobuf format.\n */\nfunction toTreeNodesWhenEdit(nodes: Array<CRDTTreeNode>): Array<PbTreeNodes> {\n  const pbTreeNodesList: Array<PbTreeNodes> = [];\n  if (!nodes || !nodes.length) {\n    return pbTreeNodesList;\n  }\n\n  for (const node of nodes) {\n    pbTreeNodesList.push(\n      create(PbTreeNodesSchema, {\n        content: toTreeNodes(node),\n      }),\n    );\n  }\n\n  return pbTreeNodesList;\n}\n\n/**\n * `toRHT` converts the given model to Protobuf format.\n */\nfunction toRHT(rht: RHT): { [key: string]: PbNodeAttr } {\n  const pbRHT: { [key: string]: PbNodeAttr } = {};\n  for (const node of rht) {\n    pbRHT[node.getKey()] = create(PbNodeAttrSchema, {\n      value: node.getValue(),\n      updatedAt: toTimeTicket(node.getUpdatedAt()),\n      isRemoved: node.isRemoved(),\n    });\n  }\n\n  return pbRHT;\n}\n\n/**\n * `toTreeNodes` converts the given model to Protobuf format.\n */\nfunction toTreeNodes(node: CRDTTreeNode): Array<PbTreeNode> {\n  if (!node) {\n    return [];\n  }\n\n  const pbTreeNodes: Array<PbTreeNode> = [];\n  traverseAll(node, (n, depth) => {\n    const pbTreeNode = create(PbTreeNodeSchema, {\n      id: toTreeNodeID(n.id),\n      type: n.type,\n      removedAt: toTimeTicket(n.removedAt),\n      depth,\n    });\n\n    if (n.isText) {\n      pbTreeNode.value = n.value;\n    }\n    if (n.insPrevID) {\n      pbTreeNode.insPrevId = toTreeNodeID(n.insPrevID);\n    }\n    if (n.insNextID) {\n      pbTreeNode.insNextId = toTreeNodeID(n.insNextID);\n    }\n\n    if (n.mergedFrom) {\n      pbTreeNode.mergedFrom = toTreeNodeID(n.mergedFrom);\n    }\n    if (n.mergedAt) {\n      pbTreeNode.mergedAt = toTimeTicket(n.mergedAt);\n    }\n\n    if (n.attrs) {\n      pbTreeNode.attributes = toRHT(n.attrs);\n    }\n\n    pbTreeNodes.push(pbTreeNode);\n  });\n\n  return pbTreeNodes;\n}\n\n/**\n * `toObject` converts the given model to Protobuf format.\n */\nfunction toObject(obj: CRDTObject): PbJSONElement {\n  return create(PbJSONElementSchema, {\n    body: {\n      case: 'jsonObject',\n      value: create(PbJSONElement_JSONObjectSchema, {\n        nodes: toRHTNodes(obj.getRHT()),\n        createdAt: toTimeTicket(obj.getCreatedAt()),\n        movedAt: toTimeTicket(obj.getMovedAt()),\n        removedAt: toTimeTicket(obj.getRemovedAt()),\n      }),\n    },\n  });\n}\n\n/**\n * `toArray` converts the given model to Protobuf format.\n */\nfunction toArray(arr: CRDTArray): PbJSONElement {\n  return create(PbJSONElementSchema, {\n    body: {\n      case: 'jsonArray',\n      value: create(PbJSONElement_JSONArraySchema, {\n        nodes: toRGANodes(arr),\n        createdAt: toTimeTicket(arr.getCreatedAt()),\n        movedAt: toTimeTicket(arr.getMovedAt()),\n        removedAt: toTimeTicket(arr.getRemovedAt()),\n      }),\n    },\n  });\n}\n\n/**\n * `toPrimitive` converts the given model to Protobuf format.\n */\nfunction toPrimitive(primitive: Primitive): PbJSONElement {\n  return create(PbJSONElementSchema, {\n    body: {\n      case: 'primitive',\n      value: create(PbJSONElement_PrimitiveSchema, {\n        type: toValueType(primitive.getType()),\n        value: primitive.toBytes(),\n        createdAt: toTimeTicket(primitive.getCreatedAt()),\n        movedAt: toTimeTicket(primitive.getMovedAt()),\n        removedAt: toTimeTicket(primitive.getRemovedAt()),\n      }),\n    },\n  });\n}\n\n/**\n * `toText` converts the given model to Protobuf format.\n */\nfunction toText(text: CRDTText<Record<string, any>>): PbJSONElement {\n  return create(PbJSONElementSchema, {\n    body: {\n      case: 'text',\n      value: create(PbJSONElement_TextSchema, {\n        nodes: toTextNodes(text.getRGATreeSplit()),\n        createdAt: toTimeTicket(text.getCreatedAt()),\n        movedAt: toTimeTicket(text.getMovedAt()),\n        removedAt: toTimeTicket(text.getRemovedAt()),\n      }),\n    },\n  });\n}\n\n/**\n * `toCounter` converts the given model to Protobuf format.\n */\nfunction toCounter(counter: CRDTCounter): PbJSONElement {\n  return create(PbJSONElementSchema, {\n    body: {\n      case: 'counter',\n      value: create(PbJSONElement_CounterSchema, {\n        type: toCounterType(counter.getType()),\n        value: counter.toBytes(),\n        createdAt: toTimeTicket(counter.getCreatedAt()),\n        movedAt: toTimeTicket(counter.getMovedAt()),\n        removedAt: toTimeTicket(counter.getRemovedAt()),\n        hllRegisters: counter.hllBytes() || new Uint8Array(),\n      }),\n    },\n  });\n}\n\n/**\n * `toTree` converts the given model to Protobuf format.\n */\nfunction toTree(tree: CRDTTree): PbJSONElement {\n  return create(PbJSONElementSchema, {\n    body: {\n      case: 'tree',\n      value: create(PbJSONElement_TreeSchema, {\n        nodes: toTreeNodes(tree.getRoot()),\n        createdAt: toTimeTicket(tree.getCreatedAt()),\n        movedAt: toTimeTicket(tree.getMovedAt()),\n        removedAt: toTimeTicket(tree.getRemovedAt()),\n      }),\n    },\n  });\n}\n\n/**\n * `toElement` converts the given model to Protobuf format.\n */\nexport function toElement(element: CRDTElement): PbJSONElement {\n  if (element instanceof CRDTObject) {\n    return toObject(element);\n  }\n  if (element instanceof CRDTArray) {\n    return toArray(element);\n  }\n  if (element instanceof Primitive) {\n    return toPrimitive(element);\n  }\n  if (element instanceof CRDTText) {\n    return toText(element);\n  }\n  if (element instanceof CRDTCounter) {\n    return toCounter(element);\n  }\n  if (element instanceof CRDTTree) {\n    return toTree(element);\n  }\n\n  throw new YorkieError(Code.ErrUnimplemented, `unimplemented element`);\n}\n\n/**\n * `toChangePack` converts the given model to Protobuf format.\n */\nfunction toChangePack(pack: ChangePack<Indexable>): PbChangePack {\n  return create(PbChangePackSchema, {\n    documentKey: pack.getDocumentKey(),\n    checkpoint: toCheckpoint(pack.getCheckpoint()),\n    isRemoved: pack.getIsRemoved(),\n    changes: toChanges(pack.getChanges()),\n    snapshot: pack.getSnapshot(),\n    versionVector: toVersionVector(pack.getVersionVector()),\n    epoch: pack.getEpoch(),\n  });\n}\n\n/**\n * `toRevisionSummary` converts a protobuf RevisionSummary to a RevisionSummary.\n */\nexport function toRevisionSummary(\n  pbRevision: PbRevisionSummary,\n): RevisionSummary {\n  return {\n    id: pbRevision.id,\n    label: pbRevision.label,\n    description: pbRevision.description,\n    snapshot: pbRevision.snapshot,\n    createdAt: pbRevision.createdAt\n      ? timestampDate(pbRevision.createdAt)\n      : new Date(),\n  };\n}\n\n/**\n * `errorMetadataOf` returns the error metadata of the given connect error.\n */\nexport function errorMetadataOf(error: ConnectError): Record<string, string> {\n  if (!(error instanceof ConnectError)) {\n    return {};\n  }\n\n  // NOTE(chacha912): Currently, we only use the first detail to represent the\n  // error metadata.\n  const infos = error.findDetails(ErrorInfoSchema);\n  for (const info of infos) {\n    return info.metadata;\n  }\n\n  return {};\n}\n\n/**\n * `errorCodeOf` returns the error code of the given connect error.\n */\nexport function errorCodeOf(error: ConnectError): string {\n  return errorMetadataOf(error).code ?? '';\n}\n\n/**\n * `isErrorCode` checks if the error is a ConnectError with the given error code.\n */\nexport function isErrorCode(\n  error: unknown,\n  code: string,\n): error is ConnectError {\n  return error instanceof ConnectError && errorCodeOf(error) === code;\n}\n\n/**\n * `fromChangeID` converts the given Protobuf format to model format.\n */\nfunction fromChangeID(pbChangeID: PbChangeID): ChangeID {\n  // TODO(hackerwins): Remove BigInt conversion. Some of the bigint values are\n  // passed as string in the protobuf. We should fix this in the future.\n  return ChangeID.of(\n    pbChangeID.clientSeq,\n    BigInt(pbChangeID.lamport),\n    toHexString(pbChangeID.actorId),\n    fromVersionVector(pbChangeID.versionVector)!,\n    BigInt(pbChangeID.serverSeq),\n  );\n}\n\n/**\n * `fromVersionVector` converts the given Protobuf format to model format.\n */\nfunction fromVersionVector(\n  pbVersionVector?: PbVersionVector,\n): VersionVector | undefined {\n  if (!pbVersionVector) {\n    return;\n  }\n\n  const vector = new VersionVector();\n  Object.entries(pbVersionVector.vector).forEach(([key, value]) => {\n    const hexKey = bytesToHex(base64ToUint8Array(key));\n    vector.set(hexKey, BigInt(value.toString()));\n  });\n  return vector;\n}\n\n/**\n * `fromTimeTicket` converts the given Protobuf format to model format.\n */\nfunction fromTimeTicket(pbTimeTicket?: PbTimeTicket): TimeTicket | undefined {\n  if (!pbTimeTicket) {\n    return;\n  }\n\n  return TimeTicket.of(\n    BigInt(pbTimeTicket.lamport),\n    pbTimeTicket.delimiter,\n    toHexString(pbTimeTicket.actorId),\n  );\n}\n\n/**\n * `fromPresence` converts the given Protobuf format to model format.\n *\n * Each value should be the JSON encoding of the value, but only the SDKs'\n * write side enforces that: a Go app calling `SetJSON` with non-JSON text, or\n * a client speaking the RPC API directly, can store raw text, and a server\n * older than yorkie#2386 hands it on as-is. Parsing it unguarded threw out of\n * `applyChangePack` before the checkpoint advanced, so the same change came\n * back on every pull. `parseAttrValue` falls back to the raw text, which is\n * also what the server's repair of that value reads as.\n */\nfunction fromPresence<P extends Indexable>(pbPresence: PbPresence): P {\n  const data: Record<string, unknown> = {};\n  Object.entries(pbPresence.data).forEach(([key, value]) => {\n    data[key] = parseAttrValue(value);\n  });\n\n  return data as P;\n}\n\n/**\n * `fromPresenceChange` converts the given Protobuf format to model format.\n */\nfunction fromPresenceChange<P extends Indexable>(\n  pbPresenceChange: PbPresenceChange,\n): PresenceChange<P> {\n  const type = pbPresenceChange.type;\n  if (type === PbPresenceChange_ChangeType.PUT) {\n    const presence = fromPresence<P>(pbPresenceChange.presence!);\n    return {\n      type: PresenceChangeType.Put,\n      presence,\n    };\n  }\n  if (type === PbPresenceChange_ChangeType.PATCH) {\n    // The server folds a patch into the base it holds before storing one, so\n    // a pulled pack does not normally carry a patch. It is decoded anyway --\n    // an echo of a pushed change, or a peer ahead of this SDK, must not fail\n    // the whole pack. There is no `full` on the wire: `Change.execute` merges\n    // the carried keys onto the presence already held for that actor. A\n    // patch can leave `presence` unset, as Go allows\n    // (`api/converter/from_pb.go`, `FromPresenceChange`).\n    const presence = pbPresenceChange.presence\n      ? fromPresence<P>(pbPresenceChange.presence)\n      : ({} as P);\n    return {\n      type: PresenceChangeType.Patch,\n      presence,\n    };\n  }\n  if (type === PbPresenceChange_ChangeType.CLEAR) {\n    return {\n      type: PresenceChangeType.Clear,\n    };\n  }\n  if (\n    type === PbPresenceChange_ChangeType.UNSPECIFIED ||\n    type === PbPresenceChange_ChangeType.DELETE\n  ) {\n    // NOTE: these two types are defined but no SDK sends them. Go still\n    // decodes them, because stored rows go through that path, into a change\n    // that stores an empty presence for the actor (`api/converter/from_pb.go`,\n    // `FromPresenceChange`). Do the same: throwing here fails the pack, and\n    // the same stored change comes back on every pull.\n    return {\n      type: PresenceChangeType.Put,\n      presence: {} as P,\n    };\n  }\n\n  throw new YorkieError(Code.ErrInvalidType, `unsupported type: ${type}`);\n}\n\n/**\n * `fromPresences` converts the given Protobuf format to model format.\n */\nfunction fromPresences<P extends Indexable>(pbPresences: {\n  [key: string]: PbPresence;\n}): Map<ActorID, P> {\n  const presences = new Map<ActorID, P>();\n  Object.entries(pbPresences).forEach(([actorID, pbPresence]) => {\n    presences.set(actorID, fromPresence(pbPresence));\n  });\n  return presences;\n}\n\n/**\n * `fromValueType` converts the given Protobuf format to model format.\n */\nfunction fromValueType(pbValueType: PbValueType): PrimitiveType {\n  switch (pbValueType) {\n    case PbValueType.NULL:\n      return PrimitiveType.Null;\n    case PbValueType.BOOLEAN:\n      return PrimitiveType.Boolean;\n    case PbValueType.INTEGER:\n      return PrimitiveType.Integer;\n    case PbValueType.LONG:\n      return PrimitiveType.Long;\n    case PbValueType.DOUBLE:\n      return PrimitiveType.Double;\n    case PbValueType.STRING:\n      return PrimitiveType.String;\n    case PbValueType.BYTES:\n      return PrimitiveType.Bytes;\n    case PbValueType.DATE:\n      return PrimitiveType.Date;\n  }\n  throw new YorkieError(\n    Code.ErrUnimplemented,\n    `unimplemented value type: ${pbValueType}`,\n  );\n}\n\n/**\n * `fromCounterType` converts the given Protobuf format to model format.\n */\nfunction fromCounterType(pbValueType: PbValueType): CounterType {\n  switch (pbValueType) {\n    case PbValueType.INTEGER_CNT:\n      return CounterType.Int;\n    case PbValueType.LONG_CNT:\n      return CounterType.Long;\n    case PbValueType.INTEGER_DEDUP_CNT:\n      return CounterType.IntDedup;\n  }\n  throw new YorkieError(\n    Code.ErrUnimplemented,\n    `unimplemented value type: ${pbValueType}`,\n  );\n}\n\n/**\n * `fromElementSimple` converts the given Protobuf format to model format.\n */\nfunction fromElementSimple(pbElementSimple: PbJSONElementSimple): CRDTElement {\n  switch (pbElementSimple.type) {\n    case PbValueType.JSON_OBJECT:\n      if (!pbElementSimple.value) {\n        return CRDTObject.create(fromTimeTicket(pbElementSimple.createdAt)!);\n      }\n      return dropSplitLinksInElement(bytesToObject(pbElementSimple.value));\n    case PbValueType.JSON_ARRAY:\n      if (!pbElementSimple.value) {\n        return CRDTArray.create(fromTimeTicket(pbElementSimple.createdAt)!);\n      }\n      return dropSplitLinksInElement(bytesToArray(pbElementSimple.value));\n    case PbValueType.TEXT:\n      return CRDTText.create(\n        RGATreeSplit.create(),\n        fromTimeTicket(pbElementSimple.createdAt)!,\n      );\n    case PbValueType.TREE:\n      return dropSplitLinksInElement(bytesToTree(pbElementSimple.value)!);\n    case PbValueType.NULL:\n    case PbValueType.BOOLEAN:\n    case PbValueType.INTEGER:\n    case PbValueType.LONG:\n    case PbValueType.DOUBLE:\n    case PbValueType.STRING:\n    case PbValueType.BYTES:\n    case PbValueType.DATE:\n      return Primitive.of(\n        Primitive.valueFromBytes(\n          fromValueType(pbElementSimple.type),\n          pbElementSimple.value,\n        ),\n        fromTimeTicket(pbElementSimple.createdAt)!,\n      );\n    case PbValueType.INTEGER_CNT:\n    case PbValueType.LONG_CNT:\n    case PbValueType.INTEGER_DEDUP_CNT:\n      return CRDTCounter.create(\n        fromCounterType(pbElementSimple.type),\n        CRDTCounter.valueFromBytes(\n          fromCounterType(pbElementSimple.type),\n          pbElementSimple.value,\n        ),\n        fromTimeTicket(pbElementSimple.createdAt)!,\n      );\n  }\n}\n\n/**\n * `fromTextNodePos` converts the given Protobuf format to model format.\n */\nfunction fromTextNodePos(pbTextNodePos: PbTextNodePos): RGATreeSplitPos {\n  return RGATreeSplitPos.of(\n    RGATreeSplitNodeID.of(\n      fromTimeTicket(pbTextNodePos.createdAt)!,\n      pbTextNodePos.offset,\n    ),\n    pbTextNodePos.relativeOffset,\n  );\n}\n\n/**\n * `fromTextNodeID` converts the given Protobuf format to model format.\n */\nfunction fromTextNodeID(pbTextNodeID: PbTextNodeID): RGATreeSplitNodeID {\n  return RGATreeSplitNodeID.of(\n    fromTimeTicket(pbTextNodeID.createdAt)!,\n    pbTextNodeID.offset,\n  );\n}\n\n/**\n * `fromTextNode` converts the given Protobuf format to model format.\n */\nfunction fromTextNode(pbTextNode: PbTextNode): RGATreeSplitNode<CRDTTextValue> {\n  const textValue = CRDTTextValue.create(pbTextNode.value);\n  Object.entries(pbTextNode.attributes).forEach(([key, value]) => {\n    textValue\n      .getAttrs()\n      .setInternal(\n        key,\n        value.value,\n        fromTimeTicket(value.updatedAt)!,\n        value.isRemoved,\n      );\n  });\n\n  const textNode = RGATreeSplitNode.create(\n    fromTextNodeID(pbTextNode.id!),\n    textValue,\n  );\n  textNode.setRemovedAt(fromTimeTicket(pbTextNode.removedAt));\n  if (pbTextNode.removalEvents.length) {\n    // A rejected ledger is logged and dropped rather than thrown on, the same\n    // way a malformed HLL payload is below: `fromTextNode` is reached from\n    // `bytesToSnapshot` and from element payloads inside remote operations,\n    // and neither caller has a handler -- throwing would stop this client\n    // from attaching, restoring from local bytes, or ever draining the pull\n    // that carries one peer's bad node, which is a document wedged for good\n    // rather than one node decoded coarsely.\n    //\n    // The cost is a node left with `removed_at` alone, which answers\n    // `isRemovedInView` and `uncancelledRemovalBy` differently from a replica\n    // holding the full ledger. That is a divergence of one node against a\n    // payload no honest peer emits; a wedged document is worse.\n    const drop = (reason: string) =>\n      logger.warn(\n        `discarding malformed removal ledger for text node ${fromTextNodeID(\n          pbTextNode.id!,\n        ).toTestString()}: ${reason}`,\n      );\n    // No count bound: a snapshot carries the ledgers its writer's rules grew,\n    // and one replica deleting and undoing a character while a peer lags\n    // behind GC grows a ledger past any fixed count. Go bounds only the\n    // element payloads of client-pushed operations, on the server.\n    const events: Array<TimeTicket> = [];\n    for (const e of pbTextNode.removalEvents) {\n      const ticket = fromTimeTicket(e);\n      if (!ticket) {\n        break;\n      }\n      events.push(ticket);\n    }\n    if (events.length !== pbTextNode.removalEvents.length) {\n      drop('a ticket is missing');\n      return textNode;\n    }\n    try {\n      // `setRemovalEvents` leaves the node as it was when it refuses, so the\n      // node here still carries `removed_at` alone.\n      textNode.setRemovalEvents(events);\n    } catch (err) {\n      drop((err as Error).message);\n    }\n  }\n  return textNode;\n}\n\n/**\n * `fromTreePos` converts the given Protobuf format to model format.\n */\nfunction fromTreePos(pbTreePos: PbTreePos): CRDTTreePos {\n  return CRDTTreePos.of(\n    fromTreeNodeID(pbTreePos.parentId!),\n    fromTreeNodeID(pbTreePos.leftSiblingId!),\n  );\n}\n\n/**\n * `fromTreeNodeID` converts the given Protobuf format to model format.\n */\nfunction fromTreeNodeID(pbTreeNodeID: PbTreeNodeID): CRDTTreeNodeID {\n  return CRDTTreeNodeID.of(\n    fromTimeTicket(pbTreeNodeID.createdAt)!,\n    pbTreeNodeID.offset,\n  );\n}\n\n/**\n * `fromTreeNodesWhenEdit` converts the given Protobuf format to model format.\n */\nfunction fromTreeNodesWhenEdit(\n  pbTreeNodes: Array<PbTreeNodes>,\n): Array<CRDTTreeNode> | undefined {\n  if (!pbTreeNodes.length) {\n    return;\n  }\n\n  const treeNodes: Array<CRDTTreeNode> = [];\n  for (const node of pbTreeNodes) {\n    const treeNode = fromTreeNodes(node.content);\n    // An entry whose content is empty decodes to no node at all, and neither\n    // keeping nor dropping it is safe. Keeping it puts a hole in the contents\n    // array that every later reader dereferences — `edit` down to `toXML`.\n    // Dropping it changes what the operation means: `CRDTTree.edit` reads an\n    // absent content list as \"delete the range\", so a payload the sender\n    // wrote as an insert would apply here as a deletion, and the split-ticket\n    // delimiters this replica reconstructs would no longer line up with the\n    // sender's. Reject the pack at the boundary instead, the way every other\n    // malformed field in this decoder does.\n    if (!treeNode) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        'tree edit content has an entry with no node',\n      );\n    }\n\n    // Operation content is fully client-controlled and is always freshly\n    // created by the editing client, so it can never be a split product,\n    // carry a merge lineage, or arrive already tombstoned -- `edit` stamps\n    // the lineage on the content it inserts from the merge parent it\n    // resolves locally, and tombstones it itself when the parent it lands in\n    // is removed. Drop the engine-only links and the tombstones the wire\n    // format carries anyway: the tree follows the links as trusted\n    // structural pointers once `edit` registers these nodes in nodeMapByID,\n    // and a node born tombstoned under a live parent is counted as live\n    // content that no GC pair will ever collect. The ATTRIBUTE tombstones\n    // `fromRHT` decodes verbatim are left alone -- the undo copy-reinsert\n    // path produces genuine ones, and stripping them here would diverge from\n    // every other producer and decoder of the same bytes. `CRDTTree.edit`\n    // books them into gc instead, so a crafted one is counted and\n    // collectable; see `clearTombstones`.\n    treeNode.dropEngineOnlyLinks();\n    treeNode.clearTombstones();\n    treeNodes.push(treeNode);\n  }\n\n  return treeNodes;\n}\n\n/**\n * `fromTreeNodes` converts the given Protobuf format to model format.\n */\nfunction fromTreeNodes(\n  pbTreeNodes: Array<PbTreeNode>,\n): CRDTTreeNode | undefined {\n  if (pbTreeNodes.length === 0) {\n    return;\n  }\n\n  const nodes: Array<CRDTTreeNode> = [];\n  for (const pbTreeNode of pbTreeNodes) {\n    nodes.push(fromTreeNode(pbTreeNode));\n  }\n\n  const root = nodes[nodes.length - 1];\n  const depthTable = new Map<number, CRDTTreeNode>();\n  depthTable.set(pbTreeNodes[nodes.length - 1].depth, nodes[nodes.length - 1]);\n  for (let i = nodes.length - 2; i >= 0; i--) {\n    const parent = depthTable.get(pbTreeNodes[i].depth - 1);\n    // The depths come off the wire. A peer can send a node whose parent depth\n    // was never written, or name a text node as a parent; dereferencing the\n    // miss threw a bare TypeError from inside the build. Reject the payload\n    // at the boundary instead, with the error every other malformed field\n    // here raises, so the caller sees a decode failure rather than a crash\n    // part way through assembling a tree.\n    if (!parent || parent.isText) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `invalid tree node depth: ${pbTreeNodes[i].depth}`,\n      );\n    }\n    parent.prepend(nodes[i]);\n    depthTable.set(pbTreeNodes[i].depth, nodes[i]);\n  }\n\n  root.updateDescendantsSize();\n  root.updateDescendantsSize(true);\n\n  // build CRDTTree from the root to construct the links between nodes.\n  return CRDTTree.create(root, InitialTimeTicket).getRoot();\n}\n\n/**\n * `fromRHT` converts the given Protobuf format to model format.\n */\nfunction fromRHT(pbRHT: { [key: string]: PbNodeAttr }): RHT {\n  const rht = RHT.create();\n  for (const [key, pbRHTNode] of Object.entries(pbRHT)) {\n    rht.setInternal(\n      key,\n      pbRHTNode.value,\n      fromTimeTicket(pbRHTNode.updatedAt)!,\n      pbRHTNode.isRemoved,\n    );\n  }\n\n  return rht;\n}\n\n/**\n * `fromTreeNode` converts the given Protobuf format to model format.\n */\nfunction fromTreeNode(pbTreeNode: PbTreeNode): CRDTTreeNode {\n  const id = fromTreeNodeID(pbTreeNode.id!);\n  const node = CRDTTreeNode.create(id, pbTreeNode.type);\n  const pbAttrs = Object.entries(pbTreeNode.attributes);\n  if (node.isText) {\n    node.value = pbTreeNode.value;\n  } else if (pbAttrs.length) {\n    node.attrs = fromRHT(pbTreeNode.attributes);\n  }\n\n  if (pbTreeNode.insPrevId) {\n    node.insPrevID = fromTreeNodeID(pbTreeNode.insPrevId);\n  }\n\n  if (pbTreeNode.insNextId) {\n    node.insNextID = fromTreeNodeID(pbTreeNode.insNextId);\n  }\n\n  if (pbTreeNode.mergedFrom) {\n    node.mergedFrom = fromTreeNodeID(pbTreeNode.mergedFrom);\n  }\n\n  if (pbTreeNode.mergedAt) {\n    node.mergedAt = fromTimeTicket(pbTreeNode.mergedAt);\n  }\n\n  node.removedAt = fromTimeTicket(pbTreeNode.removedAt);\n\n  return node;\n}\n\n/**\n * `fromOperation` converts the given Protobuf format to model format.\n */\nexport function fromOperation(pbOperation: PbOperation): Operation | undefined {\n  if (pbOperation.body.case === 'set') {\n    const pbSetOperation = pbOperation.body.value;\n    return SetOperation.create(\n      pbSetOperation!.key,\n      fromElementSimple(pbSetOperation!.value!),\n      fromTimeTicket(pbSetOperation!.parentCreatedAt)!,\n      fromTimeTicket(pbSetOperation!.executedAt)!,\n    );\n  } else if (pbOperation.body.case === 'add') {\n    const pbAddOperation = pbOperation.body.value;\n    return AddOperation.create(\n      fromTimeTicket(pbAddOperation!.parentCreatedAt)!,\n      fromTimeTicket(pbAddOperation!.prevCreatedAt)!,\n      fromElementSimple(pbAddOperation!.value!),\n      fromTimeTicket(pbAddOperation!.executedAt)!,\n    );\n  } else if (pbOperation.body.case === 'move') {\n    const pbMoveOperation = pbOperation.body.value;\n    return MoveOperation.create(\n      fromTimeTicket(pbMoveOperation!.parentCreatedAt)!,\n      fromTimeTicket(pbMoveOperation!.prevCreatedAt)!,\n      fromTimeTicket(pbMoveOperation!.createdAt)!,\n      fromTimeTicket(pbMoveOperation!.executedAt)!,\n    );\n  } else if (pbOperation.body.case === 'remove') {\n    const pbRemoveOperation = pbOperation.body.value;\n    return RemoveOperation.create(\n      fromTimeTicket(pbRemoveOperation!.parentCreatedAt)!,\n      fromTimeTicket(pbRemoveOperation!.createdAt)!,\n      fromTimeTicket(pbRemoveOperation!.executedAt)!,\n    );\n  } else if (pbOperation.body.case === 'edit') {\n    const pbEditOperation = pbOperation.body.value;\n    const attributes = new Map();\n    Object.entries(pbEditOperation!.attributes).forEach(([key, value]) => {\n      attributes.set(key, value);\n    });\n    const executedAt = fromTimeTicket(pbEditOperation!.executedAt)!;\n\n    const fromPbSpan = (pbSpan: PbRestoreSpan): RestoreSpan<CRDTTextValue> => {\n      // A span addresses content by insertion identity, so it is malformed\n      // without a `createdAt`, and `RGATreeSplit.restore` slices `content` by\n      // `cursor - span.start`, so `[start, end)` has to be an ordered interval\n      // exactly covering it. Reject both here, as the server's\n      // `fromRestoreSpans` does, instead of failing deep in the restore path.\n      if (\n        !pbSpan.createdAt ||\n        !Number.isInteger(pbSpan.start) ||\n        !Number.isInteger(pbSpan.end) ||\n        pbSpan.start < 0 ||\n        pbSpan.end < pbSpan.start ||\n        pbSpan.end - pbSpan.start !== pbSpan.content.length\n      ) {\n        throw new YorkieError(\n          Code.ErrInvalidArgument,\n          'malformed restore span: missing timestamp or invalid range',\n        );\n      }\n      const createdAt = fromTimeTicket(pbSpan.createdAt)!;\n      const value = CRDTTextValue.create(pbSpan.content);\n      for (const [key, attr] of Object.entries(pbSpan.attributes)) {\n        value.setAttr(key, attr, executedAt);\n      }\n      return {\n        createdAt,\n        start: pbSpan.start,\n        end: pbSpan.end,\n        value,\n      };\n    };\n    let restoreSpans: Array<RestoreSpan<CRDTTextValue>> | undefined;\n    let retombstoneSpans: Array<RestoreSpan<CRDTTextValue>> | undefined;\n    let restoreMode: 'restore' | 'retombstone' | undefined;\n    if (\n      pbEditOperation!.restoreSpans.length ||\n      pbEditOperation!.retombstoneSpans.length\n    ) {\n      restoreSpans = pbEditOperation!.restoreSpans.map(fromPbSpan);\n      retombstoneSpans = pbEditOperation!.retombstoneSpans.map(fromPbSpan);\n      restoreMode =\n        pbEditOperation!.restoreMode === PbRestoreMode.RETOMBSTONE\n          ? 'retombstone'\n          : 'restore';\n    }\n\n    return EditOperation.create(\n      fromTimeTicket(pbEditOperation!.parentCreatedAt)!,\n      fromTextNodePos(pbEditOperation!.from!),\n      fromTextNodePos(pbEditOperation!.to!),\n      pbEditOperation!.content,\n      attributes,\n      executedAt,\n      restoreMode ? true : undefined,\n      restoreSpans,\n      restoreMode,\n      retombstoneSpans,\n    );\n  } else if (pbOperation.body.case === 'style') {\n    const pbStyleOperation = pbOperation.body.value;\n    const attributes = new Map<string, string>();\n    Object.entries(pbStyleOperation!.attributes).forEach(([key, value]) => {\n      attributes.set(key, value);\n    });\n    const attributesToRemove = pbStyleOperation!.attributesToRemove ?? [];\n\n    return new StyleOperation(\n      fromTimeTicket(pbStyleOperation!.parentCreatedAt)!,\n      fromTextNodePos(pbStyleOperation!.from!),\n      fromTextNodePos(pbStyleOperation!.to!),\n      attributes,\n      attributesToRemove,\n      fromTimeTicket(pbStyleOperation!.executedAt)!,\n    );\n  } else if (pbOperation.body.case === 'increase') {\n    const pbIncreaseOperation = pbOperation.body.value;\n    return IncreaseOperation.create(\n      fromTimeTicket(pbIncreaseOperation!.parentCreatedAt)!,\n      fromElementSimple(pbIncreaseOperation!.value!),\n      fromTimeTicket(pbIncreaseOperation!.executedAt)!,\n      pbIncreaseOperation!.actor || undefined,\n    );\n  } else if (pbOperation.body.case === 'treeEdit') {\n    const pbTreeEditOperation = pbOperation.body.value;\n    let treeRestoreSpans: Array<TreeRestoreSpan> | undefined;\n    let treeRetombstoneSpans: Array<TreeRestoreSpan> | undefined;\n    let treeRestoreMode: 'restore' | 'retombstone' | undefined;\n    if (\n      pbTreeEditOperation!.restoreSpans.length ||\n      pbTreeEditOperation!.retombstoneSpans.length\n    ) {\n      treeRestoreSpans = pbTreeEditOperation!.restoreSpans.map(\n        fromPbTreeRestoreSpan,\n      );\n      treeRetombstoneSpans = pbTreeEditOperation!.retombstoneSpans.map(\n        fromPbTreeRestoreSpan,\n      );\n      treeRestoreMode =\n        pbTreeEditOperation!.restoreMode === PbRestoreMode.RETOMBSTONE\n          ? 'retombstone'\n          : 'restore';\n    }\n    const treeEditExecutedAt = fromTimeTicket(pbTreeEditOperation!.executedAt)!;\n    const treeEditContents = fromTreeNodesWhenEdit(\n      pbTreeEditOperation!.contents,\n    );\n    const treeEdit = TreeEditOperation.create(\n      fromTimeTicket(pbTreeEditOperation!.parentCreatedAt)!,\n      fromTreePos(pbTreeEditOperation!.from!),\n      fromTreePos(pbTreeEditOperation!.to!),\n      treeEditContents,\n      pbTreeEditOperation!.splitLevel,\n      treeEditExecutedAt,\n      treeRestoreMode ? true : undefined,\n      undefined,\n      undefined,\n      treeRestoreSpans,\n      treeRestoreMode,\n      treeRetombstoneSpans,\n    );\n    // Split tickets are read back as sent, the way yorkie's converter reads\n    // them: the server applies them verbatim, so a replica that rewrote or\n    // refused a ticket here would mint different ids than the snapshot holds.\n    //\n    // This is not a trust boundary, and no check here could make it one. The\n    // only reference a decoder has for these tickets is `executedAt`, off the\n    // same wire, so a shape check would read one of the sender's fields\n    // against another; and the content node ids and restore-span ids beside\n    // them name nodes just as freely. What bounds a hostile id is at the point\n    // of use -- `dropDuplicateContents` and `registerNode` in `CRDTTree`.\n    treeEdit.setSplitTickets(\n      pbTreeEditOperation!.splitTickets.map(\n        (ticket) => fromTimeTicket(ticket)!,\n      ),\n    );\n    return treeEdit;\n  } else if (pbOperation.body.case === 'treeStyle') {\n    const pbTreeStyleOperation = pbOperation.body.value;\n    const attributes = new Map<string, string>();\n    Object.entries(pbTreeStyleOperation!.attributes).forEach(([key, value]) => {\n      attributes.set(key, value);\n    });\n\n    // A sender may set both fields at once -- that is how it encodes the\n    // reverse of a style that overwrote some attributes and added others --\n    // so read both rather than letting either one shadow the other.\n    return new TreeStyleOperation(\n      fromTimeTicket(pbTreeStyleOperation!.parentCreatedAt)!,\n      fromTreePos(pbTreeStyleOperation!.from!),\n      fromTreePos(pbTreeStyleOperation!.to!),\n      attributes,\n      [...(pbTreeStyleOperation!.attributesToRemove ?? [])],\n      fromTimeTicket(pbTreeStyleOperation!.executedAt)!,\n    );\n  } else if (pbOperation.body.case === 'arraySet') {\n    const pbArraySetOperation = pbOperation.body.value;\n    return ArraySetOperation.create(\n      fromTimeTicket(pbArraySetOperation!.parentCreatedAt)!,\n      fromTimeTicket(pbArraySetOperation!.createdAt)!,\n      fromElementSimple(pbArraySetOperation!.value!),\n      fromTimeTicket(pbArraySetOperation!.executedAt)!,\n    );\n  } else {\n    throw new YorkieError(Code.ErrUnimplemented, `unimplemented operation`);\n  }\n}\n\n/**\n * `fromOperations` converts the given Protobuf format to model format.\n */\nfunction fromOperations(pbOperations: Array<PbOperation>): Array<Operation> {\n  const operations = [];\n  for (const pbOperation of pbOperations) {\n    const operation = fromOperation(pbOperation);\n    if (operation) {\n      operations.push(operation);\n    }\n  }\n  return operations;\n}\n\n/**\n * `fromChanges` converts the given Protobuf format to model format.\n */\nfunction fromChanges<P extends Indexable>(\n  pbChanges: Array<PbChange>,\n): Array<Change<P>> {\n  const changes: Array<Change<P>> = [];\n\n  for (const pbChange of pbChanges) {\n    changes.push(\n      Change.create({\n        id: fromChangeID(pbChange.id!),\n        operations: fromOperations(pbChange.operations),\n        presenceChange: pbChange.presenceChange\n          ? fromPresenceChange(pbChange.presenceChange!)\n          : undefined,\n        message: pbChange.message,\n      }),\n    );\n  }\n\n  return changes;\n}\n\n/**\n * `fromCheckpoint` converts the given Protobuf format to model format.\n */\nfunction fromCheckpoint(pbCheckpoint: PbCheckpoint): Checkpoint {\n  return Checkpoint.of(BigInt(pbCheckpoint.serverSeq), pbCheckpoint.clientSeq);\n}\n\n/**\n * `fromChangePack` converts the given Protobuf format to model format.\n */\nfunction fromChangePack<P extends Indexable>(\n  pbPack: PbChangePack,\n): ChangePack<P> {\n  return ChangePack.create<P>(\n    pbPack.documentKey!,\n    fromCheckpoint(pbPack.checkpoint!),\n    pbPack.isRemoved,\n    fromChanges(pbPack.changes),\n    fromVersionVector(pbPack.versionVector),\n    pbPack.snapshot,\n    pbPack.epoch,\n    pbPack.capabilities,\n  );\n}\n\n/**\n * `fromObject` converts the given Protobuf format to model format.\n */\nfunction fromObject(pbObject: PbJSONElement_JSONObject): CRDTObject {\n  const rht = new ElementRHT();\n  for (const pbRHTNode of pbObject.nodes) {\n    const value = fromElement(pbRHTNode.element!);\n    rht.set(pbRHTNode.key, value, value.getPositionedAt());\n  }\n\n  const obj = new CRDTObject(fromTimeTicket(pbObject.createdAt)!, rht);\n  obj.setMovedAt(fromTimeTicket(pbObject.movedAt));\n  obj.setRemovedAt(fromTimeTicket(pbObject.removedAt));\n  return obj;\n}\n\n/**\n * `fromArray` converts the given Protobuf format to model format.\n */\nfunction fromArray(pbArray: PbJSONElement_JSONArray): CRDTArray {\n  const rgaTreeList = new RGATreeList();\n  for (const pbRGANode of pbArray.nodes) {\n    if (!pbRGANode.element) {\n      // Dead position node (abandoned by a move).\n      if (!pbRGANode.positionCreatedAt || !pbRGANode.positionRemovedAt) {\n        throw new YorkieError(\n          Code.ErrInvalidArgument,\n          'dead RGA position node missing position timestamps',\n        );\n      }\n      const posCreatedAt = fromTimeTicket(pbRGANode.positionCreatedAt)!;\n      const posRemovedAt = fromTimeTicket(pbRGANode.positionRemovedAt)!;\n      rgaTreeList.addDeadPosition(posCreatedAt, posRemovedAt);\n      continue;\n    }\n\n    const elem = fromElement(pbRGANode.element);\n    const posMovedAt = fromTimeTicket(pbRGANode.positionMovedAt);\n\n    if (posMovedAt) {\n      if (!pbRGANode.positionCreatedAt) {\n        throw new YorkieError(\n          Code.ErrInvalidArgument,\n          'moved RGA node missing position_created_at',\n        );\n      }\n      const posCreatedAt = fromTimeTicket(pbRGANode.positionCreatedAt)!;\n      rgaTreeList.addMovedElement(elem, posCreatedAt, posMovedAt);\n    } else {\n      rgaTreeList.insert(elem);\n    }\n  }\n\n  const arr = new CRDTArray(fromTimeTicket(pbArray.createdAt)!, rgaTreeList);\n  arr.setMovedAt(fromTimeTicket(pbArray.movedAt));\n  arr.setRemovedAt(fromTimeTicket(pbArray.removedAt));\n  return arr;\n}\n\n/**\n * `fromPrimitive` converts the given Protobuf format to model format.\n */\nfunction fromPrimitive(pbPrimitive: PbJSONElement_Primitive): Primitive {\n  const primitive = Primitive.of(\n    Primitive.valueFromBytes(\n      fromValueType(pbPrimitive.type),\n      pbPrimitive.value,\n    ),\n    fromTimeTicket(pbPrimitive.createdAt)!,\n  );\n  primitive.setMovedAt(fromTimeTicket(pbPrimitive.movedAt));\n  primitive.setRemovedAt(fromTimeTicket(pbPrimitive.removedAt));\n  return primitive;\n}\n\n/**\n * `fromText` converts the given Protobuf format to model format.\n */\nfunction fromText<A extends Indexable>(\n  pbText: PbJSONElement_Text,\n): CRDTText<A> {\n  const rgaTreeSplit = new RGATreeSplit<CRDTTextValue>();\n\n  // A Text can arrive inside a client-supplied Set/Add/ArraySet payload, where\n  // its split links are as untrusted as the tree links `dropSplitLinksInElement`\n  // strips from the same payloads. They are kept rather than dropped -- such a\n  // payload can be a copy of real document state, the Text a reverse of Remove\n  // restores, whose nodes a later Edit still targets -- so each link is\n  // resolved by EXACT id against the nodes already decoded. `findNode` is\n  // `findFloorNode`, which answers a missing id with whatever node sorts below\n  // it: a dangling or forward link would silently become a link to the wrong\n  // node. An unresolvable link is dropped instead, which is what a Text with no\n  // links at all already looks like.\n  //\n  // Being decoded earlier is not enough. Every producer of a link points it at\n  // an earlier piece of the SAME insertion -- `splitNode` links a split product\n  // to its left half and relinks the following piece, and the restore path\n  // links a recreated fragment to the piece covering the offset below it -- so\n  // a link naming another insertion, or an offset at or above this node's own,\n  // is one no local edit could have made. Accepting it would let a forged\n  // payload mis-link a node, and a later Edit resolving through\n  // `findFloorNodePreferToLeft` would then compute an out-of-range offset.\n  const decoded = new Map<string, RGATreeSplitNode<CRDTTextValue>>();\n  let prev = rgaTreeSplit.getHead();\n  for (const pbNode of pbText.nodes) {\n    const current = rgaTreeSplit.insertAfter(prev, fromTextNode(pbNode));\n    if (pbNode.insPrevId) {\n      const id = current.getID();\n      const insPrevID = fromTextNodeID(pbNode.insPrevId);\n      const insPrev =\n        insPrevID.hasSameCreatedAt(id) && insPrevID.getOffset() < id.getOffset()\n          ? decoded.get(insPrevID.toIDString())\n          : undefined;\n      if (insPrev) {\n        current.setInsPrev(insPrev);\n      }\n    }\n    decoded.set(current.getID().toIDString(), current);\n    prev = current;\n  }\n  const text = new CRDTText<A>(rgaTreeSplit, fromTimeTicket(pbText.createdAt)!);\n  text.setMovedAt(fromTimeTicket(pbText.movedAt));\n  text.setRemovedAt(fromTimeTicket(pbText.removedAt));\n  return text;\n}\n\n/**\n * `fromCounter` converts the given Protobuf format to model format.\n */\nfunction fromCounter(pbCounter: PbJSONElement_Counter): CRDTCounter {\n  const counter = CRDTCounter.create(\n    fromCounterType(pbCounter.type),\n    CRDTCounter.valueFromBytes(\n      fromCounterType(pbCounter.type),\n      pbCounter.value,\n    ),\n    fromTimeTicket(pbCounter.createdAt)!,\n  );\n  counter.setMovedAt(fromTimeTicket(pbCounter.movedAt));\n  counter.setRemovedAt(fromTimeTicket(pbCounter.removedAt));\n  if (counter.isDedup() && pbCounter.hllRegisters.length > 0) {\n    // A rejected payload is logged and dropped rather than thrown on: snapshot\n    // decode has no handler, so throwing would stop this client from opening\n    // the document at all over one peer's malformed counter.\n    if (!counter.restoreHLL(pbCounter.hllRegisters)) {\n      logger.warn(\n        `discarding malformed HLL registers for counter ${counter\n          .getCreatedAt()\n          .toTestString()}: ${pbCounter.hllRegisters.length} bytes`,\n      );\n    }\n  }\n  return counter;\n}\n\n/**\n * `fromTree` converts the given Protobuf format to model format.\n */\nfunction fromTree(pbTree: PbJSONElement_Tree): CRDTTree {\n  const root = fromTreeNodes(pbTree.nodes);\n  const tree = CRDTTree.create(root!, fromTimeTicket(pbTree.createdAt)!);\n  // `toTree` writes both tickets and `CRDTElement.getMetaUsage` charges both,\n  // so dropping them here makes a tree restored from a snapshot smaller than\n  // the same tree before the restore -- one ticket per stamp. Every other\n  // `from*` restores them; this one did not.\n  tree.setMovedAt(fromTimeTicket(pbTree.movedAt));\n  tree.setRemovedAt(fromTimeTicket(pbTree.removedAt));\n  return tree;\n}\n\n/**\n * `fromElement` converts the given Protobuf format to model format.\n */\nexport function fromElement(pbElement: PbJSONElement): CRDTElement {\n  if (pbElement.body.case === 'jsonObject') {\n    return fromObject(pbElement.body.value!);\n  } else if (pbElement.body.case === 'jsonArray') {\n    return fromArray(pbElement.body.value!);\n  } else if (pbElement.body.case === 'primitive') {\n    return fromPrimitive(pbElement.body.value!);\n  } else if (pbElement.body.case === 'text') {\n    return fromText(pbElement.body.value!);\n  } else if (pbElement.body.case === 'counter') {\n    return fromCounter(pbElement.body.value!);\n  } else if (pbElement.body.case === 'tree') {\n    return fromTree(pbElement.body.value!);\n  } else {\n    throw new YorkieError(Code.ErrUnimplemented, `unimplemented element`);\n  }\n}\n\n/**\n * `fromSchemaRules` converts the given Protobuf format to model format.\n */\nfunction fromSchemaRules(pbRules: Array<PbRule>): Array<Rule> {\n  return pbRules.map((pbRule) => {\n    const rule: Record<string, unknown> = {\n      path: pbRule.path,\n      type: pbRule.type,\n    };\n    if (pbRule.treeNodes && pbRule.treeNodes.length > 0) {\n      rule.treeNodes = pbRule.treeNodes.map((tn) => ({\n        nodeType: tn.nodeType,\n        content: tn.content,\n        marks: tn.marks,\n        group: tn.group,\n      }));\n    }\n    return rule as Rule;\n  });\n}\n\n/**\n * `bytesToSnapshot` creates a Snapshot from the given byte array.\n */\nfunction bytesToSnapshot<P extends Indexable>(\n  bytes?: Uint8Array,\n): {\n  root: CRDTObject;\n  presences: Map<ActorID, P>;\n} {\n  if (!bytes) {\n    return {\n      root: CRDTObject.create(InitialTimeTicket),\n      presences: new Map(),\n    };\n  }\n\n  const snapshot = fromBinary(PbSnapshotSchema, bytes);\n  return {\n    root: fromElement(snapshot.root!) as CRDTObject,\n    presences: fromPresences<P>(snapshot.presences),\n  };\n}\n\n/**\n * `snapshotToBytes` converts the given root and presences into a byte array.\n * It is the reverse of `bytesToSnapshot`: the produced bytes decode back into\n * the same `{ root, presences }` shape via the shared `Snapshot` message.\n */\nfunction snapshotToBytes<P extends Indexable>(\n  root: CRDTObject,\n  presences: Map<ActorID, P>,\n): Uint8Array {\n  const pbPresences: { [key: string]: PbPresence } = {};\n  for (const [actorID, presence] of presences) {\n    pbPresences[actorID] = toPresence(presence);\n  }\n\n  const snapshot = create(PbSnapshotSchema, {\n    root: toElement(root),\n    presences: pbPresences,\n  });\n  return toBinary(PbSnapshotSchema, snapshot);\n}\n\n/**\n * `versionVectorToHex` converts the given VersionVector to bytes.\n */\nfunction versionVectorToHex(vector: VersionVector): string {\n  const pbVersionVector = toVersionVector(vector)!;\n\n  return bytesToHex(toBinary(PbVersionVectorSchema, pbVersionVector));\n}\n\n/**\n * `hexToVersionVector` creates a VersionVector from the given bytes.\n */\nfunction hexToVersionVector(hex: string): VersionVector {\n  const bytes = hexToBytes(hex);\n  const pbVersionVector = fromBinary(PbVersionVectorSchema, bytes);\n\n  return fromVersionVector(pbVersionVector)!;\n}\n\n/**\n * `bytesToObject` creates an JSONObject from the given byte array.\n */\nfunction bytesToObject(bytes?: Uint8Array): CRDTObject {\n  if (!bytes) {\n    throw new YorkieError(Code.ErrInvalidArgument, 'bytes is empty');\n  }\n\n  const pbElement = fromBinary(PbJSONElementSchema, bytes);\n  return fromObject(pbElement.body.value! as PbJSONElement_JSONObject);\n}\n\n/**\n * `objectToBytes` converts the given JSONObject to byte array.\n */\nfunction objectToBytes(obj: CRDTObject): Uint8Array {\n  return toBinary(PbJSONElementSchema, toElement(obj));\n}\n\n/**\n * `bytesToArray` creates an CRDTArray from the given bytes.\n */\nfunction bytesToArray(bytes?: Uint8Array): CRDTArray {\n  if (!bytes) {\n    throw new YorkieError(Code.ErrInvalidArgument, 'bytes is empty');\n  }\n\n  const pbElement = fromBinary(PbJSONElementSchema, bytes);\n  return fromArray(pbElement.body.value! as PbJSONElement_JSONArray);\n}\n\n/**\n * `arrayToBytes` converts the given CRDTArray to bytes.\n */\nfunction arrayToBytes(array: CRDTArray): Uint8Array {\n  return toBinary(PbJSONElementSchema, toArray(array));\n}\n\n/**\n * `bytesToTree` creates an CRDTTree from the given bytes.\n */\nfunction bytesToTree(bytes?: Uint8Array): CRDTTree {\n  if (!bytes) {\n    throw new YorkieError(Code.ErrInvalidArgument, 'bytes is empty');\n  }\n\n  const pbElement = fromBinary(PbJSONElementSchema, bytes);\n  return fromTree(pbElement.body.value! as PbJSONElement_Tree);\n}\n\n/**\n * `treeToBytes` converts the given tree to bytes.\n */\nfunction treeToBytes(tree: CRDTTree): Uint8Array {\n  return toBinary(PbJSONElementSchema, toTree(tree));\n}\n\n/**\n * `bytesToHex` creates an hex string from the given byte array.\n */\nfunction bytesToHex(bytes?: Uint8Array): string {\n  if (!bytes) {\n    return '';\n  }\n\n  return Array.from(bytes)\n    .map((b) => b.toString(16).padStart(2, '0'))\n    .join('');\n}\n\n/**\n * `toHexString` converts the given byte array to hex string.\n */\nfunction toHexString(bytes: Uint8Array): string {\n  return bytesToHex(bytes);\n}\n\n/**\n * `hexToBytes` converts the given hex string to byte array.\n */\nfunction hexToBytes(hex: string): Uint8Array {\n  return new Uint8Array(\n    hex.match(/.{1,2}/g)!.map((byte) => parseInt(byte, 16)),\n  );\n}\n\n/**\n * `base64ToUint8Array` converts the given base64 string to Uint8Array.\n */\nfunction base64ToUint8Array(base64: string): Uint8Array {\n  if (typeof window !== 'undefined' && typeof window.atob === 'function') {\n    const binary = window.atob(base64);\n    const len = binary.length;\n    const bytes = new Uint8Array(len);\n    for (let i = 0; i < len; i++) {\n      bytes[i] = binary.charCodeAt(i);\n    }\n    return bytes;\n  } else if (\n    typeof globalThis !== 'undefined' &&\n    typeof (globalThis as any).Buffer !== 'undefined'\n  ) {\n    const Buffer = (globalThis as any).Buffer;\n    return new Uint8Array(Buffer.from(base64, 'base64'));\n  } else {\n    throw new Error('No base64 decoder available');\n  }\n}\n\n/**\n * `toUnit8Array` converts the given hex string to byte array.\n */\nfunction toUint8Array(hex: string): Uint8Array {\n  return hexToBytes(hex);\n}\n\n/**\n * `uint8ArrayToBase64` converts the given Uint8Array to base64 string.\n */\nfunction uint8ArrayToBase64(bytes: Uint8Array): string {\n  if (typeof window !== 'undefined' && typeof window.btoa === 'function') {\n    let binary = '';\n    for (let i = 0; i < bytes.byteLength; i++) {\n      binary += String.fromCharCode(bytes[i]);\n    }\n    return window.btoa(binary);\n  } else if (\n    typeof globalThis !== 'undefined' &&\n    typeof (globalThis as any).Buffer !== 'undefined'\n  ) {\n    const Buffer = (globalThis as any).Buffer;\n    return Buffer.from(bytes).toString('base64');\n  } else {\n    throw new Error('No base64 encoder available');\n  }\n}\n/**\n * `bytesToChangeID` creates a ChangeID from the given bytes.\n */\nfunction bytesToChangeID(bytes: Uint8Array): ChangeID {\n  const pbChangeID = fromBinary(PbChangeIDSchema, bytes);\n  return fromChangeID(pbChangeID);\n}\n\n/**\n * `bytesToOperation` creates an Operation from the given bytes.\n */\nfunction bytesToOperation(bytes: Uint8Array): Operation {\n  const pbOperation = fromBinary(PbOperationSchema, bytes);\n  return fromOperation(pbOperation)!;\n}\n\n/**\n * `converter` is a converter that converts the given model to protobuf format.\n * is also used to convert models to bytes and vice versa.\n */\nexport const converter = {\n  fromPresence,\n  toChangePack,\n  fromChangePack,\n  fromChanges,\n  toTreeNodes,\n  fromTreeNodes,\n  objectToBytes,\n  bytesToObject,\n  bytesToSnapshot,\n  snapshotToBytes,\n  bytesToHex,\n  hexToBytes,\n  toHexString,\n  toUint8Array,\n  toOperation,\n  toChangeID,\n  bytesToChangeID,\n  bytesToOperation,\n  versionVectorToHex,\n  hexToVersionVector,\n  fromSchemaRules,\n  toRevisionSummary,\n  changeIDToBinary: (changeID: ChangeID) =>\n    toBinary(PbChangeIDSchema, toChangeID(changeID)),\n  operationToBinary: (op: Operation) =>\n    toBinary(PbOperationSchema, toOperation(op)),\n};\n","/*\n * Copyright 2020 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport type UUID = string;\n\n/**\n * `webCrypto` returns the ambient Web Crypto implementation, if the runtime\n * has one. Browsers and Node >= 19 expose it as `globalThis.crypto`; the\n * lookup is guarded so a runtime without it still loads this module, and it\n * is read per call so {@link hasStrongRandomSource} cannot disagree with what\n * {@link uuid} will actually draw from.\n */\nfunction webCrypto(): Crypto | undefined {\n  return typeof globalThis !== 'undefined' ? globalThis.crypto : undefined;\n}\n\n/**\n * `hasStrongRandomSource` reports whether {@link uuid} draws from the\n * runtime's CSPRNG rather than the `Math.random` fallback. A caller that\n * needs a generated UUID to be unguessable -- not merely unique -- has to\n * check this before relying on it; see {@link randomBytes}.\n */\nexport function hasStrongRandomSource(): boolean {\n  const crypto = webCrypto();\n  return !!(crypto?.randomUUID || crypto?.getRandomValues);\n}\n\nconst HEX: Array<string> = [];\nfor (let i = 0; i < 256; i++) {\n  HEX.push((i + 0x100).toString(16).slice(1));\n}\n\n/**\n * `randomBytes` fills 16 bytes from the strongest source the runtime offers.\n *\n * `crypto.getRandomValues` is a CSPRNG and is what we want: the default value\n * of `ClientOptions.key` comes from {@link uuid}, and that key is an\n * identifier the server trusts verbatim — a predictable one lets another\n * client of the same project activate under the same derived actor. Only when\n * no Web Crypto is present at all do we fall back to `Math.random`, which is\n * *not* unguessable; such a runtime must pass its own `key` rather than rely\n * on the default.\n */\nfunction randomBytes(): Uint8Array {\n  const bytes = new Uint8Array(16);\n  const crypto = webCrypto();\n  if (crypto?.getRandomValues) {\n    crypto.getRandomValues(bytes);\n    return bytes;\n  }\n  for (let i = 0; i < bytes.length; i++) {\n    bytes[i] = (Math.random() * 256) | 0;\n  }\n  return bytes;\n}\n\n/**\n * `uuid` generates a random (version 4) UUID string, using the runtime's\n * CSPRNG. See {@link randomBytes} for the fallback and why it matters.\n * @see http://www.ietf.org/rfc/rfc4122.txt\n */\nexport function uuid(): UUID {\n  const crypto = webCrypto();\n  if (crypto?.randomUUID) {\n    return crypto.randomUUID();\n  }\n\n  const b = randomBytes();\n  // Version 4 (random) and RFC 4122 variant bits.\n  b[6] = (b[6] & 0x0f) | 0x40;\n  b[8] = (b[8] & 0x3f) | 0x80;\n\n  return (\n    HEX[b[0]] +\n    HEX[b[1]] +\n    HEX[b[2]] +\n    HEX[b[3]] +\n    '-' +\n    HEX[b[4]] +\n    HEX[b[5]] +\n    '-' +\n    HEX[b[6]] +\n    HEX[b[7]] +\n    '-' +\n    HEX[b[8]] +\n    HEX[b[9]] +\n    '-' +\n    HEX[b[10]] +\n    HEX[b[11]] +\n    HEX[b[12]] +\n    HEX[b[13]] +\n    HEX[b[14]] +\n    HEX[b[15]]\n  );\n}\n","/*\n * Copyright 2026 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { fromBinary, toBinary } from '@bufbuild/protobuf';\nimport { reflect, type ReflectMessage } from '@bufbuild/protobuf/reflect';\nimport {\n  converter,\n  fromElement,\n  fromOperation,\n  toElement,\n} from '@yorkie-js/sdk/src/api/converter';\nimport {\n  JSONElementSchema as PbJSONElementSchema,\n  JSONElementSimple as PbJSONElementSimple,\n  OperationSchema as PbOperationSchema,\n  TimeTicket as PbTimeTicket,\n  ValueType as PbValueType,\n} from '@yorkie-js/sdk/src/api/yorkie/v1/resources_pb';\nimport { ActorID } from '@yorkie-js/sdk/src/document/time/actor_id';\nimport { Operation } from '@yorkie-js/sdk/src/document/operation/operation';\nimport { SetOperation } from '@yorkie-js/sdk/src/document/operation/set_operation';\nimport { AddOperation } from '@yorkie-js/sdk/src/document/operation/add_operation';\nimport { ArraySetOperation } from '@yorkie-js/sdk/src/document/operation/array_set_operation';\nimport { CRDTText } from '@yorkie-js/sdk/src/document/crdt/text';\nimport { Code, YorkieError } from '@yorkie-js/sdk/src/util/error';\n\nconst TimeTicketTypeName = 'yorkie.v1.TimeTicket';\nconst JSONElementSimpleTypeName = 'yorkie.v1.JSONElementSimple';\n\n/**\n * `reissueOperations` returns copies of the given operations in which every\n * ticket issued by the actor `from` names the actor `to` instead. Lamports and\n * delimiters are kept, so the order among the tickets is unchanged. A ticket\n * with lamport 0 is never re-issued: that is `InitialTimeTicket`, the root\n * object's and every sentinel node's identity, shared by all replicas.\n *\n * It goes through the wire format on purpose: the operations come back as the\n * server would decode them (except a Text value, see below), and the walk\n * reaches every TimeTicket the protocol carries -- positions, node IDs, split\n * tickets, restore spans and the elements nested inside a Set/Add/ArraySet\n * value -- without a per-type list that a new field could silently fall out\n * of.\n *\n * It is only sound when every ticket naming `from` was issued locally and has\n * never left this replica, which is the case for a document that has never\n * synced. See docs/design/pre-attach-ticket-reissue.md.\n */\nexport function reissueOperations(\n  ops: Array<Operation>,\n  from: ActorID,\n  to: ActorID,\n): Array<Operation> {\n  const reissuer = new TicketReissuer(from, to);\n\n  const reissued: Array<Operation> = [];\n  for (const op of ops) {\n    const pbOp = converter.toOperation(op);\n    reissuer.walk(reflect(PbOperationSchema, pbOp));\n    const decoded = fromOperation(pbOp);\n    if (!decoded) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `reissue operations: ${op.constructor.name} did not decode`,\n      );\n    }\n\n    // The wire drops a Text value's content: it carries the Text alone and\n    // the Edits that fill it. A Set/Add/ArraySet that restores a removed\n    // Text -- the reverse of a Remove, run by Undo -- carries the content,\n    // and a later Edit in the same document may target its nodes. Re-issue\n    // such a value through its full snapshot encoding instead, so the local\n    // root rebuilt from these operations keeps what the user sees.\n    reissued.push(reissuer.reissueTextValue(op, decoded));\n  }\n  return reissued;\n}\n\n/**\n * `TicketReissuer` rewrites the actor of the TimeTickets in a protobuf\n * message.\n */\nclass TicketReissuer {\n  private from: ActorID;\n  private to: ActorID;\n\n  constructor(from: ActorID, to: ActorID) {\n    this.from = from;\n    this.to = to;\n  }\n\n  /**\n   * `reissueTextValue` returns the decoded operation with its Text value\n   * replaced by a re-issued copy of the original one, content included. Any\n   * other operation is returned unchanged.\n   */\n  public reissueTextValue(orig: Operation, decoded: Operation): Operation {\n    if (\n      !(orig instanceof SetOperation) &&\n      !(orig instanceof AddOperation) &&\n      !(orig instanceof ArraySetOperation)\n    ) {\n      return decoded;\n    }\n    const value = orig.getValue();\n    if (!(value instanceof CRDTText)) {\n      return decoded;\n    }\n\n    const pbElement = toElement(value);\n    this.walk(reflect(PbJSONElementSchema, pbElement));\n    const text = fromElement(pbElement);\n\n    if (decoded instanceof SetOperation) {\n      return SetOperation.create(\n        decoded.getKey(),\n        text,\n        decoded.getParentCreatedAt(),\n        decoded.getExecutedAt(),\n      );\n    }\n    if (decoded instanceof AddOperation) {\n      return AddOperation.create(\n        decoded.getParentCreatedAt(),\n        decoded.getPrevCreatedAt(),\n        text,\n        decoded.getExecutedAt(),\n      );\n    }\n    if (decoded instanceof ArraySetOperation) {\n      return ArraySetOperation.create(\n        decoded.getParentCreatedAt(),\n        decoded.getCreatedAt(),\n        text,\n        decoded.getExecutedAt(),\n      );\n    }\n    return decoded;\n  }\n\n  /**\n   * `walk` rewrites every TimeTicket reachable from the given message in\n   * place.\n   */\n  public walk(message: ReflectMessage): void {\n    switch (message.desc.typeName) {\n      case TimeTicketTypeName: {\n        const ticket = message.message as PbTimeTicket;\n        if (\n          ticket.lamport !== 0n &&\n          converter.toHexString(ticket.actorId) === this.from\n        ) {\n          ticket.actorId = converter.toUint8Array(this.to);\n        }\n        return;\n      }\n      case JSONElementSimpleTypeName:\n        this.walkNestedElement(message.message as PbJSONElementSimple);\n        break;\n    }\n\n    for (const field of message.fields) {\n      if (!message.isSet(field)) {\n        continue;\n      }\n\n      switch (field.fieldKind) {\n        case 'message':\n          this.walk(message.get(field));\n          break;\n        case 'list':\n          if (field.listKind === 'message') {\n            for (const item of message.get(field)) {\n              this.walk(item as ReflectMessage);\n            }\n          }\n          break;\n        case 'map':\n          // Map keys are left alone: node attributes are keyed by name, and\n          // the one actor-keyed map, the deprecated created_at_map_by_actor,\n          // is never written.\n          if (field.mapKind === 'message') {\n            for (const value of message.get(field).values()) {\n              this.walk(value as ReflectMessage);\n            }\n          }\n          break;\n      }\n    }\n  }\n\n  /**\n   * `walkNestedElement` rewrites the tickets inside the encoded value of an\n   * Object, Array or Tree element: the wire carries those as the bytes of a\n   * JSONElement, out of reach of the field walk.\n   */\n  private walkNestedElement(element: PbJSONElementSimple): void {\n    switch (element.type) {\n      case PbValueType.JSON_OBJECT:\n      case PbValueType.JSON_ARRAY:\n      case PbValueType.TREE:\n        break;\n      default:\n        return;\n    }\n    if (!element.value.length) {\n      return;\n    }\n\n    const nested = fromBinary(PbJSONElementSchema, element.value);\n    this.walk(reflect(PbJSONElementSchema, nested));\n    element.value = toBinary(PbJSONElementSchema, nested);\n  }\n}\n","/*\n * Copyright 2020 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { logger } from '@yorkie-js/sdk/src/util/logger';\nimport { uuid } from '@yorkie-js/sdk/src/util/uuid';\nimport { Code, YorkieError } from './error';\n\nexport type NextFn<T> = (value: T) => void;\n\nexport type ErrorFn = (error: Error) => void;\n\nexport type CompleteFn = () => void;\n\nexport interface Observer<T> {\n  next: NextFn<T>;\n  error?: ErrorFn;\n  complete?: CompleteFn;\n}\n\nexport type Unsubscribe = () => void;\n\nexport interface SubscribeFn<T> {\n  (\n    next: Observer<T> | NextFn<T>,\n    error?: ErrorFn,\n    complete?: CompleteFn,\n  ): Unsubscribe;\n  (observer: Observer<T>): Unsubscribe;\n}\n\ninterface ObserverEntry<T> {\n  subscriptionID: string;\n  observer: Observer<T>;\n}\n\nconst Noop = (): void => {\n  // Do nothing\n};\n\n/**\n * `ObserverProxy` is proxy of `Observer`.\n */\nclass ObserverProxy<T> implements Observer<T> {\n  public finalized = false;\n\n  private observers: Array<ObserverEntry<T>> | undefined = [];\n  private finalError?: Error;\n\n  constructor(executor: Executor<T>) {\n    try {\n      executor(this);\n    } catch (error: any) {\n      this.error(error);\n    }\n  }\n\n  /**\n   * `next` iterates next observer synchronously.\n   */\n  public next(value: T): void {\n    this.forEachObserver((observer: Observer<T>) => {\n      observer.next(value);\n    });\n  }\n\n  /**\n   * `error` invoke error.\n   */\n  public error(error: Error): void {\n    this.forEachObserver((observer: Observer<T>) => {\n      observer.error!(error);\n    });\n    this.close(error);\n  }\n\n  /**\n   * `complete` completes observer.\n   */\n  public complete(): void {\n    this.forEachObserver((observer: Observer<T>) => {\n      observer.complete!();\n    });\n    this.close();\n  }\n\n  /**\n   * `subscribe` is a function for subscribing observer.\n   */\n  public subscribe(\n    nextOrObserver: Observer<T> | NextFn<T>,\n    error?: ErrorFn,\n    complete?: CompleteFn,\n  ): Unsubscribe {\n    let observer: Observer<T>;\n\n    if (!nextOrObserver) {\n      throw new YorkieError(Code.ErrInvalidArgument, 'missing observer');\n    }\n\n    if (this.finalized) {\n      throw new YorkieError(\n        Code.ErrRefused,\n        'observable is finalized due to previous error',\n      );\n    }\n\n    if (typeof nextOrObserver === 'object') {\n      observer = nextOrObserver as Observer<T>;\n    } else {\n      observer = {\n        next: nextOrObserver as NextFn<T>,\n        error,\n        complete,\n      } as Observer<T>;\n    }\n\n    if (observer.next === undefined) {\n      observer.next = Noop as NextFn<T>;\n    }\n    if (observer.error === undefined) {\n      observer.error = Noop as ErrorFn;\n    }\n    if (observer.complete === undefined) {\n      observer.complete = Noop as CompleteFn;\n    }\n\n    const id = uuid();\n    const unsub = this.unsubscribeOne.bind(this, id);\n\n    this.observers!.push({\n      subscriptionID: id,\n      observer: observer as Observer<T>,\n    });\n\n    if (this.finalized) {\n      try {\n        if (this.finalError) {\n          observer.error(this.finalError);\n        } else {\n          observer.complete();\n        }\n      } catch (err) {\n        // nothing\n        logger.warn(err);\n      }\n    }\n\n    return unsub;\n  }\n\n  private unsubscribeOne(id: string): void {\n    this.observers = this.observers?.filter((it) => it.subscriptionID !== id);\n  }\n\n  private forEachObserver(fn: (observer: Observer<T>) => void): void {\n    if (this.finalized) {\n      return;\n    }\n\n    for (let i = 0; i < this.observers!.length; i++) {\n      this.sendOne(i, fn);\n    }\n  }\n\n  private sendOne(i: number, fn: (observer: Observer<T>) => void): void {\n    if (this.observers !== undefined && this.observers[i] !== undefined) {\n      try {\n        fn(this.observers[i].observer);\n      } catch (err) {\n        logger.error(err);\n      }\n    }\n  }\n\n  private close(err?: Error): void {\n    if (this.finalized) {\n      return;\n    }\n\n    this.finalized = true;\n    if (err !== undefined) {\n      this.finalError = err;\n    }\n\n    this.observers = undefined;\n  }\n}\n\nexport interface Observable<T> {\n  subscribe: SubscribeFn<T>;\n  getProxy?: () => ObserverProxy<T>;\n}\n\nexport type Executor<T> = (observer: Observer<T>) => void;\n\n/**\n * `createObservable` creates a new instance of ObserverProxy\n * and subscribe the instance.\n */\nexport function createObservable<T>(executor: Executor<T>): Observable<T> {\n  const proxy = new ObserverProxy(executor);\n  return {\n    subscribe: proxy.subscribe.bind(proxy),\n    getProxy: (): ObserverProxy<T> => {\n      return proxy;\n    },\n  };\n}\n","/*\n * Copyright 2020 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n  TimeTicket,\n  InitialDelimiter,\n} from '@yorkie-js/sdk/src/document/time/ticket';\nimport { CRDTRoot } from '@yorkie-js/sdk/src/document/crdt/root';\nimport {\n  CRDTContainer,\n  CRDTElement,\n} from '@yorkie-js/sdk/src/document/crdt/element';\nimport { Operation } from '@yorkie-js/sdk/src/document/operation/operation';\nimport { ChangeID } from '@yorkie-js/sdk/src/document/change/change_id';\nimport { Change } from '@yorkie-js/sdk/src/document/change/change';\nimport { PresenceChange } from '@yorkie-js/sdk/src/document/presence/change';\nimport { Indexable } from '@yorkie-js/sdk/src/document/document';\nimport { deepcopy } from '@yorkie-js/sdk/src/util/object';\nimport { GCPair } from '@yorkie-js/sdk/src/document/crdt/gc';\nimport { DataSize } from '@yorkie-js/sdk/src/util/resource';\n\n/**\n * `ChangeContext` is used to record the context of modification when editing\n * a document. Each time we add an operation, a new time ticket is issued.\n * Finally returns a Change after the modification has been completed.\n */\nexport class ChangeContext<P extends Indexable = Indexable> {\n  private prevID: ChangeID;\n  private nextID: ChangeID;\n  private delimiter: number;\n  private message?: string;\n\n  private root: CRDTRoot;\n  private operations: Array<Operation>;\n  private presenceChange?: PresenceChange<P>;\n\n  /**\n   * `previousPresence` stores the previous presence to be used for undoing\n   * presence changes.\n   */\n  private previousPresence: P;\n\n  /**\n   * `reversePresenceKeys` stores the keys of the presence to be used for undoing\n   * presence changes.\n   */\n  private reversePresenceKeys: Set<string>;\n\n  constructor(prevID: ChangeID, root: CRDTRoot, presence: P, message?: string) {\n    this.prevID = prevID;\n    this.nextID = prevID.next();\n    this.delimiter = InitialDelimiter;\n\n    this.root = root;\n    this.operations = [];\n    this.previousPresence = deepcopy(presence);\n    this.presenceChange = undefined;\n    this.reversePresenceKeys = new Set();\n    this.message = message;\n  }\n\n  /**\n   * `create` creates a new instance of ChangeContext.\n   */\n  public static create<P extends Indexable>(\n    prevID: ChangeID,\n    root: CRDTRoot,\n    presence: P,\n    message?: string,\n  ): ChangeContext<P> {\n    return new ChangeContext(prevID, root, presence, message);\n  }\n\n  /**\n   * `push` pushes the given operation to this context.\n   */\n  public push(operation: Operation): void {\n    this.operations.push(operation);\n  }\n\n  /**\n   * `registerElement` registers the given element to the root.\n   */\n  public registerElement(element: CRDTElement, parent: CRDTContainer): void {\n    this.root.registerElement(element, parent);\n  }\n\n  /**\n   * `registerRemovedElement` register removed element for garbage collection.\n   */\n  public registerRemovedElement(deleted: CRDTElement): void {\n    this.root.registerRemovedElement(deleted);\n  }\n\n  /**\n   * `registerGCPair` registers the given pair to hash table.\n   */\n  public registerGCPair(pair: GCPair): void {\n    this.root.registerGCPair(pair);\n  }\n\n  /**\n   * `getNextID` returns the next ID of this context. It will be set to the\n   * document for the next change.returns the next ID of this context.\n   */\n  public getNextID(): ChangeID {\n    // Even if the change has only presence change, the next ID for the document\n    // shoule have clocks. For this, we pass the clocks of the previous ID.\n    if (this.isPresenceOnlyChange()) {\n      return this.prevID\n        .next(true)\n        .setLamport(this.prevID.getLamport())\n        .setVersionVector(this.prevID.getVersionVector());\n    }\n\n    return this.nextID;\n  }\n\n  /**\n   * `toChange` creates a new instance of Change in this context.\n   */\n  public toChange(): Change<P> {\n    // NOTE(hackerwins): If this context was created only for presence change,\n    // we can use the ID without clocks that are used to resolve the\n    // conflict.\n    const id = this.isPresenceOnlyChange()\n      ? this.prevID.next(true)\n      : this.nextID;\n    return Change.create<P>({\n      id,\n      operations: this.operations,\n      presenceChange: this.presenceChange,\n      message: this.message,\n    });\n  }\n\n  /**\n   * `isPresenceOnlyChange` returns whether this context is only for presence\n   * change or not.\n   */\n  public isPresenceOnlyChange(): boolean {\n    return this.operations.length === 0;\n  }\n\n  /**\n   * `hasChange` returns whether this context has change or not.\n   */\n  public hasChange(): boolean {\n    return this.operations.length > 0 || this.presenceChange !== undefined;\n  }\n\n  /**\n   * `setPresenceChange` registers the presence change to this context.\n   */\n  public setPresenceChange(presenceChange: PresenceChange<P>) {\n    this.presenceChange = presenceChange;\n  }\n\n  /**\n   * `hasPresenceChange` returns whether a presence change was registered\n   * during this context. Used by `Document.update` to detect a presence\n   * emit when the document was attached with `disablePresence: true`.\n   */\n  public hasPresenceChange(): boolean {\n    return this.presenceChange !== undefined;\n  }\n\n  /**\n   * `dropPresenceChange` clears any presence change registered during\n   * this context. Used by `Document.update` to silently drop presence\n   * emits on documents attached with `disablePresence: true`. After\n   * dropping, the change carries only its operations (if any); when\n   * the context was presence-only the resulting `hasChange()` returns\n   * false and no `Change` is enqueued.\n   */\n  public dropPresenceChange(): void {\n    this.presenceChange = undefined;\n  }\n\n  /**\n   * `setReversePresence` registers the previous presence to undo presence updates.\n   */\n  public setReversePresence(\n    presence: Partial<P>,\n    option?: { addToHistory: boolean },\n  ) {\n    for (const key of Object.keys(presence)) {\n      if (option?.addToHistory) {\n        this.reversePresenceKeys.add(key);\n      } else {\n        this.reversePresenceKeys.delete(key);\n      }\n    }\n  }\n\n  /**\n   * `toReversePresence` returns the reverse presence of this context.\n   */\n  public getReversePresence() {\n    if (this.reversePresenceKeys.size === 0) return undefined;\n\n    const reversePresence: Partial<P> = {};\n    for (const key of this.reversePresenceKeys) {\n      reversePresence[key as keyof P] = this.previousPresence[key as keyof P];\n    }\n    return reversePresence;\n  }\n\n  /**\n   * `clearReversePresence` discards any reverse-presence keys recorded\n   * during this context. Used by `Document.update` alongside\n   * `dropPresenceChange` for documents attached with\n   * `disablePresence: true`, so the dropped presence emit does not push\n   * a no-op undo entry onto the history stack.\n   */\n  public clearReversePresence(): void {\n    this.reversePresenceKeys.clear();\n  }\n\n  /**\n   * `issueTimeTicket` creates a time ticket to be used to create a new operation.\n   */\n  public issueTimeTicket(): TimeTicket {\n    this.delimiter += 1;\n    return this.nextID.createTimeTicket(this.delimiter);\n  }\n\n  /**\n   * `getLastTimeTicket` returns the last time ticket issued in this context.\n   */\n  public getLastTimeTicket(): TimeTicket {\n    return this.nextID.createTimeTicket(this.delimiter);\n  }\n\n  /**\n   * `acc` accumulates the given DataSize to Live size of the root.\n   */\n  public acc(diff: DataSize) {\n    this.root.acc(diff);\n  }\n\n  /**\n   * `accGC` accumulates the given DataSize to gc. See `CRDTRoot.accGC`.\n   */\n  public accGC(diff: DataSize) {\n    this.root.accGC(diff);\n  }\n\n  /**\n   * `accMovedElement` books the size a move added to the moved element. See\n   * `CRDTRoot.accMovedElement`.\n   */\n  public accMovedElement(element: CRDTElement, diff: DataSize) {\n    this.root.accMovedElement(element, diff);\n  }\n}\n","/*\n * Copyright 2020 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { logger, LogLevel } from '@yorkie-js/sdk/src/util/logger';\nimport { Code, YorkieError } from '@yorkie-js/sdk/src/util/error';\nimport { TimeTicket } from '@yorkie-js/sdk/src/document/time/ticket';\nimport { SetOperation } from '@yorkie-js/sdk/src/document/operation/set_operation';\nimport { RemoveOperation } from '@yorkie-js/sdk/src/document/operation/remove_operation';\nimport { ChangeContext } from '@yorkie-js/sdk/src/document/change/context';\nimport { CRDTElement } from '@yorkie-js/sdk/src/document/crdt/element';\nimport { CRDTObject } from '@yorkie-js/sdk/src/document/crdt/object';\nimport {\n  toJSONElement,\n  buildCRDTElement,\n} from '@yorkie-js/sdk/src/document/json/element';\nimport * as Devtools from '@yorkie-js/sdk/src/devtools/types';\n\n/**\n * `JSONObject` represents a JSON object, but unlike regular JSON, it has time\n * tickets created by a logical clock to resolve conflicts.\n */\nexport type JSONObject<T> = {\n  /**\n   * `getID` returns the ID(time ticket) of this Object.\n   */\n  getID(): TimeTicket;\n\n  /**\n   * `toJSON` returns the JSON encoding of this object.\n   */\n  toJSON(): string;\n\n  /**\n   * `toJS` returns the JSON object of this object.\n   */\n  toJS(): T;\n\n  /**\n   * `toJSForTest` returns the JSON object of this object for debugging.\n   */\n  toJSForTest(): Devtools.JSONElement;\n} & T;\n\n/**\n * `createJSONObject` creates a new instance of JSONObject.\n */\nexport function createJSONObject<T>(\n  context: ChangeContext,\n  target: CRDTObject,\n): JSONObject<T> {\n  const objectProxy = new ObjectProxy(context);\n  return new Proxy(target, objectProxy.getHandlers()) as any;\n}\n\n/**\n * `ObjectProxy` is a proxy representing `Object`.\n */\nexport class ObjectProxy {\n  private context: ChangeContext;\n  private handlers: any;\n\n  constructor(context: ChangeContext) {\n    this.context = context;\n    this.handlers = {\n      set: (target: CRDTObject, key: string, value: any): boolean => {\n        if (logger.isEnabled(LogLevel.Trivial)) {\n          logger.trivial(`obj[${key}]=${JSON.stringify(value)}`);\n        }\n\n        ObjectProxy.setInternal(context, target, key, value);\n        return true;\n      },\n\n      get: (\n        target: CRDTObject,\n        keyOrMethod: Extract<keyof JSONObject<any>, 'string'>,\n      ): any => {\n        if (logger.isEnabled(LogLevel.Trivial)) {\n          logger.trivial(`obj[${keyOrMethod}]`);\n        }\n\n        if (keyOrMethod === 'getID') {\n          return (): TimeTicket => {\n            return target.getCreatedAt();\n          };\n        } else if (keyOrMethod === 'toJSON' || keyOrMethod === 'toString') {\n          return (): string => {\n            return target.toJSON();\n          };\n        } else if (keyOrMethod === 'toJS') {\n          return (): object => {\n            return target.toJS();\n          };\n        } else if (keyOrMethod === 'toJSForTest') {\n          return (): Devtools.JSONElement => {\n            return target.toJSForTest();\n          };\n        }\n\n        return toJSONElement(context, target.get(keyOrMethod));\n      },\n\n      ownKeys: (target: CRDTObject): Array<string> => {\n        return target.getKeys();\n      },\n\n      getOwnPropertyDescriptor: () => {\n        return {\n          enumerable: true,\n          configurable: true,\n        };\n      },\n\n      deleteProperty: (target: CRDTObject, key: string): boolean => {\n        if (logger.isEnabled(LogLevel.Trivial)) {\n          logger.trivial(`obj[${key}]`);\n        }\n\n        ObjectProxy.deleteInternal(context, target, key);\n        return true;\n      },\n    };\n  }\n\n  /**\n   * `setInternal` sets a new Object for the given key\n   */\n  public static setInternal(\n    context: ChangeContext,\n    target: CRDTObject,\n    key: string,\n    value: unknown,\n  ): void {\n    if (key.includes('.')) {\n      throw new YorkieError(\n        Code.ErrInvalidObjectKey,\n        `key must not contain the '.'.`,\n      );\n    }\n\n    const createdAt = context.issueTimeTicket();\n    const element = buildCRDTElement(context, value, createdAt);\n    const removed = target.set(key, element, createdAt);\n    context.registerElement(element, target);\n    if (removed) {\n      context.registerRemovedElement(removed);\n    }\n    context.push(\n      SetOperation.create(\n        key,\n        element.deepcopy(),\n        target.getCreatedAt(),\n        createdAt,\n      ),\n    );\n  }\n\n  /**\n   * `buildObjectMembers` constructs an object where all values from the\n   * user-provided object are transformed into CRDTElements.\n   * This function takes an object and iterates through its values,\n   * converting each value into a corresponding CRDTElement.\n   */\n  public static buildObjectMembers(\n    context: ChangeContext,\n    value: object,\n  ): { [key: string]: CRDTElement } {\n    const members: { [key: string]: CRDTElement } = {};\n    for (const [k, v] of Object.entries(value)) {\n      if (k.includes('.')) {\n        throw new YorkieError(\n          Code.ErrInvalidObjectKey,\n          `key must not contain the '.'.`,\n        );\n      }\n\n      const createdAt = context.issueTimeTicket();\n      const elem = buildCRDTElement(context, v, createdAt);\n      members[k] = elem;\n    }\n    return members;\n  }\n\n  /**\n   * `deleteInternal` deletes the value of the given key.\n   */\n  public static deleteInternal(\n    context: ChangeContext,\n    target: CRDTObject,\n    key: string,\n  ): void {\n    const ticket = context.issueTimeTicket();\n    const deleted = target.deleteByKey(key, ticket);\n    if (!deleted) {\n      return;\n    }\n\n    context.push(\n      RemoveOperation.create(\n        target.getCreatedAt(),\n        deleted.getCreatedAt(),\n        ticket,\n      ),\n    );\n    context.registerRemovedElement(deleted);\n  }\n\n  /**\n   * `getHandlers` gets handlers.\n   */\n  public getHandlers(): any {\n    return this.handlers;\n  }\n}\n","/*\n * Copyright 2020 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { logger, LogLevel } from '@yorkie-js/sdk/src/util/logger';\nimport { TimeTicket } from '@yorkie-js/sdk/src/document/time/ticket';\nimport { AddOperation } from '@yorkie-js/sdk/src/document/operation/add_operation';\nimport { ArraySetOperation } from '@yorkie-js/sdk/src/document/operation/array_set_operation';\nimport { MoveOperation } from '@yorkie-js/sdk/src/document/operation/move_operation';\nimport { RemoveOperation } from '@yorkie-js/sdk/src/document/operation/remove_operation';\nimport { ChangeContext } from '@yorkie-js/sdk/src/document/change/context';\nimport { CRDTElement } from '@yorkie-js/sdk/src/document/crdt/element';\nimport { CRDTArray } from '@yorkie-js/sdk/src/document/crdt/array';\nimport { Primitive } from '@yorkie-js/sdk/src/document/crdt/primitive';\nimport {\n  JSONElement,\n  WrappedElement,\n  toWrappedElement,\n  toJSONElement,\n  buildCRDTElement,\n} from '@yorkie-js/sdk/src/document/json/element';\nimport * as Devtools from '@yorkie-js/sdk/src/devtools/types';\nimport { Code, YorkieError } from '../../util/error';\n\n/**\n * `JSONArray` represents JSON array, but unlike regular JSON, it has time\n * tickets created by a logical clock to resolve conflicts.\n */\nexport type JSONArray<T> = {\n  /**\n   * `getID` returns the ID, `TimeTicket` of this Object.\n   */\n  getID(): TimeTicket;\n\n  /**\n   * `getElementByID` returns the element for the given ID.\n   */\n  getElementByID(createdAt: TimeTicket): WrappedElement<T>;\n\n  /**\n   * `getElementByIndex` returns the element for the given index.\n   */\n  getElementByIndex(index: number): WrappedElement<T>;\n\n  /**\n   * `getLast` returns the last element of this array.\n   */\n  getLast(): WrappedElement<T>;\n\n  /**\n   * `setValue` sets the given value at the given index.\n   */\n  setValue(index: number, value: unknown): WrappedElement<T>;\n\n  /**\n   * `delete` deletes the element of the given index.\n   */\n  delete(index: number): WrappedElement<T>;\n\n  /**\n   * `deleteByID` deletes the element of the given ID.\n   */\n  deleteByID(createdAt: TimeTicket): WrappedElement<T>;\n\n  /**\n   * `insertBefore` inserts a value before the given next element.\n   */\n  insertBefore(nextID: TimeTicket, value: any): WrappedElement<T>;\n\n  /**\n   * `insertAfter` inserts a value after the given previous element.\n   */\n  insertAfter(prevID: TimeTicket, value: any): WrappedElement<T>;\n\n  /**\n   * `insertIntegerAfter` inserts a value after the given index.\n   */\n  insertIntegerAfter(index: number, value: number): WrappedElement<T>;\n\n  /**\n   * `moveBefore` moves the element before the given next element.\n   */\n  moveBefore(nextID: TimeTicket, id: TimeTicket): void;\n\n  /**\n   * `moveAfter` moves the element after the given previous element.\n   */\n  moveAfter(prevID: TimeTicket, id: TimeTicket): void;\n\n  /**\n   * `moveAfterByIndex` moves the element after the given index.\n   */\n  moveAfterByIndex(prevIndex: number, targetIndex: number): void;\n\n  /**\n   * `moveFront` moves the element before the first element.\n   */\n  moveFront(id: TimeTicket): void;\n\n  /**\n   * `moveLast` moves the element after the last element.\n   */\n  moveLast(id: TimeTicket): void;\n\n  /**\n   * `elements` returns an iterator of wrapped elements including CRDT metadata.\n   */\n  elements(): IterableIterator<WrappedElement<T>>;\n\n  /**\n   * `toTestString` returns a String containing the meta data of the node\n   * for debugging purpose.\n   */\n  toTestString(): string;\n\n  /**\n   * `toJSForTest` returns the JSON object of this array for debugging.\n   */\n  toJSForTest(): Devtools.JSONElement;\n} & Array<T>;\n\n/**\n * `createJSONArray` creates a new instance of JSONArray.\n */\nexport function createJSONArray(\n  context: ChangeContext,\n  target: CRDTArray,\n): JSONArray<WrappedElement> {\n  const arrayProxy = new ArrayProxy(context, target);\n  return new Proxy(target, arrayProxy.getHandlers()) as any;\n}\n\n/**\n * `isNumericString` checks if value is numeric string.\n */\nfunction isNumericString(val: any): boolean {\n  if (typeof val === 'string' || val instanceof String) {\n    return !isNaN(val as any);\n  }\n  return false;\n}\n\n/**\n * `isReadOnlyArrayMethod` checks if the method is a standard array read-only operation.\n */\nfunction isReadOnlyArrayMethod(method: string): boolean {\n  return [\n    'concat',\n    'entries',\n    'every',\n    'filter',\n    'find',\n    'findIndex',\n    'forEach',\n    'join',\n    'keys',\n    'map',\n    'reduce',\n    'reduceRight',\n    'slice',\n    'some',\n    'toLocaleString',\n    'toString',\n    'values',\n  ].includes(method);\n}\n\n/**\n * `ArrayProxy` is a proxy for Array.\n */\nexport class ArrayProxy {\n  private context: ChangeContext;\n  private handlers: any;\n  private array: CRDTArray;\n\n  constructor(context: ChangeContext, array: CRDTArray) {\n    this.context = context;\n    this.array = array;\n    this.handlers = {\n      get: (\n        target: CRDTArray,\n        method: keyof JSONArray<unknown>,\n        receiver: any,\n      ): any => {\n        if (method === 'getID') {\n          return (): TimeTicket => {\n            return target.getCreatedAt();\n          };\n        } else if (method === 'getElementByID') {\n          return (createdAt: TimeTicket): WrappedElement | undefined => {\n            const elem = target.getByID(createdAt);\n            if (!elem || elem.isRemoved()) {\n              return;\n            }\n            return toWrappedElement(context, elem);\n          };\n        } else if (method === 'getElementByIndex') {\n          return (index: number): WrappedElement | undefined => {\n            const elem = target.get(index);\n            return toWrappedElement(context, elem);\n          };\n        } else if (method === 'getLast') {\n          return (): WrappedElement | undefined => {\n            return toWrappedElement(context, target.getLast());\n          };\n        } else if (method === 'delete') {\n          return (index: number): WrappedElement | undefined => {\n            const deleted = ArrayProxy.deleteInternalByIndex(\n              context,\n              target,\n              index,\n            );\n            return toWrappedElement(context, deleted);\n          };\n        } else if (method === 'deleteByID') {\n          return (createdAt: TimeTicket): WrappedElement | undefined => {\n            const deleted = ArrayProxy.deleteInternalByID(\n              context,\n              target,\n              createdAt,\n            );\n            return toWrappedElement(context, deleted);\n          };\n        } else if (method === 'insertAfter') {\n          return (\n            prevID: TimeTicket,\n            value: any,\n          ): WrappedElement | undefined => {\n            // Convert element identity to position identity.\n            let posCreatedAt: TimeTicket;\n            try {\n              posCreatedAt = target.posCreatedAt(prevID);\n            } catch {\n              posCreatedAt = prevID;\n            }\n            const inserted = ArrayProxy.insertAfterInternal(\n              context,\n              target,\n              posCreatedAt,\n              value,\n            );\n            return toWrappedElement(context, inserted);\n          };\n        } else if (method === 'insertIntegerAfter') {\n          return (index: number, value: number): WrappedElement | undefined => {\n            const array = ArrayProxy.insertIntegerAfterInternal(\n              context,\n              target,\n              index,\n              value,\n            );\n            return toWrappedElement(context, array);\n          };\n        } else if (method === 'insertBefore') {\n          return (\n            nextID: TimeTicket,\n            value: any,\n          ): WrappedElement | undefined => {\n            const inserted = ArrayProxy.insertBeforeInternal(\n              context,\n              target,\n              nextID,\n              value,\n            );\n            return toWrappedElement(context, inserted);\n          };\n        } else if (method === 'setValue') {\n          return (index: number, value: number): WrappedElement | undefined => {\n            const array = ArrayProxy.setValueInternal(\n              context,\n              target,\n              index,\n              value,\n            );\n            return toWrappedElement(context, array);\n          };\n        } else if (method === 'moveBefore') {\n          return (nextID: TimeTicket, id: TimeTicket): void => {\n            ArrayProxy.moveBeforeInternal(context, target, nextID, id);\n          };\n          // JavaScript Native API\n        } else if (method === 'moveAfter') {\n          return (prevID: TimeTicket, id: TimeTicket): void => {\n            ArrayProxy.moveAfterInternal(context, target, prevID, id);\n          };\n        } else if (method === 'moveAfterByIndex') {\n          return (prevIndex: number, targetIndex: number): void => {\n            ArrayProxy.moveAfterByIndexInternal(\n              context,\n              target,\n              prevIndex,\n              targetIndex,\n            );\n          };\n        } else if (method === 'moveFront') {\n          return (id: TimeTicket): void => {\n            ArrayProxy.moveFrontInternal(context, target, id);\n          };\n        } else if (method === 'moveLast') {\n          return (id: TimeTicket): void => {\n            ArrayProxy.moveLastInternal(context, target, id);\n          };\n        } else if (isNumericString(method)) {\n          return toJSONElement(context, target.get(Number(method as string)));\n        } else if (method === 'push') {\n          return (value: any): number => {\n            return ArrayProxy.pushInternal(context, target, value);\n          };\n        } else if (method === 'splice') {\n          return (\n            start: number,\n            deleteCount?: number,\n            ...items: Array<any>\n          ): JSONArray<JSONElement> => {\n            return ArrayProxy.splice(\n              context,\n              target,\n              start,\n              deleteCount,\n              ...items,\n            );\n          };\n        } else if (method === 'length') {\n          return target.length;\n        } else if (typeof method === 'symbol' && method === Symbol.iterator) {\n          return ArrayProxy.iteratorInternal.bind(this, context, target);\n        } else if (method === 'elements') {\n          return ArrayProxy.wrappedIteratorInternal.bind(this, context, target);\n        } else if (method === 'includes') {\n          return (searchElement: JSONElement, fromIndex?: number): boolean => {\n            return ArrayProxy.includes(\n              context,\n              target,\n              searchElement,\n              fromIndex,\n            );\n          };\n        } else if (method === 'indexOf') {\n          return (searchElement: JSONElement, fromIndex?: number): number => {\n            return ArrayProxy.indexOf(\n              context,\n              target,\n              searchElement,\n              fromIndex,\n            );\n          };\n        } else if (method === 'lastIndexOf') {\n          return (searchElement: JSONElement, fromIndex?: number): number => {\n            return ArrayProxy.lastIndexOf(\n              context,\n              target,\n              searchElement,\n              fromIndex,\n            );\n          };\n        } else if (method === 'toJSForTest') {\n          return (): Devtools.JSONElement => {\n            return target.toJSForTest();\n          };\n        } else if (method === 'toTestString') {\n          return (): string => ArrayProxy.toTestString(target);\n        } else if (\n          typeof method === 'string' &&\n          isReadOnlyArrayMethod(method)\n        ) {\n          return (...args: any) => {\n            const arr = Array.from(target).map((elem) =>\n              toJSONElement(context, elem),\n            );\n            return Array.prototype[method as any].apply(arr, args);\n          };\n        }\n\n        // TODO we need to distinguish between the case we need to call default\n        // behavior and the case where we need to call an internal method\n        // throw new TypeError(`Unsupported method: ${String(method)}`);\n        return Reflect.get(target, method, receiver);\n      },\n\n      set: (target: CRDTArray, key: string, value: any): boolean => {\n        if (isNumericString(key)) {\n          const index = Number(key);\n          ArrayProxy.setValueInternal(context, target, index, value);\n          return true;\n        }\n        return Reflect.set(target, key, value);\n      },\n\n      deleteProperty: (target: CRDTArray, key: string): boolean => {\n        if (logger.isEnabled(LogLevel.Trivial)) {\n          logger.trivial(`array[${key}]`);\n        }\n        ArrayProxy.deleteInternalByIndex(context, target, Number.parseInt(key));\n        return true;\n      },\n    };\n  }\n\n  // eslint-disable-next-line jsdoc/require-jsdoc\n  public static *iteratorInternal(\n    change: ChangeContext,\n    target: CRDTArray,\n  ): IterableIterator<JSONElement> {\n    for (const elem of target) {\n      yield toJSONElement(change, elem)!;\n    }\n  }\n\n  // eslint-disable-next-line jsdoc/require-jsdoc\n  public static *wrappedIteratorInternal(\n    change: ChangeContext,\n    target: CRDTArray,\n  ): IterableIterator<WrappedElement> {\n    for (const elem of target) {\n      yield toWrappedElement(change, elem)!;\n    }\n  }\n\n  /**\n   * `buildArrayElements` constructs array elements based on the user-provided array.\n   */\n  public static buildArrayElements(\n    context: ChangeContext,\n    value: Array<unknown>,\n  ): Array<CRDTElement> {\n    const elements: Array<CRDTElement> = [];\n    for (const v of value) {\n      const createdAt = context.issueTimeTicket();\n      const elem = buildCRDTElement(context, v, createdAt);\n      elements.push(elem);\n    }\n    return elements;\n  }\n\n  /**\n   * `pushInternal` pushes the value to the target array.\n   */\n  public static pushInternal(\n    context: ChangeContext,\n    target: CRDTArray,\n    value: unknown,\n  ): number {\n    ArrayProxy.insertAfterInternal(\n      context,\n      target,\n      target.getLastCreatedAt(),\n      value,\n    );\n    return target.length;\n  }\n\n  /**\n   * `moveBeforeInternal` moves the given `createdAt` element\n   * after the previously created element.\n   */\n  public static moveBeforeInternal(\n    context: ChangeContext,\n    target: CRDTArray,\n    nextCreatedAt: TimeTicket,\n    createdAt: TimeTicket,\n  ): void {\n    const ticket = context.issueTimeTicket();\n    const prevCreatedAt = target.getPrevCreatedAt(nextCreatedAt);\n    const { deadNode, movedDiff } = target.moveAfter(\n      prevCreatedAt,\n      createdAt,\n      ticket,\n    );\n    context.push(\n      MoveOperation.create(\n        target.getCreatedAt(),\n        prevCreatedAt,\n        createdAt,\n        ticket,\n      ),\n    );\n    // The `movedAt` stamp is part of the moved element's size; see\n    // `CRDTRoot.accMovedElement` for why it cannot simply go to live.\n    context.accMovedElement(target.getByID(createdAt)!, movedDiff);\n\n    if (deadNode) {\n      // A dead position node holds no element, so `getDataSize` never counted\n      // it into live -- `gcOnlySize` is how a pair says \"add to gc, take\n      // nothing out of live\". See `CRDTRoot.registerGCPair`.\n      context.registerGCPair({\n        parent: target.getRGATreeList(),\n        child: deadNode,\n        gcOnlySize: deadNode.getDataSize(),\n      });\n    }\n  }\n\n  /**\n   * `moveAfterInternal` moves the given `createdAt` element\n   * after the specific element. Converts element identity to\n   * position identity for the prevCreatedAt.\n   */\n  public static moveAfterInternal(\n    context: ChangeContext,\n    target: CRDTArray,\n    prevCreatedAt: TimeTicket,\n    createdAt: TimeTicket,\n  ): void {\n    const ticket = context.issueTimeTicket();\n    // Convert element identity to position node identity.\n    // Fall back to prevCreatedAt if not found in elementMap\n    // (e.g., LastCreatedAt returns a position identity directly).\n    let posCreatedAt: TimeTicket;\n    try {\n      posCreatedAt = target.posCreatedAt(prevCreatedAt);\n    } catch {\n      posCreatedAt = prevCreatedAt;\n    }\n    const { deadNode, movedDiff } = target.moveAfter(\n      posCreatedAt,\n      createdAt,\n      ticket,\n    );\n    context.push(\n      MoveOperation.create(\n        target.getCreatedAt(),\n        posCreatedAt,\n        createdAt,\n        ticket,\n      ),\n    );\n    // The `movedAt` stamp is part of the moved element's size; see\n    // `CRDTRoot.accMovedElement` for why it cannot simply go to live.\n    context.accMovedElement(target.getByID(createdAt)!, movedDiff);\n\n    if (deadNode) {\n      // A dead position node holds no element, so `getDataSize` never counted\n      // it into live -- `gcOnlySize` is how a pair says \"add to gc, take\n      // nothing out of live\". See `CRDTRoot.registerGCPair`.\n      context.registerGCPair({\n        parent: target.getRGATreeList(),\n        child: deadNode,\n        gcOnlySize: deadNode.getDataSize(),\n      });\n    }\n  }\n\n  /**\n   * `moveAfterByIndexInternal` moves the given element to its new\n   * position after the given previous element.\n   */\n  public static moveAfterByIndexInternal(\n    context: ChangeContext,\n    target: CRDTArray,\n    prevIndex: number,\n    targetIndex: number,\n  ): void {\n    const prevElem = target.get(prevIndex);\n    if (!prevElem) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `index out of bounds: ${prevIndex}`,\n      );\n    }\n\n    const targetElem = target.get(targetIndex);\n    if (!targetElem) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `index out of bounds: ${targetIndex}`,\n      );\n    }\n\n    ArrayProxy.moveAfterInternal(\n      context,\n      target,\n      prevElem.getCreatedAt(),\n      targetElem.getCreatedAt(),\n    );\n  }\n\n  /**\n   * `moveFrontInternal` moves the given `createdAt` element\n   * at the first of array.\n   */\n  public static moveFrontInternal(\n    context: ChangeContext,\n    target: CRDTArray,\n    createdAt: TimeTicket,\n  ): void {\n    const ticket = context.issueTimeTicket();\n    const head = target.getHead();\n    const { deadNode, movedDiff } = target.moveAfter(\n      head.getCreatedAt(),\n      createdAt,\n      ticket,\n    );\n    context.push(\n      MoveOperation.create(\n        target.getCreatedAt(),\n        head.getCreatedAt(),\n        createdAt,\n        ticket,\n      ),\n    );\n    // The `movedAt` stamp is part of the moved element's size; see\n    // `CRDTRoot.accMovedElement` for why it cannot simply go to live.\n    context.accMovedElement(target.getByID(createdAt)!, movedDiff);\n\n    if (deadNode) {\n      // A dead position node holds no element, so `getDataSize` never counted\n      // it into live -- `gcOnlySize` is how a pair says \"add to gc, take\n      // nothing out of live\". See `CRDTRoot.registerGCPair`.\n      context.registerGCPair({\n        parent: target.getRGATreeList(),\n        child: deadNode,\n        gcOnlySize: deadNode.getDataSize(),\n      });\n    }\n  }\n\n  /**\n   * `moveLastInternal` moves the given `createdAt` element\n   * at the last of array.\n   */\n  public static moveLastInternal(\n    context: ChangeContext,\n    target: CRDTArray,\n    createdAt: TimeTicket,\n  ): void {\n    const ticket = context.issueTimeTicket();\n    const last = target.getLastCreatedAt();\n    const { deadNode, movedDiff } = target.moveAfter(last, createdAt, ticket);\n    context.push(\n      MoveOperation.create(target.getCreatedAt(), last, createdAt, ticket),\n    );\n    // The `movedAt` stamp is part of the moved element's size; see\n    // `CRDTRoot.accMovedElement` for why it cannot simply go to live.\n    context.accMovedElement(target.getByID(createdAt)!, movedDiff);\n\n    if (deadNode) {\n      // A dead position node holds no element, so `getDataSize` never counted\n      // it into live -- `gcOnlySize` is how a pair says \"add to gc, take\n      // nothing out of live\". See `CRDTRoot.registerGCPair`.\n      context.registerGCPair({\n        parent: target.getRGATreeList(),\n        child: deadNode,\n        gcOnlySize: deadNode.getDataSize(),\n      });\n    }\n  }\n\n  /**\n   * `insertAfterInternal` inserts the value after the previously\n   * created element.\n   */\n  public static insertAfterInternal(\n    context: ChangeContext,\n    target: CRDTArray,\n    prevCreatedAt: TimeTicket,\n    value: unknown,\n  ): CRDTElement {\n    const createdAt = context.issueTimeTicket();\n    const element = buildCRDTElement(context, value, createdAt);\n    target.insertAfter(prevCreatedAt, element);\n    context.registerElement(element, target);\n    context.push(\n      AddOperation.create(\n        target.getCreatedAt(),\n        prevCreatedAt,\n        element.deepcopy(),\n        createdAt,\n      ),\n    );\n    return element;\n  }\n\n  /**\n   * `insertIntegerAfterInternal` inserts the given integer after the given previous element.\n   */\n  public static insertIntegerAfterInternal(\n    context: ChangeContext,\n    target: CRDTArray,\n    index: number,\n    value: number,\n  ): CRDTElement {\n    const prevElem = target.get(index);\n    if (!prevElem) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `index out of bounds: ${index}`,\n      );\n    }\n\n    // Convert element identity to position identity for the anchor.\n    let posCreatedAt: TimeTicket;\n    try {\n      posCreatedAt = target.posCreatedAt(prevElem.getCreatedAt());\n    } catch {\n      posCreatedAt = prevElem.getCreatedAt();\n    }\n    ArrayProxy.insertAfterInternal(context, target, posCreatedAt, value);\n    return target;\n  }\n\n  /**\n   * `insertBeforeInternal` inserts the value before the previously created element.\n   */\n  public static insertBeforeInternal(\n    context: ChangeContext,\n    target: CRDTArray,\n    nextCreatedAt: TimeTicket,\n    value: unknown,\n  ): CRDTElement {\n    return ArrayProxy.insertAfterInternal(\n      context,\n      target,\n      target.getPrevCreatedAt(nextCreatedAt),\n      value,\n    );\n  }\n\n  /**\n   * `setValueInternal` sets the given value at the given index.\n   */\n  public static setValueInternal(\n    context: ChangeContext,\n    target: CRDTArray,\n    index: number,\n    value: unknown,\n  ): CRDTElement {\n    const prev = target.get(index);\n    if (!prev) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `index out of bounds: ${index}`,\n      );\n    }\n\n    ArrayProxy.setByIndexInternal(context, target, prev.getCreatedAt(), value);\n    return target;\n  }\n\n  /**\n   * `setByIndexInternal` sets the element of the given index.\n   */\n  public static setByIndexInternal(\n    context: ChangeContext,\n    target: CRDTArray,\n    createdAt: TimeTicket,\n    value: unknown,\n  ): CRDTElement {\n    const ticket = context.issueTimeTicket();\n    const element = buildCRDTElement(context, value, ticket);\n\n    const copiedValue = element.deepcopy();\n\n    context.push(\n      ArraySetOperation.create(\n        target.getCreatedAt(),\n        createdAt,\n        copiedValue,\n        ticket,\n      ),\n    );\n\n    const removed = target.set(createdAt, element, ticket);\n    context.registerElement(element, target);\n\n    // NOTE(hackerwins): The displaced element has to be registered here too,\n    // not only in `ArraySetOperation.execute`. This path runs against the\n    // clone the updater is given, so leaving it out makes the clone's\n    // accounting drift from the document the operation is replayed on.\n    // `json/object.ts`'s `setInternal` registers the value it replaces the\n    // same way.\n    if (removed) {\n      context.registerRemovedElement(removed);\n    }\n\n    return element;\n  }\n\n  /**\n   * `deleteInternalByIndex` deletes target element of given index.\n   */\n  public static deleteInternalByIndex(\n    context: ChangeContext,\n    target: CRDTArray,\n    index: number,\n  ): CRDTElement | undefined {\n    const ticket = context.issueTimeTicket();\n    const deleted = target.deleteByIndex(index, ticket);\n    if (!deleted) {\n      return;\n    }\n\n    context.push(\n      RemoveOperation.create(\n        target.getCreatedAt(),\n        deleted.getCreatedAt(),\n        ticket,\n      ),\n    );\n    context.registerRemovedElement(deleted);\n    return deleted;\n  }\n\n  /**\n   * `deleteInternalByID` deletes the element of the given ID.\n   */\n  public static deleteInternalByID(\n    context: ChangeContext,\n    target: CRDTArray,\n    createdAt: TimeTicket,\n  ): CRDTElement {\n    const ticket = context.issueTimeTicket();\n    const deleted = target.delete(createdAt, ticket);\n    context.push(\n      RemoveOperation.create(\n        target.getCreatedAt(),\n        deleted.getCreatedAt(),\n        ticket,\n      ),\n    );\n    context.registerRemovedElement(deleted);\n    return deleted;\n  }\n\n  /**\n   * `splice` is a method to remove elements from the array.\n   */\n  public static splice(\n    context: ChangeContext,\n    target: CRDTArray,\n    start: number,\n    deleteCount?: number,\n    ...items: Array<any>\n  ): JSONArray<JSONElement> {\n    const length = target.length;\n    const from =\n      start >= 0 ? Math.min(start, length) : Math.max(length + start, 0);\n    const to =\n      deleteCount === undefined\n        ? length\n        : deleteCount < 0\n          ? from\n          : Math.min(from + deleteCount, length);\n    const removeds: JSONArray<JSONElement> = [] as any;\n    for (let i = from; i < to; i++) {\n      const removed = ArrayProxy.deleteInternalByIndex(context, target, from);\n      if (removed) {\n        const removedElem = removed.deepcopy();\n        removedElem.setRemovedAt();\n        removeds.push(toJSONElement(context, removedElem)!);\n      }\n    }\n    if (items) {\n      let previousID: TimeTicket;\n      if (from === 0) {\n        previousID = target.getHead().getID();\n      } else {\n        // Convert element identity to position identity for the anchor.\n        const elemID = target.get(from - 1)!.getID();\n        try {\n          previousID = target.posCreatedAt(elemID);\n        } catch {\n          previousID = elemID;\n        }\n      }\n      for (const item of items) {\n        const newElem = ArrayProxy.insertAfterInternal(\n          context,\n          target,\n          previousID,\n          item,\n        );\n        previousID = newElem.getID();\n      }\n    }\n    return removeds;\n  }\n\n  /**\n   * `includes` returns true if the given element is in the array.\n   */\n  public static includes(\n    context: ChangeContext,\n    target: CRDTArray,\n    searchElement: JSONElement,\n    fromIndex?: number,\n  ): boolean {\n    const length = target.length;\n    const from =\n      fromIndex === undefined\n        ? 0\n        : fromIndex < 0\n          ? Math.max(fromIndex + length, 0)\n          : fromIndex;\n\n    if (from >= length) return false;\n\n    if (Primitive.isSupport(searchElement)) {\n      const arr = Array.from(target).map((elem) =>\n        toJSONElement(context, elem),\n      );\n      return arr.includes(searchElement, from);\n    }\n\n    for (let i = from; i < length; i++) {\n      if (\n        target.get(i)?.getID() === (searchElement as WrappedElement).getID()\n      ) {\n        return true;\n      }\n    }\n    return false;\n  }\n\n  /**\n   * `indexOf` returns the index of the given element.\n   */\n  public static indexOf(\n    context: ChangeContext,\n    target: CRDTArray,\n    searchElement: JSONElement,\n    fromIndex?: number,\n  ): number {\n    const length = target.length;\n    const from =\n      fromIndex === undefined\n        ? 0\n        : fromIndex < 0\n          ? Math.max(fromIndex + length, 0)\n          : fromIndex;\n\n    if (from >= length) return -1;\n\n    if (Primitive.isSupport(searchElement)) {\n      const arr = Array.from(target).map((elem) =>\n        toJSONElement(context, elem),\n      );\n      return arr.indexOf(searchElement, from);\n    }\n\n    for (let i = from; i < length; i++) {\n      if (\n        target.get(i)?.getID() === (searchElement as WrappedElement).getID()\n      ) {\n        return i;\n      }\n    }\n    return -1;\n  }\n\n  /**\n   * `lastIndexOf` returns the last index of the given element.\n   */\n  public static lastIndexOf(\n    context: ChangeContext,\n    target: CRDTArray,\n    searchElement: JSONElement,\n    fromIndex?: number,\n  ): number {\n    const length = target.length;\n    const from =\n      fromIndex === undefined || fromIndex >= length\n        ? length - 1\n        : fromIndex < 0\n          ? fromIndex + length\n          : fromIndex;\n\n    if (from < 0) return -1;\n\n    if (Primitive.isSupport(searchElement)) {\n      const arr = Array.from(target).map((elem) =>\n        toJSONElement(context, elem),\n      );\n      return arr.lastIndexOf(searchElement, from);\n    }\n\n    for (let i = from; i > 0; i--) {\n      if (\n        target.get(i)?.getID() === (searchElement as WrappedElement).getID()\n      ) {\n        return i;\n      }\n    }\n    return -1;\n  }\n  /**\n   * `toTestString` returns a String containing the meta data of the node\n   * for debugging purpose.\n   */\n  public static toTestString(target: CRDTArray): string {\n    return target.toTestString();\n  }\n\n  /**\n   * `getHandlers` gets handlers.\n   */\n  public getHandlers(): any {\n    return this.handlers;\n  }\n}\n","/*\n * Copyright 2020 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { logger, LogLevel } from '@yorkie-js/sdk/src/util/logger';\nimport { Indexable } from '@yorkie-js/sdk/src/document/document';\nimport {\n  TimeTicket,\n  TimeTicketStruct,\n} from '@yorkie-js/sdk/src/document/time/ticket';\nimport { ChangeContext } from '@yorkie-js/sdk/src/document/change/context';\nimport {\n  RGATreeSplitNode,\n  RGATreeSplitNodeID,\n  RGATreeSplitPos,\n  RGATreeSplitPosRange,\n} from '@yorkie-js/sdk/src/document/crdt/rga_tree_split';\nimport {\n  CRDTText,\n  CRDTTextValue,\n  TextValueType,\n} from '@yorkie-js/sdk/src/document/crdt/text';\nimport { EditOperation } from '@yorkie-js/sdk/src/document/operation/edit_operation';\nimport { StyleOperation } from '@yorkie-js/sdk/src/document/operation/style_operation';\nimport { stringifyObjectValues } from '@yorkie-js/sdk/src/util/object';\nimport type * as Devtools from '@yorkie-js/sdk/src/devtools/types';\nimport { SplayTree } from '@yorkie-js/sdk/src/util/splay_tree';\nimport { LLRBTree } from '@yorkie-js/sdk/src/util/llrb_tree';\nimport { Code, YorkieError } from '@yorkie-js/sdk/src/util/error';\n\n/**\n * `TextPosStruct` represents the structure of RGATreeSplitPos.\n * It is used to serialize and deserialize the RGATreeSplitPos.\n */\nexport type TextPosStruct = {\n  id: { createdAt: TimeTicketStruct; offset: number };\n  relativeOffset: number;\n};\n\n/**\n * `TextPosStructRange` represents the structure of RGATreeSplitPosRange.\n * It is used to serialize and deserialize the RGATreeSplitPosRange.\n */\nexport type TextPosStructRange = [TextPosStruct, TextPosStruct];\n\n/**\n * `Text` is an extended data type for the contents of a text editor.\n */\nexport class Text<A extends Indexable = Indexable> {\n  private context?: ChangeContext;\n  private text?: CRDTText<A>;\n\n  constructor(context?: ChangeContext, text?: CRDTText<A>) {\n    this.context = context;\n    this.text = text;\n  }\n\n  /**\n   * `initialize` initialize this text with context and internal text.\n   */\n  public initialize(context: ChangeContext, text: CRDTText<A>): void {\n    this.context = context;\n    this.text = text;\n  }\n\n  /**\n   * `getID` returns the ID of this text.\n   */\n  public getID(): TimeTicket {\n    return this.text!.getID();\n  }\n\n  /**\n   * `edit` edits this text with the given content.\n   * An index inside a UTF-16 surrogate pair throws `ErrInvalidArgument`, and\n   * so does content holding a lone half of one.\n   */\n  edit(\n    fromIdx: number,\n    toIdx: number,\n    content: string,\n    attributes?: A,\n  ): [number, number] | undefined {\n    if (!this.context || !this.text) {\n      throw new YorkieError(\n        Code.ErrNotInitialized,\n        'Text is not initialized yet',\n      );\n    }\n\n    if (fromIdx > toIdx) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        'from should be less than or equal to to',\n      );\n    }\n\n    const range = this.text.createRange(fromIdx, toIdx, content);\n    if (logger.isEnabled(LogLevel.Debug)) {\n      logger.debug(\n        `EDIT: f:${fromIdx}->${range[0].toTestString()}, t:${toIdx}->${range[1].toTestString()} c:${content}`,\n      );\n    }\n    const attrs = attributes ? stringifyObjectValues(attributes) : undefined;\n    const ticket = this.context.issueTimeTicket();\n    const [, pairs, diff, rangeAfterEdit] = this.text.edit(\n      range,\n      content,\n      ticket,\n      attrs,\n    );\n\n    this.context!.acc(diff);\n\n    for (const pair of pairs) {\n      this.context!.registerGCPair(pair);\n    }\n\n    this.context.push(\n      new EditOperation(\n        this.text.getCreatedAt(),\n        range[0],\n        range[1],\n        content,\n        attrs ? new Map(Object.entries(attrs)) : new Map(),\n        ticket,\n      ),\n    );\n\n    return this.text.findIndexesFromRange(rangeAfterEdit);\n  }\n\n  /**\n   * `delete` deletes the text in the given range.\n   */\n  delete(fromIdx: number, toIdx: number): [number, number] | undefined {\n    return this.edit(fromIdx, toIdx, '');\n  }\n\n  /**\n   * `empty` makes the text empty.\n   */\n  empty(): [number, number] | undefined {\n    return this.edit(0, this.length, '');\n  }\n\n  /**\n   * `setStyle` styles this text with the given attributes.\n   * An index inside a UTF-16 surrogate pair throws `ErrInvalidArgument`.\n   */\n  setStyle(fromIdx: number, toIdx: number, attributes: A): boolean {\n    if (!this.context || !this.text) {\n      throw new YorkieError(\n        Code.ErrNotInitialized,\n        'Text is not initialized yet',\n      );\n    }\n\n    if (fromIdx > toIdx) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        'from should be less than or equal to to',\n      );\n    }\n\n    const range = this.text.createRange(fromIdx, toIdx);\n    if (logger.isEnabled(LogLevel.Debug)) {\n      logger.debug(\n        `STYL: f:${fromIdx}->${range[0].toTestString()}, t:${toIdx}->${range[1].toTestString()} a:${JSON.stringify(\n          attributes,\n        )}`,\n      );\n    }\n\n    const attrs = stringifyObjectValues(attributes);\n    const ticket = this.context.issueTimeTicket();\n    const [pairs, size] = this.text.setStyle(range, attrs, ticket);\n\n    this.context!.acc(size.live);\n    this.context!.accGC(size.gc);\n\n    for (const pair of pairs) {\n      this.context!.registerGCPair(pair);\n    }\n\n    this.context.push(\n      StyleOperation.create(\n        this.text.getCreatedAt(),\n        range[0],\n        range[1],\n        new Map(Object.entries(attrs)),\n        ticket,\n      ),\n    );\n\n    return true;\n  }\n\n  /**\n   * `indexRangeToPosRange` returns TextRangeStruct of the given index range.\n   */\n  indexRangeToPosRange(range: [number, number]): TextPosStructRange {\n    if (!this.context || !this.text) {\n      throw new YorkieError(\n        Code.ErrNotInitialized,\n        'Text is not initialized yet',\n      );\n    }\n\n    const textRange = this.text.indexRangeToPosRange(range[0], range[1]);\n    return [textRange[0].toStruct(), textRange[1].toStruct()];\n  }\n\n  /**\n   * `posRangeToIndexRange` returns indexes of the given TextRangeStruct.\n   */\n  posRangeToIndexRange(range: TextPosStructRange): [number, number] {\n    if (!this.context || !this.text) {\n      throw new YorkieError(\n        Code.ErrNotInitialized,\n        'Text is not initialized yet',\n      );\n    }\n\n    const textRange = this.text.findIndexesFromRange([\n      RGATreeSplitPos.fromStruct(range[0]),\n      RGATreeSplitPos.fromStruct(range[1]),\n    ]);\n    return [textRange[0], textRange[1]];\n  }\n\n  /**\n   * `toTestString` returns a String containing the meta data of the node\n   * for debugging purpose.\n   */\n  toTestString(): string {\n    if (!this.context || !this.text) {\n      throw new YorkieError(\n        Code.ErrNotInitialized,\n        'Text is not initialized yet',\n      );\n    }\n\n    return this.text.toTestString();\n  }\n\n  /**\n   * `values` returns values of this text.\n   */\n  values(): Array<TextValueType<A>> {\n    if (!this.context || !this.text) {\n      throw new YorkieError(\n        Code.ErrNotInitialized,\n        'Text is not initialized yet',\n      );\n    }\n\n    return this.text.values();\n  }\n\n  /**\n   * `length` returns size of RGATreeList.\n   */\n  public get length(): number {\n    return this.text!.length;\n  }\n\n  /**\n   * `getTreeByIndex` returns IndexTree of the text for testing purpose.\n   */\n  public getTreeByIndex(): SplayTree<CRDTTextValue> {\n    return this.text!.getTreeByIndex();\n  }\n\n  /**\n   * `getTreeByID` returns IDTree of the text for testing purpose.\n   */\n  public getTreeByID(): LLRBTree<\n    RGATreeSplitNodeID,\n    RGATreeSplitNode<CRDTTextValue>\n  > {\n    return this.text!.getTreeByID();\n  }\n\n  /**\n   * `toString` returns the string representation of this text.\n   */\n  toString(): string {\n    if (!this.context || !this.text) {\n      throw new YorkieError(\n        Code.ErrNotInitialized,\n        'Text is not initialized yet',\n      );\n    }\n\n    return this.text.toString();\n  }\n\n  /**\n   * `toJSON` returns the JSON string of this tree.\n   */\n  public toJSON(): string {\n    if (!this.context || !this.text) {\n      throw new YorkieError(\n        Code.ErrNotInitialized,\n        'Text is not initialized yet',\n      );\n    }\n\n    return this.text.toJSON();\n  }\n\n  /**\n   * `toJSForTest` returns value with meta data for testing.\n   */\n  public toJSForTest(): Devtools.JSONElement {\n    if (!this.context || !this.text) {\n      throw new YorkieError(\n        Code.ErrNotInitialized,\n        'Text is not initialized yet',\n      );\n    }\n\n    return this.text.toJSForTest();\n  }\n\n  /**\n   * `createRangeForTest` returns pair of RGATreeSplitNodePos of the given indexes\n   * for testing purpose.\n   * Unlike `CRDTText.createRange`, it does not reject an index inside a\n   * surrogate pair.\n   */\n  createRangeForTest(fromIdx: number, toIdx: number): RGATreeSplitPosRange {\n    if (!this.context || !this.text) {\n      throw new YorkieError(\n        Code.ErrNotInitialized,\n        'Text is not initialized yet',\n      );\n    }\n\n    return this.text.indexRangeToPosRange(fromIdx, toIdx);\n  }\n}\n","/*\n * Copyright 2020 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TimeTicket } from '@yorkie-js/sdk/src/document/time/ticket';\nimport { ChangeContext } from '@yorkie-js/sdk/src/document/change/context';\nimport { Primitive } from '@yorkie-js/sdk/src/document/crdt/primitive';\nimport { IncreaseOperation } from '@yorkie-js/sdk/src/document/operation/increase_operation';\nimport {\n  CounterType,\n  CRDTCounter,\n} from '@yorkie-js/sdk/src/document/crdt/counter';\nimport type * as Devtools from '@yorkie-js/sdk/src/devtools/types';\nimport { Code, YorkieError } from '@yorkie-js/sdk/src/util/error';\n\n/**\n * `BaseCounter` is an internal base that holds the shared state and\n * initialization logic for Counter and DedupCounter. Not exported.\n */\nclass BaseCounter {\n  protected valueType: CounterType;\n  protected value: number | bigint;\n  protected context?: ChangeContext;\n  protected counter?: CRDTCounter;\n\n  constructor(valueType: CounterType, value: number | bigint) {\n    this.valueType = valueType;\n    this.value = value;\n  }\n\n  /**\n   * `initialize` links this proxy to a ChangeContext and CRDTCounter.\n   */\n  public initialize(context: ChangeContext, counter: CRDTCounter): void {\n    this.valueType = counter.getValueType();\n    this.context = context;\n    this.counter = counter;\n    this.value = counter.getValue();\n  }\n\n  /**\n   * `getID` returns the ID of this counter.\n   */\n  public getID(): TimeTicket {\n    return this.counter!.getID();\n  }\n\n  /**\n   * `getValueType` returns the value type of this counter.\n   */\n  public getValueType(): CounterType {\n    return this.valueType;\n  }\n\n  /**\n   * `toJSForTest` returns value with meta data for testing.\n   */\n  public toJSForTest(): Devtools.JSONElement {\n    if (!this.context || !this.counter) {\n      throw new YorkieError(\n        Code.ErrNotInitialized,\n        'Counter is not initialized yet',\n      );\n    }\n\n    return this.counter.toJSForTest();\n  }\n\n  /**\n   * `ensureInitialized` throws if this counter has not been initialized.\n   */\n  protected ensureInitialized(): void {\n    if (!this.context || !this.counter) {\n      throw new YorkieError(\n        Code.ErrNotInitialized,\n        'Counter is not initialized yet',\n      );\n    }\n  }\n}\n\n/**\n * `Counter` is a numeric counter that supports `increase()`.\n * For counting unique actors, use `DedupCounter` instead.\n *\n * ```typescript\n * // Type is inferred from value:\n * root.count = new Counter(0);           // Int\n * root.count = new Counter(0n);           // Long\n * ```\n */\nexport class Counter extends BaseCounter {\n  constructor(value: number | bigint) {\n    const type = typeof value === 'bigint' ? CounterType.Long : CounterType.Int;\n    super(type, value);\n  }\n\n  /**\n   * `getValue` returns the value of this counter.\n   */\n  public getValue(): number | bigint {\n    return this.value;\n  }\n\n  /**\n   * `increase` increases numeric data.\n   */\n  public increase(v: number | bigint): Counter {\n    this.ensureInitialized();\n\n    const ticket = this.context!.issueTimeTicket();\n    const value = Primitive.of(v, ticket);\n    if (!value.isNumericType()) {\n      throw new TypeError(\n        `Unsupported type of value: ${typeof value.getValue()}`,\n      );\n    }\n\n    this.counter!.increase(value);\n    this.context!.push(\n      IncreaseOperation.create(this.counter!.getCreatedAt(), value, ticket),\n    );\n\n    return this;\n  }\n}\n\n/**\n * `DedupCounter` is a Counter that uses HyperLogLog to count unique actors.\n * Use `add(actor)` to record a unique visitor. Provides approximate counts\n * with ~2% error rate.\n *\n * ```typescript\n * doc.update((root) => {\n *   root.uv = new yorkie.DedupCounter();\n *   root.uv.add(userId);\n * });\n * ```\n */\nexport class DedupCounter extends BaseCounter {\n  constructor() {\n    super(CounterType.IntDedup, 0);\n  }\n\n  /**\n   * `getValue` returns the value of this counter. Always a number since\n   * DedupCounter only supports IntDedup.\n   */\n  public getValue(): number {\n    return this.value as number;\n  }\n\n  /**\n   * `add` records a unique actor in the dedup counter. If the actor has\n   * already been counted, the call is ignored.\n   */\n  public add(actor: string): DedupCounter {\n    this.ensureInitialized();\n    if (!actor) {\n      throw new YorkieError(Code.ErrInvalidArgument, 'actor is required');\n    }\n\n    const ticket = this.context!.issueTimeTicket();\n    const value = Primitive.of(1, ticket);\n    this.counter!.increaseDedup(value, actor);\n    this.context!.push(\n      IncreaseOperation.create(\n        this.counter!.getCreatedAt(),\n        value,\n        ticket,\n        actor,\n      ),\n    );\n\n    return this;\n  }\n}\n\n/**\n * `isCounter` returns true if the value is a Counter or DedupCounter.\n * Used internally to detect counter instances during document updates.\n */\nexport function isCounter(value: unknown): value is Counter | DedupCounter {\n  return value instanceof Counter || value instanceof DedupCounter;\n}\n","/*\n * Copyright 2023 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TimeTicket } from '@yorkie-js/sdk/src/document/time/ticket';\nimport { ChangeContext } from '@yorkie-js/sdk/src/document/change/context';\nimport {\n  CRDTTree,\n  CRDTTreeNodeID,\n  CRDTTreeNode,\n  CRDTTreePos,\n} from '@yorkie-js/sdk/src/document/crdt/tree';\n\nimport {\n  IndexTree,\n  DefaultRootType,\n  DefaultTextType,\n} from '@yorkie-js/sdk/src/util/index_tree';\nimport { TreeEditOperation } from '@yorkie-js/sdk/src/document/operation/tree_edit_operation';\nimport { isEmpty, stringifyObjectValues } from '@yorkie-js/sdk/src/util/object';\nimport { RHT } from '../crdt/rht';\nimport { TreeStyleOperation } from '../operation/tree_style_operation';\nimport type {\n  ElementNode,\n  TextNode,\n  TreeNode,\n  TreeChange,\n  TreeChangeType,\n  TreePosStructRange,\n  CRDTTreeNodeIDStruct,\n} from '@yorkie-js/sdk/src/document/crdt/tree';\nimport type * as Devtools from '@yorkie-js/sdk/src/devtools/types';\nimport { Code, YorkieError } from '@yorkie-js/sdk/src/util/error';\nimport { ensureNoLoneSurrogate } from '@yorkie-js/sdk/src/document/json/strings';\n\n/**\n * NOTE(hackerwins): In normal case, we should define the following types in\n * json package, because they are directly used by the user. However, we define\n * them in crdt package to avoid circular dependency between json and crdt.\n */\nexport {\n  TreeNode,\n  ElementNode,\n  TextNode,\n  TreeChange,\n  TreeChangeType,\n  TreePosStructRange,\n  CRDTTreeNodeIDStruct,\n};\n\n/**\n * `buildDescendants` builds descendants of the given tree node.\n */\nfunction buildDescendants(\n  treeNode: TreeNode,\n  parent: CRDTTreeNode,\n  context: ChangeContext,\n) {\n  const { type } = treeNode;\n  const ticket = context.issueTimeTicket();\n\n  if (type === DefaultTextType) {\n    validateTextNode(treeNode as TextNode);\n    const { value } = treeNode as TextNode;\n    const textNode = CRDTTreeNode.create(\n      CRDTTreeNodeID.of(ticket, 0),\n      type,\n      value,\n    );\n\n    parent.append(textNode);\n  } else {\n    const { children = [] } = treeNode as ElementNode;\n    const { attributes } = treeNode as ElementNode;\n    let attrs;\n\n    if (typeof attributes === 'object' && !isEmpty(attributes)) {\n      const stringifiedAttributes = stringifyObjectValues(attributes);\n      attrs = new RHT();\n\n      for (const [key, value] of Object.entries(stringifiedAttributes)) {\n        attrs.set(key, value, ticket);\n      }\n    }\n    const elementNode = CRDTTreeNode.create(\n      CRDTTreeNodeID.of(ticket, 0),\n      type,\n      undefined,\n      attrs,\n    );\n\n    parent.append(elementNode);\n\n    for (const child of children) {\n      buildDescendants(child, elementNode, context);\n    }\n  }\n}\n\n/**\n * createCRDTTreeNode returns CRDTTreeNode by given TreeNode.\n */\nfunction createCRDTTreeNode(context: ChangeContext, content: TreeNode) {\n  const { type } = content;\n  const ticket = context.issueTimeTicket();\n\n  let root;\n  if (content.type === DefaultTextType) {\n    const { value } = content as TextNode;\n    root = CRDTTreeNode.create(CRDTTreeNodeID.of(ticket, 0), type, value);\n  } else if (content) {\n    const { children = [] } = content as ElementNode;\n    const { attributes } = content as ElementNode;\n    let attrs;\n\n    if (typeof attributes === 'object' && !isEmpty(attributes)) {\n      const stringifiedAttributes = stringifyObjectValues(attributes);\n      attrs = new RHT();\n\n      for (const [key, value] of Object.entries(stringifiedAttributes)) {\n        attrs.set(key, value, ticket);\n      }\n    }\n\n    root = CRDTTreeNode.create(\n      CRDTTreeNodeID.of(context.issueTimeTicket(), 0),\n      type,\n      undefined,\n      attrs,\n    );\n\n    for (const child of children) {\n      buildDescendants(child, root, context);\n    }\n  }\n\n  return root;\n}\n\n/**\n * `comparePath` compares two paths of equal length in document order.\n */\nfunction comparePath(a: Array<number>, b: Array<number>): number {\n  for (let i = 0; i < a.length; i++) {\n    if (a[i] !== b[i]) {\n      return a[i] - b[i];\n    }\n  }\n  return 0;\n}\n\n/**\n * `validateTextNode` ensures that a text node has a non-empty string value\n * that does not carry a lone half of a UTF-16 surrogate pair. The index guard\n * in `CRDTTree.findPos` refuses to split a pair; this is the other half of the\n * same contract, since a stored lone half pairs with the code unit next to it\n * and makes the index at that seam permanently unusable.\n */\nfunction validateTextNode(textNode: TextNode): boolean {\n  if (!textNode.value.length) {\n    throw new YorkieError(\n      Code.ErrInvalidArgument,\n      'text node cannot have empty value',\n    );\n  }\n  ensureNoLoneSurrogate(textNode.value);\n\n  return true;\n}\n\n/**\n * `validateTreeNodes` ensures that treeNodes consists of only one type.\n */\nfunction validateTreeNodes(treeNodes: Array<TreeNode>): boolean {\n  if (!treeNodes.length) {\n    return true;\n  }\n\n  const firstTreeNodeType = treeNodes[0].type;\n  if (firstTreeNodeType === DefaultTextType) {\n    for (const treeNode of treeNodes) {\n      const { type } = treeNode;\n      if (type !== DefaultTextType) {\n        throw new YorkieError(\n          Code.ErrInvalidArgument,\n          'element node and text node cannot be passed together',\n        );\n      }\n      validateTextNode(treeNode as TextNode);\n    }\n  } else {\n    for (const treeNode of treeNodes) {\n      const { type } = treeNode;\n      if (type === DefaultTextType) {\n        throw new YorkieError(\n          Code.ErrInvalidArgument,\n          'element node and text node cannot be passed together',\n        );\n      }\n    }\n  }\n\n  return true;\n}\n\n/**\n * `Tree` is a CRDT-based tree structure that is used to represent the document\n * tree of text-based editor such as ProseMirror.\n */\nexport class Tree {\n  private initialRoot?: ElementNode;\n  private context?: ChangeContext;\n  private tree?: CRDTTree;\n\n  constructor(initialRoot?: ElementNode) {\n    this.initialRoot = initialRoot;\n  }\n\n  /**\n   * `initialize` initialize this tree with context and internal tree.\n   */\n  public initialize(context: ChangeContext, tree: CRDTTree): void {\n    this.context = context;\n    this.tree = tree;\n  }\n\n  /**\n   * `getID` returns the ID of this tree.\n   */\n  public getID(): TimeTicket {\n    return this.tree!.getID();\n  }\n\n  /**\n   * `buildRoot` builds the root of this tree with the given initial root\n   * which set by the user.\n   */\n  public buildRoot(context: ChangeContext): CRDTTreeNode {\n    if (!this.initialRoot) {\n      return CRDTTreeNode.create(\n        CRDTTreeNodeID.of(context.issueTimeTicket(), 0),\n        DefaultRootType,\n      );\n    }\n\n    // TODO(hackerwins): Need to use the ticket of operation of creating tree.\n    const root = CRDTTreeNode.create(\n      CRDTTreeNodeID.of(context.issueTimeTicket(), 0),\n      this.initialRoot.type,\n    );\n\n    for (const child of this.initialRoot.children) {\n      buildDescendants(child, root, context);\n    }\n\n    return root;\n  }\n\n  /**\n   * `getSize` returns the size of this tree.\n   */\n  public getSize(): number {\n    if (!this.context || !this.tree) {\n      throw new YorkieError(\n        Code.ErrNotInitialized,\n        'Tree is not initialized yet',\n      );\n    }\n\n    return this.tree.getSize();\n  }\n\n  /**\n   * `getNodeSize` returns the node size of this tree.\n   */\n  public getNodeSize(): number {\n    if (!this.context || !this.tree) {\n      throw new YorkieError(\n        Code.ErrNotInitialized,\n        'Tree is not initialized yet',\n      );\n    }\n\n    return this.tree.getNodeSize();\n  }\n\n  /**\n   * `getIndexTree` returns the index tree of this tree.\n   */\n  public getIndexTree(): IndexTree<CRDTTreeNode> {\n    if (!this.context || !this.tree) {\n      throw new YorkieError(\n        Code.ErrNotInitialized,\n        'Tree is not initialized yet',\n      );\n    }\n\n    return this.tree.getIndexTree();\n  }\n\n  /**\n   * `splitByPath` splits the tree by the given path.\n   * A path whose text offset falls inside a UTF-16 surrogate pair throws\n   * `ErrInvalidArgument`.\n   */\n  public splitByPath(path: Array<number>) {\n    if (!this.context || !this.tree) {\n      throw new YorkieError(\n        Code.ErrNotInitialized,\n        'Tree is not initialized yet',\n      );\n    }\n\n    if (!path.length) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        'path should not be empty',\n      );\n    }\n\n    // A split divides the node holding the position into two siblings, so it\n    // needs a parent to hold them. The root has none, and `edit` takes the\n    // position anyway and pushes an operation that changes nothing.\n    const treePos = this.tree.pathToTreePos(path);\n    const target = treePos.node.isText ? treePos.node.parent! : treePos.node;\n\n    if (!target.parent) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        'the root node cannot be split',\n      );\n    }\n\n    // Split through `edit`'s split level rather than lowering to a delete plus\n    // an insert of a copied node. The copy made each replica insert its own\n    // node, so two replicas splitting the same position kept both copies.\n    const pos = this.tree.pathToPos(path);\n\n    this.editInternal(pos, pos, [], 1);\n  }\n\n  /**\n   * `mergeByPath` merges the tree by the given path.\n   */\n  public mergeByPath(path: Array<number>) {\n    if (!this.context || !this.tree) {\n      throw new YorkieError(\n        Code.ErrNotInitialized,\n        'Tree is not initialized yet',\n      );\n    }\n\n    if (!path.length) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        'path should not be empty',\n      );\n    }\n\n    const treePos = this.tree.pathToTreePos(path);\n\n    if (treePos.node.isText) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        'text node cannot be merged',\n      );\n    }\n\n    const { node: parentNode, offset } = treePos;\n    const leftSibling = parentNode.children[offset - 1];\n\n    if (!leftSibling) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        'the first child cannot be merged',\n      );\n    }\n\n    // Merge by deleting the empty range across the boundary, rather than\n    // lowering to a delete of the node plus an insert of its children copied\n    // into the left sibling. The copy made each replica insert its own\n    // children, so two replicas merging the same boundary kept both copies.\n    // Deleting the boundary tokens re-inserts nothing and is idempotent.\n    const parentPath = path.slice(0, -1);\n    const fromPath = [\n      ...parentPath,\n      offset - 1,\n      leftSibling.hasTextChild()\n        ? leftSibling.getChildrenText().length\n        : leftSibling.children.length,\n    ];\n    const fromPos = this.tree.pathToPos(fromPath);\n    const toPos = this.tree.pathToPos([...path, 0]);\n\n    this.editInternal(fromPos, toPos, []);\n  }\n\n  /**\n   * `styleByPath` sets the attributes to the element at the given\n   * path.\n   */\n  public styleByPath(\n    path: Array<number>,\n    attributes: { [key: string]: any },\n  ): void;\n  /**\n   * `styleByPath` sets the attributes to the elements in the given\n   * path range.\n   */\n  public styleByPath(\n    fromPath: Array<number>,\n    toPath: Array<number>,\n    attributes: { [key: string]: any },\n  ): void;\n  /**\n   * `styleByPath` sets the attributes to the elements of the given\n   * path. When called with two paths, it styles the range between\n   * them.\n   * A path whose text offset falls inside a UTF-16 surrogate pair throws\n   * `ErrInvalidArgument`.\n   */\n  public styleByPath(\n    fromPathOrPath: Array<number>,\n    toPathOrAttrs: Array<number> | { [key: string]: any },\n    maybeAttrs?: { [key: string]: any },\n  ): void {\n    if (!this.context || !this.tree) {\n      throw new YorkieError(\n        Code.ErrNotInitialized,\n        'Tree is not initialized yet',\n      );\n    }\n\n    let fromPos: CRDTTreePos;\n    let toPos: CRDTTreePos;\n    let attributes: { [key: string]: any };\n\n    if (Array.isArray(toPathOrAttrs)) {\n      // Range mode: styleByPath(fromPath, toPath, attrs)\n      const fromPath = fromPathOrPath;\n      const toPath = toPathOrAttrs;\n      attributes = maybeAttrs!;\n\n      if (fromPath.length !== toPath.length) {\n        throw new YorkieError(\n          Code.ErrInvalidArgument,\n          'path length should be equal',\n        );\n      }\n      if (!fromPath.length || !toPath.length) {\n        throw new YorkieError(\n          Code.ErrInvalidArgument,\n          'path should not be empty',\n        );\n      }\n      // Same contract as the index form: a range given backwards is a caller\n      // error, not an empty range.\n      if (comparePath(fromPath, toPath) > 0) {\n        throw new YorkieError(\n          Code.ErrInvalidArgument,\n          'from should be less than or equal to to',\n        );\n      }\n\n      fromPos = this.tree.pathToPos(fromPath);\n      toPos = this.tree.pathToPos(toPath);\n    } else {\n      // Single-path mode: styleByPath(path, attrs)\n      const path = fromPathOrPath;\n      attributes = toPathOrAttrs;\n\n      if (!path.length) {\n        throw new YorkieError(\n          Code.ErrInvalidArgument,\n          'path should not be empty',\n        );\n      }\n\n      [fromPos, toPos] = this.tree.pathToPosRange(path);\n    }\n\n    const ticket = this.context.issueTimeTicket();\n    const attrs = attributes ? stringifyObjectValues(attributes) : undefined;\n\n    const [pairs, , size] = this.tree!.style([fromPos, toPos], attrs, ticket);\n\n    this.context!.acc(size.live);\n    this.context!.accGC(size.gc);\n\n    for (const pair of pairs) {\n      this.context!.registerGCPair(pair);\n    }\n\n    this.context.push(\n      TreeStyleOperation.create(\n        this.tree.getCreatedAt(),\n        fromPos,\n        toPos,\n        attrs ? new Map(Object.entries(attrs)) : new Map(),\n        ticket,\n      ),\n    );\n  }\n\n  /**\n   * `style` sets the attributes to the elements of the given range.\n   * An index inside a UTF-16 surrogate pair throws `ErrInvalidArgument`.\n   */\n  public style(\n    fromIdx: number,\n    toIdx: number,\n    attributes: { [key: string]: any },\n  ) {\n    if (!this.context || !this.tree) {\n      throw new YorkieError(\n        Code.ErrNotInitialized,\n        'Tree is not initialized yet',\n      );\n    }\n\n    if (fromIdx > toIdx) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        'from should be less than or equal to to',\n      );\n    }\n\n    const fromPos = this.tree.findPos(fromIdx);\n    const toPos = this.tree.findPos(toIdx);\n    const ticket = this.context.issueTimeTicket();\n    const attrs = attributes ? stringifyObjectValues(attributes) : undefined;\n\n    const [pairs, , size] = this.tree!.style([fromPos, toPos], attrs, ticket);\n\n    this.context!.acc(size.live);\n    this.context!.accGC(size.gc);\n\n    for (const pair of pairs) {\n      this.context!.registerGCPair(pair);\n    }\n\n    this.context.push(\n      TreeStyleOperation.create(\n        this.tree.getCreatedAt(),\n        fromPos,\n        toPos,\n        attrs ? new Map(Object.entries(attrs)) : new Map(),\n        ticket,\n      ),\n    );\n  }\n\n  /**\n   * `removeStyle` removes the attributes to the elements of the given range.\n   * An index inside a UTF-16 surrogate pair throws `ErrInvalidArgument`.\n   */\n  public removeStyle(\n    fromIdx: number,\n    toIdx: number,\n    attributesToRemove: Array<string>,\n  ) {\n    if (!this.context || !this.tree) {\n      throw new YorkieError(\n        Code.ErrNotInitialized,\n        'Tree is not initialized yet',\n      );\n    }\n\n    if (fromIdx > toIdx) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        'from should be less than or equal to to',\n      );\n    }\n\n    const fromPos = this.tree.findPos(fromIdx);\n    const toPos = this.tree.findPos(toIdx);\n    const ticket = this.context.issueTimeTicket();\n\n    const [pairs, , size] = this.tree!.removeStyle(\n      [fromPos, toPos],\n      attributesToRemove,\n      ticket,\n    );\n\n    this.context!.acc(size.live);\n    this.context!.accGC(size.gc);\n\n    for (const pair of pairs) {\n      this.context!.registerGCPair(pair);\n    }\n\n    this.context.push(\n      TreeStyleOperation.createTreeRemoveStyleOperation(\n        this.tree.getCreatedAt(),\n        fromPos,\n        toPos,\n        attributesToRemove,\n        ticket,\n      ),\n    );\n  }\n\n  /**\n   * `removeStyleByPath` removes the attributes of the elements in\n   * the given path range.\n   * A path whose text offset falls inside a UTF-16 surrogate pair throws\n   * `ErrInvalidArgument`.\n   */\n  public removeStyleByPath(\n    fromPath: Array<number>,\n    toPath: Array<number>,\n    attributesToRemove: Array<string>,\n  ): void {\n    if (!this.context || !this.tree) {\n      throw new YorkieError(\n        Code.ErrNotInitialized,\n        'Tree is not initialized yet',\n      );\n    }\n\n    if (fromPath.length !== toPath.length) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        'path length should be equal',\n      );\n    }\n    if (!fromPath.length || !toPath.length) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        'path should not be empty',\n      );\n    }\n\n    // Same contract as the index form: a range given backwards is a caller\n    // error, not an empty range.\n    if (comparePath(fromPath, toPath) > 0) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        'from should be less than or equal to to',\n      );\n    }\n\n    const fromPos = this.tree.pathToPos(fromPath);\n    const toPos = this.tree.pathToPos(toPath);\n    const ticket = this.context.issueTimeTicket();\n\n    const [pairs, , size] = this.tree!.removeStyle(\n      [fromPos, toPos],\n      attributesToRemove,\n      ticket,\n    );\n\n    this.context!.acc(size.live);\n    this.context!.accGC(size.gc);\n\n    for (const pair of pairs) {\n      this.context!.registerGCPair(pair);\n    }\n\n    this.context.push(\n      TreeStyleOperation.createTreeRemoveStyleOperation(\n        this.tree.getCreatedAt(),\n        fromPos,\n        toPos,\n        attributesToRemove,\n        ticket,\n      ),\n    );\n  }\n\n  private editInternal(\n    fromPos: CRDTTreePos,\n    toPos: CRDTTreePos,\n    contents: Array<TreeNode>,\n    splitLevel = 0,\n  ): boolean {\n    if (contents.length !== 0 && contents[0]) {\n      validateTreeNodes(contents);\n      if (contents[0].type !== DefaultTextType) {\n        for (const content of contents) {\n          const { children = [] } = content as ElementNode;\n          validateTreeNodes(children);\n        }\n      }\n    }\n\n    const ticket = this.context!.getLastTimeTicket();\n    let crdtNodes = new Array<CRDTTreeNode>();\n\n    if (contents[0]?.type === DefaultTextType) {\n      let compVal = '';\n      for (const content of contents) {\n        const { value } = content as TextNode;\n        compVal += value;\n      }\n      crdtNodes.push(\n        CRDTTreeNode.create(\n          CRDTTreeNodeID.of(this.context!.issueTimeTicket(), 0),\n          DefaultTextType,\n          compVal,\n        ),\n      );\n    } else {\n      crdtNodes = contents\n        .map((content) => content && createCRDTTreeNode(this.context!, content))\n        .filter((a) => a) as Array<CRDTTreeNode>;\n    }\n\n    // Splitting an element creates nodes that need tickets. Record the ones\n    // issued so the operation can carry them: every other replica then uses\n    // them instead of reconstructing them from the operation, which it cannot\n    // do correctly once content has descendants.\n    const splitTickets: Array<TimeTicket> = [];\n    const [, pairs, diff] = this.tree!.edit(\n      [fromPos, toPos],\n      crdtNodes.length\n        ? crdtNodes.map((crdtNode) => crdtNode?.deepcopy())\n        : undefined,\n      splitLevel,\n      ticket,\n      () => {\n        const issued = this.context!.issueTimeTicket();\n        splitTickets.push(issued);\n        return issued;\n      },\n    );\n\n    this.context!.acc(diff);\n\n    for (const pair of pairs) {\n      this.context!.registerGCPair(pair);\n    }\n\n    const edit = TreeEditOperation.create(\n      this.tree!.getCreatedAt(),\n      fromPos,\n      toPos,\n      crdtNodes.length ? crdtNodes : undefined,\n      splitLevel,\n      ticket,\n    );\n    edit.setSplitTickets(splitTickets);\n    this.context!.push(edit);\n\n    return true;\n  }\n\n  /**\n   * `editByPath` edits this tree with the given node and path.\n   * A path whose text offset falls inside a UTF-16 surrogate pair throws\n   * `ErrInvalidArgument`.\n   */\n  public editByPath(\n    fromPath: Array<number>,\n    toPath: Array<number>,\n    content?: TreeNode,\n    splitLevel = 0,\n  ): boolean {\n    if (!this.context || !this.tree) {\n      throw new YorkieError(\n        Code.ErrNotInitialized,\n        'Tree is not initialized yet',\n      );\n    }\n    if (fromPath.length !== toPath.length) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        'path length should be equal',\n      );\n    }\n    if (!fromPath.length || !toPath.length) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        'path should not be empty',\n      );\n    }\n\n    const fromPos = this.tree.pathToPos(fromPath);\n    const toPos = this.tree.pathToPos(toPath);\n\n    return this.editInternal(\n      fromPos,\n      toPos,\n      content ? [content] : [],\n      splitLevel,\n    );\n  }\n\n  /**\n   * `editBulkByPath` edits this tree with the given node and path.\n   * A path whose text offset falls inside a UTF-16 surrogate pair throws\n   * `ErrInvalidArgument`.\n   */\n  public editBulkByPath(\n    fromPath: Array<number>,\n    toPath: Array<number>,\n    contents: Array<TreeNode>,\n    splitLevel = 0,\n  ): boolean {\n    if (!this.context || !this.tree) {\n      throw new YorkieError(\n        Code.ErrNotInitialized,\n        'Tree is not initialized yet',\n      );\n    }\n    if (fromPath.length !== toPath.length) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        'path length should be equal',\n      );\n    }\n    if (!fromPath.length || !toPath.length) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        'path should not be empty',\n      );\n    }\n\n    const fromPos = this.tree.pathToPos(fromPath);\n    const toPos = this.tree.pathToPos(toPath);\n\n    return this.editInternal(fromPos, toPos, contents, splitLevel);\n  }\n\n  /**\n   * `edit` edits this tree with the given nodes.\n   * An index inside a UTF-16 surrogate pair throws `ErrInvalidArgument`.\n   */\n  public edit(\n    fromIdx: number,\n    toIdx: number,\n    content?: TreeNode,\n    splitLevel = 0,\n  ): boolean {\n    if (!this.context || !this.tree) {\n      throw new YorkieError(\n        Code.ErrNotInitialized,\n        'Tree is not initialized yet',\n      );\n    }\n    if (fromIdx > toIdx) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        'from should be less than or equal to to',\n      );\n    }\n\n    const fromPos = this.tree.findPos(fromIdx);\n    const toPos = this.tree.findPos(toIdx);\n\n    return this.editInternal(\n      fromPos,\n      toPos,\n      content ? [content] : [],\n      splitLevel,\n    );\n  }\n\n  /**\n   * `editBulk` edits this tree with the given nodes.\n   * An index inside a UTF-16 surrogate pair throws `ErrInvalidArgument`.\n   */\n  public editBulk(\n    fromIdx: number,\n    toIdx: number,\n    contents: Array<TreeNode>,\n    splitLevel = 0,\n  ): boolean {\n    if (!this.context || !this.tree) {\n      throw new YorkieError(\n        Code.ErrNotInitialized,\n        'Tree is not initialized yet',\n      );\n    }\n    if (fromIdx > toIdx) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        'from should be less than or equal to to',\n      );\n    }\n\n    const fromPos = this.tree.findPos(fromIdx);\n    const toPos = this.tree.findPos(toIdx);\n\n    return this.editInternal(fromPos, toPos, contents, splitLevel);\n  }\n\n  /**\n   * `toXML` returns the XML string of this tree.\n   */\n  public toXML(): string {\n    if (!this.context || !this.tree) {\n      throw new YorkieError(\n        Code.ErrNotInitialized,\n        'Tree is not initialized yet',\n      );\n    }\n\n    return this.tree.toXML();\n  }\n\n  /**\n   * `toJSON` returns the JSON string of this tree.\n   */\n  public toJSON(): string {\n    if (!this.context || !this.tree) {\n      throw new YorkieError(\n        Code.ErrNotInitialized,\n        'Tree is not initialized yet',\n      );\n    }\n\n    return this.tree.toJSON();\n  }\n\n  /**\n   * `toJSForTest` returns value with meta data for testing.\n   */\n  public toJSForTest(): Devtools.JSONElement {\n    if (!this.context || !this.tree) {\n      throw new YorkieError(\n        Code.ErrNotInitialized,\n        'Tree is not initialized yet',\n      );\n    }\n\n    return this.tree.toJSForTest();\n  }\n\n  /**\n   * `toJSInfoForTest` returns detailed TreeNode information for use in Devtools.\n   */\n  public toJSInfoForTest(): Devtools.TreeNodeInfo {\n    if (!this.context || !this.tree) {\n      throw new YorkieError(\n        Code.ErrNotInitialized,\n        'Tree is not initialized yet',\n      );\n    }\n\n    return this.tree.toJSInfoForTest();\n  }\n\n  /**\n   * `getRootTreeNode` returns TreeNode of this tree.\n   */\n  public getRootTreeNode() {\n    if (!this.context || !this.tree) {\n      throw new YorkieError(\n        Code.ErrNotInitialized,\n        'Tree is not initialized yet',\n      );\n    }\n\n    return this.tree.getRootTreeNode();\n  }\n\n  /**\n   * `indexToPath` returns the path of the given index.\n   */\n  public indexToPath(index: number): Array<number> {\n    if (!this.context || !this.tree) {\n      throw new YorkieError(\n        Code.ErrNotInitialized,\n        'Tree is not initialized yet',\n      );\n    }\n\n    return this.tree.indexToPath(index);\n  }\n\n  /**\n   * `pathToIndex` returns the index of given path.\n   */\n  public pathToIndex(path: Array<number>): number {\n    if (!this.context || !this.tree) {\n      throw new YorkieError(\n        Code.ErrNotInitialized,\n        'Tree is not initialized yet',\n      );\n    }\n\n    return this.tree.pathToIndex(path);\n  }\n\n  /**\n   * `pathRangeToPosRange` converts the path range into the position range.\n   */\n  pathRangeToPosRange(\n    range: [Array<number>, Array<number>],\n  ): TreePosStructRange {\n    if (!this.context || !this.tree) {\n      throw new YorkieError(\n        Code.ErrNotInitialized,\n        'Tree is not initialized yet',\n      );\n    }\n\n    const indexRange: [number, number] = [\n      this.tree.pathToIndex(range[0]),\n      this.tree.pathToIndex(range[1]),\n    ];\n    const posRange = this.tree.indexRangeToPosRange(indexRange);\n    return [posRange[0].toStruct(), posRange[1].toStruct()];\n  }\n\n  /**\n   * `indexRangeToPosRange` converts the index range into the position range.\n   */\n  indexRangeToPosRange(range: [number, number]): TreePosStructRange {\n    if (!this.context || !this.tree) {\n      throw new YorkieError(\n        Code.ErrNotInitialized,\n        'Tree is not initialized yet',\n      );\n    }\n\n    return this.tree.indexRangeToPosStructRange(range);\n  }\n\n  /**\n   * `posRangeToIndexRange` converts the position range into the index range.\n   */\n  posRangeToIndexRange(range: TreePosStructRange): [number, number] {\n    if (!this.context || !this.tree) {\n      throw new YorkieError(\n        Code.ErrNotInitialized,\n        'Tree is not initialized yet',\n      );\n    }\n\n    const posRange: [CRDTTreePos, CRDTTreePos] = [\n      CRDTTreePos.fromStruct(range[0]),\n      CRDTTreePos.fromStruct(range[1]),\n    ];\n\n    const indexRange = this.tree.posRangeToIndexRange(posRange);\n    this.registerPendingGCPairs();\n    return indexRange;\n  }\n\n  /**\n   * `posRangeToPathRange` converts the position range into the path range.\n   */\n  posRangeToPathRange(\n    range: TreePosStructRange,\n  ): [Array<number>, Array<number>] {\n    if (!this.context || !this.tree) {\n      throw new YorkieError(\n        Code.ErrNotInitialized,\n        'Tree is not initialized yet',\n      );\n    }\n\n    const posRange: [CRDTTreePos, CRDTTreePos] = [\n      CRDTTreePos.fromStruct(range[0]),\n      CRDTTreePos.fromStruct(range[1]),\n    ];\n\n    const pathRange = this.tree.posRangeToPathRange(posRange);\n    this.registerPendingGCPairs();\n    return pathRange;\n  }\n\n  /**\n   * `registerPendingGCPairs` registers with the root any GC pairs the tree\n   * buffered while resolving a position. `posRangeToIndexRange` and\n   * `posRangeToPathRange` split text nodes to locate a position; when the\n   * position lands inside a tombstoned node the split produces a\n   * born-removed piece. Unlike edit/style/removeStyle, these read-path\n   * conversions emit no operation, so the buffered pairs would otherwise\n   * never reach the root and the piece would leak (invisible to GC).\n   */\n  private registerPendingGCPairs(): void {\n    for (const pair of this.tree!.drainPendingGCPairs()) {\n      this.context!.registerGCPair(pair);\n    }\n  }\n}\n","/*\n * Copyright 2020 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ChangeContext } from '@yorkie-js/sdk/src/document/change/context';\nimport { CRDTElement } from '@yorkie-js/sdk/src/document/crdt/element';\nimport { CRDTObject } from '@yorkie-js/sdk/src/document/crdt/object';\nimport { CRDTArray } from '@yorkie-js/sdk/src/document/crdt/array';\nimport {\n  Primitive,\n  PrimitiveValue,\n} from '@yorkie-js/sdk/src/document/crdt/primitive';\nimport { CRDTText } from '@yorkie-js/sdk/src/document/crdt/text';\nimport { CRDTCounter } from '@yorkie-js/sdk/src/document/crdt/counter';\nimport { CRDTTree } from '@yorkie-js/sdk/src/document/crdt/tree';\nimport { RGATreeSplit } from '@yorkie-js/sdk/src/document/crdt/rga_tree_split';\nimport { TimeTicket } from '@yorkie-js/sdk/src/document/time/ticket';\n\nimport {\n  JSONObject,\n  createJSONObject,\n  ObjectProxy,\n} from '@yorkie-js/sdk/src/document/json/object';\nimport {\n  JSONArray,\n  createJSONArray,\n  ArrayProxy,\n} from '@yorkie-js/sdk/src/document/json/array';\nimport { Text } from '@yorkie-js/sdk/src/document/json/text';\nimport {\n  Counter,\n  DedupCounter,\n  isCounter,\n} from '@yorkie-js/sdk/src/document/json/counter';\nimport { Tree } from '@yorkie-js/sdk/src/document/json/tree';\nimport { Indexable } from '../document';\n\n/**\n * `createJSON` create a new instance of JSONObject.\n */\nexport function createJSON<T>(\n  context: ChangeContext,\n  target: CRDTObject,\n): JSONObject<T> {\n  return createJSONObject(context, target);\n}\n\n/**\n * `WrappedElement` is a wrapper of JSONElement that provides `getID()`.\n */\nexport type WrappedElement<T = unknown, A extends Indexable = Indexable> =\n  | Primitive\n  | JSONObject<T>\n  | JSONArray<T>\n  | Text<A>\n  | Counter\n  | DedupCounter\n  | Tree;\n\n/**\n * `JSONElement` is a wrapper for `CRDTElement` that provides users with an\n * easy-to-use interface for manipulating `Document`s.\n */\nexport type JSONElement<T = unknown, A extends Indexable = Indexable> =\n  | PrimitiveValue\n  | JSONObject<T>\n  | JSONArray<T>\n  | Text<A>\n  | Counter\n  | DedupCounter\n  | Tree;\n\n/**\n * `toWrappedElement` converts the CRDT type to `WrappedElement`.\n */\nexport function toWrappedElement(\n  context: ChangeContext,\n  elem?: CRDTElement,\n): WrappedElement | undefined {\n  if (!elem) {\n    return;\n  } else if (elem instanceof Primitive) {\n    return elem;\n  } else if (elem instanceof CRDTObject) {\n    return createJSONObject(context, elem);\n  } else if (elem instanceof CRDTArray) {\n    return createJSONArray(context, elem);\n  } else if (elem instanceof CRDTText) {\n    return new Text(context, elem);\n  } else if (elem instanceof CRDTCounter) {\n    if (elem.isDedup()) {\n      const counter = new DedupCounter();\n      counter.initialize(context, elem);\n      return counter;\n    }\n    const counter = new Counter(0);\n    counter.initialize(context, elem);\n    return counter;\n  } else if (elem instanceof CRDTTree) {\n    const tree = new Tree();\n    tree.initialize(context, elem);\n    return tree;\n  }\n\n  throw new TypeError(`Unsupported type of element: ${typeof elem}`);\n}\n\n/**\n * `toJSONElement` converts the CRDT type to `JSONElement`.\n */\nexport function toJSONElement(\n  context: ChangeContext,\n  elem?: CRDTElement,\n): JSONElement | undefined {\n  const wrappedElement = toWrappedElement(context, elem);\n  if (wrappedElement instanceof Primitive) {\n    return wrappedElement.getValue();\n  }\n\n  return wrappedElement;\n}\n\n/**\n * `buildCRDTElement` constructs a CRDTElement from the given value.\n */\nexport function buildCRDTElement(\n  context: ChangeContext,\n  value: unknown,\n  createdAt: TimeTicket,\n): CRDTElement {\n  let element: CRDTElement;\n  if (Primitive.isSupport(value)) {\n    element = Primitive.of(value as PrimitiveValue, createdAt);\n  } else if (Array.isArray(value)) {\n    element = CRDTArray.create(\n      createdAt,\n      ArrayProxy.buildArrayElements(context, value),\n    );\n  } else if (typeof value === 'object') {\n    if (value instanceof Text) {\n      element = CRDTText.create(RGATreeSplit.create(), createdAt);\n      value.initialize(context, element as CRDTText);\n    } else if (isCounter(value)) {\n      element = CRDTCounter.create(\n        value.getValueType(),\n        value.getValue(),\n        createdAt,\n      );\n      value.initialize(context, element as CRDTCounter);\n    } else if (value instanceof Tree) {\n      element = CRDTTree.create(value.buildRoot(context), createdAt);\n      value.initialize(context, element as CRDTTree);\n    } else {\n      element = CRDTObject.create(\n        createdAt,\n        ObjectProxy.buildObjectMembers(context, value!),\n      );\n    }\n  } else {\n    throw new TypeError(`Unsupported type of value: ${typeof value}`);\n  }\n  return element;\n}\n","/*\n * Copyright 2020 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n  InitialTimeTicket,\n  TimeTicket,\n  TimeTicketSize,\n} from '@yorkie-js/sdk/src/document/time/ticket';\nimport {\n  CRDTContainer,\n  CRDTElement,\n} from '@yorkie-js/sdk/src/document/crdt/element';\nimport { CRDTObject } from '@yorkie-js/sdk/src/document/crdt/object';\nimport { GCPair, GCParent } from '@yorkie-js/sdk/src/document/crdt/gc';\nimport { CRDTText } from '@yorkie-js/sdk/src/document/crdt/text';\nimport { CRDTTree } from '@yorkie-js/sdk/src/document/crdt/tree';\nimport { CRDTArray } from '@yorkie-js/sdk/src/document/crdt/array';\nimport { Code, YorkieError } from '@yorkie-js/sdk/src/util/error';\nimport { VersionVector } from '../time/version_vector';\nimport {\n  DataSize,\n  addDataSizes,\n  subDataSize,\n  DocSize,\n} from '@yorkie-js/sdk/src/util/resource';\nimport { RHTNode } from '@yorkie-js/sdk/src/document/crdt/rht';\n\n/**\n * `CRDTElementPair` is a structure that represents a pair of element and its\n * parent. It is used to find the parent of a specific element to perform\n * garbage collection and to find the path of a specific element.\n */\ninterface CRDTElementPair {\n  element: CRDTElement;\n  parent?: CRDTContainer;\n}\n\n/**\n * `RootStats` is a structure that represents the statistics of the root object.\n */\nexport interface RootStats {\n  /**\n   * `elements` is the number of elements in the root object.\n   */\n  elements?: number;\n\n  /**\n   * `gcElements` is the number of elements that can be garbage collected.\n   */\n  gcElements?: number;\n\n  /**\n   * `gcPairs` is the number of garbage collection pairs.\n   */\n  gcPairs?: number;\n}\n\n/**\n * `CRDTRoot` is a structure that represents the root. It has a hash table of\n * all elements to find a specific element when applying remote changes\n * received from server.\n *\n * Every element has a unique `TimeTicket` at creation, which allows us to find\n * a particular element.\n */\nexport class CRDTRoot {\n  /**\n   * `rootObject` is the root object of the document.\n   */\n  private rootObject: CRDTObject;\n\n  /**\n   * `elementPairMapByCreatedAt` is a hash table that maps the creation time of\n   * an element to the element itself and its parent.\n   */\n  private elementPairMapByCreatedAt: Map<string, CRDTElementPair>;\n\n  /**\n   * `gcElementSetByCreatedAt` is a hash set that contains the creation\n   * time of the removed element. It is used to find the removed element when\n   * executing garbage collection.\n   */\n  private gcElementSetByCreatedAt: Set<string>;\n\n  /**\n   * `sizeInGC` maps every registered element whose size counts toward\n   * `docSize.gc` rather than `docSize.live` to the exact amount\n   * charged. Each element's size belongs\n   * to exactly one of the two, and an element reaches gc by more routes than it\n   * has removals: it can be removed itself, or be a descendant of a removed\n   * container. Recording the amount rather than a flag keeps the two sides\n   * symmetric even though `getDataSize` is not stable over an element's\n   * lifetime -- it grows by a ticket the moment `removedAt` is set, which can\n   * happen after the size has already moved.\n   *\n   * It is keyed by the element, not by its createdAt. A createdAt is meant to\n   * name one element, but it does not for the whole of a document's life: undo\n   * restores a `deepcopy` of a removed element, and the copy keeps the\n   * original's createdAt while the original is still a tombstone. Undoing an\n   * array removal reissues a ticket for the restored container alone, so its\n   * members come back aliasing the tombstoned ones outright. One slot per\n   * createdAt cannot describe both: whichever is charged last displaces the\n   * other, and collecting the displaced one then takes a size out of\n   * `docSize.live` that live was never holding -- which is how docSize goes\n   * negative. One slot per element has room for both.\n   *\n   * A zero size is not the same as no record. It says this element has been\n   * released: charged to neither side, because its subtree was orphaned by a\n   * restore and nothing will ever collect it. Anything that later charges it\n   * again has to know live is not the side to take it from.\n   *\n   * It is a `WeakMap` because a released element's record has no retirement of\n   * its own. `release` writes the zero record for a tombstone the restore\n   * orphaned, and that tombstone is dropped from `gcElementSetByCreatedAt` in\n   * the same breath -- so nothing collects it, nothing deregisters it, and a\n   * strong map would hold both the record and the element for the life of the\n   * document, growing by one subtree per remove/undo. The record is only ever\n   * reached through the element it is keyed by -- this map is never iterated\n   * and never counted -- so its useful lifetime IS the element's: the zero\n   * marker stands for exactly as long as the tombstone stays addressable,\n   * which is the only window in which `moveSizeToGC` or `accMovedElement` can\n   * consult it.\n   */\n  private sizeInGC: WeakMap<CRDTElement, DataSize>;\n\n  /**\n   * `gcPairMap` is a hash table of the registered GC pairs, keyed by both of\n   * a pair's ends.\n   *\n   * The child's IDString alone is not unique document-wide. An RHTNode is\n   * identified by (updatedAt, key), and a split deep-copies the attributes of\n   * the node it splits -- tombstones included, because the copy has to reject\n   * the same stale styles the original does. The copy is therefore a distinct\n   * piece of garbage wearing the original's id. Keying on the child alone made\n   * the two collide, and since `registerGCPair` reads a second registration\n   * under a known key as an un-registration, the second tombstone cancelled\n   * the first instead of joining it.\n   *\n   * The parent is the discriminator because it is what `purge` is called on:\n   * two pairs that share a parent and a child id name the same collectable\n   * thing, two that differ in either do not.\n   */\n  private gcPairMap: Map<string, GCPair>;\n\n  /**\n   * `gcParentIDs` numbers the GC parents this root has seen, so a pair's key\n   * can name its parent. No GC parent carries an identifier of its own, and\n   * minting one per root is enough: a key never has to mean anything outside\n   * the root that made it, since registration, lookup and purge all happen\n   * within one. Weak so a parent the document has dropped is not held alive\n   * by its number.\n   */\n  private gcParentIDs: WeakMap<GCParent, number>;\n  private nextGCParentID: number;\n\n  /**\n   * `docSize` is a structure that represents the size of the document.\n   */\n  private docSize: DocSize;\n\n  /**\n   * `ledgerHolders` are the Texts whose removal ledgers hold cancels that\n   * `garbageCollect` may prune once every replica knows them.\n   */\n  private ledgerHolders: Set<CRDTText>;\n\n  constructor(rootObject: CRDTObject) {\n    this.rootObject = rootObject;\n    this.elementPairMapByCreatedAt = new Map();\n    this.gcElementSetByCreatedAt = new Set();\n    this.sizeInGC = new WeakMap();\n    this.gcPairMap = new Map();\n    this.gcParentIDs = new WeakMap();\n    this.nextGCParentID = 0;\n    this.docSize = { live: { data: 0, meta: 0 }, gc: { data: 0, meta: 0 } };\n    this.ledgerHolders = new Set();\n\n    // NOTE(hackerwins): tombstoned elements are not re-registered here:\n    // registerElement books every one of them into gc, along with the\n    // tombstones its elements carry inside themselves.\n    this.registerElement(rootObject, undefined);\n  }\n\n  /**\n   * `create` creates a new instance of Root.\n   */\n  public static create(): CRDTRoot {\n    return new CRDTRoot(CRDTObject.create(InitialTimeTicket));\n  }\n\n  /**\n   * `findByCreatedAt` returns the element of given creation time.\n   */\n  public findByCreatedAt(createdAt: TimeTicket): CRDTElement | undefined {\n    const pair = this.elementPairMapByCreatedAt.get(createdAt.toIDString());\n    if (!pair) {\n      return;\n    }\n\n    return pair.element;\n  }\n\n  /**\n   * `findElementPairByCreatedAt` returns the element and parent pair\n   * of given creation time.\n   */\n  public findElementPairByCreatedAt(\n    createdAt: TimeTicket,\n  ): CRDTElementPair | undefined {\n    return this.elementPairMapByCreatedAt.get(createdAt.toIDString());\n  }\n\n  /**\n   * `createSubPaths` creates an array of the sub paths for the given element.\n   */\n  public createSubPaths(createdAt: TimeTicket): Array<string> {\n    let pair = this.elementPairMapByCreatedAt.get(createdAt.toIDString());\n    if (!pair) {\n      return [];\n    }\n\n    const subPaths: Array<string> = [];\n    while (pair.parent) {\n      const createdAt = pair.element.getCreatedAt();\n      const subPath = pair.parent.subPathOf(createdAt);\n      if (subPath === undefined) {\n        throw new YorkieError(\n          Code.ErrInvalidArgument,\n          `cant find the given element: ${createdAt.toIDString()}`,\n        );\n      }\n\n      subPaths.unshift(subPath!);\n      pair = this.elementPairMapByCreatedAt.get(\n        pair.parent.getCreatedAt().toIDString(),\n      )!;\n    }\n\n    subPaths.unshift('$');\n    return subPaths;\n  }\n\n  /**\n   * `createPath` creates path of the given element.\n   */\n  public createPath(createdAt: TimeTicket): string {\n    return this.createSubPaths(createdAt).join('.');\n  }\n\n  /**\n   * `registerElement` registers the given element and its descendants to hash table.\n   */\n  public registerElement(element: CRDTElement, parent?: CRDTContainer): void {\n    this.registerLive(element, parent);\n\n    // NOTE(hackerwins): An element can be registered while it already carries a\n    // `removedAt`. An undo re-sets the `deepcopy` its reverse captured, and that\n    // copy keeps the members that were tombstoned before the container was; a\n    // snapshot loads a document that still holds tombstones; and the losing side\n    // of an LWW set is marked removed by `ElementRHT.set` before it is booked.\n    // The size registered above is the post-removal one in every such case, so\n    // it belongs to gc rather than live, and the tombstone has to be\n    // collectable. Booking it here is what makes both true whichever route\n    // brought it in, and it is the one place all of them pass through.\n    //\n    // This is a second pass on purpose. Adopting a tombstone moves its whole\n    // subtree, so doing it while the first pass is still walking would move\n    // descendants live has not been charged for yet, and drive live negative.\n    this.adoptTombstones(element);\n\n    // The two passes above see elements only. A Text/Tree/Array also holds\n    // tombstones *inside* itself -- removed tree nodes, removed text pieces,\n    // removed attributes, dead array positions -- and those are collected\n    // through `gcPairMap`, which only a GC pair reaches.\n    //\n    // Every route that brings such an element in has to book them, not just\n    // snapshot load: a Set/Add/ArraySet payload is decoded by the same readers\n    // a snapshot is, and an undo re-sets a `deepcopy` of a removed container\n    // whose tree may still hold nodes that were tombstoned before it. Left\n    // unbooked they are invisible to every later edit, yet charged to nothing\n    // and collectable by nothing, so the bytes stay in the document forever.\n    this.registerInternalGCPairs(element);\n  }\n\n  /**\n   * `registerInternalGCPairs` books the tombstones the given element and its\n   * descendant elements carry inside themselves into gc. Freshly created\n   * content has none, so this costs one walk of the registered subtree and no\n   * registration in the common case.\n   */\n  private registerInternalGCPairs(element: CRDTElement): void {\n    const register = (elem: CRDTElement) => {\n      if (elem instanceof CRDTText || elem instanceof CRDTTree) {\n        for (const pair of elem.getGCPairs()) {\n          this.registerGCPair(pair);\n        }\n        if (elem instanceof CRDTText && elem.hasCancelledRemovals()) {\n          this.registerLedgerHolder(elem);\n        }\n      } else if (elem instanceof CRDTArray) {\n        // A dead position node holds no element, so the live size its array\n        // was registered with never counted it -- `gcOnlySize` is how a pair\n        // says \"add to gc, take nothing out of live\". The text and tree\n        // pairs say the same thing through `getGCPairs`.\n        for (const node of elem.getAllRGANodes()) {\n          if (!node.getElementEntry() && node.getRemovedAt()) {\n            this.registerGCPair({\n              parent: elem.getRGATreeList(),\n              child: node,\n              gcOnlySize: node.getDataSize(),\n            });\n          }\n        }\n      }\n    };\n\n    register(element);\n    if (element instanceof CRDTContainer) {\n      element.getDescendants((elem) => {\n        register(elem);\n        return false;\n      });\n    }\n  }\n\n  /**\n   * `registerLive` registers the given element and its descendants to the pair\n   * map, and charges `docSize.live` for each.\n   */\n  private registerLive(element: CRDTElement, parent?: CRDTContainer): void {\n    this.elementPairMapByCreatedAt.set(element.getCreatedAt().toIDString(), {\n      parent,\n      element,\n    });\n    addDataSizes(this.docSize.live, element.getDataSize());\n\n    if (element instanceof CRDTContainer) {\n      element.getDescendants((elem, par) => {\n        this.elementPairMapByCreatedAt.set(elem.getCreatedAt().toIDString(), {\n          parent: par,\n          element: elem,\n        });\n        addDataSizes(this.docSize.live, elem.getDataSize());\n        return false;\n      });\n    }\n  }\n\n  /**\n   * `adoptTombstones` books every element of the given subtree that already\n   * carries a `removedAt` into gc.\n   */\n  private adoptTombstones(element: CRDTElement): void {\n    if (element.getRemovedAt()) {\n      this.adoptRemovedElement(element);\n    }\n\n    if (element instanceof CRDTContainer) {\n      element.getDescendants((elem) => {\n        if (elem.getRemovedAt()) {\n          this.adoptRemovedElement(elem);\n        }\n        return false;\n      });\n    }\n  }\n\n  /**\n   * `deregisterElement` deregister the given element and its descendants from hash table.\n   */\n  public deregisterElement(element: CRDTElement): number {\n    let count = 0;\n\n    const deregisterElementInternal = (elem: CRDTElement) => {\n      const createdAt = elem.getCreatedAt().toIDString();\n      // Subtract the size from wherever it is actually counted, and by the\n      // amount actually charged. A descendant created inside an\n      // already-removed container never passed through a removal, so it still\n      // sits in live; subtracting it from gc would push gc below zero and\n      // leave its cost in live forever.\n      const charged = this.sizeInGC.get(elem);\n      if (charged) {\n        subDataSize(this.docSize.gc, charged);\n        this.sizeInGC.delete(elem);\n      } else {\n        subDataSize(this.docSize.live, elem.getDataSize());\n      }\n\n      // NOTE(hackerwins): Drop the index entries by identity, not by key. A\n      // createdAt is meant to name one element, but undo breaks that: it\n      // restores a `deepcopy` of a removed container, and the copy keeps every\n      // descendant's createdAt while the original is still a tombstone. Only\n      // the top level of an undone array set gets a fresh ticket, so the\n      // descendants below it are answered by the live copy while the tombstone\n      // is still the one being collected here. Deleting by key would evict the\n      // live element's entry, and every later operation addressed at it throws\n      // `fail to find` -- inside `applyChangePack`, which is the permanent\n      // desync this release exists to stop.\n      //\n      // The tombstone loses nothing by it: it is already unlinked from the\n      // tree, and whatever now owns the slot will clear it when its own turn\n      // comes. `gcElementSetByCreatedAt` carries no element of its own, so the\n      // pair map is what decides the identity for both.\n      //\n      // The Go SDK reads the same rule off a different structure. Its\n      // `gcElementPairMap` holds the element, because its `elementMap` has no\n      // parent to resolve one through, so it compares that entry directly\n      // instead of borrowing this one's answer. Same rule, one resolver each --\n      // the two differ in where the identity is read, not in what it decides.\n      if (this.elementPairMapByCreatedAt.get(createdAt)?.element === elem) {\n        this.elementPairMapByCreatedAt.delete(createdAt);\n        this.gcElementSetByCreatedAt.delete(createdAt);\n      }\n      count++;\n    };\n\n    deregisterElementInternal(element);\n    if (element instanceof CRDTContainer) {\n      element.getDescendants((e) => {\n        deregisterElementInternal(e);\n        return false;\n      });\n    }\n\n    return count;\n  }\n\n  /**\n   * `registerRemovedElement` registers the given element to the hash set.\n   */\n  public registerRemovedElement(element: CRDTElement): void {\n    const moved = this.moveSizeToGC(element);\n    this.moveDescendantsToGC(element);\n\n    // NOTE(hackerwins): When an element is removed, parent sets the removedAt\n    // to mark the child as removed. That ticket is part of the size charged to\n    // gc just now, but it was not part of what live held -- registerElement ran\n    // before the removal -- so live gets it back. Only on the move that carried\n    // it: a size already in gc, or one moved as a descendant while its own\n    // removedAt is still unset, did not.\n    //\n    // An element that already carried its `removedAt` when it was registered\n    // does not get the refund. `registerElement` books it with\n    // `adoptRemovedElement` and the top-up branch of `moveSizeToGC` then\n    // reports that nothing moved, so a later removal of it lands here with\n    // `moved` false. Live did hold that ticket, and there is nothing to give\n    // back.\n    if (moved && element.getRemovedAt()) {\n      this.docSize.live.meta += TimeTicketSize;\n    }\n\n    this.gcElementSetByCreatedAt.add(element.getCreatedAt().toIDString());\n  }\n\n  /**\n   * `adoptRemovedElement` books an element that was already tombstoned when it\n   * was registered, and its descendants, into gc. It is\n   * `registerRemovedElement` without the ticket refund: the size just charged\n   * to live already included the `removedAt` ticket, so live has nothing to get\n   * back.\n   */\n  private adoptRemovedElement(element: CRDTElement): void {\n    this.moveSizeToGC(element);\n    this.moveDescendantsToGC(element);\n    this.gcElementSetByCreatedAt.add(element.getCreatedAt().toIDString());\n  }\n\n  /**\n   * `moveDescendantsToGC` moves the size of every descendant of the given\n   * element from live to gc.\n   *\n   * NOTE(hackerwins): registerElement books a container and every descendant\n   * into live, and deregisterElement subtracts both when the tombstone is\n   * collected. Removing a container therefore has to move its descendants as\n   * well: booking only the container itself would strand their size in live\n   * forever and drive gc negative once the collection subtracted them.\n   */\n  private moveDescendantsToGC(element: CRDTElement): void {\n    if (!(element instanceof CRDTContainer)) {\n      return;\n    }\n\n    element.getDescendants((elem) => {\n      this.moveSizeToGC(elem);\n      return false;\n    });\n  }\n\n  /**\n   * `moveSizeToGC` moves the size of the given element from live to gc, and\n   * reports whether it moved a size live was holding. A size already charged to\n   * gc for this same element -- because it was removed before, because a\n   * container above it was, or because a restore released it -- only has its\n   * charge topped up: getDataSize grows by a ticket when removedAt is set,\n   * which can happen after the move.\n   *\n   * Another element sharing this createdAt has a charge of its own, and it is\n   * not this one's: this element is still in live and moves in full.\n   */\n  private moveSizeToGC(element: CRDTElement): boolean {\n    const size = element.getDataSize();\n\n    const charged = this.sizeInGC.get(element);\n    if (charged) {\n      addDataSizes(this.docSize.gc, {\n        data: size.data - charged.data,\n        meta: size.meta - charged.meta,\n      });\n      this.sizeInGC.set(element, size);\n      return false;\n    }\n\n    addDataSizes(this.docSize.gc, size);\n    subDataSize(this.docSize.live, size);\n    this.sizeInGC.set(element, size);\n    return true;\n  }\n\n  /**\n   * `unregisterRemovedElementPair` drops the collection entry registered under\n   * the given createdAt, if there is one, and releases the charge it holds. It\n   * reports whether an entry was dropped.\n   *\n   * It is the narrow counterpart of `registerRemovedElement`, for the one\n   * caller that has to retire a tombstone without collecting it: a `Set` that\n   * restores an element under a createdAt a tombstone already answers to.\n   * `ElementRHT.set` has by then re-pointed `nodeMapByCreatedAt` at the\n   * restored copy, so the entry the removal left behind now resolves, through\n   * that index, to live data -- and collection would purge it.\n   *\n   * Deliberately narrow. The obvious alternative, deregistering the tombstone\n   * and its descendants outright, reaches past the entry that is stale: the\n   * tombstone's descendant set can be a strict superset of the restored copy's\n   * -- a peer may have added a child into the container after the undoing\n   * replica took its copy -- and deregistering evicts those descendants from\n   * `elementPairMapByCreatedAt` with nothing to put them back. A later change\n   * addressed at one of them then throws inside `applyChangePack` on every\n   * replica, and permanently on the server, which replays the same change log\n   * to rebuild the document and its snapshots.\n   *\n   * What it still does reach is the accounting, and it has to. The subtree is\n   * orphaned by the restore, so dropping the entry is dropping the only thing\n   * that would ever have collected it. Its cost is released from wherever it\n   * sits -- `docSize.gc` for anything a removal moved there, `docSize.live` for\n   * a member a peer added into the container after it was already removed.\n   */\n  public unregisterRemovedElementPair(createdAt: TimeTicket): boolean {\n    const key = createdAt.toIDString();\n    if (!this.gcElementSetByCreatedAt.has(key)) {\n      return false;\n    }\n\n    const element = this.elementPairMapByCreatedAt.get(key)?.element;\n    if (!element) {\n      // The worklist carries no element of its own; with nothing to resolve it\n      // through there is no charge to release and no identity to compare.\n      // Dropping the entry is still right -- it can never be collected.\n      this.gcElementSetByCreatedAt.delete(key);\n      return true;\n    }\n\n    this.release(element);\n    if (element instanceof CRDTContainer) {\n      element.getDescendants((elem) => {\n        this.release(elem);\n        return false;\n      });\n    }\n\n    this.gcElementSetByCreatedAt.delete(key);\n    return true;\n  }\n\n  /**\n   * `release` forgets the cost of an element that has become unreachable\n   * without being collected, and any collection entry naming it. It leaves\n   * `elementPairMapByCreatedAt` alone: the slot may since have been taken over\n   * by a live element restored under this same createdAt, and that element's\n   * registration has to stand.\n   */\n  private release(element: CRDTElement): void {\n    const createdAt = element.getCreatedAt().toIDString();\n\n    // Subtract from whichever side is actually holding it, by the amount\n    // actually charged -- the same split `deregisterElement` makes. A member\n    // added into an already-removed container never passed through a removal,\n    // so it still sits in live.\n    const charged = this.sizeInGC.get(element);\n    if (charged) {\n      subDataSize(this.docSize.gc, charged);\n    } else {\n      subDataSize(this.docSize.live, element.getDataSize());\n    }\n\n    // Record the release rather than forgetting it. This element stays\n    // addressable -- that is the whole point of not deregistering it -- so a\n    // peer that has not seen the restore can still remove something inside this\n    // subtree, and `moveSizeToGC` would then take its size out of live for a\n    // second time and drive docSize negative. A zero charge says live is not\n    // holding it. A copy restored under the same createdAt has a slot of its\n    // own and is still charged normally. Nothing retires this record -- the\n    // element is past collection and past deregistration -- so `sizeInGC` is a\n    // `WeakMap` and the record goes when the element does.\n    this.sizeInGC.set(element, { data: 0, meta: 0 });\n\n    if (this.elementPairMapByCreatedAt.get(createdAt)?.element === element) {\n      this.gcElementSetByCreatedAt.delete(createdAt);\n    }\n  }\n\n  /**\n   * `keyOf` returns the `gcPairMap` key identifying the given pair.\n   */\n  private keyOf(pair: GCPair): string {\n    let parentID = this.gcParentIDs.get(pair.parent);\n    if (parentID === undefined) {\n      parentID = ++this.nextGCParentID;\n      this.gcParentIDs.set(pair.parent, parentID);\n    }\n    return `${parentID}:${pair.child.toIDString()}`;\n  }\n\n  /**\n   * `registerGCPair` registers the given pair to hash table.\n   */\n  public registerGCPair(pair: GCPair): void {\n    const key = this.keyOf(pair);\n    const prev = this.gcPairMap.get(key);\n    if (prev) {\n      // A second registration under the same key un-registers: the child is\n      // no longer collectable, it was revived. What comes back out has to be\n      // what the map was contributing, or the bytes stay charged to gc for\n      // the life of the document -- the count drops to zero, so nothing else\n      // notices, while MaxSizeLimit keeps reading them.\n      //\n      // An attribute always contributes its own size while it is in the map:\n      // collection reads `getDataSize`, and nothing else's charge covers it\n      // once the write that revives it replaces it with a live node. A pair\n      // registered with a zero `gcOnlySize` -- a live attribute removed from\n      // a node that was ALREADY a tombstone, whose bytes were still inside\n      // that node's charge at the time -- would otherwise give back nothing.\n      // A born-dead split piece is the other way round: the rest of its\n      // bytes really are inside a sibling's charge, so it gives back exactly\n      // what registration added.\n      const isRHTNode = prev.child instanceof RHTNode;\n      subDataSize(\n        this.docSize.gc,\n        isRHTNode\n          ? prev.child.getDataSize()\n          : (prev.gcOnlySize ?? prev.child.getDataSize()),\n      );\n      this.gcPairMap.delete(key);\n      return;\n    }\n\n    this.gcPairMap.set(key, pair);\n\n    if (pair.gcOnlySize) {\n      // NOTE: The child's size was never counted in docSize.live (it was\n      // born removed, or it was registered by the snapshot-load scan where\n      // live only counts visible nodes), so there is nothing to move out\n      // of live. Only the given size is added to gc; purge subtracts the\n      // child's size from gc as usual.\n      addDataSizes(this.docSize.gc, pair.gcOnlySize);\n      return;\n    }\n\n    const size = this.gcPairMap.get(key)!.child.getDataSize();\n    addDataSizes(this.docSize.gc, size);\n    subDataSize(this.docSize.live, size);\n\n    // NOTE(hackerwins): In general cases, when removing a node, its size\n    // includes removedAt, so when subtracting the node size from docSize.Live,\n    // we need to subtract the removedAt size. However, RHTNode doesn't have\n    // removedAt, so we don't need to subtract it from the Live size.\n    if (!(pair.child instanceof RHTNode)) {\n      this.docSize.live.meta += TimeTicketSize;\n    }\n  }\n\n  /**\n   * `unregisterGCPair` removes the given pair from the hash table. Called\n   * when a tombstoned node is revived (un-tombstoned) by an\n   * identity-preserving undo, so that a later re-registration (redo) is\n   * not swallowed by the toggle in `registerGCPair`.\n   *\n   * NOTE: must be called AFTER the node's removedAt has been cleared, so\n   * `getDataSize()` no longer includes the tombstone ticket.\n   */\n  public unregisterGCPair(pair: GCPair): void {\n    const key = this.keyOf(pair);\n    const registered = this.gcPairMap.get(key);\n    if (!registered) {\n      return;\n    }\n\n    this.gcPairMap.delete(key);\n\n    // Mirror registerGCPair's accounting: move the node's size back from\n    // gc to live, and drop the tombstone ticket counted at register time.\n    const size = pair.child.getDataSize();\n    subDataSize(this.docSize.gc, size);\n    addDataSizes(this.docSize.live, size);\n    if (!(pair.child instanceof RHTNode)) {\n      this.docSize.gc.meta -= TimeTicketSize;\n    }\n  }\n\n  /**\n   * `getElementMapSize` returns the size of element map.\n   */\n  public getElementMapSize(): number {\n    return this.elementPairMapByCreatedAt.size;\n  }\n\n  /**\n   * `getGarbageElementSetSize()` returns the size of removed element set.\n   */\n  public getGarbageElementSetSize(): number {\n    const seen = new Set<string>();\n\n    for (const createdAt of this.gcElementSetByCreatedAt) {\n      seen.add(createdAt);\n      const pair = this.elementPairMapByCreatedAt.get(createdAt);\n      if (pair?.element instanceof CRDTContainer) {\n        pair.element.getDescendants((el) => {\n          seen.add(el.getCreatedAt().toIDString());\n          return false;\n        });\n      }\n    }\n    return seen.size;\n  }\n\n  /**\n   * `getObject` returns root object.\n   */\n  public getObject(): CRDTObject {\n    return this.rootObject;\n  }\n\n  /**\n   * `getGarbageLen` returns length of nodes which can be garbage collected.\n   */\n  public getGarbageLen(): number {\n    return this.getGarbageElementSetSize() + this.gcPairMap.size;\n  }\n\n  /**\n   * `getDocSize` returns the size of the document.\n   */\n  getDocSize(): DocSize {\n    return this.docSize;\n  }\n\n  /**\n   * `deepcopy` copies itself deeply.\n   */\n  public deepcopy(): CRDTRoot {\n    return new CRDTRoot(this.rootObject.deepcopy());\n  }\n\n  /**\n   * `garbageCollect` purges elements that were removed before the given time.\n   *\n   * A pass can hold a purge back (see `GCParent.purgeBarrierAt`), and holding one back can be\n   * the only reason another is held back: purging a node hands its successor\n   * to the node in front of it, and that successor is one this pass already\n   * found stable. So a pass that both purged and deferred may have more to do,\n   * and the loop repeats until a pass purges nothing new or defers nothing.\n   * Everything held back stays on the worklist for the next vector that covers\n   * it. The repeat also makes the result independent of iteration order, which\n   * decides only how many passes it takes, not what ends up collected.\n   */\n  public garbageCollect(minSyncedVersionVector: VersionVector): number {\n    let count = 0;\n\n    // Pruning first can release a tombstone whose last pending cancel the\n    // vector now covers.\n    this.pruneLedgers(minSyncedVersionVector);\n\n    for (;;) {\n      const [purged, deferred] = this.collect(minSyncedVersionVector);\n      count += purged;\n\n      if (purged === 0 || deferred === 0) {\n        return count;\n      }\n    }\n  }\n\n  /**\n   * `registerLedgerHolder` registers a Text whose removal ledgers may be\n   * pruned (see `RGATreeSplit.pruneLedgers`).\n   */\n  public registerLedgerHolder(holder: CRDTText): void {\n    this.ledgerHolders.add(holder);\n  }\n\n  /**\n   * `pruneLedgers` prunes every registered holder and drops the ones with\n   * nothing left to prune. A removed holder is dropped too: an undo that\n   * brings it back registers its copy again.\n   */\n  private pruneLedgers(vector: VersionVector): void {\n    for (const holder of this.ledgerHolders) {\n      if (holder.getRemovedAt() || holder.pruneLedgers(vector) === 0) {\n        this.ledgerHolders.delete(holder);\n      }\n    }\n  }\n\n  /**\n   * `collect` runs one collection pass, reporting how much it purged and how\n   * much it held back on a barrier.\n   */\n  private collect(minSyncedVersionVector: VersionVector): [number, number] {\n    let count = 0;\n    let deferred = 0;\n\n    for (const createdAt of this.gcElementSetByCreatedAt) {\n      // NOTE(hackerwins): Neither lookup is guaranteed to hit. A document\n      // written by an SDK that registered an element without its parent, or\n      // that left two elements under one createdAt, holds a member of this set\n      // that cannot be reached for purging. Dereferencing either one throws\n      // inside `applyChangePack`, and because that is where every sync applies\n      // the server's change pack, the same pass throws again on the next sync:\n      // the client stops syncing the document for good (#1340).\n      //\n      // Skip it rather than drop it. The element is still in the document and\n      // its size is still charged to `docSize.gc`, which only\n      // `deregisterElement` releases; forgetting the member would leave that\n      // charge counted against the size limit with nothing left reporting it\n      // as garbage. `getGCElementPairs` already guards the same lookup.\n      const pair = this.elementPairMapByCreatedAt.get(createdAt);\n      if (!pair || !pair.parent) {\n        continue;\n      }\n      const removedAt = pair.element.getRemovedAt();\n      if (!removedAt || !minSyncedVersionVector?.afterOrEqual(removedAt)) {\n        continue;\n      }\n\n      // A tombstone is not only a value that is gone, it is also a place in\n      // its parent that other replicas may still be deciding against.\n      // removedAt covers the value; the barrier covers the place.\n      const elementBarrier = pair.parent.purgeBarrierAt?.(pair.element);\n      if (\n        elementBarrier &&\n        !minSyncedVersionVector.afterOrEqual(elementBarrier)\n      ) {\n        deferred++;\n        continue;\n      }\n\n      pair.parent.purge(pair.element);\n      count += this.deregisterElement(pair.element);\n    }\n\n    for (const [key, pair] of this.gcPairMap) {\n      const removedAt = pair.child.getRemovedAt();\n      if (!removedAt) {\n        // Node was revived but its pair was not unregistered. Reverse the\n        // GC accounting (gc → live) and drop the stale entry via\n        // unregisterGCPair so the registerGCPair toggle can't be tripped\n        // later and docSize.gc/live stay consistent.\n        this.unregisterGCPair(pair);\n        continue;\n      }\n      if (!minSyncedVersionVector?.afterOrEqual(removedAt)) {\n        continue;\n      }\n\n      // A Text node whose removal ledger still matters stays; see\n      // `GCChild.heldFromPurge`.\n      if (pair.child.heldFromPurge?.(minSyncedVersionVector)) {\n        continue;\n      }\n\n      const barrier = pair.parent.purgeBarrierAt?.(pair.child);\n      if (barrier && !minSyncedVersionVector.afterOrEqual(barrier)) {\n        deferred++;\n        continue;\n      }\n\n      pair.parent.purge(pair.child);\n\n      subDataSize(this.docSize.gc, pair.child.getDataSize());\n      this.gcPairMap.delete(key);\n      count += 1;\n    }\n\n    return [count, deferred];\n  }\n\n  /**\n   * `toJSON` returns the JSON encoding of this root object.\n   */\n  public toJSON(): string {\n    return this.rootObject.toJSON();\n  }\n\n  /**\n   * `toSortedJSON` returns the sorted JSON encoding of this root object.\n   */\n  public toSortedJSON(): string {\n    return this.rootObject.toSortedJSON();\n  }\n\n  /**\n   * `getStats` returns the current statistics of the root object.\n   * This includes counts of various types of elements and structural information.\n   */\n  public getStats(): RootStats {\n    return {\n      elements: this.getElementMapSize(),\n      gcPairs: this.gcPairMap.size,\n      gcElements: this.getGarbageElementSetSize(),\n    };\n  }\n\n  /**\n   * `acc` accumulates the given DataSize to Live.\n   */\n  public acc(diff: DataSize) {\n    addDataSizes(this.docSize.live, diff);\n  }\n\n  /**\n   * `accMovedElement` books the size a move added to the moved element.\n   *\n   * An element already tombstoned when it is moved -- a remove and a move of\n   * the same element, concurrent on two replicas, arrive in some order on each\n   * -- is not in live at all: its whole size was moved to gc when it was\n   * removed. Charging the ticket to live there would leave live permanently\n   * ahead of a rebuild, and gc permanently behind by the same amount, which is\n   * the drift in the delivery order where the remove lands first. The gc charge\n   * also has to be topped up so collection, which subtracts the element's\n   * CURRENT size, does not overshoot.\n   */\n  public accMovedElement(element: CRDTElement, diff: DataSize): void {\n    const charged = this.sizeInGC.get(element);\n    if (charged) {\n      // A zero charge is `release`'s marker for a subtree orphaned by a\n      // restore: neither side is holding it and neither takes the ticket.\n      // No real charge is zero -- every element carries a createdAt.\n      if (charged.data === 0 && charged.meta === 0) {\n        return;\n      }\n\n      addDataSizes(this.docSize.gc, diff);\n      addDataSizes(charged, diff);\n      return;\n    }\n\n    addDataSizes(this.docSize.live, diff);\n  }\n\n  /**\n   * `accGC` accumulates the given DataSize to gc.\n   *\n   * `docSize.gc` has to stay equal to the sum of the CURRENT size of every\n   * registered pair's child, because collection subtracts exactly that when\n   * it purges one. Registration alone cannot maintain that: writing an\n   * attribute onto a node that is already a tombstone changes the size of a\n   * child that was registered earlier, with no pair of its own to carry the\n   * difference. That is what this reports.\n   */\n  public accGC(diff: DataSize) {\n    addDataSizes(this.docSize.gc, diff);\n  }\n\n  /**\n   * `getGCElementPairs` returns an iterator for all GC element pairs.\n   * This is similar to Go's GCElementPairMap() functionality.\n   */\n  public *getGCElementPairs(): IterableIterator<CRDTElementPair> {\n    for (const createdAt of this.gcElementSetByCreatedAt) {\n      const pair = this.elementPairMapByCreatedAt.get(createdAt);\n      if (pair) {\n        yield pair;\n      }\n    }\n  }\n}\n","/*\n * Copyright 2023 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { deepcopy } from '@yorkie-js/sdk/src/util/object';\nimport { Indexable } from '@yorkie-js/sdk/src/document/document';\nimport { ChangeContext } from '@yorkie-js/sdk/src/document/change/context';\nimport { PresenceChangeType } from './change';\n\n/**\n * `MaxPresenceBaseSize` is the largest presence the server keeps as a patch\n * base, mirroring `maxPresenceBaseSize` on the server. A presence above it is\n * refused by every fold, so patching it only buys a failed round trip.\n */\nconst MaxPresenceBaseSize = 4 * 1024;\n\n/**\n * `PresenceEntryOverhead` is the per-key cost the server adds on top of the\n * key and value bytes when it measures a presence (`presenceEntryOverhead`).\n */\nconst PresenceEntryOverhead = 64;\n\nconst encoder = new TextEncoder();\n\n/**\n * `isCacheablePresence` reports whether the server would keep the given\n * presence as a patch base. It mirrors the server's accounting: the UTF-8\n * bytes of each key and of its JSON-encoded value, plus a fixed per-entry\n * overhead. It stops counting as soon as the limit is passed, so an oversized\n * presence does not pay for encoding every value.\n */\nfunction isCacheablePresence(presence: Indexable): boolean {\n  let size = 0;\n  for (const [key, value] of Object.entries(presence)) {\n    size +=\n      encoder.encode(key).length +\n      encoder.encode(JSON.stringify(value)).length +\n      PresenceEntryOverhead;\n    if (size > MaxPresenceBaseSize) {\n      return false;\n    }\n  }\n  return true;\n}\n\n/**\n * `removesKey` reports whether the given partial presence deletes a top-level\n * key rather than setting one. An undo produces these: the reverse presence of\n * a `set` that introduced a key carries that key with no previous value.\n *\n * A patch cannot express a deletion -- only the changed keys go on the wire,\n * and the server folds them onto the base it holds, which leaves a key the\n * update dropped standing for every peer. So an update that removes a key\n * falls back to a full put, which does say what the whole presence now is.\n */\nfunction removesKey(presence: Record<string, unknown>): boolean {\n  for (const key of Object.keys(presence)) {\n    if (presence[key] === undefined) {\n      return true;\n    }\n  }\n  return false;\n}\n\n/**\n * `Presence` represents a proxy for the Presence to be manipulated from the outside.\n */\nexport class Channel<P extends Indexable> {\n  private context: ChangeContext;\n  private presence: P;\n\n  /**\n   * `patchable` is whether this update may record a patch instead of a full\n   * put. The document decides it: the server has to have advertised\n   * `presence-patch` on its last pack and to be holding a base for us.\n   */\n  private patchable: boolean;\n\n  /**\n   * `patchedKeys` are the keys recorded by the patch this context holds, if it\n   * holds one. Several `set` calls in one update overwrite each other's\n   * presence change, so the keys accumulate here rather than being taken from\n   * the last call alone.\n   */\n  private patchedKeys?: Set<string>;\n\n  /**\n   * `baseless` is whether this context has already recorded a full put or a\n   * `clear`. A context carries at most one presence change, so a patch\n   * recorded after one of those would replace it rather than follow it -- and\n   * the server has no base to fold that patch into. Once raised, the rest of\n   * the update stays a full put.\n   */\n  private baseless = false;\n\n  constructor(\n    changeContext: ChangeContext,\n    presence: P,\n    patchable: boolean = false,\n  ) {\n    this.context = changeContext;\n    this.presence = presence;\n    this.patchable = patchable;\n  }\n\n  /**\n   * `set` updates the presence based on the partial presence.\n   */\n  public set(presence: Partial<P>, option?: { addToHistory: boolean }) {\n    for (const key of Object.keys(presence)) {\n      this.presence[key as keyof P] = presence[key]!;\n    }\n\n    if (\n      this.patchable &&\n      !this.baseless &&\n      !removesKey(presence) &&\n      isCacheablePresence(this.presence)\n    ) {\n      const keys = this.patchedKeys ?? new Set<string>();\n      for (const key of Object.keys(presence)) {\n        keys.add(key);\n      }\n      this.patchedKeys = keys;\n\n      const patch: Partial<P> = {};\n      for (const key of keys) {\n        patch[key as keyof P] = deepcopy(this.presence[key as keyof P]);\n      }\n\n      this.context.setPresenceChange({\n        type: PresenceChangeType.Patch,\n        presence: patch,\n        full: deepcopy(this.presence),\n      });\n    } else {\n      this.baseless = true;\n      this.patchedKeys = undefined;\n      this.context.setPresenceChange({\n        type: PresenceChangeType.Put,\n        presence: deepcopy(this.presence),\n      });\n    }\n\n    this.context.setReversePresence(presence, option);\n  }\n\n  /**\n   * `get` returns the presence value of the given key.\n   */\n  public get<K extends keyof P>(key: K): P[K] {\n    return this.presence[key];\n  }\n\n  /**\n   * `clear` clears the presence.\n   */\n  public clear() {\n    this.presence = {} as P;\n    this.baseless = true;\n    this.patchedKeys = undefined;\n\n    this.context.setPresenceChange({\n      type: PresenceChangeType.Clear,\n    });\n  }\n}\n","/*\n * Copyright 2023 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Operation } from './operation/operation';\nimport { Indexable } from './document';\nimport { ArraySetOperation } from './operation/array_set_operation';\nimport { RemoveOperation } from './operation/remove_operation';\nimport { MoveOperation } from './operation/move_operation';\nimport { AddOperation } from './operation/add_operation';\nimport { TimeTicket } from '../yorkie';\nimport { EditOperation } from './operation/edit_operation';\nimport { TreeEditOperation } from './operation/tree_edit_operation';\nimport { TreeStyleOperation } from './operation/tree_style_operation';\nimport { CRDTTreeNodeID } from './crdt/tree';\n\n/**\n * `HistoryOperation` is a type of history operation.\n */\nexport type HistoryOperation<P extends Indexable> =\n  | Operation\n  | {\n      type: 'presence';\n      value: Partial<P>;\n    };\n\n/**\n * `MaxUndoRedoStackDepth` is the default maximum depth of undo/redo stack.\n * A document can override it with `DocumentOptions.maxUndoDepth`.\n */\nexport const MaxUndoRedoStackDepth = 50;\n\n/**\n * `History` is a class that stores the history of the document.\n */\nexport class History<P extends Indexable> {\n  private undoStack: Array<Array<HistoryOperation<P>>> = [];\n  private redoStack: Array<Array<HistoryOperation<P>>> = [];\n  private readonly maxDepth: number;\n\n  constructor(maxDepth: number = MaxUndoRedoStackDepth) {\n    this.maxDepth = maxDepth;\n  }\n\n  /**\n   * `getMaxDepth` returns how many entries each of the undo and redo stacks\n   * keeps before dropping the oldest.\n   */\n  public getMaxDepth(): number {\n    return this.maxDepth;\n  }\n\n  /**\n   * `hasUndo` returns true if there are undo operations.\n   */\n  public hasUndo(): boolean {\n    return this.undoStack.length > 0;\n  }\n\n  /**\n   * `hasRedo` returns true if there are redo operations.\n   */\n  public hasRedo(): boolean {\n    return this.redoStack.length > 0;\n  }\n\n  /**\n   * `pushUndo` pushes new undo operations of a change to undo stack.\n   */\n  public pushUndo(undoOps: Array<HistoryOperation<P>>): void {\n    if (this.undoStack.length >= this.maxDepth) {\n      this.undoStack.shift();\n    }\n    this.undoStack.push(undoOps);\n  }\n\n  /**\n   * `popUndo` pops the last undo operations of a change from undo stack.\n   */\n  public popUndo(): Array<HistoryOperation<P>> | undefined {\n    return this.undoStack.pop();\n  }\n\n  /**\n   * `pushRedo` pushes new redo operations of a change to redo stack.\n   */\n  public pushRedo(redoOps: Array<HistoryOperation<P>>): void {\n    if (this.redoStack.length >= this.maxDepth) {\n      this.redoStack.shift();\n    }\n    this.redoStack.push(redoOps);\n  }\n\n  /**\n   * `popRedo` pops the last redo operations of a change from redo stack.\n   */\n  public popRedo(): Array<HistoryOperation<P>> | undefined {\n    return this.redoStack.pop();\n  }\n\n  /**\n   * `clearRedo` flushes remaining redo operations.\n   */\n  public clearRedo(): void {\n    this.redoStack = [];\n  }\n\n  /**\n   * `clearUndo` flushes remaining undo operations.\n   */\n  public clearUndo(): void {\n    this.undoStack = [];\n  }\n\n  /**\n   * `getUndoStackForTest` returns the undo stack for test.\n   */\n  public getUndoStackForTest(): Array<Array<HistoryOperation<P>>> {\n    return this.undoStack;\n  }\n\n  /**\n   * `getRedoStackForTest` returns the redo stack for test.\n   */\n  public getRedoStackForTest(): Array<Array<HistoryOperation<P>>> {\n    return this.redoStack;\n  }\n\n  /**\n   * `reconcileCreatedAt` updates the createdAt and prevCreatedAt fields.\n   *\n   * When an element is replaced(e.g., UndoRemove as Add, or Set),\n   * it receives a new createdAt(executedAt). However, existing history\n   * operations may still reference the old createdAt or prevCreatedAt.\n   *\n   * This method scans both undo/redo stacks and replaces any matching\n   * createdAt/prevCreatedAt with the new one, ensuring consistency.\n   */\n  public reconcileCreatedAt(\n    prevCreatedAt: TimeTicket,\n    currCreatedAt: TimeTicket,\n  ): void {\n    const replace = (stack: Array<Array<HistoryOperation<P>>>) => {\n      // TODO(hackerwins): Optimize by indexing operations.\n      for (const ops of stack) {\n        for (const op of ops) {\n          if (\n            (op instanceof ArraySetOperation ||\n              op instanceof RemoveOperation ||\n              op instanceof MoveOperation) &&\n            op.getCreatedAt() === prevCreatedAt\n          ) {\n            op.setCreatedAt(currCreatedAt);\n          }\n\n          if (\n            (op instanceof AddOperation || op instanceof MoveOperation) &&\n            op.getPrevCreatedAt() === prevCreatedAt\n          ) {\n            op.setPrevCreatedAt(currCreatedAt);\n          }\n        }\n      }\n    };\n    replace(this.undoStack);\n    replace(this.redoStack);\n  }\n\n  /**\n   * `reconcileTextEdit` reconciles the text edit operation.\n   * Scan both undo/redo stacks and replace the edit operation with the new position.\n   */\n  public reconcileTextEdit(\n    parentCreatedAt: TimeTicket,\n    rangeFrom: number,\n    rangeTo: number,\n    contentLength: number,\n  ): void {\n    const replace = (stack: Array<Array<HistoryOperation<P>>>) => {\n      // TODO(hackerwins): Optimize by indexing operations.\n      for (const ops of stack) {\n        for (const op of ops) {\n          if (\n            op instanceof EditOperation &&\n            op.getParentCreatedAt().compare(parentCreatedAt) === 0\n          ) {\n            op.reconcileOperation(rangeFrom, rangeTo, contentLength);\n          }\n        }\n      }\n    };\n    replace(this.undoStack);\n    replace(this.redoStack);\n  }\n\n  /**\n   * `reconcileTreeNodeID` re-points the tree edits and tree styles in both\n   * stacks that target the tree `parentCreatedAt` names, from `prev` to\n   * `curr`. Used when a split re-creates an element under a new id, the tree\n   * counterpart of `reconcileCreatedAt`.\n   *\n   * Scoped to one tree element, like `reconcileTextEdit` and\n   * `reconcileTreeEdit`: a node id is only unique within its own tree, and the\n   * pairs reach here from a peer's change as well as this replica's own, so an\n   * unscoped sweep would let one tree's split re-point entries recorded\n   * against a different tree.\n   */\n  public reconcileTreeNodeID(\n    parentCreatedAt: TimeTicket,\n    prev: CRDTTreeNodeID,\n    curr: CRDTTreeNodeID,\n  ): void {\n    const replace = (stack: Array<Array<HistoryOperation<P>>>) => {\n      for (const ops of stack) {\n        for (const op of ops) {\n          if (\n            (op instanceof TreeEditOperation ||\n              op instanceof TreeStyleOperation) &&\n            op.getParentCreatedAt().compare(parentCreatedAt) === 0\n          ) {\n            op.reconcileNodeID(prev, curr);\n          }\n        }\n      }\n    };\n    replace(this.undoStack);\n    replace(this.redoStack);\n  }\n\n  /**\n   * `reconcileTreeEdit` reconciles the tree edit operation.\n   * Scan both undo/redo stacks and adjust tree edit operations\n   * when a remote edit modifies the same tree.\n   */\n  public reconcileTreeEdit(\n    parentCreatedAt: TimeTicket,\n    rangeFrom: number,\n    rangeTo: number,\n    contentSize: number,\n  ): void {\n    const replace = (stack: Array<Array<HistoryOperation<P>>>) => {\n      for (const ops of stack) {\n        for (const op of ops) {\n          if (\n            op instanceof TreeEditOperation &&\n            op.getParentCreatedAt().compare(parentCreatedAt) === 0\n          ) {\n            op.reconcileOperation(rangeFrom, rangeTo, contentSize);\n          }\n        }\n      }\n    };\n    replace(this.undoStack);\n    replace(this.redoStack);\n  }\n}\n","/*\n * Copyright 2026 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * `ContentExpr` represents a parsed ProseMirror-compatible content expression.\n *\n * Content expressions define what children a node can contain using a grammar:\n *   expr       -> sequence ('|' sequence)*     // alternatives\n *   sequence   -> element+                     // sequence\n *   element    -> atom quantifier?             // element + quantifier\n *   atom       -> name | '(' expr ')'          // node type or group\n *   quantifier -> '+' | '*' | '?'              // 1+, 0+, 0-1\n */\nexport interface ContentExpr {\n  type: 'node' | 'sequence' | 'alternative' | 'repeat';\n  children?: Array<ContentExpr>;\n  nodeType?: string;\n  min?: number;\n  max?: number;\n}\n\ntype Token = {\n  type: 'name' | 'plus' | 'star' | 'question' | 'pipe' | 'lparen' | 'rparen';\n  value: string;\n};\n\n/**\n * `tokenize` splits a content expression string into tokens.\n */\nfunction tokenize(expr: string): Array<Token> {\n  const tokens: Array<Token> = [];\n  let i = 0;\n  while (i < expr.length) {\n    if (/\\s/.test(expr[i])) {\n      i++;\n      continue;\n    }\n    if (expr[i] === '+') {\n      tokens.push({ type: 'plus', value: '+' });\n      i++;\n    } else if (expr[i] === '*') {\n      tokens.push({ type: 'star', value: '*' });\n      i++;\n    } else if (expr[i] === '?') {\n      tokens.push({ type: 'question', value: '?' });\n      i++;\n    } else if (expr[i] === '|') {\n      tokens.push({ type: 'pipe', value: '|' });\n      i++;\n    } else if (expr[i] === '(') {\n      tokens.push({ type: 'lparen', value: '(' });\n      i++;\n    } else if (expr[i] === ')') {\n      tokens.push({ type: 'rparen', value: ')' });\n      i++;\n    } else {\n      let name = '';\n      while (i < expr.length && /[a-zA-Z0-9_]/.test(expr[i])) {\n        name += expr[i];\n        i++;\n      }\n      if (name) {\n        tokens.push({ type: 'name', value: name });\n      } else {\n        throw new Error(\n          `Unexpected character '${expr[i]}' at position ${i} in content expression`,\n        );\n      }\n    }\n  }\n  return tokens;\n}\n\n/**\n * `parseAlternatives` parses alternatives separated by '|'.\n */\nfunction parseAlternatives(\n  tokens: Array<Token>,\n  pos: number,\n): { expr: ContentExpr; pos: number } {\n  const seqs: Array<ContentExpr> = [];\n  let result = parseSequence(tokens, pos);\n  seqs.push(result.expr);\n  while (result.pos < tokens.length && tokens[result.pos]?.type === 'pipe') {\n    result = parseSequence(tokens, result.pos + 1);\n    seqs.push(result.expr);\n  }\n  if (seqs.length === 1) {\n    return { expr: seqs[0], pos: result.pos };\n  }\n  return { expr: { type: 'alternative', children: seqs }, pos: result.pos };\n}\n\n/**\n * `parseSequence` parses a sequence of elements.\n */\nfunction parseSequence(\n  tokens: Array<Token>,\n  pos: number,\n): { expr: ContentExpr; pos: number } {\n  const elements: Array<ContentExpr> = [];\n  while (\n    pos < tokens.length &&\n    tokens[pos].type !== 'pipe' &&\n    tokens[pos].type !== 'rparen'\n  ) {\n    const result = parseElement(tokens, pos);\n    elements.push(result.expr);\n    pos = result.pos;\n  }\n  if (elements.length === 1) {\n    return { expr: elements[0], pos };\n  }\n  return { expr: { type: 'sequence', children: elements }, pos };\n}\n\n/**\n * `parseElement` parses an atom optionally followed by a quantifier.\n */\nfunction parseElement(\n  tokens: Array<Token>,\n  pos: number,\n): { expr: ContentExpr; pos: number } {\n  const result = parseAtom(tokens, pos);\n  let expr = result.expr;\n  pos = result.pos;\n  if (pos < tokens.length) {\n    if (tokens[pos].type === 'plus') {\n      expr = { type: 'repeat', children: [expr], min: 1, max: Infinity };\n      pos++;\n    } else if (tokens[pos].type === 'star') {\n      expr = { type: 'repeat', children: [expr], min: 0, max: Infinity };\n      pos++;\n    } else if (tokens[pos].type === 'question') {\n      expr = { type: 'repeat', children: [expr], min: 0, max: 1 };\n      pos++;\n    }\n  }\n  return { expr, pos };\n}\n\n/**\n * `parseAtom` parses a name or a parenthesized sub-expression.\n */\nfunction parseAtom(\n  tokens: Array<Token>,\n  pos: number,\n): { expr: ContentExpr; pos: number } {\n  if (pos >= tokens.length) {\n    throw new Error('Unexpected end of content expression');\n  }\n  if (tokens[pos].type === 'lparen') {\n    const result = parseAlternatives(tokens, pos + 1);\n    if (result.pos >= tokens.length || tokens[result.pos]?.type !== 'rparen') {\n      throw new Error('Unmatched parenthesis in content expression');\n    }\n    return { expr: result.expr, pos: result.pos + 1 };\n  }\n  if (tokens[pos].type !== 'name') {\n    throw new Error(\n      `Expected node type name but got '${tokens[pos].value}' in content expression`,\n    );\n  }\n  return { expr: { type: 'node', nodeType: tokens[pos].value }, pos: pos + 1 };\n}\n\n/**\n * `parseContentExpression` parses a ProseMirror-compatible content expression\n * string into a `ContentExpr` AST.\n *\n * Examples:\n *   - `\"paragraph+\"` -> 1+ paragraphs\n *   - `\"text*\"` -> 0+ text nodes\n *   - `\"heading paragraph+\"` -> one heading then 1+ paragraphs\n *   - `\"paragraph | heading\"` -> one paragraph or one heading\n *   - `\"(paragraph | heading)+\"` -> 1+ of paragraph or heading\n *   - `\"block+\"` -> 1+ nodes from \"block\" group (resolved via groupResolver)\n */\nexport function parseContentExpression(expr: string): ContentExpr {\n  const trimmed = expr.trim();\n  if (trimmed.length === 0) {\n    return { type: 'sequence', children: [] };\n  }\n  const tokens = tokenize(trimmed);\n  const result = parseAlternatives(tokens, 0);\n  if (result.pos < tokens.length) {\n    throw new Error(\n      `Unexpected token '${tokens[result.pos].value}' at position ${result.pos} in content expression`,\n    );\n  }\n  return result.expr;\n}\n\n/**\n * `matchExpr` attempts to match child types starting at any of the given\n * positions against the expression. Returns the set of all reachable\n * positions after matching, enabling backtracking for ambiguous expressions\n * like `a* a`.\n */\nfunction matchExpr(\n  expr: ContentExpr,\n  types: Array<string>,\n  positions: Set<number>,\n  resolver: (name: string) => Array<string>,\n): Set<number> {\n  switch (expr.type) {\n    case 'node': {\n      const allowed = resolver(expr.nodeType!);\n      const result = new Set<number>();\n      for (const pos of positions) {\n        if (pos < types.length && allowed.includes(types[pos])) {\n          result.add(pos + 1);\n        }\n      }\n      return result;\n    }\n    case 'sequence': {\n      let current = positions;\n      for (const child of expr.children!) {\n        current = matchExpr(child, types, current, resolver);\n        if (current.size === 0) {\n          return current;\n        }\n      }\n      return current;\n    }\n    case 'alternative': {\n      const result = new Set<number>();\n      for (const child of expr.children!) {\n        for (const pos of matchExpr(child, types, positions, resolver)) {\n          result.add(pos);\n        }\n      }\n      return result;\n    }\n    case 'repeat': {\n      const min = expr.min ?? 0;\n      const max = expr.max ?? Infinity;\n      // Collect all positions reachable with 0..max repetitions\n      let current = positions;\n      const reachable = new Set<number>();\n      if (min === 0) {\n        for (const p of current) reachable.add(p);\n      }\n      for (let count = 1; count <= max; count++) {\n        const next = matchExpr(expr.children![0], types, current, resolver);\n        // Remove positions we've already seen to avoid infinite loops\n        const newPositions = new Set<number>();\n        for (const p of next) {\n          if (!reachable.has(p) || count < min) {\n            newPositions.add(p);\n          }\n        }\n        if (newPositions.size === 0) break;\n        current = newPositions;\n        if (count >= min) {\n          for (const p of current) reachable.add(p);\n        }\n      }\n      return reachable;\n    }\n  }\n  return new Set();\n}\n\n/**\n * `matchContentExpression` matches an array of child type names against\n * a parsed content expression. It uses the `groupResolver` to resolve\n * group names (like \"block\") to a list of concrete node type names.\n *\n * Returns `{ valid: true }` if the children match, or\n * `{ valid: false, error: string }` if they do not.\n */\nexport function matchContentExpression(\n  expr: ContentExpr,\n  childTypes: Array<string>,\n  groupResolver: (name: string) => Array<string>,\n): { valid: boolean; error?: string } {\n  const positions = matchExpr(expr, childTypes, new Set([0]), groupResolver);\n  if (positions.has(childTypes.length)) {\n    return { valid: true };\n  }\n  if (positions.size === 0) {\n    return { valid: false, error: 'Children do not match content expression' };\n  }\n  return {\n    valid: false,\n    error: `Unexpected child at position ${Math.max(...positions)}`,\n  };\n}\n","/*\n * Copyright 2026 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CRDTTree, CRDTTreeNode } from '@yorkie-js/sdk/src/document/crdt/tree';\nimport {\n  parseContentExpression,\n  matchContentExpression,\n} from '@yorkie-js/sdk/src/document/schema/content-expression';\n\n/**\n * `TreeNodeRuleInput` represents the input for a tree node rule,\n * matching the TreeNodeRule type from the schema package.\n */\nexport type TreeNodeRuleInput = {\n  nodeType: string;\n  content?: string;\n  marks?: string;\n  group?: string;\n};\n\n/**\n * `TreeValidationResult` represents the result of tree validation.\n */\nexport type TreeValidationResult = {\n  valid: boolean;\n  error?: string;\n};\n\n/**\n * `buildGroupResolver` builds a group resolver function from the given\n * tree node rules. The resolver maps a name to the list of node types\n * that belong to that group. If the name is not a group, it returns\n * the name itself (treating it as a concrete node type).\n */\nexport function buildGroupResolver(\n  treeNodes: Array<TreeNodeRuleInput>,\n): (name: string) => Array<string> {\n  const groupMap = new Map<string, Array<string>>();\n\n  for (const node of treeNodes) {\n    if (node.group) {\n      const groups = node.group.split(/\\s+/);\n      for (const group of groups) {\n        if (!groupMap.has(group)) {\n          groupMap.set(group, []);\n        }\n        groupMap.get(group)!.push(node.nodeType);\n      }\n    }\n  }\n\n  return (name: string): Array<string> => {\n    if (groupMap.has(name)) {\n      return groupMap.get(name)!;\n    }\n    return [name];\n  };\n}\n\n/**\n * `validateTreeAgainstSchema` validates a CRDTTree's structure against\n * the given tree node rules. It checks:\n * 1. Each node's type exists in the rules\n * 2. Children match the content expression (for non-text nodes)\n * 3. Text node marks are allowed by the parent's marks rule\n */\nexport function validateTreeAgainstSchema(\n  tree: CRDTTree,\n  treeNodes: Array<TreeNodeRuleInput>,\n): TreeValidationResult {\n  const ruleMap = new Map<string, TreeNodeRuleInput>();\n  for (const node of treeNodes) {\n    ruleMap.set(node.nodeType, node);\n  }\n\n  const resolver = buildGroupResolver(treeNodes);\n  const root = tree.getRoot();\n\n  return validateNode(root, ruleMap, resolver);\n}\n\n/**\n * `validateNode` recursively validates a CRDTTreeNode against the rules.\n */\nfunction validateNode(\n  node: CRDTTreeNode,\n  ruleMap: Map<string, TreeNodeRuleInput>,\n  resolver: (name: string) => Array<string>,\n): TreeValidationResult {\n  // Check that the node type exists in the rules\n  const rule = ruleMap.get(node.type);\n  if (!rule) {\n    return {\n      valid: false,\n      error: `Unknown node type: \"${node.type}\"`,\n    };\n  }\n\n  // Skip further validation for text nodes - they are leaf nodes validated\n  // by their parent's marks rule\n  if (node.isText) {\n    return { valid: true };\n  }\n\n  // Get non-removed children\n  const children = node.children;\n\n  // Check that all non-text children have known types\n  for (const child of children) {\n    if (!child.isText && !ruleMap.has(child.type)) {\n      return {\n        valid: false,\n        error: `Unknown node type: \"${child.type}\"`,\n      };\n    }\n  }\n\n  // Validate content expression (empty string means no children allowed)\n  if (rule.content !== undefined) {\n    const childTypes = children.map((child) => child.type);\n    const expr = parseContentExpression(rule.content);\n    const result = matchContentExpression(expr, childTypes, resolver);\n    if (!result.valid) {\n      return {\n        valid: false,\n        error: `Node \"${node.type}\": ${result.error}`,\n      };\n    }\n  }\n\n  // Validate marks on text children if the rule specifies allowed marks\n  if (rule.marks) {\n    const allowedMarks = rule.marks.split(/\\s+/);\n    const markResult = validateChildMarks(node, children, allowedMarks);\n    if (!markResult.valid) {\n      return markResult;\n    }\n  }\n\n  // Recurse into non-text children\n  for (const child of children) {\n    if (!child.isText) {\n      const result = validateNode(child, ruleMap, resolver);\n      if (!result.valid) {\n        return result;\n      }\n    }\n  }\n\n  return { valid: true };\n}\n\n/**\n * `validateChildMarks` checks that text children of a node only have\n * marks that are listed in the allowed marks.\n */\nfunction validateChildMarks(\n  parent: CRDTTreeNode,\n  children: Array<CRDTTreeNode>,\n  allowedMarks: Array<string>,\n): TreeValidationResult {\n  for (const child of children) {\n    if (!child.isText) {\n      continue;\n    }\n\n    if (!child.attrs) {\n      continue;\n    }\n\n    for (const rhtNode of child.attrs) {\n      if (rhtNode.isRemoved()) {\n        continue;\n      }\n      const markName = rhtNode.getKey();\n      if (!allowedMarks.includes(markName)) {\n        return {\n          valid: false,\n          error: `Node \"${parent.type}\": text child has disallowed mark \"${markName}\". Allowed marks: ${allowedMarks.join(', ')}`,\n        };\n      }\n    }\n  }\n\n  return { valid: true };\n}\n","/*\n * Copyright 2025 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PrimitiveRule, Rule } from '@yorkie-js/schema/src/rulesets';\nimport { CRDTObject } from '@yorkie-js/sdk/src/document/crdt/object';\nimport { CRDTArray } from '@yorkie-js/sdk/src/document/crdt/array';\nimport { CRDTText } from '@yorkie-js/sdk/src/document/crdt/text';\nimport { CRDTTree } from '@yorkie-js/sdk/src/document/crdt/tree';\nimport { CRDTCounter } from '@yorkie-js/sdk/src/document/crdt/counter';\nimport { validateTreeAgainstSchema } from '@yorkie-js/sdk/src/document/schema/tree-validator';\nimport {\n  Primitive,\n  PrimitiveType,\n} from '@yorkie-js/sdk/src/document/crdt/primitive';\n\nexport type ValidationResult = {\n  valid: boolean;\n  errors?: Array<ValidationError>;\n};\n\nexport type ValidationError = {\n  path: string;\n  message: string;\n};\n\n/**\n * `validateYorkieRuleset` validates the given data against the ruleset.\n */\nexport function validateYorkieRuleset(\n  data: any,\n  ruleset: Array<Rule>,\n): ValidationResult {\n  const errors: Array<ValidationError> = [];\n  for (const rule of ruleset) {\n    const value = getValueByPath(data, rule.path);\n    const result = validateValue(value, rule);\n    if (!result.valid) {\n      for (const error of result.errors || []) {\n        errors.push(error);\n      }\n    }\n  }\n\n  return {\n    valid: errors.length === 0,\n    errors,\n  };\n}\n\n/**\n * `getValueByPath` gets a value from the given object using the given path.\n */\nfunction getValueByPath(obj: any, path: string): any {\n  if (!path.startsWith('$')) {\n    throw new Error(`Path must start with $, got ${path}`);\n  }\n\n  const keys = path.split('.');\n  let current = obj;\n\n  for (let i = 1; i < keys.length; i++) {\n    const key = keys[i];\n    if (!(current instanceof CRDTObject)) {\n      return undefined;\n    }\n    current = current.get(key);\n  }\n\n  return current;\n}\n\n/**\n * `validateValue` validates a value against a rule.\n */\nfunction validateValue(value: any, rule: Rule): ValidationResult {\n  switch (rule.type) {\n    case 'string':\n    case 'boolean':\n    case 'integer':\n    case 'double':\n    case 'long':\n    case 'date':\n    case 'bytes':\n    case 'null':\n      return validatePrimitiveValue(value, rule as PrimitiveRule);\n    case 'object':\n      if (!(value instanceof CRDTObject)) {\n        return {\n          valid: false,\n          errors: [\n            {\n              path: rule.path,\n              message: `expected object at path ${rule.path}`,\n            },\n          ],\n        };\n      }\n      break;\n    case 'array':\n      if (!(value instanceof CRDTArray)) {\n        return {\n          valid: false,\n          errors: [\n            {\n              path: rule.path,\n              message: `expected array at path ${rule.path}`,\n            },\n          ],\n        };\n      }\n      break;\n    case 'yorkie.Text':\n      if (!(value instanceof CRDTText)) {\n        return {\n          valid: false,\n          errors: [\n            {\n              path: rule.path,\n              message: `expected yorkie.Text at path ${rule.path}`,\n            },\n          ],\n        };\n      }\n      break;\n    case 'yorkie.Tree': {\n      if (!(value instanceof CRDTTree)) {\n        return {\n          valid: false,\n          errors: [\n            {\n              path: rule.path,\n              message: `expected yorkie.Tree at path ${rule.path}`,\n            },\n          ],\n        };\n      }\n      if ('treeNodes' in rule && rule.treeNodes && rule.treeNodes.length > 0) {\n        const treeResult = validateTreeAgainstSchema(\n          value as CRDTTree,\n          rule.treeNodes,\n        );\n        if (!treeResult.valid) {\n          return {\n            valid: false,\n            errors: [{ path: rule.path, message: treeResult.error! }],\n          };\n        }\n      }\n      break;\n    }\n    case 'yorkie.Counter':\n      if (!(value instanceof CRDTCounter)) {\n        return {\n          valid: false,\n          errors: [\n            {\n              path: rule.path,\n              message: `expected yorkie.Counter at path ${rule.path}`,\n            },\n          ],\n        };\n      }\n      break;\n    default:\n      throw new Error(`Unknown rule type: ${(rule as any).type}`);\n  }\n\n  return {\n    valid: true,\n  };\n}\n\n/**\n * `getPrimitiveType` converts a string type to PrimitiveType.\n */\nfunction getPrimitiveType(type: string): PrimitiveType {\n  switch (type) {\n    case 'null':\n      return PrimitiveType.Null;\n    case 'boolean':\n      return PrimitiveType.Boolean;\n    case 'integer':\n      return PrimitiveType.Integer;\n    case 'long':\n      return PrimitiveType.Long;\n    case 'double':\n      return PrimitiveType.Double;\n    case 'string':\n      return PrimitiveType.String;\n    case 'bytes':\n      return PrimitiveType.Bytes;\n    case 'date':\n      return PrimitiveType.Date;\n    default:\n      throw new Error(`Unknown primitive type: ${type}`);\n  }\n}\n\n/**\n * `validatePrimitiveValue` validates a primitive value against a rule.\n */\nfunction validatePrimitiveValue(\n  value: any,\n  rule: PrimitiveRule,\n): ValidationResult {\n  if (\n    value instanceof Primitive &&\n    value.getType() === getPrimitiveType(rule.type)\n  ) {\n    return { valid: true };\n  }\n\n  return {\n    valid: false,\n    errors: [\n      {\n        path: rule.path,\n        message: `expected ${rule.type} at path ${rule.path}`,\n      },\n    ],\n  };\n}\n","/*\n * Copyright 2024 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocEventsForReplay, DocNotification } from './types';\n\n/**\n * `EventSourceDevPanel` is the name of the source representing messages\n *  from the Devtools panel.\n */\nexport const EventSourceDevPanel = 'yorkie-devtools-panel';\n\n/**\n * `EventSourceSDK` is the name of the source representing messages\n * from the SDK.\n */\nexport const EventSourceSDK = 'yorkie-devtools-sdk';\n\n/**\n * PanelToSDKMessage is a message sent from the Devtools panel to the SDK.\n */\nexport type PanelToSDKMessage =\n  /**\n   * Informs the SDK that the panel is available.\n   */\n  | { msg: 'devtools::connect' }\n\n  /**\n   * Informs the SDK that the panel is not available.\n   */\n  | { msg: 'devtools::disconnect' }\n\n  /**\n   * Informs the SDK that the panel is interested in receiving the \"event\" for the document,\n   * starting with the initial \"full sync\" event.\n   */\n  | {\n      msg: 'devtools::subscribe';\n      docKey: string;\n    };\n\n/**\n * Definition of all messages the SDK can send to the Devtools panel.\n */\nexport type SDKToPanelMessage =\n  /**\n   * Sent when the dev panel is already opened and listened,\n   * before the sdk is loaded. If the panel receives this message,\n   * it will replay its initial \"connect\" message.\n   */\n  | {\n      msg: 'refresh-devtools';\n    }\n  /**\n   * Sent when the document is available for the panel to watch.\n   */\n  | {\n      msg: 'doc::available';\n      docKey: string;\n    }\n  /**\n   * Sent when a document the panel may be watching leaves the page: it\n   * detached, or it was removed. The recording is kept, so the same key can\n   * come back with `doc::available` when the document attaches again.\n   */\n  | {\n      msg: 'doc::unavailable';\n      docKey: string;\n    }\n  /**\n   * Sent initially, to synchronize the entire current state of the document.\n   */\n  | {\n      msg: 'doc::sync::full';\n      docKey: string;\n      events: Array<DocEventsForReplay>;\n    }\n  /**\n   * Sent whenever the document is changed.\n   */\n  | {\n      msg: 'doc::sync::partial';\n      docKey: string;\n      event: DocEventsForReplay;\n    }\n  /**\n   * Sent initially, to hand over the notifications recorded so far. These are\n   * the events that cannot be replayed, so they travel beside the replay\n   * stream instead of inside it.\n   */\n  | {\n      msg: 'doc::notification::full';\n      docKey: string;\n      notifications: Array<DocNotification>;\n    }\n  /**\n   * Sent whenever an event that cannot be replayed occurs in the document.\n   */\n  | {\n      msg: 'doc::notification::partial';\n      docKey: string;\n      notification: DocNotification;\n    };\n\nexport type FullPanelToSDKMessage = PanelToSDKMessage & {\n  source: 'yorkie-devtools-panel';\n};\n\nexport type FullSDKToPanelMessage = SDKToPanelMessage & {\n  source: 'yorkie-devtools-sdk';\n};\n","/*\n * Copyright 2024 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { PrimitiveValue } from '@yorkie-js/sdk/src/document/crdt/primitive';\nimport type { CRDTTreePosStruct } from '@yorkie-js/sdk/src/document/crdt/tree';\nimport { CounterValue } from '@yorkie-js/sdk/src/document/crdt/counter';\nimport {\n  Json,\n  DocEvent,\n  DocEventType,\n  type Indexable,\n  type StatusChangedEvent,\n  type SnapshotEvent,\n  type LocalChangeEvent,\n  type RemoteChangeEvent,\n  type InitializedEvent,\n  type WatchedEvent,\n  type UnwatchedEvent,\n  type PresenceChangedEvent,\n  type ConnectionChangedEvent,\n  type SyncStatusChangedEvent,\n  type AuthErrorEvent,\n  type EpochMismatchEvent,\n  type WriteRejectedEvent,\n  type LocalChangesDroppedEvent,\n  type PersistDisabledEvent,\n} from '@yorkie-js/sdk/src/document/document';\nimport type { OpInfo } from '@yorkie-js/sdk/src/document/operation/operation';\n\n/**\n * `Client` represents a client value in devtools.\n */\nexport type Client = {\n  clientID: string;\n  presence: Json;\n};\n\n/**\n * `JSONElement` represents the result of `Element.toJSForTest()`.\n */\nexport type JSONElement = {\n  type: JSONElementType;\n  key?: string;\n  value: JSONElementValue;\n  createdAt: string;\n};\n\ntype JSONElementType =\n  | 'YORKIE_PRIMITIVE'\n  | 'YORKIE_COUNTER'\n  | 'YORKIE_OBJECT'\n  | 'YORKIE_ARRAY'\n  | 'YORKIE_TEXT'\n  | 'YORKIE_TREE';\n\n/**\n * `ElementValue` represents the result of `Element.toJSForTest()`.\n *\n * NOTE(chacha912): Json type is used to represent the result of\n * `Text.toJSForTest()` and `Tree.toJSForTest()`.\n */\ntype JSONElementValue =\n  | PrimitiveValue\n  | CounterValue\n  | ContainerValue // Array | Object\n  | Json; // Text | Tree\n\n/**\n * `ContainerValue` represents the result of `Array.toJSForTest()` and\n * `Object.toJSForTest()`.\n */\nexport type ContainerValue = {\n  [key: string]: JSONElement;\n};\n\n/**\n * `TreeNodeInfo` represents the crdt tree node information in devtools.\n */\nexport type TreeNodeInfo = {\n  id: string;\n  type: string;\n  parent?: string;\n  size: number;\n  value?: string;\n  removedAt?: string;\n  isRemoved: boolean;\n  insPrev?: string;\n  insNext?: string;\n  children: Array<TreeNodeInfo>;\n  attributes?: object; // TODO(chacha912): Specify the type accurately.\n  depth: number;\n  index?: number;\n  path?: Array<number>;\n  pos?: CRDTTreePosStruct;\n};\n\n/**\n * `DocEventForReplay` is an event used to replay a document.\n */\nexport type DocEventForReplay<P extends Indexable = Indexable, T = OpInfo> =\n  | StatusChangedEvent\n  | SnapshotEvent\n  | LocalChangeEvent<T, P>\n  | RemoteChangeEvent<T, P>\n  | InitializedEvent<P>\n  | WatchedEvent<P>\n  | UnwatchedEvent<P>\n  | PresenceChangedEvent<P>;\n\n/**\n * `DocEventsForReplay` is a list of events used to replay a document.\n */\nexport type DocEventsForReplay = Array<DocEventForReplay>;\n\n/**\n * `isDocEventForReplay` checks if an event can be used to replay a document.\n */\nexport function isDocEventForReplay(\n  event: DocEvent,\n): event is DocEventForReplay {\n  const types = [\n    DocEventType.StatusChanged,\n    DocEventType.Snapshot,\n    DocEventType.LocalChange,\n    DocEventType.RemoteChange,\n    DocEventType.Initialized,\n    DocEventType.Watched,\n    DocEventType.Unwatched,\n    DocEventType.PresenceChanged,\n  ];\n\n  return types.includes(event.type);\n}\n\n/**\n * `isDocEventsForReplay` checks if a list of events can be used to replay a document.\n */\nexport function isDocEventsForReplay(\n  events: Array<DocEvent>,\n): events is DocEventsForReplay {\n  return events.every(isDocEventForReplay);\n}\n\n/**\n * `DocNotificationEvent` is an event that cannot be used to replay a document.\n * `Document.applyDocEventsForReplay` has no case for it, so devtools shows it\n * as a standalone record instead of feeding it to the replay pipeline.\n */\nexport type DocNotificationEvent<P extends Indexable = Indexable> =\n  | ConnectionChangedEvent\n  | SyncStatusChangedEvent\n  | AuthErrorEvent\n  | EpochMismatchEvent\n  | WriteRejectedEvent\n  | LocalChangesDroppedEvent<P>\n  | PersistDisabledEvent;\n\n/**\n * `DocNotification` is a `DocNotificationEvent` stamped with the time the SDK\n * observed it. The panel can receive the record long after the fact, in the\n * initial full sync, so the SDK is the only place that knows when it happened.\n */\nexport type DocNotification = {\n  event: DocNotificationEvent;\n  timestamp: number;\n};\n\n/**\n * `isDocNotificationEvent` checks if an event should be reported to devtools\n * as a notification. The list is explicit rather than the complement of\n * `isDocEventForReplay`, so that a `DocEventType` added later is classified on\n * purpose instead of landing in this channel by default.\n */\nexport function isDocNotificationEvent(\n  event: DocEvent,\n): event is DocNotificationEvent {\n  const types = [\n    DocEventType.ConnectionChanged,\n    DocEventType.SyncStatusChanged,\n    DocEventType.AuthError,\n    DocEventType.EpochMismatch,\n    DocEventType.WriteRejected,\n    DocEventType.LocalChangesDropped,\n    DocEventType.PersistDisabled,\n  ];\n\n  return types.includes(event.type);\n}\n","/*\n * Copyright 2024 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Document, Indexable } from '@yorkie-js/sdk/src/yorkie';\nimport { logger } from '@yorkie-js/sdk/src/util/logger';\nimport type * as DevTools from './protocol';\nimport { EventSourceDevPanel, EventSourceSDK } from './protocol';\nimport {\n  DocEventsForReplay,\n  DocNotification,\n  DocNotificationEvent,\n  isDocEventForReplay,\n  isDocNotificationEvent,\n} from './types';\nimport { DocEventType, DocStatus } from '@yorkie-js/sdk/src/document/document';\n\ntype DevtoolsStatus = 'connected' | 'disconnected' | 'synced';\n\n/**\n * `devtoolsStatusByDocKey` stores the panel connection status of each document.\n * The panel reaches every document on the page through a single window message\n * channel, so the status cannot be shared across documents.\n */\nconst devtoolsStatusByDocKey = new Map<string, DevtoolsStatus>();\n\n/**\n * `teardownByDoc` holds what every `setupDevtools` call has to give back: the\n * document subscription, the window listener and the recording. They are kept\n * per Document rather than per key, because one key can have several Documents\n * behind it and releasing one of them must not release the others.\n */\nconst teardownByDoc = new WeakMap<object, () => void>();\n\n/**\n * `recordingResetByDoc` holds, per Document, the way to throw its replay\n * recording away. See `resetDevtoolsRecording`.\n */\nconst recordingResetByDoc = new WeakMap<\n  object,\n  (baseline?: DocEventsForReplay) => void\n>();\n\n/**\n * `Registration` is one `setupDevtools` call. Each keeps its own recording, so\n * handing a key from one Document to another hands over a complete history\n * instead of whatever the previous holder had collected.\n */\ntype Registration = {\n  token: object;\n  events: Array<DocEventsForReplay>;\n  notifications: Array<DocNotification>;\n  attached: boolean;\n};\n\n/**\n * `registrationsByDocKey` holds every Document that has claimed a key on this\n * page, oldest first.\n */\nconst registrationsByDocKey = new Map<string, Array<Registration>>();\n\n/**\n * `ownerByDocKey` names the registration that speaks for a key: the protocol\n * identifies a document by its key alone, so only one of them can answer the\n * panel and fill the replay buffer.\n *\n * NOTE(chacha912): The key goes to the Document that is *attached*, not to\n * the one built most recently. A page under React's development double-render\n * builds two Documents per key and throws one away, and which of the two is\n * built last is decided by whichever token request happens to return first.\n * Picking by construction order hands the panel the discarded Document about\n * half the time, and the user sees a document that never changes again.\n * Construction order still decides between Documents that never attach.\n */\nconst ownerByDocKey = new Map<string, object>();\n\n/**\n * `sendFullSync` hands the panel the whole recording of the given key. It is\n * sent when the panel asks, and again whenever the recording behind the key is\n * replaced, because the panel has no way to notice that on its own.\n */\nfunction sendFullSync(docKey: string): void {\n  if (getDevtoolsStatus(docKey) !== 'synced') {\n    return;\n  }\n\n  sendToPanel({\n    msg: 'doc::sync::full',\n    docKey,\n    events: docEventsForReplayByDocKey.get(docKey) || [],\n  });\n  sendToPanel({\n    msg: 'doc::notification::full',\n    docKey,\n    notifications: docNotificationsByDocKey.get(docKey) || [],\n  });\n}\n\n/**\n * `ownerOf` returns the registration currently speaking for the given key.\n */\nfunction ownerOf(docKey: string): Registration | undefined {\n  const token = ownerByDocKey.get(docKey);\n  return (registrationsByDocKey.get(docKey) || []).find(\n    (registration) => registration.token === token,\n  );\n}\n\n/**\n * `claimKey` makes the given registration the one that answers for the key and\n * publishes its recording. It reports whether the owner actually changed.\n */\nfunction claimKey(docKey: string, registration: Registration): boolean {\n  if (ownerByDocKey.get(docKey) === registration.token) {\n    return false;\n  }\n\n  ownerByDocKey.set(docKey, registration.token);\n  docEventsForReplayByDocKey.set(docKey, registration.events);\n  docNotificationsByDocKey.set(docKey, registration.notifications);\n  return true;\n}\n\n/**\n * `releaseKey` gives up a key the leaving registration held, handing it to\n * another Document of the same key that is still attached. It reports whether\n * a successor took over.\n */\nfunction releaseKey(docKey: string, registration: Registration): boolean {\n  if (ownerByDocKey.get(docKey) !== registration.token) {\n    // NOTE(chacha912): Another Document already speaks for the key, so the\n    // panel keeps what it is showing. A key nobody holds is a key whose\n    // Documents have all left, and it has nothing left to announce.\n    return ownerByDocKey.has(docKey);\n  }\n\n  const successor = (registrationsByDocKey.get(docKey) || [])\n    .filter((other) => other !== registration && other.attached)\n    .pop();\n  if (!successor) {\n    ownerByDocKey.delete(docKey);\n    docEventsForReplayByDocKey.delete(docKey);\n    docNotificationsByDocKey.delete(docKey);\n    return false;\n  }\n\n  claimKey(docKey, successor);\n  return true;\n}\n\n/**\n * `getDevtoolsStatus` returns the panel connection status of the given\n * document.\n */\nfunction getDevtoolsStatus(docKey: string): DevtoolsStatus {\n  return devtoolsStatusByDocKey.get(docKey) || 'disconnected';\n}\n\n/**\n * `isPanelConnected` returns whether the panel is attached to any document on\n * this page.\n */\nfunction isPanelConnected(): boolean {\n  for (const status of devtoolsStatusByDocKey.values()) {\n    if (status !== 'disconnected') {\n      return true;\n    }\n  }\n\n  return false;\n}\n\n/**\n * `docEventsForReplayByDocKey` stores all events in the document for replaying\n * (time-traveling feature) in Devtools. Later, external storage such as\n * IndexedDB will be used.\n */\nconst docEventsForReplayByDocKey = new Map<string, Array<DocEventsForReplay>>();\ndeclare global {\n  interface Window {\n    docEventsForReplayByDocKey: Map<string, Array<DocEventsForReplay>>;\n  }\n}\nif (typeof window !== 'undefined') {\n  window.docEventsForReplayByDocKey = docEventsForReplayByDocKey;\n}\n\n/**\n * `docNotificationsByDocKey` stores the events that cannot be replayed, such as\n * `LocalChangesDropped`. They are kept beside `docEventsForReplayByDocKey`\n * because `Document.applyDocEventsForReplay` has no case for them and the\n * panel's time travel is an index over the replay list.\n */\nconst docNotificationsByDocKey = new Map<string, Array<DocNotification>>();\n\n/**\n * `repeatKeyOf` returns a value identifying a notification that a retry loop\n * can republish unchanged. Two records sharing a key describe the same\n * ongoing condition, not two things that happened.\n *\n * `LocalChangesDropped` deliberately has no key: every one of them reports a\n * distinct set of discarded changes and must always be recorded.\n *\n * NOTE(hackerwins): `DocEventType` is read lazily. `document.ts` imports this\n * module, so the enum is still uninitialized while this one is evaluated.\n */\nfunction repeatKeyOf(event: DocNotificationEvent): string | undefined {\n  switch (event.type) {\n    case DocEventType.SyncStatusChanged:\n    case DocEventType.ConnectionChanged:\n      return `${event.type}:${event.value}`;\n    case DocEventType.AuthError:\n      return `${event.type}:${event.value.method}:${event.value.reason}`;\n    case DocEventType.EpochMismatch:\n      return `${event.type}:${event.value.method}`;\n    case DocEventType.WriteRejected:\n      return `${event.type}:${event.value.method}:${event.value.code}`;\n    default:\n      return undefined;\n  }\n}\n\n/**\n * `isStatusRepeat` reports whether the given event restates the condition\n * already held by the most recent record of the same type.\n *\n * Without this the retry loops bury everything else. A document holding an\n * invalid token publishes `AuthError` from the sync loop every\n * `retrySyncLoopDelay` and again from the watch loop every\n * `reconnectStreamDelay`, and the sync loop republishes `SyncStatusChanged`\n * on every round it runs. Minutes of that would leave a single\n * `LocalChangesDropped` as one row among thousands.\n */\nfunction isStatusRepeat(\n  recorded: Array<DocNotification>,\n  event: DocNotificationEvent,\n  pending: Array<DocNotification>,\n): boolean {\n  const key = repeatKeyOf(event);\n  if (key === undefined) {\n    return false;\n  }\n\n  for (const list of [pending, recorded]) {\n    for (let i = list.length - 1; i >= 0; i--) {\n      const previous = list[i].event;\n      if (previous.type === event.type) {\n        return repeatKeyOf(previous) === key;\n      }\n    }\n  }\n\n  return false;\n}\n\n/**\n * `sendToPanel` sends a message to the devtools panel.\n */\nfunction sendToPanel(\n  message: DevTools.SDKToPanelMessage,\n  options?: { force: boolean },\n): void {\n  const connected =\n    'docKey' in message && getDevtoolsStatus(message.docKey) !== 'disconnected';\n  if (!(options?.force || connected)) {\n    return;\n  }\n\n  window.postMessage(\n    {\n      source: EventSourceSDK,\n      ...message,\n    },\n    '*',\n  );\n}\n\n/**\n * `setupDevtools` sets up the devtools integration. It sends messages to the\n * devtools panel when a document is available, when a document is subscribed,\n * and when a document is changed.\n */\nexport function setupDevtools<T, P extends Indexable>(\n  doc: Document<T, P>,\n): void {\n  if (!doc.isEnableDevtools() || typeof window === 'undefined') {\n    return;\n  }\n\n  // NOTE(chacha912): A document key can be claimed twice on one page: a\n  // component remounts, or a page swaps documents while the old one is still\n  // being torn down. Every claim records on its own, and `ownerByDocKey`\n  // decides which recording the panel sees.\n  const registration: Registration = {\n    token: {},\n    events: [],\n    notifications: [],\n    attached: false,\n  };\n  const registrations = registrationsByDocKey.get(doc.getKey()) || [];\n  registrations.push(registration);\n  registrationsByDocKey.set(doc.getKey(), registrations);\n\n  // NOTE(chacha912): A Document that has attached is the one the page is\n  // working with, so a newly built Document does not displace it. Between\n  // Documents that never attach, the newest still wins: the older one is a\n  // remount leftover the application can no longer reach.\n  if (!ownerOf(doc.getKey())?.attached) {\n    claimKey(doc.getKey(), registration);\n  }\n  // NOTE(hackerwins): A re-claim replaces the Document behind the key, not the\n  // panel's attachment to it. Zeroing the status here would make\n  // `isPanelConnected` report false on a single-document page, so the SDK would\n  // send `refresh-devtools` and wipe the view the re-announce path exists to\n  // preserve.\n  if (!devtoolsStatusByDocKey.has(doc.getKey())) {\n    devtoolsStatusByDocKey.set(doc.getKey(), 'disconnected');\n  }\n\n  const isOwner = () => ownerByDocKey.get(doc.getKey()) === registration.token;\n\n  /**\n   * `answersForKey` reports whether this registration is the one to answer the\n   * panel about the key. The owner answers while there is one. A key whose\n   * Documents have all detached has no owner at all, and a `devtools::subscribe`\n   * that nobody answers leaves the panel waiting with neither a full sync nor\n   * an error, so the newest registration speaks for such a key until a Document\n   * attaches again.\n   */\n  const answersForKey = () => {\n    if (ownerByDocKey.has(doc.getKey())) {\n      return isOwner();\n    }\n\n    const registered = registrationsByDocKey.get(doc.getKey()) || [];\n    return registered[registered.length - 1] === registration;\n  };\n\n  const unsub = doc.subscribe('all', (events) => {\n    // NOTE(hackerwins): One transaction can carry both replayable events and\n    // events that cannot be replayed, so the batch is split by hand.\n    // `events.filter(isDocEventForReplay)` does not narrow here: this callback\n    // receives `DocEvents<P>` with `P` still an unresolved type parameter,\n    // while the guard is declared over `DocEvent<Indexable, OpInfo>`.\n    const eventsForReplay: DocEventsForReplay = [];\n    const notifications: Array<DocNotification> = [];\n    for (const event of events) {\n      if (isDocEventForReplay(event)) {\n        eventsForReplay.push(event);\n      } else if (isDocNotificationEvent(event)) {\n        if (isStatusRepeat(registration.notifications, event, notifications)) {\n          continue;\n        }\n        notifications.push({ event, timestamp: Date.now() });\n      }\n    }\n\n    // NOTE(hackerwins): The replay half of the batch goes first, so that the\n    // document state the panel replays never lags behind a notification that\n    // refers to it. The two lists are rendered separately anyway, so the\n    // interleaving within one transaction is not observable.\n    if (eventsForReplay.length > 0) {\n      registration.events.push(eventsForReplay);\n      if (isOwner() && getDevtoolsStatus(doc.getKey()) === 'synced') {\n        sendToPanel({\n          msg: 'doc::sync::partial',\n          docKey: doc.getKey(),\n          event: eventsForReplay,\n        });\n      }\n    }\n\n    for (const notification of notifications) {\n      registration.notifications.push(notification);\n      if (isOwner() && getDevtoolsStatus(doc.getKey()) === 'synced') {\n        sendToPanel({\n          msg: 'doc::notification::partial',\n          docKey: doc.getKey(),\n          notification,\n        });\n      }\n    }\n\n    // NOTE(chacha912): A page that swaps documents as the user navigates —\n    // one document per page of a board, say — leaves every document it has\n    // ever opened registered here. Without this the panel keeps offering all\n    // of them and the user picks a detached one that will never move again.\n    // The recording survives, so attaching again brings the key back.\n    for (const event of events) {\n      if (event.type !== DocEventType.StatusChanged) {\n        continue;\n      }\n      const attached = event.value.status === DocStatus.Attached;\n      registration.attached = attached;\n      if (attached) {\n        // NOTE(chacha912): Two Documents of one key can be attached at once: a\n        // remount whose predecessor has not finished detaching, or two clients\n        // collaborating inside a single page. The one that already holds the\n        // key keeps it, because taking it over here would replace the history\n        // the user is watching with this Document's empty recording.\n        const owner = ownerOf(doc.getKey());\n        if (owner && owner !== registration && owner.attached) {\n          continue;\n        }\n\n        claimKey(doc.getKey(), registration);\n        sendToPanel({ msg: 'doc::available', docKey: doc.getKey() });\n        // NOTE(chacha912): The panel may have subscribed to this key while\n        // the document was still attaching, and answered with the empty log it\n        // had at that moment. It cannot tell that the log it holds is the wrong\n        // one, so the recording is handed over here rather than waiting for the\n        // panel to ask again.\n        sendFullSync(doc.getKey());\n        continue;\n      }\n\n      // NOTE(chacha912): A page that shows one document at a time leaves every\n      // document it has opened registered here. Announcing them all gives the\n      // user a list of documents that will never move again, so a key that has\n      // no attached Document behind it goes quiet until one attaches.\n      const successor = releaseKey(doc.getKey(), registration);\n      sendToPanel({\n        msg: successor ? 'doc::available' : 'doc::unavailable',\n        docKey: doc.getKey(),\n      });\n      if (successor) {\n        sendFullSync(doc.getKey());\n      }\n    }\n  });\n\n  // NOTE(chacha912): Send initial message, in case the devtool panel is already open.\n  // NOTE(hackerwins): When the panel is already attached to another document on\n  // this page, announcing this document is enough. Asking for a refresh would\n  // throw away the view the user is currently looking at.\n  if (isPanelConnected()) {\n    sendToPanel(\n      {\n        msg: 'doc::available',\n        docKey: doc.getKey(),\n      },\n      { force: true },\n    );\n  } else {\n    sendToPanel(\n      {\n        msg: 'refresh-devtools',\n      },\n      { force: true },\n    );\n  }\n\n  const handleMessage = (\n    event: MessageEvent<DevTools.FullPanelToSDKMessage>,\n  ) => {\n    // NOTE(hackerwins): `message` events also arrive from child frames. Only\n    // this window's own posts come from the panel relay; a third-party iframe\n    // must not be able to drive the bridge.\n    if (event.source !== window || event.data?.source !== EventSourceDevPanel) {\n      return;\n    }\n\n    const message = event.data;\n    switch (message.msg) {\n      case 'devtools::connect':\n        // NOTE(hackerwins): The panel clears its state before sending\n        // `devtools::connect`, so every document has to announce itself\n        // again, including one that is already connected.\n        devtoolsStatusByDocKey.set(doc.getKey(), 'connected');\n        if (!isOwner()) {\n          break;\n        }\n        sendToPanel({\n          msg: 'doc::available',\n          docKey: doc.getKey(),\n        });\n        logger.info(`[YD] Devtools connected. Doc: ${doc.getKey()}`);\n        break;\n      case 'devtools::disconnect':\n        devtoolsStatusByDocKey.set(doc.getKey(), 'disconnected');\n        logger.info(`[YD] Devtools disconnected. Doc: ${doc.getKey()}`);\n        break;\n      case 'devtools::subscribe':\n        // NOTE(hackerwins): The panel watches one document at a time, so\n        // subscribing to another document stops the stream of this one. This\n        // runs whoever owns the key: a registration that no longer speaks for\n        // it still has to stop streaming.\n        if (message.docKey !== doc.getKey()) {\n          if (getDevtoolsStatus(doc.getKey()) === 'synced') {\n            devtoolsStatusByDocKey.set(doc.getKey(), 'connected');\n          }\n          break;\n        }\n        if (!answersForKey()) {\n          break;\n        }\n\n        devtoolsStatusByDocKey.set(doc.getKey(), 'synced');\n        sendFullSync(doc.getKey());\n        logger.info(`[YD] Devtools subscribed. Doc: ${doc.getKey()}`);\n        break;\n    }\n  };\n  window.addEventListener('message', handleMessage);\n\n  // NOTE(chacha912): A Document that stays on the page keeps its subscription\n  // and its recording even while detached, so that attaching again brings the\n  // history back. A Document the page has thrown away has to give them back:\n  // the bindings build a new Document under the same key whenever their effect\n  // re-runs, and a registration nobody releases leaves a window listener, a\n  // subscription and a recording that grows with every event behind on each\n  // remount. `teardownDevtools` is how the holder of the Document says so.\n  recordingResetByDoc.set(doc, (baseline?: DocEventsForReplay) => {\n    // The array is the one `claimKey` handed to `docEventsForReplayByDocKey`,\n    // so it is emptied in place rather than replaced.\n    registration.events.length = 0;\n    if (baseline?.length) {\n      registration.events.push(baseline);\n    }\n    if (isOwner()) {\n      sendFullSync(doc.getKey());\n    }\n  });\n\n  teardownByDoc.set(doc, () => {\n    teardownByDoc.delete(doc);\n    recordingResetByDoc.delete(doc);\n    unsub();\n    window.removeEventListener('message', handleMessage);\n\n    const remaining = (registrationsByDocKey.get(doc.getKey()) || []).filter(\n      (other) => other !== registration,\n    );\n    if (remaining.length > 0) {\n      registrationsByDocKey.set(doc.getKey(), remaining);\n    } else {\n      registrationsByDocKey.delete(doc.getKey());\n    }\n\n    if (isOwner()) {\n      // NOTE(chacha912): The key goes to another attached Document of the same\n      // key if there is one, and otherwise goes quiet: the panel must not be\n      // left offering a document that nothing on the page can reach any more.\n      const successor = releaseKey(doc.getKey(), registration);\n      sendToPanel({\n        msg: successor ? 'doc::available' : 'doc::unavailable',\n        docKey: doc.getKey(),\n      });\n      if (successor) {\n        sendFullSync(doc.getKey());\n      }\n    }\n\n    // NOTE(chacha912): The status is dropped last, after the messages above\n    // have gone out through it. Nothing is left to answer\n    // `devtools::disconnect` for a key with no Document, so a status left\n    // behind would keep `isPanelConnected` reporting a panel that has closed.\n    if (remaining.length === 0) {\n      devtoolsStatusByDocKey.delete(doc.getKey());\n    }\n  });\n}\n\n/**\n * `resetDevtoolsRecording` drops the replay events recorded for the given\n * Document and tells the panel, which has no way to notice on its own.\n *\n * The panel replays a document from its initial root by applying the raw\n * changes the recording carries. A document that re-issues its pre-attach\n * tickets to the client's actor (`Document.setActor` with `reissue`) rewrites\n * those changes in place: the recorded copies name an actor nothing in the\n * document uses any more, so replaying them and then the changes that follow\n * the attach diverges from the live root, or throws on an operation whose\n * target the replay never created. Nothing can repair the recorded copies\n * from here, so the history is dropped and the panel restarts from the\n * re-issued document. It is a no-op for a Document with no registration.\n *\n * The panel replays onto a freshly built empty Document and has no way to be\n * told \"start from here\", so a recording that merely started over would be a\n * history missing its beginning: the events recorded after the reset would be\n * replayed onto a root that never had the ones before it, which diverges or\n * throws on an operation whose target the replay never created. The caller\n * therefore hands over a `baseline` -- a snapshot event carrying the document\n * as it stands -- which becomes the recording's first entry so that what the\n * panel holds is a complete history again.\n */\nexport function resetDevtoolsRecording<T, P extends Indexable>(\n  doc: Document<T, P>,\n  baseline?: DocEventsForReplay,\n): void {\n  recordingResetByDoc.get(doc)?.(baseline);\n}\n\n/**\n * `teardownDevtools` releases what `setupDevtools` registered for the given\n * Document: its subscription, its window listener and its recording. Call it\n * when the Document is discarded — nothing else reaches those, and a page that\n * rebuilds Documents under one key accumulates them otherwise. It is a no-op\n * for a Document that has no devtools registration, and calling it twice is\n * harmless.\n */\nexport function teardownDevtools<T, P extends Indexable>(\n  doc: Document<T, P>,\n): void {\n  teardownByDoc.get(doc)?.();\n}\n","/*\n * Copyright 2020 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { DocEventType as PbDocEventType } from '@yorkie-js/sdk/src/api/yorkie/v1/resources_pb';\nimport { converter } from '@yorkie-js/sdk/src/api/converter';\nimport { reissueOperations } from '@yorkie-js/sdk/src/api/reissue';\nimport { logger, LogLevel } from '@yorkie-js/sdk/src/util/logger';\nimport {\n  ChangeApplyError,\n  Code,\n  YorkieError,\n} from '@yorkie-js/sdk/src/util/error';\nimport { deepcopy } from '@yorkie-js/sdk/src/util/object';\nimport { DocSize, totalDocSize } from '@yorkie-js/sdk/src/util/resource';\nimport {\n  Observer,\n  Observable,\n  createObservable,\n  Unsubscribe,\n  ErrorFn,\n  CompleteFn,\n  NextFn,\n} from '@yorkie-js/sdk/src/util/observable';\nimport {\n  ActorID,\n  InitialActorID,\n} from '@yorkie-js/sdk/src/document/time/actor_id';\nimport { Attachable } from '@yorkie-js/sdk/src/client/attachable';\nimport { VersionVector } from '@yorkie-js/sdk/src/document/time/version_vector';\nimport {\n  Change,\n  ChangeStruct,\n} from '@yorkie-js/sdk/src/document/change/change';\nimport {\n  ChangeID,\n  InitialChangeID,\n} from '@yorkie-js/sdk/src/document/change/change_id';\nimport { ChangeContext } from '@yorkie-js/sdk/src/document/change/context';\nimport { ChangePack } from '@yorkie-js/sdk/src/document/change/change_pack';\nimport {\n  Checkpoint,\n  InitialCheckpoint,\n} from '@yorkie-js/sdk/src/document/change/checkpoint';\nimport {\n  OpSource,\n  OpInfo,\n  ObjectOpInfo,\n  TextOpInfo,\n  CounterOpInfo,\n  ArrayOpInfo,\n  TreeOpInfo,\n  Operation,\n} from '@yorkie-js/sdk/src/document/operation/operation';\nimport { ArraySetOperation } from '@yorkie-js/sdk/src/document/operation/array_set_operation';\nimport { AddOperation } from '@yorkie-js/sdk/src/document/operation/add_operation';\nimport { SetOperation } from '@yorkie-js/sdk/src/document/operation/set_operation';\nimport { dropSplitLinksInElement } from '@yorkie-js/sdk/src/document/crdt/split_links';\nimport {\n  createJSON,\n  JSONElement,\n} from '@yorkie-js/sdk/src/document/json/element';\nimport { JSONArray } from '@yorkie-js/sdk/src/document/json/array';\nimport { JSONObject } from '@yorkie-js/sdk/src/document/json/object';\nimport { Counter } from '@yorkie-js/sdk/src/document/json/counter';\nimport { Text } from '@yorkie-js/sdk/src/document/json/text';\nimport { Tree } from '@yorkie-js/sdk/src/document/json/tree';\nimport { CRDTRoot, RootStats } from '@yorkie-js/sdk/src/document/crdt/root';\nimport { CRDTObject } from '@yorkie-js/sdk/src/document/crdt/object';\nimport { Channel } from '@yorkie-js/sdk/src/document/presence/presence';\nimport {\n  PresenceChangeType,\n  PresencePatchCapability,\n} from '@yorkie-js/sdk/src/document/presence/change';\nimport {\n  History,\n  HistoryOperation,\n  MaxUndoRedoStackDepth,\n} from '@yorkie-js/sdk/src/document/history';\nimport {\n  Primitive,\n  PrimitiveValue,\n} from '@yorkie-js/sdk/src/document/crdt/primitive';\nimport { Rule } from '@yorkie-js/schema';\nimport { validateYorkieRuleset } from '@yorkie-js/sdk/src/document/schema/ruleset_validator';\nimport {\n  resetDevtoolsRecording,\n  setupDevtools,\n} from '@yorkie-js/sdk/src/devtools';\nimport * as Devtools from '@yorkie-js/sdk/src/devtools/types';\nimport { EditOperation } from './operation/edit_operation';\nimport { TreeEditOperation } from './operation/tree_edit_operation';\nimport { TreeStyleOperation } from './operation/tree_style_operation';\nimport { CRDTTreeNodeID } from './crdt/tree';\n\n/**\n * `DocumentOptions` are the options to create a new document.\n */\nexport interface DocumentOptions {\n  /**\n   * `disableGC` disables garbage collection if true.\n   */\n  disableGC?: boolean;\n\n  /**\n   * `disablePresence` declares that this document does not use presence.\n   * When true, `Document.update`'s `presence.set` calls are silently\n   * dropped and the server strips any presence that nonetheless reaches\n   * it. The option is server-fixated on first attach — once a document\n   * is created presenceless, subsequent attaches observe `true` from the\n   * attach response regardless of the local option value. Use for\n   * counter-only or other presence-free workloads where the per-client\n   * presence map would otherwise leak memory in long-lived documents.\n   */\n  disablePresence?: boolean;\n\n  /**\n   * `enableDevtools` enables devtools if true.\n   */\n  enableDevtools?: boolean;\n\n  /**\n   * `maxUndoDepth` is how many changes `history.undo()` can go back, and\n   * likewise for `history.redo()`. Each `Document.update` that changes the\n   * document is one entry; the oldest is dropped when the stack is full.\n   * Defaults to `MaxUndoRedoStackDepth` (50). Must be a positive integer.\n   * A reverse entry keeps a copy of the content it would restore, so a\n   * larger depth holds more memory.\n   */\n  maxUndoDepth?: number;\n}\n\n/**\n * `ReissueToken` is the capability `Document.setActor` demands before it\n * re-issues anything. It is a module-private symbol: nothing stores it on a\n * `Document`, the published bundle does not re-export it (`yorkie.ts`), and\n * `Symbol` identity cannot be reconstructed, so holding a `Document` handle\n * is not enough to ask for a re-issue -- only the owning `Client`, which\n * imports this module, can. The re-issue rewrites element identity under a\n * caller-chosen actor, so it must not be reachable from application code.\n *\n * @internal\n */\nexport const ReissueToken: unique symbol = Symbol('yorkie.setActor.reissue');\n\n/**\n * `SetActorOptions` are the options of `Document.setActor`.\n *\n * @internal\n */\nexport interface SetActorOptions {\n  /**\n   * `reissue` re-issues the tickets a never-synced document minted under its\n   * previous actor to the new one, in the local changes and the root alike.\n   * A document that has synced, has no local changes or already has the\n   * actor falls back to the plain `setActor`. It has to be `ReissueToken`:\n   * only `Client.attach` holds it, because whether the re-issue is sound\n   * depends on what else the actor has minted, which only the client knows.\n   */\n  reissue?: typeof ReissueToken;\n}\n\n/**\n * `DocStatus` represents the status of the document.\n */\nexport enum DocStatus {\n  /**\n   * Detached means that the document is not attached to the client.\n   * The actor of the ticket is created without being assigned.\n   */\n  Detached = 'detached',\n  /**\n   * Attached means that this document is attached to the client.\n   * The actor of the ticket is created with being assigned by the client.\n   */\n  Attached = 'attached',\n  /**\n   * Removed means that this document is removed. If the document is removed,\n   * it cannot be edited.\n   */\n  Removed = 'removed',\n}\n\n/**\n * `DocEventType` represents the type of the event that occurs in `Document`.\n */\nexport enum DocEventType {\n  /**\n   * status changed event type\n   */\n  StatusChanged = 'status-changed',\n\n  /**\n   * `ConnectionChanged` means that the watch stream connection status has changed.\n   */\n  ConnectionChanged = 'connection-changed',\n\n  /**\n   * `SyncStatusChanged` means that the document sync status has changed.\n   */\n  SyncStatusChanged = 'sync-status-changed',\n\n  /**\n   * snapshot event type\n   */\n  Snapshot = 'snapshot',\n\n  /**\n   * local document change event type\n   */\n  LocalChange = 'local-change',\n\n  /**\n   * remote document change event type\n   */\n  RemoteChange = 'remote-change',\n\n  /**\n   * `Initialized` means that online clients have been loaded from the server.\n   */\n  Initialized = 'initialized',\n\n  /**\n   * `Watched` means that the client has established a connection with the server,\n   * enabling real-time synchronization.\n   */\n  Watched = 'watched',\n\n  /**\n   * `Unwatched` means that the connection has been disconnected.\n   */\n  Unwatched = 'unwatched',\n\n  /**\n   * `PresenceChanged` means that the presences of the client has updated.\n   */\n  PresenceChanged = 'presence-changed',\n\n  /**\n   * `AuthError` indicates an authorization failure in syncLoop or watchLoop.\n   */\n  AuthError = 'auth-error',\n\n  /**\n   * `EpochMismatch` indicates the document was compacted on the server\n   * and this client must detach and reattach to recover.\n   */\n  EpochMismatch = 'epoch-mismatch',\n\n  /**\n   * `WriteRejected` indicates the server refused to store this document's\n   * pushed changes for a reason that resending them cannot fix, such as the\n   * document being over its size limit. The sync loop parks this document —\n   * the client's other documents keep syncing — and the rejected changes stay\n   * applied locally but will never reach the server until the app recovers.\n   */\n  WriteRejected = 'write-rejected',\n\n  /**\n   * `LocalChangesDropped` indicates the offline-persistence layer had to\n   * discard un-pushed local changes it could not reconcile with the server\n   * (a stale-epoch re-anchor, a server-side GC/purge of the document, or a\n   * store reused under a different actor). The event carries the dropped\n   * changes so the app can surface the data loss and, if it wishes, re-apply\n   * them on top of the re-anchored state.\n   */\n  LocalChangesDropped = 'local-changes-dropped',\n\n  /**\n   * `PersistDisabled` indicates the offline-persistence layer stopped\n   * persisting this document because writing it costs more than the configured\n   * budget allows. Editing continues; durability does not. An app that reports\n   * sync state should say so, since the user's work is no longer being kept.\n   */\n  PersistDisabled = 'persist-disabled',\n}\n\n/**\n * `DocEvent` is an event that occurs in `Document`. It can be delivered\n * using `Document.subscribe()`.\n */\nexport type DocEvent<P extends Indexable = Indexable, T = OpInfo> =\n  | StatusChangedEvent\n  | ConnectionChangedEvent\n  | SyncStatusChangedEvent\n  | SnapshotEvent\n  | LocalChangeEvent<T, P>\n  | RemoteChangeEvent<T, P>\n  | PresenceEvent<P>\n  | AuthErrorEvent\n  | EpochMismatchEvent\n  | WriteRejectedEvent\n  | LocalChangesDroppedEvent<P>\n  | PersistDisabledEvent;\n\n/**\n * `DocEvents` represents document events that occur within\n * a single transaction (e.g., doc.update).\n */\nexport type DocEvents<P extends Indexable = Indexable> = Array<DocEvent<P>>;\n\ninterface BaseDocEvent {\n  type: DocEventType;\n}\n\n/**\n * `StatusChangedEvent` is an event that occurs when the status of a document changes.\n */\nexport interface StatusChangedEvent extends BaseDocEvent {\n  type: DocEventType.StatusChanged;\n  source: OpSource;\n  value:\n    | { status: DocStatus.Attached; actorID: string }\n    | { status: DocStatus.Detached }\n    | { status: DocStatus.Removed };\n}\n\n/**\n * `StreamConnectionStatus` represents whether the stream connection is connected or not.\n */\nexport enum StreamConnectionStatus {\n  /**\n   * `Connected` means that the stream connection is connected.\n   */\n  Connected = 'connected',\n\n  /**\n   * `Disconnected` means that the stream connection is disconnected.\n   */\n  Disconnected = 'disconnected',\n}\n\n/**\n * `ConnectionChangedEvent` is an event that occurs when the stream connection state changes.\n */\nexport interface ConnectionChangedEvent extends BaseDocEvent {\n  type: DocEventType.ConnectionChanged;\n  value: StreamConnectionStatus;\n}\n\n/**\n * `DocSyncStatus` represents the result of synchronizing the document with the server.\n */\nexport enum DocSyncStatus {\n  /**\n   * `Synced` means that document synced successfully.\n   */\n  Synced = 'synced',\n\n  /**\n   * `SyncFiled` means that document synchronization has failed.\n   */\n  SyncFailed = 'sync-failed',\n}\n\n/**\n * `SyncStatusChangedEvent` is an event that occurs when document is synced with the server.\n */\nexport interface SyncStatusChangedEvent extends BaseDocEvent {\n  type: DocEventType.SyncStatusChanged;\n  value: DocSyncStatus;\n}\n\n/**\n * `SnapshotEvent` is an event that occurs when a snapshot is received from\n * the server.\n */\nexport interface SnapshotEvent extends BaseDocEvent {\n  type: DocEventType.Snapshot;\n  source: OpSource.Remote;\n  value: {\n    snapshot: string | undefined;\n    serverSeq: string;\n    snapshotVector: string;\n  };\n}\n\n/**\n * `ChangeInfo` represents the modifications made during a document update\n * and the message passed.\n */\nexport interface ChangeInfo<T = OpInfo> {\n  message: string;\n  operations: Array<T>;\n  actor: ActorID;\n  clientSeq: number;\n  serverSeq: string;\n}\n\n/**\n * `PresenceEvent` is an event that occurs when the presence of a client changes.\n */\nexport type PresenceEvent<P extends Indexable = Indexable> =\n  | InitializedEvent<P>\n  | WatchedEvent<P>\n  | UnwatchedEvent<P>\n  | PresenceChangedEvent<P>;\n\n/**\n * `LocalChangeEvent` is an event that occurs when the document is changed\n * by local changes.\n */\nexport interface LocalChangeEvent<\n  T = OpInfo,\n  P extends Indexable = Indexable,\n> extends BaseDocEvent {\n  type: DocEventType.LocalChange;\n  source: OpSource.Local | OpSource.UndoRedo;\n  value: ChangeInfo<T>;\n  rawChange?: ChangeStruct<P>;\n}\n\n/**\n * `RemoteChangeEvent` is an event that occurs when the document is changed\n * by remote changes.\n */\nexport interface RemoteChangeEvent<\n  T = OpInfo,\n  P extends Indexable = Indexable,\n> extends BaseDocEvent {\n  type: DocEventType.RemoteChange;\n  source: OpSource.Remote;\n  value: ChangeInfo<T>;\n  rawChange?: ChangeStruct<P>;\n}\n\nexport interface InitializedEvent<P extends Indexable> extends BaseDocEvent {\n  type: DocEventType.Initialized;\n  source: OpSource.Local;\n  value: Array<{ clientID: ActorID; presence: P }>;\n}\n\nexport interface WatchedEvent<P extends Indexable> extends BaseDocEvent {\n  type: DocEventType.Watched;\n  source: OpSource.Remote;\n  value: { clientID: ActorID; presence: P };\n}\n\nexport interface UnwatchedEvent<P extends Indexable> extends BaseDocEvent {\n  type: DocEventType.Unwatched;\n  source: OpSource.Remote;\n  value: { clientID: ActorID; presence: P };\n}\n\nexport interface PresenceChangedEvent<\n  P extends Indexable,\n> extends BaseDocEvent {\n  type: DocEventType.PresenceChanged;\n  source: OpSource;\n  value: { clientID: ActorID; presence: P };\n}\n\nexport interface AuthErrorEvent extends BaseDocEvent {\n  type: DocEventType.AuthError;\n  value: {\n    reason: string;\n    method: 'PushPull' | 'Watch';\n  };\n}\n\nexport interface EpochMismatchEvent extends BaseDocEvent {\n  type: DocEventType.EpochMismatch;\n  value: {\n    method: 'PushPull';\n  };\n}\n\n/**\n * `WriteRejectedEvent` reports a push the server refused for a reason that\n * resending cannot fix. `value.code` says which — `ErrDocumentSizeExceedsLimit`\n * when the document is over its size limit, `ErrChangeTooLarge` when a single\n * change is too large to store — so the app can tell this apart from a network\n * failure, tell the user, and switch the editor to read-only.\n */\nexport interface WriteRejectedEvent extends BaseDocEvent {\n  type: DocEventType.WriteRejected;\n  value: {\n    code: Code;\n    reason: string;\n    method: 'PushPull';\n  };\n}\n\nexport type PersistDisabledReason =\n  // Serializing the document exceeded `maxPersistBytes`.\n  | 'too-large'\n  // Serializing the document took longer than `maxPersistMillis`.\n  | 'too-slow';\n\n/**\n * `PersistDisabledEvent` reports that this document is no longer being\n * persisted. It fires once per attachment: the measurement that triggers it is\n * taken at compaction, and latching tears the persist subscription down, so\n * the cost of discovering the document is unaffordable is paid once.\n */\nexport interface PersistDisabledEvent extends BaseDocEvent {\n  type: DocEventType.PersistDisabled;\n  value: { reason: PersistDisabledReason; bytes: number; millis: number };\n}\n\n/**\n * `LocalChangesDroppedReason` enumerates why the offline-persistence layer\n * had to discard un-pushed local changes it could not reconcile.\n */\nexport type LocalChangesDroppedReason =\n  | 'epoch-reanchor'\n  | 'document-purged'\n  | 'actor-mismatch'\n  | 'restore-failed'\n  // The server refused this client's writes (`ErrPermissionDenied`) and\n  // `Client.resync` took the refused changes out of the queue to re-anchor the\n  // document on the server state. Raised once the detach has succeeded, i.e.\n  // once the changes are gone for good.\n  | 'write-denied'\n  // The persisted change log had a `clientSeq` hole — an append that never\n  // landed — so it could not be replayed: the server rejects a discontinuous\n  // run, and a document restored from one would never sync again.\n  | 'log-discontinuity';\n\n/**\n * `LocalChangesDroppedEvent` is an app-visible data-loss signal: the persisted\n * un-pushed local changes could not be reconciled with the server and were\n * discarded. `value.changes` carries their serialized structs so the app can\n * surface the loss and optionally re-apply them on top of the recovered state.\n */\nexport interface LocalChangesDroppedEvent<\n  P extends Indexable = Indexable,\n> extends BaseDocEvent {\n  type: DocEventType.LocalChangesDropped;\n  value: {\n    reason: LocalChangesDroppedReason;\n    changes: Array<ChangeStruct<P>>;\n  };\n}\n\ntype DocEventCallbackMap<P extends Indexable> = {\n  default: NextFn<\n    LocalChangeEvent<OpInfo, P> | RemoteChangeEvent<OpInfo, P> | SnapshotEvent\n  >;\n  presence: NextFn<PresenceEvent<P>>;\n  'my-presence': NextFn<InitializedEvent<P> | PresenceChangedEvent<P>>;\n  others: NextFn<WatchedEvent<P> | UnwatchedEvent<P> | PresenceChangedEvent<P>>;\n  connection: NextFn<ConnectionChangedEvent>;\n  status: NextFn<StatusChangedEvent>;\n  sync: NextFn<SyncStatusChangedEvent>;\n  'auth-error': NextFn<AuthErrorEvent>;\n  'epoch-mismatch': NextFn<EpochMismatchEvent>;\n  'write-rejected': NextFn<WriteRejectedEvent>;\n  'local-changes-dropped': NextFn<LocalChangesDroppedEvent<P>>;\n  'persist-disabled': NextFn<PersistDisabledEvent>;\n  all: NextFn<DocEvents<P>>;\n};\nexport type DocEventTopic = keyof DocEventCallbackMap<never>;\nexport type DocEventCallback<P extends Indexable> =\n  DocEventCallbackMap<P>[DocEventTopic];\n\n/**\n * `Json` represents the JSON data type. It is used to represent the data\n * structure of the document.\n */\nexport type Json = JsonPrimitive | JsonArray | JsonObject;\n\n// eslint-disable-next-line @typescript-eslint/no-restricted-types\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonArray = Array<Json>;\ntype JsonObject = { [key: string]: Json | undefined };\n\n/**\n * `Indexable` represents an object with string keys and Json values. It is\n * used to various places such as the presence or attributes of text elements\n * and etc.\n */\nexport type Indexable = Record<string, Json>;\n\nexport type LeafElement = PrimitiveValue | Primitive | Text | Counter | Tree;\nexport type BaseArray<T> = JSONArray<T> | Array<T>;\nexport type BaseObject<T> = JSONObject<T> | T;\n\n/**\n * `OpInfoOfElement` represents the type of the operation info of the given element.\n */\ntype OpInfoOfElement<TElem> = TElem extends Text\n  ? TextOpInfo\n  : TElem extends Counter\n    ? CounterOpInfo\n    : TElem extends Tree\n      ? TreeOpInfo\n      : TElem extends BaseArray<any>\n        ? ArrayOpInfo\n        : TElem extends BaseObject<any>\n          ? ObjectOpInfo\n          : OpInfo;\n\n/**\n * `OpInfoOfInner` represents the type of the operation info of the\n * given path in the Document.subscribe.\n */\ntype OpInfoOfInner<\n  TElem,\n  TKeyOrPath,\n  TDepth extends number = 0,\n> = TDepth extends 0\n  ? OpInfoOfElement<TElem>\n  : TKeyOrPath extends `${infer TFirst}.${infer TRest}`\n    ? TFirst extends keyof TElem\n      ? OpInfoOfInner<TElem[TFirst], TRest, DecreasedDepthOf<TDepth>>\n      : OpInfo\n    : TKeyOrPath extends keyof TElem\n      ? OpInfoOfElement<TElem[TKeyOrPath]>\n      : OpInfo;\n\n/**\n * `DecreasedDepthOf` represents the type of the decreased depth of the given depth.\n */\ntype DecreasedDepthOf<Depth extends number> = Depth extends 10\n  ? 9\n  : Depth extends 9\n    ? 8\n    : Depth extends 8\n      ? 7\n      : Depth extends 7\n        ? 6\n        : Depth extends 6\n          ? 5\n          : Depth extends 5\n            ? 4\n            : Depth extends 4\n              ? 3\n              : Depth extends 3\n                ? 2\n                : Depth extends 2\n                  ? 1\n                  : Depth extends 1\n                    ? 0\n                    : -1;\n\n/**\n * `PathOfInner` represents the type of the path of the given element.\n */\ntype PathOfInner<\n  TElem,\n  Prefix extends string = '',\n  Depth extends number = 0,\n> = Depth extends 0\n  ? Prefix\n  : TElem extends Record<string, any>\n    ? {\n        [TKey in keyof TElem]: TElem[TKey] extends LeafElement\n          ? `${Prefix}${TKey & string}`\n          : TElem[TKey] extends BaseArray<infer TArrayElement>\n            ?\n                | `${Prefix}${TKey & string}`\n                | `${Prefix}${TKey & string}.${number}`\n                | PathOfInner<\n                    TArrayElement,\n                    `${Prefix}${TKey & string}.${number}.`,\n                    DecreasedDepthOf<Depth>\n                  >\n            :\n                | `${Prefix}${TKey & string}`\n                | PathOfInner<\n                    TElem[TKey],\n                    `${Prefix}${TKey & string}.`,\n                    DecreasedDepthOf<Depth>\n                  >;\n      }[keyof TElem]\n    : Prefix extends `${infer TRest}.`\n      ? TRest\n      : Prefix;\n\n/**\n * `OpInfoOf` represents the type of the operation info of the given\n * path in the Document.subscribe. It is used to remove the `$.` prefix.\n */\ntype OpInfoOf<\n  TRoot,\n  TKey extends string = '',\n  TDepth extends number = 10,\n> = TKey extends `$.${infer TPath}`\n  ? OpInfoOfInner<TRoot, TPath, TDepth>\n  : OpInfoOfInner<TRoot, TKey, TDepth>;\n\n/**\n * `PathOf` represents the type of all possible paths in the Document.subscribe.\n */\ntype PathOf<TRoot, Depth extends number = 10> = PathOfInner<TRoot, '$.', Depth>;\n\n/**\n * `reissueVersionVector` returns a copy of the given vector whose entry for\n * `from` is moved to `to`.\n */\nfunction reissueVersionVector(\n  vector: VersionVector,\n  from: ActorID,\n  to: ActorID,\n): VersionVector {\n  const reissued = vector.deepcopy();\n  const lamport = reissued.get(from);\n  if (lamport === undefined) {\n    return reissued;\n  }\n\n  reissued.unset(from);\n  const existing = reissued.get(to);\n  reissued.set(\n    to,\n    existing !== undefined && existing > lamport ? existing : lamport,\n  );\n  return reissued;\n}\n\n/**\n * `packBlobs` concatenates the given byte blobs into a single, self-contained\n * envelope. Each blob is prefixed with its length as a 4-byte little-endian\n * uint32, so `unpackBlobs` can split them back out without a shared schema.\n * This avoids adding a new message to the generated protobuf api, whose source\n * of truth lives in the yorkie server repo.\n */\nfunction packBlobs(blobs: Array<Uint8Array>): Uint8Array {\n  let total = 0;\n  for (const blob of blobs) {\n    total += 4 + blob.length;\n  }\n\n  const out = new Uint8Array(total);\n  const view = new DataView(out.buffer);\n  let offset = 0;\n  for (const blob of blobs) {\n    view.setUint32(offset, blob.length, true);\n    offset += 4;\n    out.set(blob, offset);\n    offset += blob.length;\n  }\n  return out;\n}\n\n/**\n * `unpackBlobs` is the reverse of `packBlobs`: it splits the given envelope\n * back into the original ordered list of byte blobs.\n */\nfunction unpackBlobs(bytes: Uint8Array): Array<Uint8Array> {\n  const blobs: Array<Uint8Array> = [];\n  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n  let offset = 0;\n  while (offset < bytes.length) {\n    if (offset + 4 > bytes.length) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        'corrupt envelope: truncated length prefix',\n      );\n    }\n    const len = view.getUint32(offset, true);\n    offset += 4;\n    if (offset + len > bytes.length) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        'corrupt envelope: blob length exceeds remaining bytes',\n      );\n    }\n    blobs.push(bytes.subarray(offset, offset + len));\n    offset += len;\n  }\n  return blobs;\n}\n\n/**\n * `replaySourceOf` returns the source a queued local change has to be executed\n * under when it is replayed.\n *\n * A change an undo or a redo produced ran with `OpSource.UndoRedo`, which is\n * the only source `SetOperation.execute`/`RemoveOperation.execute` consult to\n * skip an operation whose target sits under a removed parent. Replaying it as\n * `Local` runs an operation that never ran -- the rebuilt root then differs\n * from the one the user is looking at, and `ElementRHT.delete` can throw out\n * of the replay. Every path that replays the queue (`applySnapshot`,\n * `reissueActor`, `restoreAppendedChanges`) goes through this.\n */\nfunction replaySourceOf<P extends Indexable>(\n  change: Change<P>,\n): OpSource.Local | OpSource.UndoRedo {\n  return change.isUndoRedo() ? OpSource.UndoRedo : OpSource.Local;\n}\n\n/**\n * `Document` is a CRDT-based data type. We can represent the model\n * of the application and edit it even while offline.\n * It implements Attachable interface to be managed by Attachment.\n */\nexport class Document<\n  R,\n  P extends Indexable = Indexable,\n> implements Attachable {\n  private key: string;\n  private status: DocStatus;\n  private opts: DocumentOptions;\n  private maxSizeLimit: number;\n  private schemaRules: Array<Rule>;\n\n  private changeID: ChangeID;\n  private checkpoint: Checkpoint;\n  private localChanges: Array<Change<P>>;\n\n  // `absorbedRemote` records that this document took in state it did not\n  // mint itself: a snapshot, a remote change or a persisted envelope. Such a\n  // document is not \"never synced\" even when its checkpoint, status and\n  // version vector still look untouched (a snapshot pack can carry the\n  // initial checkpoint), so `setActor` with `reissue` leaves it alone.\n  private absorbedRemote: boolean;\n\n  // `mintedOperations` records that this document has produced at least one\n  // local change carrying operations, so tickets naming its actor may already\n  // be in the document the key names. Decoding a persisted envelope\n  // (`fromBytes`, `restoreFromBytes`) sets it too: that state was minted under\n  // an actor in an earlier session. It is never cleared -- a push cannot be\n  // taken back -- and it is what `Client` consults to decide whether the\n  // actor's lamport space in a document key is still free for a re-issue\n  // (`Client.claimReissue`).\n  private mintedOperations: boolean;\n\n  // `epoch` is the document's last-known compaction epoch (proto int64). The\n  // client learns it from every server response pack (`applyChangePack`) and\n  // presents it back on the next attach/sync (`createChangePack`). A resumed\n  // offline client persists it (`toBytes`) so, after a reload, the attach\n  // presents the epoch the document was last synced under; if the document was\n  // force-compacted while offline the server sees a stale epoch and rejects the\n  // resume with `ErrEpochMismatch`, driving the store-backed re-anchor.\n  private epoch: bigint;\n\n  // `presencePatchable` is whether the last pack the server returned\n  // advertised the `presence-patch` capability. Absence means unsupported, so\n  // it starts false and an old server -- which advertises nothing -- keeps it\n  // false. See `canPatchPresence`.\n  private presencePatchable: boolean;\n\n  // `presenceBaseSent` is whether the server has a base to fold a patch into:\n  // a full put has been recorded since the last thing that left it without\n  // one. Attach, a `clear`, and a restore from offline persistence all clear\n  // it; recording a put sets it.\n  private presenceBaseSent: boolean;\n\n  // `presencePatchSent` is whether the last presence change recorded was a\n  // patch. It is what decides whether a reply that has dropped the capability\n  // needs healing: an old server (v0.7.24 or earlier) does not reject a\n  // patch, it stores it with an empty change type and serves it back as\n  // `CHANGE_TYPE_UNSPECIFIED`, which every reader that pulls it fails to\n  // decode (`ErrInvalidType`). A later put does not undo that, so the server\n  // must be upgraded first and must not roll back below v0.7.25.\n  private presencePatchSent: boolean;\n\n  // `docID` is the server-assigned document id (`AttachDocumentResponse.\n  // documentId`) recorded by the client after a successful attach. It is\n  // persisted in the `toBytes` envelope so a restored offline session can\n  // compare it against the id the server returns on re-attach: if they differ\n  // the server GC'd/deleted the document and minted a fresh one, which would\n  // otherwise silently drop the local snapshot + edits (Tier-3 guard). Empty\n  // until the first attach records it (and for legacy envelopes without it).\n  private docID: string;\n\n  private root: CRDTRoot;\n  private presences: Map<ActorID, P>;\n  private clone?: { root: CRDTRoot; presences: Map<ActorID, P> };\n  private internalHistory: History<P>;\n  private isUpdating: boolean;\n  private onlineClients: Set<ActorID>;\n\n  // `mintingSuspended` is set while the change queue has a hole relative to\n  // the acked checkpoint: `discardLocalChanges` has taken the un-pushed\n  // changes out without rewinding `clientSeq`, so the next sequence this\n  // document would mint is past the one the server will validate against.\n  // While it is set, every minting entry point (`update`, undo/redo) refuses\n  // rather than queueing a change that can only be rejected with\n  // `ErrInvalidClientSeq` — or be wiped, unreported, by the re-anchor. It is\n  // lifted by `resetForReanchor` (counter back to zero) or by\n  // `restoreLocalChanges` (hole filled back in), which are the only two ways\n  // out of that state. See {@link Document.discardLocalChanges}.\n  private mintingSuspended = false;\n\n  private eventStream: Observable<DocEvents<P>>;\n  private eventStreamObserver!: Observer<DocEvents<P>>;\n\n  // Persistence follows the pending queue, including changes with no public\n  // event. Keep this signal separate from editor and presence subscriptions.\n  private localChangeStream: Observable<void>;\n  private localChangeObserver!: Observer<void>;\n\n  // `disableGC`, when true, declares that this document does not produce or\n  // consume tombstones (see disable-gc-on-attach in the server repo). It is\n  // set by the client on Attach and consumed by applyChange to skip merging\n  // remote actors' version vectors into changeID, keeping each subsequent\n  // local Change's VV at O(1) for high-fan-out Counter workloads.\n  private disableGC: boolean;\n\n  // `disablePresence`, when true, declares that this document does not use\n  // presence. The client sets it from the local option on construction and\n  // overwrites it from the server-fixated value in the attach response. While\n  // true, `Document.update`'s `presence.set` calls are silently dropped on\n  // the way out (server enforcement is authoritative for the wire side).\n  private disablePresence: boolean;\n\n  // `presenceDropWarned` ensures the silent-drop warning emitted by\n  // `Document.update` for opt-in documents fires only once per document\n  // lifetime. Otherwise long-lived counter-only documents would spam the\n  // console on every well-meaning `presence.set` call.\n  private presenceDropWarned: boolean;\n\n  /**\n   * `history` is exposed to the user to manage undo/redo operations.\n   */\n  public history;\n\n  constructor(key: string, opts?: DocumentOptions) {\n    this.key = key;\n    this.status = DocStatus.Detached;\n    this.opts = opts || {};\n    this.maxSizeLimit = 0;\n    this.schemaRules = [];\n\n    this.changeID = InitialChangeID;\n    this.checkpoint = InitialCheckpoint;\n    this.localChanges = [];\n    this.absorbedRemote = false;\n    this.mintedOperations = false;\n    this.epoch = 0n;\n    this.presencePatchable = false;\n    this.presenceBaseSent = false;\n    this.presencePatchSent = false;\n    this.docID = '';\n    this.disableGC = false;\n    // Seed from the local option so the gate already works before the first\n    // attach response lands (e.g. a unit test that constructs a Document with\n    // `{ disablePresence: true }` and calls `update` immediately).\n    this.disablePresence = !!opts?.disablePresence;\n    this.presenceDropWarned = false;\n\n    this.root = CRDTRoot.create();\n    this.presences = new Map();\n    this.onlineClients = new Set();\n    const maxUndoDepth = opts?.maxUndoDepth ?? MaxUndoRedoStackDepth;\n    if (!Number.isInteger(maxUndoDepth) || maxUndoDepth < 1) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `maxUndoDepth must be a positive integer: ${maxUndoDepth}`,\n      );\n    }\n    this.internalHistory = new History(maxUndoDepth);\n    this.isUpdating = false;\n\n    this.eventStream = createObservable<DocEvents<P>>(\n      (observer) => (this.eventStreamObserver = observer),\n    );\n\n    this.localChangeStream = createObservable<void>(\n      (observer) => (this.localChangeObserver = observer),\n    );\n\n    this.history = {\n      // `canUndo`/`canRedo` answer for the `undo`/`redo` below, so they must\n      // test every reason those refuse — `mintingSuspended` included. The\n      // documented pattern is check-then-call (`if (canUndo()) undo()`, from a\n      // keymap handler in the examples), and a predicate that says yes to a\n      // call that then throws `ErrRefused` turns the re-anchor window into an\n      // exception at an existing call site that never had to handle one.\n      canUndo: () =>\n        this.internalHistory.hasUndo() && !this.isUpdating && this.isMintable(),\n      canRedo: () =>\n        this.internalHistory.hasRedo() && !this.isUpdating && this.isMintable(),\n      undo: () => this.executeUndoRedo(true),\n      redo: () => this.executeUndoRedo(false),\n    };\n\n    setupDevtools(this);\n  }\n\n  /**\n   * `update` executes the given updater to update this document.\n   */\n  public update(\n    updater: (root: JSONObject<R>, presence: Channel<P>) => void,\n    message?: string,\n  ): void {\n    if (this.getStatus() === DocStatus.Removed) {\n      throw new YorkieError(Code.ErrDocumentRemoved, `${this.key} is removed`);\n    }\n    this.ensureMintable('Update');\n\n    // 01. Update the clone object and create a change.\n    this.ensureClone();\n    const actorID = this.changeID.getActorID();\n    const ctx = ChangeContext.create<P>(\n      this.changeID,\n      this.clone!.root,\n      this.clone!.presences.get(actorID) || ({} as P),\n      message,\n    );\n\n    try {\n      const proxy = createJSON<JSONObject<R>>(\n        ctx,\n        this.clone!.root.getObject(),\n      );\n\n      if (!this.presences.has(actorID)) {\n        this.clone!.presences.set(actorID, {} as P);\n      }\n\n      // NOTE(hackerwins): The updater should not be able to call undo/redo.\n      // If the updater calls undo/redo, an error will be thrown.\n      this.isUpdating = true;\n      updater(\n        proxy,\n        new Channel(\n          ctx,\n          this.clone!.presences.get(actorID)!,\n          this.canPatchPresence(),\n        ),\n      );\n    } catch (err) {\n      // NOTE(hackerwins): If the updater fails, we need to remove the cloneRoot and\n      // clonePresences to prevent the user from accessing the invalid state.\n      this.clone = undefined;\n\n      throw err;\n    } finally {\n      this.isUpdating = false;\n    }\n\n    // Silently drop any presence change recorded by the updater when the\n    // document was attached presenceless. The server is authoritative —\n    // it strips presence on PushPull entry and never emits presence on\n    // watch events for these documents — but dropping locally avoids the\n    // wasted enqueue, a redundant LocalChange event with no payload, and\n    // a stale history entry. The warning is emitted at most once per\n    // document instance so high-frequency callers don't spam the console.\n    if (this.disablePresence && ctx.hasPresenceChange()) {\n      ctx.dropPresenceChange();\n      ctx.clearReversePresence();\n      if (!this.presenceDropWarned) {\n        this.presenceDropWarned = true;\n        logger.warn(\n          `[Document] \"${this.key}\" was attached with disablePresence=true; ` +\n            `presence updates from Document.update are silently dropped.`,\n        );\n      }\n    }\n\n    const rules = this.getSchemaRules();\n    if (!ctx.isPresenceOnlyChange() && rules.length) {\n      const result = validateYorkieRuleset(this.clone?.root.getObject(), rules);\n      if (!result.valid) {\n        this.clone = undefined;\n        throw new YorkieError(\n          Code.ErrDocumentSchemaValidationFailed,\n          `schema validation failed: ${result.errors\n            ?.map((error) => error.message)\n            .join(', ')}`,\n        );\n      }\n    }\n\n    const size = totalDocSize(this.clone?.root.getDocSize());\n    if (\n      !ctx.isPresenceOnlyChange() &&\n      this.maxSizeLimit > 0 &&\n      this.maxSizeLimit < size\n    ) {\n      // NOTE(hackerwins): If the updater fails, we need to remove the cloneRoot and\n      // clonePresences to prevent the user from accessing the invalid state.\n      this.clone = undefined;\n      throw new YorkieError(\n        Code.ErrDocumentSizeExceedsLimit,\n        `document size exceeded: ${size} > ${this.maxSizeLimit}`,\n      );\n    }\n\n    // 02. Update the root object and presences from changes.\n    if (ctx.hasChange()) {\n      if (logger.isEnabled(LogLevel.Trivial)) {\n        logger.trivial(`trying to update a local change: ${this.toJSON()}`);\n      }\n\n      const prev = {\n        hadPresence: this.presences.has(actorID),\n        wasOnline: this.status === DocStatus.Attached,\n        presence: this.presences.has(actorID)\n          ? deepcopy(this.presences.get(actorID)!)\n          : undefined,\n      };\n      const change = ctx.toChange();\n      let executed;\n      try {\n        executed = change.execute(this.root, this.presences, OpSource.Local);\n      } catch (err) {\n        // NOTE: `Change.execute` does not roll back, so an operation that\n        // throws here leaves the clone holding the whole change while the\n        // root holds only the prefix that applied, and the change is never\n        // recorded. Drop the clone so the next access rebuilds it from the\n        // root, the same way a failing updater above does.\n        this.clone = undefined;\n\n        // The prefix that landed burned this change's TimeTickets into the\n        // root. `changeID` is not advanced here -- the change was never\n        // queued -- so without this the next `update` builds its context from\n        // the same ID, reissues those exact tickets and takes over the\n        // prefix's slots in `elementPairMapByCreatedAt`, leaving two live\n        // elements under one id. Burn the lamport (and this actor's version\n        // vector entry with it) so no later ticket can collide, and restore\n        // `clientSeq`: the counter names queued changes to the server, and\n        // advancing it for a change nobody queued would leave a hole the\n        // server rejects with `change clientSeq must increase by one`.\n        if (!ctx.isPresenceOnlyChange()) {\n          this.changeID = ctx\n            .getNextID()\n            .setClientSeq(this.changeID.getClientSeq());\n        }\n\n        throw err;\n      }\n      const { operations, opInfos, reverseOps } = executed;\n\n      // NOTE(hackerwins): In update(Set), the element is replaced with a new value.\n      // The history stack may still reference the old element's createdAt,\n      // so we reconcile it to the new createdAt here.\n      for (const op of change.getOperations()) {\n        if (op instanceof ArraySetOperation) {\n          this.internalHistory.reconcileCreatedAt(\n            op.getCreatedAt(),\n            op.getValue().getCreatedAt(),\n          );\n        }\n      }\n\n      // A plain local split can re-create an element a merge took away, too\n      // (a peer merged two blocks and this user splits them again), and the\n      // stacks may still name the merged-away element. Re-point them the way\n      // `applyChangeInternal` does for a peer's split and `executeUndoRedo`\n      // for an undo/redo one, before this change's own reverse is pushed.\n      for (const op of operations) {\n        if (op instanceof TreeEditOperation) {\n          for (const [prevID, currID] of op.getSplitRecreatedIDs()) {\n            this.internalHistory.reconcileTreeNodeID(\n              op.getParentCreatedAt(),\n              prevID,\n              currID,\n            );\n          }\n        }\n      }\n\n      const reversePresence = ctx.getReversePresence();\n      if (reversePresence) {\n        reverseOps.push({\n          type: 'presence',\n          value: reversePresence,\n        });\n      }\n\n      this.localChanges.push(change);\n      this.trackPresenceBase(change);\n      this.mintedOperations ||= operations.length > 0;\n      if (reverseOps.length) {\n        this.internalHistory.pushUndo(reverseOps);\n      }\n      // NOTE(chacha912): Clear redo when a new local operation is applied.\n      if (opInfos.length) {\n        this.internalHistory.clearRedo();\n      }\n      this.changeID = ctx.getNextID();\n      this.localChangeObserver.next();\n\n      // 03. Publish the document change event.\n      // Gated on the operations that RAN, not on the `OpInfo`s they produced,\n      // matching `executeUndoRedoInternal`: an operation can mutate CRDT state\n      // without yielding anything an editor could render (a style on a node a\n      // peer removed concurrently has no index to report), and the change is\n      // still queued into `localChanges` above and still consumes a\n      // `clientSeq`. Preserve the change event even when its OpInfo is empty;\n      // persistence observes the pending queue through a separate signal.\n      const event: DocEvents<P> = [];\n      if (operations.length) {\n        event.push({\n          type: DocEventType.LocalChange,\n          source: OpSource.Local,\n          value: {\n            message: change.getMessage() || '',\n            operations: opInfos,\n            actor: actorID,\n            clientSeq: change.getID().getClientSeq(),\n            serverSeq: change.getID().getServerSeq(),\n          },\n          rawChange: this.isEnableDevtools() ? change.toStruct() : undefined,\n        });\n      }\n      if (change.hasPresenceChange()) {\n        const presenceEvent = this.reconcilePresence(\n          actorID,\n          prev,\n          OpSource.Local,\n        );\n        if (presenceEvent) {\n          event.push(presenceEvent);\n        }\n      }\n\n      this.publish(event);\n\n      if (logger.isEnabled(LogLevel.Trivial)) {\n        logger.trivial(`after update a local change: ${this.toJSON()}`);\n      }\n    }\n  }\n\n  /**\n   * `subscribe` registers a callback to subscribe to events on the document.\n   * The callback will be called when the document is changed.\n   */\n  public subscribe(\n    next: DocEventCallbackMap<P>['default'],\n    error?: ErrorFn,\n    complete?: CompleteFn,\n  ): Unsubscribe;\n  /**\n   * `subscribe` registers a callback to subscribe to events on the document.\n   * The callback will be called when the clients watching the document\n   * establishe or update its presence.\n   */\n  public subscribe(\n    type: 'presence',\n    next: DocEventCallbackMap<P>['presence'],\n    error?: ErrorFn,\n    complete?: CompleteFn,\n  ): Unsubscribe;\n  /**\n   * `subscribe` registers a callback to subscribe to events on the document.\n   * The callback will be called when the current client establishes or updates its presence.\n   */\n  public subscribe(\n    type: 'my-presence',\n    next: DocEventCallbackMap<P>['my-presence'],\n    error?: ErrorFn,\n    complete?: CompleteFn,\n  ): Unsubscribe;\n  /**\n   * `subscribe` registers a callback to subscribe to events on the document.\n   * The callback will be called when the client establishes or terminates a connection,\n   * or updates its presence.\n   */\n  public subscribe(\n    type: 'others',\n    next: DocEventCallbackMap<P>['others'],\n    error?: ErrorFn,\n    complete?: CompleteFn,\n  ): Unsubscribe;\n  /**\n   * `subscribe` registers a callback to subscribe to events on the document.\n   * The callback will be called when the stream connection status changes.\n   */\n  public subscribe(\n    type: 'connection',\n    next: DocEventCallbackMap<P>['connection'],\n    error?: ErrorFn,\n    complete?: CompleteFn,\n  ): Unsubscribe;\n  /**\n   * `subscribe` registers a callback to subscribe to events on the document.\n   * The callback will be called when the document status changes.\n   */\n  public subscribe(\n    type: 'status',\n    next: DocEventCallbackMap<P>['status'],\n    error?: ErrorFn,\n    complete?: CompleteFn,\n  ): Unsubscribe;\n  /**\n   * `subscribe` registers a callback to subscribe to events on the document.\n   * The callback will be called when the document is synced with the server.\n   */\n  public subscribe(\n    type: 'sync',\n    next: DocEventCallbackMap<P>['sync'],\n    error?: ErrorFn,\n    complete?: CompleteFn,\n  ): Unsubscribe;\n  /**\n   * `subscribe` registers a callback to subscribe to events on the document.\n   * The callback will be called when the targetPath or any of its nested values change.\n   */\n  public subscribe<TPath extends PathOf<R>, TOpInfo extends OpInfoOf<R, TPath>>(\n    targetPath: TPath,\n    next: NextFn<LocalChangeEvent<TOpInfo, P> | RemoteChangeEvent<TOpInfo, P>>,\n    error?: ErrorFn,\n    complete?: CompleteFn,\n  ): Unsubscribe;\n  /**\n   * `subscribe` registers a callback to subscribe to events on the document.\n   * The callback will be called when the authentification error occurs.\n   */\n  public subscribe(\n    type: 'auth-error',\n    next: DocEventCallbackMap<P>['auth-error'],\n    error?: ErrorFn,\n  ): Unsubscribe;\n  /**\n   * `subscribe` registers a callback to subscribe to events on the document.\n   * The callback will be called when an epoch mismatch error occurs.\n   */\n  public subscribe(\n    type: 'epoch-mismatch',\n    next: DocEventCallbackMap<P>['epoch-mismatch'],\n    error?: ErrorFn,\n  ): Unsubscribe;\n  /**\n   * `subscribe` registers a callback to subscribe to events on the document.\n   * The callback will be called when the server rejects this document's\n   * pushed changes for a reason that resending them cannot fix.\n   */\n  public subscribe(\n    type: 'write-rejected',\n    next: DocEventCallbackMap<P>['write-rejected'],\n    error?: ErrorFn,\n  ): Unsubscribe;\n  /**\n   * `subscribe` registers a callback to subscribe to events on the document.\n   * The callback will be called when the offline-persistence layer had to\n   * discard un-pushed local changes it could not reconcile (a data-loss event).\n   */\n  public subscribe(\n    type: 'local-changes-dropped',\n    next: DocEventCallbackMap<P>['local-changes-dropped'],\n    error?: ErrorFn,\n  ): Unsubscribe;\n  /**\n   * `subscribe` registers a callback to subscribe to events on the document.\n   * The callback will be called when the offline-persistence layer stopped\n   * persisting this document because writing it exceeds the configured budget.\n   * Editing continues; durability does not.\n   */\n  public subscribe(\n    type: 'persist-disabled',\n    next: DocEventCallbackMap<P>['persist-disabled'],\n    error?: ErrorFn,\n  ): Unsubscribe;\n  /**\n   * `subscribe` registers a callback to subscribe to events on the document.\n   */\n  public subscribe(\n    type: 'all',\n    next: DocEventCallbackMap<P>['all'],\n    error?: ErrorFn,\n    complete?: CompleteFn,\n  ): Unsubscribe;\n  /**\n   * `subscribe` registers a callback to subscribe to events on the document.\n   */\n  public subscribe<TPath extends PathOf<R>, TOpInfo extends OpInfoOf<R, TPath>>(\n    arg1: TPath | DocEventTopic | DocEventCallbackMap<P>['default'],\n    arg2?:\n      | NextFn<LocalChangeEvent<TOpInfo, P> | RemoteChangeEvent<TOpInfo, P>>\n      | DocEventCallback<P>\n      | ErrorFn,\n    arg3?: ErrorFn | CompleteFn,\n    arg4?: CompleteFn,\n  ): Unsubscribe {\n    if (typeof arg1 === 'string') {\n      if (typeof arg2 !== 'function') {\n        throw new YorkieError(\n          Code.ErrInvalidArgument,\n          'Second argument must be a callback function',\n        );\n      }\n      if (arg1 === 'presence') {\n        const callback = arg2 as DocEventCallbackMap<P>['presence'];\n        return this.eventStream.subscribe(\n          (event) => {\n            for (const docEvent of event) {\n              if (\n                docEvent.type !== DocEventType.Initialized &&\n                docEvent.type !== DocEventType.Watched &&\n                docEvent.type !== DocEventType.Unwatched &&\n                docEvent.type !== DocEventType.PresenceChanged\n              ) {\n                continue;\n              }\n\n              callback(docEvent);\n            }\n          },\n          arg3,\n          arg4,\n        );\n      }\n      if (arg1 === 'my-presence') {\n        const callback = arg2 as DocEventCallbackMap<P>['my-presence'];\n        return this.eventStream.subscribe(\n          (event) => {\n            for (const docEvent of event) {\n              if (\n                docEvent.type !== DocEventType.Initialized &&\n                docEvent.type !== DocEventType.PresenceChanged\n              ) {\n                continue;\n              }\n\n              if (\n                docEvent.type === DocEventType.PresenceChanged &&\n                docEvent.value.clientID !== this.changeID.getActorID()\n              ) {\n                continue;\n              }\n\n              callback(docEvent);\n            }\n          },\n          arg3,\n          arg4,\n        );\n      }\n      if (arg1 === 'others') {\n        const callback = arg2 as DocEventCallbackMap<P>['others'];\n        return this.eventStream.subscribe(\n          (event) => {\n            for (const docEvent of event) {\n              if (\n                docEvent.type !== DocEventType.Watched &&\n                docEvent.type !== DocEventType.Unwatched &&\n                docEvent.type !== DocEventType.PresenceChanged\n              ) {\n                continue;\n              }\n\n              if (docEvent.value.clientID !== this.changeID.getActorID()) {\n                callback(docEvent);\n              }\n            }\n          },\n          arg3,\n          arg4,\n        );\n      }\n      if (arg1 === 'connection') {\n        const callback = arg2 as DocEventCallbackMap<P>['connection'];\n        return this.eventStream.subscribe(\n          (event) => {\n            for (const docEvent of event) {\n              if (docEvent.type !== DocEventType.ConnectionChanged) {\n                continue;\n              }\n              callback(docEvent);\n            }\n          },\n          arg3,\n          arg4,\n        );\n      }\n      if (arg1 === 'status') {\n        const callback = arg2 as DocEventCallbackMap<P>['status'];\n        return this.eventStream.subscribe(\n          (event) => {\n            for (const docEvent of event) {\n              if (docEvent.type !== DocEventType.StatusChanged) {\n                continue;\n              }\n              callback(docEvent);\n            }\n          },\n          arg3,\n          arg4,\n        );\n      }\n      if (arg1 === 'sync') {\n        const callback = arg2 as DocEventCallbackMap<P>['sync'];\n        return this.eventStream.subscribe(\n          (event) => {\n            for (const docEvent of event) {\n              if (docEvent.type !== DocEventType.SyncStatusChanged) {\n                continue;\n              }\n              callback(docEvent);\n            }\n          },\n          arg3,\n          arg4,\n        );\n      }\n      if (arg1 === 'auth-error') {\n        const callback = arg2 as DocEventCallbackMap<P>['auth-error'];\n        return this.eventStream.subscribe((event) => {\n          for (const docEvent of event) {\n            if (docEvent.type !== DocEventType.AuthError) {\n              continue;\n            }\n\n            callback(docEvent);\n          }\n        }, arg3);\n      }\n      if (arg1 === 'epoch-mismatch') {\n        const callback = arg2 as DocEventCallbackMap<P>['epoch-mismatch'];\n        return this.eventStream.subscribe((event) => {\n          for (const docEvent of event) {\n            if (docEvent.type !== DocEventType.EpochMismatch) {\n              continue;\n            }\n\n            callback(docEvent);\n          }\n        }, arg3);\n      }\n      if (arg1 === 'write-rejected') {\n        const callback = arg2 as DocEventCallbackMap<P>['write-rejected'];\n        return this.eventStream.subscribe((event) => {\n          for (const docEvent of event) {\n            if (docEvent.type !== DocEventType.WriteRejected) {\n              continue;\n            }\n\n            callback(docEvent);\n          }\n        }, arg3);\n      }\n      if (arg1 === 'persist-disabled') {\n        const callback = arg2 as DocEventCallbackMap<P>['persist-disabled'];\n        return this.eventStream.subscribe((event) => {\n          for (const docEvent of event) {\n            if (docEvent.type !== DocEventType.PersistDisabled) {\n              continue;\n            }\n\n            callback(docEvent);\n          }\n        }, arg3);\n      }\n      if (arg1 === 'local-changes-dropped') {\n        const callback =\n          arg2 as DocEventCallbackMap<P>['local-changes-dropped'];\n        return this.eventStream.subscribe((event) => {\n          for (const docEvent of event) {\n            if (docEvent.type !== DocEventType.LocalChangesDropped) {\n              continue;\n            }\n\n            callback(docEvent);\n          }\n        }, arg3);\n      }\n      if (arg1 === 'all') {\n        const callback = arg2 as DocEventCallbackMap<P>['all'];\n        return this.eventStream.subscribe(callback, arg3, arg4);\n      }\n      const target = arg1;\n      const callback = arg2 as NextFn<\n        LocalChangeEvent<TOpInfo, P> | RemoteChangeEvent<TOpInfo, P>\n      >;\n      return this.eventStream.subscribe(\n        (event) => {\n          for (const docEvent of event) {\n            if (\n              docEvent.type !== DocEventType.LocalChange &&\n              docEvent.type !== DocEventType.RemoteChange\n            ) {\n              continue;\n            }\n\n            const targetOps: Array<TOpInfo> = [];\n            for (const op of docEvent.value.operations) {\n              if (this.isSameElementOrChildOf(op.path, target)) {\n                targetOps.push(op as TOpInfo);\n              }\n            }\n\n            if (targetOps.length) {\n              callback({\n                ...docEvent,\n                value: { ...docEvent.value, operations: targetOps },\n              });\n            }\n          }\n        },\n        arg3,\n        arg4,\n      );\n    }\n    if (typeof arg1 === 'function') {\n      const callback = arg1 as DocEventCallbackMap<P>['default'];\n      const error = arg2 as ErrorFn;\n      const complete = arg3 as CompleteFn;\n      return this.eventStream.subscribe(\n        (event) => {\n          for (const docEvent of event) {\n            if (\n              docEvent.type !== DocEventType.Snapshot &&\n              docEvent.type !== DocEventType.LocalChange &&\n              docEvent.type !== DocEventType.RemoteChange\n            ) {\n              continue;\n            }\n\n            callback(docEvent);\n          }\n        },\n        error,\n        complete,\n      );\n    }\n\n    throw new YorkieError(Code.ErrInvalidArgument, `\"${arg1}\" is not a valid`);\n  }\n\n  /**\n   * `publish` triggers an event in this document, which can be received by\n   * callback functions from document.subscribe().\n   */\n  public publish(events: DocEvents<P>) {\n    if (this.eventStreamObserver) {\n      this.eventStreamObserver.next(events);\n    }\n  }\n\n  /**\n   * `applyChangePack` applies the given change pack into this document.\n   * 1. Remove local changes applied to server.\n   * 2. Update the checkpoint.\n   * 3. Do Garbage collection.\n   */\n  public applyChangePack(pack: ChangePack<P>): void {\n    // 01. Apply snapshot or changes to the root object.\n    //\n    // NOTE: the checkpoint below is only reached once everything applied, so\n    // a throw here leaves it where it was and the server redelivers this same\n    // pack on every sync. Report that once, naming the checkpoint the\n    // document is stuck at, before letting the error out: otherwise the only\n    // field signal is a sync that never makes progress.\n    //\n    // This line runs at the default log level and repeats on every\n    // redelivery, so everything it interpolates has to be metadata: the key,\n    // the checkpoint, and an error that names the change and the operation by\n    // type and ticket only. No operation payload — i.e. no document content —\n    // may be carried into it.\n    try {\n      if (pack.hasSnapshot()) {\n        this.applySnapshot(\n          pack.getCheckpoint().getServerSeq(),\n          pack.getVersionVector()!,\n          pack.getSnapshot()!,\n          pack.getCheckpoint().getClientSeq(),\n        );\n      } else {\n        this.applyChanges(pack.getChanges(), OpSource.Remote);\n        this.removePushedLocalChanges(pack.getCheckpoint().getClientSeq());\n      }\n    } catch (err) {\n      logger.error(\n        `[Document] \"${this.key}\" cannot apply the pack at checkpoint ` +\n          `${this.checkpoint.toTestString()}; the server will redeliver it ` +\n          `until this is resolved: ${err}`,\n      );\n      throw err;\n    }\n\n    // 02. Update the checkpoint.\n    this.checkpoint = this.checkpoint.forward(pack.getCheckpoint());\n\n    // 02-1. Learn the document's current compaction epoch from the server so a\n    // subsequent attach/sync (and any persisted envelope) presents it back.\n    this.epoch = pack.getEpoch();\n\n    // 02-2. Learn whether this server takes presence patches, and remember\n    // whether that leaves a presence to heal.\n    const needsHeal = this.learnPresenceCapability(pack);\n\n    // 03. Do Garbage collection.\n    if (!pack.hasSnapshot()) {\n      this.garbageCollect(pack.getVersionVector()!);\n    }\n\n    // 04. Update the status.\n    if (pack.getIsRemoved()) {\n      this.applyStatus(DocStatus.Removed);\n    }\n\n    if (logger.isEnabled(LogLevel.Trivial)) {\n      logger.trivial(`${this.root.toJSON()}`);\n    }\n\n    // 05. Heal a presence the server may have stored as empty. Deferred to\n    // here so the put is minted against the state this pack left behind.\n    if (needsHeal) {\n      this.healPresenceBase();\n    }\n  }\n\n  /**\n   * `getCheckpoint` returns the checkpoint of this document.\n   */\n  public getCheckpoint(): Checkpoint {\n    return this.checkpoint;\n  }\n\n  /**\n   * `getEpoch` returns the document's last-known compaction epoch.\n   */\n  public getEpoch(): bigint {\n    return this.epoch;\n  }\n\n  /**\n   * `canPatchPresence` returns whether the next presence update may be\n   * recorded as a patch rather than a full put. Both halves are required: the\n   * server has to have advertised `presence-patch` on the pack it last\n   * returned, and it has to be holding a base of ours to fold the patch into.\n   */\n  private canPatchPresence(): boolean {\n    return this.presencePatchable && this.presenceBaseSent;\n  }\n\n  /**\n   * `learnPresenceCapability` takes the `presence-patch` capability from a\n   * pack the server returned and reports whether the presence now has to be\n   * healed with a full put.\n   *\n   * Absence means unsupported, so a reply from an old server during a rolling\n   * upgrade turns patching off. An old server (v0.7.24 or earlier) does not\n   * reject a patch -- it stores it with an empty change type and serves it\n   * back as `CHANGE_TYPE_UNSPECIFIED`, which every reader that pulls it fails\n   * to decode with `ErrInvalidType`, stopping its sync loop. The heal only\n   * stops further patches and re-sends a base; it cannot repair a patch\n   * already stored, so the server must be upgraded first and must not roll\n   * back below v0.7.25 once clients of this SDK connect.\n   *\n   * The test is only whether a patch is outstanding, not whether patching was\n   * on a moment ago: a patch restored from offline persistence was minted in\n   * an earlier session, so there is no \"was patchable\" to compare against and\n   * the heal would be skipped exactly when it is needed.\n   *\n   * It does not heal itself: the caller decides when the put is minted, so it\n   * lands against the state the pack left behind rather than mid-application.\n   */\n  private learnPresenceCapability(pack: ChangePack<P>): boolean {\n    this.presencePatchable = pack.hasCapability(PresencePatchCapability);\n    return !this.presencePatchable && this.presencePatchSent;\n  }\n\n  /**\n   * `healPresenceBase` re-sends the whole presence as a put, after a patch\n   * that a server without the capability may have stored, so no further\n   * patch follows on top of a base that server never held.\n   *\n   * Minting it is a side effect of applying a pack rather than something the\n   * caller asked for, so it defers to `isMintable` instead of throwing\n   * `ErrRefused` out of an unrelated API: inside the re-anchor window\n   * `discardLocalChanges` opens, and on a removed document, the heal is\n   * dropped. Nothing is lost by that -- a re-anchor re-sends the presence as\n   * a put of its own, and a removed document has no peers left to tell.\n   */\n  private healPresenceBase(): void {\n    if (this.status === DocStatus.Removed || !this.isMintable()) {\n      return;\n    }\n\n    // `set` merges onto the presence the update already holds, so the change\n    // it records is a put of the whole presence either way. Naming the keys\n    // keeps that explicit rather than resting on an empty merge.\n    const actorID = this.changeID.getActorID();\n    const presence = deepcopy(this.presences.get(actorID) ?? ({} as P));\n    this.update((_, p) => p.set(presence));\n  }\n\n  /**\n   * `trackPresenceBase` records what the given local change did to the base\n   * the server holds for us, so the next update knows whether it may patch.\n   */\n  private trackPresenceBase(change: Change<P>): void {\n    const presenceChange = change.getPresenceChange();\n    if (!presenceChange) {\n      return;\n    }\n\n    if (presenceChange.type === PresenceChangeType.Put) {\n      this.presenceBaseSent = true;\n      this.presencePatchSent = false;\n    } else if (presenceChange.type === PresenceChangeType.Patch) {\n      this.presencePatchSent = true;\n    } else {\n      // A `clear` leaves the server with no base: the server treats a patch\n      // after one as baseless, so the next presence change has to be a put.\n      this.presenceBaseSent = false;\n      this.presencePatchSent = false;\n    }\n  }\n\n  /**\n   * `resetPresenceBase` drops the assumption that the server holds a base for\n   * us, so the next presence update is a full put. A reconnect -- including\n   * restoring a document from offline persistence -- has to do this: the\n   * server that answers next may never have seen our presence.\n   */\n  public resetPresenceBase(): void {\n    this.presenceBaseSent = false;\n  }\n\n  /**\n   * `resetPresenceStateForRestore` returns the presence-patch state to what a\n   * document rehydrated from offline persistence may assume. Every path that\n   * rebuilds the queue from persisted structs goes through it, so an in-place\n   * restore is left in the same state as the static `fromBytes`.\n   *\n   * The capability is unknown again -- it is learned from a returned pack, and\n   * none has landed in this session -- and the base is gone with it. The\n   * restored queue is still pushed as persisted, though: a patch in it reaches\n   * the server verbatim, so it counts as a patch outstanding, which is what\n   * decides whether a server without the capability leaves a presence to heal.\n   */\n  private resetPresenceStateForRestore(): void {\n    this.presencePatchable = false;\n    this.presenceBaseSent = false;\n    this.presencePatchSent = this.hasPendingPresencePatch();\n  }\n\n  /**\n   * `hasPendingPresencePatch` reports whether a presence patch is still queued\n   * to be pushed. That is what makes a patch \"outstanding\": it reaches the\n   * server verbatim, so a server without the capability would store it as an\n   * unspecified change and leave a presence to heal.\n   */\n  private hasPendingPresencePatch(): boolean {\n    return this.localChanges.some(\n      (change) => change.getPresenceChange()?.type === PresenceChangeType.Patch,\n    );\n  }\n\n  /**\n   * `restorePresencePatches` rewrites the earliest pending presence patch into\n   * a full put of the presence as of that change, leaving the later patches\n   * alone: the server folds them in order, so a put in front of them is the\n   * base they need. It answers `ErrPresenceBaseUnavailable`, where nothing in\n   * the rejected pack was stored and the whole pack is resent.\n   */\n  public restorePresencePatches(): void {\n    // The base is gone whether or not this pack carried a patch, so the next\n    // update has to send a put as well. The rewrite below supplies it for the\n    // pack already queued.\n    this.resetPresenceBase();\n\n    for (const change of this.localChanges) {\n      const presenceChange = change.getPresenceChange();\n      // `full` is what the patch is rewritten into, and only a locally minted\n      // patch has one -- a queued change is always local, so a patch without\n      // it cannot be rewritten and is left for the server to fold.\n      if (presenceChange?.type === PresenceChangeType.Patch) {\n        if (!presenceChange.full) {\n          continue;\n        }\n\n        change.setPresenceChange({\n          type: PresenceChangeType.Put,\n          presence: presenceChange.full,\n        });\n        this.presenceBaseSent = true;\n        break;\n      }\n    }\n\n    // The rewrite deliberately leaves the later patches alone, so the queue\n    // usually still holds one. A patch is outstanding whenever it does, and\n    // clearing the flag regardless would tell `learnPresenceCapability` there\n    // is nothing to heal -- exactly when a server without the capability is\n    // about to store those patches as unspecified changes.\n    this.presencePatchSent = this.hasPendingPresencePatch();\n  }\n\n  /**\n   * `isPresencePatchableForTest` returns whether the next presence update\n   * would be recorded as a patch.\n   */\n  public isPresencePatchableForTest(): boolean {\n    return this.canPatchPresence();\n  }\n\n  /**\n   * `getDocID` returns the server-assigned document id recorded on attach, or\n   * an empty string before the first attach (or for a legacy envelope that\n   * predates docID persistence).\n   */\n  public getDocID(): string {\n    return this.docID;\n  }\n\n  /**\n   * `setDocID` records the server-assigned document id so the next persisted\n   * envelope carries it for the Tier-3 silent-purge guard.\n   */\n  public setDocID(docID: string): void {\n    this.docID = docID;\n  }\n\n  /**\n   * `getChangeID` returns the change id of this document.\n   */\n  public getChangeID(): ChangeID {\n    return this.changeID;\n  }\n\n  /**\n   * `hasLocalChanges` returns whether this document has local changes or not.\n   */\n  public hasLocalChanges(): boolean {\n    return this.localChanges.length > 0;\n  }\n\n  /**\n   * `toBytes` serializes the full restorable state of this document into a\n   * self-contained byte envelope: the root and presences (as a snapshot), the\n   * checkpoint, the changeID (lamport, version vector, actor), and the pending\n   * local changes. `fromBytes` reverses it, so a document survives a reload\n   * with its un-pushed edits intact. The envelope is a length-prefixed\n   * concatenation of existing byte encodings rather than a new protobuf message.\n   */\n  public toBytes(): Uint8Array {\n    const encoder = new TextEncoder();\n\n    const snapshot = converter.snapshotToBytes(\n      this.getRootObject(),\n      this.presences,\n    );\n    const checkpoint = encoder.encode(\n      JSON.stringify({\n        serverSeq: this.checkpoint.getServerSeq().toString(),\n        clientSeq: this.checkpoint.getClientSeq(),\n      }),\n    );\n    const changeID = converter.changeIDToBinary(this.changeID);\n    const pendingChanges = encoder.encode(\n      JSON.stringify(this.localChanges.map((change) => change.toStruct())),\n    );\n    // The epoch is appended after the pending changes so an older envelope\n    // (four blobs) still decodes: `fromBytes` treats a missing epoch blob as 0n.\n    const epoch = encoder.encode(this.epoch.toString());\n    // The docID is the last blob, appended after epoch, so an envelope written\n    // before docID support (five blobs) still decodes: `fromBytes` treats a\n    // missing docID blob as an empty string.\n    const docID = encoder.encode(this.docID);\n\n    return packBlobs([\n      snapshot,\n      checkpoint,\n      changeID,\n      pendingChanges,\n      epoch,\n      docID,\n    ]);\n  }\n\n  /**\n   * `fromBytes` reconstructs a document from the bytes produced by `toBytes`,\n   * restoring the root, presences, checkpoint, changeID, and pending local\n   * changes.\n   */\n  public static fromBytes<R, P extends Indexable = Indexable>(\n    key: string,\n    bytes: Uint8Array,\n    opts?: DocumentOptions,\n  ): Document<R, P> {\n    const decoder = new TextDecoder();\n    // Envelope invariant: trailing blobs are OPTIONAL for back-compat. A legacy\n    // envelope written before a later field was added carries fewer blobs (e.g.\n    // four blobs pre-epoch, five pre-docID), and each such blob is nil-guarded\n    // below to a sensible default. This tolerate-fewer decode is intentional, so\n    // no strict blob-count check is imposed. Any future field MUST be appended\n    // as a new trailing blob and remain optional/nil-guarded here to keep older\n    // envelopes decodable.\n    const [\n      snapshot,\n      checkpointBytes,\n      changeIDBytes,\n      pendingChangesBytes,\n      epochBytes,\n      docIDBytes,\n    ] = unpackBlobs(bytes);\n\n    const doc = new Document<R, P>(key, opts);\n\n    const { root, presences } = converter.bytesToSnapshot<P>(snapshot);\n    doc.root = new CRDTRoot(root);\n    doc.presences = presences;\n\n    const checkpoint = JSON.parse(decoder.decode(checkpointBytes)) as {\n      serverSeq: string;\n      clientSeq: number;\n    };\n    doc.checkpoint = Checkpoint.of(\n      BigInt(checkpoint.serverSeq),\n      checkpoint.clientSeq,\n    );\n\n    doc.changeID = converter.bytesToChangeID(changeIDBytes);\n\n    const structs = JSON.parse(decoder.decode(pendingChangesBytes)) as Array<\n      ChangeStruct<P>\n    >;\n    doc.localChanges = structs.map((struct) => Change.fromStruct<P>(struct));\n    doc.resetPresenceStateForRestore();\n\n    // The epoch blob is optional: envelopes written before epoch support have\n    // only four blobs, so treat an absent blob as the initial epoch 0n.\n    doc.epoch = epochBytes ? BigInt(decoder.decode(epochBytes)) : 0n;\n\n    // The docID blob is optional: envelopes written before docID support have\n    // only five blobs, so treat an absent blob as an empty string.\n    doc.docID = docIDBytes ? decoder.decode(docIDBytes) : '';\n    doc.absorbedRemote = true;\n    // A persisted envelope is state an actor already held under this key: its\n    // root carries tickets that actor minted, and its pending changes are\n    // about to be pushed under it. Mark the decoded document as having minted,\n    // so an app that restores through this public factory and attaches the\n    // result takes the re-issue claim (`Client.markReissueClaim`) exactly as\n    // the in-place `restoreFromBytes` path does -- otherwise a later document\n    // of the same key would re-issue onto lamports this one has consumed.\n    doc.mintedOperations = true;\n\n    return doc;\n  }\n\n  /**\n   * `restoreFromBytes` rehydrates this document in place from the bytes\n   * produced by `toBytes`, overwriting the root, presences, checkpoint,\n   * changeID, and pending local changes. Unlike the static `fromBytes`, it\n   * mutates the existing instance so a document the caller already holds (and\n   * is about to attach) recovers its persisted, un-pushed state.\n   *\n   * Ordering: the caller must have stamped the actor (`setActor`) before\n   * calling this. The rehydrated changes and changeID carry the actor they\n   * were persisted under, and the snapshot's element actors are restored as\n   * persisted, so this does not rely on `setActor` rewriting existing element\n   * actors (a documented limitation of `setActor`).\n   *\n   * Actor guard: the persisted changeID must carry the same actor the caller\n   * just stamped. If a store is reused under a different clientKey the current\n   * stable actor differs from the persisted one; restoring anyway would stamp\n   * subsequent edits with the current actor while the restored root/changes\n   * keep the persisted actor, silently diverging the CRDT against a server that\n   * keys on the current actor. On mismatch this throws `ErrClientNotActivated`-\n   * free `ErrInvalidArgument` so the store-backed attach path can surface a\n   * data-loss event and re-anchor instead of corrupting state.\n   */\n  public restoreFromBytes(bytes: Uint8Array): void {\n    const currentActor = this.changeID.getActorID();\n    const restored = Document.fromBytes<R, P>(this.key, bytes, this.opts);\n    const restoredActor = restored.changeID.getActorID();\n    if (currentActor && restoredActor && currentActor !== restoredActor) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `persisted actor \"${restoredActor}\" does not match the current ` +\n          `stable actor \"${currentActor}\"; the store was reused under a ` +\n          `different client identity, restoring would diverge the CRDT`,\n      );\n    }\n    this.root = restored.root;\n    this.presences = restored.presences;\n    this.checkpoint = restored.checkpoint;\n    this.changeID = restored.changeID;\n    this.localChanges = restored.localChanges;\n    this.epoch = restored.epoch;\n    this.docID = restored.docID;\n    // The presence-patch state goes with the queue: `fromBytes` already put\n    // the decoded document in the state a restore owes (no capability, no\n    // base, a patch outstanding if the queue holds one), and the fields are\n    // copied one by one here, so it has to be carried across explicitly.\n    this.presencePatchable = restored.presencePatchable;\n    this.presenceBaseSent = restored.presenceBaseSent;\n    this.presencePatchSent = restored.presencePatchSent;\n    this.absorbedRemote = true;\n    // A persisted envelope is state this actor already held under this key,\n    // so treat it as minted: the claim bookkeeping must not hand the actor's\n    // lamport space to a later re-issue. The decoded `restored` carries the\n    // same flag; it is set here too because the fields are copied one by one.\n    this.mintedOperations = true;\n    // Drop any stale clone so the next `update` re-clones from the restored\n    // root/presences rather than the pre-restore state.\n    this.clone = undefined;\n    // Clear the undo/redo history: its reverse-ops reference the pre-restore\n    // root/changeID that was just replaced, so a later undo/redo would apply\n    // stale ticket references against the rehydrated state and corrupt it.\n    this.clearHistory();\n  }\n\n  /**\n   * `advanceClientSeqTo` moves this document's `clientSeq` counter forward to\n   * the given sequence, and never backward.\n   *\n   * It exists for the one caller that has to undo a persisted header without\n   * undoing the counter inside it. `restoreFromBytes` returns checkpoint,\n   * epoch and `changeID` to what the snapshot carries, which is right for a\n   * header the appended log cannot back — except for the counter. A counter is\n   * not a claim about content the way a checkpoint is: it records which\n   * `clientSeq` values this client has already MINTED, and the server has\n   * taken some of them. Rewinding it to the snapshot's counter mints those\n   * sequences a second time; the server skips them as duplicates and the next\n   * ack, whose `clientSeq` covers them, drops them from `localChanges` as\n   * pushed. The edits are lost with no event.\n   *\n   * The position to hand over is the acked checkpoint, not the header's\n   * counter. The server validates continuity from the position it holds, so\n   * the next change must be its `clientSeq` plus one; the counter can lead\n   * that, and resuming there would mint past the server and wedge every later\n   * push on `ErrInvalidClientSeq`.\n   *\n   * The counter only ever rises, so the guard is the whole contract: a caller\n   * that hands over a stale position cannot pull the document back into\n   * reusing sequence numbers.\n   */\n  public advanceClientSeqTo(clientSeq: number): void {\n    if (clientSeq > this.changeID.getClientSeq()) {\n      this.changeID = this.changeID.setClientSeq(clientSeq);\n    }\n  }\n\n  /**\n   * `getPendingChangeStructs` returns the serialized structs of the current\n   * un-pushed local changes. Used by the offline-persistence layer to carry the\n   * dropped changes in a `LocalChangesDropped` data-loss event so the app can\n   * surface (and optionally re-apply) edits that could not be reconciled.\n   */\n  public getPendingChangeStructs(): Array<ChangeStruct<P>> {\n    return this.localChanges.map((change) => change.toStruct());\n  }\n\n  /**\n   * `discardLocalChanges` takes the un-pushed local changes out of the queue\n   * and returns them. Used by `Client.resync` when the server has refused this\n   * client's writes: the queued changes would be re-sent and re-denied by every\n   * later sync, so the only way forward is to stop presenting them.\n   *\n   * The `clientSeq` counter is deliberately left where it is. The discarded\n   * changes already minted those sequences, and rewinding would mint them a\n   * second time — the hazard {@link Document.advanceClientSeqTo} exists to rule\n   * out: the server skips a `clientSeq` it has already taken as a duplicate,\n   * and the offline-persistence watermarks assume the counter only rises. The\n   * cost of not rewinding is that the queue now has a hole relative to the\n   * acked checkpoint, so **no change may be minted before the document is\n   * re-anchored**. That is not left to the caller to remember: the discard\n   * suspends minting outright, so `update` and undo/redo refuse with\n   * `ErrRefused` until the hole is closed. `Client.resync` spans several\n   * awaits — a detach that enqueues a task and does an RPC, then a re-attach —\n   * and the app keeps hold of the `Document` throughout, so without the\n   * suspension a single edit in that window either wedges the detach with\n   * `ErrInvalidClientSeq` or is wiped by `resetForReanchor` without ever\n   * appearing in the data-loss event. A loud refusal the app can catch is the\n   * one outcome that loses nothing. `resync` also detaches without the usual\n   * presence clear, so the recovery itself mints nothing.\n   *\n   * Only that window is closed. An edit landing *before* the discard is taken\n   * by it and reported in the data-loss event, and one landing after the\n   * re-anchor is ordinary pre-attach editing; neither is at risk.\n   *\n   * This does **not** undo the discarded changes on `root`: they are already\n   * applied and there is no server-confirmed copy to fall back on. The caller\n   * is expected to follow with `resetForReanchor` and a fresh attach, which\n   * replaces the local state with the server's — or, if that fails, to hand the\n   * changes back with {@link Document.restoreLocalChanges}. Both lift the\n   * suspension; they are the only two ways out of it.\n   */\n  public discardLocalChanges(): Array<Change<P>> {\n    const discarded = this.localChanges;\n    this.localChanges = [];\n    // An empty discard leaves no hole, so it must not suspend minting: there\n    // would be nothing to hand back, and `restoreLocalChanges([])` is a no-op.\n    if (discarded.length) {\n      this.mintingSuspended = true;\n    }\n    return discarded;\n  }\n\n  /**\n   * `isMintable` returns whether this document may queue a new local change.\n   * It is `false` only inside the re-anchor window `discardLocalChanges`\n   * opens, where `update` and undo/redo refuse with `ErrRefused`.\n   *\n   * It is public so that a caller which mints a change as a *side effect* of\n   * something else can ask instead of throwing out of an unrelated API:\n   * `Client.detach` mints a presence clear, and an unmount cleanup calling it\n   * has nowhere to put that exception. `history.canUndo`/`canRedo` read it for\n   * the same reason.\n   */\n  public isMintable(): boolean {\n    return !this.mintingSuspended;\n  }\n\n  /**\n   * `ensureMintable` refuses a caller that would queue a local change while\n   * the queue has the `clientSeq` hole `discardLocalChanges` left behind.\n   */\n  private ensureMintable(action: string): void {\n    if (this.mintingSuspended) {\n      throw new YorkieError(\n        Code.ErrRefused,\n        `${action} is not allowed on \"${this.key}\" while it is being ` +\n          `re-anchored after the server refused its changes`,\n      );\n    }\n  }\n\n  /**\n   * `restoreLocalChanges` puts changes taken by `discardLocalChanges` back at\n   * the head of the queue, undoing the discard. It is the rollback for a\n   * recovery that could not go through: `Client.resync` restores the queue when\n   * the detach it needs is itself refused, so a failed recovery leaves the\n   * document exactly as it found it rather than with its edits destroyed.\n   *\n   * The restored changes are older than anything queued since, so they go in\n   * front; `clientSeq` is untouched because the discard never moved it.\n   *\n   * Putting them back closes the hole, so minting is allowed again — the\n   * document is left exactly as the discard found it, writable included.\n   */\n  public restoreLocalChanges(changes: Array<Change<P>>): void {\n    this.mintingSuspended = false;\n    if (!changes.length) {\n      return;\n    }\n    this.localChanges = [...changes, ...this.localChanges];\n  }\n\n  /**\n   * `subscribeLocalChangesInternal` observes newly queued local changes after\n   * the document state and changeID have been committed. It runs before public\n   * events so a subscriber-triggered sync cannot remove changes before the\n   * persistence layer captures them. Public events can be empty or suppressed.\n   *\n   * @internal\n   */\n  public subscribeLocalChangesInternal(callback: () => void): Unsubscribe {\n    return this.localChangeStream.subscribe(callback);\n  }\n\n  /**\n   * `getPendingChangesAfter` returns the un-pushed local changes whose\n   * `clientSeq` is above the given one, each paired with that sequence.\n   *\n   * The pairing is the point: a `ChangeStruct` carries its `clientSeq` encoded\n   * inside the hex `changeID`, so a caller working from structs alone cannot\n   * tell which changes it has already seen without decoding them. The\n   * offline-persistence layer needs exactly that to append only what is new.\n   */\n  public getPendingChangesAfter(\n    clientSeq: number,\n  ): Array<{ clientSeq: number; struct: ChangeStruct<P> }> {\n    const out: Array<{ clientSeq: number; struct: ChangeStruct<P> }> = [];\n    for (const change of this.localChanges) {\n      const seq = change.getID().getClientSeq();\n      if (seq > clientSeq) {\n        out.push({ clientSeq: seq, struct: change.toStruct() });\n      }\n    }\n    return out;\n  }\n\n  /**\n   * `metaToBytes` serializes just the checkpoint and changeID — the client's\n   * position against the server — without touching the root.\n   *\n   * This is what the offline-persistence layer writes after a sync. A sync\n   * advances the checkpoint while leaving the document unchanged, so\n   * re-serializing the whole document to record it would cost time\n   * proportional to the document for information that is a few dozen bytes.\n   * Without it a restore would resume from whatever checkpoint the last\n   * snapshot happened to carry.\n   */\n  public metaToBytes(): Uint8Array {\n    const encoder = new TextEncoder();\n    const checkpoint = encoder.encode(\n      JSON.stringify({\n        serverSeq: this.checkpoint.getServerSeq().toString(),\n        clientSeq: this.checkpoint.getClientSeq(),\n      }),\n    );\n    const changeID = converter.changeIDToBinary(this.changeID);\n    // The epoch and docID are learned from sync responses, so meta is the only\n    // place they can be recorded between snapshots. Omitting the epoch made a\n    // server-side force-compaction invisible until the next attach presented a\n    // stale one, took `ErrEpochMismatch`, and re-anchored — discarding every\n    // un-pushed edit for want of a field.\n    const encoderEpoch = encoder.encode(this.epoch.toString());\n    const docID = encoder.encode(this.docID);\n    return packBlobs([checkpoint, changeID, encoderEpoch, docID]);\n  }\n\n  /**\n   * `restoreMetaFromBytes` applies the bytes produced by `metaToBytes`,\n   * overwriting the checkpoint and changeID. Trailing blobs stay optional, the\n   * same extension rule the `toBytes` envelope follows.\n   */\n  public restoreMetaFromBytes(bytes: Uint8Array): void {\n    const decoder = new TextDecoder();\n    const [checkpointBytes, changeIDBytes, epochBytes, docIDBytes] =\n      unpackBlobs(bytes);\n\n    const checkpoint = JSON.parse(decoder.decode(checkpointBytes)) as {\n      serverSeq: string;\n      clientSeq: number;\n    };\n    this.checkpoint = Checkpoint.of(\n      BigInt(checkpoint.serverSeq),\n      checkpoint.clientSeq,\n    );\n    if (changeIDBytes) {\n      this.changeID = converter.bytesToChangeID(changeIDBytes);\n    }\n    // Trailing blobs stay optional, the same rule the `toBytes` envelope\n    // follows, so meta written before these fields existed still decodes.\n    if (epochBytes) {\n      this.epoch = BigInt(decoder.decode(epochBytes));\n    }\n    if (docIDBytes) {\n      this.docID = decoder.decode(docIDBytes);\n    }\n  }\n\n  /**\n   * `restoreAppendedChanges` replays changes that were recorded *after* the\n   * snapshot this document was restored from, as the offline-persistence\n   * layer's change log holds them.\n   *\n   * These are the opposite case to the pending changes carried inside a\n   * `toBytes` envelope. Those are already reflected in the snapshot's root —\n   * `toBytes` serializes the live root — so `fromBytes` queues them without\n   * applying. A change from the log was written after that root was captured,\n   * so it must be both **applied**, to bring the root forward, and **queued**,\n   * so it is still pushed. Doing only the first loses the edit on reconnect;\n   * doing only the second leaves the user looking at stale content.\n   *\n   * The log must be contiguous and ascending by `clientSeq`. A caller that\n   * cannot satisfy that should restore from the snapshot alone and report the\n   * loss rather than replaying a broken run.\n   */\n  public restoreAppendedChanges(\n    structs: Array<ChangeStruct<P>>,\n    ackedClientSeq = 0,\n  ): void {\n    if (!structs.length) {\n      return;\n    }\n\n    const changes = structs.map((struct) => Change.fromStruct<P>(struct));\n    let prev: number | undefined;\n    for (const change of changes) {\n      const clientSeq = change.getID().getClientSeq();\n      if (prev !== undefined && clientSeq <= prev) {\n        throw new YorkieError(\n          Code.ErrInvalidArgument,\n          `appended changes must be ascending by clientSeq, got ${clientSeq} ` +\n            `after ${prev}`,\n        );\n      }\n      prev = clientSeq;\n    }\n\n    // Every entry is applied — the log is the delta between the snapshot and\n    // current content, so skipping an acked one would leave the root behind.\n    // Only the unacked ones are queued: re-pushing what the server has already\n    // taken presents a `clientSeq` it will skip.\n    //\n    // A change an undo or a redo produced carries that through the struct\n    // (`Change.isUndoRedo`) and is replayed under `OpSource.UndoRedo`: see\n    // `replaySourceOf`.\n    this.replayLocalChanges(changes);\n    this.localChanges.push(\n      ...changes.filter(\n        (change) => change.getID().getClientSeq() > ackedClientSeq,\n      ),\n    );\n    // Restoring counts as a reconnect: the server that answers the resume may\n    // never have seen this presence, so the first update owes it a full put.\n    // Run after the queue is rebuilt, so a patch that came back with it is\n    // seen (and `replayLocalChanges` cannot leave its own tracking behind).\n    this.resetPresenceStateForRestore();\n    this.mintedOperations ||= changes.some(\n      (change) => change.getOperations().length > 0,\n    );\n\n    // Adopt the last replayed change's ID as the document's own counter.\n    //\n    // `applyChanges` only syncs clocks, which leaves `clientSeq` behind and\n    // over-advances `lamport` (it bumps per change, on top of a snapshot that\n    // predates them). Both matter. `createChangePack` derives the pushed\n    // checkpoint from `clientSeq`, so a counter left behind mints a sequence\n    // the server has already seen and silently drops the next edit; and a\n    // lamport that ran ahead mis-stamps every later ticket.\n    //\n    // An `update` leaves `changeID` equal to the change it just minted, so the\n    // state after replaying a run is the last change's ID exactly.\n    // Guarded: an all-acked replay must not pull the clock back below what the\n    // meta header already established.\n    const lastID = changes[changes.length - 1].getID();\n    if (lastID.getClientSeq() >= this.changeID.getClientSeq()) {\n      this.changeID = lastID;\n    }\n    this.absorbedRemote = true;\n\n    // The clone predates the replay, and the history's reverse-ops reference\n    // the pre-replay state — the same reasoning `restoreFromBytes` applies.\n    this.clone = undefined;\n    this.clearHistory();\n    this.localChangeObserver.next();\n  }\n\n  /**\n   * `resetForReanchor` drops all local state that was seeded from a stale\n   * persisted envelope so the document can be re-attached fresh. The server\n   * then re-anchors the client from the current snapshot. Used only on the\n   * store-backed attach path when the resume is rejected with\n   * `ErrEpochMismatch`: the persisted checkpoint/epoch/changeID and any\n   * un-pushed local changes are stale relative to the compacted document, so\n   * presenting them again would just be rejected. This mirrors constructing a\n   * brand-new Document instance without forcing the caller to swap the object\n   * reference it already holds.\n   */\n  public resetForReanchor(): void {\n    // The counter goes back to zero, so whatever hole `discardLocalChanges`\n    // left is gone and the document may mint again — the re-attach itself\n    // mints the initial presence change.\n    this.mintingSuspended = false;\n    this.changeID = InitialChangeID;\n    this.checkpoint = InitialCheckpoint;\n    this.localChanges = [];\n    this.absorbedRemote = false;\n    this.epoch = 0n;\n    this.presencePatchable = false;\n    this.presenceBaseSent = false;\n    this.presencePatchSent = false;\n    this.docID = '';\n    this.root = CRDTRoot.create();\n    this.presences = new Map();\n    this.clone = undefined;\n    // Clear the undo/redo history: its reverse-ops reference the stale\n    // root/changeID that was just dropped, so a later undo/redo would apply\n    // stale ticket references against the re-anchored state and corrupt it.\n    this.clearHistory();\n  }\n\n  /**\n   * `ensureClone` make a clone of root.\n   */\n  public ensureClone(): void {\n    if (this.clone) {\n      return;\n    }\n\n    this.clone = {\n      root: this.root.deepcopy(),\n      presences: deepcopy(this.presences),\n    };\n  }\n\n  /**\n   * `createChangePack` create change pack of the local changes to send to the\n   * remote server.\n   */\n  public createChangePack(): ChangePack<P> {\n    const changes = Array.from(this.localChanges);\n    const checkpoint = this.checkpoint.increaseClientSeq(changes.length);\n    return ChangePack.create(\n      this.key,\n      checkpoint,\n      false,\n      changes,\n      this.getVersionVector(),\n      undefined,\n      this.epoch,\n    );\n  }\n\n  /**\n   * `setActor` sets actor into this document. This is also applied in the local\n   * changes the document has. It returns whether the tickets were re-issued.\n   *\n   * Without `reissue` it rewrites only the change IDs and each operation's\n   * `executedAt`; the root and the tickets inside the operations keep the\n   * actor they were minted under. With `reissue`, a never-synced document\n   * re-issues every ticket of its previous actor to the given one, so a\n   * position or element ID taken from it before then no longer resolves. See\n   * docs/design/pre-attach-ticket-reissue.md.\n   *\n   * `reissue` has to carry `ReissueToken`, which only the owning `Client`\n   * holds: rewriting element identity under a caller-chosen actor is not a\n   * capability a holder of this handle gets.\n   */\n  public setActor(actorID: ActorID, opts?: SetActorOptions): boolean {\n    if (opts?.reissue !== undefined && opts.reissue !== ReissueToken) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        'setActor: reissue is internal to Client.attach',\n      );\n    }\n\n    if (opts?.reissue === ReissueToken && this.reissueActor(actorID)) {\n      return true;\n    }\n\n    for (const change of this.localChanges) {\n      change.setActor(actorID);\n    }\n    this.changeID = this.changeID.setActor(actorID);\n    return false;\n  }\n\n  /**\n   * `reissueActor` re-issues the tickets of a never-synced document to the\n   * given actor and returns true, or returns false and changes nothing when\n   * the document has synced, has no local changes or already has the actor.\n   *\n   * The local changes go through `reissueOperations`, and the root and\n   * presences are rebuilt by replaying them on a fresh root: a never-synced\n   * root is exactly the initial root plus its local changes, and the replay\n   * is the computation the server performs on the pushed changes. Everything\n   * is built aside and swapped in at the end, so a throw leaves the document\n   * untouched.\n   */\n  private reissueActor(actor: ActorID): boolean {\n    const prev = this.changeID.getActorID();\n    if (prev === actor || !this.localChanges.length || !this.neverSynced()) {\n      return false;\n    }\n\n    // Each rebuilt change carries over the source it was originally executed\n    // with (`Change.isUndoRedo`). An undo or a redo ran its change with\n    // `OpSource.UndoRedo`, and that source is what\n    // `SetOperation.execute`/`RemoveOperation.execute` consult to skip an\n    // operation whose target now sits under a removed parent: replaying such a\n    // change as `Local` would run an operation that never ran, so the rebuilt\n    // root would differ from the one the user is looking at (and\n    // `ElementRHT.delete` can throw out of the replay).\n    const changes = this.localChanges.map((change) => {\n      const id = change.getID();\n      return Change.create<P>({\n        id: id\n          .setActor(actor)\n          .setVersionVector(\n            reissueVersionVector(id.getVersionVector(), prev, actor),\n          ),\n        operations: reissueOperations(change.getOperations(), prev, actor),\n        presenceChange: change.getPresenceChange(),\n        message: change.getMessage(),\n        undoRedo: change.isUndoRedo(),\n      });\n    });\n\n    const root = CRDTRoot.create();\n    const presences = new Map<ActorID, P>();\n    for (const change of changes) {\n      change.execute(root, presences, replaySourceOf(change));\n    }\n\n    const onlineClients = new Set(this.onlineClients);\n    if (onlineClients.delete(prev)) {\n      onlineClients.add(actor);\n    }\n\n    this.localChanges = changes;\n    this.root = root;\n    this.presences = presences;\n    this.onlineClients = onlineClients;\n    this.changeID = this.changeID\n      .setActor(actor)\n      .setVersionVector(\n        reissueVersionVector(this.changeID.getVersionVector(), prev, actor),\n      );\n\n    // The clone and the undo/redo stacks hold the old tickets. The stacks\n    // cannot be re-issued the way the local changes are: a reverse operation\n    // has no `executedAt` until the undo runs it (`converter.toOperation`\n    // rejects it), and it carries local-only state the wire format does not\n    // name -- the split tickets and re-issued content ids `executeUndoRedo`\n    // records on it. They are dropped, which is the state every other path\n    // that rewrites the root (`applySnapshot`, `restoreFromBytes`,\n    // `resetForReanchor`) leaves them in. The drop follows from the re-issue\n    // itself, not from whether the attach that asked for it then succeeds.\n    this.clone = undefined;\n    this.clearHistory();\n\n    // The devtools recording holds the raw changes as they were minted, which\n    // no longer replay onto this root. Emptying it is not enough on its own:\n    // the panel replays a history onto a freshly built empty Document, so a\n    // recording that starts after the attach would be replayed onto a root\n    // that never had the pre-attach changes -- the replay diverges, or throws\n    // on an operation whose target it never created, in a panel that has no\n    // error boundary. The re-issued root is handed over as the recording's\n    // first event, so what the panel holds is a complete history again.\n    resetDevtoolsRecording(\n      this,\n      this.isEnableDevtools() ? [this.toReplayBaseline()] : undefined,\n    );\n    return true;\n  }\n\n  /**\n   * `toReplayBaseline` returns a snapshot event carrying this document's\n   * current root and presences, as the devtools replay consumes it\n   * (`applyDocEventsForReplay`). It is how a recording that no longer starts\n   * at the initial root is given one to start from.\n   */\n  private toReplayBaseline(): Devtools.DocEventForReplay<P> {\n    return {\n      type: DocEventType.Snapshot,\n      source: OpSource.Remote,\n      value: {\n        serverSeq: this.checkpoint.getServerSeq().toString(),\n        snapshot: converter.bytesToHex(\n          converter.snapshotToBytes(this.root.getObject(), this.presences),\n        ),\n        snapshotVector: converter.versionVectorToHex(\n          this.changeID.getVersionVector(),\n        ),\n      },\n    };\n  }\n\n  /**\n   * `neverSynced` returns whether every ticket naming this document's actor\n   * was minted by a local change still in `localChanges`: nothing has been\n   * pushed and nothing pulled.\n   */\n  private neverSynced(): boolean {\n    if (\n      this.absorbedRemote ||\n      this.status !== DocStatus.Detached ||\n      !this.checkpoint.equals(InitialCheckpoint)\n    ) {\n      return false;\n    }\n\n    const actor = this.changeID.getActorID();\n    for (const [id] of this.changeID.getVersionVector()) {\n      if (id !== actor) {\n        return false;\n      }\n    }\n    return true;\n  }\n\n  /**\n   * `hasMintedOperations` returns whether this document has produced a local\n   * change carrying operations, i.e. whether tickets naming its actor may\n   * already be in the document its key names. The client reads it to decide\n   * whether a re-issue -- which starts the actor's lamports back at 1 -- can\n   * still be sound for that key. See `Client.claimReissue`.\n   */\n  public hasMintedOperations(): boolean {\n    return this.mintedOperations;\n  }\n\n  /**\n   * `setDisableGC` records whether this document participates in GC. The\n   * client calls this on attach so subsequent applyChange runs use the\n   * lamport-only sync path.\n   */\n  public setDisableGC(disableGC: boolean): void {\n    this.disableGC = disableGC;\n  }\n\n  /**\n   * `setDisablePresence` records the server-fixated presence-disabled state\n   * of this document. The client calls this on attach (before\n   * `applyChangePack`) so any subsequent `Document.update` invocation sees\n   * the gating state already settled. Flipping the flag at runtime is\n   * supported: the next `update` honours the new value.\n   */\n  public setDisablePresence(disablePresence: boolean): void {\n    this.disablePresence = disablePresence;\n  }\n\n  /**\n   * `isPresenceDisabled` returns the current presence-disabled state of\n   * this document. Reflects the server-fixated value once attached;\n   * before attach it reflects the local construction option.\n   */\n  public isPresenceDisabled(): boolean {\n    return this.disablePresence;\n  }\n\n  /**\n   * `isEnableDevtools` returns whether devtools is enabled or not.\n   */\n  public isEnableDevtools(): boolean {\n    return !!this.opts.enableDevtools;\n  }\n\n  /**\n   * `getKey` returns the key of this document.\n   */\n  public getKey(): string {\n    return this.key;\n  }\n\n  /**\n   * `getStatus` returns the status of this document.\n   */\n  public getStatus(): DocStatus {\n    return this.status;\n  }\n\n  /**\n   * `getClone` returns this clone.\n   */\n  public getClone() {\n    return this.clone;\n  }\n\n  /**\n   * `getCloneRoot` returns clone object.\n   */\n  public getCloneRoot(): CRDTObject | undefined {\n    if (!this.clone) {\n      return;\n    }\n\n    return this.clone.root.getObject();\n  }\n\n  /**\n   * `getRoot` returns a new proxy of cloned root.\n   */\n  public getRoot(): JSONObject<R> {\n    this.ensureClone();\n\n    const ctx = ChangeContext.create(\n      this.changeID.next(),\n      this.clone!.root,\n      this.clone!.presences.get(this.changeID.getActorID()) || ({} as P),\n    );\n    return createJSON<R>(ctx, this.clone!.root.getObject());\n  }\n\n  /**\n   * `getDocSize` returns the size of this document.\n   */\n  public getDocSize(): DocSize {\n    return this.root.getDocSize();\n  }\n\n  /**\n   * `getMaxSizePerDocument` gets the maximum size of this document.\n   */\n  public getMaxSizePerDocument() {\n    return this.maxSizeLimit;\n  }\n\n  /**\n   * `setMaxSizePerDocument` sets the maximum size of this document.\n   */\n  public setMaxSizePerDocument(size: number) {\n    this.maxSizeLimit = size;\n  }\n\n  /**\n   * `getSchemaRules` gets the schema rules of this document.\n   */\n  public getSchemaRules() {\n    return this.schemaRules;\n  }\n\n  /**\n   * `setSchemaRules` sets the schema rules of this document.\n   */\n  public setSchemaRules(rules: Array<Rule>) {\n    this.schemaRules = rules;\n  }\n\n  /**\n   * `garbageCollect` purges elements that were removed before the given time.\n   */\n  public garbageCollect(minSyncedVersionVector: VersionVector): number {\n    if (this.opts.disableGC) {\n      return 0;\n    }\n\n    if (this.clone) {\n      this.clone.root.garbageCollect(minSyncedVersionVector);\n    }\n    return this.root.garbageCollect(minSyncedVersionVector);\n  }\n\n  /**\n   * `getRootObject` returns root object.\n   */\n  public getRootObject(): CRDTObject {\n    return this.root.getObject();\n  }\n\n  /**\n   * `getGarbageLen` returns the length of elements should be purged.\n   */\n  public getGarbageLen(): number {\n    return this.root.getGarbageLen();\n  }\n\n  /**\n   * `getRootCRDT` returns the CRDTRoot for testing purposes.\n   * This method is intended for internal testing only.\n   */\n  public getRootCRDT(): CRDTRoot {\n    return this.root;\n  }\n\n  /**\n   * `getGarbageLenFromClone` returns the length of elements should be purged from clone.\n   */\n  public getGarbageLenFromClone(): number {\n    return this.clone!.root.getGarbageLen();\n  }\n\n  /**\n   * `toJSON` returns the JSON encoding of this document.\n   */\n  public toJSON(): string {\n    return this.root.toJSON();\n  }\n\n  /**\n   * `toSortedJSON` returns the sorted JSON encoding of this document.\n   */\n  public toSortedJSON(): string {\n    return this.root.toSortedJSON();\n  }\n\n  /**\n   * `getStats` returns the statistics of this document.\n   */\n  public getStats(): RootStats {\n    return this.root.getStats();\n  }\n\n  /**\n   * `toJSForTest` returns value with meta data for testing.\n   */\n  public toJSForTest(): Devtools.JSONElement {\n    return {\n      ...this.getRoot().toJSForTest(),\n      key: 'root',\n    };\n  }\n\n  /**\n   * `applySnapshot` applies the given snapshot into this document.\n   */\n  public applySnapshot(\n    serverSeq: bigint,\n    snapshotVector: VersionVector,\n    snapshot?: Uint8Array,\n    clientSeq: number = -1,\n  ) {\n    const { root, presences } = converter.bytesToSnapshot<P>(snapshot);\n    this.root = new CRDTRoot(root);\n    this.presences = presences;\n    this.absorbedRemote = true;\n    this.changeID = this.changeID.setClocks(\n      snapshotVector.maxLamport(),\n      snapshotVector,\n    );\n\n    // drop clone because it is contaminated.\n    this.clone = undefined;\n\n    this.removePushedLocalChanges(clientSeq);\n\n    // NOTE(hackerwins): If the document has local changes, we need to apply\n    // them after applying the snapshot, as local changes are not included in the snapshot data.\n    // Afterward, we should publish a snapshot event with the latest\n    // version of the document to ensure the user receives the most up-to-date snapshot.\n    //\n    // Each queued change is replayed under the source it originally ran with:\n    // see `replaySourceOf`.\n    this.replayLocalChanges(this.localChanges);\n    this.clearHistory();\n    this.publish([\n      {\n        type: DocEventType.Snapshot,\n        source: OpSource.Remote,\n        value: {\n          serverSeq: serverSeq.toString(),\n          snapshot: this.isEnableDevtools()\n            ? converter.bytesToHex(snapshot)\n            : undefined,\n          snapshotVector: converter.versionVectorToHex(snapshotVector),\n        },\n      },\n    ]);\n  }\n\n  /**\n   * `clearHistory` flushes both undo and redo stacks. This is used\n   * after applying a snapshot or initialRoot so that setup operations\n   * are not reachable via undo.\n   */\n  public clearHistory() {\n    this.internalHistory.clearRedo();\n    this.internalHistory.clearUndo();\n  }\n\n  /**\n   * `applyChanges` applies the given changes into this document.\n   */\n  public applyChanges(changes: Array<Change<P>>, source: OpSource): void {\n    if (logger.isEnabled(LogLevel.Debug)) {\n      logger.debug(\n        `trying to apply ${changes.length} remote changes.` +\n          `elements:${this.root.getElementMapSize()}, ` +\n          `removeds:${this.root.getGarbageElementSetSize()}`,\n      );\n    }\n    if (logger.isEnabled(LogLevel.Trivial)) {\n      logger.trivial(\n        changes\n          .map(\n            (change) =>\n              `${change.getID().toTestString()}\\t${change.toTestString()}`,\n          )\n          .join('\\n'),\n      );\n    }\n\n    for (const change of changes) {\n      this.applyChange(change, source);\n    }\n\n    if (logger.isEnabled(LogLevel.Debug)) {\n      logger.debug(\n        `after appling ${changes.length} remote changes.` +\n          `elements:${this.root.getElementMapSize()}, ` +\n          ` removeds:${this.root.getGarbageElementSetSize()}`,\n      );\n    }\n  }\n\n  /**\n   * `replayLocalChanges` applies the given queued local changes, each under\n   * the source it originally ran with (`replaySourceOf`). A plain\n   * `applyChanges(changes, OpSource.Local)` would run an operation an undo had\n   * skipped, so every replay of the queue goes through here instead.\n   */\n  private replayLocalChanges(changes: Array<Change<P>>): void {\n    for (const change of changes) {\n      this.applyChange(change, replaySourceOf(change));\n    }\n  }\n\n  /**\n   * `applyChange` applies the given change into this document.\n   */\n  public applyChange(change: Change<P>, source: OpSource) {\n    try {\n      this.applyChangeInternal(change, source);\n    } catch (err) {\n      // NOTE: `Change.execute` does not roll back, so a change that fails\n      // partway leaves the clone and the root holding different prefixes of\n      // it. Drop the clone so the next access rebuilds it from the root, the\n      // way `update` does on failure.\n      this.clone = undefined;\n\n      // NOTE: only a remote change is named. The checkpoint only advances\n      // after the changes of a pack have been applied, so a remote change\n      // that throws is redelivered by the server forever and needs to be\n      // diagnosable rather than looking like a network problem. A local\n      // replay (`restoreAppendedChanges`) or a devtools-driven local apply\n      // has a caller waiting on it, and rewriting the error it threw would\n      // hide the code that caller matches on.\n      if (source !== OpSource.Remote) {\n        throw err;\n      }\n\n      throw err instanceof ChangeApplyError\n        ? err.withDocKey(this.key)\n        : new ChangeApplyError({\n            docKey: this.key,\n            changeID: change.getID().toTestString(),\n            cause: err,\n          });\n    }\n  }\n\n  /**\n   * `applyChangeInternal` applies the given change into the clone and the root.\n   */\n  private applyChangeInternal(change: Change<P>, source: OpSource) {\n    if (source === OpSource.Remote) {\n      this.absorbedRemote = true;\n    }\n    this.ensureClone();\n    change.execute(this.clone!.root, this.clone!.presences, source);\n\n    const events: DocEvents<P> = [];\n    const actorID = change.getID().getActorID();\n\n    // Capture prev state before execute updates this.presences\n    const prev = change.hasPresenceChange()\n      ? {\n          hadPresence: this.presences.has(actorID),\n          wasOnline: this.onlineClients.has(actorID),\n          presence: this.presences.has(actorID)\n            ? deepcopy(this.presences.get(actorID)!)\n            : undefined,\n        }\n      : undefined;\n\n    const { opInfos, operations } = change.execute(\n      this.root,\n      this.presences,\n      source,\n    );\n    for (const op of operations) {\n      if (op instanceof EditOperation) {\n        const [from, to] = op.normalizePos(this.root);\n\n        this.internalHistory.reconcileTextEdit(\n          op.getParentCreatedAt(),\n          from,\n          to,\n          op.getContent()?.length ?? 0,\n        );\n      }\n      if (op instanceof TreeEditOperation) {\n        // A split re-creates the elements a merge took away, under brand-new\n        // ids -- see `CRDTTree.mergeSourceOf`. That happens whoever sent the\n        // split: `executeUndoRedo` re-points this replica's stacks when the\n        // split is its own, and here when it arrives from a peer. Left\n        // un-re-pointed, an entry still naming the element the peer replaced\n        // addresses a node garbage collection will purge, and the change it\n        // eventually pushes is rejected on every replica (#1425).\n        //\n        // Done before the index reconciliation below and before the event is\n        // published, for the same reason the undo/redo path defers to after\n        // execution: the pairs are only known once the split has run.\n        for (const [prev, curr] of op.getSplitRecreatedIDs()) {\n          this.internalHistory.reconcileTreeNodeID(\n            op.getParentCreatedAt(),\n            prev,\n            curr,\n          );\n        }\n\n        // One reconciliation per range the op actually changed, in the order\n        // it changed them: an identity-preserving restore/retombstone revives\n        // or re-removes several nodes at positions its stored indices never\n        // describe, and each measurement is relative to the one before it.\n        for (const [from, to, contentSize] of op.getExecutedRanges()) {\n          this.internalHistory.reconcileTreeEdit(\n            op.getParentCreatedAt(),\n            from,\n            to,\n            contentSize,\n          );\n        }\n      }\n    }\n    this.changeID = this.disableGC\n      ? this.changeID.syncLamport(change.getID())\n      : this.changeID.syncClocks(change.getID());\n    // Gated on the operations that RAN, not on the `OpInfo`s they produced,\n    // for the same reason as the undo/redo path in `executeUndoRedo`: an\n    // operation can change CRDT state without producing anything an editor\n    // could render (a style on a node the sender removed concurrently, a Tree\n    // restore whose revived nodes all sit under a removed ancestor). Such a\n    // change still moved this replica and still occupies a `serverSeq`, so a\n    // peer applying it has to see the event -- otherwise devtools replay and\n    // any subscriber counting changes lose it.\n    if (operations.length) {\n      const rawChange = this.isEnableDevtools() ? change.toStruct() : undefined;\n      events.push(\n        source === OpSource.Remote\n          ? {\n              type: DocEventType.RemoteChange,\n              source,\n              value: {\n                actor: actorID,\n                clientSeq: change.getID().getClientSeq(),\n                serverSeq: change.getID().getServerSeq(),\n                message: change.getMessage() || '',\n                operations: opInfos,\n              },\n              rawChange,\n            }\n          : {\n              type: DocEventType.LocalChange,\n              source,\n              value: {\n                actor: actorID,\n                clientSeq: change.getID().getClientSeq(),\n                serverSeq: change.getID().getServerSeq(),\n                message: change.getMessage() || '',\n                operations: opInfos,\n              },\n              rawChange,\n            },\n      );\n    }\n    if (prev && change.hasPresenceChange()) {\n      const presenceChange = change.getPresenceChange()!;\n      if (presenceChange.type === PresenceChangeType.Clear) {\n        this.removeOnlineClient(actorID);\n      }\n      const presenceEvent = this.reconcilePresence(actorID, prev, source);\n      if (presenceEvent) {\n        events.push(presenceEvent);\n      }\n    }\n    // DocEvent should be emitted synchronously with applying changes.\n    // This is because 3rd party model should be synced with the Document\n    // after RemoteChange event is emitted. If the event is emitted\n    // asynchronously, the model can be changed and breaking consistency.\n    if (events.length) {\n      this.publish(events);\n    }\n  }\n\n  /**\n   * `applyWatchInit` applies the watch initialization with the given client IDs.\n   */\n  public applyWatchInit(clientIDs: Array<string>) {\n    const onlineClients: Set<ActorID> = new Set();\n    for (const clientID of clientIDs) {\n      if (clientID === this.changeID.getActorID()) {\n        continue;\n      }\n\n      onlineClients.add(clientID);\n    }\n    this.setOnlineClients(onlineClients);\n\n    // NOTE(hackerwins): We intentionally do NOT prune presences for clients\n    // no longer in the online set. The presences map retains stale entries,\n    // but getPresences() / getOthersPresences() already filter by\n    // onlineClients, so stale data is never exposed to the caller.\n    //\n    // Keeping stale presences allows correct recovery when a client's watch\n    // stream reconnects: the server sends DOCUMENT_WATCHED, applyDocEvent\n    // checks hasPresence(publisher), and because the old presence is still\n    // in the map the \"watched\" event fires and the client becomes visible\n    // again. Previously, pruning here deleted the presence, causing\n    // hasPresence to return false and silently dropping the reconnected peer.\n\n    this.publish([\n      {\n        type: DocEventType.Initialized,\n        source: OpSource.Local,\n        value: this.getPresences(),\n      },\n    ]);\n  }\n\n  /**\n   * `applyDocEvent` applies the given doc event into this document.\n   */\n  public applyDocEvent(type: PbDocEventType, publisher: string) {\n    const prev = {\n      hadPresence: this.presences.has(publisher),\n      wasOnline: this.onlineClients.has(publisher),\n      presence: this.presences.has(publisher)\n        ? deepcopy(this.presences.get(publisher)!)\n        : undefined,\n    };\n\n    if (type === PbDocEventType.DOCUMENT_WATCHED) {\n      if (this.onlineClients.has(publisher) && this.hasPresence(publisher)) {\n        return;\n      }\n      this.addOnlineClient(publisher);\n    } else if (type === PbDocEventType.DOCUMENT_UNWATCHED) {\n      // NOTE(hackerwins): Only the online set is touched here; the presence\n      // itself is kept, for the same reason applyWatchInit keeps it above.\n      // Dropping it would make hasPresence false, so the DOCUMENT_WATCHED\n      // that follows a watch-stream reconnect would publish no \"watched\"\n      // event and the peer would stay invisible. The unwatched event still\n      // fires: reconcilePresence keys that transition on isOnline, which\n      // removeOnlineClient alone flips.\n      this.removeOnlineClient(publisher);\n    }\n\n    const event = this.reconcilePresence(publisher, prev, OpSource.Remote);\n    if (event) {\n      this.publish([event]);\n    }\n  }\n\n  /**\n   * `applyStatus` applies the document status into this document.\n   */\n  public applyStatus(status: DocStatus) {\n    const actorID = this.changeID.getActorID();\n    const prev = {\n      hadPresence: this.presences.has(actorID),\n      wasOnline: this.status === DocStatus.Attached,\n      presence: this.presences.has(actorID)\n        ? deepcopy(this.presences.get(actorID)!)\n        : undefined,\n    };\n\n    this.status = status;\n\n    if (status === DocStatus.Detached) {\n      this.setActor(InitialActorID);\n    }\n\n    const event = this.reconcilePresence(actorID, prev, OpSource.Local);\n    if (event) {\n      this.publish([event]);\n    }\n\n    this.publish([\n      {\n        source: status === DocStatus.Removed ? OpSource.Remote : OpSource.Local,\n        type: DocEventType.StatusChanged,\n        value:\n          status === DocStatus.Attached\n            ? { status, actorID: this.changeID.getActorID() }\n            : { status },\n      },\n    ]);\n  }\n\n  /**\n   * `applyDocEventsForReplay` applies the given events into this document.\n   */\n  public applyDocEventsForReplay(events: Array<Devtools.DocEventForReplay<P>>) {\n    for (const event of events) {\n      if (event.type === DocEventType.StatusChanged) {\n        this.applyStatus(event.value.status);\n        if (event.value.status === DocStatus.Attached) {\n          this.setActor(event.value.actorID);\n        }\n        continue;\n      }\n\n      if (event.type === DocEventType.Snapshot) {\n        const { snapshot, serverSeq, snapshotVector } = event.value;\n        if (!snapshot) continue;\n\n        // TODO(hackerwins): We need to check version vector and lamport clock\n        // of the snapshot is valid.\n        this.applySnapshot(\n          BigInt(serverSeq),\n          converter.hexToVersionVector(snapshotVector),\n          converter.hexToBytes(snapshot),\n        );\n        continue;\n      }\n\n      if (\n        event.type === DocEventType.LocalChange ||\n        event.type === DocEventType.RemoteChange\n      ) {\n        if (!event.rawChange) continue;\n        const change = Change.fromStruct<P>(event.rawChange);\n        this.applyChange(change, event.source);\n      }\n\n      if (event.type === DocEventType.Initialized) {\n        const onlineClients: Set<ActorID> = new Set();\n        for (const { clientID, presence } of event.value) {\n          onlineClients.add(clientID);\n          this.presences.set(clientID, presence);\n        }\n        this.setOnlineClients(onlineClients);\n      } else if (event.type === DocEventType.Watched) {\n        const { clientID, presence } = event.value;\n        this.addOnlineClient(clientID);\n        this.presences.set(clientID, presence);\n      } else if (event.type === DocEventType.Unwatched) {\n        const { clientID } = event.value;\n        this.removeOnlineClient(clientID);\n        this.presences.delete(clientID);\n      } else if (event.type === DocEventType.PresenceChanged) {\n        const { clientID, presence } = event.value;\n        this.presences.set(clientID, presence);\n      }\n    }\n  }\n\n  /**\n   * `getValueByPath` returns the JSONElement corresponding to the given path.\n   */\n  public getValueByPath(path: string): JSONElement | undefined {\n    if (!path.startsWith('$')) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `path must start with \"$\"`,\n      );\n    }\n    const paths = path.split('.');\n    paths.shift();\n    let value: JSONObject<any> = this.getRoot();\n    for (const key of paths) {\n      value = value[key];\n      if (!value) return undefined;\n    }\n    return value;\n  }\n\n  /**\n   * `setOnlineClients` sets the given online client set.\n   */\n  public setOnlineClients(onlineClients: Set<ActorID>) {\n    this.onlineClients = onlineClients;\n  }\n\n  /**\n   * `resetOnlineClients` resets the online client set.\n   */\n  public resetOnlineClients() {\n    this.onlineClients = new Set();\n  }\n\n  /**\n   * `addOnlineClient` adds the given clientID into the online client set.\n   */\n  public addOnlineClient(clientID: ActorID) {\n    this.onlineClients.add(clientID);\n  }\n\n  /**\n   * `removeOnlineClient` removes the clientID from the online client set.\n   */\n  public removeOnlineClient(clientID: ActorID) {\n    this.onlineClients.delete(clientID);\n  }\n\n  /**\n   * `reconcilePresence` compares the previous and current state of a client's\n   * presence/online status and returns the appropriate event to emit.\n   *\n   * For remote clients, \"online\" means the client is in onlineClients.\n   * For self, \"online\" means the document status is Attached.\n   *\n   * State transition table:\n   *   (!hadP || !wasOn) → (hasP && isOn)  : watched (remote) or presence-changed (self)\n   *   (hadP && wasOn)   → (hasP && isOn)  : presence-changed\n   *   (hadP && wasOn)   → (!hasP || !isOn): unwatched (remote only)\n   *   otherwise                           : no event (waiting)\n   */\n  private reconcilePresence(\n    actorID: ActorID,\n    prev: { hadPresence: boolean; wasOnline: boolean; presence?: P },\n    source: OpSource,\n  ): WatchedEvent<P> | UnwatchedEvent<P> | PresenceChangedEvent<P> | undefined {\n    const isSelf = actorID === this.changeID.getActorID();\n    const hasPresence = this.presences.has(actorID);\n    const isOnline = isSelf\n      ? this.status === DocStatus.Attached\n      : this.onlineClients.has(actorID);\n\n    if (!hasPresence || !isOnline) {\n      // Transitioned from ready → not ready: unwatched (remote only)\n      if (prev.hadPresence && prev.wasOnline && !isSelf) {\n        return {\n          type: DocEventType.Unwatched,\n          source: OpSource.Remote,\n          value: {\n            clientID: actorID,\n            presence: prev.presence!,\n          },\n        };\n      }\n      return undefined;\n    }\n\n    const presence = deepcopy(this.presences.get(actorID)!);\n\n    if (!prev.hadPresence || !prev.wasOnline) {\n      // Transitioned from not-ready → ready\n      if (isSelf) {\n        return {\n          type: DocEventType.PresenceChanged,\n          source,\n          value: { clientID: actorID, presence },\n        };\n      }\n      return {\n        type: DocEventType.Watched,\n        source: OpSource.Remote,\n        value: { clientID: actorID, presence },\n      };\n    }\n\n    // Both were ready and still are: presence value changed\n    return {\n      type: DocEventType.PresenceChanged,\n      source,\n      value: { clientID: actorID, presence },\n    };\n  }\n\n  /**\n   * `hasPresence` returns whether the given clientID has a presence or not.\n   */\n  public hasPresence(clientID: ActorID): boolean {\n    return this.presences.has(clientID);\n  }\n\n  /**\n   * `getMyPresence` returns the presence of the current client.\n   */\n  public getMyPresence(): P {\n    // TODO(chacha912): After resolving the presence initialization issue,\n    // remove default presence.(#608)\n    if (this.status !== DocStatus.Attached) {\n      return {} as P;\n    }\n\n    const p = this.presences.get(this.changeID.getActorID())!;\n    return p ? deepcopy(p) : ({} as P);\n  }\n\n  /**\n   * `getOthersPresences` returns the presences of all other clients.\n   */\n  public getOthersPresences(): Array<{ clientID: ActorID; presence: P }> {\n    const others: Array<{ clientID: ActorID; presence: P }> = [];\n    const myClientID = this.changeID.getActorID();\n\n    for (const clientID of this.onlineClients) {\n      if (clientID !== myClientID && this.presences.has(clientID)) {\n        others.push({\n          clientID,\n          presence: deepcopy(this.presences.get(clientID)!),\n        });\n      }\n    }\n\n    return others;\n  }\n\n  /**\n   * `getPresence` returns the presence of the given clientID.\n   */\n  public getPresence(clientID: ActorID): P | undefined {\n    if (clientID === this.changeID.getActorID()) {\n      return this.getMyPresence();\n    }\n\n    if (!this.onlineClients.has(clientID)) return;\n    const p = this.presences.get(clientID);\n    return p ? deepcopy(p) : undefined;\n  }\n\n  /**\n   * `getPresences` returns the presences of online clients.\n   */\n  public getPresences(): Array<{ clientID: ActorID; presence: P }> {\n    const presences: Array<{ clientID: ActorID; presence: P }> = [];\n    presences.push({\n      clientID: this.changeID.getActorID(),\n      presence: deepcopy(this.getMyPresence()),\n    });\n\n    for (const clientID of this.onlineClients) {\n      if (this.presences.has(clientID)) {\n        presences.push({\n          clientID,\n          presence: deepcopy(this.presences.get(clientID)!),\n        });\n      }\n    }\n    return presences;\n  }\n\n  /**\n   * `getPresenceForTest` returns the presence of the given clientID\n   * regardless of whether the client is online or not.\n   */\n  public getPresenceForTest(clientID: ActorID): P | undefined {\n    const p = this.presences.get(clientID);\n    return p ? deepcopy(p) : undefined;\n  }\n\n  /**\n   * `getSelfForTest` returns the client that has attached this document.\n   */\n  public getSelfForTest() {\n    return {\n      clientID: this.getChangeID().getActorID(),\n      presence: this.getMyPresence(),\n    };\n  }\n\n  /**\n   * `getOthersForTest` returns all the other clients in online, sorted by clientID.\n   */\n  public getOthersForTest() {\n    const myClientID = this.getChangeID().getActorID();\n\n    return this.getPresences()\n      .filter((a) => a.clientID !== myClientID)\n      .sort((a, b) => (a.clientID > b.clientID ? 1 : -1));\n  }\n\n  /**\n   * `getUndoStackForTest` returns the undo stack for test.\n   */\n  public getUndoStackForTest(): Array<Array<HistoryOperation<P>>> {\n    return this.internalHistory.getUndoStackForTest();\n  }\n\n  /**\n   * `getRedoStackForTest` returns the redo stack for test.\n   */\n  public getRedoStackForTest(): Array<Array<HistoryOperation<P>>> {\n    return this.internalHistory.getRedoStackForTest();\n  }\n\n  /**\n   * `getVersionVector` returns the version vector of document\n   */\n  public getVersionVector() {\n    return this.changeID.getVersionVector();\n  }\n\n  private isSameElementOrChildOf(elem: string, parent: string): boolean {\n    if (parent === elem) {\n      return true;\n    }\n\n    const nodePath = elem.split('.');\n    return parent.split('.').every((path, index) => path === nodePath[index]);\n  }\n\n  /**\n   * `acknowledgePushedChanges` removes the local changes the server has\n   * confirmed, and forwards only the client seq of the checkpoint. It is for a\n   * response pack dropped without applying its remote state: the server seq\n   * must stay put so the skipped state is pulled again later, while the\n   * confirmed changes must not be pushed again. The server dedupes a re-pushed\n   * change when storing it, but a snapshot it builds for the same request\n   * would apply that change a second time.\n   *\n   * The pack's *metadata* is not remote state, and is taken in full: the\n   * compaction epoch and the removal flag describe the document itself, not\n   * the content being skipped, and neither is re-sent by a later pull the way\n   * the skipped changes are.\n   *\n   * @internal\n   */\n  public acknowledgePushedChanges(pack: ChangePack<P>): void {\n    const clientSeq = pack.getCheckpoint().getClientSeq();\n\n    // The capabilities describe the server that took this push, not the\n    // content being skipped, so they are metadata as well -- and a push whose\n    // reply is dropped is exactly a push that carried the patch which a server\n    // without the capability has just stored as an unspecified change. Skipping\n    // the heal here would leave a document in PushOnly/SyncOff patching into\n    // the void for as long as it stays there.\n    const needsHeal = this.learnPresenceCapability(pack);\n\n    this.removePushedLocalChanges(clientSeq);\n    this.checkpoint = this.checkpoint.forward(\n      Checkpoint.of(this.checkpoint.getServerSeq(), clientSeq),\n    );\n\n    // Dropping the epoch would leave the client presenting a superseded one on\n    // the next request, which the server answers with `ErrEpochMismatch` — a\n    // re-anchor that discards exactly the un-pushed edits PushOnly exists to\n    // keep. A compaction is also the shape that arrives as a snapshot, i.e.\n    // precisely the pack this path drops.\n    this.epoch = pack.getEpoch();\n\n    // A removal is terminal: there is no later pull to learn it from, because\n    // the server row is gone. Skipping it leaves the document attached and its\n    // persisted envelope pointing at a row that no longer exists.\n    if (pack.getIsRemoved()) {\n      this.applyStatus(DocStatus.Removed);\n    }\n\n    // Minted last, so the put is queued behind the ack that just dropped the\n    // pushed changes rather than in front of it.\n    if (needsHeal) {\n      this.healPresenceBase();\n    }\n  }\n\n  /**\n   * `removePushedLocalChanges` removes local changes that have been applied to\n   * the server from the local changes.\n   *\n   * @param clientSeq - client sequence number to remove local changes before it\n   */\n  private removePushedLocalChanges(clientSeq: number) {\n    while (this.localChanges.length) {\n      const change = this.localChanges[0];\n      if (change.getID().getClientSeq() > clientSeq) {\n        break;\n      }\n      this.localChanges.shift();\n    }\n  }\n\n  /**\n   * `executeUndoRedo` executes undo or redo operation with shared logic.\n   */\n  private executeUndoRedo(isUndo: boolean): void {\n    if (this.isUpdating) {\n      throw new YorkieError(\n        Code.ErrRefused,\n        `${isUndo ? 'Undo' : 'Redo'} is not allowed during an update`,\n      );\n    }\n    this.ensureMintable(isUndo ? 'Undo' : 'Redo');\n\n    // NOTE: The refusal above must not drop the clone: an updater is holding\n    // a proxy over it, and `update` reads it again after the updater returns.\n    try {\n      this.executeUndoRedoInternal(isUndo);\n    } catch (err) {\n      // A partially executed undo/redo leaves the clone ahead of the root;\n      // drop it so the next access rebuilds it from the root.\n      this.clone = undefined;\n      throw err;\n    }\n  }\n\n  /**\n   * `executeUndoRedoInternal` pops the history entry and applies it to the\n   * clone and the root.\n   */\n  private executeUndoRedoInternal(isUndo: boolean): void {\n    const ops = isUndo\n      ? this.internalHistory.popUndo()\n      : this.internalHistory.popRedo();\n\n    if (!ops) {\n      return;\n    }\n\n    this.ensureClone();\n    // TODO(chacha912): After resolving the presence initialization issue,\n    // remove default presence.(#608)\n    const ctx = ChangeContext.create<P>(\n      this.changeID,\n      this.clone!.root,\n      this.clone!.presences.get(this.changeID.getActorID()) || ({} as P),\n    );\n\n    // Tree node ids this entry re-mints, and what they replace. Collected\n    // while the change is built and applied to the history stacks only once\n    // the operations have run — see the split branch below.\n    const pending: Array<{\n      op: TreeEditOperation;\n      prev: CRDTTreeNodeID;\n      curr: CRDTTreeNodeID;\n      // Which of the operation's split tickets `curr` is, so the drain can\n      // tell whether the ROOT execution got that far — the hook that records\n      // the pair fires on the clone pass first, and the two passes need not\n      // mint the same number of elements. -1 for a re-issued content id,\n      // which is minted unconditionally.\n      ticketIndex: number;\n    }> = [];\n    // The splitting operations whose re-pointing hook is still registered,\n    // so it can be taken off once the change has been applied — it closes\n    // over this entry, which outlives nothing here.\n    const splitOps: Array<TreeEditOperation> = [];\n    /**\n     * `repointRest` re-points the operations that follow `op` in this entry\n     * from `prev` to `curr`.\n     */\n    const repointRest = (\n      op: Operation,\n      prev: CRDTTreeNodeID,\n      curr: CRDTTreeNodeID,\n    ) => {\n      for (const later of ops.slice(ops.indexOf(op) + 1)) {\n        if (\n          later instanceof TreeEditOperation ||\n          later instanceof TreeStyleOperation\n        ) {\n          later.reconcileNodeID(prev, curr);\n        }\n      }\n    };\n\n    // apply undo/redo operation in the context to generate a change\n    for (const op of ops) {\n      if (!(op instanceof Operation)) {\n        // apply presence change to the context\n        const presence = new Channel<P>(\n          ctx,\n          deepcopy(this.clone!.presences.get(this.changeID.getActorID())!),\n          this.canPatchPresence(),\n        );\n        presence.set(op.value, { addToHistory: true });\n        continue;\n      }\n\n      const ticket = ctx.issueTimeTicket();\n      op.setExecutedAt(ticket);\n\n      // A Set/Add/ArraySet reverse carries a deepcopy of the value it\n      // restores, and that copy keeps the split-sibling links of the tree it\n      // was taken from. Every other replica decodes this same operation\n      // through `dropSplitLinksInElement`, so without this the replica that\n      // ran the undo is the only one left holding the links, and the two\n      // disagree from the next same-boundary split on.\n      if (\n        op instanceof SetOperation ||\n        op instanceof AddOperation ||\n        op instanceof ArraySetOperation\n      ) {\n        dropSplitLinksInElement(op.getValue());\n      }\n\n      // NOTE(hackerwins): In undo/redo, both Set and Add may act as updates.\n      // - Set: replaces the element value.\n      // - Add: serves as UndoRemove, effectively restoring a deleted element.\n      // In both cases, the history stack may point to the old createdAt,\n      // so we update it to the new createdAt.\n      if (op instanceof ArraySetOperation) {\n        const prev = op.getCreatedAt();\n        op.getValue().setCreatedAt(ticket);\n        this.internalHistory.reconcileCreatedAt(prev, ticket);\n      } else if (op instanceof AddOperation) {\n        const prev = op.getValue().getCreatedAt();\n        op.getValue().setCreatedAt(ticket);\n        this.internalHistory.reconcileCreatedAt(prev, ticket);\n      } else if (op instanceof TreeEditOperation) {\n        // A reverse that re-inserts a copy of removed nodes carries their\n        // original ids; inserting them again would leave two nodes under one\n        // id. Restore-mode reverses revive by identity and keep theirs.\n        //\n        // Same hazard as the split below: the nodes come back under brand-new\n        // ids, so anything else recorded against the old ones has to follow.\n        for (const [prev, curr] of op.reissueContentIDs(() =>\n          ctx.issueTimeTicket(),\n        )) {\n          repointRest(op, prev, curr);\n          pending.push({ op, prev, curr, ticketIndex: -1 });\n        }\n\n        // A split reverse -- the undo of a merge, or the redo of a split --\n        // mints one element per split level, and each needs a ticket the\n        // loop above did not issue: it issues exactly one per operation.\n        // Left without them, `TreeEditOperation.execute` falls back to\n        // reconstructing them by counting delimiters up from its own\n        // executedAt, which runs straight over the ticket the NEXT operation\n        // in this same entry was issued -- landing two LIVE elements under\n        // one id, on every replica and on the server, since the change\n        // carries both operations. Recording them on the operation is what\n        // stops any other replica reconstructing them either.\n        //\n        // One per level is an upper bound, not an exact count: the split\n        // stops early when it reaches the root. A ticket nobody consumes\n        // only advances the delimiter, while one short would silently\n        // reopen the fallback. Mirrors yorkie's `executeUndoRedo`.\n        const level = op.getSplitLevel();\n        if (level > 0) {\n          const tickets = Array.from({ length: level }, () =>\n            ctx.issueTimeTicket(),\n          );\n          op.setSplitTickets(tickets);\n\n          // The split re-creates elements a merge removed, under the new\n          // tickets. Operations recorded against the old elements -- the\n          // rest of this entry (the style that followed a split, say) and\n          // any other entry in the stacks -- still name them. Once garbage\n          // collection has purged the old elements, a replica applying such\n          // an operation cannot find them and rejects the whole change\n          // (#1425). Re-point them, so the change is encoded with the ids\n          // every replica will have.\n          //\n          // Both re-pointings are driven from the split itself, as it takes\n          // each ticket: only then is it known that the element exists. The\n          // split stops as soon as it runs out of ancestors, so a level it\n          // never reached mints nothing, and re-pointing that level up front\n          // -- on the strength of `splitLevel` alone -- would leave the\n          // operation naming a ticket no node ever received, which\n          // `toTreeNodePair` cannot resolve. The rest of THIS entry cannot\n          // wait for the split to return either: those operations run in the\n          // same change, right after it, so the hook fires mid-execution,\n          // while they are still pending. The history stacks could wait, but\n          // are collected here and applied below for a different reason --\n          // the new reverse ops are built from the executed state and must\n          // not be pushed before the stacks are re-pointed.\n          op.onSplitTicketConsumed((index) => {\n            // Read through the operation rather than off `tickets` and a\n            // captured array: an earlier re-point in this same entry may have\n            // replaced `replacedIDs` wholesale (`reconcileNodeID`).\n            const prev = op.getReplacedIDs()[index];\n            if (!prev) {\n              return;\n            }\n            const curr = CRDTTreeNodeID.of(op.getSplitTickets()[index], 0);\n            // Called once per execution, and the change is executed twice\n            // (clone, then root). `repointRest` no longer finds `prev` the\n            // second time, but the pending entry would be a duplicate.\n            if (pending.some((p) => p.op === op && p.prev.equals(prev))) {\n              return;\n            }\n            repointRest(op, prev, curr);\n            pending.push({ op, prev, curr, ticketIndex: index });\n          });\n          splitOps.push(op);\n        }\n      }\n\n      ctx.push(op);\n    }\n\n    const change = ctx.toChange();\n    const actorID = this.changeID.getActorID();\n    const prev = {\n      hadPresence: this.presences.has(actorID),\n      wasOnline: this.status === DocStatus.Attached,\n      presence: this.presences.has(actorID)\n        ? deepcopy(this.presences.get(actorID)!)\n        : undefined,\n    };\n    let executed;\n    try {\n      change.execute(\n        this.clone!.root,\n        this.clone!.presences,\n        OpSource.UndoRedo,\n      );\n      try {\n        executed = change.execute(this.root, this.presences, OpSource.UndoRedo);\n      } catch (err) {\n        // Same hazard as the root pass in `update()`: the operations that ran\n        // burned their tickets into the root, the change is never queued and\n        // `changeID` never advances, so the next change would reissue them.\n        // Burn the lamport, keep `clientSeq`. The caller (`executeUndoRedo`)\n        // drops the clone.\n        if (!ctx.isPresenceOnlyChange()) {\n          this.changeID = ctx\n            .getNextID()\n            .setClientSeq(this.changeID.getClientSeq());\n        }\n        throw err;\n      }\n    } finally {\n      // Detach the handlers whether or not either pass succeeded, so a later\n      // execution of these operations cannot re-point anything and the\n      // closures do not keep the popped entry alive.\n      for (const splitOp of splitOps) {\n        splitOp.onSplitTicketConsumed();\n      }\n    }\n    const { operations, opInfos, reverseOps } = executed;\n    const reverse = ctx.getReversePresence();\n    if (reverse) {\n      reverseOps.push({ type: 'presence', value: reverse });\n    }\n\n    // Now that the operations have run, re-point the history stacks at the\n    // ids this entry actually minted. Deferred to here because the new\n    // reverse ops are built from the executed state, so they already carry\n    // the new ids and must not be pushed before this runs.\n    //\n    // Two things can still make a collected pair false, and both are only\n    // knowable now. `change.execute` skips an operation whose target element\n    // was removed during undo/redo, so it minted nothing at all. And a pair\n    // is collected as the split takes its ticket on WHICHEVER execution runs\n    // first -- the clone -- while the stacks have to follow the root: the\n    // clone and the root are separate trees, so a split that crossed a level\n    // in the clone can stop short of it in the root, leaving a pair naming a\n    // ticket no node in the root ever received. Check the index against what\n    // the root pass reports consuming (`getConsumedSplitTicketCount`, reset\n    // per execution, so it describes the root pass here). Re-issued content\n    // ids carry -1: those are minted unconditionally, once, up front.\n    for (const { op, prev, curr, ticketIndex } of pending) {\n      if (!operations.includes(op)) continue;\n      if (ticketIndex >= 0 && ticketIndex >= op.getConsumedSplitTicketCount()) {\n        continue;\n      }\n      this.internalHistory.reconcileTreeNodeID(\n        op.getParentCreatedAt(),\n        prev,\n        curr,\n      );\n    }\n\n    // And then what the TREE says the split re-created, the same signal the\n    // local `update()` and remote `applyChangeInternal` paths re-point from.\n    // The pairs above come from the reverse op, which names the merge IT\n    // reverses; the split as executed can reverse one this entry never knew\n    // about -- a peer merged two blocks while the undo sat on the stack, and\n    // the redo of an unrelated split separates them again. Neither signal\n    // subsumes the other: the tree derives a pair only where the merge left\n    // `mergedFrom` stamps behind (`CRDTTree.mergeSourceOf`), which a split's\n    // own boundary-deletion undo does not. Both are applied, in that order;\n    // a pair the other already handled sweeps nothing and costs nothing.\n    for (const op of operations) {\n      if (op instanceof TreeEditOperation) {\n        for (const [prev, curr] of op.getSplitRecreatedIDs()) {\n          this.internalHistory.reconcileTreeNodeID(\n            op.getParentCreatedAt(),\n            prev,\n            curr,\n          );\n        }\n      }\n    }\n\n    if (reverseOps.length) {\n      if (isUndo) {\n        this.internalHistory.pushRedo(reverseOps);\n      } else {\n        this.internalHistory.pushUndo(reverseOps);\n      }\n    }\n\n    // NOTE(chacha912): When there is no applied operation or presence\n    // during undo/redo, skip propagating change remotely.\n    //\n    // The test is whether an operation RAN, not whether it produced an\n    // `OpInfo`. Those differ: a style may change CRDT state without anything\n    // an editor could render, because `canStyle` admits a node another client\n    // removed concurrently and a tombstone has no index to report. Gating on\n    // `opInfos` dropped such a reverse style on the floor -- it mutated this\n    // replica and never reached the others, which is the divergence the\n    // `canStyle` contract exists to prevent, reintroduced through undo.\n    //\n    // `change.execute` omits an operation whose target was removed while the\n    // undo was pending (its result is undefined), so that case is still gated\n    // out. What gets through instead is a change that ran and showed nothing,\n    // which costs a redundant change on the wire and never a silent drop.\n    if (!change.hasPresenceChange() && !operations.length) {\n      return;\n    }\n\n    this.localChanges.push(change);\n    this.trackPresenceBase(change);\n    this.mintedOperations ||= operations.length > 0;\n    // Remember the source this change ran under: a replay of the queue has to\n    // use it again. See `Change.isUndoRedo`.\n    change.markAsUndoRedo();\n    this.changeID = ctx.getNextID();\n    this.localChangeObserver.next();\n    const events: DocEvents<P> = [];\n    // Gated on the operations that RAN, not on the `OpInfo`s they produced: an\n    // undo can run and show nothing (a reverse style on a node a peer removed,\n    // a Tree restore whose nodes all land under a removed ancestor), and the\n    // change is still queued above and still consumes a `clientSeq`. Keep\n    // the established public event; persistence uses the separate queue signal.\n    if (operations.length) {\n      events.push({\n        type: DocEventType.LocalChange,\n        source: OpSource.UndoRedo,\n        value: {\n          message: change.getMessage() || '',\n          operations: opInfos,\n          actor: actorID,\n          clientSeq: change.getID().getClientSeq(),\n          serverSeq: change.getID().getServerSeq(),\n        },\n        rawChange: this.isEnableDevtools() ? change.toStruct() : undefined,\n      });\n    }\n    if (change.hasPresenceChange()) {\n      const presenceEvent = this.reconcilePresence(\n        actorID,\n        prev,\n        OpSource.UndoRedo,\n      );\n      if (presenceEvent) {\n        events.push(presenceEvent);\n      }\n    }\n    this.publish(events);\n  }\n}\n","/*\n * Copyright 2025 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SyncMode } from '@yorkie-js/sdk/src/client/client';\nimport { Attachable } from './attachable';\nimport { Document } from '@yorkie-js/sdk/src/document/document';\nimport { SessionLockHandle } from '@yorkie-js/sdk/src/client/session-lock';\n\n/**\n * `WatchStream` represents a stream that watches the changes of a resource.\n * Uses the unified Watch RPC: AsyncIterable<WatchResponse>\n */\nexport type WatchStream = AsyncIterable<unknown>;\n\n/**\n * `WatchStreamCreator` is a function type that creates a watch stream for a resource.\n * It takes an onDisconnect callback and the owned abort controller, and\n * returns a promise that resolves to a tuple of\n * [WatchStream, AbortController] for managing the stream lifecycle.\n */\nexport type WatchStreamCreator = (\n  onDisconnect: (err?: unknown) => void,\n  abortController: AbortController,\n) => Promise<[WatchStream, AbortController]>;\n\n/**\n * `Attachment` is a class that manages the state of an attachable resource (Document or Presence).\n */\nexport class Attachment<R extends Attachable> {\n  resource: R;\n  /**\n   * For Documents: the document's resourceID, available at attach time.\n   * For Channels: the server-issued session_id. Starts empty and is\n   * populated after the first `RefreshChannel` first-call response.\n   */\n  resourceID: string;\n  syncMode?: SyncMode;\n  changeEventReceived?: boolean;\n  /**\n   * `pendingPullPauses` counts `Client.changeSyncMode` calls that stop pulling\n   * (`RealtimePushOnly` or `RealtimeSyncOff`) and have not run yet. The switch\n   * itself waits on the client task queue, behind a sync that may already\n   * have pulled; the response guard reads this so that pull is dropped as\n   * soon as the caller asks for the pause.\n   *\n   * A pull dropped for this count alone is always re-driven: in `Realtime` the\n   * guard re-arms `changeEventReceived`, so it is pulled again even if the\n   * switch behind it never lands, and in `Polling` the interval timer pulls at\n   * the next tick. In `Manual` neither holds — `needRealtimeSync` returns\n   * false for it unconditionally, so the sync loop never revisits the document\n   * and the re-arm would be a no-op — so the guard does not drop on this count\n   * for a Manual document at all. Documents only.\n   */\n  pendingPullPauses = 0;\n  lastHeartbeatTime: number;\n  pollInterval: number;\n  pollIntervalPinned: boolean;\n  /**\n   * `disableGC` is set when the document was attached with\n   * `{ disableGC: true }`. The client sets the matching wire field on\n   * every PushPullChanges so the server can skip minVV tracking and\n   * omit the response VersionVector. Documents only.\n   */\n  disableGC: boolean;\n  /**\n   * `disablePresence` mirrors the server-fixated value returned by the\n   * attach response. `pushPullChanges` does **not** read this — the\n   * `disable_presence` wire field is request-only (set on the first\n   * attach, ignored thereafter on the server side). Carried here for\n   * devtools / debugging visibility. Documents only.\n   */\n  disablePresence: boolean;\n  /**\n   * `unsubscribeLocalBroadcast` is set by `attachChannel` when it forwards\n   * a Channel's `local-broadcast` events to the RPC client, and consumed\n   * by `detachInternal` so the subscription does not survive a detach.\n   * Without this, re-attaching a channel accumulates duplicate handlers\n   * on each attach cycle.\n   */\n  unsubscribeLocalBroadcast?: () => void;\n  /**\n   * `unsubscribePersist` is set by `attachDocument` when the client has an\n   * offline `store` configured: it holds the unsubscribe for the local-change\n   * subscription that persists `doc.toBytes()`. `detachInternal` tears it down\n   * so the subscription does not survive a detach and re-attaches do not\n   * accumulate duplicate persist handlers. Documents only.\n   */\n  unsubscribePersist?: () => void;\n  /**\n   * `sessionLockHandle` is set by `attachDocument` on the offline persistence\n   * path (a `store` is configured): it holds the single-active-session lock for\n   * this document key. `detachInternal` releases it so a later tab can take over.\n   * Documents only.\n   */\n  sessionLockHandle?: SessionLockHandle;\n\n  private reconnectStreamDelay: (err?: unknown) => number;\n  private cancelled: boolean;\n  private watchStream?: WatchStream;\n  private watchLoopTimerID?: ReturnType<typeof setTimeout>;\n  private watchAbortController?: AbortController;\n  private syncPromise?: Promise<void>;\n  private _detaching = false;\n  private _writeRejected = false;\n\n  constructor(\n    reconnectStreamDelay: (err?: unknown) => number,\n    resource: R,\n    resourceID: string = '',\n    syncMode?: SyncMode,\n    pollInterval: number = 0,\n    pollIntervalPinned: boolean = false,\n    disableGC: boolean = false,\n    disablePresence: boolean = false,\n  ) {\n    this.reconnectStreamDelay = reconnectStreamDelay;\n    this.resource = resource;\n    this.resourceID = resourceID;\n    this.syncMode = syncMode;\n    this.changeEventReceived = syncMode !== undefined ? false : undefined;\n    // Initialize to 0 so `needSync`/`needRealtimeSync` return true on the\n    // very first tick. Otherwise the first heartbeat is delayed by one full\n    // poll interval — channels would show stale sessionCount until then.\n    this.lastHeartbeatTime = 0;\n    this.pollInterval = pollInterval;\n    this.pollIntervalPinned = pollIntervalPinned;\n    this.disableGC = disableGC;\n    this.disablePresence = disablePresence;\n    this.cancelled = false;\n  }\n\n  /**\n   * `changeSyncMode` changes the sync mode of the document.\n   */\n  public changeSyncMode(syncMode: SyncMode) {\n    this.syncMode = syncMode;\n  }\n\n  /**\n   * `needRealtimeSync` returns whether the resource needs to be synced in real time.\n   * Only applicable to Document resources with syncMode defined.\n   */\n  public needRealtimeSync(): boolean {\n    if (this.syncMode === SyncMode.RealtimeSyncOff) {\n      return false;\n    }\n\n    if (this.syncMode === SyncMode.RealtimePushOnly) {\n      return this.resource.hasLocalChanges();\n    }\n\n    if (this.syncMode === SyncMode.Polling) {\n      // Time-based: pull at every poll interval, regardless of local changes.\n      return Date.now() - this.lastHeartbeatTime >= this.pollInterval;\n    }\n\n    return (\n      this.syncMode !== SyncMode.Manual &&\n      (this.resource.hasLocalChanges() || (this.changeEventReceived ?? false))\n    );\n  }\n\n  /**\n   * `needSync` determines if the attachment needs sync.\n   * This includes both document sync and presence heartbeat.\n   */\n  public needSync(heartbeatInterval: number): boolean {\n    // For Document: check if realtime sync is needed\n    if (this.resource instanceof Document) {\n      return this.needRealtimeSync();\n    }\n\n    // For Channel in Manual mode: never auto-sync\n    if (this.syncMode === SyncMode.Manual) {\n      return false;\n    }\n\n    // For Channel in Realtime or Polling mode: heartbeat at the\n    // attachment's own interval (falls back to client-level value if zero).\n    const interval =\n      this.pollInterval > 0 ? this.pollInterval : heartbeatInterval;\n    return Date.now() - this.lastHeartbeatTime >= interval;\n  }\n\n  /**\n   * `updateHeartbeatTime` updates the last heartbeat time.\n   */\n  public updateHeartbeatTime(): void {\n    this.lastHeartbeatTime = Date.now();\n  }\n\n  /**\n   * `runWatchLoop` runs the watch loop.\n   */\n  public async runWatchLoop(\n    watchStreamCreator: WatchStreamCreator,\n  ): Promise<void> {\n    const doLoop = async (): Promise<void> => {\n      if (this.cancelled || this.watchStream || this.watchAbortController) {\n        return;\n      }\n      if (this.watchLoopTimerID) {\n        clearTimeout(this.watchLoopTimerID);\n        this.watchLoopTimerID = undefined;\n      }\n\n      // Own cancellation before the first response, not only after init.\n      const ac = new AbortController();\n      this.watchAbortController = ac;\n      try {\n        const [stream] = await watchStreamCreator((err) => {\n          // A cancelled stream must not clear or reconnect its successor.\n          if (this.watchAbortController !== ac) {\n            return;\n          }\n          this.watchStream = undefined;\n          this.watchAbortController = undefined;\n          if (!this.cancelled) {\n            this.watchLoopTimerID = setTimeout(\n              doLoop,\n              this.reconnectStreamDelay(err),\n            );\n          }\n        }, ac);\n        if (this.watchAbortController === ac && !ac.signal.aborted) {\n          this.watchStream = stream;\n        }\n      } catch {\n        if (this.watchAbortController === ac) {\n          this.watchAbortController = undefined;\n        }\n      }\n    };\n\n    await doLoop();\n  }\n\n  /**\n   * `markDetaching` marks this attachment as being in the process of detaching.\n   * Once marked, the sync loop will skip this attachment.\n   */\n  public markDetaching(): void {\n    this._detaching = true;\n  }\n\n  /**\n   * `isDetaching` returns whether this attachment is being detached.\n   */\n  public isDetaching(): boolean {\n    return this._detaching;\n  }\n\n  /**\n   * `resetDetaching` resets the detaching flag so the attachment can resume\n   * syncing. Used when a detach RPC fails and the document remains attached.\n   */\n  public resetDetaching(): void {\n    this._detaching = false;\n  }\n\n  /**\n   * `markWriteRejected` marks this attachment as holding changes the server\n   * refused to store (`ErrDocumentSizeExceedsLimit`, `ErrChangeTooLarge`).\n   * The sync loop then skips this attachment alone, instead of the rejection\n   * taking down the loop shared by every other attachment of the client.\n   * Documents only.\n   */\n  public markWriteRejected(): void {\n    this._writeRejected = true;\n  }\n\n  /**\n   * `isWriteRejected` returns whether the sync loop should skip this\n   * attachment because the server rejected its last push outright.\n   */\n  public isWriteRejected(): boolean {\n    return this._writeRejected;\n  }\n\n  /**\n   * `clearWriteRejected` lets the sync loop pick this attachment up again,\n   * once a push has been accepted — an explicit `client.sync(doc)` after the\n   * document was shrunk is the way back in.\n   */\n  public clearWriteRejected(): void {\n    this._writeRejected = false;\n  }\n\n  /**\n   * `setSyncPromise` sets the in-progress sync promise for this attachment.\n   */\n  public setSyncPromise(promise: Promise<void>): void {\n    this.syncPromise = promise;\n  }\n\n  /**\n   * `clearSyncPromise` clears the in-progress sync promise.\n   */\n  public clearSyncPromise(): void {\n    this.syncPromise = undefined;\n  }\n\n  /**\n   * `waitForSyncComplete` waits for any in-progress sync to complete.\n   */\n  public async waitForSyncComplete(): Promise<void> {\n    if (this.syncPromise) {\n      try {\n        await this.syncPromise;\n      } catch {\n        // Ignore sync errors — we just need it to finish\n      }\n    }\n  }\n\n  /**\n   * `resetCancelled` clears the cancelled flag so the watch loop can run again\n   * after a previous cancellation (e.g., after changeSyncMode back to Realtime).\n   * Caller must invoke `runWatchLoop` immediately after to claim the stream slot;\n   * `doLoop`'s controller ownership guard prevents double-stream creation if a\n   * delayed `onDisconnect` callback from the previously-cancelled stream races.\n   */\n  public resetCancelled(): void {\n    this.cancelled = false;\n  }\n\n  /**\n   * `cancelWatchStream` cancels the watch stream.\n   */\n  public cancelWatchStream(): void {\n    this.cancelled = true;\n\n    const ac = this.watchAbortController;\n    this.watchStream = undefined;\n    this.watchAbortController = undefined;\n    ac?.abort();\n    clearTimeout(this.watchLoopTimerID);\n    this.watchLoopTimerID = undefined;\n  }\n}\n","/*\n * Copyright 2021 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Interceptor } from '@connectrpc/connect';\n\n/**\n * `createAuthInterceptor` creates an interceptor to add the Authorization header for each\n * request.\n */\nexport function createAuthInterceptor(\n  apiKey?: string,\n  token?: string,\n): {\n  authInterceptor: Interceptor;\n  setToken: (token: string) => void;\n} {\n  let currentToken = token;\n\n  const setToken = (token: string) => {\n    currentToken = token;\n  };\n\n  const authInterceptor: Interceptor = (next) => async (req) => {\n    if (apiKey) {\n      req.header.set('x-api-key', apiKey);\n    }\n    if (currentToken) {\n      req.header.set('authorization', currentToken);\n    }\n    return await next(req);\n  };\n\n  return {\n    authInterceptor,\n    setToken,\n  };\n}\n","/*\n * Copyright 2021 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport pkg from '../../package.json';\nimport { Interceptor } from '@connectrpc/connect';\n\n/**\n * `createMetricInterceptor` creates an interceptor to add the x-yorkie-user-agent header for each\n * request.\n */\nexport function createMetricInterceptor(userAgent?: string): Interceptor {\n  return (next) => async (req) => {\n    if (userAgent) {\n      req.header.set('x-yorkie-user-agent', userAgent);\n    } else {\n      req.header.set('x-yorkie-user-agent', pkg.name + '/' + pkg.version);\n    }\n    return await next(req);\n  };\n}\n","/*\n * Copyright 2024 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * `validateSerializable` returns whether the given value is serializable or not.\n */\nexport const validateSerializable = (value: unknown): boolean => {\n  try {\n    const serialized = JSON.stringify(value);\n\n    if (serialized === undefined) {\n      return false;\n    }\n  } catch {\n    return false;\n  }\n  return true;\n};\n","/*\n * Copyright 2025 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ActorID } from '@yorkie-js/sdk/src/document/time/actor_id';\nimport { Attachable } from '@yorkie-js/sdk/src/client/attachable';\nimport {\n  createObservable,\n  NextFn,\n  Observer,\n  Unsubscribe,\n} from '@yorkie-js/sdk/src/util/observable';\nimport { Json } from '../yorkie';\n\n/**\n * Observable interface for subscribing to presence events.\n */\nexport interface Observable<T> {\n  subscribe(observer: (event: T) => void): Unsubscribe;\n}\n\n/**\n * `PresenceStatus` represents the status of the presence.\n */\nexport enum ChannelStatus {\n  /**\n   * `Detached` means that the presence is not attached to the client.\n   */\n  Detached = 'detached',\n\n  /**\n   * `Attached` means that the presence is attached to the client.\n   */\n  Attached = 'attached',\n\n  /**\n   * `Removed` means that the presence is removed.\n   */\n  Removed = 'removed',\n}\n\n/**\n * `BroadcastOptions` are the options for broadcasting a message.\n */\nexport interface BroadcastOptions {\n  /**\n   * `error` is called when an error occurs.\n   */\n  error?: (error: Error) => void;\n\n  /**\n   * `maxRetries` is the maximum number of retries.\n   */\n  maxRetries?: number;\n}\n\n/**\n * `ChannelEventType` represents the type of channel event.\n */\nexport enum ChannelEventType {\n  /**\n   * `Changed` means that the presence has changed.\n   */\n  PresenceChanged = 'presence-changed',\n\n  /**\n   * `Initialized` means that the presence watch has been initialized.\n   */\n  Initialized = 'initialized',\n\n  /**\n   * `Broadcast` means that a broadcast message has been received.\n   */\n  Broadcast = 'broadcast',\n\n  /**\n   * `LocalBroadcast` means that a broadcast message has been sent by the local client.\n   */\n  LocalBroadcast = 'local-broadcast',\n\n  /**\n   * `AuthError` means that an authentication error has occurred.\n   */\n  AuthError = 'auth-error',\n\n  /**\n   * `SyncError` means that a non-recoverable sync (RefreshChannel) error\n   * occurred. Subscribers can use this to render an error state in the UI\n   * without polling internal SDK state. The SDK still retries via its sync\n   * loop, so subsequent successful events (PresenceChanged/Initialized) can\n   * be treated as recovery.\n   */\n  SyncError = 'sync-error',\n}\n\n/**\n * `PresenceEvent` represents a presence change event.\n */\nexport interface PresenceEvent {\n  /**\n   * `type` is the type of the event.\n   */\n  type: ChannelEventType.PresenceChanged | ChannelEventType.Initialized;\n\n  /**\n   * `count` is the current count value.\n   */\n  count: number;\n}\n\nexport interface BroadcastEvent {\n  type: ChannelEventType.Broadcast;\n  clientID: ActorID;\n  topic: string;\n  payload: Json;\n  options?: BroadcastOptions;\n}\n\nexport interface LocalBroadcastEvent {\n  type: ChannelEventType.LocalBroadcast;\n  clientID: ActorID;\n  topic: string;\n  payload: Json;\n  options?: BroadcastOptions;\n}\n\n/**\n * `AuthErrorEvent` represents an authentication error event.\n */\nexport interface AuthErrorEvent {\n  /**\n   * `type` is the type of the event.\n   */\n  type: ChannelEventType.AuthError;\n\n  /**\n   * `reason` is the reason for the authentication error.\n   */\n  reason: string;\n\n  /**\n   * `method` is the method that caused the authentication error.\n   */\n  method: string;\n}\n\n/**\n * `SyncErrorEvent` represents a non-recoverable sync (RefreshChannel) error.\n * It carries the underlying error object so subscribers can inspect codes\n * (e.g. via `isErrorCode`) without losing the original Error.\n */\nexport interface SyncErrorEvent {\n  /**\n   * `type` is the type of the event.\n   */\n  type: ChannelEventType.SyncError;\n\n  /**\n   * `error` is the underlying error thrown by the RPC call.\n   */\n  error: unknown;\n\n  /**\n   * `method` is the RPC method that failed (e.g. `RefreshChannel`).\n   */\n  method: string;\n}\n\n/**\n * `ChannelEvent` represents an event that occurs in the channel.\n */\nexport type ChannelEvent =\n  | PresenceEvent\n  | BroadcastEvent\n  | LocalBroadcastEvent\n  | AuthErrorEvent\n  | SyncErrorEvent;\n\n/**\n * `ChannelEventCallbackMap` represents a map of event types to callbacks.\n */\nexport type ChannelEventCallbackMap = {\n  broadcast: NextFn<BroadcastEvent>;\n  'local-broadcast': NextFn<LocalBroadcastEvent>;\n  'auth-error': NextFn<AuthErrorEvent>;\n  'sync-error': NextFn<SyncErrorEvent>;\n  presence: NextFn<PresenceEvent>;\n  all: NextFn<ChannelEvent>;\n};\n\n/**\n * KeyPathSeparator is the separator for key paths in a channel key.\n */\nconst KeyPathSeparator = '.';\n\n/**\n * `Channel` represents a lightweight channel for presence and messaging.\n */\nexport class Channel implements Observable<ChannelEvent>, Attachable {\n  private key: string;\n  private status: ChannelStatus;\n  private actorID?: ActorID;\n  private sessionID?: string;\n  private sessionCount: number;\n  private seq: number;\n\n  private eventStream: Observable<ChannelEvent>;\n  private eventStreamObserver!: Observer<ChannelEvent>;\n\n  /**\n   * @param key - the key of the channel.\n   */\n  constructor(key: string) {\n    this.validateChannelKey(key);\n    this.key = key;\n    this.status = ChannelStatus.Detached;\n    this.sessionCount = 0;\n    this.seq = 0;\n    this.eventStream = createObservable<ChannelEvent>(\n      (observer) => (this.eventStreamObserver = observer),\n    );\n  }\n\n  /**\n   * `getKey` returns the key of this channel.\n   */\n  public getKey(): string {\n    return this.key;\n  }\n\n  /**\n   * `getFirstKeyPath` returns the first key path to the presence count.\n   */\n  public getFirstKeyPath(): string {\n    return this.key.split(KeyPathSeparator)[0];\n  }\n\n  /**\n   * `getStatus` returns the status of this channel.\n   */\n  public getStatus(): ChannelStatus {\n    return this.status;\n  }\n\n  /**\n   * `applyStatus` applies the channel status into this channel.\n   */\n  public applyStatus(status: ChannelStatus): void {\n    this.status = status;\n  }\n\n  /**\n   * `isAttached` returns whether this channel is attached or not.\n   */\n  public isAttached(): boolean {\n    return this.status === ChannelStatus.Attached;\n  }\n\n  /**\n   * `getActorID` returns the actor ID of this channel.\n   */\n  public getActorID(): ActorID | undefined {\n    return this.actorID;\n  }\n\n  /**\n   * `setActor` sets the actor ID into this channel.\n   */\n  public setActor(actorID: ActorID): void {\n    this.actorID = actorID;\n  }\n\n  /**\n   * `getSessionID` returns the session ID from the server.\n   */\n  public getSessionID(): string | undefined {\n    return this.sessionID;\n  }\n\n  /**\n   * `setSessionID` sets the session ID from the server.\n   */\n  public setSessionID(sessionID: string): void {\n    this.sessionID = sessionID;\n  }\n\n  /**\n   * `getSessionCount` returns the current channel online session count value.\n   */\n  public getSessionCount(): number {\n    return this.sessionCount;\n  }\n\n  /**\n   * `updateSessionCount` updates the session count and sequence number if the sequence is newer.\n   * Returns true if the count was updated, false if the update was ignored.\n   */\n  public updateSessionCount(sessionCount: number, seq: number): boolean {\n    // Always accept initialization (seq === 0)\n    if (seq === 0 || seq > this.seq) {\n      this.sessionCount = sessionCount;\n      this.seq = seq;\n      return true;\n    }\n\n    return false;\n  }\n\n  /**\n   * `hasLocalChanges` returns whether this channel has local changes or not.\n   * Channel is server-managed, so it always returns false.\n   */\n  public hasLocalChanges(): boolean {\n    // NOTE(hackerwins): Consider to keep broadcast messages locally in the future.\n    return false;\n  }\n\n  /**\n   * `subscribe` registers a callback to subscribe to events on the channel.\n   * The callback will be called when the broadcast event is received from the remote client.\n   */\n  public subscribe(\n    type: 'broadcast',\n    next: ChannelEventCallbackMap['broadcast'],\n  ): Unsubscribe;\n  /**\n   * `subscribe` registers a callback to subscribe to events on the channel.\n   * The callback will be called when the local client sends a broadcast event.\n   */\n  public subscribe(\n    type: 'local-broadcast',\n    next: ChannelEventCallbackMap['local-broadcast'],\n  ): Unsubscribe;\n  /**\n   * `subscribe` registers a callback to subscribe to events on the channel.\n   * The callback will be called when an authentication error occurs.\n   */\n  public subscribe(\n    type: 'auth-error',\n    next: ChannelEventCallbackMap['auth-error'],\n  ): Unsubscribe;\n  /**\n   * `subscribe` registers a callback to subscribe to non-recoverable sync\n   * (RefreshChannel) errors. Subsequent successful events on the channel\n   * imply recovery — there is no separate \"recovered\" event.\n   */\n  public subscribe(\n    type: 'sync-error',\n    next: ChannelEventCallbackMap['sync-error'],\n  ): Unsubscribe;\n  /**\n   * `subscribe` registers a callback to subscribe to presence events on the channel.\n   * The callback will be called when the presence count changes.\n   */\n  public subscribe(\n    type: 'presence',\n    next: ChannelEventCallbackMap['presence'],\n  ): Unsubscribe;\n  /**\n   * `subscribe` registers a callback to subscribe to all events on the channel.\n   */\n  public subscribe(\n    type: 'all',\n    next: ChannelEventCallbackMap['all'],\n  ): Unsubscribe;\n  /**\n   * `subscribe` registers a callback to subscribe to broadcast events for a specific topic.\n   * The callback will be called when a broadcast event with the matching topic is received.\n   */\n  public subscribe(topic: string, next: NextFn<BroadcastEvent>): Unsubscribe;\n  /**\n   * `subscribe` registers an observer for all channel events.\n   * Returns an unsubscribe function.\n   */\n  public subscribe(arg1: NextFn<ChannelEvent>): Unsubscribe;\n\n  /**\n   * `subscribe` implementation.\n   */\n  public subscribe(\n    arg1:\n      | 'broadcast'\n      | 'local-broadcast'\n      | 'auth-error'\n      | 'sync-error'\n      | 'presence'\n      | 'all'\n      | string\n      | NextFn<ChannelEvent>,\n    arg2?:\n      | ChannelEventCallbackMap['broadcast']\n      | ChannelEventCallbackMap['local-broadcast']\n      | ChannelEventCallbackMap['auth-error']\n      | ChannelEventCallbackMap['sync-error']\n      | ChannelEventCallbackMap['presence']\n      | ChannelEventCallbackMap['all']\n      | NextFn<BroadcastEvent>,\n  ): Unsubscribe {\n    if (typeof arg1 === 'function') {\n      return this.eventStream.subscribe(arg1);\n    }\n\n    const typeOrTopic = arg1;\n    const callback = arg2;\n\n    if (!callback) {\n      throw new Error(\n        'callback is required when subscribing to specific event type or topic',\n      );\n    }\n\n    // Handle reserved event types\n    if (typeOrTopic === 'broadcast') {\n      return this.eventStream.subscribe((event) => {\n        if (event.type === ChannelEventType.Broadcast) {\n          (callback as ChannelEventCallbackMap['broadcast'])(event);\n        }\n      });\n    }\n\n    if (typeOrTopic === 'local-broadcast') {\n      return this.eventStream.subscribe((event) => {\n        if (event.type === ChannelEventType.LocalBroadcast) {\n          (callback as ChannelEventCallbackMap['local-broadcast'])(event);\n        }\n      });\n    }\n\n    if (typeOrTopic === 'auth-error') {\n      return this.eventStream.subscribe((event) => {\n        if (event.type === ChannelEventType.AuthError) {\n          (callback as ChannelEventCallbackMap['auth-error'])(event);\n        }\n      });\n    }\n\n    if (typeOrTopic === 'sync-error') {\n      return this.eventStream.subscribe((event) => {\n        if (event.type === ChannelEventType.SyncError) {\n          (callback as ChannelEventCallbackMap['sync-error'])(event);\n        }\n      });\n    }\n\n    if (typeOrTopic === 'presence') {\n      return this.eventStream.subscribe((event) => {\n        if (\n          event.type === ChannelEventType.PresenceChanged ||\n          event.type === ChannelEventType.Initialized\n        ) {\n          (callback as ChannelEventCallbackMap['presence'])(event);\n        }\n      });\n    }\n\n    if (typeOrTopic === 'all') {\n      return this.eventStream.subscribe(callback as NextFn<ChannelEvent>);\n    }\n\n    // Handle topic-based subscription for broadcast events\n    const topic = typeOrTopic;\n    return this.eventStream.subscribe((event) => {\n      if (event.type === ChannelEventType.Broadcast && event.topic === topic) {\n        (callback as NextFn<BroadcastEvent>)(event);\n      }\n    });\n  }\n\n  /**\n   * `publish` publishes an event to all registered handlers.\n   */\n  public publish(event: ChannelEvent): void {\n    if (this.eventStreamObserver) {\n      this.eventStreamObserver.next(event);\n    }\n  }\n\n  /**\n   * `broadcast` sends a message to all clients watching this channel.\n   */\n  public broadcast(\n    topic: string,\n    payload: any,\n    options?: BroadcastOptions,\n  ): void {\n    if (this.status !== ChannelStatus.Attached) {\n      throw new Error(`channel is not attached: ${this.status}`);\n    }\n\n    if (!this.actorID) {\n      throw new Error('actorID is not set');\n    }\n\n    this.publish({\n      type: ChannelEventType.LocalBroadcast,\n      clientID: this.actorID,\n      topic,\n      payload,\n      options,\n    });\n  }\n\n  private validateChannelKey(key: string): void {\n    if (key === '') {\n      throw new Error('channel key must not be empty');\n    }\n    if (key.includes(' ')) {\n      throw new Error('channel key must not contain a whitespace');\n    }\n    if (key.startsWith(KeyPathSeparator)) {\n      throw new Error('channel key must not start with a period');\n    }\n    if (key.endsWith(KeyPathSeparator)) {\n      throw new Error('channel key must not end with a period');\n    }\n    if (key.includes(`${KeyPathSeparator}${KeyPathSeparator}`)) {\n      throw new Error('channel key path must not empty');\n    }\n  }\n}\n","/*\n * Copyright 2026 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * `MinLogBytes` is the floor below which a log never triggers compaction.\n * Without it the ratio alone would make the smallest documents the busiest: a\n * 500-byte document would compact after two changes.\n */\nexport const MinLogBytes = 64 * 1024;\n\n/**\n * `LogRatio` is the share of the snapshot's size the log may reach before it\n * is worth re-snapshotting.\n */\nexport const LogRatio = 0.5;\n\n/**\n * `MaxReplay` bounds how many changes a restore has to replay. This is a\n * latency budget rather than a storage one, which is why it is separate from\n * the byte rule.\n */\nexport const MaxReplay = 1000;\n\n/**\n * `PersistState` is what the compaction decision is made from.\n */\nexport interface PersistState {\n  /** Size of the stored snapshot the log is appended to. */\n  snapshotBytes: number;\n  /** Total size of the appended change log. */\n  logBytes: number;\n  /** Number of appended changes. */\n  changeCount: number;\n}\n\n/**\n * `shouldCompact` decides whether the appended log has grown enough to be\n * worth replacing with a fresh snapshot.\n *\n * The threshold is **relative to the snapshot**, not a constant, because the\n * point at which appending stops paying is a function of what it is appended\n * to. Measured, an 8,000-cell sheet's log reaches its snapshot's size after\n * roughly 6,300 edits while a 5,000-character note's does after roughly 50 —\n * two orders of magnitude apart, so no single count or byte figure serves\n * both.\n *\n * Making it relative also removes the pathological case by construction. A\n * small document compacts often, which is harmless precisely because its\n * snapshot is small and serializes in about a millisecond; a large one\n * compacts rarely, so its expensive serialization is divided across thousands\n * of edits. Cost and threshold scale with the same quantity, so \"compacts\n * frequently *and* expensively\" is unreachable.\n */\nexport function shouldCompact(state: PersistState): boolean {\n  if (state.changeCount > MaxReplay) {\n    return true;\n  }\n  return state.logBytes > Math.max(MinLogBytes, state.snapshotBytes * LogRatio);\n}\n","/*\n * Copyright 2026 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, YorkieError } from '@yorkie-js/sdk/src/util/error';\n\n/**\n * `SessionLockHandle` represents an acquired, held session lock. It is held for\n * the lifetime of a document attachment and released on detach/deactivate.\n */\nexport interface SessionLockHandle {\n  /**\n   * `release` releases the held lock so a later tab can acquire it. It must be\n   * idempotent: calling it more than once is a no-op.\n   */\n  release(): void;\n}\n\n/**\n * `SessionLock` is a pluggable, single-active-session guard used by the offline\n * persistence path. Offline persistence derives a *stable* actor from the app's\n * clientKey, so two browser tabs of the same app+user share that actor. Two live\n * tabs would then share one server checkpoint and mint colliding `clientSeq`\n * values — silent edit loss. The guard elects a single active session per\n * document key so the second tab fails fast instead of corrupting the store.\n *\n * The abstraction is injectable so it can be tested without a real browser: the\n * default {@link WebLocksSessionLock} is backed by the Web Locks API, and tests\n * pass an in-memory fake.\n */\nexport interface SessionLock {\n  /**\n   * `acquire` tries to acquire the lock named `name` without waiting. It\n   * resolves with a {@link SessionLockHandle} when the lock was acquired, or\n   * `undefined` when it is already held elsewhere (e.g. by another tab) — the\n   * caller treats `undefined` as fail-fast.\n   */\n  acquire(name: string): Promise<SessionLockHandle | undefined>;\n}\n\n/**\n * `hasWebLocks` reports whether the Web Locks API is available in the current\n * runtime. It is absent in Node, workers without the API, and older browsers.\n */\nfunction hasWebLocks(): boolean {\n  return (\n    typeof navigator !== 'undefined' &&\n    !!navigator.locks &&\n    typeof navigator.locks.request === 'function'\n  );\n}\n\n/**\n * `WebLocksSessionLock` is the default {@link SessionLock}, backed by the Web\n * Locks API (`navigator.locks.request` with `{ ifAvailable: true }`).\n *\n * A Web Lock is held for as long as the promise returned from the request's\n * callback stays pending. To hold the lock for the whole attachment lifetime,\n * `acquire` keeps that callback pending on a promise that only resolves when the\n * returned handle's `release` is called. When the lock is already held (another\n * tab), `ifAvailable` invokes the callback with a `null` lock and `acquire`\n * resolves `undefined` — the fail-fast signal.\n *\n * When the Web Locks API is unavailable (non-browser runtimes), this is a no-op:\n * `acquire` always resolves a handle whose `release` does nothing, so it never\n * breaks non-browser usage. Multi-tab safety simply does not apply there.\n */\nexport class WebLocksSessionLock implements SessionLock {\n  /**\n   * `acquire` acquires the named lock without waiting, or resolves `undefined`\n   * when it is already held elsewhere.\n   */\n  public acquire(name: string): Promise<SessionLockHandle | undefined> {\n    if (!hasWebLocks()) {\n      // No Web Locks in this runtime: treat as always available (no-op guard).\n      return Promise.resolve({ release: () => {} });\n    }\n\n    return new Promise<SessionLockHandle | undefined>(\n      (resolveAcquire, reject) => {\n        // `releaseHeld` resolves the callback's held promise, which is what\n        // releases the underlying Web Lock. Set once the callback runs.\n        let releaseHeld: (() => void) | undefined;\n        let released = false;\n\n        navigator\n          .locks!.request(name, { ifAvailable: true }, (lock) => {\n            if (!lock) {\n              // Held by another tab: fail fast.\n              resolveAcquire(undefined);\n              return;\n            }\n\n            // Hold the lock until `release` is called on the returned handle.\n            return new Promise<void>((resolveHeld) => {\n              releaseHeld = resolveHeld;\n              resolveAcquire({\n                release: () => {\n                  if (released) {\n                    return;\n                  }\n                  released = true;\n                  releaseHeld?.();\n                },\n              });\n            });\n          })\n          .catch(reject);\n      },\n    );\n  }\n}\n\n/**\n * `acquireSessionLock` runs the single-active-session decision the store-backed\n * `attach` makes: take the lock, and translate an absent handle — the\n * fail-fast signal — into a rejected attach carrying\n * {@link Code.ErrDocumentOpenElsewhere}.\n *\n * It lives here, rather than inline in `attach`, so the decision has exactly\n * one implementation. A test that re-states it would pass while the real path\n * regressed, which is the failure mode this guard can least afford: getting it\n * wrong means two tabs sharing one checkpoint and silently losing edits.\n */\nexport async function acquireSessionLock(\n  lock: SessionLock,\n  name: string,\n  docKey: string,\n): Promise<SessionLockHandle> {\n  const handle = await lock.acquire(name);\n  if (!handle) {\n    throw new YorkieError(\n      Code.ErrDocumentOpenElsewhere,\n      `document \"${docKey}\" is already open in another tab under offline ` +\n        `persistence; only one active session per document is allowed to ` +\n        `avoid silent edit loss`,\n    );\n  }\n  return handle;\n}\n","/*\n * Copyright 2025 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WatchStream } from '@yorkie-js/sdk/src/client/attachment';\nimport { Code, YorkieError } from '@yorkie-js/sdk/src/util/error';\nimport { WatchResponse } from '@yorkie-js/sdk/src/api/yorkie/v1/yorkie_pb';\n\n/**\n * `WatchIdleTimeoutFactor` multiplies the heartbeat interval the server\n * advertises to get how long a silent stream is given before it is treated as\n * half-open. More than one interval, so a single late or dropped heartbeat\n * does not tear down a stream that is merely slow.\n */\nconst WatchIdleTimeoutFactor = 3;\n\n/**\n * `WatchIdleTimeoutMin` floors the timeout. The interval arrives off the wire,\n * so a server advertising a handful of milliseconds would otherwise time every\n * stream out as soon as it came up and spin the reconnect loop.\n */\nconst WatchIdleTimeoutMin = 1000;\n\n/**\n * `WatchIdleTimeoutMax` caps the timeout, so a nonsensical interval cannot\n * overflow `setTimeout`, which fires at once for delays above 2^31-1 ms.\n */\nconst WatchIdleTimeoutMax = 24 * 60 * 60 * 1000;\n\n/**\n * `watchIdleTimeout` returns how long, in milliseconds, a watch stream may\n * stay silent before it is treated as half-open, given the heartbeat interval\n * the server advertised. A server that sends no heartbeats advertises 0 and\n * gets 0 back: nothing is expected to arrive on a quiet stream, so nothing may\n * time one out.\n */\nexport function watchIdleTimeout(heartbeatIntervalMs: number): number {\n  if (!(heartbeatIntervalMs > 0)) {\n    return 0;\n  }\n\n  return Math.min(\n    Math.max(heartbeatIntervalMs * WatchIdleTimeoutFactor, WatchIdleTimeoutMin),\n    WatchIdleTimeoutMax,\n  );\n}\n\n/**\n * `watchHeartbeatInterval` returns the heartbeat interval, in milliseconds, a\n * watch init response advertises. A server older than the heartbeat, or one\n * with it turned off, advertises 0.\n */\nexport function watchHeartbeatInterval(resp: WatchResponse): number {\n  return resp.body.case === 'initialization'\n    ? Number(resp.body.value.heartbeatIntervalMs)\n    : 0;\n}\n\n/**\n * `WatchStreamConfig` contains callbacks for handling the watch stream lifecycle.\n */\nexport interface WatchStreamConfig<Resp> {\n  /** The async iterable stream of responses. */\n  stream: AsyncIterable<Resp>;\n  /** The AbortController to cancel the stream. */\n  ac: AbortController;\n  /** Returns true if the response is the init (first) response. */\n  isInit: (resp: Resp) => boolean;\n  /**\n   * Returns the heartbeat interval, in milliseconds, the server advertised in\n   * the init response; 0 when it sends none. A non-zero interval arms the idle\n   * watchdog.\n   */\n  heartbeatIntervalOf: (init: Resp) => number;\n  /** Called for each response from the stream. */\n  onResponse: (resp: Resp) => void;\n  /** Called when the stream ends normally. */\n  onStreamEnd: () => void;\n  /** Called when the stream encounters an error. */\n  onError: (err: unknown) => void;\n  /**\n   * Called when reconnection should be attempted, with the retryable error\n   * that ended the stream, if one did.\n   */\n  onDisconnect: (err?: unknown) => void;\n  /** Returns true if the error should be silently ignored (e.g. AbortError). */\n  shouldIgnoreError?: (err: unknown) => boolean;\n}\n\n/**\n * `runWatchStream` runs a watch stream and returns a promise that resolves\n * with the stream and AbortController on the first (init) response.\n *\n * This extracts the shared `Promise + async for-await + error handling`\n * pattern from document and channel watch streams.\n */\nexport function runWatchStream<Resp>(\n  config: WatchStreamConfig<Resp>,\n  handleConnectError: (err: unknown) => Promise<boolean>,\n  setWatchLoopInactive: () => void,\n): Promise<[WatchStream, AbortController]> {\n  const {\n    stream,\n    ac,\n    isInit,\n    heartbeatIntervalOf,\n    onResponse,\n    onStreamEnd,\n    onError,\n    onDisconnect,\n    shouldIgnoreError,\n  } = config;\n\n  return new Promise((resolve, reject) => {\n    // The idle watchdog aborts the stream when nothing, heartbeat or event,\n    // arrives within the timeout. It is armed only after the init response:\n    // the server's handshake includes an auth webhook with retries the client\n    // has no basis to bound.\n    let idleTimeout = 0;\n    let idleTimer: ReturnType<typeof setTimeout> | undefined;\n    let lastActivity = 0;\n    let idled = false;\n\n    // One timer per stream: a response only records the time, and the timer\n    // re-arms itself for what is left of the timeout, so a busy stream does\n    // not create and cancel a timer per response.\n    const onIdleTimer = () => {\n      // A stream the client already aborted is not idle, whichever of the\n      // abort and this timer the transport gets to first.\n      if (ac.signal.aborted) {\n        return;\n      }\n\n      const remaining = lastActivity + idleTimeout - Date.now();\n      if (remaining > 0) {\n        idleTimer = setTimeout(onIdleTimer, remaining);\n        return;\n      }\n\n      // Reconnect from here rather than once the stream unwinds: a transport\n      // need not settle a read that is pending on a half-open socket, and\n      // over Node's fetch it does not. Whatever the old stream does after\n      // this is ignored below.\n      idled = true;\n      ac.abort();\n      onError(\n        new YorkieError(\n          Code.ErrWatchStreamIdle,\n          `watch stream is idle for ${idleTimeout}ms`,\n        ),\n      );\n      onDisconnect();\n    };\n\n    // Settle an opening watch even if the transport never finishes its read.\n    const onAbort = () => {\n      clearTimeout(idleTimer);\n      // Publish the intentional disconnect off this stack, not on it.\n      // `cancelWatchStream()` aborts from inside `detachInternal`, which runs\n      // under `deactivateInternal`'s iteration over the attachment map, and\n      // `onStreamEnd` publishes document events whose subscribers may call\n      // back into the client. A microtask still runs before any awaited\n      // continuation, so the disconnect is published ahead of the reconnect\n      // the loop schedules on a timer — just not re-entrantly.\n      if (!idled) {\n        queueMicrotask(onStreamEnd);\n      }\n      reject(ac.signal.reason);\n    };\n    ac.signal.addEventListener('abort', onAbort, { once: true });\n    if (ac.signal.aborted) {\n      onAbort();\n      return;\n    }\n\n    const handleStream = async () => {\n      try {\n        let resolved = false;\n        for await (const resp of stream) {\n          // A successor already owns the watch; drop what the old stream\n          // still had buffered.\n          if (idled || ac.signal.aborted) {\n            break;\n          }\n\n          lastActivity = Date.now();\n          onResponse(resp);\n          if (idled || ac.signal.aborted) {\n            break;\n          }\n\n          if (!resolved && isInit(resp)) {\n            resolved = true;\n            idleTimeout = watchIdleTimeout(heartbeatIntervalOf(resp));\n            if (idleTimeout > 0) {\n              idleTimer = setTimeout(onIdleTimer, idleTimeout);\n            }\n            resolve([stream, ac]);\n          }\n        }\n\n        if (idled || ac.signal.aborted) {\n          return;\n        }\n\n        // Stream ended normally\n        onStreamEnd();\n        onDisconnect();\n      } catch (err) {\n        // The stream is over; the timer must not fire during the await below.\n        clearTimeout(idleTimer);\n\n        if (idled || ac.signal.aborted) {\n          return;\n        }\n\n        if (shouldIgnoreError && shouldIgnoreError(err)) {\n          return;\n        }\n\n        onError(err);\n        if (idled || ac.signal.aborted) {\n          return;\n        }\n\n        const retry = await handleConnectError(err);\n        if (idled || ac.signal.aborted) {\n          return;\n        }\n        if (retry) {\n          onDisconnect(err);\n        } else {\n          setWatchLoopInactive();\n        }\n\n        reject(err);\n      } finally {\n        ac.signal.removeEventListener('abort', onAbort);\n        clearTimeout(idleTimer);\n      }\n    };\n\n    handleStream();\n  });\n}\n","/*\n * Copyright 2020 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ActorID } from '@yorkie-js/sdk/src/document/time/actor_id';\nimport {\n  createClient as createConnectClient,\n  Client as ConnectClient,\n  ConnectError,\n  Code as ConnectCode,\n} from '@connectrpc/connect';\nimport {\n  createConnectTransport,\n  createGrpcWebTransport,\n} from '@connectrpc/connect-web';\nimport {\n  YorkieService,\n  WatchResponse,\n} from '@yorkie-js/sdk/src/api/yorkie/v1/yorkie_pb';\nimport {\n  DocEventType as PbDocEventType,\n  ChannelEvent_Type as PbChannelEventType,\n  ChangePack as PbChangePack,\n} from '@yorkie-js/sdk/src/api/yorkie/v1/resources_pb';\nimport {\n  converter,\n  errorCodeOf,\n  errorMetadataOf,\n  isErrorCode,\n} from '@yorkie-js/sdk/src/api/converter';\nimport { RevisionSummary } from '@yorkie-js/sdk/src/api/revision';\nimport { ChangePack } from '@yorkie-js/sdk/src/document/change/change_pack';\nimport {\n  ChangeApplyError,\n  Code,\n  YorkieError,\n} from '@yorkie-js/sdk/src/util/error';\nimport { logger } from '@yorkie-js/sdk/src/util/logger';\nimport { hasStrongRandomSource, uuid } from '@yorkie-js/sdk/src/util/uuid';\nimport { Attachment, WatchStream } from '@yorkie-js/sdk/src/client/attachment';\nimport {\n  Document,\n  DocStatus,\n  Indexable,\n  DocEventType,\n  StreamConnectionStatus,\n  DocSyncStatus,\n  LocalChangesDroppedReason,\n  ReissueToken,\n} from '@yorkie-js/sdk/src/document/document';\nimport {\n  Change,\n  ChangeStruct,\n} from '@yorkie-js/sdk/src/document/change/change';\nimport { OpSource } from '@yorkie-js/sdk/src/document/operation/operation';\nimport { createAuthInterceptor } from '@yorkie-js/sdk/src/client/auth_interceptor';\nimport { createMetricInterceptor } from '@yorkie-js/sdk/src/client/metric_interceptor';\nimport { validateSerializable } from '../util/validator';\nimport {\n  Channel,\n  ChannelStatus,\n  ChannelEventType,\n  BroadcastOptions,\n} from '@yorkie-js/sdk/src/channel/channel';\nimport { Attachable } from './attachable';\nimport { DocStore, StoredChange } from '@yorkie-js/sdk/src/client/doc-store';\nimport {\n  PersistState,\n  shouldCompact,\n} from '@yorkie-js/sdk/src/client/persist-policy';\nimport {\n  SessionLock,\n  SessionLockHandle,\n  WebLocksSessionLock,\n  acquireSessionLock,\n} from '@yorkie-js/sdk/src/client/session-lock';\nimport {\n  runWatchStream,\n  watchHeartbeatInterval,\n} from '@yorkie-js/sdk/src/client/watch';\n\n/**\n * `Key` is a string representing the key of Document or Channel.\n */\ntype Key = string;\n\n/**\n * `SyncMode` defines synchronization modes for the PushPullChanges API\n * (documents) and the RefreshChannel heartbeat (channels).\n */\nexport enum SyncMode {\n  /**\n   * `Manual` mode indicates that changes are not automatically pushed or pulled.\n   */\n  Manual = 'manual',\n\n  /**\n   * `Realtime` mode indicates that changes are automatically pushed and pulled.\n   */\n  Realtime = 'realtime',\n\n  /**\n   * `RealtimePushOnly` mode indicates that only local changes are automatically pushed.\n   *\n   * The reply to a push-only request is taken as a push ack only: its\n   * client-seq acknowledgement and pack metadata, never remote state and never\n   * its version vector. Garbage-collecting with that vector would purge\n   * tombstones that the remote changes this document has not pulled yet may\n   * anchor on, leaving them unapplicable once it resumes pulling.\n   */\n  RealtimePushOnly = 'realtime-pushonly',\n\n  /**\n   * `RealtimeSyncOff` mode indicates that changes are not automatically pushed or pulled,\n   * but the watch stream is kept active.\n   */\n  RealtimeSyncOff = 'realtime-syncoff',\n\n  /**\n   * `Polling` mode runs the sync loop without opening a watch stream.\n   * - For Channel: heartbeat refreshes TTL and brings sessionCount.\n   * - For Document: PushPullChanges runs at the polling interval. Remote\n   *   changes arrive on the next tick (latency = interval). Not suitable\n   *   for collaborative editing — use Realtime for that.\n   */\n  Polling = 'polling',\n}\n\n/**\n * `ClientStatus` represents the status of the client.\n */\nexport enum ClientStatus {\n  /**\n   * `Deactivated` means that the client is not activated. It is the initial\n   * status of the client. If the client is deactivated, all `Document`s of the\n   * client are also not used.\n   */\n  Deactivated = 'deactivated',\n\n  /**\n   * `Activated` means that the client is activated. If the client is activated,\n   * all `Document`s of the client are also ready to be used.\n   */\n  Activated = 'activated',\n}\n\n/**\n * `ClientCondition` represents the condition of the client.\n */\nexport enum ClientCondition {\n  /**\n   * `SyncLoop` is a key of the sync loop condition.\n   */\n  SyncLoop = 'SyncLoop',\n\n  /**\n   * `WatchLoop` is a key of the watch loop condition.\n   */\n  WatchLoop = 'WatchLoop',\n}\n\n/**\n * `ClientOptions` are user-settable options used when defining clients.\n */\n// Hoisted out of the append path: this is the hot loop the incremental design\n// exists to make cheap, and allocating a codec per change works against that.\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\n\n/**\n * `unretryableWriteCodes` are the server codes for a push refused on its\n * content rather than on conditions: the same pack re-sent is re-measured\n * against the same gate and refused again. Kept in one place because three\n * sites read it — the sync loop's parking of the rejected attachment, the\n * `write-rejected` event, and `handleConnectError`'s non-retry answer.\n */\nconst unretryableWriteCodes = [\n  Code.ErrDocumentSizeExceedsLimit,\n  Code.ErrChangeTooLarge,\n] as const;\n\n/**\n * `keepaliveHeader` marks a request that must be issued with `fetch`'s\n * `keepalive` option, which lets it outlive the page that sent it.\n *\n * It travels on the request rather than on a field the transport reads at\n * fetch time: connect awaits its interceptor chain before calling the\n * transport's `fetch`, so a flag set around the `rpcClient.<rpc>()` call and\n * cleared when that call returns is already false by the time the real fetch\n * reads it. The transport strips the header before the request leaves.\n */\nconst keepaliveHeader = 'x-yorkie-keepalive';\n\nexport interface ClientOptions {\n  /**\n   * `rpcAddr` is the address of the RPC server. It is used to connect to\n   * the server.\n   */\n  rpcAddr?: string;\n\n  /**\n   * `key` is the client key. It is used to identify the client.\n   * If not set, a random key is generated from the runtime's CSPRNG; a\n   * runtime with no Web Crypto cannot generate one unguessably, so the\n   * constructor throws `ErrInvalidArgument` there rather than activate under\n   * a key another client can predict. Pass `key` to support such a runtime.\n   *\n   * That random default is minted per `Client` instance, so it differs on every\n   * launch. **Offline persistence requires a stable key**: the server derives\n   * the actor stamped into every change from the project and this key, and it\n   * also scopes the {@link ClientOptions.store} keys\n   * (`apiKey/clientKey/docKey`). A new key therefore does not address the\n   * previous launch's entries at all — the restore finds nothing, the un-pushed\n   * edits are lost *silently* (no {@link DocEventType.LocalChangesDropped}\n   * event: the `actor-mismatch` guard in\n   * {@link Document.restoreFromBytes} only fires when the *same* store key is\n   * reached under a different actor), and the previous namespace is orphaned.\n   * `DocStore` exposes no enumeration or prune, so nothing can reclaim those\n   * entries afterwards and a durable backend grows without bound, one dead\n   * namespace per launch.\n   *\n   * An app setting `store` must therefore pass a key it persists itself and\n   * reuses on the next launch. Make it an **opaque random value the app mints\n   * once** — `crypto.randomUUID()` kept in local storage, say — scoped to the\n   * signed-in user and cleared on sign-out. Do **not** derive it from a user\n   * id, a device id, an email, or anything else guessable or shared:\n   *\n   * - The key is an identifier, not a credential. It is sent verbatim in\n   *   `ActivateClientRequest.client_key` and nothing proves the caller owns it,\n   *   so a guessable key lets another client of the same project activate under\n   *   the same derived actor and attribute changes to it.\n   * - A key shared between users of one browser (a device id) gives them one\n   *   store namespace. `attach` loads and rehydrates the persisted bytes\n   *   locally *before* the attach RPC, so the previous user's document content\n   *   and un-pushed edits would surface in the next user's session ahead of any\n   *   server authorization.\n   */\n  key?: string;\n\n  /**\n   * `apiKey` is the API key of the project. It is used to identify the project.\n   * If not set, API key of the default project is used.\n   */\n  apiKey?: string;\n\n  /**\n   * `metadata` is the metadata of the client. It is used to store additional\n   * information about the client.\n   */\n  metadata?: Record<string, string>;\n\n  /**\n   * `authTokenInjector` is a function that provides a token for the auth webhook.\n   * When the webhook response status code is 401, this function is called to refresh the token.\n   * The `reason` parameter is the reason from the webhook response.\n   *\n   * If the function rejects, the client keeps the previous token, and its\n   * loops (the sync loop, the Watch streams and broadcast retries) do not\n   * call the function again for a while: 1s after the first failure,\n   * doubling up to 30s, jittered. A loop that got a 401 retries on its own\n   * after its usual delay, or once that time is up if it is later, but\n   * waits at most 5s for it, so the loops come back once the token API\n   * does. A one-shot call such as `attach`, `detach`, `remove` or `sync`\n   * calls the function on every 401, as before: it throws the function's\n   * error if the function rejects, and the `ErrUnauthenticated` it received\n   * otherwise; retrying it is up to the caller. The first try of `broadcast`\n   * calls it the same way and throws the function's error if it rejects;\n   * otherwise `broadcast` retries as usual.\n   *\n   * A rejection is treated as transient. When the function can tell that a\n   * refresh will never succeed (for example, the token API answers that the\n   * user is signed out), the app should deactivate the client to stop the\n   * retries. If the server refuses the deactivation with a 401 as well and\n   * the function rejects again, `deactivate` still stops the client locally\n   * and throws the function's error; the server reaps it after its\n   * `clientDeactivateThreshold`.\n   */\n  authTokenInjector?: (reason?: string) => Promise<string>;\n\n  /**\n   * `syncLoopDuration` is the duration of the sync loop. After each sync loop,\n   * the client waits for the duration to next sync. The default value is\n   * `50`(ms).\n   */\n  syncLoopDuration?: number;\n\n  /**\n   * `retrySyncLoopDelay` is the delay of the retry sync loop. If the sync loop\n   * fails, the client waits for the delay to retry the sync loop, or up to 5s\n   * after a 401 while the token refresh backs off (see `authTokenInjector`).\n   * The default value is `1000`(ms).\n   */\n  retrySyncLoopDelay?: number;\n\n  /**\n   * `reconnectStreamDelay` is the delay of the reconnect stream. If the stream\n   * is disconnected, the client waits for the delay to reconnect the stream,\n   * or up to 5s after a 401 while the token refresh backs off (see\n   * `authTokenInjector`). The default value is `1000`(ms).\n   */\n  reconnectStreamDelay?: number;\n\n  /**\n   * `channelHeartbeatInterval` is the interval of the channel heartbeat (ms).\n   * The client sends a `RefreshChannel` heartbeat to refresh the channel\n   * session TTL. The default value is `5000` (ms) — co-tuned to the server's\n   * `ChannelSessionTTL` (15 s) at TTL/3. Values larger than the server TTL\n   * risk premature session expiry.\n   */\n  channelHeartbeatInterval?: number;\n\n  /**\n   * `watchHeartbeatInterval` is the interval (ms) at which the client asks the\n   * server to send a heartbeat on an idle Watch stream, so that a half-open\n   * stream is noticed and reconnected. It is a request, not a setting: the\n   * server clamps it to its own bounds and the client times a silent stream\n   * out at three times the interval the server actually uses. `0` asks for no\n   * heartbeats, which also leaves the stream without an idle timeout. The\n   * default value is `20000` (ms).\n   *\n   * Unlike `channelHeartbeatInterval`, which is how often the client sends\n   * `RefreshChannel` to keep a channel session alive, this is how often the\n   * server writes to the client's Watch stream.\n   */\n  watchHeartbeatInterval?: number;\n\n  /**\n   * `userAgent` is the user agent of the client. It is used to identify the\n   * client.\n   */\n  userAgent?: string;\n\n  /**\n   * `useGrpcWebTransport` determines the transport protocol.\n   * If true, uses gRPC-Web transport for backward compatibility.\n   * If false (default), uses Connect Protocol transport.\n   */\n  useGrpcWebTransport?: boolean;\n\n  /**\n   * `deactivateOnUnload` controls whether the client registers a\n   * `beforeunload` listener during `activate()` that deactivates the client\n   * when the page is unloaded. The default value is `true`.\n   *\n   * Setting this to `false` skips the listener registration. This is useful\n   * for apps that don't need GC or presence cleanup on unload (for example,\n   * `disableGC` documents without collaboration): the unload-time\n   * deactivate becomes pure overhead and its `fetch({ keepalive: true })`\n   * request can reject mid-flight during hard navigation, surfacing as an\n   * unhandled `[unknown]` `ConnectError`. The server reaps the stale\n   * client after its `clientDeactivateThreshold`, so opting out is safe.\n   */\n  deactivateOnUnload?: boolean;\n\n  /**\n   * `store` is a pluggable persistence backend for offline document state.\n   * When set, the client writes one base snapshot at attach and then **appends\n   * each local change**, so recording an edit costs the size of that edit\n   * rather than of the whole document. The log is compacted back into a\n   * snapshot once it grows large relative to it. A sync that only acks a push\n   * writes the small `meta` header; a sync that pulls content writes a\n   * snapshot, because the log carries local changes only. On `attach` the\n   * document is rehydrated from the snapshot and the log is replayed over it,\n   * so un-pushed local changes survive a reload. The\n   * restored checkpoint is presented in the attach ChangePack so the server\n   * seeds the client's document sequence from it and re-accepts the re-pushed\n   * local changes. When unset (the default), no persistence happens.\n   *\n   * For offline persistence you also want `deactivateOnUnload: false`: the\n   * default `true` deactivates the client on page unload, which detaches\n   * documents server-side and defeats the point of resuming un-pushed local\n   * changes on the next load. Setting `store` therefore auto-defaults\n   * `deactivateOnUnload` to `false`; pass it explicitly to override.\n   *\n   * You **must** also set {@link ClientOptions.key} to an opaque random value\n   * the app mints once and reuses across launches. Both the store keys and the\n   * actor recovery is keyed by are derived from it, and the default is a fresh\n   * random key per `Client`, so leaving it unset means every restart silently\n   * loses every un-pushed change and orphans the previous launch's entries.\n   * This cannot be defaulted correctly — only the app knows what identity\n   * should outlive the process — so the client warns rather than guessing. See\n   * {@link ClientOptions.key} for why the value must not be a user id, a device\n   * id, or anything else guessable or shared between users of one browser.\n   */\n  store?: DocStore;\n\n  /**\n   * `sessionLock` is the single-active-session guard used only on the offline\n   * persistence path (when `store` is set). Offline persistence derives a\n   * stable actor from the app's clientKey, so two tabs of the same app+user\n   * share it; two live tabs would share one server checkpoint and mint\n   * colliding `clientSeq` values — silent edit loss. On `attach` the client\n   * acquires a lock keyed by `apiKey/clientKey/docKey` and holds it for the\n   * attachment lifetime; if it is already held (another tab) the attach fails\n   * fast. The default {@link WebLocksSessionLock} uses the Web Locks API and is\n   * a no-op in non-browser runtimes; inject a fake for testing. Ignored when\n   * `store` is unset (non-persistence clients keep today's behavior).\n   */\n  sessionLock?: SessionLock;\n\n  /**\n   * `maxPersistBytes` caps the size of a snapshot this client is willing to\n   * write. A document whose snapshot exceeds it stops being persisted and a\n   * {@link DocEventType.PersistDisabled} event is published; editing is\n   * unaffected.\n   *\n   * Only snapshots are measured. Appends are a few hundred bytes regardless of\n   * document size, so they need no budget — the budget exists for the one\n   * operation whose cost scales with the document.\n   *\n   * Unset means no limit.\n   */\n  maxPersistBytes?: number;\n\n  /**\n   * `maxPersistMillis` caps how long serializing a snapshot may block the main\n   * thread before this client gives up persisting the document. Same effect\n   * and same event as {@link maxPersistBytes}. Unset means no limit.\n   */\n  maxPersistMillis?: number;\n}\n\n/**\n * `DeactivateOptions` are user-settable options used when deactivating clients.\n */\nexport interface DeactivateOptions {\n  /**\n   * `keepalive` is used to enable the keepalive option when deactivating.\n   * If true, the client will request deactivation immediately using `fetch`\n   * with the `keepalive` option enabled. This is useful for ensuring the\n   * deactivation request can continue even if the page is being unloaded.\n   * Local teardown and the returned Promise do not wait for the response.\n   * Late responses and errors are ignored, including authentication errors;\n   * this does not confirm that the server accepted the deactivation.\n   */\n  keepalive?: boolean;\n\n  /**\n   * `synchronous` is used to enable the synchronous option when deactivating.\n   * If true, the server will wait for all pending operations to complete\n   * before deactivating.\n   */\n  synchronous?: boolean;\n}\n\n/**\n * `AttachOptions` are user-settable options used when attaching documents.\n */\nexport interface AttachOptions<R, P> {\n  /**\n   * `initialRoot` is the initial root of the document. It is used to\n   * initialize the document. It is used when the fields are not set in the\n   * document.\n   */\n  initialRoot?: R;\n\n  /**\n   * `initialPresence` is the initial presence of the client.\n   */\n  initialPresence?: P;\n\n  /**\n   * `syncMode` defines the synchronization mode of the document.\n   */\n  syncMode?: SyncMode;\n\n  /**\n   * `documentPollInterval` (ms) — only used when `syncMode` is `Polling`.\n   * Default: 3000.\n   */\n  documentPollInterval?: number;\n\n  /**\n   * `schema` is the schema of the document. It is used to validate the\n   * document.\n   */\n  schema?: string;\n\n  /**\n   * `disableGC` declares that this attachment will not produce or consume\n   * tombstones. The server skips minVV tracking and omits the response\n   * VersionVector for this client. Use only with Counter or primitive\n   * workloads; misuse on a document that uses Tree, Text, or Array\n   * deletions leads to undefined GC behavior on this client.\n   *\n   * This option controls the wire contract with the server. It is\n   * distinct from any local-only GC toggle on the Document.\n   */\n  disableGC?: boolean;\n\n  /**\n   * `disablePresence` declares that this document does not use presence.\n   * The first client to attach a document sets the persisted server-side\n   * flag — subsequent attaches inherit the fixated value regardless of\n   * what they pass. The client uses the server response to gate\n   * `Document.update`'s presence emits (silently dropped) and skips the\n   * initial `presence.set(opts.initialPresence)` emitted on attach.\n   *\n   * If omitted, the resolved value is `doc.isPresenceDisabled()` (the\n   * value seeded from `DocumentOptions.disablePresence`, then overwritten\n   * by any previous attach response on the same Document instance), with\n   * a final fallback of `false`.\n   */\n  disablePresence?: boolean;\n}\n\n/**\n * `ResyncOptions` are the options of {@link Client.resync}.\n */\nexport interface ResyncOptions<P> {\n  /**\n   * `discardLocalChanges` must be `true`: the un-pushed local changes are\n   * taken out of the queue and returned to the caller instead of being sent\n   * again. There is no non-discarding form — the server refused those changes,\n   * and re-presenting them is what wedged the document in the first place.\n   * It is spelled out at the call site so the data loss is never implicit.\n   */\n  discardLocalChanges: true;\n\n  /**\n   * `initialPresence` is the presence to attach with. Defaults to the\n   * document's current presence, so a recovery keeps the cursor the user is\n   * holding: presence is not what the server refused.\n   */\n  initialPresence?: P;\n}\n\n/**\n * `AttachChannelOptions` are user-settable options used when attaching channels.\n */\nexport interface AttachChannelOptions {\n  /**\n   * `syncMode` selects how the channel keeps presence in sync with the server.\n   * Default is `SyncMode.Realtime`.\n   * - `SyncMode.Realtime`: open a watch stream and run the heartbeat. Required\n   *   to receive broadcast events.\n   * - `SyncMode.Polling`: heartbeat-only. No watch stream is opened. The\n   *   heartbeat refreshes TTL and brings the latest sessionCount. Recommended\n   *   for large channels where broadcast is not needed.\n   * - `SyncMode.Manual`: no automatic activity. Caller must invoke `sync()`.\n   */\n  syncMode?: SyncMode;\n\n  /**\n   * `channelHeartbeatInterval` overrides the heartbeat interval (ms) for\n   * this attachment. If unset, the client-level default\n   * (`ClientOptions.channelHeartbeatInterval`, default 5000 ms) applies\n   * to both Realtime and Polling modes.\n   */\n  channelHeartbeatInterval?: number;\n}\n\n/**\n * `DefaultDocumentPollIntervalMs` is the default poll interval (ms) for\n * `SyncMode.Polling` documents when the user has not set an explicit\n * `documentPollInterval`.\n */\nconst DefaultDocumentPollIntervalMs = 3000;\n\n/**\n * `DefaultChannelHeartbeatMs` is the default heartbeat interval for both\n * Realtime and Polling channel modes. Co-tuned to the server's\n * `ChannelSessionTTL` (15 s) at TTL/3.\n */\nconst DefaultChannelHeartbeatMs = 5000;\n\n/**\n * `AuthRetryMaxWaitMs` caps how long a loop retry that got a 401 waits for\n * the token refresh backoff. The rest of the client expects a failed loop to\n * run again soon: a channel session lapses after the server's 15s TTL, and a\n * refresh that succeeds elsewhere (a one-shot call, another loop) should take\n * effect without waking anything. The default heartbeat, TTL/3, keeps both.\n */\nconst AuthRetryMaxWaitMs = DefaultChannelHeartbeatMs;\n\n/**\n * `DefaultWatchHeartbeatMs` is the default heartbeat interval a client asks\n * the server for on its Watch streams: short enough to notice a half-open\n * stream in about a minute, and below the idle timeout of a typical proxy or\n * load balancer.\n */\nconst DefaultWatchHeartbeatMs = 20000;\n\n/**\n * `DefaultClientOptions` is the default options for Client.\n */\nconst DefaultClientOptions = {\n  rpcAddr: 'https://api.yorkie.dev',\n  syncLoopDuration: 50,\n  retrySyncLoopDelay: 1000,\n  reconnectStreamDelay: 1000,\n  channelHeartbeatInterval: DefaultChannelHeartbeatMs,\n  watchHeartbeatInterval: DefaultWatchHeartbeatMs,\n  deactivateOnUnload: true,\n};\n\n/**\n * `DefaultBroadcastOptions` is the default options for broadcast.\n */\nconst DefaultBroadcastOptions = {\n  maxRetries: Infinity,\n  initialRetryInterval: 1000,\n  maxBackoff: 20000,\n};\n\n/**\n * `AuthRefreshBackoff` bounds the wait between token refreshes after\n * `authTokenInjector` rejects: it starts at `initial`, doubles on each failure\n * in a row up to `max`, and each wait is jittered by ±`jitter` so clients that\n * lost their token API at the same moment do not come back at the same moment.\n */\nconst AuthRefreshBackoff = {\n  initial: 1000,\n  max: 30000,\n  jitter: 0.2,\n};\n\n/**\n * `authRefreshDelay` returns the wait before the next refresh, given how many\n * refreshes have failed in a row (1 for the first failure).\n */\nfunction authRefreshDelay(failures: number): number {\n  const base = Math.min(\n    AuthRefreshBackoff.initial * 2 ** (failures - 1),\n    AuthRefreshBackoff.max,\n  );\n  const jitter = 1 + AuthRefreshBackoff.jitter * (Math.random() * 2 - 1);\n  return Math.min(base * jitter, AuthRefreshBackoff.max);\n}\n\n/**\n * `toHeartbeatIntervalMs` converts the `watchHeartbeatInterval` option to the\n * wire value. Anything that is not a positive number asks for no heartbeats.\n * A fraction of a millisecond is rounded up rather than down, so a tiny\n * positive interval is clamped up by the server instead of reading as an\n * opt-out. A value too large for an int64 would fail every Watch request\n * at serialization, so it is capped; the server clamps it to its maximum.\n */\nfunction toHeartbeatIntervalMs(interval: number): bigint {\n  if (!(interval > 0)) {\n    return 0n;\n  }\n  return BigInt(Math.min(Math.ceil(interval), Number.MAX_SAFE_INTEGER));\n}\n\n/**\n * `escapeNamespacePart` percent-encodes the separator (and the escape\n * character itself) so a component cannot forge one. Without it,\n * `join(a, b)` is not injective: `apiKey` and `clientKey` are taken verbatim\n * from `ClientOptions` and a docKey is caller-supplied, so a clientKey\n * containing `/` could produce the same joined string as a different\n * (apiKey, clientKey, docKey) triple — two distinct identities sharing one\n * store namespace and one session lock. Escaping `%` first keeps the encoding\n * reversible and collision-free.\n */\nfunction escapeNamespacePart(part: string): string {\n  return part.replace(/%/g, '%25').replace(/\\//g, '%2F');\n}\n\n/**\n * `namespaceOf` builds the `apiKey/clientKey/docKey` identity namespace used\n * for both `DocStore` keys and the single-active-session lock name. Each\n * component is escaped, so the mapping from identity to namespace is\n * one-to-one: distinct identities can never address the same persisted\n * envelope or block each other's session lock.\n */\nfunction namespaceOf(\n  apiKey: string,\n  clientKey: string,\n  docKey: string,\n): string {\n  return (\n    `${escapeNamespacePart(apiKey)}/${escapeNamespacePart(clientKey)}/` +\n    escapeNamespacePart(docKey)\n  );\n}\n\n/**\n * `Client` is a normal client that can communicate with the server.\n * It has documents and sends changes of the documents in local\n * to the server to synchronize with other replicas in remote.\n */\nexport class Client {\n  private id?: ActorID;\n  // actorID is the stable actor stamped into document changes. It comes from\n  // `ActivateClientResponse.actor_id` (a new server), and falls back to the\n  // per-session `id` against an older server that does not return it. It is\n  // kept separate from `id` so RPC calls keep using the per-session client id\n  // for row lookups while documents author changes under the stable actor.\n  private actorID?: ActorID;\n  private key: string;\n  private metadata: Record<string, string>;\n  private status: ClientStatus;\n  private attachmentMap: Map<string, Attachment<Attachable>>;\n  // `liveAttachments` holds every attachment this client created and has not\n  // torn down yet, mapped to the key it was attached under. `attachmentMap`\n  // keeps at most one attachment per key, so an attach that takes a key\n  // another attachment already holds drops the old one out of it; teardown\n  // still has to reach that one, or its watch stream and session lock outlive\n  // the client. Entries are added where `attachmentMap` is written and removed\n  // by `detachInternal`.\n  private liveAttachments: Map<Attachment<Attachable>, string>;\n  // `attachingDocs` holds keys with an in-flight attach. attachmentMap is\n  // only populated after the attach round-trip resolves, so this set is\n  // needed to reject a concurrent duplicate attach of the same key.\n  private attachingDocs: Set<string>;\n  // `keyGenerated` is true when the client key was minted for this instance\n  // from the runtime's CSPRNG rather than passed in, which makes the actor\n  // this client's alone. The constructor refuses to mint a key at all when\n  // the CSPRNG is missing, so a generated key is always unguessable here:\n  // see `claimReissue`.\n  private keyGenerated: boolean;\n  // `reissueClaims` maps a document key to the actor this client last\n  // attached it under. See `claimReissue`.\n  private reissueClaims: Map<string, ActorID>;\n\n  private apiKey: string;\n  private authTokenInjector?: (reason?: string) => Promise<string>;\n  // `authRefreshFailures` counts the token refreshes that failed in a row,\n  // `authRefreshRetryAt` is when the next one may run,\n  // `authRefreshGeneration` numbers the injector calls, and\n  // `authTokenGeneration` is the number of the call whose token is in use.\n  // See `refreshAuthToken`.\n  private authRefreshFailures = 0;\n  private authRefreshRetryAt = 0;\n  private authRefreshGeneration = 0;\n  private authTokenGeneration = 0;\n  private conditions: Record<ClientCondition, boolean>;\n  // `syncLoopGeneration` numbers the sync loops; see `runSyncLoop`.\n  private syncLoopGeneration = 0;\n  private syncLoopDuration: number;\n  private reconnectStreamDelay: number;\n  private retrySyncLoopDelay: number;\n  private channelHeartbeatInterval: number;\n  private watchHeartbeatIntervalMs: bigint;\n  private deactivateOnUnload: boolean;\n  private store?: DocStore;\n  // Per-store-key write chain that serializes `store.saveSnapshot` calls for a\n  // document. Async saves (esp. IndexedDB) for the same key can otherwise\n  // interleave and let an earlier save resolve after a later one, persisting\n  // stale bytes. Each key's tail promise is kept here so the next save chains\n  // after it; see `persistToStore`.\n  private persistQueues: Map<string, Promise<void>> = new Map();\n  // Per-store-key accounting for the incremental write path: how large the\n  // stored snapshot is, how much has been appended since, and the highest\n  // clientSeq already written. The compaction decision reads it; `append`\n  // advances it. Cleared in `detachInternal`.\n  private persistStates: Map<\n    string,\n    PersistState & {\n      lastAppendedClientSeq: number;\n      /** Set when an append failed. A log with a hole cannot be replayed, so\n       *  the next opportunity writes a fresh snapshot instead of appending\n       *  into it. */\n      poisoned: boolean;\n    }\n  > = new Map();\n  // Single-active-session guard for the offline persistence path. Only consulted\n  // when `store` is set; a stable Web Locks default is created so store-backed\n  // clients get multi-tab safety out of the box.\n  private sessionLock: SessionLock;\n  private maxPersistBytes?: number;\n  // Store keys whose document exceeded the persist budget. Sticky: the latch\n  // has to outlive the subscription teardown, or a write path that does not go\n  // through the edit loop — a sync, a repair — keeps writing to a snapshot\n  // that can never be updated again, which is a permanent divergence with no\n  // route back.\n  private persistDisabled: Set<string> = new Set();\n  private maxPersistMillis?: number;\n\n  private rpcClient: ConnectClient<typeof YorkieService>;\n  private setAuthToken: (token: string) => void;\n  private taskQueue: Array<() => Promise<any>>;\n  private processing = false;\n  private deactivating = false;\n  private sessionGeneration = 0;\n\n  /**\n   * @param rpcAddr - the address of the RPC server.\n   * @param opts - the options of the client.\n   */\n  constructor(opts?: ClientOptions) {\n    opts = opts || DefaultClientOptions;\n\n    const rpcAddr = opts.rpcAddr || DefaultClientOptions.rpcAddr;\n    // The client key is the identity the server trusts verbatim: it derives\n    // this client's actor from it, so a key another client of the project can\n    // land on is a key that client can activate under. A generated one is\n    // therefore only usable when `uuid` draws from the runtime's CSPRNG;\n    // without Web Crypto it falls back to `Math.random`, which is guessable,\n    // so refuse to mint an identity at all rather than send a weak one. Such\n    // a runtime has to pass its own `key`. See `claimReissue` and\n    // `util/uuid`.\n    if (!opts.key && !hasStrongRandomSource()) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `the runtime has no Web Crypto, so a client key cannot be generated ` +\n          `unguessably. Pass \\`key\\` as an opaque random value your app mints ` +\n          `itself (not a user id or a device id).`,\n      );\n    }\n    this.key = opts.key || uuid();\n    // A generated key names an actor this client alone can reach, which is\n    // what the pre-attach re-issue rests on; an explicit one is shared by\n    // every session that passes it. See `claimReissue`.\n    this.keyGenerated = !opts.key;\n    this.metadata = opts.metadata || {};\n    this.status = ClientStatus.Deactivated;\n    this.attachmentMap = new Map();\n    this.liveAttachments = new Map();\n    this.attachingDocs = new Set();\n    this.reissueClaims = new Map();\n\n    // TODO(hackerwins): Consider to group the options as a single object.\n    this.apiKey = opts.apiKey || '';\n    this.authTokenInjector = opts.authTokenInjector;\n    this.conditions = {\n      [ClientCondition.SyncLoop]: false,\n      [ClientCondition.WatchLoop]: false,\n    };\n    this.syncLoopDuration =\n      opts.syncLoopDuration ?? DefaultClientOptions.syncLoopDuration;\n    this.reconnectStreamDelay =\n      opts.reconnectStreamDelay ?? DefaultClientOptions.reconnectStreamDelay;\n    this.retrySyncLoopDelay =\n      opts.retrySyncLoopDelay ?? DefaultClientOptions.retrySyncLoopDelay;\n    this.channelHeartbeatInterval =\n      opts.channelHeartbeatInterval ??\n      DefaultClientOptions.channelHeartbeatInterval;\n    this.watchHeartbeatIntervalMs = toHeartbeatIntervalMs(\n      opts.watchHeartbeatInterval ??\n        DefaultClientOptions.watchHeartbeatInterval,\n    );\n    this.store = opts.store;\n    // Offline persistence needs the client to stay attached across an unload:\n    // the default deactivate-on-unload would detach and reset the server\n    // checkpoint, defeating a later resume. So when a store is configured,\n    // default deactivateOnUnload to false unless the app set it explicitly.\n    this.deactivateOnUnload =\n      opts.deactivateOnUnload ??\n      (this.store ? false : DefaultClientOptions.deactivateOnUnload);\n    // A store with no caller-supplied key cannot survive a restart, by\n    // construction: the generated key is per-instance, and it scopes both the\n    // store keys and the actor the server derives. The next launch addresses a\n    // fresh namespace, so it restores nothing and orphans what the last one\n    // wrote — no `actor-mismatch` event fires, because the old entries are\n    // never reached. Warn where the two options meet: neither is wrong alone,\n    // the loss is silent, and `DocStore` has no prune to reclaim the orphans.\n    if (this.store && !opts.key) {\n      logger.warn(\n        `[PS] c:\"${this.key}\" offline persistence needs a stable clientKey: ` +\n          `\\`store\\` is set but \\`key\\` is not, so a random one was generated ` +\n          `for this instance. The next launch addresses a different namespace, ` +\n          `silently restoring nothing and stranding what this one persists. ` +\n          `Pass \\`key\\` as an opaque random value your app mints once and ` +\n          `persists across launches (not a user id or a device id).`,\n      );\n    }\n    // Default to the Web Locks-backed guard; it is a no-op outside browsers and\n    // is only consulted on the store-backed attach path below.\n    this.sessionLock = opts.sessionLock ?? new WebLocksSessionLock();\n    this.maxPersistBytes = opts.maxPersistBytes;\n    this.maxPersistMillis = opts.maxPersistMillis;\n\n    const { authInterceptor, setToken } = createAuthInterceptor(this.apiKey);\n    this.setAuthToken = setToken;\n\n    const transportOptions = {\n      baseUrl: rpcAddr,\n      interceptors: [authInterceptor, createMetricInterceptor(opts?.userAgent)],\n      fetch: (input: RequestInfo | URL, init?: RequestInit) => {\n        const url =\n          typeof input === 'string'\n            ? input\n            : input instanceof URL\n              ? input.toString()\n              : input.url;\n\n        // Whether this request must go out with `fetch`'s `keepalive` option\n        // is carried on the request itself (see `keepaliveHeader`), not on a\n        // field read here: connect awaits its interceptor chain before\n        // calling this fetch, so a flag the caller clears once\n        // `rpcClient.<rpc>()` returns is already back to false by now. Strip\n        // the marker so it never reaches the server.\n        let headers = init?.headers;\n        let keepalive = false;\n        if (headers instanceof Headers && headers.has(keepaliveHeader)) {\n          keepalive = true;\n          headers = new Headers(headers);\n          headers.delete(keepaliveHeader);\n        }\n        init = init === undefined ? undefined : { ...init, headers };\n\n        // Server-streaming RPCs (Watch/WatchDocument/WatchChannel) need the\n        // caller's signal active for the response body's full lifetime so\n        // user-initiated cancellation can reach the underlying connection.\n        if (/\\/yorkie\\.v1\\.YorkieService\\/Watch/.test(url)) {\n          return fetch(input as RequestInfo, {\n            ...init,\n            keepalive,\n          });\n        }\n\n        // For unary RPCs, @connectrpc/connect calls AbortController.abort()\n        // on its per-call signal as cleanup after the call completes — even\n        // on success. In browsers that stray abort surfaces as an\n        // \"Uncaught (in promise) AbortError: The user aborted a request.\"\n        // tied to the (already-finished) fetch's body stream and gets picked\n        // up by global error trackers once per call. Decouple our underlying\n        // fetch from the caller's signal once the response is in hand so the\n        // post-success cleanup abort does not propagate. Aborts that arrive\n        // before the response settles still cancel the fetch via the\n        // forwarding listener.\n        const callerSignal =\n          init?.signal ?? (input instanceof Request ? input.signal : undefined);\n        const innerAC = new AbortController();\n        let onCallerAbort: (() => void) | undefined;\n        if (callerSignal) {\n          if (callerSignal.aborted) {\n            innerAC.abort(callerSignal.reason);\n          } else {\n            onCallerAbort = () => innerAC.abort(callerSignal.reason);\n            callerSignal.addEventListener('abort', onCallerAbort);\n          }\n        }\n        const detach = () => {\n          if (callerSignal && onCallerAbort) {\n            callerSignal.removeEventListener('abort', onCallerAbort);\n          }\n        };\n\n        return fetch(input as RequestInfo, {\n          ...init,\n          signal: innerAC.signal,\n          keepalive,\n        }).then(\n          (res) => {\n            detach();\n            return res;\n          },\n          (err) => {\n            detach();\n            throw err;\n          },\n        );\n      },\n    };\n\n    // Here we make the client itself, combining the service\n    // definition with the transport.\n    this.rpcClient = createConnectClient(\n      YorkieService,\n      opts.useGrpcWebTransport\n        ? createGrpcWebTransport(transportOptions)\n        : createConnectTransport(transportOptions),\n    );\n    this.taskQueue = [];\n  }\n\n  /**\n   * `activate` activates this client. That is, it registers itself to the server\n   * and receives a unique ID from the server. The given ID is used to\n   * distinguish different clients.\n   */\n  public async activate(): Promise<void> {\n    if (this.isActive()) {\n      return Promise.resolve();\n    }\n\n    if (this.authTokenInjector) {\n      const token = await this.authTokenInjector();\n      this.setAuthToken(token);\n      this.authRefreshFailures = 0;\n      this.authRefreshRetryAt = 0;\n      this.authTokenGeneration = ++this.authRefreshGeneration;\n    }\n\n    return this.enqueueTask(async () => {\n      try {\n        const res = await this.rpcClient.activateClient(\n          {\n            clientKey: this.key,\n            metadata: this.metadata,\n          },\n          { headers: { 'x-shard-key': `${this.apiKey}/${this.key}` } },\n        );\n\n        this.id = res.clientId;\n        this.actorID = res.actorId || res.clientId;\n        this.status = ClientStatus.Activated;\n        this.deactivating = false;\n        this.runSyncLoop();\n\n        logger.info(`[AC] c:\"${this.getKey()}\" activated, id:\"${this.id}\"`);\n\n        // NOTE(hackerwins): Set up beforeunload event to deactivate the client\n        // when the page is being unloaded.\n        if (typeof window !== 'undefined' && this.deactivateOnUnload) {\n          window.addEventListener('beforeunload', () => {\n            void this.deactivate({ keepalive: true }).catch((err) => {\n              logger.debug(\n                `[DC] c:\"${this.getKey()}\" beforeunload deactivate failed:`,\n                err,\n              );\n            });\n          });\n        }\n      } catch (err) {\n        logger.error(`[AC] c:\"${this.getKey()}\" err :`, err);\n        await this.handleConnectError(err);\n        throw err;\n      }\n    });\n  }\n\n  /**\n   * `deactivate` deactivates this client.\n   *\n   * @param options - If keepalive is true, the client will request deactivation\n   * immediately using `fetch` with the `keepalive` option enabled. This is\n   * useful for ensuring the deactivation request completes even if the page is\n   * being unloaded, such as in `beforeunload` or `unload` event listeners.\n   * If synchronous is true, the server will wait for all pending operations to\n   * complete before deactivating.\n   *\n   * Without `keepalive`, if the server refuses deactivation with a 401 and\n   * `authTokenInjector` rejects, the client is deactivated locally anyway\n   * and the injector's error is thrown.\n   *\n   * With `keepalive`, the response is not waited for at all: the client tears\n   * down locally as soon as the request is sent and the returned Promise\n   * resolves, and a late response or error is dropped. A page that freezes in\n   * the back/forward cache never processes that response, so waiting for it\n   * leaves the Promise pending forever in Safari.\n   */\n  public deactivate(\n    options: DeactivateOptions = { keepalive: false, synchronous: false },\n  ): Promise<void> {\n    if (this.status === ClientStatus.Deactivated) {\n      return Promise.resolve();\n    }\n\n    // Mark as deactivating immediately so the sync loop exits early.\n    this.deactivating = true;\n\n    if (options.keepalive) {\n      return this.deactivateKeepalive(options);\n    }\n\n    const task = async () => {\n      try {\n        await this.rpcClient.deactivateClient(\n          {\n            clientId: this.id!,\n            synchronous: options.synchronous,\n          },\n          { headers: { 'x-shard-key': `${this.apiKey}/${this.key}` } },\n        );\n        this.deactivateInternal();\n        logger.info(`[DC] c\"${this.getKey()}\" deactivated`);\n      } catch (err) {\n        logger.error(`[DC] c:\"${this.getKey()}\" err :`, err);\n\n        // NOTE(chacha912): The app deactivates to stop the retries when the\n        // token can no longer be refreshed, and the auth webhook may refuse\n        // `DeactivateClient` too. Stop locally then, or the loops would keep\n        // resending the refused token with nothing left to stop them.\n        // `deactivating` stays set until then, as after a deactivation that\n        // succeeds: the sync loop exits at its next tick instead of resuming,\n        // and a late first `RefreshChannel` response is dropped.\n        if (\n          isErrorCode(err, Code.ErrUnauthenticated) &&\n          this.authTokenInjector\n        ) {\n          try {\n            await this.refreshAuthToken(errorMetadataOf(err).reason, false);\n          } catch (refreshErr) {\n            this.deactivateInternal();\n            throw refreshErr;\n          }\n          this.deactivating = false;\n          throw err;\n        }\n\n        this.deactivating = false;\n        await this.handleConnectError(err);\n        throw err;\n      }\n    };\n\n    return this.enqueueTask(task);\n  }\n\n  /**\n   * `deactivateKeepalive` sends `DeactivateClient` with `keepalive` and tears\n   * the client down locally without waiting for the response.\n   *\n   * The caller is on its way out — that is what `keepalive` is for — so the\n   * response may never be processed: a page frozen in the back/forward cache\n   * resumes long after, if ever. Teardown and the returned Promise therefore\n   * hang off sending the request rather than off the response, and the\n   * response itself is dropped. By the time it could land, the app may have\n   * activated this client again, and deactivating that session or running\n   * `handleConnectError`'s recovery against it would be wrong.\n   */\n  private deactivateKeepalive(options: DeactivateOptions): Promise<void> {\n    try {\n      this.rpcClient\n        .deactivateClient(\n          {\n            clientId: this.id!,\n            synchronous: options.synchronous,\n          },\n          {\n            headers: {\n              'x-shard-key': `${this.apiKey}/${this.key}`,\n              // Marks the fetch as `keepalive`. A field toggled around this\n              // call would be cleared before connect's async interceptor\n              // chain reached the fetch that reads it.\n              [keepaliveHeader]: '1',\n            },\n          },\n        )\n        .catch((err) => {\n          logger.debug(`[DC] c:\"${this.getKey()}\" keepalive err :`, err);\n        });\n    } catch (err) {\n      // The request never left, e.g. the page froze first. Tear down anyway:\n      // otherwise the Watch stream stays open and peers keep seeing a client\n      // that is gone.\n      logger.debug(`[DC] c:\"${this.getKey()}\" keepalive send err :`, err);\n    }\n\n    this.deactivateInternal();\n    logger.info(`[DC] c\"${this.getKey()}\" deactivated`);\n    return Promise.resolve();\n  }\n\n  /**\n   * `has` checks if the given resource is attached to this client.\n   * @param key - the key of the resource.\n   * @returns true if the resource is attached to this client.\n   */\n  public has(key: Key): boolean {\n    return this.attachmentMap.has(key);\n  }\n\n  /**\n   * `attach` attaches a Document or Channel to this client.\n   * Overloaded to support both types.\n   */\n  public attach<R, P extends Indexable>(\n    resource: Document<R, P>,\n    opts?: AttachOptions<R, P>,\n  ): Promise<Document<R, P>>;\n\n  /**\n   * `attach` attaches the given channel to this client. The channel is\n   * registered locally and the server is notified on the next RefreshChannel\n   * heartbeat.\n   */\n  public attach(\n    resource: Channel,\n    opts?: AttachChannelOptions,\n  ): Promise<Channel>;\n\n  /**\n   * `attach` attaches a Document or Channel to this client.\n   * Overloaded to support both types.\n   */\n  public attach<R, P extends Indexable>(\n    resource: Document<R, P> | Channel,\n    opts?: AttachOptions<R, P> | AttachChannelOptions,\n  ): Promise<Document<R, P> | Channel> {\n    if (resource instanceof Channel) {\n      return this.attachChannel(resource, opts as AttachChannelOptions);\n    } else {\n      return this.attachDocument(resource, opts as AttachOptions<R, P>);\n    }\n  }\n\n  /**\n   * `claimReissue` marks the given document key as attached under the given\n   * actor and returns whether a document of that key edited before this\n   * attach may re-issue its tickets to the actor.\n   *\n   * A re-issue keeps each ticket's lamport, which starts at 1 in every fresh\n   * document, so it is sound only for an actor that has minted nothing else\n   * in the document. An explicit client key gives every session of that key\n   * -- a reload, another tab -- one stable actor, and a re-issued ticket\n   * would equal one an earlier session's first edits carry: the server would\n   * keep one of the two elements. Only a generated key makes the actor this\n   * client's alone, so only then does the re-issue run; other documents keep\n   * the initial actor, as before the re-issue existed.\n   *\n   * \"Generated\" also has to mean unguessable: a key from `uuid`'s\n   * `Math.random` fallback can be landed on by another client of the\n   * project, and the actor is derived from the key server-side, so that\n   * client would share this actor exactly as a second session of an explicit\n   * key does. The constructor keeps that case out of reach by refusing to\n   * generate a key without the CSPRNG, so `keyGenerated` implies it.\n   *\n   * Within this client, a second never-synced document of a key whose actor\n   * has already minted operation tickets there would mint the tickets the\n   * first document pushed, so such a repeat is declined. That is what the\n   * claim records, and only that: asking is free, and `markReissueClaim`\n   * takes the claim where tickets naming the actor actually enter the\n   * document -- at attach for a document that already carries them\n   * (`Document.hasMintedOperations`), and at `detachInternal` for one that\n   * minted them while attached. A plain attach of an untouched document\n   * takes nothing, so the next document of that key may still re-issue.\n   *\n   * A taken claim is never released: an attach whose response was lost may\n   * still have pushed, and a detach does not take pushed tickets back.\n   */\n  private claimReissue(actor: ActorID, docKey: string): boolean {\n    if (!this.keyGenerated) {\n      return false;\n    }\n\n    return this.reissueClaims.get(docKey) !== actor;\n  }\n\n  /**\n   * `markReissueClaim` records that the given actor has minted tickets in the\n   * document the given key names, so no later document of that key may\n   * re-issue onto this actor. See `claimReissue`.\n   */\n  private markReissueClaim(actor: ActorID, docKey: string): void {\n    this.reissueClaims.set(docKey, actor);\n  }\n\n  /**\n   * `attach` attaches the given document to this client. It tells the server that\n   * this client will synchronize the given document.\n   */\n  private attachDocument<R, P extends Indexable>(\n    doc: Document<R, P>,\n    opts: AttachOptions<R, P> = {},\n  ): Promise<Document<R, P>> {\n    // 01. Check if the client is ready to attach documents.\n    if (!this.isActive()) {\n      throw new YorkieError(\n        Code.ErrClientNotActivated,\n        `${this.key} is not active`,\n      );\n    }\n    if (doc.getStatus() !== DocStatus.Detached) {\n      throw new YorkieError(\n        Code.ErrNotDetached,\n        `${doc.getKey()} is not detached`,\n      );\n    }\n    // Reject a duplicate attach of the same key on this client. Without this\n    // guard the request reaches the server, which reports the already-attached\n    // key as a misleading `ErrClientNotFound`; the SDK then deactivates the\n    // whole client. `attachmentMap` covers the resolved case and\n    // `attachingDocs` covers a concurrent in-flight attach.\n    if (\n      this.attachmentMap.has(doc.getKey()) ||\n      this.attachingDocs.has(doc.getKey())\n    ) {\n      throw new YorkieError(\n        Code.ErrAlreadyAttached,\n        `${doc.getKey()} is already attached`,\n      );\n    }\n\n    // Resolve the effective presence-disabled state at attach time. The\n    // local option wins; absent that, the Document's seeded value (from\n    // construction or a prior attach response on this instance) is used;\n    // final fallback is `false`. The server is authoritative — the\n    // attach response overwrites this with the fixated value — so this\n    // is purely a local pre-attach decision controlling whether to push\n    // the initial presence and (once the wire field lands) what to send\n    // on the request.\n    const resolvedDisablePresence =\n      opts.disablePresence ?? doc.isPresenceDisabled() ?? false;\n\n    // 02. Attach the document to the client.\n    const syncMode = opts.syncMode ?? SyncMode.Realtime;\n    if (\n      opts.documentPollInterval !== undefined &&\n      opts.documentPollInterval <= 0\n    ) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        'documentPollInterval must be greater than 0',\n      );\n    }\n    const pollIntervalPinned = opts.documentPollInterval !== undefined;\n    const pollInterval = pollIntervalPinned\n      ? opts.documentPollInterval!\n      : syncMode === SyncMode.Polling\n        ? DefaultDocumentPollIntervalMs\n        : 0;\n\n    // Stamp the actor once the options are known to be valid, and before any\n    // local elements are rehydrated. A document edited before this attach\n    // re-issues the tickets it minted under the initial actor to this one; a\n    // rejected option must not have re-issued it or taken the claim. The\n    // restore (which repopulates the root/changeID/pending changes under\n    // their persisted actor) must run after this call; it is deferred into\n    // the enqueued task because the store load is async; see the\n    // `store.load` step below.\n    const actor = (this.actorID ?? this.id)!;\n    const reissued = doc.setActor(actor, {\n      reissue: this.claimReissue(actor, doc.getKey())\n        ? ReissueToken\n        : undefined,\n    });\n    // Take the claim where the actor's lamport space in this key stops being\n    // free: the re-issue just minted tickets under it, or pre-attach edits\n    // the re-issue declined are about to be pushed with their `executedAt`\n    // re-stamped to it. It is taken before the round trip, since an attach\n    // whose response is lost may still have pushed. A document that has\n    // minted nothing leaves the claim alone, so a later document of the key\n    // can still re-issue; `detachInternal` takes it if this one mints while\n    // attached.\n    if (reissued || doc.hasMintedOperations()) {\n      this.markReissueClaim(actor, doc.getKey());\n    }\n\n    // Mark the attach in flight synchronously so a concurrent duplicate\n    // attach of the same key is rejected by the guard above before it is\n    // enqueued. Cleared in the task's `finally`.\n    this.attachingDocs.add(doc.getKey());\n    // Capture before queueing: a queued attach belongs to the lifecycle in\n    // which it was requested, even if another activation runs before it.\n    const ownsSession = this.captureSession();\n    return this.enqueueTask(async () => {\n      // Set when the attach is abandoned because the session went away, so the\n      // `catch` below knows the throw is not a connection error.\n      let abandoned = false;\n      const assertSession = () => {\n        if (!ownsSession()) {\n          abandoned = true;\n          throw new YorkieError(\n            Code.ErrClientNotActivated,\n            `${this.key} lost its session while attaching ${doc.getKey()}`,\n          );\n        }\n      };\n      // Single-active-session lock, held for the attachment lifetime and\n      // released either on the failure path below or by `detachInternal`. Kept\n      // in this local until the attachment exists to capture it; if attach\n      // throws before then, the `catch` releases it so the lock is not leaked.\n      let sessionLockHandle: SessionLockHandle | undefined;\n      try {\n        assertSession();\n        // Acquire the single-active-session guard before any restore or RPC, so\n        // a second tab of the same offline-persistence client fails fast instead\n        // of driving sync on a shared checkpoint. Only on the store-backed path:\n        // non-store clients keep today's behavior (no guard). The Web Locks\n        // default is a no-op in non-browser runtimes.\n        if (this.store) {\n          const lockName =\n            'yorkie-session:' +\n            namespaceOf(this.apiKey, this.key, doc.getKey());\n          sessionLockHandle = await acquireSessionLock(\n            this.sessionLock,\n            lockName,\n            doc.getKey(),\n          );\n        }\n\n        // `attachOnce` runs the restore + attach RPC + apply-response sequence.\n        // It is a closure so the store-backed path can retry it once as a\n        // fresh (non-restored) attach after an `ErrEpochMismatch` re-anchor.\n        // `reanchor` skips the store restore and clears any state the caller\n        // reset, so the pack presents an initial checkpoint/epoch and the\n        // server sends the current snapshot.\n        const attachOnce = async (reanchor: boolean) => {\n          assertSession();\n          // Restore any persisted offline state before building the attach\n          // pack. The actor was already stamped above, so rehydrating here\n          // respects the actor-set-before-elements ordering. `createChangePack`\n          // reads `doc.checkpoint`, so the restored (non-zero) checkpoint flows\n          // straight into the attach ChangePack; the server (Q3) seeds the\n          // client's document sequence from it instead of 0 and re-accepts the\n          // re-pushed local changes.\n          let restored = false;\n          if (this.store && !reanchor) {\n            // A flaky store must not abort attach: on a load/restore failure,\n            // fall back to a fresh (unrestored) attach instead of throwing out\n            // of attach. `restoreFromBytes` also throws on an actor mismatch\n            // (store reused under a different clientKey); that is genuine data\n            // loss, so surface it and clear the stale entry rather than\n            // divergently restoring.\n            let bytes: Uint8Array | undefined;\n            let storedMeta: Uint8Array | undefined;\n            let storedChanges: Array<StoredChange> = [];\n            try {\n              const stored = await this.store.load(this.storeKey(doc.getKey()));\n              bytes = stored?.snapshot;\n              storedMeta = stored?.meta;\n              storedChanges = stored?.changes ?? [];\n            } catch (err) {\n              logger.warn(\n                `[AD] c:\"${this.getKey()}\" d:\"${doc.getKey()}\" store load ` +\n                  `failed; falling back to a fresh attach:`,\n                err,\n              );\n              bytes = undefined;\n            }\n            if (bytes) {\n              try {\n                doc.restoreFromBytes(bytes);\n                // Replay the log written after the snapshot. Anything at or\n                // below what the snapshot already carries is dropped rather\n                // than replayed: a compaction that wrote the snapshot without\n                // its log clear being observed would otherwise apply those\n                // changes a second time.\n                // Two watermarks, because the log answers two questions.\n                //\n                // The *snapshot* watermark says which entries the snapshot\n                // already contains, so everything above it must be replayed to\n                // bring the root forward. It is read before the meta header is\n                // applied, since meta describes the server's position and not\n                // the snapshot's contents.\n                //\n                // The *ack* watermark says which of those the server has\n                // already taken, so only entries above it are queued for push.\n                //\n                // The `max` here is a guard rather than a live branch: a\n                // document's pending queue only ever holds changes above its\n                // checkpoint (an ack removes them), so the carried value leads\n                // whenever the queue is non-empty. It was load-bearing while\n                // `saveMeta` trimmed the log and a snapshot's queue could go\n                // stale against an advancing checkpoint; that state is now\n                // unreachable. Kept because the ordering it asserts is what\n                // makes the two-watermark split correct, and a future change\n                // that reintroduces trimming would need it again.\n                //\n                // The envelope's own counter joins the max, because it is the\n                // highest `clientSeq` this client has MINTED — and a minted\n                // sequence is never replayable, whether the snapshot contains\n                // it or it was lost. It normally ties the other two (the\n                // counter equals the last pending entry, or the checkpoint\n                // when the queue is empty), so it only leads for a base this\n                // very branch rewrote: a repair persists the snapshot with the\n                // acked counter carried forward, deliberately ahead of the\n                // snapshot's checkpoint. Without it, the next edit appended\n                // after such a repair starts above `watermark + 1` and the\n                // contiguity guard below discards it.\n                const carried = doc.getPendingChangesAfter(0);\n                const snapshotWatermark = Math.max(\n                  carried.length ? carried[carried.length - 1].clientSeq : 0,\n                  doc.getCheckpoint().getClientSeq(),\n                  doc.getChangeID().getClientSeq(),\n                );\n                if (storedMeta) {\n                  doc.restoreMetaFromBytes(storedMeta);\n                }\n                const ackedWatermark = doc.getCheckpoint().getClientSeq();\n                const watermark = snapshotWatermark;\n                const fresh = storedChanges.filter(\n                  (change) => change.clientSeq > watermark,\n                );\n                // The header is only trustworthy as far as the log backs it.\n                // If the entries between the snapshot and the acked checkpoint\n                // are missing — an evicting store, a partial quota failure, a\n                // lossy backend — then restoring with that header yields a root\n                // without those changes and a checkpoint that stops the server\n                // from ever resending them. An empty log is the same case, and\n                // it used to skip validation entirely.\n                //\n                // The counter is the second position meta carries, and the log\n                // has to reach *it*, not merely the checkpoint. The two differ\n                // whenever an edit is minted while a sync is in flight: the\n                // response acks N while meta records a counter of N+1. Losing\n                // only that trailing entry leaves the log reaching N — enough\n                // to satisfy the checkpoint — while `restoreAppendedChanges`\n                // keeps the counter at N+1 over a root that holds N. The next\n                // edit then mints N+2, a gap the server rejects on every push\n                // from then on. That is not `ErrEpochMismatch`, so nothing\n                // re-anchors and the document never syncs again.\n                //\n                // Read after the header is applied, so it is meta's counter\n                // rather than the snapshot's. With meta absent it cannot trip:\n                // the snapshot's own counter is already folded into\n                // `snapshotWatermark` above, so `headerWatermark` never leads\n                // the watermark the log is measured against.\n                const headerWatermark = Math.max(\n                  ackedWatermark,\n                  doc.getChangeID().getClientSeq(),\n                );\n                const lastReplayable = fresh.length\n                  ? fresh[fresh.length - 1].clientSeq\n                  : watermark;\n                const backsTheHeader = lastReplayable >= headerWatermark;\n                if (fresh.length || !backsTheHeader) {\n                  // The run has to be contiguous. A hole — a failed append —\n                  // cannot be pushed, because the server rejects a clientSeq\n                  // gap, so replaying it would produce a document that never\n                  // syncs again. Report the loss and keep the snapshot.\n                  const contiguous = fresh.every(\n                    (change, i) =>\n                      i === 0 ||\n                      change.clientSeq === fresh[i - 1].clientSeq + 1,\n                  );\n                  // Parsed in its own try: a corrupt *log* entry says nothing\n                  // about the snapshot, and letting it reach the outer handler\n                  // would report `restore-failed` and delete a snapshot that\n                  // restored perfectly well.\n                  let structs: Array<ChangeStruct<P>> | undefined;\n                  try {\n                    structs = fresh.map(\n                      (change) =>\n                        JSON.parse(\n                          textDecoder.decode(change.bytes),\n                        ) as ChangeStruct<P>,\n                    );\n                  } catch (parseErr) {\n                    logger.warn(\n                      `[AD] c:\"${this.getKey()}\" d:\"${doc.getKey()}\" ` +\n                        `persisted change log is undecodable; keeping the ` +\n                        `snapshot:`,\n                      parseErr,\n                    );\n                  }\n                  if (\n                    !structs ||\n                    !backsTheHeader ||\n                    !contiguous ||\n                    (fresh.length && fresh[0].clientSeq !== watermark + 1)\n                  ) {\n                    // Reported rather than thrown, because what is lost here is\n                    // the *log*, not the envelope — and the event exists to say\n                    // what was lost. Routing this through the generic restore\n                    // failure would hand the app the snapshot's pending changes\n                    // (often none) and call it an actor mismatch.\n                    logger.warn(\n                      `[AD] c:\"${this.getKey()}\" d:\"${doc.getKey()}\" ` +\n                        `persisted change log is not contiguous from ` +\n                        `clientSeq ${watermark + 1}; keeping the snapshot`,\n                    );\n                    this.emitLocalChangesDropped(\n                      doc,\n                      'log-discontinuity',\n                      structs ?? [],\n                    );\n                    // Undo the header. It described a position the log cannot\n                    // back, so keeping it would leave the document claiming\n                    // content its root does not have — and the server would\n                    // never resend it. Re-restoring from the snapshot bytes\n                    // returns checkpoint, changeID and epoch to what the\n                    // snapshot itself carries, which the server *can* resume\n                    // from.\n                    doc.restoreFromBytes(bytes);\n                    // ...except the counter, which is not a claim about\n                    // content. The header's *checkpoint* names sequences the\n                    // server has already taken, and the snapshot's counter can\n                    // be below it: a snapshot at counter 3 under a header that\n                    // acked 7. Minting 4..7 again gets them skipped as\n                    // duplicates on push, and the next ack — whose clientSeq\n                    // covers them — drops them from `localChanges` as pushed.\n                    // New edits lost with no event, which is the one outcome\n                    // this whole branch exists to avoid.\n                    //\n                    // The acked checkpoint, not the header's counter. The\n                    // server validates continuity from the position it holds,\n                    // so the next change has to be its clientSeq plus one; the\n                    // counter can lead that (an edit minted while a sync was in\n                    // flight), and it is exactly the entry that lead came from\n                    // that the log has lost. Resuming at the counter would mint\n                    // past the server's position and wedge every later push on\n                    // `ErrInvalidClientSeq`.\n                    doc.advanceClientSeqTo(ackedWatermark);\n                    // Rewrite the base from the *repaired* document, which\n                    // clears the log with it. Re-serializing rather than\n                    // writing `bytes` straight back is what makes the counter\n                    // correction survive: `saveSnapshot` drops the meta blob\n                    // that held the acked position, and the original envelope's\n                    // `changeID` still carries the snapshot's pre-ack counter —\n                    // so persisting it would reproduce this very repair (and\n                    // its silent clientSeq reuse) on the next reload.\n                    //\n                    // Re-serializing cannot smuggle the rejected header back\n                    // in. `restoreFromBytes` just above returned root,\n                    // presences, checkpoint, epoch, docID and the pending queue\n                    // to what the snapshot carries, so `toBytes` re-emits that\n                    // same envelope; the counter is the one field that differs,\n                    // and advancing it is the whole point. Removing the entry\n                    // instead would discard a snapshot that restored perfectly\n                    // well.\n                    this.persistToStore(\n                      this.storeKey(doc.getKey()),\n                      doc.toBytes(),\n                      (err) =>\n                        logger.error(\n                          `[PS] c:\"${this.getKey()}\" d:\"${doc.getKey()}\" ` +\n                            `log-discontinuity rebase failed:`,\n                          err,\n                        ),\n                    );\n                  } else {\n                    doc.restoreAppendedChanges(structs, ackedWatermark);\n                  }\n                }\n                restored = true;\n              } catch (err) {\n                // A persisted envelope that cannot be safely restored is\n                // unusable and MUST never abort attach or poison every future\n                // one. Two failure classes are handled the same way:\n                //   - actor mismatch (a YorkieError: store reused under a\n                //     different clientKey) — restoring would diverge the CRDT;\n                //   - any other failure (a native error such as a SyntaxError\n                //     from a corrupt/truncated envelope, or a\n                //     `ChangeApplyError` from a log entry that will not\n                //     replay) — the persisted state cannot be reconstructed.\n                // `ChangeApplyError` is excluded from the first class\n                // explicitly: it is a `YorkieError`, but a change that fails\n                // to apply says nothing about client identity.\n                // In both cases emit an app-visible data-loss event with\n                // whatever pending changes are recoverable, clear the stale\n                // entry, and fall through to a fresh attach. Treating a native\n                // decode error as unusable (rather than rethrowing) is what\n                // keeps a single poisoned store entry from failing every later\n                // attach.\n                const reason: LocalChangesDroppedReason =\n                  err instanceof YorkieError &&\n                  !(err instanceof ChangeApplyError)\n                    ? 'actor-mismatch'\n                    : 'restore-failed';\n                logger.warn(\n                  `[AD] c:\"${this.getKey()}\" d:\"${doc.getKey()}\" ` +\n                    `persisted state unusable (${reason}); dropping stale ` +\n                    `edits:`,\n                  err,\n                );\n                let dropped: Array<ChangeStruct<P>> = [];\n                try {\n                  dropped = Document.fromBytes<R, P>(\n                    doc.getKey(),\n                    bytes,\n                  ).getPendingChangeStructs();\n                } catch {\n                  // The envelope itself may be undecodable; recover nothing.\n                  dropped = [];\n                }\n                this.emitLocalChangesDropped(doc, reason, dropped);\n                await this.removeFromStore(doc.getKey());\n              }\n            }\n          }\n\n          // Seed the initial presence after restore so it is not overwritten by\n          // the rehydrated presences map. Skipped when presence is disabled.\n          // When restoring, the presence map already came back from storage, so\n          // adding an initial-presence change here would append a spurious\n          // local change.\n          if (!resolvedDisablePresence && !restored) {\n            doc.update((_, p) => p.set(opts.initialPresence || {}));\n          }\n\n          // Snapshot the pre-attach state used by the Tier-3 silent-purge\n          // guard: the docID persisted with the restored envelope and whether\n          // the local snapshot is non-empty. Captured before `applyChangePack`\n          // overwrites the checkpoint/root with the server's response.\n          const persistedDocID = doc.getDocID();\n          const hadLocalState =\n            restored && doc.getCheckpoint().getServerSeq() > 0n;\n          const persistedPending = restored\n            ? doc.getPendingChangeStructs()\n            : [];\n\n          // A restored queue can still hold presence patches minted in an\n          // earlier session, and this attach is the request they ride out on,\n          // so it needs the presence-base fallback as much as a sync does.\n          assertSession();\n          const res = await this.pushWithPresenceBase(\n            doc,\n            () => converter.toChangePack(doc.createChangePack()),\n            (changePack) =>\n              this.rpcClient.attachDocument(\n                {\n                  clientId: this.id!,\n                  changePack,\n                  schemaKey: opts.schema,\n                  disableGc: opts.disableGC ?? false,\n                  disablePresence: resolvedDisablePresence,\n                },\n                {\n                  headers: {\n                    'x-shard-key': `${this.apiKey}/${doc.getKey()}`,\n                  },\n                },\n              ),\n          );\n\n          assertSession();\n\n          const maxSize = res.maxSizePerDocument ?? 0;\n          if (maxSize > 0) {\n            doc.setMaxSizePerDocument(res.maxSizePerDocument);\n          }\n          if (res.schemaRules.length > 0) {\n            doc.setSchemaRules(converter.fromSchemaRules(res.schemaRules));\n          }\n\n          // Tier-3 silent-purge guard: if the server GC'd/deleted the document\n          // while this client was offline, attach mints a fresh empty doc with\n          // a new documentId and a server sequence back at 0. Restoring the\n          // local snapshot on top would present un-pushed edits against an\n          // unrelated document. Detect it by comparing the returned documentId\n          // against the persisted one, or a serverSeq that regressed to 0 while\n          // the local snapshot was non-empty, and surface an app-visible\n          // data-loss event carrying the dropped edits before clearing the\n          // stale entry and attaching fresh.\n          if (this.store && restored) {\n            const serverSeq = res.changePack?.checkpoint?.serverSeq ?? 0n;\n            const idChanged =\n              persistedDocID !== '' && res.documentId !== persistedDocID;\n            const seqRegressed = hadLocalState && serverSeq === 0n;\n            if (idChanged || seqRegressed) {\n              logger.warn(\n                `[AD] c:\"${this.getKey()}\" d:\"${doc.getKey()}\" server ` +\n                  `purged the document (docID or serverSeq reset); dropping ` +\n                  `persisted offline state`,\n              );\n              this.emitLocalChangesDropped(\n                doc,\n                'document-purged',\n                persistedPending,\n              );\n              await this.removeFromStore(doc.getKey());\n              doc.resetForReanchor();\n              doc.setActor((this.actorID ?? this.id)!);\n              doc.setDisableGC(opts.disableGC ?? false);\n              doc.setDisablePresence(res.disablePresence);\n              doc.applyChangePack(converter.fromChangePack<P>(res.changePack!));\n              doc.setDocID(res.documentId);\n              return res;\n            }\n          }\n\n          const pack = converter.fromChangePack<P>(res.changePack!);\n          // Record the opt-out decision before applying the attach response\n          // so the first applyChangePack already routes remote changes\n          // through the lamport-only sync path.\n          doc.setDisableGC(opts.disableGC ?? false);\n          doc.setDisablePresence(res.disablePresence);\n          doc.applyChangePack(pack);\n          // Record the server-assigned document id so the next persisted\n          // envelope carries it for the Tier-3 guard on a later restore.\n          doc.setDocID(res.documentId);\n          return res;\n        };\n\n        let res;\n        try {\n          res = await attachOnce(false);\n        } catch (err) {\n          // Store-backed re-anchor: a resume attach that presents a persisted\n          // (stale) checkpoint/epoch is rejected with `ErrEpochMismatch` when\n          // the document was force-compacted while this client was offline.\n          // The persisted entry is unusable, so drop it, reset the document to\n          // a fresh state (re-stamping the actor, since reset clears changeID),\n          // and retry a clean attach — the server re-anchors us from the\n          // current snapshot. Gated to the store path so non-store clients keep\n          // today's app-driven `epoch-mismatch` behavior.\n          //\n          // Data loss is not silent: before discarding, capture the un-pushed\n          // local changes and emit an app-visible `LocalChangesDropped` event\n          // carrying them, so the app can react/re-apply. Replaying them on top\n          // of the re-anchored (compacted) state is a follow-up enhancement.\n          if (this.store && isErrorCode(err, Code.ErrEpochMismatch)) {\n            logger.warn(\n              `[AD] c:\"${this.getKey()}\" d:\"${doc.getKey()}\" stale epoch on ` +\n                `resume; clearing persisted state and re-anchoring`,\n            );\n            const dropped = doc.getPendingChangeStructs();\n            this.emitLocalChangesDropped(doc, 'epoch-reanchor', dropped);\n            await this.removeFromStore(doc.getKey());\n            doc.resetForReanchor();\n            doc.setActor((this.actorID ?? this.id)!);\n            res = await attachOnce(true);\n          } else {\n            throw err;\n          }\n        }\n\n        if (doc.getStatus() === DocStatus.Removed) {\n          // The document was already removed server-side, so no Attachment is\n          // created here and nothing will ever call `detachInternal` to release\n          // the session lock. Release it now before the early return, otherwise\n          // the lock leaks and every later attach of this doc key fails fast.\n          sessionLockHandle?.release();\n          return doc;\n        }\n\n        // The client may have been torn down while the round trip was in\n        // flight: a `keepalive` deactivate runs `deactivateInternal` in the\n        // same tick, without passing through the task queue. Registering the\n        // attachment now would put it — and the watch stream opened below —\n        // on a Deactivated client, where nothing will ever detach it. The\n        // same holds if the client was activated again meanwhile: this attach\n        // was made under the previous `clientId`, so the server never\n        // associated it with the live session.\n        assertSession();\n\n        const attachment = new Attachment(\n          (err) => this.loopRetryDelay(err, this.reconnectStreamDelay),\n          doc,\n          res.documentId,\n          syncMode,\n          pollInterval,\n          pollIntervalPinned,\n          opts.disableGC ?? false,\n          res.disablePresence,\n        );\n        // Hand the held session lock to the attachment so `detachInternal`\n        // releases it on detach/deactivate, freeing a later tab to take over.\n        attachment.sessionLockHandle = sessionLockHandle;\n        this.attachmentMap.set(doc.getKey(), attachment);\n        this.liveAttachments.set(attachment, doc.getKey());\n        // Status subscribers can synchronously deactivate the client. Make\n        // the attachment visible to teardown before notifying them.\n        doc.applyStatus(DocStatus.Attached);\n        assertSession();\n\n        // Persist incrementally: one snapshot established here, then one\n        // appended change per local mutation. Re-serializing the document on\n        // every edit costs time proportional to the document — and a document\n        // is at its largest while being edited — whereas a change is a few\n        // hundred bytes regardless of size.\n        //\n        // The unsubscribe is captured on the attachment so `detachInternal` can\n        // tear it down and re-attaches do not accumulate handlers. Errors are\n        // logged, not thrown, so a failing store never breaks the editing path.\n        //\n        // Observe the local queue directly. Public events do not cover every\n        // queued change: presence.clear() and a failed detach can consume a\n        // clientSeq without emitting one. Presence-only undo/redo and operations\n        // with empty OpInfo must also reach the log. The internal signal runs\n        // after the document commits its state, before public callbacks can\n        // start a sync and remove pending changes. Remote changes do not signal.\n        //\n        // The post-sync checkpoint is written separately in `syncInternal` as\n        // `meta`: an ack-only push emits no Remote/Snapshot event, so it cannot\n        // be captured here.\n        if (this.store) {\n          const storeKey = this.storeKey(doc.getKey());\n          const onError = (err: unknown) =>\n            logger.error(\n              `[PS] c:\"${this.getKey()}\" persist d:\"${doc.getKey()}\" failed:`,\n              err,\n            );\n\n          // Establish the base the log appends to.\n          //\n          // The watermark is the highest `clientSeq` the snapshot *already\n          // carries*, not the checkpoint. `toBytes` bundles the pending queue\n          // into its envelope, so anything un-pushed at this moment is inside\n          // the snapshot; appending it again would restore it twice — once\n          // from the envelope, once from the log.\n          // Over budget on the very first write means no persist subscription\n          // is installed at all, rather than one that latches itself off on the\n          // next edit. `snapshotWithinBudget` has already published the event.\n          const snapshot = this.snapshotWithinBudget(doc, storeKey);\n          const carried = doc.getPendingChangesAfter(0);\n          if (snapshot) {\n            this.persistStates.set(storeKey, {\n              snapshotBytes: snapshot.length,\n              logBytes: 0,\n              changeCount: 0,\n              lastAppendedClientSeq: carried.length\n                ? carried[carried.length - 1].clientSeq\n                : doc.getCheckpoint().getClientSeq(),\n              poisoned: false,\n            });\n            // A failed base write must not leave the client appending into a\n            // void: `appendChange` on a key with no entry is a silent success\n            // in both shipped stores, so nothing would be persisted and nothing\n            // would say so. Poisoning routes the next edit through a fresh\n            // snapshot, which is the same repair a failed append takes.\n            this.persistSnapshotOrPoison(storeKey, snapshot, onError);\n\n            const append = () => {\n              const state = this.persistStates.get(storeKey);\n              if (!state) {\n                return;\n              }\n              // Capture all changes after the durable watermark, not just\n              // the change that triggered the internal notification.\n              // A previous append failed, so the log has a hole and cannot be\n              // replayed. Writing a snapshot loses nothing — it embeds the whole\n              // pending queue — while appending into a holed log would lose the\n              // entire offline session at restore.\n              if (state.poisoned) {\n                const repaired = this.snapshotWithinBudget(doc, storeKey);\n                if (!repaired) {\n                  return;\n                }\n                state.snapshotBytes = repaired.length;\n                state.logBytes = 0;\n                state.changeCount = 0;\n                state.poisoned = false;\n                state.lastAppendedClientSeq = doc\n                  .getPendingChangesAfter(0)\n                  .reduce(\n                    (max, p) => Math.max(max, p.clientSeq),\n                    doc.getCheckpoint().getClientSeq(),\n                  );\n                this.persistSnapshotOrPoison(storeKey, repaired, onError);\n                return;\n              }\n\n              const pending = doc.getPendingChangesAfter(\n                state.lastAppendedClientSeq,\n              );\n              for (const { clientSeq, struct } of pending) {\n                const bytes = textEncoder.encode(JSON.stringify(struct));\n                state.lastAppendedClientSeq = clientSeq;\n                state.logBytes += bytes.length;\n                state.changeCount += 1;\n                this.appendToStore(storeKey, { clientSeq, bytes }, (err) => {\n                  state.poisoned = true;\n                  onError(err);\n                });\n              }\n\n              if (shouldCompact(state)) {\n                const compacted = this.snapshotWithinBudget(doc, storeKey);\n                if (!compacted) {\n                  return;\n                }\n                state.snapshotBytes = compacted.length;\n                state.logBytes = 0;\n                state.changeCount = 0;\n                this.persistSnapshotOrPoison(storeKey, compacted, onError);\n              }\n            };\n\n            attachment.unsubscribePersist =\n              doc.subscribeLocalChangesInternal(append);\n          }\n        }\n\n        if (syncMode !== SyncMode.Manual && syncMode !== SyncMode.Polling) {\n          await this.runWatchLoop(doc.getKey());\n        }\n        assertSession();\n\n        logger.info(`[AD] c:\"${this.getKey()}\" attaches d:\"${doc.getKey()}\"`);\n\n        const crdtObject = doc.getRootObject();\n        if (opts.initialRoot) {\n          const initialRoot = opts.initialRoot;\n          doc.update((root) => {\n            for (const [k, v] of Object.entries(initialRoot)) {\n              if (!crdtObject.has(k)) {\n                const key = k as keyof R;\n                root[key] = v as any;\n              }\n            }\n          });\n        }\n\n        // Clear undo/redo stacks so that initialRoot setup operations\n        // are not reachable via undo.\n        doc.clearHistory();\n\n        return doc;\n      } catch (err) {\n        // Release the session lock on any failure so the guard is not leaked\n        // and a later attach (this or another tab) can acquire it. Release is\n        // idempotent, so this is safe even if `detachInternal` also runs.\n        sessionLockHandle?.release();\n        logger.error(`[AD] c:\"${this.getKey()}\" err :`, err);\n        // An abandoned attach is a local lifecycle cancellation, not a\n        // server error requiring connection recovery.\n        if (!abandoned) {\n          await this.handleConnectError(err, false, ownsSession);\n        }\n        throw err;\n      } finally {\n        this.attachingDocs.delete(doc.getKey());\n      }\n    });\n  }\n\n  /**\n   * `detach` detaches a Document or Channel from this client.\n   * Overloaded to support both types.\n   */\n  public detach<R, P extends Indexable>(\n    resource: Document<R, P>,\n    opts?: {\n      keepalive?: boolean;\n    },\n  ): Promise<Document<R, P>>;\n\n  /**\n   * `detach` detaches the given channel from this client. The detach is a\n   * local cleanup; the server reclaims the session via TTL when heartbeats\n   * stop.\n   */\n  public detach(resource: Channel): Promise<Channel>;\n\n  /**\n   * `detach` detaches a Document or Channel from this client.\n   */\n  public detach(resource: any, opts?: any): Promise<any> {\n    if (resource instanceof Channel) {\n      return this.detachChannel(resource);\n    } else {\n      return this.detachDocument(resource, opts);\n    }\n  }\n\n  /**\n   * `detach` detaches the given document from this client. It tells the\n   * server that this client will no longer synchronize the given document.\n   *\n   * To collect garbage things like CRDT tombstones left on the document, all\n   * the changes should be applied to other replicas before GC time. For this,\n   * if the document is no longer used by this client, it should be detached.\n   *\n   * `skipPresenceClear` suppresses the presence-clear change the detach\n   * normally mints. It exists for `resync`, whose whole premise is that this\n   * client may mint no further change: the server is refusing its writes, and\n   * the discarded queue has left a `clientSeq` hole that any new change would\n   * present. The server drops the client's presence on detach regardless.\n   */\n  private detachDocument<R, P extends Indexable>(\n    doc: Document<R, P>,\n    opts: {\n      keepalive?: boolean;\n      skipPresenceClear?: boolean;\n    } = { keepalive: false },\n  ): Promise<Document<R, P>> {\n    if (!this.isActive()) {\n      throw new YorkieError(\n        Code.ErrClientNotActivated,\n        `${this.key} is not active`,\n      );\n    }\n    const attachment = this.attachmentMap.get(doc.getKey());\n    if (!attachment) {\n      throw new YorkieError(\n        Code.ErrNotAttached,\n        `${doc.getKey()} is not attached`,\n      );\n    }\n    // The presence clear is a change this document may not be in a position to\n    // mint: inside the re-anchor window `resync` opens, `update` refuses with\n    // `ErrRefused`, and that would come straight back out of `detach` — before\n    // any task is enqueued, so synchronously, at call sites that have nowhere\n    // to put it (React's unmount cleanup calls `client.detach` unguarded). The\n    // clear is a courtesy to the other peers, not part of the detach contract:\n    // the server drops this client's presence on detach regardless. So skip it\n    // when it cannot be minted rather than failing the detach over it.\n    if (!opts.skipPresenceClear && doc.isMintable()) {\n      doc.update((_, p) => p.clear());\n    }\n\n    // Mark as detaching immediately so the sync loop skips this document.\n    attachment.markDetaching();\n\n    const task = async () => {\n      // Captured before the round trip so a late `ErrClientNotFound` cannot\n      // deactivate a session that replaced this one. See `captureSession`.\n      const ownsSession = this.captureSession();\n      const ownsAttachment = () =>\n        ownsSession() && this.attachmentMap.get(doc.getKey()) === attachment;\n      try {\n        // Wait for any in-progress sync to finish before detaching.\n        await attachment.waitForSyncComplete();\n        if (!ownsAttachment()) {\n          return doc;\n        }\n\n        const res = await this.pushWithPresenceBase(\n          doc,\n          () => converter.toChangePack(doc.createChangePack()),\n          (changePack) =>\n            this.rpcClient.detachDocument(\n              {\n                clientId: this.id!,\n                documentId: attachment.resourceID,\n                changePack,\n              },\n              {\n                headers: {\n                  'x-shard-key': `${this.apiKey}/${doc.getKey()}`,\n                  ...(opts.keepalive ? { [keepaliveHeader]: '1' } : {}),\n                },\n              },\n            ),\n        );\n\n        if (!ownsAttachment()) {\n          return doc;\n        }\n        const pack = converter.fromChangePack<P>(res.changePack!);\n        doc.applyChangePack(pack);\n\n        if (doc.getStatus() !== DocStatus.Removed) {\n          doc.applyStatus(DocStatus.Detached);\n        }\n\n        this.detachInternal(doc.getKey());\n        // A detached document has no owner for its offline state, and leaving\n        // the entry makes the *next* attach in this session present a resume\n        // the server refuses for a row it just detached — which surfaces as\n        // `document already detached` rather than as anything about storage.\n        await this.removeFromStore(doc.getKey());\n        logger.info(`[DD] c:\"${this.getKey()}\" detaches d:\"${doc.getKey()}\"`);\n        return doc;\n      } catch (err) {\n        if (!ownsAttachment()) {\n          return doc;\n        }\n        logger.error(`[DD] c:\"${this.getKey()}\" err :`, err);\n        attachment.resetDetaching();\n        await this.handleConnectError(err, false, ownsSession);\n        throw err;\n      }\n    };\n\n    // The keepalive detach runs outside the queue: the caller is on its way\n    // out and a queued task would not get its turn. The request carries\n    // `keepaliveHeader`, so the transport sets `keepalive` on the fetch it\n    // actually issues.\n    if (opts.keepalive) {\n      return task();\n    }\n\n    return this.enqueueTask(task);\n  }\n\n  /**\n   * `resync` recovers a document whose local writes the server has refused\n   * (`ErrPermissionDenied` from PushPull — an owner locked the document, this\n   * member was downgraded to read-only, a share link was revoked), without\n   * forcing the app to throw the client and the `Document` away.\n   *\n   * The refused changes cannot simply be left queued: push and pull share one\n   * RPC, so every later sync re-sends them, is denied again, and the client\n   * stops receiving other peers' changes too. Nor can they be undone in place —\n   * they are already applied to `root` and there is no server-confirmed copy to\n   * fall back on. So recovery re-anchors on the server state:\n   *\n   * 1. wait for any in-flight sync, then take the un-pushed changes out of the\n   *    queue and keep them for the caller,\n   * 2. detach — with the queue empty, and the presence clear a detach usually\n   *    mints suppressed, the pack carries no changes at all, so a webhook that\n   *    refuses this client's writes has nothing left to refuse and the counter\n   *    never has to be rewound over sequences the server may already hold,\n   * 3. `resetForReanchor()`, and\n   * 4. attach the **same** `Document` instance again, under the sync mode it\n   *    had, so the server snapshot arrives through the usual events, and\n   *    restart the sync loop that the denial stopped.\n   *\n   * Keeping the instance is the point: the app's subscriptions and the editor\n   * bound to the document survive, where re-creating the client remounts them.\n   * It also means the app can still call `Document.update` while steps 1–4 are\n   * in flight, and between the discard and the re-anchor the change queue has\n   * a `clientSeq` hole no new change may be minted over. So the discard\n   * suspends minting for exactly that span: `update` and undo/redo throw\n   * `ErrRefused` until step 3 (or the rollback below) lifts it, instead of the\n   * edit wedging the detach with `ErrInvalidClientSeq` or being wiped by\n   * `resetForReanchor` with nothing reported. An edit that lands before step 1\n   * is simply part of the discarded set and reported with the rest.\n   *\n   * Returns the discarded changes so the app can report them (\"N edits were not\n   * saved\"). Re-applying them is deliberately not the default — the server\n   * refused them.\n   *\n   * Failure is accounted for rather than left half-done. If the detach is\n   * itself refused, the queue is handed back and the document is left attached\n   * exactly as it was, so the call can be retried. Once the detach has gone\n   * through the changes are gone for good, so they are published as a\n   * `local-changes-dropped` event at that moment — before the re-attach, which\n   * is the one step that can still fail with the edits already discarded. An\n   * app that only listens to that event therefore sees the loss on every path\n   * that loses something.\n   */\n  public async resync<R, P extends Indexable>(\n    doc: Document<R, P>,\n    opts: ResyncOptions<P>,\n  ): Promise<Array<ChangeStruct<P>>> {\n    if (!this.isActive()) {\n      throw new YorkieError(\n        Code.ErrClientNotActivated,\n        `${this.key} is not active`,\n      );\n    }\n\n    const attachment = this.attachmentMap.get(doc.getKey()) as\n      | Attachment<Document<R, P>>\n      | undefined;\n    if (!attachment) {\n      throw new YorkieError(\n        Code.ErrNotAttached,\n        `${doc.getKey()} is not attached`,\n      );\n    }\n\n    // Only the discarding form exists today. Requiring it explicitly keeps the\n    // data loss at the call site rather than in the default.\n    if (!opts?.discardLocalChanges) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        'resync requires discardLocalChanges: true',\n      );\n    }\n\n    // Preserve how the document was attached, so recovery is invisible to the\n    // app beyond the re-anchor itself. Presence is carried over too — the\n    // cursor the user is still holding is not part of what the server refused.\n    const syncMode = attachment.syncMode;\n    const disableGC = attachment.disableGC;\n    const pollInterval = attachment.pollIntervalPinned\n      ? attachment.pollInterval\n      : undefined;\n    const initialPresence = opts.initialPresence ?? doc.getMyPresence();\n\n    // Close the window to concurrent syncs before the queue is touched. Two\n    // hazards, and they need two different guards:\n    //\n    // - A sync already in flight. Its response removes pushed changes from the\n    //   queue by checkpoint, so discarding underneath it would apply that\n    //   removal to a queue it never saw. Every sync path — the loop and the\n    //   public `Client.sync` — runs inside the client's task queue, and that\n    //   queue runs strictly one task at a time, so taking a turn in it waits\n    //   for an in-flight sync whether or not that sync registered itself with\n    //   `setSyncPromise`. `waitForSyncComplete` alone would not be enough: a\n    //   hand-driven `Client.sync` is invisible to an attachment that was never\n    //   handed its promise. (It is kept below for the one sync-adjacent path\n    //   that runs outside the queue, a `keepalive` detach.)\n    // - A *fresh* sync starting in one of the await gaps that follow. Holding\n    //   the queue across the whole recovery is not an option — the `detach` and\n    //   `attach` below enqueue tasks of their own, and the queue is serial, so\n    //   nesting would deadlock. The span is covered instead by the detaching\n    //   flag the sync loop already honours, set here rather than left to\n    //   `detachDocument`, and cleared again on the rollback path below where\n    //   the document stays attached.\n    let discarded: Array<Change<P>> = [];\n    await this.enqueueTask(async () => {\n      attachment.markDetaching();\n      await attachment.waitForSyncComplete();\n\n      // Take the offline-persistence layer out of the picture before the queue\n      // is emptied. Its log is keyed by `clientSeq` and its watermark only\n      // moves forward, so a log left holding the discarded changes would\n      // survive the re-anchor and be replayed into a document the server has\n      // already refused them for. Unsubscribing first also stops an append\n      // from firing against a queue that is about to be emptied.\n      if (attachment.unsubscribePersist) {\n        attachment.unsubscribePersist();\n        attachment.unsubscribePersist = undefined;\n      }\n      this.persistStates.delete(this.storeKey(doc.getKey()));\n      await this.removeFromStore(doc.getKey());\n\n      discarded = doc.discardLocalChanges();\n    });\n\n    const structs = discarded.map((change) => change.toStruct());\n    logger.info(\n      `[RS] c:\"${this.getKey()}\" resync d:\"${doc.getKey()}\", ` +\n        `discarded:${discarded.length}`,\n    );\n\n    try {\n      // Detach without the presence clear a detach normally mints: the queue is\n      // empty and `discardLocalChanges` leaves the counter past the acked\n      // checkpoint, so any change minted here would present a `clientSeq` hole\n      // and be rejected with `ErrInvalidClientSeq` — turning the recovery into\n      // a second dead end. The server drops this client's presence on detach\n      // anyway, and `resetForReanchor` clears it locally a moment later.\n      await this.detachDocument(doc, { skipPresenceClear: true });\n    } catch (err) {\n      // The detach is the point of no return, and it did not happen: hand the\n      // refused changes back so the document is left exactly as it was found —\n      // still attached, queue intact, counter untouched, syncing — and the call\n      // can be retried once the webhook relents. `detachDocument` resets the\n      // detaching flag on its own failure path, but not when it throws before\n      // enqueueing, so reset it here too; it is idempotent.\n      doc.restoreLocalChanges(discarded);\n      attachment.resetDetaching();\n      logger.error(\n        `[RS] c:\"${this.getKey()}\" resync d:\"${doc.getKey()}\" detach failed; ` +\n          `local changes restored`,\n        err,\n      );\n      throw err;\n    }\n\n    // Past here the changes are gone for good, so report them before the step\n    // that can still fail. An app listening for the data-loss event gets them\n    // even if the re-attach below throws.\n    this.emitLocalChangesDropped(doc, 'write-denied', structs);\n\n    doc.resetForReanchor();\n    await this.attachDocument(doc, {\n      syncMode,\n      documentPollInterval: pollInterval,\n      disableGC,\n      initialPresence,\n    });\n\n    // The `ErrPermissionDenied` that led here stopped the sync loop:\n    // `handleConnectError` does not retry it, so the loop's catch cleared\n    // `SyncLoop` and scheduled no further tick. Re-attaching alone does not\n    // revive it — unlike `attachChannel`, `attachDocument` never starts the\n    // loop — so a recovered document would sit attached and never sync again.\n    if (!this.conditions[ClientCondition.SyncLoop]) {\n      this.runSyncLoop();\n    }\n\n    return structs;\n  }\n\n  /**\n   * `attachChannel` attaches the given channel to this client. The channel is\n   * registered locally and the server is notified on the next RefreshChannel\n   * heartbeat.\n   */\n  public async attachChannel(\n    channel: Channel,\n    opts: AttachChannelOptions = {},\n  ): Promise<Channel> {\n    if (channel.getStatus() !== ChannelStatus.Detached) {\n      throw new YorkieError(\n        Code.ErrNotDetached,\n        `${channel.getKey()} is not detached`,\n      );\n    }\n\n    const syncMode = opts.syncMode ?? SyncMode.Realtime;\n    this.assertValidChannelSyncMode(syncMode);\n\n    if (\n      opts.channelHeartbeatInterval !== undefined &&\n      opts.channelHeartbeatInterval <= 0\n    ) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        'channelHeartbeatInterval must be greater than 0',\n      );\n    }\n\n    const pollIntervalPinned = opts.channelHeartbeatInterval !== undefined;\n    const pollInterval =\n      opts.channelHeartbeatInterval ?? this.channelHeartbeatInterval;\n\n    // Capture before queueing: teardown must invalidate this attach even\n    // if activation finishes before the task runs. An inactive client is\n    // not a lost session here — channels attach without activation, so the\n    // capture only rejects an attach whose client was torn down underneath\n    // it (see `captureSession`).\n    const ownsSession = this.captureSession(true);\n    const task = async () => {\n      // Registering the channel on a client torn down since this attach was\n      // requested would leave an attachment nothing detaches and restart its\n      // sync loop.\n      if (!ownsSession()) {\n        throw new YorkieError(\n          Code.ErrClientNotActivated,\n          `${this.key} lost its session while attaching ${channel.getKey()}`,\n        );\n      }\n\n      // A new channel after completed teardown starts a fresh lazy lifecycle.\n      // The old ID and stop flag would otherwise suppress the heartbeat loop\n      // and prevent its first response from adopting the new server client ID.\n      if (!this.isActive() && (this.id !== undefined || this.deactivating)) {\n        this.id = undefined;\n        this.actorID = undefined;\n        this.deactivating = false;\n        this.conditions[ClientCondition.SyncLoop] = false;\n      }\n\n      // Channel gets its actor ID from the first refresh response. If the\n      // client was already activated (or another channel has triggered the\n      // first refresh), propagate the existing id.\n      if (this.id) {\n        channel.setActor(this.id);\n      }\n\n      const attachment = new Attachment<Channel>(\n        (err) => this.loopRetryDelay(err, this.reconnectStreamDelay),\n        channel,\n        '', // sessionID populated on first refresh response\n        syncMode,\n        pollInterval,\n        pollIntervalPinned,\n      );\n\n      // Forward local broadcast events to the RPC client. Capture the\n      // unsubscribe so `detachInternal` can tear it down — otherwise\n      // re-attaching the same channel accumulates duplicate handlers.\n      attachment.unsubscribeLocalBroadcast = channel.subscribe(\n        'local-broadcast',\n        (event) => {\n          const { topic, payload, options } = event;\n          this.broadcast(channel.getKey(), topic, payload, options).catch(\n            (error) => {\n              if (options?.error) options.error(error);\n              logger.error(`[BC] c:\"${this.getKey()}\" failed: ${error}`);\n            },\n          );\n        },\n      );\n\n      this.attachmentMap.set(channel.getKey(), attachment);\n      this.liveAttachments.set(attachment, channel.getKey());\n\n      // Make sure the sync loop is running so the first refresh fires.\n      // The watch stream is opened later by syncInternal once the first\n      // refresh response populates this.id (the watch RPC requires it).\n      if (!this.conditions[ClientCondition.SyncLoop]) {\n        this.runSyncLoop();\n      }\n\n      logger.info(\n        `[AP] c:\"${this.getKey()}\" attaches p:\"${channel.getKey()}\" mode:${syncMode}`,\n      );\n      return channel;\n    };\n\n    return this.enqueueTask(task);\n  }\n\n  /**\n   * `detachChannel` detaches the given channel from this client. The detach\n   * is a local cleanup; the server reclaims the session via TTL when\n   * heartbeats stop.\n   */\n  public async detachChannel(channel: Channel): Promise<Channel> {\n    const attachment = this.attachmentMap.get(channel.getKey()) as\n      | Attachment<Channel>\n      | undefined;\n    // The key alone is not enough: another Channel of the same key may hold\n    // it now (attached again while an earlier detach was pending), and\n    // detaching through a stale object must not take that one down.\n    if (!attachment || attachment.resource !== channel) {\n      throw new YorkieError(\n        Code.ErrNotAttached,\n        `${channel.getKey()} is not attached`,\n      );\n    }\n\n    // Mark the attachment as detaching so the sync loop's\n    // `attachment.isDetaching()` guard skips it, and wait for any\n    // in-flight RefreshChannel to finish before tearing down. Without\n    // this, a concurrent first-call refresh would land on a detached\n    // channel and emit a PresenceChanged event after the user has\n    // detached — and would even re-create the session on the server.\n    attachment.markDetaching();\n    await attachment.waitForSyncComplete();\n\n    const task = async () => {\n      // No DetachChannel RPC: the server reclaims the session via TTL.\n      // We only need local cleanup.\n      channel.applyStatus(ChannelStatus.Detached);\n      // Tear down the attachment captured above, not whatever the key holds\n      // now: a Channel of the same key attached while this detach waited is\n      // a different attachment and stays.\n      this.detachInternal(channel.getKey(), attachment);\n\n      logger.info(\n        `[DP] c:\"${this.getKey()}\" detaches p:\"${channel.getKey()}\" (local)`,\n      );\n      return channel;\n    };\n\n    return this.enqueueTask(task);\n  }\n\n  /**\n   * `changeSyncMode` changes the synchronization mode of the given document.\n   */\n  public async changeSyncMode<R, P extends Indexable>(\n    doc: Document<R, P>,\n    syncMode: SyncMode,\n  ): Promise<Document<R, P>>;\n\n  /**\n   * `changeSyncMode` changes the synchronization mode of the given channel.\n   */\n  public async changeSyncMode(\n    channel: Channel,\n    syncMode: SyncMode,\n  ): Promise<Channel>;\n\n  /**\n   * `changeSyncMode` changes the synchronization mode of the given resource.\n   */\n  public async changeSyncMode(\n    resource: Document<any, any> | Channel,\n    syncMode: SyncMode,\n  ): Promise<Document<any, any> | Channel> {\n    // The switch runs on the task queue, so it waits for a sync that is\n    // already pulling. A pause must still cover that pull: by the time its\n    // response arrives the caller has asked not to receive anything (an IME\n    // composition, for example), so mark the request now and let the\n    // response guard in `syncInternal` see it. A document that is not\n    // attached yet has no attachment to mark; its switch still applies once\n    // the queue reaches it.\n    const pausing =\n      resource instanceof Document &&\n      (syncMode === SyncMode.RealtimePushOnly ||\n        syncMode === SyncMode.RealtimeSyncOff)\n        ? this.attachmentMap.get(resource.getKey())\n        : undefined;\n    if (pausing) {\n      pausing.pendingPullPauses += 1;\n    }\n\n    return this.enqueueTask(async () => {\n      try {\n        if (resource instanceof Channel) {\n          return await this.changeChannelSyncMode(resource, syncMode);\n        }\n        return await this.changeDocumentSyncMode(resource, syncMode);\n      } finally {\n        if (pausing) {\n          pausing.pendingPullPauses -= 1;\n        }\n      }\n    });\n  }\n\n  private async changeDocumentSyncMode<R, P extends Indexable>(\n    doc: Document<R, P>,\n    syncMode: SyncMode,\n  ): Promise<Document<R, P>> {\n    if (!this.isActive()) {\n      throw new YorkieError(\n        Code.ErrClientNotActivated,\n        `${this.key} is not active`,\n      );\n    }\n\n    const attachment = this.attachmentMap.get(doc.getKey());\n    if (!attachment) {\n      throw new YorkieError(\n        Code.ErrNotAttached,\n        `${doc.getKey()} is not attached`,\n      );\n    }\n\n    const prevSyncMode = attachment.syncMode;\n    if (prevSyncMode === syncMode) {\n      return doc;\n    }\n\n    // Tear down stream first if leaving a stream-using mode (prevents the\n    // sync loop from observing an inconsistent mode while the stream is\n    // still live).\n    if (syncMode === SyncMode.Manual || syncMode === SyncMode.Polling) {\n      attachment.cancelWatchStream();\n    }\n\n    attachment.changeSyncMode(syncMode);\n\n    // NOTE(hackerwins): In non-pushpull mode, the client does not receive\n    // change events from the server. Therefore, we need to set\n    // `changeEventReceived` to true to sync the local and remote changes.\n    // This has limitations in that unnecessary syncs occur if the client\n    // and server do not have any changes.\n    if (syncMode === SyncMode.Realtime) {\n      attachment.changeEventReceived = true;\n    }\n\n    // Recompute interval default if the user did not pin it.\n    if (!attachment.pollIntervalPinned) {\n      attachment.pollInterval =\n        syncMode === SyncMode.Polling ? DefaultDocumentPollIntervalMs : 0;\n    }\n\n    // RealtimePushOnly and RealtimeSyncOff retain the watch stream, so\n    // no restart is needed when transitioning between them and Realtime.\n    // Only Manual and Polling are stream-less modes.\n    // Start watch stream if entering a stream-using mode from a stream-less one.\n    if (\n      (prevSyncMode === SyncMode.Manual || prevSyncMode === SyncMode.Polling) &&\n      syncMode !== SyncMode.Manual &&\n      syncMode !== SyncMode.Polling\n    ) {\n      attachment.resetCancelled();\n      await this.runWatchLoop(doc.getKey());\n    }\n\n    return doc;\n  }\n\n  /**\n   * `assertValidChannelSyncMode` rejects sync modes that are not valid for\n   * channels. `RealtimePushOnly` and `RealtimeSyncOff` are document-only.\n   */\n  private assertValidChannelSyncMode(syncMode: SyncMode): void {\n    if (\n      syncMode !== SyncMode.Manual &&\n      syncMode !== SyncMode.Realtime &&\n      syncMode !== SyncMode.Polling\n    ) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        `invalid channel sync mode: ${syncMode}`,\n      );\n    }\n  }\n\n  private async changeChannelSyncMode(\n    channel: Channel,\n    syncMode: SyncMode,\n  ): Promise<Channel> {\n    const attachment = this.attachmentMap.get(channel.getKey());\n    if (!attachment) {\n      throw new YorkieError(\n        Code.ErrNotAttached,\n        `${channel.getKey()} is not attached`,\n      );\n    }\n\n    const prevSyncMode = attachment.syncMode;\n    if (prevSyncMode === syncMode) {\n      return channel;\n    }\n\n    this.assertValidChannelSyncMode(syncMode);\n\n    // Tear down stream if leaving Realtime.\n    if (prevSyncMode === SyncMode.Realtime) {\n      attachment.cancelWatchStream();\n    }\n\n    attachment.changeSyncMode(syncMode);\n\n    // Recompute interval default if the user did not pin it.\n    if (!attachment.pollIntervalPinned) {\n      attachment.pollInterval =\n        syncMode === SyncMode.Manual ? 0 : this.channelHeartbeatInterval;\n    }\n\n    // Start watch stream if entering Realtime.\n    if (syncMode === SyncMode.Realtime) {\n      attachment.resetCancelled();\n      await this.runWatchLoop(channel.getKey());\n    }\n\n    return channel;\n  }\n\n  /**\n   * `sync` pushes local changes of the attached documents to the server and\n   * receives changes of the remote replica from the server then apply them to\n   * local documents.\n   *\n   * For Channel in manual mode, it refreshes the TTL by sending a heartbeat.\n   */\n  public sync<R, P extends Indexable>(\n    doc?: Document<R, P>,\n  ): Promise<Array<Document<R, P>>>;\n\n  /**\n   * `sync` refreshes the TTL of the given channel by sending a heartbeat.\n   * This is used for manual mode channel.\n   */\n  public sync(channel: Channel): Promise<Channel>;\n\n  /**\n   * `sync` implementation that handles both Document and Channel.\n   */\n  public sync<R, P extends Indexable>(\n    resource?: Document<R, P> | Channel,\n  ): Promise<Array<Document<R, P>> | Channel> {\n    if (!(resource instanceof Channel) && !this.isActive()) {\n      throw new YorkieError(\n        Code.ErrClientNotActivated,\n        `${this.key} is not active`,\n      );\n    }\n\n    if (resource instanceof Channel) {\n      const attachment = this.attachmentMap.get(\n        resource.getKey(),\n      ) as Attachment<Channel>;\n      if (!attachment) {\n        throw new YorkieError(\n          Code.ErrNotAttached,\n          `${resource.getKey()} is not attached`,\n        );\n      }\n      return this.enqueueTask(async () => {\n        // Channels sync on an inactive client too, so this capture tracks\n        // teardown only — matching the exemption above.\n        const ownsSession = this.captureSession(true);\n        return this.syncInternal(attachment).catch(async (err) => {\n          logger.error(`[SY] c:\"${this.getKey()}\" err :`, err);\n          await this.handleConnectError(err, false, ownsSession);\n          throw err;\n        });\n      }) as Promise<Channel>;\n    }\n\n    if (resource instanceof Document) {\n      // prettier-ignore\n      const attachment = this.attachmentMap.get(resource.getKey()) as Attachment<Document<R, P>>;\n      if (!attachment) {\n        throw new YorkieError(\n          Code.ErrNotAttached,\n          `${resource.getKey()} is not attached`,\n        );\n      }\n      return this.enqueueTask(async () => {\n        const ownsSession = this.captureSession();\n        return this.trackSync(\n          attachment,\n          this.syncInternal(attachment, SyncMode.Realtime),\n        ).catch(async (err) => {\n          logger.error(`[SY] c:\"${this.getKey()}\" err :`, err);\n          if (isErrorCode(err, Code.ErrEpochMismatch)) {\n            attachment.resource.publish([\n              {\n                type: DocEventType.EpochMismatch,\n                value: {\n                  method: 'PushPull',\n                },\n              },\n            ]);\n          }\n          await this.handleConnectError(err, false, ownsSession);\n          throw err;\n        });\n      }) as Promise<Array<Document<R, P>>>;\n    }\n\n    return this.enqueueTask(async () => {\n      const ownsSession = this.captureSession();\n      const promises = [];\n      for (const [, attachment] of this.attachmentMap) {\n        // Only sync Document resources that have syncMode defined\n        if (\n          attachment.syncMode !== undefined &&\n          attachment.resource instanceof Document\n        ) {\n          promises.push(\n            this.trackSync(\n              attachment,\n              this.syncInternal(\n                attachment as Attachment<Document<R, P>>,\n                attachment.syncMode,\n              ),\n            ),\n          );\n        }\n      }\n      return Promise.all(promises).catch(async (err) => {\n        logger.error(`[SY] c:\"${this.getKey()}\" err :`, err);\n        await this.handleConnectError(err, false, ownsSession);\n        throw err;\n      });\n    }) as Promise<Array<Document<R, P>>>;\n  }\n\n  /**\n   * `remove` removes the given document.\n   */\n  public remove<R, P extends Indexable>(doc: Document<R, P>): Promise<void> {\n    if (!this.isActive()) {\n      throw new YorkieError(\n        Code.ErrClientNotActivated,\n        `${this.key} is not active`,\n      );\n    }\n    const attachment = this.attachmentMap.get(doc.getKey());\n    if (!attachment) {\n      throw new YorkieError(\n        Code.ErrNotAttached,\n        `${doc.getKey()} is not attached`,\n      );\n    }\n    doc.setActor((this.actorID ?? this.id)!);\n\n    const buildPack = (): PbChangePack => {\n      const pack = converter.toChangePack(doc.createChangePack());\n      pack.isRemoved = true;\n      return pack;\n    };\n    // Built here rather than inside the task, as before: the pack a remove\n    // sends is the document as the caller saw it. A presence-base retry\n    // rebuilds it, which is the one case it has to be rebuilt -- the patch it\n    // carried has just been rewritten into a full put.\n    let pending: PbChangePack | undefined = buildPack();\n\n    const ownsSession = this.captureSession();\n    const ownsAttachment = () =>\n      ownsSession() && this.attachmentMap.get(doc.getKey()) === attachment;\n    return this.enqueueTask(async () => {\n      if (!ownsAttachment()) {\n        return;\n      }\n      try {\n        const res = await this.pushWithPresenceBase(\n          doc,\n          () => {\n            const pack = pending ?? buildPack();\n            pending = undefined;\n            return pack;\n          },\n          (changePack) =>\n            this.rpcClient.removeDocument(\n              {\n                clientId: this.id!,\n                documentId: attachment.resourceID,\n                changePack,\n              },\n              { headers: { 'x-shard-key': `${this.apiKey}/${doc.getKey()}` } },\n            ),\n        );\n\n        if (!ownsAttachment()) {\n          return;\n        }\n        const pack = converter.fromChangePack<P>(res.changePack!);\n        doc.applyChangePack(pack);\n        this.detachInternal(doc.getKey());\n        // The document is gone server-side; keeping a local envelope for it\n        // would leave the Tier-3 purge guard to discover that on some later\n        // attach.\n        await this.removeFromStore(doc.getKey());\n\n        logger.info(`[RD] c:\"${this.getKey()}\" removes d:\"${doc.getKey()}\"`);\n      } catch (err) {\n        logger.error(`[RD] c:\"${this.getKey()}\" err :`, err);\n        await this.handleConnectError(err, false, ownsSession);\n        throw err;\n      }\n    });\n  }\n\n  /**\n   * `getID` returns the per-session id of this client. It is the wire\n   * `clientId` used for RPC routing, not the actor stamped into document\n   * changes. Use {@link getActorID} for the change author.\n   */\n  public getID(): string | undefined {\n    return this.id;\n  }\n\n  /**\n   * `getActorID` returns the actor stamped into this client's document\n   * changes. On a server that supports stable actors it is the stable actor\n   * derived from the project and client key (`ActivateClientResponse.actorId`);\n   * otherwise it falls back to the per-session id. This is the actor a version\n   * vector is keyed by, so tests and callers that reason about change\n   * authorship or GC must use this, not {@link getID}.\n   */\n  public getActorID(): ActorID | undefined {\n    return this.actorID;\n  }\n\n  /**\n   * `getKey` returns a key of client.\n   */\n  public getKey(): string {\n    return this.key;\n  }\n\n  /**\n   * `storeKey` scopes a document key to this client's identity before it is\n   * used as a `DocStore` key. The session lock is already scoped by\n   * `apiKey/clientKey/docKey`; the store must match so a store shared across\n   * identities (different apiKey/clientKey) cannot collide on the bare docKey\n   * and hand one identity another's persisted envelope. Built through\n   * {@link namespaceOf}, so the scoping is injective.\n   */\n  private storeKey(docKey: string): string {\n    return namespaceOf(this.apiKey, this.key, docKey);\n  }\n\n  /**\n   * `persistToStore` saves the given bytes for a store key, serializing writes\n   * per key so concurrent saves for the same document cannot interleave and\n   * persist stale bytes (an earlier save resolving after a later one). Each key\n   * chains onto its previous save; failures are logged, not thrown, and do not\n   * break the chain for the next write. `onError` labels the log site.\n   */\n  private persistToStore(\n    storeKey: string,\n    bytes: Uint8Array,\n    onError: (err: unknown) => void,\n  ): void {\n    const store = this.store;\n    if (!store || this.persistDisabled.has(storeKey)) {\n      return;\n    }\n    const prev = this.persistQueues.get(storeKey);\n    // With no in-flight write for this key, start the write synchronously so\n    // a store whose `save` has synchronous side effects (e.g. MemoryDocStore)\n    // lands immediately, preserving the pre-serialization observable timing.\n    // Only when a previous write is still pending do we chain after it, which\n    // is exactly the interleaving case this guards against.\n    const next = (\n      prev\n        ? prev\n            .catch(() => undefined)\n            .then(() => store.saveSnapshot(storeKey, bytes))\n        : store.saveSnapshot(storeKey, bytes)\n    ).catch(onError);\n    this.persistQueues.set(storeKey, next);\n    // Drop the queue entry once this write is the tail, so the map does not grow\n    // for keys that stop being written.\n    void next.finally(() => {\n      if (this.persistQueues.get(storeKey) === next) {\n        this.persistQueues.delete(storeKey);\n      }\n    });\n  }\n\n  /**\n   * `snapshotWithinBudget` serializes a document for persistence and measures\n   * what that cost. It answers `undefined` when the cost exceeds the client's\n   * budget, having already latched persistence off for that document and\n   * published {@link DocEventType.PersistDisabled}.\n   *\n   * Every snapshot write goes through here, which is the point: the budget is\n   * only meaningful if nothing can serialize behind its back, and latching has\n   * to tear down the subscription rather than merely skip a write — otherwise\n   * each later edit keeps paying the serialization the budget exists to avoid.\n   * The waste is bounded to the one measurement that discovers the problem.\n   */\n  private snapshotWithinBudget<R, P extends Indexable>(\n    doc: Document<R, P>,\n    storeKey: string,\n  ): Uint8Array | undefined {\n    if (this.persistDisabled.has(storeKey)) {\n      return undefined;\n    }\n    const startedAt = Date.now();\n    const bytes = doc.toBytes();\n    const millis = Date.now() - startedAt;\n\n    const tooLarge =\n      this.maxPersistBytes !== undefined && bytes.length > this.maxPersistBytes;\n    const tooSlow =\n      this.maxPersistMillis !== undefined && millis > this.maxPersistMillis;\n    if (!tooLarge && !tooSlow) {\n      return bytes;\n    }\n\n    logger.warn(\n      `[PS] c:\"${this.getKey()}\" d:\"${doc.getKey()}\" persistence disabled ` +\n        `(${bytes.length} bytes, ${millis}ms)`,\n    );\n    this.persistDisabled.add(storeKey);\n    this.persistStates.delete(storeKey);\n    const attachment = this.attachmentMap.get(doc.getKey());\n    if (attachment?.unsubscribePersist) {\n      attachment.unsubscribePersist();\n      attachment.unsubscribePersist = undefined;\n    }\n    doc.publish([\n      {\n        type: DocEventType.PersistDisabled,\n        value: {\n          reason: tooLarge ? 'too-large' : 'too-slow',\n          bytes: bytes.length,\n          millis,\n        },\n      },\n    ]);\n    return undefined;\n  }\n\n  /**\n   * `persistSnapshotOrPoison` writes a snapshot and re-poisons the log if that\n   * write fails.\n   *\n   * Every snapshot write is also a *repair*: the callers reset the log\n   * accounting and clear `poisoned` before it resolves, so that appends can\n   * resume immediately. If the write then rejects, the store still holds the\n   * old snapshot and whatever holed log went with it, while the client\n   * believes the log is clean — the next append lands past the hole and the\n   * following restore discards everything since the base snapshot. A\n   * randomized fuzz over the transition space wedged 8 of 60 seeds this way.\n   *\n   * Re-poisoning makes the next edit try the snapshot again, which is the\n   * behaviour the design's failure table already describes.\n   */\n  private persistSnapshotOrPoison(\n    storeKey: string,\n    bytes: Uint8Array,\n    onError: (err: unknown) => void,\n  ): void {\n    this.persistToStore(storeKey, bytes, (err) => {\n      // Re-read: a latch or a detach may have replaced or removed this entry\n      // between the write and its rejection.\n      const current = this.persistStates.get(storeKey);\n      if (current) {\n        current.poisoned = true;\n      }\n      onError(err);\n    });\n  }\n\n  /**\n   * `appendToStore` appends one change for a store key, chained onto the same\n   * per-key write queue `persistToStore` uses so an append can never overtake\n   * the snapshot it belongs after. Failures are logged, not thrown: the store\n   * may trail the document, and must never break the editing path.\n   */\n  private appendToStore(\n    storeKey: string,\n    change: StoredChange,\n    onError: (err: unknown) => void,\n  ): void {\n    const store = this.store;\n    if (!store || this.persistDisabled.has(storeKey)) {\n      return;\n    }\n    const prev = this.persistQueues.get(storeKey);\n    const next = (\n      prev\n        ? prev\n            .catch(() => undefined)\n            .then(() => store.appendChange(storeKey, change))\n        : store.appendChange(storeKey, change)\n    ).catch(onError);\n    this.persistQueues.set(storeKey, next);\n    void next.finally(() => {\n      if (this.persistQueues.get(storeKey) === next) {\n        this.persistQueues.delete(storeKey);\n      }\n    });\n  }\n\n  /**\n   * `saveMetaToStore` records the post-sync header, leaving the snapshot and\n   * the change log intact. It does **not** drop acknowledged entries: the log\n   * is the delta between the snapshot and current content as well as the queue\n   * of un-pushed changes, and a push-ack brings the snapshot no further\n   * forward, so trimming would leave that content in neither place. Only\n   * compaction trims, by folding the entries into a new snapshot first.\n   *\n   * Deliberately not a snapshot: an online client syncs\n   * constantly, and re-serializing per sync would reintroduce the cost the\n   * incremental path removes.\n   */\n  private saveMetaToStore(\n    storeKey: string,\n    bytes: Uint8Array,\n    onError: (err: unknown) => void,\n  ): void {\n    const store = this.store;\n    if (!store || this.persistDisabled.has(storeKey)) {\n      return;\n    }\n    // The accounting is untouched: `saveMeta` no longer trims the log, so the\n    // entries it describes are all still there and still count toward the\n    // compaction threshold.\n    const prev = this.persistQueues.get(storeKey);\n    const next = (\n      prev\n        ? prev\n            .catch(() => undefined)\n            .then(() => store.saveMeta(storeKey, bytes))\n        : store.saveMeta(storeKey, bytes)\n    ).catch(onError);\n    this.persistQueues.set(storeKey, next);\n    void next.finally(() => {\n      if (this.persistQueues.get(storeKey) === next) {\n        this.persistQueues.delete(storeKey);\n      }\n    });\n  }\n\n  /**\n   * `removeFromStore` clears the persisted envelope for a document key, scoped\n   * to this client's identity. A flaky store must not abort the attach/recover\n   * path, so a rejection is logged rather than thrown.\n   */\n  private async removeFromStore(docKey: string): Promise<void> {\n    if (!this.store) {\n      return;\n    }\n    const store = this.store;\n    const storeKey = this.storeKey(docKey);\n    // Chained on the same per-key queue as the writes. Bypassing it lets an\n    // in-flight write resurrect the entry the remove exists to destroy — and\n    // every caller here removes precisely because the envelope must never be\n    // restored again.\n    const prev = this.persistQueues.get(storeKey);\n    const next = (\n      prev\n        ? prev.catch(() => undefined).then(() => store.remove(storeKey))\n        : store.remove(storeKey)\n    ).catch((err) => {\n      logger.warn(\n        `[PS] c:\"${this.getKey()}\" d:\"${docKey}\" store remove failed:`,\n        err,\n      );\n    });\n    this.persistQueues.set(storeKey, next);\n    void next.finally(() => {\n      if (this.persistQueues.get(storeKey) === next) {\n        this.persistQueues.delete(storeKey);\n      }\n    });\n    await next;\n  }\n\n  /**\n   * `emitLocalChangesDropped` surfaces an app-visible data-loss event carrying\n   * the un-pushed local changes the offline-persistence layer had to discard.\n   * The design mandates raising this instead of silently dropping edits when a\n   * persisted envelope cannot be reconciled with the server (a stale-epoch\n   * re-anchor, a server-side purge, or a store reused under a different actor).\n   */\n  private emitLocalChangesDropped<R, P extends Indexable>(\n    doc: Document<R, P>,\n    reason: LocalChangesDroppedReason,\n    changes: Array<ChangeStruct<P>>,\n  ): void {\n    doc.publish([\n      {\n        type: DocEventType.LocalChangesDropped,\n        value: { reason, changes },\n      },\n    ]);\n  }\n\n  /**\n   * `isActive` checks if the client is active.\n   */\n  public isActive(): boolean {\n    return this.status === ClientStatus.Activated;\n  }\n\n  /**\n   * `getStatus` returns the status of this client.\n   */\n  public getStatus(): ClientStatus {\n    return this.status;\n  }\n\n  /**\n   * `getCondition` returns the condition of this client.\n   */\n  public getCondition(condition: ClientCondition): boolean {\n    return this.conditions[condition];\n  }\n\n  /**\n   * `createRevision` creates a new revision for the given document.\n   */\n  public async createRevision<R, P extends Indexable>(\n    doc: Document<R, P>,\n    label: string,\n    description?: string,\n  ): Promise<RevisionSummary> {\n    if (!this.isActive()) {\n      throw new YorkieError(\n        Code.ErrClientNotActivated,\n        `${this.key} is not active`,\n      );\n    }\n    const attachment = this.attachmentMap.get(doc.getKey());\n    if (!attachment) {\n      throw new YorkieError(\n        Code.ErrNotAttached,\n        `${doc.getKey()} is not attached`,\n      );\n    }\n\n    const task = async () => {\n      const ownsSession = this.captureSession();\n      try {\n        const res = await this.rpcClient.createRevision(\n          {\n            clientId: this.id!,\n            documentId: attachment.resourceID,\n            label,\n            description: description || '',\n          },\n          { headers: { 'x-shard-key': `${this.apiKey}/${doc.getKey()}` } },\n        );\n\n        if (!res.revision) {\n          throw new YorkieError(\n            Code.ErrInvalidArgument,\n            'revision is not returned',\n          );\n        }\n\n        logger.info(\n          `[CR] c:\"${this.getKey()}\" creates revision d:\"${doc.getKey()}\" l:\"${label}\"`,\n        );\n\n        return converter.toRevisionSummary(res.revision);\n      } catch (err) {\n        logger.error(`[CR] c:\"${this.getKey()}\" err :`, err);\n        await this.handleConnectError(err, false, ownsSession);\n        throw err;\n      }\n    };\n\n    return this.enqueueTask(task);\n  }\n\n  /**\n   * `listRevisions` lists all revisions for the given document.\n   */\n  public async listRevisions<R, P extends Indexable>(\n    doc: Document<R, P>,\n    options?: {\n      pageSize?: number;\n      offset?: number;\n      isForward?: boolean;\n    },\n  ): Promise<Array<RevisionSummary>> {\n    if (!this.isActive()) {\n      throw new YorkieError(\n        Code.ErrClientNotActivated,\n        `${this.key} is not active`,\n      );\n    }\n    const attachment = this.attachmentMap.get(doc.getKey());\n    if (!attachment) {\n      throw new YorkieError(\n        Code.ErrNotAttached,\n        `${doc.getKey()} is not attached`,\n      );\n    }\n\n    const task = async () => {\n      const ownsSession = this.captureSession();\n      try {\n        const res = await this.rpcClient.listRevisions(\n          {\n            clientId: this.id!,\n            documentId: attachment.resourceID,\n            pageSize: options?.pageSize || 10,\n            offset: options?.offset || 0,\n            isForward: options?.isForward ?? false,\n          },\n          { headers: { 'x-shard-key': `${this.apiKey}/${doc.getKey()}` } },\n        );\n\n        logger.info(\n          `[LR] c:\"${this.getKey()}\" lists revisions d:\"${doc.getKey()}\" count:${\n            res.revisions.length\n          }`,\n        );\n\n        return res.revisions.map(converter.toRevisionSummary);\n      } catch (err) {\n        logger.error(`[LR] c:\"${this.getKey()}\" err :`, err);\n        await this.handleConnectError(err, false, ownsSession);\n        throw err;\n      }\n    };\n\n    return this.enqueueTask(task);\n  }\n\n  /**\n   * `getRevision` retrieves a specific revision by its ID with full snapshot data.\n   */\n  public async getRevision<R, P extends Indexable>(\n    doc: Document<R, P>,\n    revisionID: string,\n  ): Promise<RevisionSummary> {\n    if (!this.isActive()) {\n      throw new YorkieError(\n        Code.ErrClientNotActivated,\n        `${this.key} is not active`,\n      );\n    }\n    const attachment = this.attachmentMap.get(doc.getKey());\n    if (!attachment) {\n      throw new YorkieError(\n        Code.ErrNotAttached,\n        `${doc.getKey()} is not attached`,\n      );\n    }\n\n    const task = async () => {\n      const ownsSession = this.captureSession();\n      try {\n        const res = await this.rpcClient.getRevision(\n          {\n            clientId: this.id!,\n            documentId: attachment.resourceID,\n            revisionId: revisionID,\n          },\n          { headers: { 'x-shard-key': `${this.apiKey}/${doc.getKey()}` } },\n        );\n\n        if (!res.revision) {\n          throw new YorkieError(\n            Code.ErrInvalidArgument,\n            'revision is not returned',\n          );\n        }\n\n        logger.info(\n          `[GR] c:\"${this.getKey()}\" gets revision d:\"${doc.getKey()}\" r:\"${revisionID}\"`,\n        );\n\n        return converter.toRevisionSummary(res.revision);\n      } catch (err) {\n        logger.error(`[GR] c:\"${this.getKey()}\" err :`, err);\n        await this.handleConnectError(err, false, ownsSession);\n        throw err;\n      }\n    };\n\n    return this.enqueueTask(task);\n  }\n\n  /**\n   * `restoreRevision` restores the document to the given revision.\n   */\n  public async restoreRevision<R, P extends Indexable>(\n    doc: Document<R, P>,\n    revisionId: string,\n  ): Promise<void> {\n    if (!this.isActive()) {\n      throw new YorkieError(\n        Code.ErrClientNotActivated,\n        `${this.key} is not active`,\n      );\n    }\n    const attachment = this.attachmentMap.get(doc.getKey());\n    if (!attachment) {\n      throw new YorkieError(\n        Code.ErrNotAttached,\n        `${doc.getKey()} is not attached`,\n      );\n    }\n\n    const task = async () => {\n      const ownsSession = this.captureSession();\n      try {\n        await this.rpcClient.restoreRevision(\n          {\n            clientId: this.id!,\n            documentId: attachment.resourceID,\n            revisionId,\n          },\n          { headers: { 'x-shard-key': `${this.apiKey}/${doc.getKey()}` } },\n        );\n\n        logger.info(\n          `[RR] c:\"${this.getKey()}\" restores revision d:\"${doc.getKey()}\" r:\"${revisionId}\"`,\n        );\n      } catch (err) {\n        logger.error(`[RR] c:\"${this.getKey()}\" err :`, err);\n        await this.handleConnectError(err, false, ownsSession);\n        throw err;\n      }\n    };\n\n    return this.enqueueTask(task);\n  }\n\n  /**\n   * `peekChannel` reads the current session count of a channel without\n   * creating a session on the server. Use this when the caller only needs\n   * to display the count (e.g. \"N people writing\") without contributing to\n   * it and without receiving broadcasts.\n   *\n   * Unlike `attach({ readOnly: true })`, this does not occupy a `Session`\n   * entry on the server, does not generate heartbeat RPCs, and does not\n   * subscribe to channel events. Polling is the caller's responsibility.\n   */\n  public async peekChannel(channelKey: string): Promise<number> {\n    return this.enqueueTask(async () => {\n      const firstKeyPath = channelKey.split('.')[0];\n      const res = await this.rpcClient.peekChannel(\n        { channelKey },\n        {\n          headers: {\n            'x-shard-key': `${this.apiKey}/${firstKeyPath}`,\n          },\n        },\n      );\n      return Number(res.sessionCount);\n    });\n  }\n\n  /**\n   * `broadcast` broadcasts the given payload to the given topic.\n   */\n  public async broadcast(\n    key: Key,\n    topic: string,\n    payload: any,\n    options?: BroadcastOptions,\n  ): Promise<void> {\n    const attachment = this.attachmentMap.get(key);\n    if (!attachment) {\n      throw new YorkieError(Code.ErrNotAttached, `${key} is not attached`);\n    }\n\n    if (!validateSerializable(payload)) {\n      throw new YorkieError(\n        Code.ErrInvalidArgument,\n        'payload is not serializable',\n      );\n    }\n\n    const ch = attachment.resource as Channel;\n\n    const maxRetries =\n      options?.maxRetries ?? DefaultBroadcastOptions.maxRetries;\n    const maxBackoff = DefaultBroadcastOptions.maxBackoff;\n\n    let retryCount = 0;\n\n    const exponentialBackoff = (retryCount: number) => {\n      const retryInterval = Math.min(\n        DefaultBroadcastOptions.initialRetryInterval * 2 ** retryCount,\n        maxBackoff,\n      );\n      return retryInterval;\n    };\n\n    const doLoop = async (): Promise<void> => {\n      return this.enqueueTask(async () => {\n        const ownsSession = this.captureSession();\n        try {\n          await this.rpcClient.broadcast(\n            {\n              clientId: this.id!,\n              channelKey: key,\n              topic,\n              payload: new TextEncoder().encode(JSON.stringify(payload)),\n            },\n            {\n              headers: {\n                'x-shard-key': `${this.apiKey}/${ch.getFirstKeyPath()}`,\n              },\n            },\n          );\n\n          logger.info(\n            `[BC] c:\"${this.getKey()}\" broadcasts p:\"${key}\" t:\"${topic}\"`,\n          );\n        } catch (err) {\n          logger.error(`[BC] c:\"${this.getKey()}\" err:`, err);\n\n          // Only the retries are a loop: the first try is the app's call.\n          if (await this.handleConnectError(err, retryCount > 0, ownsSession)) {\n            // Publish auth-error event before handling the error\n            if (isErrorCode(err, Code.ErrUnauthenticated)) {\n              if (attachment.resource instanceof Channel) {\n                attachment.resource.publish({\n                  type: ChannelEventType.AuthError,\n                  reason: errorMetadataOf(err).reason || 'unauthenticated',\n                  method: 'Broadcast',\n                });\n              }\n            }\n\n            if (retryCount < maxRetries) {\n              retryCount++;\n              setTimeout(\n                () => doLoop(),\n                this.loopRetryDelay(err, exponentialBackoff(retryCount - 1)),\n              );\n              logger.info(\n                `[BC] c:\"${this.getKey()}\" retry attempt ${retryCount}/${maxRetries}`,\n              );\n            } else {\n              logger.error(\n                `[BC] c:\"${this.getKey()}\" exceeded maximum retry attempts`,\n              );\n              throw err; // Stop retrying after maxRetries\n            }\n          }\n        }\n      });\n    };\n\n    return doLoop();\n  }\n\n  /**\n   * `runSyncLoop` runs the sync loop. The sync loop pushes local changes to\n   * the server and pulls remote changes from the server.\n   */\n  private runSyncLoop(): void {\n    // A loop started earlier may still have a retry pending, up to 5s away\n    // after a 401 (`loopRetryDelay`), when `activate` starts this one; it\n    // must not run alongside.\n    const generation = ++this.syncLoopGeneration;\n    const doLoop = async (): Promise<void> => {\n      if (generation !== this.syncLoopGeneration) {\n        return;\n      }\n      if (this.deactivating) {\n        logger.debug(`[SL] c:\"${this.getKey()}\" exit sync loop (deactivating)`);\n        this.conditions[ClientCondition.SyncLoop] = false;\n        return;\n      }\n      // Stop the loop only when nothing remains to sync. A channel-only client\n      // has no `Activated` status until the first refresh succeeds, but its\n      // attachment is enough to keep ticking.\n      if (!this.isActive() && this.attachmentMap.size === 0) {\n        logger.debug(`[SL] c:\"${this.getKey()}\" exit sync loop (idle)`);\n        this.conditions[ClientCondition.SyncLoop] = false;\n        return;\n      }\n\n      // Set when the task gets its turn, so the catch below judges the error\n      // against the session whose `clientId` the syncs actually carried. A\n      // `keepalive` deactivate can have torn this one down — and the app can\n      // have activated a new one — while the syncs were in flight.\n      let ownsSession = () => true;\n      try {\n        await this.enqueueTask(async () => {\n          ownsSession = this.captureSession();\n          const syncs: Array<any> = [];\n          for (const [, attachment] of this.attachmentMap) {\n            // Stop syncing if client is being deactivated.\n            if (this.deactivating) {\n              break;\n            }\n\n            if (!attachment.needSync(this.channelHeartbeatInterval)) {\n              continue;\n            }\n\n            // Skip documents that are being detached.\n            if (attachment.isDetaching()) {\n              continue;\n            }\n\n            // Skip a document whose last push the server rejected outright:\n            // resending the same pack cannot change its verdict. Only this\n            // attachment is parked; the loop keeps syncing the rest and keeps\n            // the channel heartbeats going. An explicit `client.sync(doc)`\n            // after the document is shrunk clears it.\n            if (attachment.isWriteRejected()) {\n              continue;\n            }\n\n            // Reset changeEventReceived for Document resources\n            const changeEventReceived = attachment.changeEventReceived;\n            if (attachment.changeEventReceived !== undefined) {\n              attachment.changeEventReceived = false;\n            }\n\n            const syncPromise = this.syncInternal(\n              attachment,\n              attachment.syncMode!,\n            )\n              .then(() => {})\n              .catch((e) => {\n                // The pull this sync owed a remote change never happened, so\n                // put the flag back: with no local changes, `needSync` would\n                // otherwise skip the document on the retry, and the change\n                // would wait for the next remote event or Watch reconnect.\n                if (changeEventReceived) {\n                  attachment.changeEventReceived = true;\n                }\n\n                // `ErrPermissionDenied` rides the same event as\n                // `ErrUnauthenticated`: both mean the server refused this\n                // client's writes, and the app needs to tell that apart from a\n                // network failure — `sync-failed` alone cannot. A denial\n                // arriving before the app's own revocation signal (a lock, a\n                // role downgrade, a revoked link) is often the *first* notice\n                // it gets, and it is the trigger for `Client.resync`.\n                if (\n                  isErrorCode(e, Code.ErrUnauthenticated) ||\n                  isErrorCode(e, Code.ErrPermissionDenied)\n                ) {\n                  attachment.resource.publish([\n                    {\n                      type: DocEventType.AuthError,\n                      value: {\n                        reason: errorMetadataOf(e).reason,\n                        method: 'PushPull',\n                      },\n                    },\n                  ]);\n                }\n\n                if (isErrorCode(e, Code.ErrEpochMismatch)) {\n                  attachment.resource.publish([\n                    {\n                      type: DocEventType.EpochMismatch,\n                      value: {\n                        method: 'PushPull',\n                      },\n                    },\n                  ]);\n                }\n\n                // A rejected write is this document's problem, not the\n                // client's: park the attachment and swallow the error here,\n                // so it never reaches `Promise.all` below. Letting it through\n                // would take `handleConnectError` down the non-retry path and\n                // stop the loop for every other attached document and for the\n                // channel heartbeats that keep their sessions alive.\n                // `syncInternal` has already published `write-rejected` on the\n                // document, so the app still learns why this one stopped.\n                if (\n                  unretryableWriteCodes.some((code) => isErrorCode(e, code))\n                ) {\n                  attachment.markWriteRejected();\n                  return;\n                }\n\n                throw e;\n              })\n              .finally(() => {\n                attachment.clearSyncPromise();\n              });\n\n            attachment.setSyncPromise(syncPromise);\n            syncs.push(syncPromise);\n          }\n\n          await Promise.all(syncs);\n          setTimeout(doLoop, this.syncLoopDuration);\n        });\n      } catch (err) {\n        // If the client is deactivating, suppress sync errors from\n        // in-flight RPCs and stop the sync loop quietly.\n        if (this.deactivating) {\n          this.conditions[ClientCondition.SyncLoop] = false;\n          return;\n        }\n\n        logger.error(`[SL] c:\"${this.getKey()}\" sync failed:`, err);\n        if (await this.handleConnectError(err, true, ownsSession)) {\n          setTimeout(doLoop, this.loopRetryDelay(err, this.retrySyncLoopDelay));\n        } else {\n          this.conditions[ClientCondition.SyncLoop] = false;\n        }\n      }\n    };\n\n    logger.debug(`[SL] c:\"${this.getKey()}\" run sync loop`);\n    this.conditions[ClientCondition.SyncLoop] = true;\n    doLoop();\n  }\n\n  /**\n   * `runWatchLoop` runs the watch loop for the given resource (Document or Channel).\n   * The watch loop listens to the events of the given resource from the server.\n   */\n  private async runWatchLoop(key: Key): Promise<void> {\n    const attachment = this.attachmentMap.get(key);\n    if (!attachment) {\n      throw new YorkieError(Code.ErrNotAttached, `${key} is not attached`);\n    }\n\n    this.conditions[ClientCondition.WatchLoop] = true;\n    return attachment.runWatchLoop(\n      (\n        onDisconnect: (err?: unknown) => void,\n        ac: AbortController,\n      ): Promise<[WatchStream, AbortController]> => {\n        if (!this.isActive()) {\n          this.conditions[ClientCondition.WatchLoop] = false;\n          return Promise.reject(\n            new YorkieError(\n              Code.ErrClientNotActivated,\n              `${this.key} is not active`,\n            ),\n          );\n        }\n\n        // NOTE(hackerwins): Check if the resource is still attached to prevent\n        // watch stream creation after detachment.\n        if (!this.attachmentMap.has(key)) {\n          this.conditions[ClientCondition.WatchLoop] = false;\n          return Promise.reject(\n            new YorkieError(Code.ErrNotAttached, `${key} is not attached`),\n          );\n        }\n\n        // Create watch stream based on resource type\n        if (attachment.resource instanceof Document) {\n          return this.createDocumentWatchStream(\n            attachment as Attachment<Document<any, any>>,\n            key,\n            ac,\n            onDisconnect,\n          );\n        } else if (attachment.resource instanceof Channel) {\n          return this.createChannelWatchStream(\n            attachment as Attachment<Channel>,\n            key,\n            ac,\n            onDisconnect,\n          );\n        }\n\n        return Promise.reject(\n          new YorkieError(\n            Code.ErrClientNotActivated,\n            `Unknown resource type for ${key}`,\n          ),\n        );\n      },\n    );\n  }\n\n  /**\n   * `createDocumentWatchStream` creates a watch stream for a Document.\n   * @internal\n   */\n  private createDocumentWatchStream<R, P extends Indexable>(\n    attachment: Attachment<Document<R, P>>,\n    key: Key,\n    ac: AbortController,\n    onDisconnect: (err?: unknown) => void,\n  ): Promise<[WatchStream, AbortController]> {\n    // The session this stream belongs to, captured with the `clientId`\n    // it is opened under: a late error must not deactivate a session that\n    // a `keepalive` deactivate and a re-activation have since replaced.\n    const ownsSession = this.captureSession();\n    const stream = this.rpcClient.watch(\n      {\n        clientId: this.id!,\n        // Declare the stable actor so the server keys watch peers and\n        // watched/unwatched events by the same actor stamped into presence\n        // changes. Send it or nothing (never the session id, which the server\n        // rejects as a mismatch); an empty value makes the server fall back to\n        // the session id, as old SDKs get by omitting the field.\n        actorId: this.actorID ?? '',\n        heartbeatIntervalMs: this.watchHeartbeatIntervalMs,\n        resources: [\n          {\n            resource: {\n              case: 'document',\n              value: { documentId: attachment.resourceID },\n            },\n          },\n        ],\n      },\n      {\n        headers: { 'x-shard-key': `${this.apiKey}/${key}` },\n        signal: ac.signal,\n      },\n    );\n\n    attachment.resource.publish([\n      {\n        type: DocEventType.ConnectionChanged,\n        value: StreamConnectionStatus.Connected,\n      },\n    ]);\n    logger.info(`[WD] c:\"${this.getKey()}\" watches d:\"${key}\"`);\n\n    // NOTE(hackerwins): Set changeEventReceived to true to prevent\n    // event stream gap issues. This ensures sync loop continues even when\n    // no remote change events are received immediately after watch stream starts.\n    if (attachment.changeEventReceived !== undefined) {\n      attachment.changeEventReceived = true;\n    }\n\n    const resetAndPublishDisconnect = () => {\n      attachment.resource.resetOnlineClients();\n      attachment.resource.publish([\n        {\n          type: DocEventType.Initialized,\n          source: OpSource.Local,\n          value: attachment.resource.getPresences(),\n        },\n      ]);\n      attachment.resource.publish([\n        {\n          type: DocEventType.ConnectionChanged,\n          value: StreamConnectionStatus.Disconnected,\n        },\n      ]);\n    };\n\n    return runWatchStream(\n      {\n        stream,\n        ac,\n        isInit: (resp) => resp.body.case === 'initialization',\n        heartbeatIntervalOf: watchHeartbeatInterval,\n        onResponse: (resp) =>\n          this.handleWatchDocumentResponse(attachment, resp),\n        onStreamEnd: () => {\n          resetAndPublishDisconnect();\n          logger.debug(`[WD] c:\"${this.getKey()}\" unwatches (stream ended)`);\n        },\n        onError: (err) => {\n          resetAndPublishDisconnect();\n          logger.debug(`[WD] c:\"${this.getKey()}\" unwatches`, err);\n          if (isErrorCode(err, Code.ErrUnauthenticated)) {\n            attachment.resource.publish([\n              {\n                type: DocEventType.AuthError,\n                value: {\n                  reason: errorMetadataOf(err).reason,\n                  method: 'Watch',\n                },\n              },\n            ]);\n          }\n        },\n        onDisconnect,\n      },\n      (err) => this.handleConnectError(err, true, ownsSession),\n      () => {\n        this.conditions[ClientCondition.WatchLoop] = false;\n      },\n    );\n  }\n\n  /**\n   * `createChannelWatchStream` creates a watch stream for a Channel.\n   * @internal\n   */\n  private createChannelWatchStream(\n    attachment: Attachment<Channel>,\n    key: Key,\n    ac: AbortController,\n    onDisconnect: (err?: unknown) => void,\n  ): Promise<[WatchStream, AbortController]> {\n    // The session this stream belongs to, captured with the `clientId`\n    // it is opened under: a late error must not deactivate a session that\n    // a `keepalive` deactivate and a re-activation have since replaced.\n    const ownsSession = this.captureSession();\n    const stream = this.rpcClient.watch(\n      {\n        clientId: this.id!,\n        heartbeatIntervalMs: this.watchHeartbeatIntervalMs,\n        resources: [\n          {\n            resource: {\n              case: 'channel',\n              value: { channelKey: key },\n            },\n          },\n        ],\n      },\n      {\n        headers: {\n          'x-shard-key': `${\n            this.apiKey\n          }/${attachment.resource.getFirstKeyPath()}`,\n        },\n        signal: ac.signal,\n      },\n    );\n\n    logger.info(`[WP] c:\"${this.getKey()}\" watches p:\"${key}\"`);\n\n    return runWatchStream(\n      {\n        stream,\n        ac,\n        isInit: (resp) => resp.body.case === 'initialization',\n        heartbeatIntervalOf: watchHeartbeatInterval,\n        onResponse: (resp) => this.handleWatchChannelResponse(attachment, resp),\n        onStreamEnd: () => {\n          logger.debug(`[WP] c:\"${this.getKey()}\" p:\"${key}\" stream ended`);\n        },\n        onError: (err) => {\n          logger.debug(`[WP] c:\"${this.getKey()}\" p:\"${key}\" err:`, err);\n        },\n        onDisconnect,\n        shouldIgnoreError: (err) => {\n          if (err instanceof Error && err.name === 'AbortError') {\n            logger.debug(`[WP] c:\"${this.getKey()}\" p:\"${key}\" stream aborted`);\n            return true;\n          }\n          return false;\n        },\n      },\n      (err) => this.handleConnectError(err, true, ownsSession),\n      () => {\n        this.conditions[ClientCondition.WatchLoop] = false;\n      },\n    );\n  }\n\n  /**\n   * `handleWatchChannelResponse` handles the watch channel response from the server.\n   * This method parses the protocol buffer response and updates the channel.\n   * @internal\n   */\n  private handleWatchChannelResponse(\n    attachment: Attachment<Channel>,\n    resp: WatchResponse,\n  ) {\n    const channel = attachment.resource;\n\n    if (resp.body.case === 'initialization') {\n      for (const ri of resp.body.value.resourceInits) {\n        if (ri.init.case === 'channelInit') {\n          const { sessionCount, seq } = ri.init.value;\n          if (channel.updateSessionCount(Number(sessionCount), Number(seq))) {\n            channel.publish({\n              type: ChannelEventType.Initialized,\n              count: Number(sessionCount),\n            });\n          }\n        }\n      }\n      return;\n    }\n\n    if (resp.body.case === 'event') {\n      const watchEvent = resp.body.value;\n      if (watchEvent.event.case === 'channelEvent') {\n        const event = watchEvent.event.value.event;\n        if (!event) return;\n\n        // Handle broadcast events\n        if (event.type === PbChannelEventType.BROADCAST) {\n          const decoder = new TextDecoder();\n          try {\n            const payload = JSON.parse(decoder.decode(event.payload));\n            channel.publish({\n              type: ChannelEventType.Broadcast,\n              clientID: event.publisher,\n              topic: event.topic,\n              payload,\n            });\n          } catch (err) {\n            logger.error(\n              `[WP] c:\"${this.getKey()}\" failed to parse broadcast payload:`,\n              err,\n            );\n          }\n          return;\n        }\n\n        // Handle count change events\n        if (\n          channel.updateSessionCount(\n            Number(event.sessionCount),\n            Number(event.seq),\n          )\n        ) {\n          channel.publish({\n            type: ChannelEventType.PresenceChanged,\n            count: Number(event.sessionCount),\n          });\n        }\n      }\n    }\n  }\n\n  private handleWatchDocumentResponse<R, P extends Indexable>(\n    attachment: Attachment<Document<R, P>>,\n    resp: WatchResponse,\n  ) {\n    if (resp.body.case === 'initialization') {\n      for (const ri of resp.body.value.resourceInits) {\n        if (ri.init.case === 'documentInit') {\n          attachment.resource.applyWatchInit(ri.init.value.clientIds);\n        }\n      }\n      return;\n    }\n\n    if (resp.body.case === 'event') {\n      const watchEvent = resp.body.value;\n      if (watchEvent.event.case === 'docEvent') {\n        const docEvent = watchEvent.event.value;\n        if (docEvent.event?.type === PbDocEventType.DOCUMENT_CHANGED) {\n          if (attachment.changeEventReceived !== undefined) {\n            attachment.changeEventReceived = true;\n          }\n          return;\n        }\n        if (docEvent.event) {\n          attachment.resource.applyDocEvent(\n            docEvent.event.type,\n            docEvent.event.publisher,\n          );\n        }\n      }\n    }\n  }\n\n  private deactivateInternal() {\n    this.sessionGeneration++;\n    this.status = ClientStatus.Deactivated;\n\n    // Walk every live attachment, not just the ones `attachmentMap` still\n    // names: an attachment a same-key attach evicted from the map is\n    // unreachable by key, and leaving it here keeps its watch stream open and\n    // its session lock held on a client the caller has deactivated. The map\n    // is folded in too so teardown stays complete even if an attachment ever\n    // reaches it without being registered as live.\n    const pending = new Map(this.liveAttachments);\n    for (const [key, attachment] of this.attachmentMap) {\n      if (!pending.has(attachment)) {\n        pending.set(attachment, key);\n      }\n    }\n    for (const [attachment, key] of pending) {\n      this.detachInternal(key, attachment);\n      if (attachment.resource instanceof Document) {\n        attachment.resource.applyStatus(DocStatus.Detached);\n      } else if (attachment.resource instanceof Channel) {\n        attachment.resource.applyStatus(ChannelStatus.Detached);\n      }\n    }\n  }\n\n  private detachInternal(\n    key: Key,\n    attachment: Attachment<Attachable> | undefined = this.attachmentMap.get(\n      key,\n    ),\n  ) {\n    // NOTE(hackerwins): If attachment is not found, it means that the document\n    // has been already detached by another routine.\n    // This can happen when detach or remove is called while the watch loop is\n    // running.\n    if (!attachment) {\n      return;\n    }\n    // The state kept by key belongs to whichever attachment the key holds.\n    // When a caller tears down an attachment the key no longer holds (a\n    // same-key resource was attached since), only that attachment's own\n    // resources go; the key's state stays with the newer one.\n    const ownsKey = this.attachmentMap.get(key) === attachment;\n\n    attachment.cancelWatchStream();\n    // Tear down the `local-broadcast` subscription installed by\n    // attachChannel, if any. Without this a re-attach would stack\n    // duplicate handlers on the same channel.\n    if (attachment.unsubscribeLocalBroadcast) {\n      attachment.unsubscribeLocalBroadcast();\n      attachment.unsubscribeLocalBroadcast = undefined;\n    }\n    // Tear down the persist-on-local-change subscription installed by\n    // attachDocument, if any. Without this a re-attach would stack duplicate\n    // persist handlers on the same document.\n    if (attachment.unsubscribePersist) {\n      attachment.unsubscribePersist();\n      attachment.unsubscribePersist = undefined;\n    }\n    if (ownsKey) {\n      this.persistStates.delete(this.storeKey(key));\n      this.persistDisabled.delete(this.storeKey(key));\n    }\n    // Release the single-active-session lock installed by attachDocument on the\n    // offline persistence path, so a later tab can take over the document.\n    if (attachment.sessionLockHandle) {\n      attachment.sessionLockHandle.release();\n      attachment.sessionLockHandle = undefined;\n    }\n    if (attachment.resource instanceof Document) {\n      // Take the re-issue claim if the document minted operation tickets\n      // while it was attached: those tickets are in the document this key\n      // names, so the actor's lamports there are no longer free for a later\n      // document of the key to re-issue onto. One that minted nothing leaves\n      // the claim alone. See `claimReissue`.\n      //\n      // The actor comes from this client, not from the document: a detach\n      // resets the document's own actor to the initial one\n      // (`applyStatus(Detached)`) before this runs.\n      const actor = this.actorID ?? this.id;\n      if (actor && attachment.resource.hasMintedOperations()) {\n        this.markReissueClaim(actor, key);\n      }\n      attachment.resource.resetOnlineClients();\n    }\n    if (ownsKey) {\n      this.attachmentMap.delete(key);\n    }\n    // Unconditional: this attachment is torn down whether or not the key\n    // still points at it, so teardown must stop seeing it either way.\n    this.liveAttachments.delete(attachment);\n  }\n\n  /**\n   * `pushWithPresenceBase` sends a pack built by `build` and answers\n   * `ErrPresenceBaseUnavailable` by resending it once with the presence put\n   * back in full.\n   *\n   * The server had no base to fold the pack's presence patch into -- evicted,\n   * restarted, or moved to another shard -- and stored none of the pack. An\n   * expected signal, not a failure. Every request that pushes a pack goes\n   * through here, not just push-pull: a queue restored from offline\n   * persistence can still hold patches minted in an earlier session, and the\n   * next request it rides out on is an attach. Without the retry that attach\n   * fails, and fails again on every try, because the pack never changes.\n   *\n   * The retry carries its own base, so it cannot hit the same error twice.\n   */\n  private async pushWithPresenceBase<R, P extends Indexable, T>(\n    doc: Document<R, P>,\n    build: () => PbChangePack,\n    send: (pack: PbChangePack) => Promise<T>,\n  ): Promise<T> {\n    const ownsSession = this.captureSession();\n    try {\n      return await send(build());\n    } catch (err) {\n      if (\n        !ownsSession() ||\n        !isErrorCode(err, Code.ErrPresenceBaseUnavailable)\n      ) {\n        throw err;\n      }\n\n      logger.info(\n        `[PP] c:\"${this.getKey()}\" d:\"${doc.getKey()}\" presence base ` +\n          `unavailable; resending with a full presence`,\n      );\n      doc.restorePresencePatches();\n      return await send(build());\n    }\n  }\n\n  private async syncInternal<R, P extends Indexable>(\n    attachment: Attachment<Attachable>,\n    syncMode?: SyncMode,\n  ): Promise<Attachable> {\n    const { resource } = attachment;\n\n    // Handle channel heartbeat\n    if (resource instanceof Channel) {\n      const isFirstCall = !resource.getSessionID();\n      // A channel heartbeats on an inactive client by design, so the capture\n      // must not read Deactivated as a lost session; teardown bumps the\n      // generation, which it does read. See `captureSession`.\n      const ownsSession = this.captureSession(true);\n      const ownsAttachment = () =>\n        ownsSession() &&\n        !attachment.isDetaching() &&\n        this.attachmentMap.get(resource.getKey()) === attachment;\n      if (!ownsAttachment()) {\n        return resource;\n      }\n      try {\n        const res = await this.rpcClient.refreshChannel(\n          {\n            clientId: this.id ?? '',\n            channelKey: resource.getKey(),\n            sessionId: resource.getSessionID() ?? '',\n            // First-call only — these fields are ignored by the server\n            // once a session_id is established.\n            clientKey: isFirstCall ? this.key : '',\n            metadata: isFirstCall ? this.metadata : {},\n          },\n          {\n            headers: {\n              'x-shard-key': `${this.apiKey}/${resource.getFirstKeyPath()}`,\n            },\n          },\n        );\n\n        // Teardown can finish and activation can clear `deactivating`\n        // before this response arrives. Check both the lifecycle and the\n        // attachment before applying first-call or heartbeat state.\n        if (!ownsAttachment()) {\n          return resource;\n        }\n        if (isFirstCall) {\n          // Server has just activated the client and attached the channel.\n          // Only adopt the server-issued client_id when we don't already\n          // have one. If the client was already activated (e.g. via\n          // `client.activate()` or a previous channel's first-call), keep\n          // our existing id so prior document attachments stay valid.\n          if (res.clientId && !this.id) {\n            this.id = res.clientId;\n            // Channel activation carries no stable actor, so fall back to the\n            // session id. Without this a channel-first client leaves actorID\n            // undefined, so a later document attach stamps the session id while\n            // getActorID() returns undefined, contradicting its contract.\n            this.actorID = res.clientId;\n            this.status = ClientStatus.Activated;\n            resource.setActor(res.clientId);\n          } else if (this.id) {\n            resource.setActor(this.id);\n          }\n          // Defer the Attached transition until a real session_id arrives.\n          // If the server replies with empty `sessionId` (protocol drift,\n          // partial response) the channel stays Detached and the next tick\n          // re-enters the first-call branch instead of flapping through\n          // an Attached state with no session.\n          if (res.sessionId) {\n            resource.setSessionID(res.sessionId);\n            attachment.resourceID = res.sessionId;\n            resource.applyStatus(ChannelStatus.Attached);\n          }\n\n          // Realtime channels need a watch stream; open it now that\n          // this.id is populated. `runWatchLoop` is idempotent against\n          // re-entry via `attachment.watchStream`, so no global flag check\n          // is needed (and using a global flag would silently block any\n          // subsequent attachment from opening its own stream).\n          if (attachment.syncMode === SyncMode.Realtime) {\n            this.runWatchLoop(resource.getKey()).catch((err) => {\n              logger.error(\n                `[WP] c:\"${this.getKey()}\" failed to start watch for p:\"${resource.getKey()}\":`,\n                err,\n              );\n            });\n          }\n        }\n\n        const prevCount = resource.getSessionCount();\n        if (resource.updateSessionCount(Number(res.sessionCount), 0)) {\n          if (resource.getSessionCount() !== prevCount) {\n            resource.publish({\n              type: ChannelEventType.PresenceChanged,\n              count: resource.getSessionCount(),\n            });\n          }\n        }\n        attachment.updateHeartbeatTime();\n\n        logger.debug(\n          `[RP] c:\"${this.getKey()}\" refreshes p:\"${resource.getKey()}\" mode:${attachment.syncMode}`,\n        );\n      } catch (err) {\n        // In particular, an expired old session must not clear the session\n        // of a Channel object that the app has already attached again.\n        if (!ownsAttachment()) {\n          return resource;\n        }\n        if (isErrorCode(err, Code.ErrSessionNotFound)) {\n          // Server has reclaimed our session (TTL expiry, restart, etc.).\n          // Clear local sessionID so the next tick re-enters the first-call\n          // branch and re-attaches transparently. Do not surface to caller.\n          logger.info(\n            `[RP] c:\"${this.getKey()}\" session expired for p:\"${resource.getKey()}\", re-attaching`,\n          );\n          resource.setSessionID('');\n          attachment.resourceID = '';\n          return resource;\n        }\n\n        // Surface the failure to channel subscribers so React layers can\n        // render an error state. Any subsequent successful event implies\n        // recovery — there is no separate \"recovered\" event. Skip the\n        // publish during teardown so a spurious error badge doesn't flash\n        // on the way out (mirrors the deactivate guard in the success path).\n        if (!this.deactivating && !attachment.isDetaching()) {\n          resource.publish({\n            type: ChannelEventType.SyncError,\n            error: err,\n            method: 'RefreshChannel',\n          });\n        }\n\n        logger.error(`[RP] c:\"${this.getKey()}\" err :`, err);\n        throw err;\n      }\n      return resource;\n    }\n\n    // Handle Document sync\n    const doc = resource as Document<R, P>;\n    const { resourceID: docID } = attachment;\n    const ownsSession = this.captureSession();\n    const ownsAttachment = () =>\n      ownsSession() && this.attachmentMap.get(doc.getKey()) === attachment;\n    if (!ownsAttachment()) {\n      return doc;\n    }\n\n    // The pack the request actually carried: the builder records it, so a\n    // presence-base retry leaves the log line below reporting the resent one.\n    let reqPack!: ChangePack<P>;\n    const pushOnly = syncMode === SyncMode.RealtimePushOnly;\n    try {\n      const res = await this.pushWithPresenceBase(\n        doc,\n        () => {\n          reqPack = doc.createChangePack();\n          return converter.toChangePack(reqPack);\n        },\n        (changePack) =>\n          this.rpcClient.pushPullChanges(\n            {\n              clientId: this.id!,\n              documentId: docID,\n              changePack,\n              pushOnly,\n              disableGc: attachment.disableGC,\n            },\n            { headers: { 'x-shard-key': `${this.apiKey}/${doc.getKey()}` } },\n          ),\n      );\n\n      // Another sync can reject Promise.all and release the task queue\n      // while this request is still pending. Never apply its pack to a\n      // document that has since been detached or attached again.\n      if (!ownsAttachment()) {\n        return doc;\n      }\n      const respPack = converter.fromChangePack<P>(res.changePack!);\n\n      // NOTE(chacha912, hackerwins): A request sent with PushPull, e.g. an\n      // explicit sync(doc), still pulls while the document is in PushOnly or\n      // SyncOff. Ignore any remote state it brings back, a snapshot included:\n      // the server seq stays put, so the skipped state is pulled again once\n      // realtime sync resumes. The push itself did land, so still take the\n      // client seq ack rather than push the same changes again — along with\n      // the pack's metadata (compaction epoch, removal flag), which describes\n      // the document rather than the content being skipped.\n      //\n      // The response to a push-only request is a push ack as well, even\n      // though it carries no changes: the server still attaches the minimum\n      // version vector, and applying that would garbage-collect tombstones\n      // while the changes anchored on them are precisely what this document\n      // has not pulled yet. Those changes arrive on the first full pull after\n      // the pause and are applied before that pull's vector collects anything;\n      // collecting here instead leaves the document unable to apply them\n      // (\"cannot find node\"), stuck on a pack the server redelivers forever.\n      // Judged by the mode the request was sent in, not the mode now: the\n      // mode can change while the request is in flight, and it is the\n      // request that decided whether anything was pulled.\n      //\n      // The pack's content does not enter the decision. A reply with neither\n      // changes nor a snapshot still carries the version vector, and an\n      // explicit `sync(doc)` sends PushPull regardless of the attachment mode\n      // (see `sync`), so keying on content would let that empty reply reach\n      // `garbageCollect` on a document that is paused mid-composition — the\n      // very collection this guard exists to prevent. While a document is in\n      // PushOnly/SyncOff nothing of the reply but the push ack is taken.\n      //\n      // A pause the caller has asked for but the task queue has not run yet\n      // counts as well (`pendingPullPauses`): this request may be the very\n      // sync the switch is waiting behind. Not for a `Manual` document,\n      // though. Dropping is only safe while something still re-drives the\n      // pull: `Realtime` has the re-arm below, and `Polling` has its own\n      // interval timer (`updateHeartbeatTime` just below starts the next\n      // tick). `Manual` has neither — `needRealtimeSync` returns false for it\n      // unconditionally, so the sync loop never visits the document and the\n      // re-arm is a no-op — and the only request in flight there is an\n      // explicit `sync(doc)` the caller made by hand. Dropping its pack would\n      // resolve that call having silently discarded the state it asked for,\n      // with nothing left to pull it again.\n      const modeDropsRemoteState =\n        pushOnly ||\n        attachment.syncMode === SyncMode.RealtimePushOnly ||\n        attachment.syncMode === SyncMode.RealtimeSyncOff;\n      const dropsRemoteState =\n        modeDropsRemoteState ||\n        (attachment.pendingPullPauses > 0 &&\n          attachment.syncMode !== SyncMode.Manual);\n      if (dropsRemoteState) {\n        doc.acknowledgePushedChanges(respPack);\n\n        // A pack dropped only for a pause that has not run yet still has to be\n        // re-pulled, and in `Realtime` nothing else re-drives it: the sync loop\n        // cleared `changeEventReceived` before driving this very sync, and a\n        // switch that never lands (it rejects because the client deactivated or\n        // the document detached while it waited, or the caller gave up on it)\n        // leaves the mode in Realtime with no pending event. Re-arm the flag\n        // so the next tick pulls again. Idempotent either way: a pause that\n        // does land makes `needRealtimeSync` ignore the flag, and the resume\n        // to Realtime sets it again. `Polling` does not read the flag — its\n        // interval timer re-drives the pull — and `Manual` never gets here,\n        // because a pending pause alone does not drop its pack.\n        if (\n          !modeDropsRemoteState &&\n          attachment.changeEventReceived !== undefined\n        ) {\n          attachment.changeEventReceived = true;\n        }\n      } else {\n        doc.applyChangePack(respPack);\n      }\n      attachment.updateHeartbeatTime();\n\n      // Whether the response actually moved the root. A dropped pack does not:\n      // it only takes the push ack, which leaves the document exactly where the\n      // pure push-ack branches below expect it.\n      const movedRoot =\n        !dropsRemoteState && (respPack.hasChanges() || respPack.hasSnapshot());\n\n      // Re-persist after a successful sync when a store is configured. A push\n      // that is merely acked (nothing pulled, or a pulled pack dropped because\n      // the document is in PushOnly/SyncOff) advances the checkpoint and\n      // drops the pushed changes from `localChanges` without emitting any\n      // Remote/Snapshot event, so the event-driven persist alone would leave\n      // the stored envelope holding already-pushed changes and a stale\n      // checkpoint until the next local edit. This is a full overwrite (not an\n      // append), so it does not grow unbounded. Errors are logged, not thrown.\n      if (this.store) {\n        const storeKey = this.storeKey(doc.getKey());\n        const onError = (err: unknown) =>\n          logger.error(\n            `[PS] c:\"${this.getKey()}\" persist-on-sync d:\"${doc.getKey()}\" ` +\n              `failed:`,\n            err,\n          );\n        // Folds everything the document holds into a fresh snapshot and\n        // rebases the log accounting onto it.\n        const reSnapshot = () => {\n          const snapshot = this.snapshotWithinBudget(doc, storeKey);\n          const state = this.persistStates.get(storeKey);\n          if (state && snapshot) {\n            state.snapshotBytes = snapshot.length;\n            state.logBytes = 0;\n            state.changeCount = 0;\n            state.poisoned = false;\n            state.lastAppendedClientSeq = doc\n              .getPendingChangesAfter(0)\n              .reduce(\n                (max, pending) => Math.max(max, pending.clientSeq),\n                doc.getCheckpoint().getClientSeq(),\n              );\n          }\n          if (snapshot) {\n            this.persistSnapshotOrPoison(storeKey, snapshot, onError);\n          }\n        };\n\n        if (movedRoot) {\n          // The response moved the root, and the append log holds *local*\n          // changes only — nothing in it carries remote content. Writing meta\n          // alone would advance the persisted `serverSeq` past a root the\n          // store never received, so the server would never resend those\n          // changes and this replica would lose them permanently while\n          // claiming to hold them. A snapshot is the only thing that records\n          // them.\n          //\n          // Cost: a pull re-serializes the document. That is the price of a\n          // local-only log; persisting remote changes incrementally as well\n          // would avoid it and is the natural follow-up.\n          reSnapshot();\n        } else {\n          // A pure push-ack. Which write is correct turns on `poisoned`, and\n          // that flag is only ever raised from an append's *rejection*\n          // callback — with a real async store an append that is going to\n          // fail can still be in flight when the sync response lands. Sampling\n          // it now would read a healthy log, pick the cheap header write, and\n          // queue it over the hole that append is about to leave. So decide\n          // once the writes already queued for this key have settled; both\n          // candidate writes chain onto that same queue anyway, so waiting\n          // reorders nothing.\n          const decide = () => {\n            // A removal learned from this very sync has already dropped the\n            // envelope by now; re-writing it here would resurrect an entry\n            // pointing at a server row that no longer exists.\n            if (doc.getStatus() === DocStatus.Removed) {\n              return;\n            }\n            if (this.persistStates.get(storeKey)?.poisoned) {\n              // The log has a hole: the change that failed to append lives\n              // only in memory. Writing the header would put the persisted\n              // `serverSeq` past content the store does not hold — and since\n              // it is our own acked change, the server will never resend it.\n              // Repair with a snapshot, which embeds the whole pending queue.\n              //\n              // The repair-on-next-edit path cannot cover this: a sync, or a\n              // tab close, gets there first.\n              reSnapshot();\n            } else {\n              // A healthy log: the root did not move, so the cheap header\n              // write is both sufficient and correct.\n              this.saveMetaToStore(storeKey, doc.metaToBytes(), onError);\n            }\n          };\n          const queued = this.persistQueues.get(storeKey);\n          if (queued) {\n            void queued.then(decide, decide);\n          } else {\n            decide();\n          }\n        }\n      }\n\n      attachment.resource.publish([\n        {\n          type: DocEventType.SyncStatusChanged,\n          value: DocSyncStatus.Synced,\n        },\n      ]);\n\n      // The push the server rejected is behind us, so let the sync loop take\n      // this document again. Reaching here from an explicit `client.sync(doc)`\n      // is the way back for a document parked by a size rejection.\n      attachment.clearWriteRejected();\n\n      // NOTE(chacha912): If a document has been removed, watchStream should\n      // be disconnected to not receive an event for that document.\n      if (doc.getStatus() === DocStatus.Removed) {\n        this.detachInternal(doc.getKey());\n        // And drop the persisted entry, as `remove()` and `detachDocument()`\n        // do. Learning of the removal from a sync is the third way a document\n        // can end, and the only one that used to leave the envelope behind: it\n        // carries a `serverSeq` for a row that no longer exists, so the next\n        // attach under the same client key is rejected for presenting a\n        // checkpoint ahead of the server. Only `ErrEpochMismatch` is recovered\n        // on the store path, so that error escapes attach and the app has no\n        // route back short of clearing its own store.\n        await this.removeFromStore(doc.getKey());\n      }\n\n      const key = doc.getKey();\n      const remoteSize = respPack.getChangeSize();\n      logger.info(\n        `[PP] c:\"${this.getKey()}\" sync d:\"${key}\", push:${reqPack.getChangeSize()} pull:${remoteSize} cp:${respPack\n          .getCheckpoint()\n          .toTestString()}`,\n      );\n\n      return doc;\n    } catch (err) {\n      if (!ownsAttachment()) {\n        return doc;\n      }\n      doc.publish([\n        {\n          type: DocEventType.SyncStatusChanged,\n          value: DocSyncStatus.SyncFailed,\n        },\n      ]);\n\n      // The server refused to store what was pushed, and will refuse it again:\n      // the push is not retried for these codes, and the sync loop parks this\n      // document. `sync-failed` alone cannot be told apart from a network\n      // blip, so report the reason too. Published here, next to the status the\n      // app already gets, so it covers the sync loop and an explicit\n      // `sync(doc)` alike.\n      const rejection = unretryableWriteCodes.find((code) =>\n        isErrorCode(err, code),\n      );\n      if (rejection) {\n        doc.publish([\n          {\n            type: DocEventType.WriteRejected,\n            value: {\n              code: rejection,\n              reason: (err as ConnectError).rawMessage,\n              method: 'PushPull',\n            },\n          },\n        ]);\n      }\n\n      logger.error(`[PP] c:\"${this.getKey()}\" err :`, err);\n      throw err;\n    }\n  }\n\n  /**\n   * `handleConnectError` handles the given error. If the given error can be\n   * retried after handling, it returns true. `inRetryLoop` is true for the\n   * loops that retry on their own (sync, Watch, broadcast retries): their\n   * 401s skip the token refresh while it backs off, and a refresh that\n   * rejects does not throw.\n   *\n   * `ownsSession` reports whether the caller's session is still the live one\n   * (see {@link captureSession}). Only `ErrClientNotActivated` /\n   * `ErrClientNotFound` consult it, because only they tear the client down:\n   * a late error from a session a `keepalive` deactivate already closed must\n   * not deactivate the session that replaced it.\n   */\n  private async handleConnectError(\n    err: any,\n    inRetryLoop = false,\n    ownsSession: () => boolean = () => true,\n  ): Promise<boolean> {\n    if (!(err instanceof ConnectError)) {\n      return false;\n    }\n\n    // NOTE(hackerwins): If the error is 'ErrDocumentSizeExceedsLimit' or\n    // 'ErrChangeTooLarge', the server refused to store the pushed changes and\n    // will refuse the same pack again: the size gate re-evaluates it on every\n    // attempt and nothing the client resends changes its verdict. Retrying\n    // also blocks pulls, because push and pull share one `PushPull` RPC. So\n    // report it as not retryable; `syncInternal` publishes a `write-rejected`\n    // event carrying the code so the app can say why. This is checked ahead of\n    // the generic retry block below because the server sends both as\n    // `ResourceExhausted`.\n    //\n    // The sync loop never consults this for a document rejection — it parks\n    // that one attachment itself (see `runSyncLoop`) rather than letting the\n    // error reach the client-wide handler, which would stop the loop for every\n    // other document and for the channel heartbeats.\n    if (unretryableWriteCodes.some((code) => errorCodeOf(err) === code)) {\n      return false;\n    }\n\n    // NOTE(hackerwins): These errors are retryable.\n    // Connect guide indicates that for error codes like `ResourceExhausted` and\n    // `Unavailable`, retries should be attempted following their guidelines.\n    // Additionally, `Unknown` and `Canceled` are added separately as it\n    // typically occurs when the server is stopped.\n    if (\n      err.code === ConnectCode.Canceled ||\n      err.code === ConnectCode.Unknown ||\n      err.code === ConnectCode.ResourceExhausted ||\n      err.code === ConnectCode.Unavailable\n    ) {\n      return true;\n    }\n\n    // NOTE(chacha912): If the error is `Unauthenticated`, it means that the\n    // token is invalid or expired. In this case, the client gets a new token\n    // from the `authTokenInjector` and retries the api call.\n    if (errorCodeOf(err) === Code.ErrUnauthenticated) {\n      if (this.authTokenInjector) {\n        await this.refreshAuthToken(errorMetadataOf(err).reason, inRetryLoop);\n      }\n      return true;\n    }\n\n    // NOTE(emplam27): If the error is 'ErrTooManySubscribers' it means,\n    // that the document has reached the maximum number of allowed subscriptions.\n    // In this case, the client should retry the connection.\n    if (errorCodeOf(err) === Code.ErrTooManySubscribers) {\n      logger.error(`[WD] c:\"${this.getKey()}\" err :`, err.rawMessage);\n      return true;\n    }\n\n    // NOTE(emplam27): If the error is 'ErrTooManyAttachments' it means,\n    // that the client has reached the maximum number of allowed attachments.\n    // In this case, the client should remove some attachments.\n    if (errorCodeOf(err) === Code.ErrTooManyAttachments) {\n      return false;\n    }\n\n    // NOTE(hackerwins): If the error is 'ErrEpochMismatch', it means the\n    // document has been compacted and the client's checkpoint is stale.\n    // The sync loop should stop, and the user must detach and reattach.\n    if (errorCodeOf(err) === Code.ErrEpochMismatch) {\n      return false;\n    }\n\n    // NOTE(hackerwins): Some errors should fix the state of the client.\n    if (\n      errorCodeOf(err) === Code.ErrClientNotActivated ||\n      errorCodeOf(err) === Code.ErrClientNotFound\n    ) {\n      // Only the session the failed request belonged to may be torn down. A\n      // `keepalive` deactivate deactivates the client synchronously, outside\n      // the task queue, so every in-flight task and loop can come back to a\n      // client the app has since activated again under a new `clientId`; the\n      // server's \"no such client\" is about the id that is already gone.\n      if (ownsSession()) {\n        this.deactivateInternal();\n      }\n    }\n\n    return false;\n  }\n\n  /**\n   * `refreshAuthToken` asks `authTokenInjector` for a new token after a 401.\n   *\n   * For a loop, a rejection is treated as transient: the previous token is\n   * kept and the loop is still told to retry. Letting it through would throw\n   * it from inside the loops' `catch` blocks, so the sync loop would never\n   * schedule its retry and the Watch stream would never reconnect, with no\n   * event left for the app. Each failure in a row doubles the wait before\n   * the injector is called again (`authRefreshDelay`); a loop's 401 that\n   * arrives sooner skips it, and the loop's retry waits until then, but at\n   * most 5s for it (`loopRetryDelay`). A one-shot call (`inRetryLoop` false)\n   * always calls it and gets its rejection thrown, as before this change:\n   * the app retried on purpose, the token API may be back, and the\n   * injector's error is how the app learns why it failed.\n   *\n   * Each 401 makes its own call, as before; they do not join one call, since\n   * an injector that never settles would then hold every later 401 too. A\n   * call that settles after a later one already set its token neither sets\n   * its own nor changes the backoff, so an older token never overrides a\n   * newer one, and a call still pending when the client activates again does\n   * not override the new session's token. A call is not dropped just because\n   * a later one is still pending: with a slow token API, the loops' calls\n   * would then keep dropping each other. 401s that arrive together, such as\n   * the sync loop's and the Watch streams' when the token expires, count as\n   * one failure.\n   */\n  private async refreshAuthToken(\n    reason: string | undefined,\n    inRetryLoop: boolean,\n  ): Promise<void> {\n    if (inRetryLoop && Date.now() < this.authRefreshRetryAt) {\n      return;\n    }\n\n    const generation = ++this.authRefreshGeneration;\n    const failures = this.authRefreshFailures;\n    try {\n      const token = await this.authTokenInjector!(reason);\n      if (generation > this.authTokenGeneration) {\n        this.authTokenGeneration = generation;\n        this.setAuthToken(token);\n        this.authRefreshFailures = 0;\n        this.authRefreshRetryAt = 0;\n      }\n    } catch (err) {\n      logger.error(`[AT] c:\"${this.getKey()}\" token refresh failed:`, err);\n      if (\n        generation > this.authTokenGeneration &&\n        this.authRefreshFailures === failures\n      ) {\n        this.authRefreshFailures = failures + 1;\n        this.authRefreshRetryAt = Date.now() + authRefreshDelay(failures + 1);\n      }\n      if (!inRetryLoop) {\n        throw err;\n      }\n    }\n  }\n\n  /**\n   * `loopRetryDelay` returns how long a retry waits after `err`: its own\n   * `delay`, or, for a 401, until the next token refresh may run if that is\n   * later, so the retry does not just resend a refused token, but no longer\n   * than `AuthRetryMaxWaitMs`. Other errors keep their own delay: a method the\n   * auth webhook does not guard still works with the refused token.\n   */\n  private loopRetryDelay(err: unknown, delay: number): number {\n    if (!isErrorCode(err, Code.ErrUnauthenticated)) {\n      return delay;\n    }\n    const backoff = Math.min(\n      this.authRefreshRetryAt - Date.now(),\n      AuthRetryMaxWaitMs,\n    );\n    return Math.max(delay, backoff);\n  }\n\n  /**\n   * `trackSync` registers an in-flight sync on its attachment so that\n   * `Attachment.waitForSyncComplete` can see it, and clears it once the sync\n   * settles. It returns the original promise untouched, so the caller keeps\n   * both the result and the failure.\n   *\n   * The sync loop registers its own syncs; this covers the hand-driven\n   * `Client.sync`, which used to be invisible to every caller that waits for\n   * an in-flight sync before touching the change queue — `detachDocument` and\n   * `resync`, both of which would otherwise act on a queue a live `PushPull`\n   * is about to rewrite by checkpoint.\n   */\n  private trackSync<T>(attachment: Attachment<any>, sync: Promise<T>) {\n    // What is registered must never reject on its own: nothing awaits it\n    // except `waitForSyncComplete`, so a rejection would surface as an\n    // unhandled rejection. The failure stays on the promise we hand back.\n    const settled = sync.then(\n      () => {},\n      () => {},\n    );\n    attachment.setSyncPromise(settled);\n    settled.then(() => attachment.clearSyncPromise());\n    return sync;\n  }\n\n  /**\n   * `captureSession` captures the session (activation) the caller belongs to\n   * and returns a predicate reporting whether the client is still in it.\n   *\n   * A `keepalive` deactivate tears the client down in the same tick, outside\n   * the task queue, so a task or loop that is mid-flight can come back to a\n   * deactivated client — or, if the app activated it again meanwhile, to a\n   * different session under a new `clientId`. Recovery driven by the old\n   * session's errors would then be applied to the new one.\n   *\n   * A channel-first client has no id until its first refresh succeeds. That\n   * initial lifecycle still owns its errors. The generation invalidates it\n   * on teardown, including when a later activation receives the same id.\n   *\n   * `allowInactive` captures a session that does not require the client to be\n   * activated. Channels attach and heartbeat on an inactive client by design —\n   * `RefreshChannel` lazy-activates it server-side — so for them a Deactivated\n   * status is not evidence that the session went away; only a teardown (which\n   * bumps the generation) or one in progress is.\n   *\n   * Call it where the request's `clientId` is read, so the captured id is the\n   * one the request actually carries.\n   */\n  private captureSession(allowInactive = false): () => boolean {\n    const sessionID = this.id;\n    const generation = this.sessionGeneration;\n    const wasDeactivating = this.deactivating;\n    return () => {\n      if (generation !== this.sessionGeneration) {\n        return false;\n      }\n      if (allowInactive || sessionID === undefined) {\n        // A teardown already under way at capture time is the lifecycle this\n        // caller was handed — a `keepalive` deactivate leaves the flag set\n        // until the next activation — so only one that starts afterwards\n        // invalidates it. One that finishes bumps the generation above.\n        return wasDeactivating || !this.deactivating;\n      }\n      return this.isActive() && this.id === sessionID;\n    };\n  }\n\n  /**\n   * `enqueueTask` enqueues the given task to the task queue.\n   */\n  private enqueueTask(task: () => Promise<any>): Promise<any> {\n    return new Promise((resolve, reject) => {\n      this.taskQueue.push(() => task().then(resolve).catch(reject));\n\n      if (!this.processing) {\n        this.processNext();\n      }\n    });\n  }\n\n  /**\n   * `processNext` processes the next task in the task queue. This method is\n   * part of enqueueTask.\n   */\n  private async processNext() {\n    if (this.taskQueue.length === 0) {\n      this.processing = false;\n      return;\n    }\n\n    try {\n      this.processing = true;\n      const task = this.taskQueue.shift()!;\n      await task();\n    } catch {\n      logger.error(`[TQ] c:\"${this.getKey()}\" process failed, id:\"${this.id}\"`);\n    }\n\n    this.processNext();\n  }\n}\n","/*\n * Copyright 2026 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * `StoredChange` is one persisted local change, tagged with the `clientSeq` it\n * carries. The sequence is what lets a store drop changes a sync has already\n * acknowledged, and what lets a restore detect a hole rather than replaying a\n * discontinuous run.\n */\nexport interface StoredChange {\n  clientSeq: number;\n  bytes: Uint8Array;\n}\n\n/**\n * `StoredDoc` is everything a backend holds for one document: a base snapshot,\n * the changes appended since it, and a small mutable header.\n */\nexport interface StoredDoc {\n  /** A `Document.toBytes()` envelope. */\n  snapshot: Uint8Array;\n\n  /**\n   * Checkpoint and changeID as of the last sync. Absent until the first one.\n   * Held apart from the snapshot because a sync has to advance it constantly\n   * while the snapshot stays put.\n   */\n  meta?: Uint8Array;\n\n  /** Changes appended since the snapshot, ascending by `clientSeq`. */\n  changes: Array<StoredChange>;\n}\n\n/**\n * `DocStore` is a pluggable persistence backend for offline document state.\n *\n * It is deliberately a snapshot plus an append-only change log rather than one\n * opaque blob. Re-serializing the whole document on every edit costs time\n * proportional to the document — hundreds of milliseconds on a large one — and\n * a document is at its largest while it is being edited, which is exactly when\n * the writes happen. Appending costs the size of one change, which does not\n * grow with the document at all.\n *\n * The interface stays byte-oriented and async so a durable backend (IndexedDB,\n * say) can implement it without the client knowing which storage it talks to,\n * and so a backend is free to compress or encrypt what it is handed. The\n * default `MemoryDocStore` keeps everything in a process-local map and carries\n * no dependency.\n */\nexport interface DocStore {\n  /**\n   * `load` returns the persisted state for the given document key, or\n   * `undefined` when nothing has been stored for it. `changes` must be ordered\n   * by ascending `clientSeq`.\n   */\n  load(docKey: string): Promise<StoredDoc | undefined>;\n\n  /**\n   * `saveSnapshot` replaces the snapshot and atomically drops every appended\n   * change **and any stored meta**. This is compaction: the new snapshot\n   * already contains those changes, so keeping them would replay them twice,\n   * and it embeds a newer header than meta holds, so keeping that would\n   * regress the client's clocks.\n   */\n  saveSnapshot(docKey: string, bytes: Uint8Array): Promise<void>;\n\n  /**\n   * `appendChange` appends one local change. This is the hot path — frequent\n   * and small — so an implementation must not rewrite the whole entry to\n   * satisfy it.\n   *\n   * It is an **upsert keyed by `clientSeq`**: re-appending a change already\n   * stored replaces it rather than duplicating it, so a retried write is safe.\n   */\n  appendChange(docKey: string, change: StoredChange): Promise<void>;\n\n  /**\n   * `saveMeta` records the post-sync header. It leaves the snapshot alone —\n   * an online client syncs constantly, and re-snapshotting per sync would\n   * reintroduce the cost this interface exists to avoid — and it leaves the\n   * **log** alone too.\n   *\n   * That second part is load-bearing. The log does two jobs: it holds\n   * un-pushed changes so they survive a reload, and it is the delta between\n   * the snapshot and the document's current content. Deleting acknowledged\n   * entries serves the first job and destroys the second, because nothing\n   * brings the snapshot forward on a push-ack — the content would then exist\n   * in neither place while the persisted `serverSeq` claims the server has it.\n   * Only compaction trims the log, and it does so by folding the entries into\n   * a new snapshot first.\n   *\n   * The header itself carries the acknowledged `clientSeq`, so a restore reads\n   * it from there; the store needs no separate parameter for it.\n   *\n   * It is a no-op when nothing is stored for the key.\n   */\n  saveMeta(docKey: string, bytes: Uint8Array): Promise<void>;\n\n  /**\n   * `remove` deletes everything persisted for the document key. It is a no-op\n   * when nothing is stored.\n   */\n  remove(docKey: string): Promise<void>;\n}\n\n/**\n * `MemoryDocStore` is an in-memory `DocStore`. It holds entries in a `Map` for\n * the lifetime of the process and carries no external dependency. It is the\n * default when a durable backend is not configured, and it doubles as a test\n * double for the persistence loop.\n *\n * Every byte array is copied on the way in and on the way out, so neither a\n * caller mutating what it wrote nor one mutating what it read can corrupt the\n * stored entry.\n */\nexport class MemoryDocStore implements DocStore {\n  private store: Map<string, StoredDoc>;\n\n  constructor() {\n    this.store = new Map();\n  }\n\n  /**\n   * `load` returns a deep copy of the persisted entry, or `undefined`.\n   */\n  public load(docKey: string): Promise<StoredDoc | undefined> {\n    const entry = this.store.get(docKey);\n    if (!entry) {\n      return Promise.resolve(undefined);\n    }\n    return Promise.resolve({\n      snapshot: entry.snapshot.slice(),\n      meta: entry.meta ? entry.meta.slice() : undefined,\n      changes: entry.changes.map((change) => ({\n        clientSeq: change.clientSeq,\n        bytes: change.bytes.slice(),\n      })),\n    });\n  }\n\n  /**\n   * `saveSnapshot` stores a copy of the bytes and clears the change log.\n   */\n  public saveSnapshot(docKey: string, bytes: Uint8Array): Promise<void> {\n    this.store.set(docKey, {\n      snapshot: bytes.slice(),\n      // The header is dropped, not carried forward. A snapshot envelope\n      // embeds its own checkpoint and changeID, and they are newer than\n      // whatever meta held; applying the old header over the new snapshot\n      // would regress `serverSeq` and — worse — `lamport`, whose regression\n      // makes the next edit mint tickets that collide with identities already\n      // in the restored root.\n      changes: [],\n    });\n    return Promise.resolve();\n  }\n\n  /**\n   * `appendChange` appends a copy of the change, keeping the log ordered by\n   * `clientSeq`.\n   */\n  public appendChange(docKey: string, change: StoredChange): Promise<void> {\n    const entry = this.store.get(docKey);\n    if (!entry) {\n      return Promise.resolve();\n    }\n    // Upsert, not push: `clientSeq` identifies the change, and a re-append of\n    // one already stored is a retry rather than a second change. The\n    // IndexedDB reference keys on [docKey, clientSeq] and so behaves this way\n    // implicitly; the two must not disagree, because an app writes its backend\n    // against this contract.\n    const existing = entry.changes.findIndex(\n      (c) => c.clientSeq === change.clientSeq,\n    );\n    const stored = {\n      clientSeq: change.clientSeq,\n      bytes: change.bytes.slice(),\n    };\n    if (existing >= 0) {\n      entry.changes[existing] = stored;\n    } else {\n      entry.changes.push(stored);\n      entry.changes.sort((a, b) => a.clientSeq - b.clientSeq);\n    }\n    return Promise.resolve();\n  }\n\n  /**\n   * `saveMeta` stores a copy of the header, leaving the snapshot and the log\n   * untouched.\n   */\n  public saveMeta(docKey: string, bytes: Uint8Array): Promise<void> {\n    const entry = this.store.get(docKey);\n    if (!entry) {\n      return Promise.resolve();\n    }\n    entry.meta = bytes.slice();\n    return Promise.resolve();\n  }\n\n  /**\n   * `remove` deletes everything persisted for the document key.\n   */\n  public remove(docKey: string): Promise<void> {\n    this.store.delete(docKey);\n    return Promise.resolve();\n  }\n}\n","/*\n * Copyright 2025 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * `YSONTextNode` represents a single character in a Text CRDT.\n *\n * @example\n * ```typescript\n * { val: 'H', attrs: { bold: true } }\n * ```\n */\nexport interface YSONTextNode {\n  /**\n   * The character value\n   */\n  val: string;\n\n  /**\n   * Optional attributes (e.g., formatting)\n   */\n  attrs?: Record<string, any>;\n}\n\n/**\n * `YSONText` represents a Text CRDT structure.\n *\n * @example\n * ```typescript\n * {\n *   type: 'Text',\n *   nodes: [\n *     { val: 'H' },\n *     { val: 'i' }\n *   ]\n * }\n * ```\n */\nexport interface YSONText {\n  type: 'Text';\n  nodes: Array<YSONTextNode>;\n}\n\n/**\n * `YSONTreeNode` represents a node in a Tree CRDT.\n *\n * For text nodes: `{ type: 'text', value: 'content' }`\n * For element nodes: `{ type: 'p', children: [...] }`\n */\nexport interface YSONTreeNode {\n  /**\n   * Node type (e.g., 'text', 'p', 'div')\n   */\n  type: string;\n\n  /**\n   * Text content (for text nodes)\n   */\n  value?: string;\n\n  /**\n   * Attributes (for element nodes)\n   */\n  attrs?: Record<string, string>;\n\n  /**\n   * Child nodes (for element nodes)\n   */\n  children?: Array<YSONTreeNode>;\n}\n\n/**\n * `YSONTree` represents a Tree CRDT structure.\n *\n * @example\n * ```typescript\n * {\n *   type: 'Tree',\n *   root: {\n *     type: 'doc',\n *     children: [\n *       { type: 'p', children: [{ type: 'text', value: 'Hello' }] }\n *     ]\n *   }\n * }\n * ```\n */\nexport interface YSONTree {\n  type: 'Tree';\n  root: YSONTreeNode;\n}\n\n/**\n * `YSONInt` represents a 32-bit integer.\n *\n * @example\n * ```typescript\n * { type: 'Int', value: 42 }\n * ```\n */\nexport interface YSONInt {\n  type: 'Int';\n  value: number;\n}\n\n/**\n * `YSONLong` represents a 64-bit integer.\n *\n * @example\n * ```typescript\n * { type: 'Long', value: 64 }\n * ```\n */\nexport interface YSONLong {\n  type: 'Long';\n  value: number;\n}\n\n/**\n * `YSONDate` represents an ISO 8601 timestamp.\n *\n * @example\n * ```typescript\n * { type: 'Date', value: '2025-01-02T15:04:05.058Z' }\n * ```\n */\nexport interface YSONDate {\n  type: 'Date';\n  value: string;\n}\n\n/**\n * `YSONBinData` represents Base64-encoded binary data.\n *\n * @example\n * ```typescript\n * { type: 'BinData', value: 'AQID' }\n * ```\n */\nexport interface YSONBinData {\n  type: 'BinData';\n  value: string;\n}\n\n/**\n * `YSONCounter` represents a Counter CRDT for collaborative counting.\n *\n * @example\n * ```typescript\n * { type: 'Counter', value: { type: 'Int', value: 10 } }\n * ```\n */\nexport interface YSONCounter {\n  type: 'Counter';\n  value: YSONInt | YSONLong;\n}\n\n/**\n * `YSONDedupCounter` represents a DedupCounter CRDT that uses HyperLogLog\n * to count unique actors.\n *\n * @example\n * ```typescript\n * { type: 'DedupCounter', value: { type: 'Int', value: 15 }, registers: 'AQID...' }\n * ```\n */\nexport interface YSONDedupCounter {\n  type: 'DedupCounter';\n  value: YSONInt;\n  registers: string;\n}\n\n/**\n * `YSONValue` represents any valid YSON value.\n *\n * Can be:\n * - Primitives: string, number, boolean, null\n * - Collections: arrays, objects\n * - CRDT types: Text, Tree, Counter\n * - Special types: Int, Long, Date, BinData\n */\nexport type YSONValue =\n  | string\n  | number\n  | boolean\n  // eslint-disable-next-line @typescript-eslint/no-restricted-types\n  | null\n  | YSONText\n  | YSONTree\n  | YSONInt\n  | YSONLong\n  | YSONDate\n  | YSONBinData\n  | YSONCounter\n  | YSONDedupCounter\n  | { [key: string]: YSONValue }\n  | Array<YSONValue>;\n\n/**\n * `isText` checks if a value is a YSONText object.\n */\nexport function isText(value: any): value is YSONText {\n  return (\n    typeof value === 'object' &&\n    value !== null &&\n    value.type === 'Text' &&\n    Array.isArray(value.nodes)\n  );\n}\n\n/**\n * `isTree` checks if a value is a YSONTree object.\n */\nexport function isTree(value: any): value is YSONTree {\n  return (\n    typeof value === 'object' &&\n    value !== null &&\n    value.type === 'Tree' &&\n    typeof value.root === 'object'\n  );\n}\n\n/**\n * `isInt` checks if a value is a YSONInt object.\n */\nexport function isInt(value: any): value is YSONInt {\n  return (\n    typeof value === 'object' &&\n    value !== null &&\n    value.type === 'Int' &&\n    typeof value.value === 'number'\n  );\n}\n\n/**\n * `isLong` checks if a value is a YSONLong object.\n */\nexport function isLong(value: any): value is YSONLong {\n  return (\n    typeof value === 'object' &&\n    value !== null &&\n    value.type === 'Long' &&\n    typeof value.value === 'number'\n  );\n}\n\n/**\n * `isDate` checks if a value is a YSONDate object.\n */\nexport function isDate(value: any): value is YSONDate {\n  return (\n    typeof value === 'object' &&\n    value !== null &&\n    value.type === 'Date' &&\n    typeof value.value === 'string'\n  );\n}\n\n/**\n * `isBinData` checks if a value is a YSONBinData object.\n */\nexport function isBinData(value: any): value is YSONBinData {\n  return (\n    typeof value === 'object' &&\n    value !== null &&\n    value.type === 'BinData' &&\n    typeof value.value === 'string'\n  );\n}\n\n/**\n * `isCounter` checks if a value is a YSONCounter object.\n */\nexport function isCounter(value: any): value is YSONCounter {\n  return (\n    typeof value === 'object' &&\n    value !== null &&\n    value.type === 'Counter' &&\n    typeof value.value === 'object'\n  );\n}\n\n/**\n * `isDedupCounter` checks if a value is a YSONDedupCounter object.\n */\nexport function isDedupCounter(value: any): value is YSONDedupCounter {\n  return (\n    typeof value === 'object' &&\n    value !== null &&\n    value.type === 'DedupCounter' &&\n    typeof value.value === 'object' &&\n    typeof value.registers === 'string'\n  );\n}\n\n/**\n * `isObject` checks if a value is a plain YSON object (not a special type).\n */\nexport function isObject(value: any): value is { [key: string]: YSONValue } {\n  return (\n    typeof value === 'object' &&\n    value !== null &&\n    !Array.isArray(value) &&\n    !isText(value) &&\n    !isTree(value) &&\n    !isInt(value) &&\n    !isLong(value) &&\n    !isDate(value) &&\n    !isBinData(value) &&\n    !isCounter(value) &&\n    !isDedupCounter(value)\n  );\n}\n","/*\n * Copyright 2025 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, YorkieError } from '@yorkie-js/sdk/src/util/error';\nimport type {\n  YSONValue,\n  YSONText,\n  YSONTree,\n  YSONTextNode,\n  YSONTreeNode,\n  YSONInt,\n  YSONLong,\n  YSONDate,\n  YSONBinData,\n  YSONCounter,\n  YSONDedupCounter,\n} from './types';\n\n/**\n * `parse` parses a YSON string into a typed JavaScript object.\n *\n * YSON extends JSON to support Yorkie CRDT types:\n * - `Text([...])` for Text CRDT\n * - `Tree(...)` for Tree CRDT\n * - Standard JSON for primitives, objects, and arrays\n *\n * @param yson - YSON formatted string\n * @returns Parsed YSONValue\n * @throws YorkieError if parsing fails\n *\n * @example\n * ```typescript\n * const data = parse('{\"content\":Text([{\"val\":\"Hi\"}])}');\n * // { content: { type: 'Text', nodes: [{ val: 'Hi' }] } }\n *\n * // With type parameter:\n * const data = parse<{ content: YSONText }>('{\"content\":Text([{\"val\":\"Hi\"}])}');\n * // data.content is now typed as YSONText\n * ```\n */\nexport function parse<T = YSONValue>(yson: string): T {\n  try {\n    // Preprocess YSON string to handle special types\n    const processed = preprocessYSON(yson);\n\n    // Parse as JSON\n    const parsed = JSON.parse(processed);\n\n    // Post-process to restore type information\n    return postprocessValue(parsed) as T;\n  } catch (err) {\n    throw new YorkieError(\n      Code.ErrInvalidArgument,\n      `Failed to parse YSON: ${err instanceof Error ? err.message : String(err)}`,\n    );\n  }\n}\n\n/**\n * `preprocessYSON` converts YSON special syntax to JSON-compatible format.\n *\n * Transformations:\n * - `Text([...])` → `{\"__yson_type\":\"Text\",\"__yson_data\":[...]}`\n * - `Tree(...)` → `{\"__yson_type\":\"Tree\",\"__yson_data\":...}`\n * - `Int(42)` → `{\"__yson_type\":\"Int\",\"__yson_data\":42}`\n * - `Long(64)` → `{\"__yson_type\":\"Long\",\"__yson_data\":64}`\n * - `Date(\"...\")` → `{\"__yson_type\":\"Date\",\"__yson_data\":\"...\"}`\n * - `BinData(\"...\")` → `{\"__yson_type\":\"BinData\",\"__yson_data\":\"...\"}`\n * - `DedupCounter(Int(15),\"b64\")` → `{\"__yson_type\":\"DedupCounter\",\"__yson_data\":{\"__yson_type\":\"Int\",\"__yson_data\":15},\"__yson_registers\":\"b64\"}`\n * - `Counter(Int(10))` → `{\"__yson_type\":\"Counter\",\"__yson_data\":{\"__yson_type\":\"Int\",\"__yson_data\":10}}`\n */\n/**\n * `ysonConstructors` lists the YSON type constructor names the scanner\n * recognizes. Longer names are listed before their suffixes (e.g.\n * `DedupCounter` before `Counter`) so the scanner prefers the longest match.\n */\nconst ysonConstructors = [\n  'DedupCounter',\n  'Counter',\n  'BinData',\n  'Date',\n  'Long',\n  'Int',\n  'Text',\n  'Tree',\n];\n\n/**\n * `reservedKeyPrefix` is the key namespace `preprocessYSON` emits its markers\n * in: `__yson_type`, `__yson_data` and `__yson_registers`. Because the markers\n * are plain JSON keys, a key the input itself writes in this namespace would be\n * read back as a marker, so such keys are escaped on the way in and restored on\n * the way out.\n */\nconst reservedKeyPrefix = '__yson_';\n\n/**\n * `escapedKeyPrefix` is what an input key in the reserved namespace is prefixed\n * with. It starts with `reservedKeyPrefix` itself, which is what makes the\n * escape injective: a key already spelled `__yson_esc_x` is escaped in turn, to\n * `__yson_esc___yson_esc_x`, and strips back to exactly what it was.\n */\nconst escapedKeyPrefix = '__yson_esc_';\n\n/**\n * `escapeKey` returns `key` in a namespace the marker reader never looks at.\n */\nfunction escapeKey(key: string): string {\n  return key.startsWith(reservedKeyPrefix) ? escapedKeyPrefix + key : key;\n}\n\n/**\n * `unescapeKey` undoes `escapeKey`.\n */\nfunction unescapeKey(key: string): string {\n  return key.startsWith(escapedKeyPrefix)\n    ? key.slice(escapedKeyPrefix.length)\n    : key;\n}\n\n/**\n * `defineKey` writes `val` under `key` as an own data property of `target`.\n *\n * Every key here comes from the parsed document, so plain assignment would\n * hand a key named `__proto__` to the object's own setter and replace the\n * result's prototype instead of recording a key. `JSON.parse` makes such a key\n * an inert own property; this keeps it one.\n */\nfunction defineKey(target: Record<string, any>, key: string, val: any): void {\n  Object.defineProperty(target, key, {\n    value: val,\n    writable: true,\n    enumerable: true,\n    configurable: true,\n  });\n}\n\n/**\n * `unescapeKeys` returns a copy of `value` with every object key unescaped, at\n * any depth. The `attrs` of a text or tree node are user data that reaches the\n * output without going through the object branch of `postprocessValue`, and\n * `preprocessYSON` escapes keys in key position wherever they appear, so an\n * attribute's own value can hold escaped keys too.\n */\nfunction unescapeKeys<T>(value: T): T {\n  if (Array.isArray(value)) {\n    return value.map((item) => unescapeKeys(item)) as unknown as T;\n  }\n  if (value === null || typeof value !== 'object') {\n    return value;\n  }\n  const result: Record<string, any> = {};\n  for (const [key, val] of Object.entries(value)) {\n    defineKey(result, unescapeKey(key), unescapeKeys(val));\n  }\n  return result as T;\n}\n\n/**\n * `isIdentChar` reports whether `ch` can appear inside an identifier. Used to\n * ensure a constructor keyword is matched at a token boundary, not as the tail\n * of some longer word.\n */\nfunction isIdentChar(ch: string | undefined): boolean {\n  return ch !== undefined && /[A-Za-z0-9_]/.test(ch);\n}\n\n/**\n * `scanStringLiteral` returns the index just past the JSON string literal that\n * starts at `start` (which must point at the opening quote), honouring `\\\"`\n * escapes, together with whether the literal was closed. A literal ending in an\n * escaped quote is indistinguishable from a closed one by index alone, so\n * callers that must reject truncated input need the flag.\n */\nfunction scanStringLiteral(s: string, start: number): [number, boolean] {\n  let i = start + 1;\n  while (i < s.length) {\n    const ch = s[i];\n    if (ch === '\\\\') {\n      i += 2;\n      continue;\n    }\n    if (ch === '\"') {\n      return [i + 1, true];\n    }\n    i++;\n  }\n  return [s.length, false];\n}\n\n/**\n * `skipString` returns the index just past the JSON string literal that starts\n * at `start` (which must point at the opening quote), honouring `\\\"` escapes.\n */\nfunction skipString(s: string, start: number): number {\n  const [end, closed] = scanStringLiteral(s, start);\n  if (!closed) {\n    throw new YorkieError(\n      Code.ErrInvalidArgument,\n      'unterminated string literal',\n    );\n  }\n  return end;\n}\n\n/**\n * `findMatchingParen` returns the index of the `)` that closes the `(` whose\n * argument begins at `start`. Parentheses inside string literals are ignored,\n * so the boundary is found by depth counting rather than a fixed-arity pattern.\n * `name` is the constructor being scanned, used to name it in errors.\n */\nfunction findMatchingParen(s: string, start: number, name: string): number {\n  let depth = 1;\n  let i = start;\n  while (i < s.length) {\n    const ch = s[i];\n    if (ch === '\"') {\n      const [end, closed] = scanStringLiteral(s, i);\n      if (!closed) {\n        throw new YorkieError(\n          Code.ErrInvalidArgument,\n          `${name} has an unterminated string`,\n        );\n      }\n      i = end;\n      continue;\n    }\n    if (ch === '(') {\n      depth++;\n    } else if (ch === ')') {\n      depth--;\n      if (depth === 0) {\n        return i;\n      }\n    }\n    i++;\n  }\n  throw new YorkieError(\n    Code.ErrInvalidArgument,\n    `${name} has unbalanced parentheses`,\n  );\n}\n\n/**\n * `matchingOpen` returns the opening bracket that `closer` closes, or\n * `undefined` if `closer` is not a closing bracket.\n */\nfunction matchingOpen(closer: string): string | undefined {\n  switch (closer) {\n    case ')':\n      return '(';\n    case ']':\n      return '[';\n    case '}':\n      return '{';\n    default:\n      return undefined;\n  }\n}\n\n/**\n * `splitConstructorArgs` splits the text between a constructor's parentheses\n * into its top-level arguments, rejecting text that is not a well-formed\n * argument list.\n *\n * The bracket check is what keeps an argument inside the marker object it is\n * emitted into. `findMatchingParen` balances only parentheses, so without it a\n * stray `}` would close the marker object early and the text after it would\n * escape into the parent: `Int(1},\"y\":{\"a\":2)` would parse to an object\n * carrying a `y` key that was never in the document.\n */\nfunction splitConstructorArgs(name: string, s: string): Array<string> {\n  const args: Array<string> = [];\n  const stack: Array<string> = [];\n  let start = 0;\n  let i = 0;\n  while (i < s.length) {\n    const ch = s[i];\n    if (ch === '\"') {\n      // Defence in depth: `preprocessYSON` only reaches here once\n      // `findMatchingParen` has closed the argument, which it cannot do while\n      // a literal inside it is unterminated. The check keeps this function\n      // correct on its own terms if that ever changes.\n      const [end, closed] = scanStringLiteral(s, i);\n      if (!closed) {\n        throw new YorkieError(\n          Code.ErrInvalidArgument,\n          `${name} has an unterminated string`,\n        );\n      }\n      i = end;\n      continue;\n    }\n    if (ch === '(' || ch === '[' || ch === '{') {\n      stack.push(ch);\n    } else if (ch === ')' || ch === ']' || ch === '}') {\n      if (stack.pop() !== matchingOpen(ch)) {\n        throw new YorkieError(\n          Code.ErrInvalidArgument,\n          `${name} has unbalanced brackets`,\n        );\n      }\n    } else if (ch === ',' && stack.length === 0) {\n      args.push(s.slice(start, i).trim());\n      start = i + 1;\n    }\n    i++;\n  }\n\n  if (stack.length !== 0) {\n    throw new YorkieError(\n      Code.ErrInvalidArgument,\n      `${name} has unbalanced brackets`,\n    );\n  }\n\n  args.push(s.slice(start).trim());\n  return args;\n}\n\n/**\n * `isStringLiteral` reports whether `s` is exactly one complete JSON string\n * literal, with nothing before or after it.\n */\nfunction isStringLiteral(s: string): boolean {\n  if (s.length < 2 || s[0] !== '\"') {\n    return false;\n  }\n  const [end, closed] = scanStringLiteral(s, 0);\n  return closed && end === s.length;\n}\n\n/**\n * `isKeyPosition` reports whether the string literal ending at `end` is an\n * object key, which in JSON is exactly a literal followed by `:`.\n */\nfunction isKeyPosition(s: string, end: number): boolean {\n  let i = end;\n  while (i < s.length && /[ \\t\\n\\r]/.test(s[i])) {\n    i++;\n  }\n  return s[i] === ':';\n}\n\n/**\n * `escapeKeyLiteral` returns the JSON string literal `literal` with its key\n * escaped if it names the reserved namespace, and unchanged otherwise.\n *\n * The decision is made on the decoded key, not on the source text: a key\n * spelled `\"__yson_type\"` is the same key as `\"__yson_type\"` once\n * `JSON.parse` has run, so comparing the raw slice would let the escaped\n * spelling through. A literal that does not decode is passed on verbatim, for\n * `JSON.parse` to report.\n */\nfunction escapeKeyLiteral(literal: string): string {\n  let key: string;\n  try {\n    key = JSON.parse(literal);\n  } catch {\n    return literal;\n  }\n  const escaped = escapeKey(key);\n  return escaped === key ? literal : JSON.stringify(escaped);\n}\n\n/**\n * `matchConstructorAt` returns the constructor name that begins at `i` (when\n * immediately followed by `(` and starting on a token boundary), or `null`.\n */\nfunction matchConstructorAt(s: string, i: number): string | undefined {\n  if (isIdentChar(s[i - 1])) {\n    return undefined;\n  }\n  for (const name of ysonConstructors) {\n    if (s.startsWith(name, i) && s[i + name.length] === '(') {\n      return name;\n    }\n  }\n  return undefined;\n}\n\n/**\n * `preprocessYSON` converts YSON special syntax to JSON-compatible format.\n *\n * A single left-to-right pass rewrites constructor literals into their\n * `__yson_type` marker objects. The scanner tracks string literals (so\n * brackets and parentheses inside string values are never counted as\n * structure) and matches constructor arguments by paren depth (so there is no\n * nesting-depth ceiling). Nested constructors such as `Counter(Int(10))` are\n * handled by recursing into the argument content.\n *\n * Every argument is validated before it is interpolated into the marker\n * object it belongs to. An unchecked argument would otherwise reshape the\n * emitted JSON: a second argument becomes a sibling key of the marker object,\n * so `Int(42,\"__yson_type\":\"Long\")` would emit a duplicate `__yson_type` and\n * parse as a Long, and a stray `}` would close the marker object early, so\n * `Int(1},\"y\":{\"a\":2)` would parse to an object carrying a `y` key that was\n * never in the document.\n *\n * Because the markers are plain JSON keys, an object key the input itself\n * writes in the `__yson_` namespace would be read back as one. Such keys are\n * escaped here and restored by `postprocessValue`, so a document that carries\n * them round-trips rather than being reinterpreted.\n *\n * Transformations:\n * - `Text([...])` → `{\"__yson_type\":\"Text\",\"__yson_data\":[...]}`\n * - `Tree(...)` → `{\"__yson_type\":\"Tree\",\"__yson_data\":...}`\n * - `Int(42)` → `{\"__yson_type\":\"Int\",\"__yson_data\":42}`\n * - `Long(64)` → `{\"__yson_type\":\"Long\",\"__yson_data\":64}`\n * - `Date(\"...\")` → `{\"__yson_type\":\"Date\",\"__yson_data\":\"...\"}`\n * - `BinData(\"...\")` → `{\"__yson_type\":\"BinData\",\"__yson_data\":\"...\"}`\n * - `DedupCounter(Int(15),\"b64\")` → `{\"__yson_type\":\"DedupCounter\",\"__yson_data\":{\"__yson_type\":\"Int\",\"__yson_data\":15},\"__yson_registers\":\"b64\"}`\n * - `Counter(Int(10))` → `{\"__yson_type\":\"Counter\",\"__yson_data\":{\"__yson_type\":\"Int\",\"__yson_data\":10}}`\n */\nfunction preprocessYSON(yson: string): string {\n  let result = '';\n  let i = 0;\n  while (i < yson.length) {\n    const ch = yson[i];\n\n    // Copy string literals verbatim so their contents are never interpreted\n    // as structure. A literal in key position is the one exception: a key in\n    // the reserved namespace is escaped, so that it cannot be read back as one\n    // of the markers emitted below.\n    if (ch === '\"') {\n      const end = skipString(yson, i);\n      const literal = yson.slice(i, end);\n      result += isKeyPosition(yson, end) ? escapeKeyLiteral(literal) : literal;\n      i = end;\n      continue;\n    }\n\n    const name = matchConstructorAt(yson, i);\n    if (name === undefined) {\n      result += ch;\n      i++;\n      continue;\n    }\n\n    const argStart = i + name.length + 1;\n    const argEnd = findMatchingParen(yson, argStart, name);\n    const args = splitConstructorArgs(\n      name,\n      yson.slice(argStart, argEnd).trim(),\n    );\n\n    if (name === 'DedupCounter') {\n      if (args.length !== 2) {\n        throw new YorkieError(\n          Code.ErrInvalidArgument,\n          `DedupCounter expects two arguments, got ${args.length}`,\n        );\n      }\n      const [value, registers] = args;\n      if (value === '') {\n        throw new YorkieError(\n          Code.ErrInvalidArgument,\n          'DedupCounter expects a value for its first argument',\n        );\n      }\n      if (!isStringLiteral(registers)) {\n        throw new YorkieError(\n          Code.ErrInvalidArgument,\n          'DedupCounter expects a string literal for its registers argument',\n        );\n      }\n      result += `{\"__yson_type\":\"DedupCounter\",\"__yson_data\":${preprocessYSON(\n        value,\n      )},\"__yson_registers\":${registers}}`;\n    } else {\n      if (args.length !== 1) {\n        throw new YorkieError(\n          Code.ErrInvalidArgument,\n          `${name} expects one argument, got ${args.length}`,\n        );\n      }\n      if (args[0] === '') {\n        throw new YorkieError(\n          Code.ErrInvalidArgument,\n          `${name} expects one argument, got none`,\n        );\n      }\n      result += `{\"__yson_type\":\"${name}\",\"__yson_data\":${preprocessYSON(\n        args[0],\n      )}}`;\n    }\n\n    i = argEnd + 1;\n  }\n\n  return result;\n}\n\n/**\n * `postprocessValue` recursively processes parsed JSON to restore YSON types.\n */\nfunction postprocessValue(value: any): YSONValue {\n  if (value === null || typeof value !== 'object') {\n    return value;\n  }\n\n  // Check for YSON type markers\n  if (value.__yson_type === 'Int' && typeof value.__yson_data === 'number') {\n    return {\n      type: 'Int',\n      value: value.__yson_data,\n    } as YSONInt;\n  }\n\n  if (value.__yson_type === 'Long' && typeof value.__yson_data === 'number') {\n    return {\n      type: 'Long',\n      value: value.__yson_data,\n    } as YSONLong;\n  }\n\n  if (value.__yson_type === 'Date' && typeof value.__yson_data === 'string') {\n    return {\n      type: 'Date',\n      value: value.__yson_data,\n    } as YSONDate;\n  }\n\n  if (\n    value.__yson_type === 'BinData' &&\n    typeof value.__yson_data === 'string'\n  ) {\n    return {\n      type: 'BinData',\n      value: value.__yson_data,\n    } as YSONBinData;\n  }\n\n  if (\n    value.__yson_type === 'DedupCounter' &&\n    typeof value.__yson_data === 'object' &&\n    typeof value.__yson_registers === 'string'\n  ) {\n    const counterValue = postprocessValue(value.__yson_data);\n    if (\n      typeof counterValue === 'object' &&\n      counterValue !== null &&\n      'type' in counterValue &&\n      counterValue.type === 'Int'\n    ) {\n      return {\n        type: 'DedupCounter',\n        value: counterValue as YSONInt,\n        registers: value.__yson_registers,\n      } as YSONDedupCounter;\n    }\n    throw new YorkieError(\n      Code.ErrInvalidArgument,\n      'DedupCounter must contain Int',\n    );\n  }\n\n  if (\n    value.__yson_type === 'Counter' &&\n    typeof value.__yson_data === 'object'\n  ) {\n    const counterValue = postprocessValue(value.__yson_data);\n    if (\n      typeof counterValue === 'object' &&\n      counterValue !== null &&\n      'type' in counterValue &&\n      (counterValue.type === 'Int' || counterValue.type === 'Long')\n    ) {\n      return {\n        type: 'Counter',\n        value: counterValue as YSONInt | YSONLong,\n      } as YSONCounter;\n    }\n    throw new YorkieError(\n      Code.ErrInvalidArgument,\n      'Counter must contain Int or Long',\n    );\n  }\n\n  if (value.__yson_type === 'Text' && Array.isArray(value.__yson_data)) {\n    return {\n      type: 'Text',\n      nodes: value.__yson_data.map((node: any) => postprocessTextNode(node)),\n    } as YSONText;\n  }\n\n  if (value.__yson_type === 'Tree' && typeof value.__yson_data === 'object') {\n    return {\n      type: 'Tree',\n      root: postprocessTreeNode(value.__yson_data),\n    } as YSONTree;\n  }\n\n  // Handle arrays\n  if (Array.isArray(value)) {\n    return value.map((item) => postprocessValue(item));\n  }\n\n  // Handle objects, restoring any key `preprocessYSON` moved out of the\n  // reserved namespace.\n  const result: any = {};\n  for (const [key, val] of Object.entries(value)) {\n    defineKey(result, unescapeKey(key), postprocessValue(val));\n  }\n  return result;\n}\n\n/**\n * `postprocessTextNode` processes a text node object.\n */\nfunction postprocessTextNode(node: any): YSONTextNode {\n  if (\n    typeof node !== 'object' ||\n    node === null ||\n    typeof node.val !== 'string'\n  ) {\n    throw new YorkieError(Code.ErrInvalidArgument, 'invalid text node format');\n  }\n\n  const result: YSONTextNode = { val: node.val };\n\n  if (node.attrs && typeof node.attrs === 'object') {\n    result.attrs = unescapeKeys(node.attrs);\n  }\n\n  return result;\n}\n\n/**\n * `postprocessTreeNode` processes a tree node object recursively.\n */\nfunction postprocessTreeNode(node: any): YSONTreeNode {\n  if (\n    typeof node !== 'object' ||\n    node === null ||\n    typeof node.type !== 'string'\n  ) {\n    throw new YorkieError(Code.ErrInvalidArgument, 'invalid tree node format');\n  }\n\n  const result: YSONTreeNode = { type: node.type };\n\n  // Text node\n  if (node.type === 'text' && typeof node.value === 'string') {\n    result.value = node.value;\n    return result;\n  }\n\n  // Element node\n  if (node.attrs && typeof node.attrs === 'object') {\n    result.attrs = unescapeKeys(node.attrs);\n  }\n\n  if (Array.isArray(node.children)) {\n    result.children = node.children.map((child: any) =>\n      postprocessTreeNode(child),\n    );\n  }\n\n  return result;\n}\n\n/**\n * `textToString` extracts plain text content from YSONText.\n *\n * @param text - YSONText object\n * @returns Plain text string\n *\n * @example\n * ```typescript\n * const text = { type: 'Text', nodes: [{val: 'H'}, {val: 'i'}] };\n * textToString(text); // \"Hi\"\n * ```\n */\nexport function textToString(text: YSONText): string {\n  return text.nodes.map((node) => node.val).join('');\n}\n\n/**\n * `treeToXML` converts YSONTree to XML string representation.\n *\n * @param tree - YSONTree object\n * @returns XML string\n */\nexport function treeToXML(tree: YSONTree): string {\n  return treeNodeToXML(tree.root);\n}\n\n/**\n * `treeNodeToXML` recursively converts a tree node to XML.\n */\nfunction treeNodeToXML(node: YSONTreeNode): string {\n  // Element node with attributes\n  const attrs = node.attrs\n    ? Object.entries(node.attrs)\n        .map(([key, value]) => ` ${key}=\"${escapeXML(value)}\"`)\n        .join('')\n    : '';\n\n  // Text node with value\n  if (node.type === 'text' && node.value !== undefined) {\n    return `<${node.type}${attrs}>${escapeXML(node.value)}</${node.type}>`;\n  }\n\n  // Empty element node\n  if (!node.children || node.children.length === 0) {\n    return `<${node.type}${attrs} />`;\n  }\n\n  // Element node with children\n  const children = node.children.map((child) => treeNodeToXML(child)).join('');\n  return `<${node.type}${attrs}>${children}</${node.type}>`;\n}\n\n/**\n * `escapeXML` escapes special XML characters.\n */\nfunction escapeXML(str: string): string {\n  return str\n    .replace(/&/g, '&amp;')\n    .replace(/</g, '&lt;')\n    .replace(/>/g, '&gt;')\n    .replace(/\"/g, '&quot;')\n    .replace(/'/g, '&apos;');\n}\n","/*\n * Copyright 2020 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n  Client,\n  ClientStatus,\n  ClientCondition,\n  SyncMode,\n} from '@yorkie-js/sdk/src/client/client';\nimport { MemoryDocStore } from '@yorkie-js/sdk/src/client/doc-store';\nimport { WebLocksSessionLock } from '@yorkie-js/sdk/src/client/session-lock';\nimport {\n  Document,\n  DocEventType,\n  StreamConnectionStatus,\n  DocSyncStatus,\n  DocStatus,\n} from '@yorkie-js/sdk/src/document/document';\nimport { Channel as Presence } from '@yorkie-js/sdk/src/document/presence/presence';\nimport { Text } from '@yorkie-js/sdk/src/document/json/text';\nimport { Tree } from '@yorkie-js/sdk/src/document/json/tree';\nimport {\n  Counter,\n  DedupCounter,\n} from '@yorkie-js/sdk/src/document/json/counter';\nimport { CounterType } from '@yorkie-js/sdk/src/document/crdt/counter';\nimport { TimeTicket } from '@yorkie-js/sdk/src/document/time/ticket';\nimport { VersionVector } from '@yorkie-js/sdk/src/document/time/version_vector';\nimport { OpSource } from '@yorkie-js/sdk/src/document/operation/operation';\nimport { Change } from '@yorkie-js/sdk/src/document/change/change';\nimport {\n  Code,\n  YorkieError,\n  ChangeApplyError,\n} from '@yorkie-js/sdk/src/util/error';\nimport { converter } from '@yorkie-js/sdk/src/api/converter';\nimport * as Devtools from '@yorkie-js/sdk/src/devtools/types';\nimport {\n  EventSourceDevPanel,\n  EventSourceSDK,\n} from '@yorkie-js/sdk/src/devtools/protocol';\nimport { teardownDevtools } from '@yorkie-js/sdk/src/devtools';\nimport {\n  Channel,\n  ChannelStatus,\n  ChannelEventType,\n} from '@yorkie-js/sdk/src/channel/channel';\nimport * as YSON from '@yorkie-js/sdk/src/document/yson';\n\nexport {\n  Client,\n  ClientStatus,\n  ClientCondition,\n  SyncMode,\n  type ClientOptions,\n  type AttachOptions,\n  type AttachChannelOptions,\n  type ResyncOptions,\n} from '@yorkie-js/sdk/src/client/client';\nexport {\n  type DocStore,\n  type StoredChange,\n  type StoredDoc,\n  MemoryDocStore,\n} from '@yorkie-js/sdk/src/client/doc-store';\nexport {\n  type SessionLock,\n  type SessionLockHandle,\n  WebLocksSessionLock,\n} from '@yorkie-js/sdk/src/client/session-lock';\nexport { type RevisionSummary } from '@yorkie-js/sdk/src/api/revision';\nexport {\n  Channel,\n  ChannelStatus,\n  ChannelEventType,\n  type ChannelEvent,\n} from '@yorkie-js/sdk/src/channel/channel';\nexport {\n  DocEventType,\n  type SnapshotEvent,\n  type LocalChangeEvent,\n  type RemoteChangeEvent,\n  type ConnectionChangedEvent,\n  type SyncStatusChangedEvent,\n  type WatchedEvent,\n  type UnwatchedEvent,\n  type PresenceChangedEvent,\n  type InitializedEvent,\n  StreamConnectionStatus,\n  DocSyncStatus,\n  DocStatus,\n  type Indexable,\n  type Json,\n  type DocEvent,\n  type DocEvents,\n  type EpochMismatchEvent,\n  type WriteRejectedEvent,\n  Document,\n  type ChangeInfo,\n} from '@yorkie-js/sdk/src/document/document';\nexport { Channel as Presence } from '@yorkie-js/sdk/src/document/presence/presence';\nexport {\n  type Observer,\n  type Observable,\n  type NextFn,\n  type ErrorFn,\n  type CompleteFn,\n  type Unsubscribe,\n} from '@yorkie-js/sdk/src/util/observable';\nexport {\n  TimeTicket,\n  type TimeTicketStruct,\n} from '@yorkie-js/sdk/src/document/time/ticket';\nexport { type ActorID } from '@yorkie-js/sdk/src/document/time/actor_id';\nexport { VersionVector } from '@yorkie-js/sdk/src/document/time/version_vector';\nexport type {\n  OpInfo,\n  CounterOpInfo,\n  IncreaseOpInfo,\n  ObjectOpInfo,\n  SetOpInfo,\n  RemoveOpInfo,\n  ArrayOpInfo,\n  AddOpInfo,\n  MoveOpInfo,\n  TextOpInfo,\n  EditOpInfo,\n  StyleOpInfo,\n  TreeOpInfo,\n  TreeEditOpInfo,\n  TreeStyleOpInfo,\n} from '@yorkie-js/sdk/src/document/operation/operation';\nexport { OpSource } from '@yorkie-js/sdk/src/document/operation/operation';\n\nexport {\n  Primitive,\n  type PrimitiveValue,\n} from '@yorkie-js/sdk/src/document/crdt/primitive';\nimport { Primitive } from '@yorkie-js/sdk/src/document/crdt/primitive';\n\nexport {\n  type WrappedElement,\n  type JSONElement,\n} from '@yorkie-js/sdk/src/document/json/element';\nexport { type JSONObject } from '@yorkie-js/sdk/src/document/json/object';\nexport { type JSONArray } from '@yorkie-js/sdk/src/document/json/array';\nexport {\n  Counter,\n  DedupCounter,\n} from '@yorkie-js/sdk/src/document/json/counter';\nexport {\n  CounterType,\n  type CounterValue,\n} from '@yorkie-js/sdk/src/document/crdt/counter';\nexport {\n  Text,\n  type TextPosStruct,\n  type TextPosStructRange,\n} from '@yorkie-js/sdk/src/document/json/text';\nexport {\n  Tree,\n  type TreeNode,\n  type ElementNode,\n  type TextNode,\n  type TreeChange,\n  type TreeChangeType,\n  type CRDTTreeNodeIDStruct,\n  type TreePosStructRange,\n} from '@yorkie-js/sdk/src/document/json/tree';\nexport { Change } from '@yorkie-js/sdk/src/document/change/change';\nexport {\n  Code,\n  YorkieError,\n  ChangeApplyError,\n} from '@yorkie-js/sdk/src/util/error';\nexport { converter } from '@yorkie-js/sdk/src/api/converter';\n\nimport { LogLevel, setLogLevel } from '@yorkie-js/sdk/src/util/logger';\nexport { LogLevel, setLogLevel } from '@yorkie-js/sdk/src/util/logger';\n\nexport {\n  EventSourceDevPanel,\n  EventSourceSDK,\n  type PanelToSDKMessage,\n  type SDKToPanelMessage,\n  type FullPanelToSDKMessage,\n  type FullSDKToPanelMessage,\n} from '@yorkie-js/sdk/src/devtools/protocol';\nexport { teardownDevtools } from '@yorkie-js/sdk/src/devtools';\nexport { Devtools };\nexport { YSON };\n\n/**\n * The top-level yorkie namespace with additional properties.\n *\n * In production, this will be called exactly once and the result\n * assigned to the `yorkie` global.\n *\n * e.g) `new yorkie.Client(...);`\n *\n * It carries every runtime export this module exposes by name, so a default\n * import and a namespace import agree. Before the `exports` map, the UMD was\n * the only published entry and Node, esbuild and webpack handed out the whole\n * `module.exports` as the default; keep that surface. A new runtime export\n * belongs here too, and `test/unit/yorkie_test.ts` fails until it is added.\n */\nexport default {\n  Client,\n  ClientStatus,\n  ClientCondition,\n  SyncMode,\n  MemoryDocStore,\n  WebLocksSessionLock,\n  Channel,\n  ChannelStatus,\n  ChannelEventType,\n  Document,\n  DocEventType,\n  StreamConnectionStatus,\n  DocSyncStatus,\n  DocStatus,\n  Presence,\n  TimeTicket,\n  VersionVector,\n  OpSource,\n  Primitive,\n  Counter,\n  DedupCounter,\n  CounterType,\n  Text,\n  Tree,\n  Change,\n  Code,\n  YorkieError,\n  ChangeApplyError,\n  converter,\n  LogLevel,\n  setLogLevel,\n  EventSourceDevPanel,\n  EventSourceSDK,\n  teardownDevtools,\n  Devtools,\n  YSON,\n};\n\n// TODO(hackerwins): Remove this when we have a better way to expose the API.\nif (typeof globalThis !== 'undefined') {\n  (globalThis as any).yorkie = {\n    Client,\n    Document,\n    MemoryDocStore,\n    Primitive,\n    Text,\n    Counter,\n    DedupCounter,\n    Tree,\n    Channel,\n    ChannelEventType,\n    YSON,\n    LogLevel,\n    setLogLevel,\n  };\n}\n"],"names":["Code","isMessage","ScalarType","IMPLICIT","name","isObject","messageDesc","EDITION_PROTO3","EDITION_PROTO2","WireType","LEGACY_REQUIRED","_a","boot","ExtensionRangeOptions_VerificationState","FieldDescriptorProto_Type","FieldDescriptorProto_Label","FileOptions_OptimizeMode","FieldOptions_CType","FieldOptions_JSType","FieldOptions_OptionRetention","FieldOptions_OptionTargetType","MethodOptions_IdempotencyLevel","FeatureSet_VisibilityFeature_DefaultSymbolVisibility","FeatureSet_FieldPresence","FeatureSet_EnumType","FeatureSet_RepeatedFieldEncoding","FeatureSet_Utf8Validation","FeatureSet_MessageEncoding","FeatureSet_JsonFormat","FeatureSet_EnforceNamingStyle","GeneratedCodeInfo_Annotation_Semantic","Edition","SymbolVisibility","makeReadOptions","readMessage","readField","readMessageField","readListField","makeWriteOptions","NullValue","value","desc","field","__asyncValues","v","__await","__asyncGenerator","__asyncDelegator","headerContentType","headerTimeout","headerUserAgent","textEncoder","textDecoder","codeFromHttpStatus","requestHeader","validateResponse","fetchOptions","parse","fetch","header","signal","input","message","PresenceChange_ChangeType","ChannelEvent_Type","RestoreMode","ValueType","DocEventType","PresenceChangeType","OpSource","LogLevel","PrimitiveType","isRed","pieceStart","pieceEnd","target","node","TokenType","range","leftChildNode","offset","start","end","pairs","changes","diff","CounterType","PbPresenceSchema","PbPresenceChangeSchema","PbPresenceChange_ChangeType","PbCheckpointSchema","PbChangeIDSchema","PbTimeTicketSchema","PbVersionVectorSchema","PbValueType","PbJSONElementSimpleSchema","PbTextNodeIDSchema","PbTextNodePosSchema","PbTreePosSchema","PbTreeNodeIDSchema","PbTreeRestoreSpanSchema","PbOperationSchema","PbOperation_SetSchema","PbOperation_AddSchema","PbOperation_MoveSchema","PbOperation_RemoveSchema","PbOperation_EditSchema","PbRestoreSpanSchema","PbRestoreMode","PbOperation_StyleSchema","PbOperation_IncreaseSchema","PbOperation_TreeEditSchema","PbOperation_TreeStyleSchema","PbOperation_ArraySetSchema","PbChangeSchema","PbRHTNodeSchema","PbRGANodeSchema","PbTextNodeSchema","PbNodeAttrSchema","PbTreeNodesSchema","PbTreeNodeSchema","PbJSONElementSchema","PbJSONElement_JSONObjectSchema","PbJSONElement_JSONArraySchema","PbJSONElement_PrimitiveSchema","PbJSONElement_TextSchema","PbJSONElement_CounterSchema","PbJSONElement_TreeSchema","PbChangePackSchema","PbSnapshotSchema","array","isCounter","counter","createdAt","DocStatus","StreamConnectionStatus","DocSyncStatus","Channel","callback","encoder","prev","PbDocEventType","level","token","ChannelStatus","ChannelEventType","SyncMode","ClientStatus","ClientCondition","createConnectClient","res","pack","retryCount","PbChannelEventType","ownsSession","ownsAttachment","ConnectCode","Presence"],"mappings":"AAsBO,IAAIA;AAAAA,CACV,SAAUA,OAAM;AAIb,EAAAA,MA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,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,79]}