{"version":3,"file":"cli.mjs","names":["pidAlive","e","wsCarrier","ConnectionTransportManager","isDialUnavailable","join","normalize","base64","base64","base64","isPlainObject","base64","v.pipe","v.string","v.base64","v.custom","v.object","v.string","v.intersect","v.optional","v.boolean","fromBase64","base64","fromJwk","fromSerializedObject","fromFormattedString","extractableOrNonExtractable","base64","base64","base64","base64","base64","scopedUrlAlphabet","v.custom","v.object","v.string","v.optional","v.picklist","v.literal","v.array","v.number","v.variant","v.safeParse","position","bundledStrings","errors","textEncoder","fs","createRequire","HANDSHAKE_TIMEOUT_MS","KEEPALIVE_PING","KEEPALIVE_PONG","makeSession","TransportConnection","textEncoder","textDecoder","DEFAULT_SERVER_SECURITY_LEVELS","exports","StatusCodes","t","O","runtime","WireConnectionTransportManager","DEFAULT_SERVER_SECURITY_LEVELS","WireTransportConnection","wireWsCarrier","isPlainObject","isPlainObject","unwrapOptional","getAtPath","unwrapOptional","getAtPath","getAtPath","unwrapOptional","getAtPath","unwrapOptional","unwrapOptional","unwrapOptional","getAtPath","getAtPath","exec","pidAlive","pidAlive","WebSocket","STORE_VERSION","readable","exec","normalize","STORE_VERSION","bounded","STORE_VERSION","ACTIVE_STATES","pidAlive"],"sources":["../src/cli/args.ts","../src/daemon/instanceRecord.ts","../src/daemon/packageVersion.ts","../src/cli/configSync.ts","../src/config/flags.ts","../src/config/tags.ts","../src/config/tagGroups.ts","../src/protocol/savedFilters.ts","../src/config/resolve.ts","../src/config/loader.ts","../src/config/hash.ts","../src/config/envVars.ts","../src/config/validate.ts","../src/cli/load.ts","../src/cli/context.ts","../../nice-wire/src/Carrier/AcceptorCarrier.ts","../../nice-error/src/internal/internal_errors.ts","../../nice-error/src/utils/getErrorDomainProps.ts","../../nice-error/src/utils/jsErrorOrCastJsError.ts","../../nice-error/package.json","../../nice-error/src/utils/logger.ts","../../nice-error/src/utils/loadedVersions.ts","../../nice-error/src/NiceError/nice_error.static.ts","../../nice-error/src/utils/packError/causePack.ts","../../nice-error/src/utils/packError/msgPack.ts","../../nice-error/src/utils/packError/packError.ts","../../nice-error/src/utils/serializeErrorCause.ts","../../nice-error/src/NiceError/NiceError.ts","../../nice-error/src/NiceError/NiceErrorHydrated.ts","../../nice-error/src/observability/tap.ts","../../nice-error/src/utils/isNiceErrorObject.ts","../../nice-error/src/utils/foreignNiceErrorRecord.ts","../../nice-error/src/NiceErrorDomain/NiceErrorDomain.ts","../../nice-error/src/NiceErrorDomain/defineNiceError.ts","../../nice-error/src/NiceErrorDomain/err.ts","../../nice-error/src/internal/nice_core_errors.ts","../../nice-error/src/utils/isRegularErrorObject.ts","../../nice-error/src/utils/inspectPotentialError/inspectPotentialError.ts","../../nice-error/src/utils/castNiceError.ts","../../nice-error/src/result/niceTry.ts","../../nice-wire/src/Connect/err_wire_connect.ts","../../nice-wire/src/Carrier/duplex/inboundFrameQueue.ts","../../nice-wire/src/Connect/sanitizeEndpoint.ts","../../nice-wire/src/Carrier/duplex/ws/ws_util.ts","../../nice-wire/src/Carrier/duplex/ws/webSocketByteChannel.ts","../../nice-wire/src/Carrier/duplex/ws/wsCarrier.ts","../../nice-wire/src/Connect/endpointEvidence.ts","../../nice-wire/src/Connect/ConnectionTransportManager.ts","../../nice-util/src/data_type/string/nullEmpty.ts","../../nice-util/src/crypto/x25519/createSharedBitsFromX25519.ts","../../nice-util/src/crypto/aes_gcm/createAesGcmKeyFromX25519Keys.ts","../../nice-util/src/crypto/aes_gcm/decryptBytesWithAesGcmKey.ts","../../../node_modules/@scure/base/index.js","../../nice-util/src/crypto/aes_gcm/decryptTextDataWithAesGcmKey.ts","../../nice-util/src/crypto/aes_gcm/encryptBytesWithAesGcmKey.ts","../../nice-util/src/crypto/aes_gcm/encryptTextDataWithAesGcmKey.ts","../../nice-util/src/crypto/canonical/stringifyCanonicalJson.ts","../../nice-util/src/crypto/canonical/buildCanonicalChallenge.ts","../../nice-util/src/data_type/bytes/base64.ts","../../nice-util/src/crypto/canonical/sha256.ts","../../nice-util/src/crypto/ed25519/signTextDataWithKeyEd25519.ts","../../nice-util/src/crypto/ed25519/signCombinedTextDataWithKeyEd25519.ts","../../nice-util/src/crypto/client_key_link/buildVerifyKeyBoundInfoString.ts","../../nice-util/src/storage_adapter/typed_storage/StorageValidationError.ts","../../nice-util/src/storage_adapter/typed_storage/createTypedStorage.ts","../../nice-util/src/crypto/ed25519/generateEd25519KeyPair.ts","../../nice-util/src/core/createDataStringConverter_stringToObject.ts","../../../node_modules/valibot/dist/index.mjs","../../nice-util/src/core/core_valibot_schemas.ts","../../nice-util/src/crypto/crypto.schema.ts","../../nice-util/src/crypto/crypto.converters.ts","../../nice-util/src/crypto/ed25519/importEd25519Key.ts","../../nice-util/src/crypto/ed25519/serializeEd25519Key_Jwk.ts","../../nice-util/src/crypto/ed25519/serializeEd25519Key_Raw.ts","../../nice-util/src/crypto/ed25519/verifyWithKeyEd25519.ts","../../nice-util/src/crypto/x25519/generateX25519KeyPair.ts","../../nice-util/src/crypto/x25519/importX25519Key.ts","../../nice-util/src/crypto/x25519/serializeX25519Key_Jwk.ts","../../nice-util/src/crypto/x25519/serializeX25519Key_Raw.ts","../../nice-util/src/crypto/client_key_link/withKeyMintLock.ts","../../nice-util/src/crypto/client_key_link/ClientCryptoKeyLink.ts","../../nice-util/src/storage_adapter/StorageAdapter.ts","../../nice-util/src/storage_adapter/specific/memory/memory_storage.ts","../../nice-util/src/timing/unrefTimer.ts","../../../node_modules/nanoid/url-alphabet/index.js","../../../node_modules/nanoid/index.js","../../nice-wire/src/protocolVersion.ts","../../nice-wire/src/nice_wire.static.ts","../../nice-wire/src/utils/runtimeCoordinateToStringIds.ts","../../nice-wire/src/RuntimeCoordinate.ts","../../nice-wire/src/crypto/actionHandshake.ts","../../nice-wire/src/crypto/securityLevelOrder.ts","../../nice-wire/src/Connect/WireClient.ts","../../../node_modules/msgpackr/unpack.js","../../../node_modules/msgpackr/pack.js","../../../node_modules/detect-libc/lib/process.js","../../../node_modules/detect-libc/lib/filesystem.js","../../../node_modules/detect-libc/lib/elf.js","../../../node_modules/detect-libc/lib/detect-libc.js","../../../node_modules/node-gyp-build-optional-packages/node-gyp-build.js","../../../node_modules/node-gyp-build-optional-packages/index.js","../../../node_modules/msgpackr-extract/index.js","../../../node_modules/msgpackr/node-index.js","../../nice-wire/src/crypto/actionFrameCrypto.ts","../../nice-wire/src/Mux/protocolFrame.ts","../../nice-wire/src/crypto/frameBytes.ts","../../nice-wire/src/SecureSession/frameCryptoPipe.ts","../../nice-wire/src/tap/wireTap.ts","../../nice-wire/src/Connect/handshakeRejectError.ts","../../nice-wire/src/Connect/duplexLinkSession.ts","../../nice-wire/src/Connect/webCryptoPreflight.ts","../../nice-wire/src/Connect/TransportConnection.ts","../../nice-wire/src/Mux/WireProtocolMux.ts","../../nice-wire/src/Connect/wireConnectionParts.ts","../../nice-wire/src/Connect/exchangeEnvelope.ts","../../nice-wire/src/SecureSession/exchangeTicketSeal.ts","../../nice-wire/src/Connect/exchangeSessionShelf.ts","../../nice-wire/src/Connect/exchangeSession.ts","../../nice-wire/src/SecureSession/acceptorSecureSession.ts","../../nice-wire/src/Connect/WireAcceptor.ts","../../nice-wire/src/Connect/serveWire.ts","../../nice-wire/src/Connect/WireExchangeAcceptor.ts","../../nice-wire/src/codec/controlFrame.ts","../../nice-wire/src/PeerLink/ReliableInbox.ts","../../nice-wire/src/PeerLink/ReliableLog.ts","../../nice-wire/src/PeerLink/reliableStream.ts","../../nice-action/src/ActionDefinition/Action/ActionBase.ts","../../nice-action/src/ActionDefinition/Action/Context/ActionContext.ts","../../nice-action/src/ActionDefinition/Action/Payload/ActionPayload.ts","../../nice-action/src/utils/hashPayloadData.ts","../../nice-action/src/ActionDefinition/Action/Payload/ActionPayload_Progress.ts","../../nice-action/src/ActionDefinition/Action/Payload/ActionPayload_Result.ts","../../nice-action/src/ActionDefinition/Action/Payload/ActionPayload_Request.ts","../../nice-action/src/ActionDefinition/Action/Core/ActionCore.ts","../../nice-action/src/ActionDefinition/Action/RunningAction.ts","../../nice-action/src/errors/err_nice_action.ts","../../nice-action/src/utils/isAction_Base_JsonObject.ts","../../nice-action/src/utils/isActionPayload_Result_JsonObject.ts","../../../node_modules/http-status-codes/build/cjs/legacy.js","../../../node_modules/http-status-codes/build/cjs/utils.js","../../../node_modules/http-status-codes/build/cjs/utils-functions.js","../../../node_modules/http-status-codes/build/cjs/status-codes.js","../../../node_modules/http-status-codes/build/cjs/reason-phrases.js","../../../node_modules/http-status-codes/build/cjs/index.js","../../common-errors/src/validation/standard_schema/extractMessageFromStandardSchema.ts","../../common-errors/src/validation/err_validation.ts","../../nice-action/src/ActionDefinition/Schema/ActionSchema.ts","../../nice-action/src/diagnostics/callSite.ts","../../../node_modules/std-env/dist/index.mjs","../../nice-action/src/utils/getAssumedRuntimeEnvironment.ts","../../nice-action/src/utils/isActionPayload_Progress_JsonObject.ts","../../nice-action/src/utils/isActionPayload_Request_JsonObject.ts","../../nice-action/src/utils/isActionPayload_Any_JsonObject.ts","../../nice-action/src/ActionRuntime/HandlerCallStack.ts","../../nice-action/src/ActionRuntime/Handler/PeerLink/Connector/err_nice_external_client.ts","../../nice-action/src/ActionRuntime/Transport/err_nice_transport.ts","../../nice-action/src/ActionRuntime/Transport/ConnectionTransportManager.ts","../../nice-action/src/ActionRuntime/ActionDomainManager.ts","../../nice-action/src/ActionRuntime/Routing/ActionRouter.ts","../../nice-action/src/ActionRuntime/Handler/ActionHandler.ts","../../nice-action/src/ActionRuntime/Handler/PeerLink/PeerLink.ts","../../nice-action/src/ActionRuntime/Handler/PeerLink/Connector/ReliableOutbox.ts","../../nice-action/src/ActionRuntime/Handler/PeerLink/Connector/ChannelConnector.ts","../../nice-action/src/ActionRuntime/ActionRuntime.ts","../../nice-action/src/ActionRuntime/Handler/Local/ActionLocalHandler.ts","../../nice-action/src/utils/isAction_Context_JsonObject.ts","../../nice-action/src/utils/isAction_Core_JsonObject.ts","../../nice-action/src/utils/isAction_Any_JsonObject.ts","../../nice-action/src/utils/assertIsActionJson.ts","../../nice-action/src/utils/isAction_Any_Instance.ts","../../nice-action/src/ActionDefinition/Domain/ActionDomainBase.ts","../../nice-action/src/ActionRuntime/ActionRuntimeManager.ts","../../nice-action/src/ActionDefinition/Domain/ActionRootDomain.ts","../../nice-action/src/ActionDefinition/Domain/ActionDomain.ts","../../nice-action/src/ActionDefinition/Domain/helpers/createRootActionDomain.ts","../../nice-action/src/utils/decodeActionFrame.ts","../../nice-action/src/ActionRuntime/Channel/serveLogger.ts","../../nice-action/src/ActionRuntime/Handler/PeerLink/Acceptor/ChannelAcceptor.ts","../../nice-action/src/ActionRuntime/Handler/PeerLink/Acceptor/createSecureChannelAcceptor.ts","../../nice-action/src/ActionRuntime/Transport/Carrier/Carrier.types.ts","../../nice-action/src/ActionRuntime/Transport/codec/actionWireCodec.ts","../../nice-action/src/ActionRuntime/Transport/codec/createBinaryWireSessionFactory.ts","../../nice-action/src/ActionRuntime/Transport/Transport.ts","../../nice-action/src/ActionRuntime/Transport/SecureSession/establishExchangeSession.ts","../../nice-action/src/ActionRuntime/Transport/TransportConnection.ts","../../nice-action/src/ActionRuntime/Transport/Exchange/ExchangeConnection.ts","../../nice-action/src/ActionRuntime/Transport/Exchange/ExchangeTransport.ts","../../nice-action/src/ActionRuntime/Transport/helpers/createUnsetTransportResolvers.ts","../../nice-action/src/ActionRuntime/Transport/SecureSession/establishLinkSession.ts","../../nice-action/src/ActionRuntime/Transport/Link/LinkConnection.ts","../../nice-action/src/ActionRuntime/Transport/Link/LinkTransport.ts","../../nice-action/src/ActionRuntime/Transport/createTransport.ts","../../nice-action/src/ActionRuntime/Channel/ActionChannel.ts","../../nice-action/src/ActionRuntime/Transport/SecureSession/exchangeAcceptor.ts","../../nice-action/src/ActionRuntime/Handler/PeerLink/Acceptor/createActionFetchHandler.ts","../../nice-action/src/ActionRuntime/Handler/PeerLink/Acceptor/Hibernation/ConnectionStateStore.ts","../../nice-action/src/ActionRuntime/Handler/PeerLink/Acceptor/Hibernation/createHibernatableWsServerAdapter.ts","../../nice-action/src/ActionRuntime/Transport/Carrier/AcceptorCarrier.types.ts","../../nice-action/src/ActionRuntime/Channel/serveChannel.ts","../../nice-action/src/ActionRuntime/Transport/Carrier/duplex/ws/err_nice_transport_ws.ts","../../nice-action/src/ActionRuntime/Transport/Carrier/duplex/ws/wsCarrier.ts","../../nice-action/src/ActionRuntime/Transport/Carrier/exchange/http/httpAcceptorCarrier.ts","../../../node_modules/fast-equals/dist/es/index.mjs","../../../node_modules/immer/dist/immer.mjs","../../nice-state/src/core/Store.ts","../../nice-realm/src/RealmDefinition/errors/err_realm.ts","../../nice-realm/src/RealmDefinition/Schema/validateValue.ts","../../nice-realm/src/RealmWire/keyDict.ts","../../nice-realm/src/RealmWire/realmFrame.types.ts","../../nice-realm/src/RealmWire/realmFrameCodec.ts","../../nice-realm/src/RealmWire/unsafeKey.ts","../../nice-realm/src/RealmWire/wirePatch.ts","../../nice-realm/src/RealmClient/assertRealmSecurity.ts","../../nice-realm/src/RealmClient/diffProjected.ts","../../nice-realm/src/RealmDefinition/Rules/evalRules.ts","../../nice-realm/src/RealmServer/expandWrite.ts","../../nice-realm/src/RealmClient/predict.ts","../../nice-realm/src/RealmClient/structuralParents.ts","../../nice-realm/src/RealmClient/writeHandle.ts","../../nice-realm/src/RealmClient/RealmClient.ts","../../nice-realm/src/RealmClient/RealmReplica.ts","../../nice-realm/src/RealmClient/realmMuxClient.ts","../../nice-realm/src/RealmDefinition/Intents/intents.types.ts","../../nice-realm/src/RealmDefinition/Rules/ruleBuilder.ts","../../nice-realm/src/RealmDefinition/Rules/rulePattern.ts","../../nice-realm/src/RealmDefinition/Rules/ruleSchemaLint.ts","../../nice-realm/src/RealmDefinition/Rules/ruleTrie.ts","../../nice-realm/src/RealmDefinition/Schema/schemaHash.ts","../../nice-realm/src/RealmDefinition/Schema/tokenMap.ts","../../nice-realm/src/RealmDefinition/defineRealm.ts","../../nice-realm/src/RealmDefinition/Schema/t.ts","../../nice-realm/src/RealmDefinition/Schema/boundedState.ts","../../nice-realm/src/RealmServer/viewSlice.ts","../../nice-realm/src/RealmServer/RealmServerEngine.ts","../../nice-realm/src/RealmServer/realmAcceptorProtocol.ts","../src/daemon/daemonProcesses.ts","../src/daemon/dataDir.ts","../src/daemon/runtime.ts","../src/protocol/statusRealm.ts","../src/daemon/lockfile.ts","../src/daemon/spawnDaemon.ts","../src/protocol/auth.ts","../src/protocol/ports.ts","../src/protocol/control.ts","../src/protocol/waitForStatusRealm.ts","../src/cli/daemonClient.ts","../src/cli/commands/control.ts","../src/daemon/envOverrides.ts","../src/ports/definitionMatch.ts","../src/ports/listeners.ts","../src/cli/envJudge.ts","../src/cli/commands/ports.ts","../src/cli/commands/doctor.ts","../src/cli/commands/env.ts","../src/cli/commands/inspect.ts","../src/protocol/logs.ts","../src/cli/commands/logs.ts","../src/daemon/lastStarts.ts","../src/daemon/taskDurations.ts","../src/run/scheduler.ts","../src/cli/commands/run.ts","../src/cli/out.ts","../src/cli/commands/status.ts","../src/cli/openBrowser.ts","../src/cli/commands/ui.ts","../src/daemon/savedFilters.ts","../src/cli.ts"],"sourcesContent":["// CLI argv parsing: global flags + positionals + a raw flag bucket each command validates for\n// itself (an unknown flag is that command's usage error, never silently ignored).\n\nexport interface ICliArgs {\n  command: string | null;\n  /** Positional terms after the command (selection ids/suites/@pins/tag=val). */\n  positionals: string[];\n  configPath?: string;\n  json: boolean;\n  noColor: boolean;\n  timeoutMs?: number;\n  help: boolean;\n  /** Non-global flags (`--watch`, `--parallel N`, `-f`, …), validated per command. */\n  flags: ReadonlyMap<string, string | true>;\n  /** Values of flags that may appear more than once (`--set A=1 --set B=2`). */\n  repeated: ReadonlyMap<string, string[]>;\n  /** Everything after a bare `--`, verbatim — arguments for a foreground `run` to append. */\n  passthrough: string[];\n}\n\nconst GLOBAL_VALUE_FLAGS = new Set([\"--config\", \"--timeout\"]);\n\n/**\n * Flags that ACCUMULATE instead of overwriting. `env --set A=1 --set B=2` has to mean both, and a\n * plain Map keeps only the last. The name still lands in `flags` so `unknownFlags` keeps rejecting\n * it on every command that does not accept it.\n */\nconst REPEATABLE_VALUE_FLAGS = new Set([\"--set\", \"--unset\", \"--with\"]);\n\n/**\n * Per-command flags that take a VALUE. Everything else is boolean — and that distinction is\n * load-bearing: a greedy \"consume the next token\" parse turned `up --no-wait demo` into\n * `--no-wait=\"demo\"` with NO positionals, which fell through to `defaultSelection` and started\n * the wrong processes with no error at all (C4). `--flag=value` is always explicit.\n */\nconst COMMAND_VALUE_FLAGS = new Set([\"--parallel\", \"--kill\"]);\n\nexport function parseCliArgs(argv: readonly string[]): ICliArgs | { error: string } {\n  const flags = new Map<string, string | true>();\n  const repeated = new Map<string, string[]>();\n  const positionals: string[] = [];\n  const passthrough: string[] = [];\n  let command: string | null = null;\n  let json = false;\n  let noColor = false;\n  let help = false;\n  let configPath: string | undefined;\n  let timeoutMs: number | undefined;\n\n  for (let i = 0; i < argv.length; i += 1) {\n    const token = argv[i] as string;\n    if (token === \"--\") {\n      passthrough.push(...argv.slice(i + 1));\n      break;\n    }\n    // Split `--flag=value` once, so globals and command flags agree on what a value is.\n    const eq = token.startsWith(\"--\") ? token.indexOf(\"=\") : -1;\n    const arg = eq > 2 ? token.slice(0, eq) : token;\n    const inlineValue = eq > 2 ? token.slice(eq + 1) : null;\n\n    if (GLOBAL_VALUE_FLAGS.has(arg)) {\n      const value = inlineValue ?? argv[i + 1];\n      if (value == null || value.startsWith(\"--\")) return { error: `flag ${arg} needs a value` };\n      if (arg === \"--config\") configPath = value;\n      else {\n        const parsed = Number(value);\n        if (!Number.isFinite(parsed) || parsed <= 0)\n          return { error: `--timeout needs a positive ms number` };\n        timeoutMs = parsed;\n      }\n      if (inlineValue == null) i += 1;\n      continue;\n    }\n    if (arg === \"--json\" || arg === \"--no-color\" || arg === \"--help\" || arg === \"-h\") {\n      if (inlineValue != null) return { error: `flag ${arg} takes no value` };\n      if (arg === \"--json\") json = true;\n      else if (arg === \"--no-color\") noColor = true;\n      else help = true;\n      continue;\n    }\n    if (REPEATABLE_VALUE_FLAGS.has(arg)) {\n      const value = inlineValue ?? argv[i + 1];\n      if (value == null || value.startsWith(\"--\")) return { error: `flag ${arg} needs a value` };\n      const values = repeated.get(arg) ?? [];\n      values.push(value);\n      repeated.set(arg, values);\n      flags.set(arg, value); // presence only — `unknownFlags` is what reads this\n      if (inlineValue == null) i += 1;\n      continue;\n    }\n    if (arg.startsWith(\"--\")) {\n      if (inlineValue != null) {\n        flags.set(arg, inlineValue);\n        continue;\n      }\n      if (COMMAND_VALUE_FLAGS.has(arg)) {\n        const next = argv[i + 1];\n        if (next != null && !next.startsWith(\"-\")) {\n          flags.set(arg, next);\n          i += 1;\n          continue;\n        }\n        // Missing value: recorded as `true` so the command's own parse reports the usage error.\n      }\n      flags.set(arg, true);\n      continue;\n    }\n    if (arg.startsWith(\"-\") && arg.length === 2) {\n      flags.set(arg, true);\n      continue;\n    }\n    if (command == null) command = arg;\n    else positionals.push(arg);\n  }\n  const args: ICliArgs = {\n    command,\n    positionals,\n    json,\n    noColor,\n    help,\n    flags,\n    repeated,\n    passthrough,\n  };\n  if (configPath != null) args.configPath = configPath;\n  if (timeoutMs != null) args.timeoutMs = timeoutMs;\n  return args;\n}\n\n/** Every command calls this with its known flags; leftovers are usage errors. */\nexport function unknownFlags(\n  flags: ReadonlyMap<string, string | true>,\n  known: readonly string[],\n): string | null {\n  for (const flag of flags.keys()) {\n    if (!known.includes(flag)) return `unknown flag ${flag}`;\n  }\n  return null;\n}\n\nexport function numericFlag(\n  flags: ReadonlyMap<string, string | true>,\n  name: string,\n): number | null | { error: string } {\n  const raw = flags.get(name);\n  if (raw == null) return null;\n  if (raw === true) return { error: `flag ${name} needs a value` };\n  const parsed = Number(raw);\n  if (!Number.isInteger(parsed) || parsed < 1) return { error: `${name} needs a positive integer` };\n  return parsed;\n}\n","// The daemon instance record (D6): how a CLI/UI discovers THE daemon for a config. Written\n// atomically after a successful bind; validated with a bounded shape + loopback target; reuse\n// requires pid+startStamp liveness AND an authed /health ping — never a pid match alone.\n\nimport { mkdir, readFile, rename, unlink, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { matchProcessStartStamp } from \"@nice-code/process\";\n\n/**\n * Bump this whenever the wire changes shape: a control action added or altered, or a field added\n * to the status realm's state. Both are BREAKING against a daemon already running — a realm whose\n * schema gained a required field never finishes attaching, so a stale daemon does not fail, it\n * HANGS, and the mismatch this constant exists to detect is never reported. That is what happened\n * on v1 → v2 (`envDrift` + `detail.envVars` + `setEnv`), and it is why this is not cosmetic.\n *\n * v2 → v3: the realm state gained `sawOutputAt`/`lastTask` in 0.80.0 WITHOUT this bump — every\n * 0.80.0 CLI greeted its still-running 0.79.0 daemon with a raw realm hash mismatch instead of\n * the named refusal. The bump is late; `realmSchemaHash` in the record is the backstop that\n * catches the next forgotten one (the CLI compares it before dialing).\n *\n * v3 → v4: the realm state gained `configName` (the project name for the browser tab title).\n */\n// v4 → v5: explicit port inspection and listener termination control action.\n// v5 → v6: `groups` left the realm; multi-value tags, `optIn`, suites, runs and saved filters joined\n// it, with the `runSuite`/`saveFilter`/`removeFilter` control actions.\n// v6 → v7: `startError` and `detail.url` joined the realm; `start`/`restart` take `replaceSame`;\n// port listeners carry the stray verdict (`stray`, `strayRoot`).\n// v7 → v8: `lastStartedAt`, `flags`, `estimatedMs` and `detail.flags` joined the realm;\n// `start`/`restart` take `flags`; the `noteRuns` control action.\nexport const COMMANDER_PROTOCOL_VERSION = 8;\n\nexport interface ICommanderInstanceRecord {\n  service: \"nice-commander\";\n  instanceId: string;\n  /** Bumped per daemon incarnation — the (generation, ingestSeq) log-timeline major key. */\n  generation: number;\n  pid: number;\n  startStamp: { stamp: string; precision: \"ticks\" | \"seconds\" } | null;\n  port: number;\n  token: string;\n  configKey: string;\n  configRevisionHash: string;\n  configPath: string;\n  protocolVersion: number;\n  packageVersion: string;\n  /** The daemon's `commanderStatusRealm.schemaHash` — attach is refused when it differs. */\n  realmSchemaHash: string;\n  /**\n   * The daemon serves the client bundle it was built with (`pinClientBundle`), so its page works\n   * whatever build is installed now — a CLI from another build may still OPEN it. Absent on\n   * daemons from before the pin, whose page breaks after an upgrade.\n   */\n  servesOwnClient?: boolean;\n}\n\n/** Generous ceiling for every string field: real values are ids, hashes and one path. */\nconst MAX_FIELD_CHARS = 4_096;\n\nfunction boundedString(value: unknown): value is string {\n  return typeof value === \"string\" && value.length <= MAX_FIELD_CHARS;\n}\n\nfunction boundedInt(value: unknown, min: number, max: number): value is number {\n  return typeof value === \"number\" && Number.isInteger(value) && value >= min && value <= max;\n}\n\n/** `startStamp` is compared against a freshly read one — a wrong shape must never compare equal. */\nfunction validStartStamp(value: unknown): value is ICommanderInstanceRecord[\"startStamp\"] {\n  if (value == null) return true; // unreadable at boot is a documented state, not corruption\n  if (typeof value !== \"object\" || Array.isArray(value)) return false;\n  const stamp = value as Record<string, unknown>;\n  return (\n    boundedString(stamp[\"stamp\"]) &&\n    (stamp[\"precision\"] === \"ticks\" || stamp[\"precision\"] === \"seconds\")\n  );\n}\n\n/**\n * Bounded shape check. The record is read from a file this user's other processes write, so it is\n * trusted-ish — but a truncated write, a stale schema, or a hand-edit must degrade to \"no daemon\"\n * rather than feed a malformed value into the reuse path. Strings are length-capped so a corrupt\n * record can't become a large allocation on every `readInstanceRecord`.\n */\nexport function isInstanceRecord(value: unknown): value is ICommanderInstanceRecord {\n  if (value == null || typeof value !== \"object\" || Array.isArray(value)) return false;\n  const record = value as Partial<ICommanderInstanceRecord>;\n  return (\n    record.service === \"nice-commander\" &&\n    boundedString(record.instanceId) &&\n    boundedInt(record.generation, 0, Number.MAX_SAFE_INTEGER) &&\n    boundedInt(record.pid, 1, Number.MAX_SAFE_INTEGER) &&\n    boundedInt(record.port, 1, 65_535) &&\n    boundedString(record.token) &&\n    boundedString(record.configKey) &&\n    boundedString(record.configRevisionHash) &&\n    boundedString(record.configPath) &&\n    boundedString(record.packageVersion) &&\n    boundedString(record.realmSchemaHash) &&\n    validStartStamp(record.startStamp) &&\n    (record.servesOwnClient == null || typeof record.servesOwnClient === \"boolean\") &&\n    record.protocolVersion === COMMANDER_PROTOCOL_VERSION\n  );\n}\n\nexport async function writeInstanceRecord(\n  path: string,\n  record: ICommanderInstanceRecord,\n): Promise<void> {\n  await mkdir(dirname(path), { recursive: true, mode: 0o700 });\n  const temp = `${path}.${process.pid}.tmp`;\n  await writeFile(temp, `${JSON.stringify(record, null, 2)}\\n`, { encoding: \"utf8\", mode: 0o600 });\n  await rename(temp, path);\n}\n\nexport async function readInstanceRecord(path: string): Promise<ICommanderInstanceRecord | null> {\n  try {\n    const parsed: unknown = JSON.parse(await readFile(path, \"utf8\"));\n    return isInstanceRecord(parsed) ? parsed : null;\n  } catch {\n    return null; // missing or corrupt — a corrupt record is treated as \"no daemon\"\n  }\n}\n\nexport async function removeInstanceRecord(path: string): Promise<void> {\n  await unlink(path).catch(() => {});\n}\n\nexport interface ISkewedInstanceRecord {\n  pid: number;\n  port: number;\n  protocolVersion: number;\n  packageVersion: string;\n  startStamp: { stamp: string; precision: \"ticks\" | \"seconds\" } | null;\n  /** Which check the record failed — what the message should name. */\n  skew: \"protocol\" | \"realm-schema\";\n  /** See `ICommanderInstanceRecord.servesOwnClient` — true means its page can be opened as-is. */\n  servesOwnClient: boolean;\n}\n\n/**\n * A record written by a daemon this build cannot talk to (edge 18): a DIFFERENT protocol\n * version, or — the 0.80.0 lesson — the SAME protocol version but a different status-realm\n * schema hash (a schema change whose bump was forgotten; the realm layer would refuse the\n * attach anyway, but with a raw hash mismatch instead of a name and a remedy).\n *\n * `readInstanceRecord` rejects both, which is right — but \"invalid\" and \"absent\" then look\n * identical, so a plain `up` would boot a second daemon straight into the first one's port and\n * report `EADDRINUSE`. That is a true statement about the wrong problem. Reading it separately\n * is what lets the CLI say which daemon is in the way, and how to replace it. Nothing here\n * authorizes a kill by itself: `signalDaemonShutdown` still verifies identity first.\n */\nexport async function readSkewedInstanceRecord(\n  path: string,\n  expectedRealmSchemaHash: string,\n): Promise<ISkewedInstanceRecord | null> {\n  let parsed: unknown;\n  try {\n    parsed = JSON.parse(await readFile(path, \"utf8\"));\n  } catch {\n    return null;\n  }\n  if (parsed == null || typeof parsed !== \"object\" || Array.isArray(parsed)) return null;\n  const record = parsed as Record<string, unknown>;\n  if (record[\"service\"] !== \"nice-commander\") return null;\n  if (!boundedInt(record[\"protocolVersion\"], 0, Number.MAX_SAFE_INTEGER)) return null;\n  if (!boundedInt(record[\"pid\"], 1, Number.MAX_SAFE_INTEGER)) return null;\n  if (!boundedInt(record[\"port\"], 1, 65_535)) return null;\n  const sameProtocol = record[\"protocolVersion\"] === COMMANDER_PROTOCOL_VERSION;\n  const sameRealm =\n    boundedString(record[\"realmSchemaHash\"]) &&\n    record[\"realmSchemaHash\"] === expectedRealmSchemaHash;\n  if (sameProtocol && sameRealm) return null; // not skewed — this is OUR daemon\n  return {\n    pid: record[\"pid\"],\n    port: record[\"port\"],\n    protocolVersion: record[\"protocolVersion\"],\n    packageVersion: boundedString(record[\"packageVersion\"]) ? record[\"packageVersion\"] : \"unknown\",\n    // `?? null`: the predicate admits an absent field (a legacy record), the type does not.\n    startStamp: validStartStamp(record[\"startStamp\"]) ? (record[\"startStamp\"] ?? null) : null,\n    skew: sameProtocol ? \"realm-schema\" : \"protocol\",\n    servesOwnClient: record[\"servesOwnClient\"] === true,\n  };\n}\n\n/** Liveness only — enough to say \"something is there\", never enough to authorize a kill (C1). */\nexport function pidAlive(pid: number): boolean {\n  try {\n    process.kill(pid, 0);\n    return true;\n  } catch (error) {\n    return (error as NodeJS.ErrnoException).code === \"EPERM\";\n  }\n}\n\n/**\n * Is this record's daemon still the process it claims to be? pid alive AND startStamp equal —\n * an unreadable stamp answers false (a reused pid must never be trusted).\n */\nexport async function recordDaemonAlive(record: ICommanderInstanceRecord): Promise<boolean> {\n  try {\n    process.kill(record.pid, 0);\n  } catch (error) {\n    if ((error as NodeJS.ErrnoException).code !== \"EPERM\") return false;\n  }\n  if (record.startStamp == null) return true; // stamp unreadable at boot: pid liveness only\n  return (await matchProcessStartStamp(record.pid, record.startStamp.stamp)) === \"match\";\n}\n\nexport interface ICommanderPing {\n  ok: true;\n  configKey: string;\n  generation: number;\n  uptimeMs: number;\n}\n\nexport type TSignalShutdownOutcome =\n  /** SIGTERM delivered and the daemon exited within the wait. */\n  | \"exited\"\n  /** SIGTERM delivered; still alive at the deadline (a big ladder, or wedged — signal again to escalate). */\n  | \"still-stopping\"\n  /** Identity could not be verified (no/mismatched start stamp) — never killed blind. */\n  | \"identity-unverified\"\n  | \"not-running\";\n\nexport interface ISignalShutdownResult {\n  outcome: TSignalShutdownOutcome;\n  pid: number | null;\n}\n\n/**\n * Protocol-independent shutdown: verify the record's pid is still the daemon it claims to be\n * (pid + startStamp — the ledger's own identity rule), then SIGTERM it. The daemon's signal\n * handler runs the exact shutdown ladder `shutdown` would have asked for over the wire, so this\n * is the remedy of last resort for a daemon a CLI cannot TALK to — a build from before a\n * protocol or realm-schema change — without asking anyone to hunt pids by hand. A second call\n * while it is still stopping escalates, mirroring the daemon's own two-signal contract.\n *\n * ⚠ `identity-unverified` is a refusal, not an error to work around: a recorded stamp that no\n * longer matches means pid reuse, and a record with no stamp cannot prove the pid is ours.\n */\nexport async function signalDaemonShutdown(\n  target: { pid: number; startStamp: ICommanderInstanceRecord[\"startStamp\"] },\n  waitMs = 15_000,\n): Promise<ISignalShutdownResult> {\n  const { pid, startStamp } = target;\n  if (!pidAlive(pid)) return { outcome: \"not-running\", pid };\n  if (startStamp == null) return { outcome: \"identity-unverified\", pid };\n  if ((await matchProcessStartStamp(pid, startStamp.stamp)) !== \"match\") {\n    return { outcome: \"identity-unverified\", pid };\n  }\n  try {\n    process.kill(pid, \"SIGTERM\");\n  } catch {\n    return { outcome: \"not-running\", pid }; // died between the check and the signal\n  }\n  const deadline = Date.now() + waitMs;\n  while (Date.now() < deadline) {\n    if (!pidAlive(pid)) return { outcome: \"exited\", pid };\n    await new Promise((resolve) => setTimeout(resolve, 150));\n  }\n  return { outcome: pidAlive(pid) ? \"still-stopping\" : \"exited\", pid };\n}\n\n/** Authed liveness probe — the final word on \"reuse this daemon\" (bounded). */\nexport async function pingDaemon(\n  record: ICommanderInstanceRecord,\n  timeoutMs = 2_000,\n): Promise<ICommanderPing | null> {\n  try {\n    const response = await fetch(`http://127.0.0.1:${record.port}/health`, {\n      headers: { authorization: `Bearer ${record.token}` },\n      signal: AbortSignal.timeout(timeoutMs),\n    });\n    if (!response.ok) return null;\n    const body = (await response.json()) as Partial<ICommanderPing>;\n    return body.ok === true && body.configKey === record.configKey\n      ? (body as ICommanderPing)\n      : null;\n  } catch {\n    return null;\n  }\n}\n","// The package's own version, for skew diagnostics (instance record, CLI error messages).\n\nimport { readFile } from \"node:fs/promises\";\n\nlet cached: string | null = null;\n\n/**\n * Resolved relative to the BUILT module, so the candidate list must cover every layout this\n * code ships in: `build/main-*.mjs` in the installed package (`../package.json` — the miss that\n * had every daemon reporting 0.0.0), and `src/daemon/*.ts` when run from sources (`../../`).\n */\nexport async function commanderPackageVersion(): Promise<string> {\n  if (cached != null) return cached;\n  for (const candidate of [\n    new URL(\"../package.json\", import.meta.url),\n    new URL(\"../../package.json\", import.meta.url),\n    new URL(\"../../../package.json\", import.meta.url),\n  ]) {\n    try {\n      const parsed = JSON.parse(await readFile(candidate, \"utf8\")) as {\n        name?: string;\n        version?: string;\n      };\n      // The name guard keeps a monorepo-root or unrelated package.json from answering.\n      if (typeof parsed.version === \"string\" && parsed.name === \"@nice-code/commander\") {\n        cached = parsed.version;\n        return cached;\n      }\n    } catch {\n      // try the next candidate\n    }\n  }\n  cached = \"0.0.0\";\n  return cached;\n}\n","// A command that starts something acts on the config the CLI just read. The daemon watches that\n// file too, but its watcher has a debounce, and cannot see what a config reads without importing\n// (a file it opens, a value it computes) — so the command asks for the reload itself.\n\nimport type { IResolvedCommanderConfig } from \"../config/types\";\nimport { commanderPackageVersion } from \"../daemon/packageVersion\";\nimport type { IReloadResult } from \"../protocol/control\";\nimport type { IOut } from \"./out\";\n\n/** The part of the daemon client a sync needs. */\nexport interface IConfigSyncClient {\n  readonly record: { packageVersion: string };\n  state(): { configRevisionHash: string };\n  /** Null when the daemon's answer is not one this build recognises. */\n  reloadConfig(): Promise<IReloadResult | null>;\n}\n\n/**\n * Bring the daemon onto `config`'s revision before acting on it. Never fails the command: when\n * the daemon ends up on another revision the start still happens, on the daemon's reading, and\n * the difference is said on stderr.\n */\nexport async function syncDaemonConfig(\n  config: Pick<IResolvedCommanderConfig, \"configRevisionHash\">,\n  client: IConfigSyncClient,\n  out: IOut,\n): Promise<void> {\n  if (client.state().configRevisionHash === config.configRevisionHash) return;\n  const result = await client.reloadConfig();\n  if (result?.configRevisionHash === config.configRevisionHash) return;\n  const note = (text: string) => out.warn(`${out.paint(\"yellow\", \"⚠\")} ${text}`);\n  if (result == null) {\n    note(\n      \"the daemon could not be asked to reload the config — what starts may be on the revision \" +\n        \"it loaded earlier (`nice-commander shutdown`, then `up`, starts one on this build)\",\n    );\n    return;\n  }\n  if (!result.applied) {\n    note(\n      \"the daemon kept its last good config — the one on disk did not load there:\\n\" +\n        result.errors.map((line) => `    - ${line}`).join(\"\\n\"),\n    );\n    return;\n  }\n  // Reloaded, and still another revision: the same file resolves differently over there.\n  const build = await commanderPackageVersion();\n  const why =\n    client.record.packageVersion === build\n      ? \"a value the config computes from the environment, or a plain .mjs/.js helper, stays \" +\n        \"as the daemon first read it\"\n      : `it runs build ${client.record.packageVersion}, this CLI is build ${build}`;\n  note(\n    `the daemon reads this config differently from this shell (${why}) — what starts is the ` +\n      \"daemon's reading. `nice-commander shutdown`, then `up`, rebuilds it from here.\",\n  );\n}\n","// Flags: the declared switches a start may turn on, and how their arguments reach a spawn. Pure —\n// shared by the validator, the daemon's starts and the foreground `run`.\n\nimport type { TNiceProcessRun } from \"@nice-code/process\";\nimport type { IResolvedCommanderFlag } from \"./types\";\n\n/**\n * An argument a shell-string `run` can take appended unquoted in sh, cmd and PowerShell alike.\n * Anything else (spaces, quotes, `$`, `%`, `,`, `;`…) would need per-shell quoting.\n */\nexport const SHELL_PLAIN_ARG = /^[A-Za-z0-9_+=:./-]+$/;\n\n/** `run` with `args` appended — after the argv, or after the shell string. */\nexport function runWithArgs(run: TNiceProcessRun, args: readonly string[]): TNiceProcessRun {\n  if (args.length === 0) return run;\n  return typeof run === \"string\" ? `${run} ${args.join(\" \")}` : [...run, ...args];\n}\n\nexport interface IFlagSelection {\n  /** The flags that are on, in declaration order — the canonical form of a request. */\n  flags: string[];\n  args: string[];\n}\n\n/** Requested names against a definition's declared flags; an undeclared name is an error. */\nexport function resolveFlags(\n  definition: { id: string; flags: readonly IResolvedCommanderFlag[] },\n  names: readonly string[],\n): IFlagSelection | { error: string } {\n  const unknown = names.filter((name) => !definition.flags.some((flag) => flag.name === name));\n  if (unknown.length > 0) {\n    const declared = definition.flags.map((flag) => flag.name);\n    return {\n      error:\n        `\"${definition.id}\" declares no flag ${unknown.map((name) => `\"${name}\"`).join(\", \")} — ` +\n        (declared.length > 0 ? `its flags: ${declared.join(\", \")}` : \"it declares none\"),\n    };\n  }\n  const on = definition.flags.filter((flag) => names.includes(flag.name));\n  return { flags: on.map((flag) => flag.name), args: on.flatMap((flag) => flag.args) };\n}\n","// Tag matching, shared by config resolution, the CLI selector and the web UI so the three can\n// never disagree about what `key=value` selects. Pure — no node imports (the client bundles it).\n\nexport type TResolvedTags = Record<string, readonly string[]>;\n\n/** `key=value` → `[key, value]`, or null when the term is not tag-shaped. */\nexport function parseTagTerm(term: string): [string, string] | null {\n  const eq = term.indexOf(\"=\");\n  return eq > 0 ? [term.slice(0, eq), term.slice(eq + 1)] : null;\n}\n\nexport function hasTag(tags: TResolvedTags, key: string, value: string): boolean {\n  return tags[key]?.includes(value) === true;\n}\n\n/** Every entry must match (AND). */\nexport function matchesTagQuery(tags: TResolvedTags, query: Record<string, string>): boolean {\n  return Object.entries(query).every(([key, value]) => hasTag(tags, key, value));\n}\n\n/** Every `key=value` a process carries, in key order. */\nexport function tagTermsOf(tags: TResolvedTags): string[] {\n  return Object.entries(tags).flatMap(([key, values]) => values.map((value) => `${key}=${value}`));\n}\n","// Tag groups: the processes that match the SAME exact subset of a filter's tags. Derived, never\n// declared. Pure and shared — the UI buckets with it, and the CLI resolves a pin with it.\n\nimport { parseTagTerm, type TResolvedTags } from \"./tags\";\n\nexport type TTagMode = \"all\" | \"any\";\n\nexport interface ITagGroup<T> {\n  /** The filter terms every member matches — and no other filter term. In filter order. */\n  signature: string[];\n  members: T[];\n}\n\n/** Which of `terms` these tags carry, in `terms` order. */\nexport function tagSignature(tags: TResolvedTags, terms: readonly string[]): string[] {\n  return terms.filter((term) => {\n    const parsed = parseTagTerm(term);\n    return parsed != null && tags[parsed[0]]?.includes(parsed[1]) === true;\n  });\n}\n\n/**\n * Bucket by signature: most matched terms first, then by where the signature's terms sit in the\n * filter — never by anything live, so buckets hold still while processes change state. In `any`\n * mode the first bucket is the `all` result whenever anything matches every term.\n */\nexport function tagGroupsFor<T extends { tags: TResolvedTags }>(\n  items: readonly T[],\n  terms: readonly string[],\n  mode: TTagMode,\n): ITagGroup<T>[] {\n  const buckets = new Map<string, ITagGroup<T>>();\n  for (const item of items) {\n    const signature = tagSignature(item.tags, terms);\n    if (signature.length === 0 || (mode === \"all\" && signature.length < terms.length)) continue;\n    const key = signature.join(\",\");\n    const bucket = buckets.get(key) ?? { signature, members: [] };\n    bucket.members.push(item);\n    buckets.set(key, bucket);\n  }\n  const rank = (group: ITagGroup<T>): number[] =>\n    group.signature.map((term) => terms.indexOf(term));\n  return [...buckets.values()].sort((a, b) => {\n    if (a.signature.length !== b.signature.length) return b.signature.length - a.signature.length;\n    const [ra, rb] = [rank(a), rank(b)];\n    for (let i = 0; i < ra.length; i += 1) {\n      if (ra[i] !== rb[i]) return (ra[i] ?? 0) - (rb[i] ?? 0);\n    }\n    return 0;\n  });\n}\n\nexport function sameSignature(a: readonly string[], b: readonly string[]): boolean {\n  return a.length === b.length && a.every((term) => b.includes(term));\n}\n","// A saved filter: a pin the operator named, or a recent run the daemon recorded. ⚠ The QUERY is\n// the identity, never an id list — members re-resolve against the live config, so a process that\n// gains the tag tomorrow joins the pin.\n\nimport { sameSignature, type TTagMode, tagGroupsFor } from \"../config/tagGroups\";\nimport { parseTagTerm, type TResolvedTags } from \"../config/tags\";\n\nexport interface ISavedFilter {\n  /** Derived from the canonical filter — saving the same filter twice is one entry. */\n  id: string;\n  /** Pins only; a recent run is labelled by its chips. */\n  name?: string;\n  mode: TTagMode;\n  /** Sorted. */\n  terms: string[];\n  /** The focused tag group's signature, when saved from a bucket heading. */\n  bucket?: string[];\n  pinned: boolean;\n  lastRunAt?: number;\n}\n\nexport const MAX_PINS = 24;\nexport const MAX_RECENTS = 8;\nexport const MAX_FILTER_TERMS = 16;\nexport const MAX_PIN_NAME_LENGTH = 48;\n\nexport type TSavedFilterQuery = Pick<ISavedFilter, \"mode\" | \"terms\" | \"bucket\">;\n\nexport function savedFilterId(query: TSavedFilterQuery): string {\n  const terms = [...query.terms].sort();\n  const bucket = query.bucket == null ? \"\" : `|${[...query.bucket].sort().join(\",\")}`;\n  return `${query.mode}:${terms.join(\",\")}${bucket}`;\n}\n\n/** The members a saved filter selects right now. `optIn` processes are never bulk members. */\nexport function savedFilterMembers<T extends { tags: TResolvedTags; optIn: boolean }>(\n  query: TSavedFilterQuery,\n  items: readonly T[],\n): T[] {\n  const groups = tagGroupsFor(\n    items.filter((item) => !item.optIn),\n    [...query.terms].sort(),\n    query.mode,\n  );\n  const bucket = query.bucket;\n  const chosen =\n    bucket == null ? groups : groups.filter((group) => sameSignature(group.signature, bucket));\n  return chosen.flatMap((group) => group.members);\n}\n\nfunction asTerms(value: unknown): string[] | null {\n  if (!Array.isArray(value) || value.length === 0 || value.length > MAX_FILTER_TERMS) return null;\n  const terms: string[] = [];\n  for (const entry of value) {\n    if (typeof entry !== \"string\" || entry.length > 512 || parseTagTerm(entry) == null) return null;\n    if (!terms.includes(entry)) terms.push(entry);\n  }\n  return terms.sort();\n}\n\n/** The one place an untrusted value (the wire, or the file) becomes a query. */\nexport function checkSavedFilterQuery(value: unknown): TSavedFilterQuery | string {\n  if (value == null || typeof value !== \"object\" || Array.isArray(value)) {\n    return \"expected an object\";\n  }\n  const record: Record<string, unknown> = { ...value };\n  const mode = record[\"mode\"];\n  if (mode !== \"all\" && mode !== \"any\") return 'mode: expected \"all\" | \"any\"';\n  const terms = asTerms(record[\"terms\"]);\n  if (terms == null) return `terms: expected 1–${MAX_FILTER_TERMS} tag=value strings`;\n  if (record[\"bucket\"] == null) return { mode, terms };\n  const bucket = asTerms(record[\"bucket\"]);\n  if (bucket == null || !bucket.every((term) => terms.includes(term))) {\n    return \"bucket: expected a subset of terms\";\n  }\n  return { mode, terms, bucket };\n}\n","// Selection resolution for CLI/UI actions. Terms: process ids, suite names, `@pin` names,\n// `tag=value` (AND across tag terms, OR with `any`), and the built-in `all`. Selector terms union;\n// tag terms filter the union. The result closes over transitive dependsOn and returns DAG order\n// (dependencies first, config order as tiebreak) — the order `up` spawns in.\n//\n// Pure — the web UI imports the ordering functions, so no node imports here.\n\nimport { type ISavedFilter, savedFilterMembers } from \"../protocol/savedFilters\";\nimport { hasTag, parseTagTerm } from \"./tags\";\nimport type { IResolvedCommanderConfig } from \"./types\";\n\n/** All the dependency walks need — satisfied by a resolved process and by a realm row alike. */\nexport interface IDependencyNode {\n  id: string;\n  dependsOn: readonly string[];\n}\n\nexport interface IResolvedSelection {\n  /** DAG-ordered unique ids — dependencies before dependents. */\n  ordered: string[];\n  /** Ids named directly by the terms (before dependency closure). */\n  direct: string[];\n  /** Ids pulled in only as transitive dependencies. */\n  autoIncluded: string[];\n}\n\nexport type TSelectionResult =\n  | { ok: true; selection: IResolvedSelection }\n  | { ok: false; errors: string[] };\n\n/** Topological order of the given id set over the dependsOn graph; config order breaks ties. */\nexport function orderByDependency(\n  processes: readonly IDependencyNode[],\n  ids: ReadonlySet<string>,\n): string[] {\n  const configOrder = new Map(processes.map((proc, index) => [proc.id, index]));\n  const inDegree = new Map<string, number>();\n  const dependents = new Map<string, string[]>();\n  for (const id of ids) {\n    inDegree.set(id, 0);\n    dependents.set(id, []);\n  }\n  for (const id of ids) {\n    const proc = processes.find((candidate) => candidate.id === id);\n    for (const dep of proc?.dependsOn ?? []) {\n      if (!ids.has(dep)) continue; // deps outside the set don't gate ordering\n      inDegree.set(id, (inDegree.get(id) ?? 0) + 1);\n      dependents.get(dep)?.push(id);\n    }\n  }\n  const ready = [...ids].filter((id) => inDegree.get(id) === 0);\n  ready.sort((a, b) => (configOrder.get(a) ?? 0) - (configOrder.get(b) ?? 0));\n  const ordered: string[] = [];\n  for (let head = 0; head < ready.length; head += 1) {\n    const id = ready[head];\n    ordered.push(id);\n    for (const dependent of dependents.get(id) ?? []) {\n      const degree = (inDegree.get(dependent) ?? 0) - 1;\n      inDegree.set(dependent, degree);\n      if (degree === 0) {\n        // Keep the queue sorted by config order without a full re-sort.\n        let at = head + 1;\n        while (\n          at < ready.length &&\n          (configOrder.get(ready[at]) ?? 0) < (configOrder.get(dependent) ?? 0)\n        ) {\n          at += 1;\n        }\n        ready.splice(at, 0, dependent);\n      }\n    }\n  }\n  // The graph is acyclic (validated at load); a shortfall here would mean a bug upstream.\n  return ordered.length === ids.size\n    ? ordered\n    : [...ordered, ...[...ids].filter((id) => !ordered.includes(id))];\n}\n\n/** Transitive dependsOn closure of `ids` (inclusive). */\nexport function withDependencies(\n  processes: readonly IDependencyNode[],\n  ids: Iterable<string>,\n): Set<string> {\n  const byId = new Map(processes.map((proc) => [proc.id, proc]));\n  const closed = new Set<string>();\n  const stack = [...ids];\n  while (stack.length > 0) {\n    const id = stack.pop() as string;\n    if (closed.has(id)) continue;\n    closed.add(id);\n    for (const dep of byId.get(id)?.dependsOn ?? []) stack.push(dep);\n  }\n  return closed;\n}\n\n/**\n * What stopping `direct` AND its dependencies may take down. A dependency is kept when a live\n * process outside the stop set still needs it — and keeping one keeps what IT needs, hence the\n * loop. Dependencies that simply are not running are not reported either way.\n */\nexport function stopSetWithDependencies(\n  processes: readonly IDependencyNode[],\n  direct: readonly string[],\n  isLive: (id: string) => boolean,\n): { stop: string[]; kept: string[] } {\n  const stop = withDependencies(processes, direct);\n  const kept: string[] = [];\n  for (let changed = true; changed; ) {\n    changed = false;\n    const needed = withDependencies(\n      processes,\n      processes.filter((proc) => !stop.has(proc.id) && isLive(proc.id)).map((proc) => proc.id),\n    );\n    for (const id of [...stop]) {\n      if (direct.includes(id) || !needed.has(id)) continue;\n      stop.delete(id);\n      if (isLive(id)) kept.push(id);\n      changed = true;\n    }\n  }\n  return { stop: orderByDependency(processes, stop), kept };\n}\n\nexport interface IResolveSelectionOptions {\n  /**\n   * Ids the daemon still holds that the config no longer declares. A process removed while\n   * running stays addressable by exact id and is included by `all`, so an edit can never strand\n   * a live process that only a full `shutdown` could reach (M1).\n   */\n  extraIds?: readonly string[];\n  /** OR across `tag=value` terms instead of AND. Opt-in: a selector must never widen quietly. */\n  any?: boolean;\n  /**\n   * `start` (the default) keeps `optIn` processes out of `all` and tag selections. `address` is\n   * for stop/logs — what is running must stay reachable however it was started.\n   */\n  purpose?: \"start\" | \"address\";\n  /** Saved filters, for `@name` terms. */\n  pins?: readonly ISavedFilter[];\n}\n\n/**\n * Resolve CLI/UI selection terms against the model. An empty `terms` is the caller's problem\n * (bare `up` consults `defaultSelection` before ever reaching here).\n */\nexport function resolveSelection(\n  config: IResolvedCommanderConfig,\n  terms: readonly string[],\n  options: IResolveSelectionOptions = {},\n): TSelectionResult {\n  const extraIds = options.extraIds ?? [];\n  const bulk = (id: string): boolean =>\n    options.purpose === \"address\" ||\n    config.processes.find((proc) => proc.id === id)?.optIn !== true;\n  const errors: string[] = [];\n  const selectors = new Set<string>();\n  const tagTerms: [string, string][] = [];\n\n  for (const term of terms) {\n    if (term.startsWith(\"@\")) {\n      const pin = options.pins?.find((candidate) => candidate.name === term.slice(1));\n      if (pin == null) {\n        errors.push(`unknown pin \"${term}\" (pins are saved from the web UI)`);\n        continue;\n      }\n      for (const proc of savedFilterMembers(pin, config.processes)) selectors.add(proc.id);\n      continue;\n    }\n    const tagTerm = parseTagTerm(term);\n    if (tagTerm != null) {\n      tagTerms.push(tagTerm);\n      continue;\n    }\n    if (term === \"all\") {\n      for (const proc of config.processes) if (bulk(proc.id)) selectors.add(proc.id);\n      for (const id of extraIds) selectors.add(id);\n      continue;\n    }\n    if (config.suites[term] != null) {\n      for (const id of config.suites[term].ids) selectors.add(id);\n      continue;\n    }\n    if (config.processes.some((proc) => proc.id === term) || extraIds.includes(term)) {\n      selectors.add(term);\n      continue;\n    }\n    errors.push(`unknown selection \"${term}\" (not a process id, suite, @pin, tag=value, or \"all\")`);\n  }\n  if (errors.length > 0) return { ok: false, errors };\n\n  let direct = [...selectors];\n  const tagOnly = selectors.size === 0 && tagTerms.length > 0;\n  if (tagOnly) {\n    // A tag-only selection scans everything it is allowed to sweep up.\n    direct = config.processes.filter((proc) => bulk(proc.id)).map((proc) => proc.id);\n  }\n  if (tagTerms.length > 0) {\n    direct = direct.filter((id) => {\n      const proc = config.processes.find((candidate) => candidate.id === id);\n      if (proc == null) return false;\n      const matches = ([key, value]: [string, string]): boolean => hasTag(proc.tags, key, value);\n      return options.any === true ? tagTerms.some(matches) : tagTerms.every(matches);\n    });\n  }\n\n  const closed = withDependencies(config.processes, direct);\n  const ordered = orderByDependency(config.processes, closed);\n  return {\n    ok: true,\n    selection: {\n      ordered,\n      direct,\n      autoIncluded: ordered.filter((id) => !direct.includes(id)),\n    },\n  };\n}\n","// Config file discovery + loading (D2 outcome). jiti loads TS (incl. transform-required syntax)\n// on Node and Bun; every load gets a FRESH loader context with all caches disabled so a reload\n// can never return yesterday's helper. Nearest-tsconfig `paths` become a jiti alias map — jiti\n// does not honor them natively (D2 spike finding). `.mjs` configs stay fully supported — and are\n// force-transpiled rather than natively imported, without which they never reloaded at all.\n// A load also reports which local modules it pulled in, so the daemon can watch them.\n\nimport { existsSync, readFileSync, realpathSync } from \"node:fs\";\nimport { dirname, isAbsolute, join, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { createJiti, type Jiti, type JitiOptions } from \"jiti\";\n\nconst CONFIG_BASENAMES = [\"commander.config.ts\", \"commander.config.mts\", \"commander.config.mjs\"];\n\n/** Walk up from `startDir` for a `commander.config.*`; returns its path or null. */\nexport function findCommanderConfig(startDir: string): string | null {\n  let dir = resolve(startDir);\n  for (;;) {\n    for (const basename of CONFIG_BASENAMES) {\n      const candidate = join(dir, basename);\n      if (existsSync(candidate)) return candidate;\n    }\n    const parent = dirname(dir);\n    if (parent === dir) return null;\n    dir = parent;\n  }\n}\n\n/** Nearest tsconfig `paths` → jiti alias prefixes (D2: jiti aliases are literal prefixes). */\nfunction aliasFromNearestTsconfig(configDir: string): Record<string, string> {\n  let dir = configDir;\n  for (;;) {\n    const tsconfigPath = join(dir, \"tsconfig.json\");\n    if (existsSync(tsconfigPath)) {\n      try {\n        const raw = JSON.parse(readFileSync(tsconfigPath, \"utf8\")) as {\n          compilerOptions?: { paths?: Record<string, string | string[]> };\n        };\n        const paths = raw.compilerOptions?.paths ?? {};\n        const alias: Record<string, string> = {};\n        for (const [key, targets] of Object.entries(paths)) {\n          const target = Array.isArray(targets) ? targets[0] : targets;\n          if (typeof target !== \"string\") continue;\n          alias[key.replace(/\\/\\*$/, \"\")] = join(dir, target.replace(/\\*$/, \"\"));\n        }\n        return alias;\n      } catch {\n        return {}; // an unreadable tsconfig must not break config loading\n      }\n    }\n    const parent = dirname(dir);\n    if (parent === dir) return {};\n    dir = parent;\n  }\n}\n\n/**\n * One fresh loader context per load attempt — the reload model depends on it (D2).\n *\n * Every file jiti transforms is added to `transformed`. With the caches off that is every module\n * the load reads from source — which is also exactly the set a later load would read afresh, so\n * it is the set worth watching. A module handed to the runtime's own `import()` (a plain `.mjs`\n * helper) is not in it, and would not reload if it were.\n */\nfunction freshLoader(configPath: string, transformed: Set<string>): Jiti {\n  const url = pathToFileURL(configPath).href;\n  const options: JitiOptions = {\n    moduleCache: false,\n    fsCache: false,\n    // Under Bun jiti would otherwise delegate to Bun's native TS import, whose module cache\n    // cannot be invalidated (stale helpers on reload) — one mechanism on every runtime.\n    tryNative: false,\n    alias: aliasFromNearestTsconfig(dirname(configPath)),\n  };\n  // jiti's own transform is only reachable as the default an instance resolved for itself.\n  const transform = createJiti(url, options).options.transform;\n  if (transform == null) return createJiti(url, options);\n  return createJiti(url, {\n    ...options,\n    transform: (input) => {\n      // jiti reports forward slashes on every platform; `resolve` gives the native spelling.\n      if (input.filename != null) transformed.add(resolve(input.filename));\n      return transform(input);\n    },\n  });\n}\n\n/** Extensions jiti hands straight to the runtime's own ESM loader instead of transforming. */\nconst NATIVE_ESM = /\\.(mjs|js)$/;\n\n/**\n * Import a config module with NO cached copy — the property the whole reload story depends on.\n *\n * ⚠ `moduleCache: false` / `fsCache: false` are NOT sufficient for plain `.mjs`. jiti's caches\n * only govern what jiti transforms; a file that is already valid ESM it forwards to the runtime's\n * native `import()`, whose registry is keyed by URL, per-process, and cannot be invalidated. The\n * failure was total and silent: editing a `.mjs` config gave a \"reloaded\" daemon still running\n * the bytes it booted with, and a *broken* save reported success because the previous module came\n * back unread. `.ts`/`.mts` were always fresh — jiti transforms those itself.\n *\n * `forceTranspile` puts `.mjs` on that same transformed path. Passing `filename` keeps relative\n * imports and `import.meta` resolving exactly as a native import would.\n */\nasync function importFresh(configPath: string, transformed: Set<string>): Promise<unknown> {\n  const loader = freshLoader(configPath, transformed);\n  if (!NATIVE_ESM.test(configPath)) return loader.import(configPath);\n  return loader.evalModule(readFileSync(configPath, \"utf8\"), {\n    filename: configPath,\n    ext: \".mjs\",\n    forceTranspile: true,\n    async: true,\n  });\n}\n\nexport interface ILoadedCommanderConfigFile {\n  /** Realpath of the config file (the D6 identity anchor). */\n  configPath: string;\n  /** Realpath directory — every relative cwd/watchFile resolves against this. */\n  configDir: string;\n  raw: unknown;\n  /**\n   * The local modules the config pulled in (absolute paths; the config itself and anything under\n   * `node_modules` excluded) — what a reload has to watch beside the config file.\n   */\n  loadedFiles: string[];\n}\n\n/** A config that could not be loaded. Still says which modules the attempt reached. */\nexport class CommanderConfigLoadError extends Error {\n  readonly loadedFiles: string[];\n\n  constructor(message: string, loadedFiles: string[], cause: unknown) {\n    super(message, { cause });\n    this.name = \"CommanderConfigLoadError\";\n    this.loadedFiles = loadedFiles;\n  }\n}\n\nconst IN_NODE_MODULES = /[\\\\/]node_modules[\\\\/]/;\n\nfunction localModules(transformed: ReadonlySet<string>, configPath: string): string[] {\n  return [...transformed].filter((file) => file !== configPath && !IN_NODE_MODULES.test(file));\n}\n\n/**\n * Load a config file's default export. Throws an Error naming the file on parse/load failure —\n * the daemon's reload path catches this and keeps the last-good model.\n */\nexport async function loadCommanderConfigFile(path: string): Promise<ILoadedCommanderConfigFile> {\n  const explicit = isAbsolute(path) ? path : resolve(path);\n  if (!existsSync(explicit)) {\n    throw new Error(`commander config not found: ${explicit}`);\n  }\n  const configPath = realpathSync(explicit);\n  const transformed = new Set<string>();\n  let mod: unknown;\n  try {\n    mod = await importFresh(configPath, transformed);\n  } catch (error) {\n    throw new CommanderConfigLoadError(\n      `failed to load ${configPath}: ${error instanceof Error ? error.message : String(error)}`,\n      localModules(transformed, configPath),\n      error,\n    );\n  }\n  if (mod == null || typeof mod !== \"object\" || !(\"default\" in mod)) {\n    throw new Error(`${configPath}: expected a default export`);\n  }\n  return {\n    configPath,\n    configDir: dirname(configPath),\n    raw: mod.default,\n    loadedFiles: localModules(transformed, configPath),\n  };\n}\n","// Canonical hashing for the resolved config model (D6). Hashes cover the RESOLVED model —\n// never raw source bytes or object insertion order — so a comment-only edit changes nothing,\n// while any semantic edit bumps exactly the affected definitionHash / configRevisionHash.\n\nimport { createHash } from \"node:crypto\";\n\n/** JSON with recursively sorted object keys (arrays keep order — it is semantic here). */\nfunction canonicalize(value: unknown): string {\n  if (value == null || typeof value !== \"object\") return JSON.stringify(value) ?? \"null\";\n  if (Array.isArray(value)) return `[${value.map((item) => canonicalize(item)).join(\",\")}]`;\n  const entries = Object.entries(value as Record<string, unknown>)\n    .filter(([, v]) => v !== undefined)\n    .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n    .map(([k, v]) => `${JSON.stringify(k)}:${canonicalize(v)}`);\n  return `{${entries.join(\",\")}}`;\n}\n\nexport function hashCanonical(value: unknown, length = 16): string {\n  return createHash(\"sha256\").update(canonicalize(value)).digest(\"hex\").slice(0, length);\n}\n\n/** D6 config identity: stable across edits (realpath identity, not contents), unique per clone. */\nexport function configKeyFor(name: string, configRealpath: string): string {\n  return `${name}-${hashCanonical(configRealpath, 8)}`;\n}\n","// Declared env knobs (`envVars`): the secret heuristic, and the pure projection of\n// \"declaration + stored overrides + the daemon's base env\" into what a start would actually use.\n// Shared by the CLI, the daemon and the realm — no I/O here, the store lives in daemon/.\n\nimport { hashCanonical } from \"./hash\";\nimport type { IResolvedCommanderConfig, IResolvedCommanderProcess } from \"./types\";\n\n/**\n * Names that hold credentials often enough that publishing one by accident is the bigger risk.\n * Matched case-insensitively; `secret: false` is the explicit opt-out.\n */\nconst SECRET_NAME = /(^|_)(SECRETS?|TOKENS?|PASSWORD|PASSWD|CREDENTIALS?|APIKEY)|_KEY$/i;\n\nexport function looksSecret(name: string): boolean {\n  return SECRET_NAME.test(name);\n}\n\nexport type TEnvValueSource = \"override\" | \"default\" | \"inherited\" | \"unset\";\n\n/** One declared variable as a viewer sees it — the shape the realm carries and the CLI prints. */\nexport interface IEnvVarView {\n  name: string;\n  description?: string;\n  secret: boolean;\n  required: boolean;\n  values?: string[];\n  source: TEnvValueSource;\n  /**\n   * ⚠ Absent for a secret, and absent when the source is `inherited` — an inherited value comes\n   * from the daemon's own environment, which is exactly what a realm must not broadcast. Only a\n   * value this config supplied (a declared default, or an override someone set here) is shown.\n   */\n  value?: string;\n}\n\n/** Stored overrides, keyed by process id then variable name. */\nexport type TEnvOverrides = Readonly<Record<string, Readonly<Record<string, string>>>>;\n\n/**\n * The overrides that would actually apply to this process. Only DECLARED names survive: an entry\n * for a variable the config no longer declares is inert and never reaches a child. That filter is\n * the safety property behind letting the UI write here at all.\n */\nexport function appliedOverrides(\n  definition: IResolvedCommanderProcess,\n  overrides: TEnvOverrides,\n): Record<string, string> {\n  const stored = overrides[definition.id];\n  const applied: Record<string, string> = {};\n  if (stored == null) return applied;\n  for (const declared of definition.envVars) {\n    const value = stored[declared.name];\n    if (value != null) applied[declared.name] = value;\n  }\n  return applied;\n}\n\n/** The env a spawn would use right now: the config's resolved `env` with overrides layered on. */\nexport function effectiveEnv(\n  definition: IResolvedCommanderProcess,\n  overrides: TEnvOverrides,\n): Record<string, string | null> {\n  const applied = appliedOverrides(definition, overrides);\n  return Object.keys(applied).length === 0 ? definition.env : { ...definition.env, ...applied };\n}\n\n/** Drift key: two starts share it exactly when they would spawn with the same overrides. */\nexport function overrideFingerprint(\n  definition: IResolvedCommanderProcess,\n  overrides: TEnvOverrides,\n): string {\n  return hashCanonical(appliedOverrides(definition, overrides), 12);\n}\n\nexport function envVarViews(\n  definition: IResolvedCommanderProcess,\n  overrides: TEnvOverrides,\n  baseEnv: NodeJS.ProcessEnv,\n): IEnvVarView[] {\n  const applied = appliedOverrides(definition, overrides);\n  return definition.envVars.map((declared) => {\n    const override = applied[declared.name];\n    const source: TEnvValueSource =\n      override != null\n        ? \"override\"\n        : declared.default != null\n          ? \"default\"\n          : baseEnv[declared.name] != null\n            ? \"inherited\"\n            : \"unset\";\n    const value = source === \"override\" ? override : source === \"default\" ? declared.default : null;\n    const view: IEnvVarView = {\n      name: declared.name,\n      secret: declared.secret,\n      required: declared.required,\n      source,\n    };\n    if (declared.description != null) view.description = declared.description;\n    if (declared.values != null) view.values = [...declared.values];\n    if (value != null && !declared.secret) view.value = value;\n    return view;\n  });\n}\n\n/** A `required` variable with nothing to fill it — a start would run without something it needs. */\nexport function missingRequired(\n  definition: IResolvedCommanderProcess,\n  overrides: TEnvOverrides,\n  baseEnv: NodeJS.ProcessEnv,\n): string[] {\n  return envVarViews(definition, overrides, baseEnv)\n    .filter((view) => view.required && view.source === \"unset\")\n    .map((view) => view.name);\n}\n\n/** Whose environment answered \"is it set\": the one a start would actually inherit from. */\nexport type TEnvJudgedIn = \"daemon\" | \"shell\";\n\nconst JUDGED_IN: Record<TEnvJudgedIn, string> = {\n  daemon: \"the daemon's environment\",\n  shell: \"this shell's environment\",\n};\n\n/** \"the daemon's environment\" / \"this shell's environment\". */\nexport function describeJudgedIn(judgedIn: TEnvJudgedIn): string {\n  return JUDGED_IN[judgedIn];\n}\n\n/** Why a start is refused over `required` variables, with the command that supplies one. */\nexport function requiredRefusal(\n  id: string,\n  missing: readonly string[],\n  judgedIn: TEnvJudgedIn,\n): string {\n  return (\n    `requires ${missing.join(\", \")} — no default, no override, and not set in ` +\n    `${JUDGED_IN[judgedIn]}; \\`nice-commander env ${id} --set ${missing[0]}=…\\` supplies it`\n  );\n}\n\n/** Per-process mutations: a string sets, `null` drops the override back to the declared default. */\nexport type TEnvMutations = Readonly<Record<string, Readonly<Record<string, string | null>>>>;\n\nexport interface ICheckedEnvMutations {\n  mutations: TEnvMutations;\n  clear: string[];\n  /** One line per refusal — nothing is ever dropped silently. */\n  warnings: string[];\n}\n\n/**\n * Keep only what the config can justify. Setting a value requires a DECLARED variable on a known\n * process — that filter is what makes the UI's write path safe. Removing is always allowed, even\n * for a name or id the config no longer knows: otherwise a stale entry could never be cleared.\n */\nexport function checkEnvMutations(\n  config: IResolvedCommanderConfig,\n  input: {\n    processes: Readonly<Record<string, Readonly<Record<string, string | null>>>>;\n    clear?: readonly string[];\n  },\n): ICheckedEnvMutations {\n  const byId = new Map(config.processes.map((proc) => [proc.id, proc]));\n  const mutations: Record<string, Record<string, string | null>> = {};\n  const warnings: string[] = [];\n  for (const [id, values] of Object.entries(input.processes)) {\n    const definition = byId.get(id);\n    const accepted: Record<string, string | null> = {};\n    for (const [name, value] of Object.entries(values)) {\n      if (value == null) {\n        accepted[name] = null;\n        continue;\n      }\n      if (definition == null) {\n        warnings.push(`\"${id}\": no such process`);\n        continue;\n      }\n      const declared = definition.envVars.find((candidate) => candidate.name === name);\n      if (declared == null) {\n        warnings.push(`\"${id}\" does not declare ${name} — add it to \\`envVars\\` in the config`);\n        continue;\n      }\n      if (declared.values != null && !declared.values.includes(value)) {\n        warnings.push(`\"${id}\" ${name}: expected one of ${declared.values.join(\", \")}`);\n        continue;\n      }\n      accepted[name] = value;\n    }\n    if (Object.keys(accepted).length > 0) mutations[id] = accepted;\n  }\n  return { mutations, clear: [...(input.clear ?? [])], warnings };\n}\n\n/**\n * Overrides that moved a value the config also spent on an endpoint. Declaring `PORT` with a\n * default of 3000 and then overriding it to 3005 leaves the endpoint, the readiness probe and\n * every link still on 3000 — the process binds happily and everything pointing at it is wrong.\n * Detected by coincidence of value rather than by the name, so it needs no special case for PORT.\n */\nexport function overridesOffEndpoint(\n  definition: IResolvedCommanderProcess,\n  overrides: TEnvOverrides,\n): { name: string; value: string; port: number }[] {\n  const ports = new Set(definition.endpoints.map((endpoint) => endpoint.port));\n  const off: { name: string; value: string; port: number }[] = [];\n  for (const [name, value] of Object.entries(appliedOverrides(definition, overrides))) {\n    const declared = definition.envVars.find((candidate) => candidate.name === name)?.default;\n    if (declared == null || value === declared || !ports.has(Number(declared))) continue;\n    off.push({ name, value, port: Number(declared) });\n  }\n  return off;\n}\n\nexport interface IStaleOverride {\n  id: string;\n  name: string;\n  /** Why it is stored but inert. */\n  reason: \"unknown process\" | \"not declared\";\n}\n\n/**\n * Stored overrides the config can no longer explain. Deliberately kept rather than pruned — a\n * process renamed mid-edit should not silently eat the value you set — so they are reported by\n * `env` and `doctor` instead, and `--clear` is what removes them.\n */\nexport function staleOverrides(\n  config: IResolvedCommanderConfig,\n  overrides: TEnvOverrides,\n): IStaleOverride[] {\n  const byId = new Map(config.processes.map((proc) => [proc.id, proc]));\n  const stale: IStaleOverride[] = [];\n  for (const [id, values] of Object.entries(overrides)) {\n    const definition = byId.get(id);\n    for (const name of Object.keys(values)) {\n      if (definition == null) stale.push({ id, name, reason: \"unknown process\" });\n      else if (!definition.envVars.some((declared) => declared.name === name)) {\n        stale.push({ id, name, reason: \"not declared\" });\n      }\n    }\n  }\n  return stale;\n}\n","// Config validation + resolved-model build (edge 31). Structural shape and semantic rules are\n// one hand-rolled pass so every issue reads uniformly (`processes[2].run: …`); friendly errors\n// fail fast at daemon start, and on reload the daemon keeps the last-good model instead.\n// Warnings never fail — they surface in status/UI.\n\nimport { existsSync, statSync } from \"node:fs\";\nimport { isAbsolute, join } from \"node:path\";\nimport type { TNiceProcessReady } from \"@nice-code/process\";\nimport { looksSecret } from \"./envVars\";\nimport { SHELL_PLAIN_ARG } from \"./flags\";\nimport { configKeyFor, hashCanonical } from \"./hash\";\nimport { matchesTagQuery, parseTagTerm, tagTermsOf } from \"./tags\";\nimport {\n  COMMANDER_ID_PATTERN,\n  type ICommanderConfig,\n  type ICommanderEndpoint,\n  type ICommanderSuiteDefinition,\n  type IResolvedCommanderConfig,\n  type IResolvedCommanderEnvVar,\n  type IResolvedCommanderFlag,\n  type IResolvedCommanderProcess,\n  type IResolvedCommanderSuite,\n  RESERVED_SELECTOR_NAME,\n  type TCommanderReady,\n  type TCommanderTagQuery,\n} from \"./types\";\n\nconst SUITE_PARALLEL_DEFAULT = 4;\nconst SUITE_STAGGER_DEFAULT_MS = 100;\n\nexport interface ICommanderValidation {\n  /** Present only when `errors` is empty. */\n  resolved?: IResolvedCommanderConfig;\n  errors: string[];\n  warnings: string[];\n}\n\n/** C0/DEL/C1 control characters have no business in tag keys/values or env keys. */\nfunction hasControlChars(value: string): boolean {\n  for (let i = 0; i < value.length; i += 1) {\n    const code = value.charCodeAt(i);\n    if (code < 0x20 || (code >= 0x7f && code <= 0x9f)) return true;\n  }\n  return false;\n}\n\nconst MAX_TAGS = 32;\nconst MAX_TAG_VALUES = 16;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === \"object\" && value != null && !Array.isArray(value);\n}\n\n/** `=` would split the child's environment block; control chars have no business in a key. */\nfunction isEnvName(value: string): boolean {\n  return value !== \"\" && !value.includes(\"=\") && !hasControlChars(value);\n}\n\n/** The optional half of a declaration, or null when one of its fields was malformed. */\nfunction readEnvVarFields(\n  declared: Record<string, unknown>,\n  name: string,\n  at: string,\n  errors: string[],\n): IResolvedCommanderEnvVar | null {\n  const before = errors.length;\n  const description = declared[\"description\"];\n  if (description != null && typeof description !== \"string\") {\n    errors.push(`${at}.description: expected a string`);\n  }\n  const fallback = declared[\"default\"];\n  if (fallback != null && typeof fallback !== \"string\") {\n    errors.push(`${at}.default: expected a string (an environment value is always text)`);\n  }\n  const rawValues = declared[\"values\"];\n  let values: string[] | undefined;\n  if (rawValues != null) {\n    if (!Array.isArray(rawValues) || rawValues.some((entry) => typeof entry !== \"string\")) {\n      errors.push(`${at}.values: expected an array of strings`);\n    } else if (rawValues.length === 0) {\n      errors.push(`${at}.values: an empty set can never be satisfied`);\n    } else {\n      values = [...rawValues];\n      if (typeof fallback === \"string\" && !values.includes(fallback)) {\n        errors.push(\n          `${at}.default: ${JSON.stringify(fallback)} is not one of ${values.join(\", \")}`,\n        );\n      }\n    }\n  }\n  const secret = declared[\"secret\"];\n  if (secret != null && typeof secret !== \"boolean\")\n    errors.push(`${at}.secret: expected a boolean`);\n  const required = declared[\"required\"];\n  if (required != null && typeof required !== \"boolean\") {\n    errors.push(`${at}.required: expected a boolean`);\n  }\n  if (errors.length !== before) return null;\n  return {\n    name,\n    ...(typeof description === \"string\" ? { description } : {}),\n    ...(typeof fallback === \"string\" ? { default: fallback } : {}),\n    ...(values != null ? { values } : {}),\n    // Fail safe: a credential-shaped name is secret unless the config says otherwise out loud.\n    secret: typeof secret === \"boolean\" ? secret : looksSecret(name),\n    required: required === true,\n  };\n}\n\nconst MAX_FLAGS = 32;\n\nfunction readFlags(\n  raw: unknown,\n  shellString: boolean,\n  at: string,\n  errors: string[],\n): IResolvedCommanderFlag[] {\n  if (raw == null) return [];\n  if (!Array.isArray(raw)) {\n    errors.push(`${at}.flags: expected an array of flag declarations`);\n    return [];\n  }\n  if (raw.length > MAX_FLAGS) {\n    errors.push(`${at}.flags: ${raw.length} entries exceeds the ${MAX_FLAGS} bound`);\n  }\n  const flags: IResolvedCommanderFlag[] = [];\n  for (const [index, declared] of raw.entries()) {\n    const atF = `${at}.flags[${index}]`;\n    if (!isRecord(declared)) {\n      errors.push(`${atF}: expected an object`);\n      continue;\n    }\n    const name = declared[\"name\"];\n    if (typeof name !== \"string\" || !COMMANDER_ID_PATTERN.test(name)) {\n      errors.push(`${atF}.name: must match ${COMMANDER_ID_PATTERN}`);\n      continue;\n    }\n    if (flags.some((existing) => existing.name === name)) {\n      errors.push(`${atF}.name: duplicate flag \"${name}\"`);\n      continue;\n    }\n    const description = declared[\"description\"];\n    if (description != null && typeof description !== \"string\") {\n      errors.push(`${atF}.description: expected a string`);\n      continue;\n    }\n    const rawArgs = declared[\"args\"] ?? [`--${name}`];\n    if (\n      !Array.isArray(rawArgs) ||\n      rawArgs.length === 0 ||\n      rawArgs.some((arg) => typeof arg !== \"string\" || arg === \"\" || hasControlChars(arg))\n    ) {\n      errors.push(`${atF}.args: expected a non-empty array of non-empty strings`);\n      continue;\n    }\n    const args = rawArgs.filter((arg): arg is string => typeof arg === \"string\");\n    const unquotable = shellString ? args.find((arg) => !SHELL_PLAIN_ARG.test(arg)) : undefined;\n    if (unquotable != null) {\n      errors.push(\n        `${atF}.args: ${JSON.stringify(unquotable)} would need shell quoting, and a shell-string ` +\n          \"`run` takes its flags unquoted — use the argv form of `run`, or a plain argument\",\n      );\n      continue;\n    }\n    flags.push({ name, args, ...(typeof description === \"string\" ? { description } : {}) });\n  }\n  return flags;\n}\n\nfunction isUrlCleanHttp(url: string): boolean {\n  try {\n    const parsed = new URL(url);\n    return (\n      (parsed.protocol === \"http:\" || parsed.protocol === \"https:\") &&\n      parsed.username === \"\" &&\n      parsed.password === \"\"\n    );\n  } catch {\n    return false;\n  }\n}\n\nfunction normalizeTagQueryOr(value: unknown): TCommanderTagQuery[] | undefined {\n  if (value == null) return undefined;\n  const list = Array.isArray(value) ? value : [value];\n  // Query VALUES are string-checked in the suite validation loop (the only caller context).\n  return list.filter(isRecord) as TCommanderTagQuery[];\n}\n\nfunction normalizeExcludes(value: ICommanderSuiteDefinition[\"exclude\"]): {\n  ids: string[];\n  queries: TCommanderTagQuery[];\n} {\n  if (value == null) return { ids: [], queries: [] };\n  const list = Array.isArray(value) ? value : [value];\n  const ids: string[] = [];\n  const queries: TCommanderTagQuery[] = [];\n  for (const entry of list) {\n    if (typeof entry === \"string\") ids.push(entry);\n    // Query VALUES are string-checked in the suite validation loop (the only caller context).\n    else if (isRecord(entry)) queries.push(entry as TCommanderTagQuery);\n  }\n  return { ids, queries };\n}\n\n/** DFS cycle check over a string→string[] graph; returns the first cycle path found. */\nfunction findCycle(graph: ReadonlyMap<string, readonly string[]>): string[] | null {\n  const visiting = new Set<string>();\n  const done = new Set<string>();\n  const stack: string[] = [];\n  const visit = (node: string): string[] | null => {\n    if (done.has(node)) return null;\n    if (visiting.has(node)) return [...stack.slice(stack.indexOf(node)), node];\n    visiting.add(node);\n    stack.push(node);\n    for (const next of graph.get(node) ?? []) {\n      const cycle = visit(next);\n      if (cycle != null) return cycle;\n    }\n    stack.pop();\n    visiting.delete(node);\n    done.add(node);\n    return null;\n  };\n  for (const node of graph.keys()) {\n    const cycle = visit(node);\n    if (cycle != null) return cycle;\n  }\n  return null;\n}\n\ntype TSelectionInput = Pick<ICommanderSuiteDefinition, \"where\" | \"include\" | \"exclude\">;\n\n/**\n * Expand `include`/`where`/`exclude` over a set of sibling definitions. A `where` never picks up\n * an `optIn` process; an explicit `include` does. Callers guarantee the reference graph is\n * acyclic; `seen` only keeps a malformed one from recursing forever.\n */\nfunction expandSelection(\n  name: string,\n  inputs: Record<string, unknown>,\n  byId: ReadonlyMap<string, IResolvedCommanderProcess>,\n  seen: Set<string> = new Set(),\n): Set<string> {\n  const out = new Set<string>();\n  const input = inputs[name];\n  if (seen.has(name) || !isRecord(input)) return out;\n  seen.add(name);\n  const selection = input as TSelectionInput;\n  for (const entry of selection.include ?? []) {\n    if (byId.has(entry)) out.add(entry);\n    else if (typeof entry === \"string\" && entry in inputs) {\n      for (const id of expandSelection(entry, inputs, byId, seen)) out.add(id);\n    }\n  }\n  for (const query of normalizeTagQueryOr(selection.where) ?? []) {\n    for (const proc of byId.values()) {\n      if (!proc.optIn && matchesTagQuery(proc.tags, query)) out.add(proc.id);\n    }\n  }\n  const { ids: excludedIds, queries } = normalizeExcludes(selection.exclude);\n  for (const id of excludedIds) out.delete(id);\n  for (const id of [...out]) {\n    const proc = byId.get(id);\n    if (proc != null && queries.some((query) => matchesTagQuery(proc.tags, query))) out.delete(id);\n  }\n  seen.delete(name);\n  return out;\n}\n\n/** The tag selection that picks out exactly `ids`, if one exists — smallest first. */\nfunction equivalentTagSelection(\n  ids: ReadonlySet<string>,\n  byId: ReadonlyMap<string, IResolvedCommanderProcess>,\n): string[] | null {\n  const members = [...ids].flatMap((id) => byId.get(id) ?? []);\n  const [first, ...rest] = members;\n  if (first == null) return null;\n  const common = tagTermsOf(first.tags).filter((term) =>\n    rest.every((proc) => tagTermsOf(proc.tags).includes(term)),\n  );\n  const selects = (terms: readonly string[]): boolean => {\n    const matched = [...byId.values()].filter(\n      (proc) => !proc.optIn && terms.every((term) => tagTermsOf(proc.tags).includes(term)),\n    );\n    return matched.length === ids.size && matched.every((proc) => ids.has(proc.id));\n  };\n  for (const term of common) if (selects([term])) return [term];\n  return common.length > 1 && selects(common) ? common : null;\n}\n\n/** `groups` was removed — say what each one becomes instead of just refusing the key. */\nfunction groupMigrationErrors(\n  groupsInput: Record<string, unknown>,\n  byId: ReadonlyMap<string, IResolvedCommanderProcess>,\n): string[] {\n  const errors = [\n    \"groups: removed — processes are organised by tags, and a run-unit is a `suite`. Per group:\",\n  ];\n  for (const name of Object.keys(groupsInput)) {\n    const ids = expandSelection(name, groupsInput, byId);\n    const tagSelection = equivalentTagSelection(ids, byId);\n    if (ids.size < 2) {\n      errors.push(\n        `groups.${name}: one member — delete it and use the id \"${[...ids][0] ?? \"?\"}\" directly`,\n      );\n    } else if (tagSelection != null) {\n      errors.push(\n        `groups.${name}: this is the tag selection \\`${tagSelection.join(\" \")}\\` — delete it and ` +\n          \"select by tag (pin it in the UI), or move it under `suites` if it is a real run-unit\",\n      );\n    } else {\n      errors.push(`groups.${name}: move it under \\`suites\\` unchanged`);\n    }\n  }\n  return errors;\n}\n\n/**\n * Validate a raw loaded config and build the resolved model. `configDir`/`configPath` are the\n * loader's realpath answers — every relative cwd and watchFile anchors there (edge 32).\n */\nexport function validateCommanderConfig(\n  raw: unknown,\n  anchor: { configPath: string; configDir: string },\n): ICommanderValidation {\n  const errors: string[] = [];\n  const warnings: string[] = [];\n\n  if (!isRecord(raw)) {\n    return { errors: [\"config: expected a default-exported object\"], warnings };\n  }\n  // Boundary cast: every field below is still runtime-checked where it matters; the typed view\n  // keeps the rules readable. (Partial is assignable to the record type, so the cast is legal.)\n  const config = raw as Partial<ICommanderConfig>;\n\n  // --- name + top-level shape ----------------------------------------------------------\n  const name = typeof config.name === \"string\" ? config.name : \"\";\n  if (!COMMANDER_ID_PATTERN.test(name)) {\n    errors.push(`name: must match ${COMMANDER_ID_PATTERN} (it seeds the data-dir slug)`);\n  }\n  if (!Array.isArray(config.processes)) {\n    errors.push(\"processes: expected an array of process definitions\");\n    return { errors, warnings };\n  }\n\n  // --- processes -----------------------------------------------------------------------\n  const byId = new Map<string, IResolvedCommanderProcess>();\n  const dependsGraph = new Map<string, string[]>();\n\n  config.processes.forEach((proc, index) => {\n    const at = `processes[${index}]${isRecord(proc) && typeof proc.id === \"string\" ? ` (${proc.id})` : \"\"}`;\n    if (!isRecord(proc)) {\n      errors.push(`${at}: expected an object`);\n      return;\n    }\n    if (typeof proc.id !== \"string\" || !COMMANDER_ID_PATTERN.test(proc.id)) {\n      errors.push(`${at}.id: must match ${COMMANDER_ID_PATTERN}`);\n      return;\n    }\n    if (byId.has(proc.id)) {\n      errors.push(`${at}.id: duplicate id \"${proc.id}\"`);\n      return;\n    }\n\n    const kind = proc.kind ?? config.defaults?.kind ?? \"service\";\n    if (kind !== \"service\" && kind !== \"task\") {\n      errors.push(`${at}.kind: expected \"service\" | \"task\"`);\n      return;\n    }\n\n    if (typeof proc.run !== \"string\" && !Array.isArray(proc.run)) {\n      errors.push(`${at}.run: expected an argv array or a shell string`);\n      return;\n    }\n    if (typeof proc.run === \"string\" && proc.shell == null) {\n      errors.push(`${at}.run: a plain string requires shell: true | \"cmd\" | \"powershell\" | \"sh\"`);\n    }\n    if (\n      proc.shell != null &&\n      proc.shell !== true &&\n      proc.shell !== false &&\n      proc.shell !== \"cmd\" &&\n      proc.shell !== \"powershell\" &&\n      proc.shell !== \"sh\"\n    ) {\n      errors.push(`${at}.shell: expected true | \"cmd\" | \"powershell\" | \"sh\"`);\n    }\n\n    // cwd anchors at the config's realpath directory — never the invoking shell's (edge 32).\n    const cwd =\n      proc.cwd == null\n        ? anchor.configDir\n        : isAbsolute(proc.cwd)\n          ? proc.cwd\n          : join(anchor.configDir, proc.cwd);\n    if (!existsSync(cwd) || !statSync(cwd).isDirectory()) {\n      errors.push(`${at}.cwd: \"${proc.cwd}\" does not exist or is not a directory`);\n    }\n\n    const env: Record<string, string | null> = {};\n    if (proc.env != null) {\n      if (!isRecord(proc.env)) {\n        errors.push(`${at}.env: expected a record of string | null`);\n      } else {\n        for (const [key, value] of Object.entries(proc.env)) {\n          if (!isEnvName(key)) {\n            errors.push(`${at}.env: invalid key ${JSON.stringify(key)}`);\n          } else if (typeof value !== \"string\" && value !== null) {\n            errors.push(`${at}.env[${JSON.stringify(key)}]: expected string | null`);\n          } else {\n            env[key] = value;\n          }\n        }\n      }\n    }\n\n    // Declared knobs. Their defaults are folded into `env` below, so `definitionHash` covers them\n    // and every consumer of the resolved env sees one map instead of two layers to merge.\n    const envVars: IResolvedCommanderEnvVar[] = [];\n    if (proc.envVars != null) {\n      if (!Array.isArray(proc.envVars)) {\n        errors.push(\n          `${at}.envVars: expected an array of declarations (a fixed map goes in \\`env\\`)`,\n        );\n      } else {\n        for (const [varIndex, declared] of proc.envVars.entries()) {\n          const atV = `${at}.envVars[${varIndex}]`;\n          if (!isRecord(declared)) {\n            errors.push(`${atV}: expected an object`);\n            continue;\n          }\n          const name = declared[\"name\"];\n          if (typeof name !== \"string\" || !isEnvName(name)) {\n            errors.push(`${atV}.name: expected an environment variable name`);\n            continue;\n          }\n          if (envVars.some((existing) => existing.name === name)) {\n            errors.push(`${atV}.name: duplicate declaration of \"${name}\"`);\n            continue;\n          }\n          // One home per variable: a knob's value belongs to its declaration, and `env` stays for\n          // what the operator is not meant to tune. Two sources would make precedence a guess.\n          if (name in env) {\n            errors.push(`${atV}.name: \"${name}\" is also in \\`env\\` — declare it in one place`);\n            continue;\n          }\n          const resolved = readEnvVarFields(declared, name, atV, errors);\n          if (resolved != null) envVars.push(resolved);\n        }\n      }\n    }\n    for (const declared of envVars) {\n      if (declared.default != null) env[declared.name] = declared.default;\n    }\n\n    const flags = readFlags(proc.flags, typeof proc.run === \"string\", at, errors);\n\n    const tagEntries = Object.entries({ ...config.defaults?.tags, ...proc.tags });\n    if (tagEntries.length > MAX_TAGS) {\n      errors.push(`${at}.tags: ${tagEntries.length} entries exceeds the ${MAX_TAGS} bound`);\n    }\n    const tags: Record<string, string[]> = {};\n    for (const [key, value] of tagEntries) {\n      if (key === \"\" || key.length > 64 || key.includes(\"=\") || hasControlChars(key)) {\n        errors.push(`${at}.tags: invalid key ${JSON.stringify(key)}`);\n      }\n      const values: readonly unknown[] = typeof value === \"string\" ? [value] : value;\n      if (!Array.isArray(values) || values.length === 0 || values.length > MAX_TAG_VALUES) {\n        errors.push(\n          `${at}.tags[${JSON.stringify(key)}]: expected a string or 1–${MAX_TAG_VALUES} strings`,\n        );\n        continue;\n      }\n      const clean: string[] = [];\n      for (const entry of values) {\n        // A comma would split the UI's `#tags=` hash; nothing legitimate needs one.\n        if (\n          typeof entry !== \"string\" ||\n          entry.length > 256 ||\n          entry.includes(\",\") ||\n          hasControlChars(entry)\n        ) {\n          errors.push(`${at}.tags[${JSON.stringify(key)}]: invalid value`);\n        } else if (!clean.includes(entry)) {\n          clean.push(entry);\n        }\n      }\n      tags[key] = clean;\n    }\n    if (proc.optIn != null && typeof proc.optIn !== \"boolean\") {\n      errors.push(`${at}.optIn: expected a boolean`);\n    }\n    if (proc.replaceSame != null && typeof proc.replaceSame !== \"boolean\") {\n      errors.push(`${at}.replaceSame: expected a boolean`);\n    }\n    const replaceSame = proc.replaceSame ?? config.defaults?.replaceSame ?? false;\n\n    const endpoints: IResolvedCommanderProcess[\"endpoints\"] = [];\n    const endpointNames = new Set<string>();\n    for (const [endpointIndex, endpoint] of (proc.endpoints ?? []).entries()) {\n      const atE = `${at}.endpoints[${endpointIndex}]`;\n      if (!isRecord(endpoint)) {\n        errors.push(`${atE}: expected an object`);\n        continue;\n      }\n      const ep = endpoint as ICommanderEndpoint;\n      if (typeof ep.name !== \"string\" || !COMMANDER_ID_PATTERN.test(ep.name)) {\n        errors.push(`${atE}.name: must match ${COMMANDER_ID_PATTERN}`);\n        continue;\n      }\n      if (endpointNames.has(ep.name)) {\n        errors.push(`${atE}.name: duplicate endpoint name \"${ep.name}\"`);\n        continue;\n      }\n      endpointNames.add(ep.name);\n      if (ep.protocol !== \"tcp\" && ep.protocol !== \"http\") {\n        errors.push(`${atE}.protocol: expected \"tcp\" | \"http\"`);\n      }\n      if (!Number.isInteger(ep.port) || ep.port < 1 || ep.port > 65_535) {\n        errors.push(`${atE}.port: expected an integer 1–65535`);\n      }\n      if (\n        ep.ownership !== \"exclusive\" &&\n        ep.ownership !== \"shared\" &&\n        ep.ownership !== \"observed\"\n      ) {\n        errors.push(`${atE}.ownership: expected \"exclusive\" | \"shared\" | \"observed\"`);\n      }\n      if (ep.url != null && !isUrlCleanHttp(ep.url)) {\n        errors.push(`${atE}.url: credential-free http(s) only`);\n      }\n      if (ep.health?.path != null && !ep.health.path.startsWith(\"/\")) {\n        ep.health = { ...ep.health, path: `/${ep.health.path}` };\n      }\n      endpoints.push({\n        name: ep.name,\n        protocol: ep.protocol,\n        host: ep.host ?? \"127.0.0.1\",\n        port: ep.port,\n        ownership: ep.ownership,\n        ...(ep.url != null ? { url: ep.url } : {}),\n        ...(ep.health != null ? { health: ep.health } : {}),\n      });\n    }\n\n    if (proc.url != null && !isUrlCleanHttp(proc.url)) {\n      errors.push(`${at}.url: credential-free http(s) only`);\n    }\n\n    // Readiness: the endpoint sugar expands HERE so downstream never re-resolves names.\n    let ready: TNiceProcessReady | undefined;\n    if (proc.ready != null) {\n      const candidate = proc.ready as TCommanderReady;\n      if (candidate.kind === \"endpoint\") {\n        const named = endpoints.find((ep) => ep.name === candidate.endpoint);\n        if (named == null) {\n          errors.push(`${at}.ready.endpoint: no endpoint named \"${candidate.endpoint}\"`);\n        } else if (named.protocol === \"tcp\") {\n          ready = {\n            kind: \"port\",\n            port: named.port,\n            host: named.host,\n            ...(candidate.timeoutMs != null ? { timeoutMs: candidate.timeoutMs } : {}),\n            ...(candidate.healthProbeMs != null ? { healthProbeMs: candidate.healthProbeMs } : {}),\n          };\n        } else {\n          ready = {\n            kind: \"httpOk\",\n            port: named.port,\n            host: named.host,\n            path: named.health?.path ?? \"/\",\n            ...(named.health?.match != null ? { bodyIncludes: named.health.match } : {}),\n            ...(candidate.timeoutMs != null ? { timeoutMs: candidate.timeoutMs } : {}),\n            ...(candidate.healthProbeMs != null ? { healthProbeMs: candidate.healthProbeMs } : {}),\n          };\n        }\n      } else {\n        ready = candidate as TNiceProcessReady;\n      }\n    }\n\n    const dependsOn = proc.dependsOn == null ? [] : [...proc.dependsOn];\n    for (const dep of dependsOn) {\n      if (typeof dep !== \"string\" || !COMMANDER_ID_PATTERN.test(dep)) {\n        errors.push(`${at}.dependsOn: invalid id ${JSON.stringify(dep)}`);\n      }\n    }\n    dependsGraph.set(proc.id, dependsOn);\n\n    if (proc.timeoutMs != null && kind !== \"task\") {\n      errors.push(`${at}.timeoutMs: only valid on kind: \"task\"`);\n    }\n    // defaults.restart applies to services only; an explicit restart on a task is an error.\n    if (proc.restart != null && kind !== \"service\") {\n      errors.push(`${at}.restart: automatic restart is service-only (rerun a task explicitly)`);\n    }\n    const restart = kind === \"service\" ? (proc.restart ?? config.defaults?.restart) : undefined;\n\n    const stdin = proc.stdin ?? \"pipe\";\n    if (stdin !== \"pipe\" && stdin !== \"ignore\") {\n      errors.push(`${at}.stdin: expected \"pipe\" | \"ignore\"`);\n    }\n    const stop = { ...config.defaults?.stop, ...proc.stop };\n    if (stop.stopInput != null && stdin !== \"pipe\") {\n      errors.push(`${at}.stop.stopInput: requires stdin: \"pipe\" (the default)`);\n    }\n\n    byId.set(proc.id, {\n      id: proc.id,\n      kind,\n      cwd,\n      run: proc.run,\n      ...(proc.shell != null ? { shell: proc.shell } : {}),\n      env,\n      envVars,\n      flags,\n      stdin,\n      tags,\n      optIn: proc.optIn === true,\n      dependsOn,\n      endpoints,\n      replaceSame: replaceSame === true,\n      ...(proc.url != null ? { url: proc.url } : {}),\n      ...(ready != null ? { ready } : {}),\n      stop,\n      ...(restart != null ? { restart } : {}),\n      log: { ...config.defaults?.log, ...proc.log },\n      ...(proc.timeoutMs != null ? { timeoutMs: proc.timeoutMs } : {}),\n      definitionHash: \"\", // filled below, once the normalized definition is complete\n    });\n  });\n\n  // --- dependsOn graph -----------------------------------------------------------------\n  for (const [id, deps] of dependsGraph) {\n    for (const dep of deps) {\n      if (!byId.has(dep)) errors.push(`process \"${id}\" dependsOn: unknown id \"${dep}\"`);\n    }\n  }\n  const processCycle = findCycle(dependsGraph);\n  if (processCycle != null) {\n    errors.push(`dependsOn cycle: ${processCycle.join(\" → \")}`);\n  }\n\n  // --- suites --------------------------------------------------------------------------\n  const removedGroups = (raw as { groups?: unknown }).groups;\n  if (removedGroups != null) {\n    errors.push(...groupMigrationErrors(isRecord(removedGroups) ? removedGroups : {}, byId));\n  }\n\n  const suitesInput: Record<string, unknown> = isRecord(config.suites) ? config.suites : {};\n  if (config.suites != null && !isRecord(config.suites)) {\n    errors.push(\"suites: expected an object keyed by suite name\");\n  }\n  const suiteRefs = new Map<string, string[]>();\n  for (const [name, suite] of Object.entries(suitesInput)) {\n    const at = `suites.${name}`;\n    if (!COMMANDER_ID_PATTERN.test(name)) {\n      errors.push(`suites.${JSON.stringify(name)}: must match ${COMMANDER_ID_PATTERN}`);\n    }\n    if (name === RESERVED_SELECTOR_NAME) {\n      errors.push(`${at}: \"${RESERVED_SELECTOR_NAME}\" is the built-in selector`);\n    }\n    if (byId.has(name)) errors.push(`${at}: collides with a process id`);\n    if (!isRecord(suite)) {\n      errors.push(`${at}: expected an object`);\n      continue;\n    }\n    const definition = suite as ICommanderSuiteDefinition;\n    if (definition.description != null && typeof definition.description !== \"string\") {\n      errors.push(`${at}.description: expected a string`);\n    }\n    if (\n      definition.parallel != null &&\n      (!Number.isInteger(definition.parallel) || definition.parallel < 1)\n    ) {\n      errors.push(`${at}.parallel: expected an integer ≥ 1`);\n    }\n    if (definition.failFast != null && typeof definition.failFast !== \"boolean\") {\n      errors.push(`${at}.failFast: expected a boolean`);\n    }\n    if (\n      definition.staggerMs != null &&\n      (typeof definition.staggerMs !== \"number\" || definition.staggerMs < 0)\n    ) {\n      errors.push(`${at}.staggerMs: expected a non-negative number`);\n    }\n    for (const entry of definition.include ?? []) {\n      if (typeof entry !== \"string\") {\n        errors.push(`${at}.include: expected id/suite strings`);\n      } else if (!byId.has(entry) && !(entry in suitesInput)) {\n        errors.push(`${at}.include: unknown id or suite \"${entry}\"`);\n      }\n    }\n    const { ids: excludedIds, queries: excludeQueries } = normalizeExcludes(definition.exclude);\n    for (const id of excludedIds) {\n      if (!byId.has(id)) errors.push(`${at}.exclude: unknown id \"${id}\"`);\n    }\n    for (const query of [...(normalizeTagQueryOr(definition.where) ?? []), ...excludeQueries]) {\n      if (Object.keys(query).length === 0) {\n        warnings.push(`${at}: an empty tag query matches everything`);\n      }\n      for (const [key, value] of Object.entries(query)) {\n        if (typeof value !== \"string\") {\n          errors.push(`${at}: tag query ${JSON.stringify(key)} must map to a string`);\n        }\n      }\n    }\n    suiteRefs.set(\n      name,\n      (definition.include ?? []).filter(\n        (entry): entry is string => typeof entry === \"string\" && entry in suitesInput,\n      ),\n    );\n  }\n  const suiteCycle = findCycle(suiteRefs);\n  if (suiteCycle != null) {\n    errors.push(`suite include cycle: ${suiteCycle.join(\" → \")}`);\n  }\n\n  // Expansion is only meaningful on an acyclic graph; on errors the model is discarded anyway.\n  const suites: Record<string, IResolvedCommanderSuite> = {};\n  if (suiteCycle == null) {\n    for (const [name, suite] of Object.entries(suitesInput)) {\n      if (!isRecord(suite)) continue;\n      const definition = suite as ICommanderSuiteDefinition;\n      const expanded = expandSelection(name, suitesInput, byId);\n      const ordered = [...byId.keys()].filter((id) => expanded.has(id));\n      if (ordered.length < 2) {\n        // A suite is a run-unit. One member is a label, and a label is a tag.\n        errors.push(\n          ordered.length === 0\n            ? `suites.${name}: expands to zero processes`\n            : `suites.${name}: one member — run \"${ordered[0]}\" directly; use a tag if you wanted a label`,\n        );\n        continue;\n      }\n      // Only a suite that adds NOTHING over the tag earns the hint — a description or a policy is\n      // exactly what makes a one-query suite worth declaring.\n      const addsNothing = Object.keys(definition).every((key) => key === \"where\");\n      const tagSelection = addsNothing ? equivalentTagSelection(expanded, byId) : null;\n      if (tagSelection != null && tagSelection.length === 1) {\n        warnings.push(\n          `suites.${name}: this is exactly the tag selection \\`${tagSelection[0]}\\` — a pinned tag group may be all you need`,\n        );\n      }\n      suites[name] = {\n        name,\n        ...(typeof definition.description === \"string\"\n          ? { description: definition.description }\n          : {}),\n        ids: ordered,\n        parallel: definition.parallel ?? SUITE_PARALLEL_DEFAULT,\n        failFast: definition.failFast === true,\n        staggerMs: definition.staggerMs ?? SUITE_STAGGER_DEFAULT_MS,\n      };\n    }\n  }\n\n  // --- endpoint conflicts across processes ----------------------------------------------\n  const portClaims = new Map<\n    number,\n    { id: string; ep: IResolvedCommanderProcess[\"endpoints\"][number] }[]\n  >();\n  for (const proc of byId.values()) {\n    for (const ep of proc.endpoints) {\n      const claims = portClaims.get(ep.port) ?? [];\n      claims.push({ id: proc.id, ep });\n      portClaims.set(ep.port, claims);\n    }\n  }\n  for (const [port, claims] of portClaims) {\n    if (claims.length < 2) continue;\n    const exclusive = claims.filter((claim) => claim.ep.ownership === \"exclusive\");\n    const shared = claims.filter((claim) => claim.ep.ownership === \"shared\");\n    if (exclusive.length > 1) {\n      warnings.push(\n        `port ${port}: duplicate exclusive endpoints (${exclusive.map((c) => `${c.id}/${c.ep.name}`).join(\", \")}) — only one can be up at a time`,\n      );\n    }\n    if (exclusive.length > 0 && shared.length > 0) {\n      errors.push(\n        `port ${port}: exclusive claim (${exclusive[0].id}/${exclusive[0].ep.name}) contradicts shared declarations (${shared.map((c) => c.id).join(\", \")})`,\n      );\n    }\n    for (let i = 1; i < shared.length; i += 1) {\n      if (\n        shared[i].ep.protocol !== shared[0].ep.protocol ||\n        shared[i].ep.host !== shared[0].ep.host\n      ) {\n        errors.push(\n          `port ${port}: shared endpoints must agree on protocol/host (${shared[0].id} vs ${shared[i].id})`,\n        );\n      }\n    }\n  }\n\n  // --- defaultSelection + watchFiles ----------------------------------------------------\n  if (config.defaultSelection != null) {\n    const selection = config.defaultSelection;\n    if (\n      typeof selection !== \"string\" ||\n      (!byId.has(selection) && !(selection in suitesInput) && parseTagTerm(selection) == null)\n    ) {\n      errors.push(`defaultSelection: expected a process id, a suite, or one tag=value term`);\n    }\n  }\n  const watchFiles = [anchor.configPath];\n  for (const file of config.watchFiles ?? []) {\n    const absolute = isAbsolute(file) ? file : join(anchor.configDir, file);\n    if (!existsSync(absolute)) {\n      warnings.push(`watchFiles: \"${file}\" does not exist (yet) — watching the parent state only`);\n    }\n    watchFiles.push(absolute);\n  }\n\n  if (errors.length > 0) return { errors, warnings };\n\n  // --- hashes over the canonical resolved model -----------------------------------------\n  const processes = [...byId.values()];\n  for (const proc of processes) {\n    const { definitionHash: _drop, ...definition } = proc;\n    proc.definitionHash = hashCanonical(definition);\n  }\n  const resolvedBase = {\n    name,\n    processes,\n    suites,\n    defaultSelection: config.defaultSelection,\n    daemon: { port: typeof config.daemon?.port === \"number\" ? config.daemon.port : 4900 },\n  };\n  const resolved: IResolvedCommanderConfig = {\n    ...resolvedBase,\n    configPath: anchor.configPath,\n    configDir: anchor.configDir,\n    configKey: configKeyFor(name, anchor.configPath),\n    configRevisionHash: hashCanonical(resolvedBase),\n    watchFiles,\n    warnings,\n  };\n  return { resolved, errors, warnings };\n}\n","// Shared CLI plumbing: config loading with uniform usage-error exits, and the exit-code\n// carrier. Every command loads the config itself — selection resolution and the configKey\n// (which names the daemon's state dir) both live there.\n\nimport { findCommanderConfig, loadCommanderConfigFile } from \"../config/loader\";\nimport type { IResolvedCommanderConfig } from \"../config/types\";\nimport { validateCommanderConfig } from \"../config/validate\";\n\n/** Exit codes (stable, documented): thrown by commands, mapped in cli.ts. */\nexport class CliExit extends Error {\n  constructor(\n    readonly code: number,\n    message: string,\n  ) {\n    super(message);\n    this.name = \"CliExit\";\n  }\n}\n\nexport const EXIT = {\n  ok: 0,\n  failure: 1,\n  usage: 2,\n  notRunning: 3,\n  timeout: 4,\n} as const;\n\nexport async function loadConfigOrExit(configPath?: string): Promise<IResolvedCommanderConfig> {\n  const path = configPath ?? findCommanderConfig(process.cwd());\n  if (path == null) {\n    throw new CliExit(\n      EXIT.usage,\n      `no commander.config.{ts,mts,mjs} found upward from ${process.cwd()} (or pass --config <path>)`,\n    );\n  }\n  let file: Awaited<ReturnType<typeof loadCommanderConfigFile>>;\n  try {\n    file = await loadCommanderConfigFile(path);\n  } catch (error) {\n    throw new CliExit(EXIT.usage, (error as Error).message);\n  }\n  const { resolved, errors } = validateCommanderConfig(file.raw, {\n    configPath: file.configPath,\n    configDir: file.configDir,\n  });\n  if (resolved == null) {\n    throw new CliExit(\n      EXIT.usage,\n      `config validation failed:\\n${errors.map((line) => `  - ${line}`).join(\"\\n\")}`,\n    );\n  }\n  return resolved;\n}\n","// Shared command plumbing: the per-invocation context and selection resolution with the\n// plan's safety rules — bare `up` falls back to `defaultSelection` (or prints suites read-only);\n// bare `down`/`restart`/`logs`/`run` can never mean an accidental `--all`.\n\nimport { type IFlagSelection, resolveFlags } from \"../config/flags\";\nimport { type IResolvedSelection, resolveSelection } from \"../config/resolve\";\nimport type { IResolvedCommanderConfig, IResolvedCommanderProcess } from \"../config/types\";\nimport type { ISavedFilter } from \"../protocol/savedFilters\";\nimport type { ICliArgs } from \"./args\";\nimport { CliExit, EXIT } from \"./load\";\nimport type { IOut } from \"./out\";\n\nexport interface ICommandContext {\n  args: ICliArgs;\n  out: IOut;\n  config: IResolvedCommanderConfig;\n  /** Saved filters, read up front only when an `@pin` term is present. */\n  pins?: readonly ISavedFilter[];\n  /** Set by commands that booted the daemon this run — cli.ts hard-exits on it (interop tie). */\n  spawnedDaemon?: boolean;\n  /**\n   * Set by commands that own live child processes. `--timeout` walks it before its hard exit, so\n   * a wall-clock bound STOPS the trees it started rather than orphaning them for the next reap.\n   */\n  onTimeout?: () => Promise<void>;\n}\n\n/**\n * The bare-selection guard on its own. It is pure argv, so commands report it BEFORE looking for\n * a daemon — `down` with no selection is a usage error whether or not a daemon is running.\n */\nexport function requireSelectionTerms(ctx: ICommandContext): void {\n  if (ctx.args.positionals.length > 0 || ctx.args.flags.get(\"--all\") === true) return;\n  throw new CliExit(\n    EXIT.usage,\n    `${ctx.args.command} requires a selection (ids, suite, @pin, tag=val) or --all`,\n  );\n}\n\nexport function selectOrExit(\n  ctx: ICommandContext,\n  options: {\n    bare: \"default\" | \"required\";\n    /** Live ids the config no longer declares — see `resolveSelection`'s `extraIds` (M1). */\n    extraIds?: readonly string[];\n  },\n): IResolvedSelection {\n  const { args, config } = ctx;\n  let terms = args.positionals;\n  if (args.flags.get(\"--all\") === true) terms = [...terms, \"all\"];\n  if (terms.length === 0) {\n    if (options.bare === \"default\" && config.defaultSelection != null) {\n      terms = [config.defaultSelection];\n    } else if (options.bare === \"default\") {\n      const suites = Object.keys(config.suites);\n      throw new CliExit(\n        EXIT.usage,\n        `bare ${args.command}: the config has no defaultSelection. ` +\n          `Suites: ${suites.length > 0 ? suites.join(\", \") : \"(none)\"} — or name ids, tag=val, --all`,\n      );\n    } else {\n      requireSelectionTerms(ctx);\n    }\n  }\n  const result = resolveSelection(config, terms, {\n    extraIds: options.extraIds ?? [],\n    any: args.flags.get(\"--any\") === true,\n    // Stopping and tailing must reach whatever is running; only a START refuses to sweep up optIn.\n    purpose: args.command === \"down\" || args.command === \"logs\" ? \"address\" : \"start\",\n    pins: ctx.pins ?? [],\n  });\n  if (!result.ok) throw new CliExit(EXIT.usage, result.errors.join(\"\\n\"));\n  return result.selection;\n}\n\n/**\n * The one process a per-process option (`--with`, `-- args`) applies to: the selection must be\n * exactly its id — a flag set means nothing to a suite or a tag.\n */\nexport function singleProcessOrExit(\n  ctx: ICommandContext,\n  option: string,\n): IResolvedCommanderProcess {\n  const [term, ...rest] = ctx.args.positionals;\n  const definition = ctx.config.processes.find((proc) => proc.id === term);\n  if (definition == null || rest.length > 0 || ctx.args.flags.has(\"--all\")) {\n    throw new CliExit(\n      EXIT.usage,\n      `${option} applies to one process — select it by its id alone ` +\n        `(\\`${ctx.args.command} <id> ${option} …\\`)`,\n    );\n  }\n  return definition;\n}\n\n/** `--with a --with b` / `--with a,b`, resolved against the selected process's declared flags. */\nexport function flagsOrExit(ctx: ICommandContext): (IFlagSelection & { id: string }) | null {\n  const raw = ctx.args.repeated.get(\"--with\") ?? [];\n  if (raw.length === 0) return null;\n  const definition = singleProcessOrExit(ctx, \"--with\");\n  const names = raw.flatMap((value) => value.split(\",\")).filter((name) => name !== \"\");\n  const resolved = resolveFlags(definition, names);\n  if (\"error\" in resolved) throw new CliExit(EXIT.usage, resolved.error);\n  return { id: definition.id, ...resolved };\n}\n\n/** Suite stagger for a start: the widest stagger among the suites named in the terms. */\nexport function staggerFor(config: IResolvedCommanderConfig, terms: readonly string[]): number {\n  let stagger = 0;\n  for (const term of terms) {\n    const suite = config.suites[term];\n    if (suite != null) stagger = Math.max(stagger, suite.staggerMs);\n  }\n  return stagger;\n}\n","import { ETransportShape } from \"../Connect/transportRuntime.types\";\nimport type { TFrame } from \"./Carrier.types\";\n\n/** Neutral lifecycle surface driven by any duplex server transport. */\nexport interface IDuplexConnectionRouter<TConn> {\n  receive(connection: TConn, frame: TFrame): void;\n  drop(connection: TConn): void;\n}\n\n/** Optional persisted attachment access for hibernatable connections. */\nexport interface IAcceptorAttachmentStore<TConn> {\n  getConnections: () => TConn[];\n  read: (connection: TConn) => unknown;\n  write: (connection: TConn, value: unknown) => void;\n}\n\nexport interface IDuplexCarrierLifecycle<TConn> {\n  receive(connection: TConn, frame: TFrame): void;\n  drop(connection: TConn): void;\n  /** @internal Activated by a serving host. */\n  _activate(router: IDuplexConnectionRouter<TConn>): void;\n  /** @internal Permanently release lifecycle bookkeeping. */\n  _dispose?(): void;\n}\n\nexport type TInboundFrameLimitReason = \"frame_bytes\" | \"message_rate\";\n\nexport interface IInboundFrameLimits<TConn> {\n  maxFrameBytes?: number;\n  rate?: { maxMessages: number; windowMs: number };\n  onExceeded: (connection: TConn, reason: TInboundFrameLimitReason) => void;\n}\n\n/** Build the inert lifecycle slot shared by duplex acceptor carrier factories. */\nexport function createDuplexCarrierLifecycle<TConn>(\n  limits?: IInboundFrameLimits<TConn>,\n): IDuplexCarrierLifecycle<TConn> {\n  let router: IDuplexConnectionRouter<TConn> | undefined;\n  let disposed = false;\n  const windows = new Map<TConn, { count: number; startedAt: number }>();\n  const maxFrameBytes = limits?.maxFrameBytes;\n  const rate = limits?.rate;\n  if (maxFrameBytes != null && (!Number.isSafeInteger(maxFrameBytes) || maxFrameBytes <= 0)) {\n    throw new Error(\"maxFrameBytes must be a positive safe integer\");\n  }\n  if (\n    rate != null &&\n    (!Number.isSafeInteger(rate.maxMessages) ||\n      rate.maxMessages <= 0 ||\n      !Number.isSafeInteger(rate.windowMs) ||\n      rate.windowMs <= 0)\n  ) {\n    throw new Error(\"inbound rate limits must be positive safe integers\");\n  }\n\n  const frameBytes = (frame: TFrame): number =>\n    typeof frame === \"string\"\n      ? new TextEncoder().encode(frame).byteLength\n      : frame instanceof ArrayBuffer\n        ? frame.byteLength\n        : frame.byteLength;\n\n  return {\n    receive(connection, frame) {\n      if (disposed) return;\n      if (router == null) {\n        throw new Error(\"acceptor carrier not served yet — activate it before feeding frames\");\n      }\n      if (maxFrameBytes != null && frameBytes(frame) > maxFrameBytes) {\n        limits?.onExceeded(connection, \"frame_bytes\");\n        return;\n      }\n      if (rate != null) {\n        const now = Date.now();\n        let window = windows.get(connection);\n        if (window == null || now - window.startedAt >= rate.windowMs) {\n          window = { count: 0, startedAt: now };\n          windows.set(connection, window);\n        }\n        window.count += 1;\n        if (window.count > rate.maxMessages) {\n          limits?.onExceeded(connection, \"message_rate\");\n          return;\n        }\n      }\n      router.receive(connection, frame);\n    },\n    drop(connection) {\n      if (disposed) return;\n      windows.delete(connection);\n      router?.drop(connection);\n    },\n    _activate(liveRouter) {\n      if (disposed) throw new Error(\"acceptor carrier already disposed\");\n      router = liveRouter;\n    },\n    _dispose() {\n      if (disposed) return;\n      disposed = true;\n      router = undefined;\n      windows.clear();\n    },\n  };\n}\n\n/** A persistent, push-capable carrier served by a `WireAcceptor`. */\nexport interface IDuplexAcceptorCarrier<TConn = unknown> extends IDuplexCarrierLifecycle<TConn> {\n  readonly shape: ETransportShape.duplex;\n  secure?: boolean;\n  send: (connection: TConn, frame: TFrame) => void;\n  /** Close a live connection; the server uses it to end a connection whose handshake it refused. */\n  close?: (connection: TConn) => void;\n  upgrade?: (request: Request, url: URL) => Response | Promise<Response>;\n  isUpgrade?: (request: Request, url: URL) => boolean;\n  attachmentStore?: IAcceptorAttachmentStore<TConn>;\n  readonly carrierLabel: string;\n}\n\nexport interface IWsAcceptorCarrierOptions<TConn> {\n  secure?: boolean;\n  send: (connection: TConn, frame: TFrame) => void;\n  /** Close a live connection (e.g. `(ws) => ws.close(1008)`), used after a refused handshake. */\n  close?: (connection: TConn) => void;\n  upgrade?: (request: Request, url: URL) => Response | Promise<Response>;\n  isUpgrade?: (request: Request, url: URL) => boolean;\n  attachmentStore?: IAcceptorAttachmentStore<TConn>;\n  carrierLabel?: string;\n  inboundLimits?: IInboundFrameLimits<TConn>;\n}\n\n/** Build a WebSocket acceptor carrier for `serveWire` or `serveChannel`. */\nexport function wsAcceptorCarrier<TConn = WebSocket>(\n  options: IWsAcceptorCarrierOptions<TConn>,\n): IDuplexAcceptorCarrier<TConn> {\n  return {\n    ...createDuplexCarrierLifecycle<TConn>(options.inboundLimits),\n    shape: ETransportShape.duplex,\n    carrierLabel: options.carrierLabel ?? \"ws\",\n    secure: options.secure,\n    send: options.send,\n    close: options.close,\n    upgrade: options.upgrade,\n    isUpgrade: options.isUpgrade ?? ((request) => request.headers.get(\"Upgrade\") === \"websocket\"),\n    attachmentStore: options.attachmentStore,\n  };\n}\n","import type { NiceError } from \"../NiceError/NiceError\";\n\n/**\n * `nice-error`'s own internal failure modes.\n *\n * These are thrown as real `NiceError`s (domain `err_nice_error`, built in\n * `nice_core_errors`) so they are observable / pattern-matchable like any other\n * error. The builder is injected via {@link _setInternalErrorBuilder} at module\n * init rather than imported directly, because `NiceError` / `NiceErrorDomain`\n * throw these — a direct import would form a load-time cycle (a domain can't be\n * built before the `NiceError` class it depends on has finished declaring).\n *\n * This module imports nothing at runtime, so it is a safe leaf for both sides.\n */\nexport enum EErrId_NiceErrorInternal {\n  context_unhydrated = \"context_unhydrated\",\n  hydrate_domain_mismatch = \"hydrate_domain_mismatch\",\n  from_context_empty = \"from_context_empty\",\n  handler_returned_promise_in_sync = \"handler_returned_promise_in_sync\",\n}\n\nexport interface TInternalErrorContext {\n  [EErrId_NiceErrorInternal.context_unhydrated]: { id: string };\n  [EErrId_NiceErrorInternal.hydrate_domain_mismatch]: { expected: string; received: string };\n  [EErrId_NiceErrorInternal.from_context_empty]: undefined;\n  [EErrId_NiceErrorInternal.handler_returned_promise_in_sync]: { identifier: string };\n}\n\ntype TInternalErrorBuilder = (kind: EErrId_NiceErrorInternal, ctx: unknown) => NiceError;\n\nlet _build: TInternalErrorBuilder | undefined;\n\n/** Wired once by `nice_core_errors` at module init to avoid an import cycle. */\nexport function _setInternalErrorBuilder(fn: TInternalErrorBuilder): void {\n  _build = fn;\n}\n\n/**\n * Build (for throwing) one of `nice-error`'s internal errors as a `NiceError`.\n * Falls back to a plain `Error` only in the unusual case where it's called before\n * `nice_core_errors` has registered the builder.\n */\nexport function internalNiceError<K extends EErrId_NiceErrorInternal>(\n  kind: K,\n  ctx: TInternalErrorContext[K],\n): NiceError | Error {\n  if (_build != null) return _build(kind, ctx);\n  return new Error(`[nice-error:${kind}]${ctx != null ? ` ${JSON.stringify(ctx)}` : \"\"}`);\n}\n","import type { INiceErrorDomainProps } from \"../NiceError/NiceError.types\";\n\n/**\n * Read the domain props (`domain` / `allDomains`) off a `NiceError` or its `def`.\n *\n * A `NiceError`'s `def` is `Omit<ERR_DEF, \"schema\">`, so widening it to the full\n * `INiceErrorDomainProps` for domain/ancestry checks needs one cast. This helper is\n * the single place that cast lives, instead of scattering it across every guard.\n */\nexport function getErrorDomainProps(holder: { def: unknown }): INiceErrorDomainProps {\n  return holder.def as unknown as INiceErrorDomainProps;\n}\n","export function jsErrorOrCastJsError(error: unknown, logMessage = true): Error {\n  if (error instanceof Error) {\n    return Object.assign(error, {\n      message: error.message,\n    });\n  }\n\n  const message =\n    (error as Error | undefined)?.message ??\n    (typeof error === \"string\" ? error : \"No error message found\");\n\n  if (logMessage) {\n    console.error(`An unknown and unstructured error was thrown: ${message}`, error);\n  }\n\n  return {\n    ...new Error(message),\n    ...(error as Error | undefined),\n  };\n}\n","","/**\n * Injectable logger seam.\n *\n * `nice-error` ships zero hard runtime deps and must run anywhere (browser,\n * Workers, edge, RTC). Instead of bundling a Node-oriented logger, it logs\n * through this small interface, defaulting to the universal `console`. Consumers\n * can route diagnostics into their own logger (tslog / pino / a devtools sink)\n * via {@link setNiceErrorLogger}.\n */\nexport interface INiceErrorLogger {\n  warn(message: string, meta?: unknown): void;\n  debug(message: string, meta?: unknown): void;\n  error(message: string, meta?: unknown): void;\n}\n\nconst consoleLogger: INiceErrorLogger = {\n  warn: (message, meta) =>\n    meta !== undefined ? console.warn(message, meta) : console.warn(message),\n  debug: (message, meta) =>\n    meta !== undefined ? console.debug(message, meta) : console.debug(message),\n  error: (message, meta) =>\n    meta !== undefined ? console.error(message, meta) : console.error(message),\n};\n\nlet activeLogger: INiceErrorLogger = consoleLogger;\n\n/** Replace the logger `nice-error` uses for internal diagnostics. */\nexport function setNiceErrorLogger(logger: INiceErrorLogger): void {\n  activeLogger = logger;\n}\n\n/** The logger `nice-error` currently logs through (defaults to `console`). */\nexport function getNiceErrorLogger(): INiceErrorLogger {\n  return activeLogger;\n}\n","import { version } from \"../../package.json\";\nimport { getNiceErrorLogger } from \"./logger\";\n\n/** This package's version, read from its manifest when the package is built. */\nexport const NICE_ERROR_VERSION: string = version;\n\n// Every loaded copy of this package reads and writes this slot, whatever its version, so\n// neither the key nor the plain list of version strings under it may change.\nconst LOADED_VERSIONS_KEY = Symbol.for(\"@nice-code/error/versions\");\n\nconst LOCKSTEP_RULE =\n  \"Every @nice-code/* package must be on the same version (the lockstep rule): an error built \" +\n  \"by one copy of @nice-code/error fails `instanceof NiceError` in another. \" +\n  \"`nice-code-lockstep`, shipped in @nice-code/util, lists the versions installed.\";\n\n/**\n * Records `version` as loaded in `scope`, and warns when a different version of this package\n * is already there. Runs when the package loads, so it must never throw.\n */\nexport function registerLoadedVersion(\n  version: string,\n  scope: object = globalThis,\n  warn: (message: string) => void = (message) => console.warn(message),\n): void {\n  try {\n    const loaded: unknown = Reflect.get(scope, LOADED_VERSIONS_KEY);\n\n    if (loaded === undefined) {\n      Reflect.set(scope, LOADED_VERSIONS_KEY, [version]);\n      return;\n    }\n\n    // The ESM and CJS builds of one version both load in some setups; that is one version.\n    if (!Array.isArray(loaded) || loaded.includes(version)) return;\n\n    const others = loaded.filter((other) => typeof other === \"string\");\n    loaded.push(version);\n    warn(\n      `[@nice-code/error] Version ${version} was loaded beside ${others.join(\", \")}. ${LOCKSTEP_RULE}`,\n    );\n  } catch {\n    // A scope that cannot be read or written leaves nothing to compare against.\n  }\n}\n\nlet warnedOfUnversionedCopy = false;\n\n/**\n * Warns, once, that an error arrived from a copy of this package that carries no brand: one\n * released before copies recorded their version, which {@link registerLoadedVersion} cannot see.\n */\nexport function warnOfUnversionedCopy(): void {\n  if (warnedOfUnversionedCopy) return;\n  warnedOfUnversionedCopy = true;\n  try {\n    getNiceErrorLogger().warn(\n      `[@nice-code/error] Version ${NICE_ERROR_VERSION} received an error built by an older ` +\n        `copy of this package, one too old to report its version. ${LOCKSTEP_RULE}`,\n    );\n  } catch {\n    // Reached from castNiceError, which must not throw because a logger did.\n  }\n}\n","export const DUR_OBJ_PACK_PREFIX = \"NE_DUROBJ[[\";\nexport const DUR_OBJ_PACK_SUFFIX = \"]]NE_DUROBJ\";\n\n/**\n * The domain of the generic wrapper `castNiceError` produces for anything that\n * wasn't already a `NiceError` (native throws, error-like objects, nullish,\n * primitives). `NiceError.isUnhandled` is defined as \"belongs to this domain\" —\n * i.e. an error we never accounted for and had to wrap. Kept here (not imported\n * from `nice_core_errors`) so `NiceError` can reference it without an import cycle.\n */\nexport const ERR_CAST_NOT_NICE_DOMAIN = \"err_cast_not_nice\";\n","import type { NiceError } from \"../../NiceError/NiceError\";\nimport { DUR_OBJ_PACK_PREFIX, DUR_OBJ_PACK_SUFFIX } from \"../../NiceError/nice_error.static\";\nimport { EErrorPackType } from \"./packError.enums\";\n\nexport const causePack = <E extends NiceError<any, any>>(error: E): E => {\n  error._packedState = { cause: error.cause, packedAs: EErrorPackType.cause_pack };\n  error.cause = `${DUR_OBJ_PACK_PREFIX}${JSON.stringify(error.toJsonObject())}${DUR_OBJ_PACK_SUFFIX}`;\n  return error;\n};\n","import type { NiceError } from \"../../NiceError/NiceError\";\nimport { DUR_OBJ_PACK_PREFIX, DUR_OBJ_PACK_SUFFIX } from \"../../NiceError/nice_error.static\";\nimport { EErrorPackType } from \"./packError.enums\";\n\nexport const msgPack = <E extends NiceError<any, any>>(error: E): E => {\n  error._packedState = { message: error.cleanMessage, packedAs: EErrorPackType.msg_pack };\n  error.message = `${DUR_OBJ_PACK_PREFIX}${JSON.stringify(error.toJsonObject())}${DUR_OBJ_PACK_SUFFIX}`;\n  return error;\n};\n","import type { NiceError } from \"../../NiceError/NiceError\";\nimport { causePack } from \"./causePack\";\nimport { msgPack } from \"./msgPack\";\nimport type { EErrorPackType } from \"./packError.enums\";\n\nexport const packError = <E extends NiceError<any, any>>(\n  error: E,\n  packType: EErrorPackType = \"msg_pack\" as EErrorPackType,\n): E => {\n  if (packType === \"no_pack\") {\n    return error;\n  }\n  if (packType === \"msg_pack\") {\n    return msgPack(error);\n  }\n  return causePack(error);\n};\n","/**\n * JSON-safe serialization of an error `cause` (and `AggregateError.errors`),\n * walked to a bounded depth so a nested `cause` chain survives transport without\n * dragging along non-serializable values or risking unbounded / circular nesting.\n */\n\nconst DEFAULT_CAUSE_DEPTH = 4;\n\nexport interface ISerializedErrorCause {\n  name?: string | undefined;\n  message?: string | undefined;\n  stack?: string | undefined;\n  cause?: unknown;\n  /** Present for `AggregateError` — its serialized sub-errors. */\n  errors?: unknown[];\n}\n\nfunction isErrorLike(\n  value: unknown,\n): value is { name?: string; message?: string; stack?: string; cause?: unknown; errors?: unknown } {\n  if (value instanceof Error) return true;\n  if (typeof value !== \"object\" || value == null) return false;\n  const o = value as Record<string, unknown>;\n  return typeof o[\"name\"] === \"string\" && typeof o[\"message\"] === \"string\";\n}\n\n/**\n * Convert an arbitrary `cause` value into something JSON-safe.\n * - Errors / error-like objects → `{ name, message, stack, cause?, errors? }`,\n *   recursing into `cause` and `AggregateError.errors` until `depth` runs out.\n * - Other values → returned as-is when JSON-serializable, else `String(value)`.\n */\nexport function serializeErrorCause(value: unknown, depth: number = DEFAULT_CAUSE_DEPTH): unknown {\n  if (value == null) return value;\n\n  if (isErrorLike(value)) {\n    const out: ISerializedErrorCause = {\n      name: value.name,\n      message: value.message,\n      stack: value.stack,\n    };\n\n    const aggregate = (value as { errors?: unknown }).errors;\n    if (Array.isArray(aggregate)) {\n      out.errors = depth > 0 ? aggregate.map((sub) => serializeErrorCause(sub, depth - 1)) : [];\n    }\n\n    if (value.cause != null && depth > 0) {\n      out.cause = serializeErrorCause(value.cause, depth - 1);\n    }\n\n    return out;\n  }\n\n  try {\n    JSON.stringify(value);\n    return value;\n  } catch {\n    return String(value);\n  }\n}\n","import { EErrId_NiceErrorInternal, internalNiceError } from \"../internal/internal_errors\";\nimport type { NiceErrorDomain } from \"../NiceErrorDomain/NiceErrorDomain\";\nimport type { NiceErrorHandler } from \"../NiceErrorHandler/NiceErrorHandler\";\nimport type { IHandleErrorOptions } from \"../NiceErrorHandler/NiceErrorHandler.types\";\nimport { getErrorDomainProps } from \"../utils/getErrorDomainProps\";\nimport { jsErrorOrCastJsError } from \"../utils/jsErrorOrCastJsError\";\nimport { NICE_ERROR_VERSION, registerLoadedVersion } from \"../utils/loadedVersions\";\nimport { getNiceErrorLogger } from \"../utils/logger\";\nimport { packError } from \"../utils/packError/packError\";\nimport { EErrorPackType } from \"../utils/packError/packError.enums\";\nimport { serializeErrorCause } from \"../utils/serializeErrorCause\";\nimport { EContextSerializedState } from \"./NiceError.enums\";\nimport {\n  type INiceErrorDomainProps,\n  type INiceErrorJsonObject,\n  type INiceErrorStructuredLog,\n  type IRegularErrorJsonObject,\n  type TDomainNiceErrorId,\n  type TErrorDataForIdMap,\n  type TErrorReconciledData,\n  type TExtractContextType,\n  type TNiceErrorSchema,\n  type TSchemaNiceErrorId,\n  type TSerializedContextState,\n  type TSerializedErrorDataMap,\n  type TUnknownNiceErrorDef,\n} from \"./NiceError.types\";\nimport type { NiceErrorHydrated } from \"./NiceErrorHydrated\";\nimport { ERR_CAST_NOT_NICE_DOMAIN } from \"./nice_error.static\";\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\ntype ContextOf<S extends TNiceErrorSchema, K extends keyof S> = TExtractContextType<S[K]>;\n\n// Set on the prototype of every copy's class, so one copy can recognize another's instances.\n// Copies of other versions read it too, so the key must not change.\nconst NICE_ERROR_BRAND = Symbol.for(\"@nice-code/error\");\n\n// ---------------------------------------------------------------------------\n// Constructor options\n// ---------------------------------------------------------------------------\n\n/** Full-featured construction from NiceErrorDomain.fromId / fromContext. */\nexport interface INiceErrorOptions<\n  ERR_DEF extends INiceErrorDomainProps,\n  ID extends TDomainNiceErrorId<ERR_DEF> = TDomainNiceErrorId<ERR_DEF>,\n> {\n  def: Omit<ERR_DEF, \"schema\">;\n  /** Primary id is first entry in ids. */\n  ids: ID[];\n  /** All active ids with their messages, http status codes, and context state. */\n  errorData: TErrorDataForIdMap<ERR_DEF[\"schema\"]>;\n  message: string;\n  httpStatusCode?: number;\n  originError?: IRegularErrorJsonObject | undefined;\n  timeCreated?: number;\n}\n\n// ---------------------------------------------------------------------------\n// NiceError\n// ---------------------------------------------------------------------------\n\nexport class NiceError<\n  ERR_DEF extends INiceErrorDomainProps = TUnknownNiceErrorDef,\n  /**\n   * Union of active error-id keys.\n   * - After `fromId(id)`: exactly one key.\n   * - After `fromContext({...})`: a union of all supplied keys.\n   * - After `hasOneOfIds([a,b])`: narrows to that subset.\n   * - Default (bare construction / castNiceError): `TUnknownNiceErrorId`.\n   */\n  ACTIVE_IDS extends TDomainNiceErrorId<ERR_DEF> = TDomainNiceErrorId<ERR_DEF>,\n> extends Error {\n  override readonly name = \"NiceError\" as const;\n\n  readonly def: Omit<ERR_DEF, \"schema\">;\n  /** Primary id is first entry in ids. */\n  readonly ids: ACTIVE_IDS[];\n  readonly httpStatusCode: number;\n  readonly timeCreated: number;\n  readonly cleanMessage: string;\n  originError?: IRegularErrorJsonObject;\n\n  _packedState?:\n    | { packedAs: EErrorPackType.cause_pack; cause: unknown }\n    | { packedAs: EErrorPackType.msg_pack; message: string }\n    | undefined;\n\n  /** Internal: all active id → reconciled data pairs. */\n  protected readonly _errorDataMap: TErrorDataForIdMap<ERR_DEF[\"schema\"]>;\n\n  // -------------------------------------------------------------------------\n  // Constructor\n  // -------------------------------------------------------------------------\n\n  constructor(options: INiceErrorOptions<ERR_DEF, ACTIVE_IDS>) {\n    const messagePure = options.message;\n    const prefixedMessage = `[${options.def.domain}](${options.ids.join(\",\")}) ${messagePure}`;\n\n    super(prefixedMessage);\n\n    this.cleanMessage = messagePure;\n    this.def = options.def;\n    this.ids = options.ids;\n    // A record off the wire may carry no errorData; every reader below assumes a map.\n    this._errorDataMap = options.errorData ?? {};\n    this.httpStatusCode = options.httpStatusCode ?? 500;\n\n    if (options.originError != null) {\n      this.originError = options.originError;\n    }\n\n    this.timeCreated = options.timeCreated ?? Date.now();\n  }\n\n  // -------------------------------------------------------------------------\n  // isUnhandled — intrinsic \"we never accounted for this\" signal\n  // -------------------------------------------------------------------------\n\n  /**\n   * `true` when this error is the generic wrapper `castNiceError` produces for a\n   * value that wasn't already a `NiceError` (native throw, error-like object,\n   * nullish, primitive) — i.e. an error that fell through without being handled\n   * by any defined domain.\n   *\n   * Defined as \"belongs to the `err_cast_not_nice` domain\", so it is stable across\n   * a serialization round-trip (the domain travels on the wire) and is `false` for\n   * every domain-defined error, including a real `NiceError` reconstructed from JSON.\n   */\n  get isUnhandled(): boolean {\n    return this.def.domain === ERR_CAST_NOT_NICE_DOMAIN;\n  }\n\n  // -------------------------------------------------------------------------\n  // hasId — narrows ACTIVE_IDS to exactly ID\n  // -------------------------------------------------------------------------\n\n  /**\n   * Type guard: returns `true` if this error was created with (or contains) the\n   * given `id`. After the guard, `getContext(id)` will be strongly typed.\n   */\n  hasId<ID extends keyof ERR_DEF[\"schema\"] & string>(id: ID): this is NiceError<ERR_DEF, ID> {\n    return id in this._errorDataMap;\n  }\n\n  // -------------------------------------------------------------------------\n  // hasOneOfIds — narrows ACTIVE_IDS to the supplied subset\n  // -------------------------------------------------------------------------\n\n  /**\n   * Returns `true` if this error contains **at least one** of the supplied ids.\n   * Narrows `ACTIVE_IDS` to the matching subset of `IDS`.\n   */\n  hasOneOfIds<IDS extends ReadonlyArray<keyof ERR_DEF[\"schema\"] & string>>(\n    ids: IDS,\n  ): this is NiceError<ERR_DEF, IDS[number]> {\n    return ids.some((id) => id in this._errorDataMap);\n  }\n\n  // -------------------------------------------------------------------------\n  // get hasMultiple\n  // -------------------------------------------------------------------------\n\n  /** `true` when this error was created with more than one id (via `fromContext`). */\n  get hasMultiple(): boolean {\n    return Object.keys(this._errorDataMap).length > 1;\n  }\n\n  // -------------------------------------------------------------------------\n  // getIds\n  // -------------------------------------------------------------------------\n\n  /** Returns all active error ids on this instance. */\n  getIds(): Array<ACTIVE_IDS> {\n    return Object.keys(this._errorDataMap) as Array<ACTIVE_IDS>;\n  }\n\n  // -------------------------------------------------------------------------\n  // getContext — strongly typed per ACTIVE_IDS\n  // -------------------------------------------------------------------------\n\n  /**\n   * Returns the typed context value for the given error id.\n   *\n   * TypeScript will only allow you to call this with an id that is part of\n   * `ACTIVE_IDS` (i.e. an id confirmed via `hasId` / `hasOneOfIds`, or passed\n   * to `fromId` / `fromContext`).\n   *\n   * @throws If the context is in the `\"unhydrated\"` state — the error was\n   * reconstructed from a JSON payload and its context has a custom serializer\n   * that hasn't been run yet. Call `niceErrorDefined.hydrate(error)` first.\n   */\n  getContext<ID extends ACTIVE_IDS>(id: ID): ContextOf<ERR_DEF[\"schema\"], ID> {\n    const errorData = this._errorDataMap[id];\n    const state = errorData?.contextState;\n\n    if (state == null) {\n      return undefined as ContextOf<ERR_DEF[\"schema\"], ID>;\n    }\n\n    if (state.kind === \"unhydrated\") {\n      throw internalNiceError(EErrId_NiceErrorInternal.context_unhydrated, { id: String(id) });\n    }\n\n    // \"raw_unset\" | \"hydrated\" — both carry `value`\n    return state.value as ContextOf<ERR_DEF[\"schema\"], ID>;\n  }\n\n  // -------------------------------------------------------------------------\n  // getErrorDataForId\n  // -------------------------------------------------------------------------\n\n  getErrorDataForId<ID extends ACTIVE_IDS>(\n    id: ID,\n  ): TErrorReconciledData<ERR_DEF[\"schema\"], ID> | undefined {\n    return this._errorDataMap[id] as TErrorReconciledData<ERR_DEF[\"schema\"], ID> | undefined;\n  }\n\n  // -------------------------------------------------------------------------\n  // withOriginError\n  // -------------------------------------------------------------------------\n\n  withOriginError(error: unknown): this {\n    this.originError = jsErrorOrCastJsError(error);\n    // When the error is cause-packed, `this.cause` holds the packed JSON string.\n    // Overwriting it would destroy the packed data and break boundary reconstruction.\n    // In that case we skip mutating `cause` — the packed data stays intact.\n    if (this._packedState?.packedAs !== EErrorPackType.cause_pack) {\n      this.cause = this.originError;\n    }\n    return this;\n  }\n\n  // -------------------------------------------------------------------------\n  // matches — fingerprint comparison\n  // -------------------------------------------------------------------------\n\n  /**\n   * Returns `true` if `other` has the same domain and the exact same set of\n   * active error ids as this error (order-independent).\n   *\n   * Useful for deduplication, retry logic, and asserting that two errors\n   * represent the same \"kind\" of problem without comparing context values.\n   *\n   * ```ts\n   * const a = err_auth.fromId(\"invalid_credentials\", { username: \"alice\" });\n   * const b = err_auth.fromId(\"invalid_credentials\", { username: \"bob\" });\n   * a.matches(b); // true  — same domain + same id set\n   *\n   * const c = err_auth.fromId(\"account_locked\");\n   * a.matches(c); // false — same domain, different id\n   * ```\n   */\n  matches(other: NiceError<any, any>): boolean {\n    const myDef = getErrorDomainProps(this);\n    const otherDef = getErrorDomainProps(other);\n    if (myDef.domain !== otherDef.domain) return false;\n\n    const myIds = this.getIds().map(String).sort();\n    const otherIds = other.getIds().map(String).sort();\n    if (myIds.length !== otherIds.length) return false;\n    return myIds.every((id, i) => id === otherIds[i]);\n  }\n\n  // -------------------------------------------------------------------------\n  // toJsonObject\n  // -------------------------------------------------------------------------\n\n  toJsonObject(): INiceErrorJsonObject<ERR_DEF> {\n    const originError: IRegularErrorJsonObject | undefined = this.originError\n      ? {\n          name: this.originError.name,\n          message: (this.originError as any).cleanMessage ?? this.originError.message,\n          stack: this.originError.stack,\n          // JSON-safe, depth-bounded cause chain (and AggregateError sub-errors)\n          // so nested causes survive transport without circular / non-serializable data.\n          cause: serializeErrorCause(this.originError.cause),\n          ...(Array.isArray((this.originError as { errors?: unknown }).errors)\n            ? {\n                errors: (this.originError as unknown as { errors: unknown[] }).errors.map((e) =>\n                  serializeErrorCause(e),\n                ),\n              }\n            : {}),\n        }\n      : undefined;\n\n    const def = {\n      domain: this.def.domain,\n      allDomains: this.def.allDomains,\n    } as Omit<ERR_DEF, \"schema\">;\n\n    if (this.def.defaultHttpStatusCode != null) {\n      def[\"defaultHttpStatusCode\"] = this.def.defaultHttpStatusCode;\n    }\n\n    if (this.def.defaultMessage != null) {\n      def[\"defaultMessage\"] = this.def.defaultMessage;\n    }\n\n    // Downgrade \"hydrated\" → \"unhydrated\" so the serialized form never carries a\n    // stale `\"hydrated\"` discriminant that would survive a JSON round-trip.\n    const errorData: TSerializedErrorDataMap<ERR_DEF[\"schema\"]> = {};\n\n    for (const rawId of Object.keys(this._errorDataMap)) {\n      const id = rawId as TSchemaNiceErrorId<ERR_DEF[\"schema\"]>;\n      const data = this._errorDataMap[id];\n      if (data == null) continue;\n\n      let contextState: TSerializedContextState<any>;\n\n      if (data.contextState.kind === EContextSerializedState.hydrated) {\n        // Drop `value` (may not be JSON-safe); keep `serialized` for later hydration.\n        contextState = {\n          kind: EContextSerializedState.unhydrated,\n          serialized: data.contextState.serialized,\n        };\n      } else {\n        contextState = data.contextState;\n      }\n\n      errorData[id] = {\n        contextState,\n        message: data.message,\n        httpStatusCode: data.httpStatusCode,\n        timeAdded: data.timeAdded,\n      };\n    }\n\n    return {\n      name: \"NiceError\",\n      def,\n      ids: this.ids,\n      errorData,\n      isUnhandled: this.isUnhandled,\n      message: this.cleanMessage,\n      httpStatusCode: this.httpStatusCode,\n      timeCreated: this.timeCreated,\n      ...(this.stack != null ? { stack: this.stack } : {}),\n      originError,\n    };\n  }\n\n  toJSON(): INiceErrorJsonObject<ERR_DEF> {\n    return this.toJsonObject();\n  }\n\n  /**\n   * The **wire form** — {@link toJsonObject} minus the server-only diagnostic fields (`stack`,\n   * `originError`) that disclose server internals and fatten the frame. Everything a peer needs to\n   * reconstruct a fully-typed error survives — ids, per-id context, rendered message, `isUnhandled`,\n   * and the domain definition — so `castNiceError` on the far side yields an error whose `getIds()`,\n   * `getContext()`, `message`, and `isUnknownOutcomeRejection(...)` all behave identically.\n   *\n   * Use this whenever an error crosses a trust/observability boundary to an untrusted peer (e.g. a\n   * realm reject frame fanned out to every client): the stack must not leave the process, and at\n   * high frequency (a cursor-write reject storm) the ~1.5 kB full form is mostly stack. Keep the\n   * complete {@link toJsonObject} for server-side logs and hooks.\n   */\n  toWireJsonObject(): INiceErrorJsonObject<ERR_DEF> {\n    const { stack: _stack, originError: _originError, ...wire } = this.toJsonObject();\n    return wire;\n  }\n\n  // -------------------------------------------------------------------------\n  // toStructuredLog — flat projection for telemetry / structured logging\n  // -------------------------------------------------------------------------\n\n  /**\n   * A flat, log-friendly object for telemetry / structured logging — distinct\n   * from {@link toJsonObject} (the wire form). Surfaces {@link isUnhandled} so a\n   * sink can separate \"an error we accounted for\" from \"one we didn't\".\n   */\n  toStructuredLog(): INiceErrorStructuredLog {\n    return {\n      domain: this.def.domain,\n      ids: this.getIds().map(String),\n      message: this.cleanMessage,\n      httpStatusCode: this.httpStatusCode,\n      isUnhandled: this.isUnhandled,\n      timeCreated: this.timeCreated,\n      ...(this.originError != null ? { originError: this.originError } : {}),\n    };\n  }\n\n  toJsonString(): string {\n    return JSON.stringify(this.toJsonObject());\n  }\n\n  toHttpResponse(): Response {\n    return new Response(this.toJsonString(), {\n      status: this.httpStatusCode,\n      headers: { \"Content-Type\": \"application/json\" },\n    });\n  }\n\n  // -------------------------------------------------------------------------\n  // hydrate — convenience delegation to NiceErrorDomain\n  // -------------------------------------------------------------------------\n\n  hydrate(definedNiceError: NiceErrorDomain<ERR_DEF>): NiceErrorHydrated<ERR_DEF, ACTIVE_IDS> {\n    return definedNiceError.hydrate(this);\n  }\n\n  // -------------------------------------------------------------------------\n  // handleWithSync — synchronous domain-dispatched error handling\n  // -------------------------------------------------------------------------\n\n  /**\n   * Iterates `cases` in order, finds the first whose domain matches this error\n   * (via `is()`), optionally further filters by active ids, hydrates the error,\n   * calls the handler, and returns `true`. Returns `false` if no case matched.\n   *\n   * Build cases with `forDomain` (any id in the domain) or `forIds` (specific\n   * id subset). Handlers are invoked synchronously — any returned Promise is\n   * not awaited. Use `handleWithAsync` when handlers are async.\n   *\n   * @example\n   * ```ts\n   * const handled = error.handleWith([\n   *   forIds(err_feature, [\"not_found\"], (h) => {\n   *     res.status(404).json({ missing: h.getContext(\"not_found\").resource });\n   *   }),\n   *   forDomain(err_feature, (h) => {\n   *     matchFirst(h, {\n   *       forbidden: ({ userId }) => res.status(403).json({ userId }),\n   *       _: () => res.status(500).end(),\n   *     });\n   *   }),\n   *   forDomain(err_service, (h) => {\n   *     res.status(h.httpStatusCode).json({ error: h.message });\n   *   }),\n   * ]);\n   * if (!handled) next(error);\n   * ```\n   */\n  handleWithSync<RD, R>(\n    handlerInput: NiceErrorHandler<RD, R> | ReadonlyArray<NiceErrorHandler<RD, R>>,\n    handlerOptions: IHandleErrorOptions = {},\n  ): R | RD | undefined {\n    const handlersArray: ReadonlyArray<NiceErrorHandler<RD, R>> = Array.isArray(handlerInput)\n      ? handlerInput\n      : [handlerInput];\n\n    for (const handler of handlersArray) {\n      const result = handler.handleErrorWithPromiseInspection(this, handlerOptions);\n      if (result.matched) {\n        if (result.isPromise) {\n          getNiceErrorLogger().warn(\n            internalNiceError(EErrId_NiceErrorInternal.handler_returned_promise_in_sync, {\n              identifier: result.target.identifier,\n            }).message,\n          );\n        }\n\n        return result.isPromise ? undefined : result.handlerResponse;\n      }\n    }\n\n    if (handlerOptions.throwOnUnhandled === true) throw this;\n    return undefined;\n  }\n\n  // -------------------------------------------------------------------------\n  // handleWithAsync — async domain-dispatched error handling\n  // -------------------------------------------------------------------------\n\n  /**\n   * Same matching logic as `handleWith`, but `await`s the handler's returned\n   * Promise before resolving. Use this when your handlers perform async work\n   * (database writes, HTTP calls, etc.).\n   *\n   * @example\n   * ```ts\n   * const handled = await error.handleWithAsync([\n   *   forDomain(err_payments, async (h) => {\n   *     await db.logFailedPayment(h);\n   *     await notifyOps(h.message);\n   *   }),\n   * ]);\n   * ```\n   */\n  async handleWithAsync<RD, R>(\n    handlerInput: NiceErrorHandler<RD, R> | ReadonlyArray<NiceErrorHandler<RD, R>>,\n    handlerOptions: IHandleErrorOptions = {},\n  ): Promise<R | RD | undefined> {\n    const handlersArray: ReadonlyArray<NiceErrorHandler<RD, R>> = Array.isArray(handlerInput)\n      ? handlerInput\n      : [handlerInput];\n\n    for (const handler of handlersArray) {\n      const result = handler.handleErrorWithPromiseInspection(this, handlerOptions);\n\n      if (result.matched) {\n        return result.isPromise ? await result.handlerPromise : result.handlerResponse;\n      }\n    }\n\n    if (handlerOptions.throwOnUnhandled === true) throw this;\n    return undefined;\n  }\n\n  get isPacked(): boolean {\n    return this._packedState != null;\n  }\n\n  pack(packType: EErrorPackType = \"msg_pack\" as EErrorPackType): this {\n    if (this.isPacked) return this;\n    return packError(this, packType);\n  }\n\n  unpack(): this {\n    if (this._packedState == null) return this;\n\n    if (this._packedState.packedAs === EErrorPackType.msg_pack) {\n      this.message = this._packedState.message;\n    }\n\n    if (this._packedState.packedAs === EErrorPackType.cause_pack) {\n      this.cause = this._packedState.cause;\n    }\n\n    this._packedState = undefined;\n    delete this._packedState;\n\n    return this;\n  }\n}\n\nObject.defineProperty(NiceError.prototype, NICE_ERROR_BRAND, { value: true });\n\nregisterLoadedVersion(NICE_ERROR_VERSION);\n\n/**\n * Returns `true` if `value` is a `NiceError` built by any loaded copy of `@nice-code/error`.\n *\n * `instanceof NiceError` knows only this copy's class. When an install holds two copies of the\n * package, an error from the other one fails `instanceof` and passes this — so prefer it\n * wherever the question is \"is this a NiceError?\". To use such an error as this copy's own,\n * pass it through `castNiceError`.\n */\nexport function isNiceError(value: unknown): value is NiceError<any, any> {\n  return (\n    typeof value === \"object\" && value != null && Reflect.get(value, NICE_ERROR_BRAND) === true\n  );\n}\n","import type { NiceErrorDomain } from \"../NiceErrorDomain/NiceErrorDomain\";\nimport { type INiceErrorOptions, NiceError } from \"./NiceError\";\nimport type {\n  ExtractFromIdContextArg,\n  FromIdArgs,\n  INiceErrorDomainProps,\n  TDomainNiceErrorId,\n  TErrorDataForIdMap,\n  TFromContextInput,\n  TUnknownNiceErrorDef,\n} from \"./NiceError.types\";\n\n/**\n * Resolves the args tuple for `addId` — mirrors `FromIdArgs` exactly so that\n * optional vs required context is consistent across both `fromId` and `addId`.\n *\n * - No context on this id                   → `[id]`\n * - Context defined, `required: true`       → `[id, context]`\n * - Context defined, `required` absent/false → `[id] | [id, context]`\n */\ntype AddIdArgs<ERR_DEF extends INiceErrorDomainProps, K extends TDomainNiceErrorId<ERR_DEF>> = [\n  ExtractFromIdContextArg<ERR_DEF[\"schema\"][K]>,\n] extends [undefined]\n  ? [id: K]\n  : [undefined] extends [ExtractFromIdContextArg<ERR_DEF[\"schema\"][K]>]\n    ? [id: K] | [id: K, context: NonNullable<ExtractFromIdContextArg<ERR_DEF[\"schema\"][K]>>]\n    : [id: K, context: ExtractFromIdContextArg<ERR_DEF[\"schema\"][K]>];\n\n/** Full-featured construction from NiceErrorDomain.fromId / fromContext. */\nexport interface INiceErrorHydratedOptions<\n  ERR_DEF extends INiceErrorDomainProps,\n  ID extends TDomainNiceErrorId<ERR_DEF>,\n> extends INiceErrorOptions<ERR_DEF, ID> {\n  def: ERR_DEF;\n  niceErrorDefined: NiceErrorDomain<ERR_DEF>;\n}\n\nexport class NiceErrorHydrated<\n  ERR_DEF extends INiceErrorDomainProps = TUnknownNiceErrorDef,\n  /**\n   * Union of active error-id keys.\n   * - After `fromId(id)`: exactly one key.\n   * - After `fromContext({...})`: a union of all supplied keys.\n   * - After `hasOneOfIds([a,b])`: narrows to that subset.\n   * - Default (bare construction / castNiceError): `TUnknownNiceErrorId`.\n   */\n  ACTIVE_IDS extends TDomainNiceErrorId<ERR_DEF> = TDomainNiceErrorId<ERR_DEF>,\n> extends NiceError<ERR_DEF, ACTIVE_IDS> {\n  override readonly def: ERR_DEF;\n  private readonly niceErrorDefined: NiceErrorDomain<ERR_DEF>;\n\n  constructor(options: INiceErrorHydratedOptions<ERR_DEF, ACTIVE_IDS>) {\n    super(options);\n    this.def = options.def;\n    this.niceErrorDefined = options.niceErrorDefined;\n  }\n\n  // -------------------------------------------------------------------------\n  // addContext — merge additional id+context entries into this error\n  // -------------------------------------------------------------------------\n\n  /**\n   * Returns a **new** `NiceErrorHydrated` with additional id+context entries merged in.\n   * The returned error's `ACTIVE_IDS` is the union of the original ids and the\n   * newly supplied keys.\n   *\n   * ```ts\n   * const err = errDef.fromId(\"id_a\", { a: 1 })\n   *   .addContext({ id_b: { b: \"x\" } });\n   * err.getIds(); // [\"id_a\", \"id_b\"]\n   * ```\n   */\n  addContext<INPUT extends TFromContextInput<ERR_DEF[\"schema\"]>>(\n    context: INPUT & Record<Exclude<keyof INPUT, keyof ERR_DEF[\"schema\"] & string>, never>,\n  ): NiceErrorHydrated<ERR_DEF, ACTIVE_IDS | (keyof INPUT & string)> {\n    const newIds = Object.keys(context) as Array<keyof ERR_DEF[\"schema\"] & string>;\n    const newErrorData: TErrorDataForIdMap<ERR_DEF[\"schema\"]> = {};\n\n    for (const id of newIds) {\n      newErrorData[id] = this.niceErrorDefined.reconcileErrorDataForId(id, context[id]);\n    }\n\n    const mergedErrorData: TErrorDataForIdMap<ERR_DEF[\"schema\"]> = {\n      ...this._errorDataMap,\n      ...newErrorData,\n    };\n\n    const mergedIds = Array.from(new Set([...this.getIds(), ...Object.keys(context)])) as Array<\n      ACTIVE_IDS | (keyof INPUT & string)\n    >;\n\n    return new NiceErrorHydrated<ERR_DEF, ACTIVE_IDS | (keyof INPUT & string)>({\n      def: this.def,\n      niceErrorDefined: this.niceErrorDefined,\n      ids: mergedIds,\n      errorData: mergedErrorData,\n      message: this.cleanMessage,\n      httpStatusCode: this.httpStatusCode,\n      originError: this.originError,\n    });\n  }\n\n  // -------------------------------------------------------------------------\n  // addId — add a single id (with optional context) to this error\n  // -------------------------------------------------------------------------\n\n  /**\n   * Returns a **new** `NiceErrorHydrated` with an additional error id (and its context,\n   * if the schema requires one). Equivalent to `addContext({ [id]: context })`\n   * but mirrors the `fromId` ergonomics for single-id additions.\n   */\n  addId<K extends TDomainNiceErrorId<ERR_DEF>>(\n    ...args: AddIdArgs<ERR_DEF, K>\n  ): NiceErrorHydrated<ERR_DEF, ACTIVE_IDS | K> {\n    const [id, context] = args as FromIdArgs<ERR_DEF, K>;\n\n    const reconciledData = this.niceErrorDefined.reconcileErrorDataForId(id, context);\n\n    const errorDataMap: TErrorDataForIdMap<ERR_DEF[\"schema\"]> = {};\n    errorDataMap[id] = reconciledData;\n\n    const mergedContexts: TErrorDataForIdMap<ERR_DEF[\"schema\"]> = {\n      ...this._errorDataMap,\n      ...errorDataMap,\n    };\n    const mergedIds = Array.from(new Set([...this.getIds(), id])) as Array<ACTIVE_IDS | K>;\n\n    return new NiceErrorHydrated<ERR_DEF, ACTIVE_IDS | K>({\n      def: this.def,\n      niceErrorDefined: this.niceErrorDefined,\n      ids: mergedIds,\n      errorData: mergedContexts,\n      message: this.cleanMessage,\n      httpStatusCode: this.httpStatusCode,\n      originError: this.originError,\n    });\n  }\n}\n","import type { NiceError } from \"../NiceError/NiceError\";\n\n/**\n * A subscriber notified once for every `NiceError` at creation time. Use it to\n * pipe errors into telemetry (Sentry / OTel), devtools, or structured logging\n * the moment they're born — without threading a reporter through every call site.\n */\nexport type TNiceErrorTap = (error: NiceError<any, any>) => void;\n\nconst taps = new Set<TNiceErrorTap>();\n\n/**\n * Register a tap fired for every `NiceError` created via a domain\n * (`fromId` / `fromContext`). Returns an unsubscribe function.\n *\n * Opt-in and zero-cost when unused. A tap that throws is swallowed so it can\n * never break error creation.\n */\nexport function onNiceError(tap: TNiceErrorTap): () => void {\n  taps.add(tap);\n  return () => {\n    taps.delete(tap);\n  };\n}\n\n/** Internal: notify all registered taps. Never throws. */\nexport function emitNiceError(error: NiceError<any, any>): void {\n  if (taps.size === 0) return;\n  for (const tap of taps) {\n    try {\n      tap(error);\n    } catch {\n      // A misbehaving tap must never break error creation.\n    }\n  }\n}\n","import { EContextSerializedState } from \"../NiceError/NiceError.enums\";\nimport { type INiceErrorJsonObject, type TErrorDataForIdMap } from \"../NiceError/NiceError.types\";\n\n/**\n * Returns `true` if `obj` is a JSON-serialised `NiceError` object matching the\n * current wire format (contextState-based errorData entries).\n *\n * Validates:\n * - Top-level shape (`name`, `message`, `isUnhandled`, `httpStatusCode`, `ids`, `def`)\n * - Each `errorData` entry has a `contextState` with a valid `kind` discriminant\n *   (`\"no_serialization\"` or `\"unhydrated\"`) — rejecting payloads in the old\n *   format (`context` / `serialized` fields) to prevent silent data corruption.\n */\nexport function isNiceErrorObject(obj: unknown): obj is INiceErrorJsonObject {\n  if (typeof obj !== \"object\" || obj == null) return false;\n  const o = obj as Record<string, unknown>;\n\n  if (\n    o[\"name\"] !== \"NiceError\" ||\n    typeof o[\"message\"] !== \"string\" ||\n    typeof o[\"isUnhandled\"] !== \"boolean\" ||\n    typeof o[\"httpStatusCode\"] !== \"number\"\n  ) {\n    return false;\n  }\n\n  // The constructor joins `ids` into the message, so a record without them cannot be rebuilt.\n  const ids = o[\"ids\"];\n  if (!Array.isArray(ids) || !ids.every((id) => typeof id === \"string\")) return false;\n\n  // Validate the `def` property.\n  const def = o[\"def\"];\n  if (typeof def !== \"object\" || def == null) return false;\n  const d = def as Record<string, unknown>;\n  if (typeof d[\"domain\"] !== \"string\" || !Array.isArray(d[\"allDomains\"])) return false;\n\n  // Validate errorData entries use the current contextState format.\n  // An absent / null errorData is acceptable (bare NiceErrors may have an empty map).\n  const errorData = o[\"errorData\"] as TErrorDataForIdMap<any>;\n  if (errorData != null) {\n    if (typeof errorData !== \"object\") return false;\n\n    for (const entry of Object.values(errorData)) {\n      if (entry == null) continue;\n      if (typeof entry !== \"object\") return false;\n\n      const e = entry;\n      const state = e[\"contextState\"];\n\n      // Reject old-format entries that still use the `context` / `serialized` shape.\n      if (state == null || typeof state !== \"object\") return false;\n\n      const kind = state[\"kind\"];\n      if (\n        kind !== EContextSerializedState.serde_unset &&\n        kind !== EContextSerializedState.unhydrated\n      )\n        return false;\n    }\n  }\n\n  return true;\n}\n","import { isNiceError } from \"../NiceError/NiceError\";\nimport type { INiceErrorJsonObject } from \"../NiceError/NiceError.types\";\nimport { isNiceErrorObject } from \"./isNiceErrorObject\";\nimport { warnOfUnversionedCopy } from \"./loadedVersions\";\n\n/** A copy released before the brand existed: its class has the same name and the same serializer. */\nfunction isUnbrandedNiceError(value: object): value is Error & { toJsonObject: () => unknown } {\n  return (\n    value instanceof Error &&\n    value.name === \"NiceError\" &&\n    \"toJsonObject\" in value &&\n    typeof value.toJsonObject === \"function\"\n  );\n}\n\n/**\n * The JSON record of a `NiceError` built by another copy of this package, or `undefined` when\n * `value` is not one — or is one that cannot serialize itself.\n *\n * Call it only after `instanceof NiceError` has failed. The record comes from the other copy's\n * own `toJsonObject()`, because only that copy knows where its instance keeps its data: read as\n * if it were this copy's, the instance has no context and a message that is already prefixed.\n */\nexport function foreignNiceErrorRecord(value: unknown): INiceErrorJsonObject<any, any> | undefined {\n  if (typeof value !== \"object\" || value == null) return undefined;\n\n  const branded = isNiceError(value);\n  if (!branded && !isUnbrandedNiceError(value)) return undefined;\n\n  try {\n    const record: unknown = value.toJsonObject();\n    if (!isNiceErrorObject(record)) return undefined;\n    if (!branded) warnOfUnversionedCopy();\n    return record;\n  } catch {\n    return undefined;\n  }\n}\n","import { EErrId_NiceErrorInternal, internalNiceError } from \"../internal/internal_errors\";\nimport { isNiceError, NiceError } from \"../NiceError/NiceError\";\nimport { EContextSerializedState } from \"../NiceError/NiceError.enums\";\nimport {\n  type FromIdArgs,\n  type IDefineNewNiceErrorDomainOptions,\n  type INiceErrorDomainProps,\n  type INiceErrorJsonObject,\n  type TContextState,\n  type TDomainNiceErrorId,\n  type TErrorDataForIdMap,\n  type TErrorReconciledData,\n  type TFromContextInput,\n} from \"../NiceError/NiceError.types\";\nimport { type INiceErrorHydratedOptions, NiceErrorHydrated } from \"../NiceError/NiceErrorHydrated\";\nimport { emitNiceError } from \"../observability/tap\";\nimport { foreignNiceErrorRecord } from \"../utils/foreignNiceErrorRecord\";\nimport { getErrorDomainProps } from \"../utils/getErrorDomainProps\";\nimport { type EErrorPackType } from \"../utils/packError/packError.enums\";\n\n// ---------------------------------------------------------------------------\n// Internal type helpers\n// ---------------------------------------------------------------------------\n\ntype ChildDef<\n  PARENT_DEF extends INiceErrorDomainProps,\n  SUB extends IDefineNewNiceErrorDomainOptions,\n> = {\n  domain: SUB[\"domain\"];\n  allDomains: [SUB[\"domain\"], ...PARENT_DEF[\"allDomains\"]];\n  schema: SUB[\"schema\"];\n};\n\n/**\n * Extracts the union of keys present in a `TFromContextInput` object.\n * e.g. `{ invalid_credentials: {...} }` → `\"invalid_credentials\"`\n */\ntype KeysOfContextInput<INPUT> = keyof INPUT & string;\n\ninterface ILinkedNiceErrorDomain {\n  domain: string;\n  definedError: NiceErrorDomain<any>;\n}\n\n// ---------------------------------------------------------------------------\n// InferNiceError / InferNiceErrorHydrated — utility types\n// ---------------------------------------------------------------------------\n\n/**\n * Infers the strongly-typed `NiceError` class type from a `NiceErrorDomain` instance.\n *\n * `ACTIVE_IDS` is set to the full union of all schema keys. Use `hasId` /\n * `hasOneOfIds` to narrow further at the call site.\n *\n * @example\n * ```ts\n * const err_user_auth = defineNiceError({ domain: \"err_user_auth\", schema: { ... } });\n * type TUserAuthError = InferNiceError<typeof err_user_auth>;\n * // → NiceError<{ domain: \"err_user_auth\"; ... }, keyof schema>\n * ```\n */\nexport type InferNiceError<T extends NiceErrorDomain<any>> =\n  T extends NiceErrorDomain<infer ERR_DEF>\n    ? NiceError<ERR_DEF, keyof ERR_DEF[\"schema\"] & string>\n    : never;\n\n/**\n * Infers the strongly-typed `NiceErrorHydrated` class type from a `NiceErrorDomain` instance.\n *\n * Use this when you need the builder methods (`addId`, `addContext`) as part of\n * the inferred type — e.g. for function return types or variable annotations.\n *\n * @example\n * ```ts\n * const err_user_auth = defineNiceError({ domain: \"err_user_auth\", schema: { ... } });\n * type TUserAuthErrorHydrated = InferNiceErrorHydrated<typeof err_user_auth>;\n * // → NiceErrorHydrated<{ domain: \"err_user_auth\"; ... }, keyof schema>\n * ```\n */\nexport type InferNiceErrorHydrated<T extends NiceErrorDomain<any>> =\n  T extends NiceErrorDomain<infer ERR_DEF>\n    ? NiceErrorHydrated<ERR_DEF, keyof ERR_DEF[\"schema\"] & string>\n    : never;\n\n// ---------------------------------------------------------------------------\n// NiceErrorDomain\n// ---------------------------------------------------------------------------\n\nexport class NiceErrorDomain<ERR_DEF extends INiceErrorDomainProps = INiceErrorDomainProps> {\n  readonly domain: ERR_DEF[\"domain\"];\n  readonly allDomains: ERR_DEF[\"allDomains\"];\n  readonly defaultHttpStatusCode?: number;\n  readonly defaultMessage?: string;\n\n  /** Kept for runtime use (message resolution, httpStatusCode, context serialization, etc.). */\n  private readonly _schema: ERR_DEF[\"schema\"];\n  private _definedChildNiceErrors: ILinkedNiceErrorDomain[] = [];\n  private _definedParentNiceError?: ILinkedNiceErrorDomain;\n  /** Set by `.packAs()` — explicit per-instance override, takes priority over `_packAsFn`. */\n  private _setPack?: EErrorPackType;\n  /** Set at definition time — called dynamically each time an error is created. */\n  private _packAsFn?: () => EErrorPackType | void;\n\n  constructor(definition: ERR_DEF) {\n    this.domain = definition.domain;\n    this.allDomains = definition.allDomains;\n    this._schema = definition.schema;\n\n    if (definition.packAs != null) {\n      this._packAsFn = definition.packAs;\n    }\n\n    if (definition.defaultHttpStatusCode != null) {\n      this.defaultHttpStatusCode = definition.defaultHttpStatusCode;\n    }\n\n    if (definition.defaultMessage != null) {\n      this.defaultMessage = definition.defaultMessage;\n    }\n  }\n\n  // -------------------------------------------------------------------------\n  // createChildDomain\n  // -------------------------------------------------------------------------\n\n  /**\n   * Creates a child domain that inherits this domain in `allDomains`.\n   * The child has its own schema and its own domain string.\n   */\n  createChildDomain<SUB extends IDefineNewNiceErrorDomainOptions>(\n    subErrorDef: SUB & { [K in Exclude<keyof SUB, keyof IDefineNewNiceErrorDomainOptions>]: never },\n  ): NiceErrorDomain<ChildDef<ERR_DEF, SUB>> {\n    const child = new NiceErrorDomain<ChildDef<ERR_DEF, SUB>>({\n      domain: subErrorDef.domain,\n      allDomains: [subErrorDef.domain, ...this.allDomains] as [\n        SUB[\"domain\"],\n        ...ERR_DEF[\"allDomains\"],\n      ],\n      schema: subErrorDef.schema,\n      defaultHttpStatusCode: subErrorDef.defaultHttpStatusCode,\n      defaultMessage: subErrorDef.defaultMessage,\n    } as ChildDef<ERR_DEF, SUB>);\n\n    this.addChildNiceErrorDomain(child);\n    child.addParentNiceErrorDomain(this);\n\n    // Child's own packAs takes priority; fall back to parent's config.\n    if (subErrorDef.packAs != null) {\n      child._packAsFn = subErrorDef.packAs;\n    } else if (this._setPack) {\n      child.packAs(this._setPack);\n    } else if (this._packAsFn) {\n      child._packAsFn = this._packAsFn;\n    }\n\n    return child;\n  }\n\n  protected addParentNiceErrorDomain<PARENT_DEF extends INiceErrorDomainProps>(\n    parentError: NiceErrorDomain<PARENT_DEF>,\n  ) {\n    if (this._definedParentNiceError?.domain === parentError.domain) {\n      return;\n    }\n    this._definedParentNiceError = {\n      domain: parentError.domain,\n      definedError: parentError,\n    };\n  }\n\n  protected addChildNiceErrorDomain<CHILD_DEF extends INiceErrorDomainProps>(\n    child: NiceErrorDomain<CHILD_DEF>,\n  ) {\n    if (this._definedChildNiceErrors.some((linked) => linked.domain === child.domain)) {\n      return;\n    }\n\n    this._definedChildNiceErrors.push({\n      domain: child.domain,\n      definedError: child,\n    });\n\n    if (this._definedParentNiceError) {\n      this._definedParentNiceError.definedError.addChildNiceErrorDomain(child);\n    }\n  }\n\n  packAs(pack: EErrorPackType): this {\n    this._setPack = pack;\n    return this;\n  }\n\n  private createError<K extends TDomainNiceErrorId<ERR_DEF>>(\n    input: INiceErrorHydratedOptions<any, any> & { message: string | undefined },\n  ): NiceErrorHydrated<ERR_DEF, K> {\n    const err = new NiceErrorHydrated<ERR_DEF, K>(input);\n\n    // Single creation funnel for fresh errors — notify observability taps once.\n    emitNiceError(err);\n\n    // Explicit .packAs() override takes priority; fall back to the dynamic function.\n    const packType = this._setPack ?? this._packAsFn?.();\n    if (packType != null && packType !== \"no_pack\") {\n      return err.pack(packType) as any;\n    }\n\n    return err;\n  }\n\n  // -------------------------------------------------------------------------\n  // hydrate\n  // -------------------------------------------------------------------------\n\n  /**\n   * Promotes a plain `NiceError<ERR_DEF>` back into a `NiceErrorHydrated` so\n   * that builder methods (`addId`, `addContext`, etc.) are available again.\n   *\n   * For each active id, if the context is in the `\"unhydrated\"` state (i.e. the\n   * error was reconstructed from a JSON payload), `hydrate` calls\n   * `fromJsonSerializable` to reconstruct the typed value and advances the state\n   * to `\"hydrated\"`. Ids already in `\"hydrated\"` or `\"raw_unset\"` state\n   * are passed through unchanged.\n   *\n   * @throws If `error.def.domain` does not match this definition's domain. Use\n   * `niceErrorDefined.isExact(error)` before calling `hydrate` to ensure compatibility.\n   *\n   * ```ts\n   * const raw = castNiceError(apiResponseBody);\n   *\n   * if (err_user_auth.isExact(raw)) {\n   *   const hydrated = err_user_auth.hydrate(raw);\n   *   // hydrated.getContext(\"invalid_credentials\") — fully typed, no throw\n   *   // hydrated.addId / addContext — available again\n   * }\n   * ```\n   */\n  hydrate<ACTIVE_IDS extends TDomainNiceErrorId<ERR_DEF> = TDomainNiceErrorId<ERR_DEF>>(\n    error: NiceError<ERR_DEF, ACTIVE_IDS> | INiceErrorJsonObject<ERR_DEF, ACTIVE_IDS>,\n  ): NiceErrorHydrated<ERR_DEF, ACTIVE_IDS> {\n    const errDef = getErrorDomainProps(error);\n    if (errDef.domain !== this.domain) {\n      throw internalNiceError(EErrId_NiceErrorInternal.hydrate_domain_mismatch, {\n        expected: this.domain,\n        received: errDef.domain,\n      });\n    }\n\n    const finalError = this._ownInstanceOf(error);\n\n    const reconciledErrorData: TErrorDataForIdMap<ERR_DEF[\"schema\"]> = {};\n\n    for (const id of finalError.getIds()) {\n      const existingData = finalError.getErrorDataForId(id);\n      if (existingData == null) continue;\n\n      let contextState: TContextState<any> = existingData.contextState;\n\n      if (contextState.kind === \"unhydrated\") {\n        const entry = this._schema[id as keyof ERR_DEF[\"schema\"]];\n        const deserialize = entry?.context?.serialization?.fromJsonSerializable;\n\n        if (deserialize != null) {\n          contextState = {\n            kind: EContextSerializedState.hydrated,\n            value: deserialize(contextState.serialized),\n            serialized: contextState.serialized,\n          };\n        }\n        // If no deserializer is found (schema mismatch), leave as \"unhydrated\".\n      }\n\n      reconciledErrorData[id] = {\n        contextState,\n        message: existingData.message,\n        httpStatusCode: existingData.httpStatusCode,\n        timeAdded: existingData.timeAdded,\n      };\n    }\n\n    return new NiceErrorHydrated<ERR_DEF, ACTIVE_IDS>({\n      def: this._buildDef(),\n      niceErrorDefined: this,\n      ids: finalError.ids,\n      errorData: reconciledErrorData,\n      message: finalError.cleanMessage ?? finalError.message,\n      httpStatusCode: finalError.httpStatusCode,\n      originError: finalError.originError,\n      timeCreated: finalError.timeCreated,\n    });\n  }\n\n  // -------------------------------------------------------------------------\n  // fromId — single-id construction\n  // -------------------------------------------------------------------------\n\n  /**\n   * Creates a `NiceErrorHydrated` for a single error id.\n   *\n   * - `id` autocompletes to the schema keys.\n   * - The second argument `context` is required / optional / absent based on\n   *   whether the schema entry declares `context.required: true`.\n   * - The returned error has `ACTIVE_IDS` narrowed to exactly `K`, so\n   *   `getContext(id)` is immediately strongly typed.\n   */\n  fromId<K extends keyof ERR_DEF[\"schema\"] & string>(\n    ...args: FromIdArgs<ERR_DEF, K>\n  ): NiceErrorHydrated<ERR_DEF, K> {\n    const [id, context] = args as FromIdArgs<ERR_DEF, K>;\n\n    const reconciledData = this.reconcileErrorDataForId(id, context);\n\n    const errorData: TErrorDataForIdMap<ERR_DEF[\"schema\"]> = {};\n    errorData[id] = reconciledData;\n\n    const err = this.createError({\n      def: this._buildDef(),\n      niceErrorDefined: this,\n      ids: [id],\n      errorData,\n      message: reconciledData.message,\n      httpStatusCode: reconciledData.httpStatusCode,\n    }) as unknown as NiceErrorHydrated<ERR_DEF, K>;\n\n    // Strip library-internal frames so the stack starts at the call site.\n    if (typeof (Error as any).captureStackTrace === \"function\") {\n      (Error as any).captureStackTrace(err, this.fromId);\n    }\n\n    return err;\n  }\n\n  // -------------------------------------------------------------------------\n  // fromContext — multi-id construction\n  // -------------------------------------------------------------------------\n\n  fromContext<INPUT extends TFromContextInput<ERR_DEF[\"schema\"]>>(\n    context: INPUT & Record<Exclude<keyof INPUT, keyof ERR_DEF[\"schema\"]>, never>,\n  ): NiceErrorHydrated<ERR_DEF, KeysOfContextInput<INPUT>> {\n    const ids = Object.keys(context) as Array<KeysOfContextInput<INPUT>>;\n    if (ids.length === 0) {\n      throw internalNiceError(EErrId_NiceErrorInternal.from_context_empty, undefined);\n    }\n\n    const errorData: TErrorDataForIdMap<ERR_DEF[\"schema\"]> = {};\n\n    for (const id of ids) {\n      errorData[id] = this.reconcileErrorDataForId(id, context[id]);\n    }\n\n    const primaryId = ids[0] as KeysOfContextInput<INPUT>;\n\n    const err = this.createError({\n      def: this._buildDef(),\n      niceErrorDefined: this,\n      ids: ids,\n      errorData,\n      message: errorData[primaryId]!.message,\n      httpStatusCode: errorData[primaryId]!.httpStatusCode,\n    }) as NiceErrorHydrated<ERR_DEF, KeysOfContextInput<INPUT>>;\n\n    // Strip library-internal frames so the stack starts at the call site.\n    if (typeof (Error as any).captureStackTrace === \"function\") {\n      (Error as any).captureStackTrace(err, this.fromContext);\n    }\n\n    return err;\n  }\n\n  // -------------------------------------------------------------------------\n  // is — type-narrowing guard\n  // -------------------------------------------------------------------------\n\n  /**\n   * Returns `true` if `error` is a `NiceError` whose `def.domain` exactly matches\n   * this definition's domain.\n   *\n   * Use this after `castNiceError` to narrow an unknown error to this specific\n   * domain before accessing its typed ids/context:\n   *\n   * ```ts\n   * const caught = castNiceError(e);\n   *\n   * if (err_user_auth.isExact(caught)) {\n   *   // caught is now NiceError<typeof err_user_auth's ERR_DEF>\n   *   const hydrated = err_user_auth.hydrate(caught);\n   *   const { username } = hydrated.getContext(\"invalid_credentials\");\n   * }\n   * ```\n   */\n  isExact(error: unknown): error is NiceError<ERR_DEF, keyof ERR_DEF[\"schema\"] & string> {\n    if (!isNiceError(error)) return false;\n    const errDef = getErrorDomainProps(error);\n    return errDef.domain === this.domain;\n  }\n\n  /**\n   * Returns `true` if `error` is a `NiceError` from this domain or from any domain\n   * below it — a child, a grandchild, and so on. Errors from a parent or a sibling\n   * domain return `false`.\n   *\n   * Use it to catch a whole subtree; use `isExact` for this domain alone.\n   *\n   * ```ts\n   * err_auth.isThisOrChild(err_auth_registration.fromId(\"email_taken\")); // true\n   * err_auth_registration.isThisOrChild(err_auth.fromId(\"account_locked\")); // false\n   * ```\n   */\n  isThisOrChild(error: unknown): boolean {\n    if (!isNiceError(error)) return false;\n    const allDomains: unknown = getErrorDomainProps(error).allDomains;\n    return Array.isArray(allDomains) && allDomains.includes(this.domain);\n  }\n\n  // -------------------------------------------------------------------------\n  // isParentOf — ancestry check\n  // -------------------------------------------------------------------------\n\n  /**\n   * Returns `true` if this domain appears anywhere in the target's ancestry\n   * chain (including an exact domain match).\n   *\n   * Accepts either a `NiceErrorDomain` (domain definition) or a `NiceError`\n   * instance (extracts the domain from its `def`).\n   */\n  isParentOf(target: NiceErrorDomain<any> | NiceError<any, any>): boolean {\n    const allDomains: string[] = isNiceError(target)\n      ? getErrorDomainProps(target).allDomains\n      : target.allDomains;\n    return Array.isArray(allDomains) && allDomains.includes(this.domain);\n  }\n\n  // -------------------------------------------------------------------------\n  // Private helpers\n  // -------------------------------------------------------------------------\n\n  /** `error` as this copy's `NiceError`: itself, or rebuilt from a record or from another copy's instance. */\n  private _ownInstanceOf<ACTIVE_IDS extends TDomainNiceErrorId<ERR_DEF>>(\n    error: NiceError<ERR_DEF, ACTIVE_IDS> | INiceErrorJsonObject<ERR_DEF, ACTIVE_IDS>,\n  ): NiceError<ERR_DEF, ACTIVE_IDS> {\n    if (error instanceof NiceError) return error;\n\n    const foreignRecord = foreignNiceErrorRecord(error);\n    if (foreignRecord != null) return new NiceError<any, any>(foreignRecord);\n\n    return new NiceError<ERR_DEF, ACTIVE_IDS>(error);\n  }\n\n  private _buildDef(): ERR_DEF {\n    return {\n      domain: this.domain,\n      allDomains: this.allDomains,\n      schema: this._schema,\n    } as unknown as ERR_DEF;\n  }\n\n  private _resolveMessage(\n    id: keyof ERR_DEF[\"schema\"] & string,\n    context: TFromContextInput<ERR_DEF[\"schema\"]>[typeof id],\n  ): string {\n    const entry = this._schema[id];\n\n    if (typeof entry?.message === \"function\") {\n      return (entry.message as (ctx: unknown) => string)(context);\n    }\n    if (typeof entry?.message === \"string\") {\n      return entry.message;\n    }\n    return this.defaultMessage ?? `[${this.domain}::${id}] An error occurred.`;\n  }\n\n  private _resolveHttpStatusCode(\n    id: keyof ERR_DEF[\"schema\"] & string,\n    context: TFromContextInput<ERR_DEF[\"schema\"]>[typeof id],\n  ): number {\n    const entry = this._schema[id];\n    let httpStatusCode: number | undefined;\n\n    if (typeof entry?.httpStatusCode === \"function\") {\n      httpStatusCode = (entry.httpStatusCode as (ctx: unknown) => number)(context);\n    }\n    if (typeof entry?.httpStatusCode === \"number\") {\n      httpStatusCode = entry.httpStatusCode;\n    }\n\n    return typeof httpStatusCode === \"number\"\n      ? httpStatusCode\n      : (this.defaultHttpStatusCode ?? 500);\n  }\n\n  reconcileErrorDataForId(\n    id: keyof ERR_DEF[\"schema\"] & string,\n    context: TFromContextInput<ERR_DEF[\"schema\"]>[typeof id],\n  ): TErrorReconciledData<ERR_DEF[\"schema\"], typeof id> {\n    const message = this._resolveMessage(id, context);\n    const httpStatusCode = this._resolveHttpStatusCode(id, context);\n    const entry = this._schema[id];\n\n    let contextState: TContextState<any>;\n\n    if (context != null && entry?.context?.serialization != null) {\n      // Context provided and a custom serializer is defined — build \"hydrated\" state.\n      const serialized = entry.context.serialization.toJsonSerializable(context as any);\n      contextState = { kind: EContextSerializedState.hydrated, value: context, serialized };\n    } else {\n      // No custom serializer (or context is absent for optional ids) — use \"raw_unset\".\n      contextState = { kind: EContextSerializedState.serde_unset, value: context };\n    }\n\n    return { contextState, message, httpStatusCode, timeAdded: Date.now() };\n  }\n}\n","import type {\n  IDefineNewNiceErrorDomainOptions,\n  TNiceErrorSchema,\n} from \"../NiceError/NiceError.types\";\nimport { NiceErrorDomain } from \"./NiceErrorDomain\";\n\nexport const defineNiceError = <ERR_DOMAIN extends string, SCHEMA extends TNiceErrorSchema>(\n  definition: IDefineNewNiceErrorDomainOptions<ERR_DOMAIN, SCHEMA>,\n) => {\n  // const {} = import(\"./NiceErrorDomain\");\n  return new NiceErrorDomain<{\n    domain: ERR_DOMAIN;\n    allDomains: [ERR_DOMAIN];\n    schema: SCHEMA;\n  }>({\n    domain: definition.domain,\n    allDomains: [definition.domain],\n    schema: definition.schema,\n    ...(definition.packAs != null ? { packAs: definition.packAs } : {}),\n  });\n};\n","import type {\n  INiceErrorContextDefinition,\n  INiceErrorIdMetadata,\n  JSONSerializableValue,\n} from \"../NiceError/NiceError.types\";\n\n/**\n * Schema entry factory — the idiomatic way to define a single error id in a\n * `NiceErrorDomain` schema.\n *\n * Using `err()` instead of writing schema entries as plain object literals\n * ensures TypeScript resolves the context argument as **required** vs **optional**\n * correctly in `fromId` / `addId` call sites.\n *\n * How `required` affects the call site:\n *\n * | Schema entry                       | `fromId(\"id\")` | `fromId(\"id\", ctx)` |\n * |------------------------------------|----------------|---------------------|\n * | `err()`  /  `err({ ... })`         | ✓              | ✗ (no context)      |\n * | `err<C>({ context: {} })`          | ✓              | ✓ (optional ctx)    |\n * | `err<C>({ context: { required: true } })` | ✗     | ✓ (required ctx)    |\n *\n * @example\n * ```ts\n * // No context — `fromId(\"not_found\")` takes no second argument.\n * not_found: err({ message: \"Resource not found\", httpStatusCode: 404 }),\n *\n * // Optional context — second arg accepted but not required.\n * rate_limited: err<{ retryAfter: number }>({\n *   message: (ctx) => ctx ? `Retry after ${ctx.retryAfter}s` : \"Rate limited\",\n *   httpStatusCode: 429,\n *   context: {},\n * }),\n *\n * // Required context — `fromId(\"invalid_input\", { field: \"email\" })` (second arg is required).\n * invalid_input: err<{ field: string }>({\n *   message: ({ field }) => `Invalid value for field: ${field}`,\n *   httpStatusCode: 422,\n *   context: { required: true },\n * }),\n *\n * // Required context with custom serialization (for non-JSON-safe context values).\n * fs_error: err<{ cause: NodeJS.ErrnoException }>({\n *   message: ({ cause }) => `File system error: ${cause.message}`,\n *   context: {\n *     required: true,\n *     serialization: {\n *       toJsonSerializable: ({ cause }) => ({ code: cause.code, message: cause.message }),\n *       fromJsonSerializable: (obj) => ({ cause: Object.assign(new Error(obj.message), obj) }),\n *     },\n *   },\n * }),\n * ```\n */\n\n// Overload 1: context.required: true → the context argument will be **required** in fromId/addId.\nexport function err<C, D extends JSONSerializableValue = Record<string, any>>(\n  meta: INiceErrorIdMetadata<C, D> & {\n    context: INiceErrorContextDefinition<C, D> & { required: true };\n  },\n): INiceErrorIdMetadata<C> & { context: { required: true } };\n\n// Overload 2: everything else (no context, or optional context) → context arg is optional/absent.\nexport function err<C = never>(meta?: INiceErrorIdMetadata<C>): INiceErrorIdMetadata<C>;\n\n// Implementation (not part of the public overload surface).\nexport function err<C = never>(meta?: INiceErrorIdMetadata<C>): INiceErrorIdMetadata<C> {\n  return meta ?? ({} as INiceErrorIdMetadata<C>);\n}\n","import { defineNiceError } from \"../NiceErrorDomain/defineNiceError\";\nimport { err } from \"../NiceErrorDomain/err\";\nimport { _setInternalErrorBuilder, EErrId_NiceErrorInternal } from \"./internal_errors\";\n\n// HTTP status codes inlined to keep nice-error zero-runtime-dep (was: http-status-codes).\nconst HTTP_UNPROCESSABLE_ENTITY = 422;\nconst HTTP_INTERNAL_SERVER_ERROR = 500;\n\nimport type {\n  IInspectErrorResult_JsError,\n  IInspectErrorResult_JsErrorObject,\n  IInspectErrorResult_JsOther,\n  IInspectErrorResult_Nullish,\n  TInspectErrorResult_JsDataType,\n} from \"../utils/inspectPotentialError/inspectPotentialError.types\";\n\nexport const err_nice = defineNiceError({\n  domain: \"err_nice\",\n  schema: {},\n});\n\nexport enum EErrId_CastNotNice {\n  js_error = \"native_error\",\n  js_error_like_object = \"js_error_like_object\",\n  nullish_value = \"nullish_value\",\n  js_data_type = \"js_data_type\",\n  js_other = \"js_other\",\n}\n\nexport const err_cast_not_nice = err_nice.createChildDomain({\n  domain: \"err_cast_not_nice\",\n  defaultHttpStatusCode: HTTP_UNPROCESSABLE_ENTITY,\n  schema: {\n    [EErrId_CastNotNice.js_error]: err<IInspectErrorResult_JsError>({\n      context: {\n        required: true,\n      },\n      message: ({ jsError }) =>\n        `A native JavaScript Error was encountered during casting: ${jsError.message}`,\n      httpStatusCode: HTTP_INTERNAL_SERVER_ERROR,\n    }),\n    [EErrId_CastNotNice.js_error_like_object]: err<IInspectErrorResult_JsErrorObject>({\n      context: {\n        required: true,\n      },\n      message: ({ jsErrorObject }) =>\n        `An object resembling a JavaScript Error was encountered during casting: [${jsErrorObject.name}] ${jsErrorObject.message}`,\n      httpStatusCode: HTTP_INTERNAL_SERVER_ERROR,\n    }),\n    [EErrId_CastNotNice.nullish_value]: err<IInspectErrorResult_Nullish>({\n      context: {\n        required: true,\n      },\n      message: ({ value }) =>\n        `A nullish value [${value === null ? \"null\" : \"undefined\"}] was encountered during casting`,\n    }),\n    [EErrId_CastNotNice.js_data_type]: err<TInspectErrorResult_JsDataType>({\n      context: {\n        required: true,\n      },\n      message: ({ jsDataType, jsDataValue }) => {\n        let inspectedValue: string | undefined;\n\n        try {\n          inspectedValue = JSON.stringify(jsDataValue);\n        } catch {\n          // Ignore JSON.stringify errors, which can happen for circular structures or certain types like BigInt.\n        }\n\n        return `A value of type [${jsDataType}] with value [${inspectedValue ?? \"UNSERIALIZABLE\"}] was encountered during casting, which is not a valid error type`;\n      },\n    }),\n    [EErrId_CastNotNice.js_other]: err<IInspectErrorResult_JsOther>({\n      context: {\n        required: true,\n      },\n      message: ({ jsDataValue }) => {\n        let inspectedValue: string | undefined;\n\n        try {\n          inspectedValue = JSON.stringify(jsDataValue);\n        } catch {\n          // Ignore JSON.stringify errors, which can happen for circular structures or certain types like BigInt.\n        }\n\n        return `An unhandled type [${typeof jsDataValue}] with value [${inspectedValue ?? \"UNSERIALIZABLE\"}] was encountered during casting, which is not a valid error type`;\n      },\n    }),\n  },\n});\n\nexport const err_nice_handler = err_nice.createChildDomain({\n  domain: \"err_nice_handler\",\n  schema: {},\n});\n\n/**\n * `nice-error`'s own failure modes — thrown as `NiceError`s (not plain `Error`s)\n * so they are observable, pattern-matchable, and visible to the same handlers /\n * devtools / telemetry as every other error in the system. The ids live in\n * `internal_errors` so throw-sites can reference them without an import cycle.\n */\nexport const err_nice_error = err_nice.createChildDomain({\n  domain: \"err_nice_error\",\n  defaultHttpStatusCode: HTTP_INTERNAL_SERVER_ERROR,\n  schema: {\n    [EErrId_NiceErrorInternal.context_unhydrated]: err<{ id: string }>({\n      context: { required: true },\n      message: ({ id }) =>\n        `[NiceError.getContext] Context for id \"${id}\" is in the \"unhydrated\" state. ` +\n        `The error was reconstructed from a serialized payload but has not been deserialized yet. ` +\n        `Call \\`niceErrorDomain.hydrate(error)\\` to reconstruct the typed context.`,\n    }),\n    [EErrId_NiceErrorInternal.hydrate_domain_mismatch]: err<{ expected: string; received: string }>(\n      {\n        context: { required: true },\n        message: ({ expected, received }) =>\n          `[NiceErrorDomain.hydrate] Domain mismatch: this definition is \"${expected}\" ` +\n          `but the error belongs to \"${received}\". ` +\n          `Call \\`niceErrorDomain.isExact(error)\\` before hydrating to ensure compatibility.`,\n      },\n    ),\n    [EErrId_NiceErrorInternal.from_context_empty]: err({\n      message: \"[NiceErrorDomain.fromContext] context object must contain at least one error id.\",\n    }),\n    [EErrId_NiceErrorInternal.handler_returned_promise_in_sync]: err<{ identifier: string }>({\n      context: { required: true },\n      message: ({ identifier }) =>\n        `[NiceError.handleWithSync] Handler ${identifier} returned a Promise but was called via ` +\n        `\\`handleWithSync\\` (synchronous). The Promise will not be awaited. Use \\`handleWithAsync\\` for async handlers.`,\n    }),\n  },\n});\n\n// Inject the builder so cycle-free throw-sites (NiceError, NiceErrorDomain) can\n// raise these as real NiceErrors. The cast bridges the registry's loose\n// `(kind, ctx)` shape to `fromId`'s per-id overloads — the only such seam.\n_setInternalErrorBuilder((kind, ctx) =>\n  err_nice_error.fromId(kind as EErrId_NiceErrorInternal.context_unhydrated, ctx as { id: string }),\n);\n","import type { IRegularErrorJsonObject } from \"../NiceError/NiceError.types\";\n\nexport function isRegularErrorJsonObject(obj: unknown): obj is IRegularErrorJsonObject {\n  if (typeof obj !== \"object\" || obj == null) return false;\n  const o = obj as Record<string, unknown>;\n  return typeof o[\"name\"] === \"string\" && typeof o[\"message\"] === \"string\";\n}\n","import { NiceError } from \"../../NiceError/NiceError\";\nimport type { IRegularErrorJsonObject } from \"../../NiceError/NiceError.types\";\nimport { DUR_OBJ_PACK_PREFIX, DUR_OBJ_PACK_SUFFIX } from \"../../NiceError/nice_error.static\";\nimport { foreignNiceErrorRecord } from \"../foreignNiceErrorRecord\";\nimport { isNiceErrorObject } from \"../isNiceErrorObject\";\nimport { isRegularErrorJsonObject } from \"../isRegularErrorObject\";\nimport { getNiceErrorLogger } from \"../logger\";\nimport { EInspectErrorResultType } from \"./inspectPotentialError.enums\";\nimport { type TInspectErrorResult } from \"./inspectPotentialError.types\";\n\nfunction interpretMessagePackedError(\n  parsedError: Error | IRegularErrorJsonObject,\n): TInspectErrorResult | null {\n  let packedErrorStr: string | undefined;\n\n  if (\n    typeof parsedError.message === \"string\" &&\n    parsedError.message.includes(DUR_OBJ_PACK_PREFIX) &&\n    parsedError.message.includes(DUR_OBJ_PACK_SUFFIX)\n  ) {\n    packedErrorStr = parsedError.message;\n  }\n\n  if (\n    typeof parsedError.cause === \"string\" &&\n    parsedError.cause.includes(DUR_OBJ_PACK_PREFIX) &&\n    parsedError.cause.includes(DUR_OBJ_PACK_SUFFIX)\n  ) {\n    packedErrorStr = parsedError.cause;\n  }\n\n  if (packedErrorStr != null) {\n    const jsonStr = packedErrorStr.split(DUR_OBJ_PACK_PREFIX)[1]!.split(DUR_OBJ_PACK_SUFFIX)[0]!;\n    try {\n      const errorObj = JSON.parse(jsonStr);\n      if (isNiceErrorObject(errorObj)) {\n        return {\n          type: EInspectErrorResultType.niceErrorObject,\n          niceErrorObject: errorObj,\n        };\n      }\n    } catch {\n      // Not a valid JSON, continue treating as regular Error\n    }\n  }\n\n  return null;\n}\n\nexport const inspectPotentialError = (potentialError: unknown): TInspectErrorResult => {\n  if (potentialError == null) {\n    return {\n      type: EInspectErrorResultType.nullish,\n      value: potentialError,\n    };\n  }\n\n  if (typeof potentialError === \"number\") {\n    return {\n      type: EInspectErrorResultType.jsDataType,\n      jsDataType: \"number\",\n      jsDataValue: potentialError,\n    };\n  }\n\n  if (typeof potentialError === \"boolean\") {\n    return {\n      type: EInspectErrorResultType.jsDataType,\n      jsDataType: \"boolean\",\n      jsDataValue: potentialError,\n    };\n  }\n\n  let parsedError: unknown = potentialError;\n\n  if (typeof potentialError === \"string\") {\n    if (potentialError.includes(\"{\") && potentialError.includes(\"name\")) {\n      try {\n        parsedError = JSON.parse(potentialError);\n      } catch {\n        // Not a JSON string, treat as regular string\n        return {\n          type: EInspectErrorResultType.jsDataType,\n          jsDataType: \"string\",\n          jsDataValue: potentialError,\n        };\n      }\n    } else {\n      return {\n        type: EInspectErrorResultType.jsDataType,\n        jsDataType: \"string\",\n        jsDataValue: potentialError,\n      };\n    }\n  }\n\n  if (typeof parsedError !== \"object\" || parsedError == null) {\n    getNiceErrorLogger().warn(\n      \"Received a potential error that is a primitive data type other than string, number, or boolean. This is unexpected and may indicate an issue with error handling in the code.\",\n      { potentialError },\n    );\n\n    return {\n      jsDataValue: potentialError,\n      type: EInspectErrorResultType.jsOther,\n    };\n  }\n\n  if (parsedError instanceof NiceError) {\n    return {\n      type: EInspectErrorResultType.niceError,\n      niceError: parsedError,\n    };\n  }\n\n  const foreignRecord = foreignNiceErrorRecord(parsedError);\n\n  if (foreignRecord != null) {\n    return {\n      type: EInspectErrorResultType.niceErrorObject,\n      niceErrorObject: foreignRecord,\n    };\n  }\n\n  if (isNiceErrorObject(parsedError)) {\n    return {\n      type: EInspectErrorResultType.niceErrorObject,\n      niceErrorObject: parsedError,\n    };\n  }\n\n  if (parsedError instanceof Error) {\n    const durObjResult = interpretMessagePackedError(parsedError);\n\n    if (durObjResult != null) {\n      return durObjResult;\n    }\n\n    return {\n      type: EInspectErrorResultType.jsError,\n      jsError: parsedError,\n    };\n  }\n\n  if (isRegularErrorJsonObject(parsedError)) {\n    const durObjResult = interpretMessagePackedError(parsedError);\n\n    if (durObjResult != null) {\n      return durObjResult;\n    }\n\n    return {\n      type: EInspectErrorResultType.jsErrorObject,\n      jsErrorObject: parsedError as IRegularErrorJsonObject,\n    };\n  }\n\n  return {\n    type: EInspectErrorResultType.jsDataType,\n    jsDataType: \"object\",\n    jsDataValue: parsedError,\n  };\n};\n","import { EErrId_CastNotNice, err_cast_not_nice } from \"../internal/nice_core_errors\";\nimport { NiceError } from \"../NiceError/NiceError\";\nimport { inspectPotentialError } from \"./inspectPotentialError/inspectPotentialError\";\nimport { EInspectErrorResultType } from \"./inspectPotentialError/inspectPotentialError.enums\";\n\n/**\n * Casts any unknown value into a `NiceError`.\n *\n * - If the value is already a `NiceError` instance, it is returned as-is.\n * - If the value is a plain `Error`, it is wrapped with the original as `originError`.\n * - If the value is a JSON-serialised `NiceError` object (e.g. from an API\n *   response), a best-effort `NiceError` is re-created from it.\n * - For all other values, a generic `NiceError` is created with a descriptive\n *   message.\n *\n * After casting, use `NiceErrorDomain.isExact(error)` to narrow the error to a\n * specific domain and access its strongly-typed ids and context.\n */\nexport const castNiceError = (error: unknown): NiceError => {\n  const inspected = inspectPotentialError(error);\n\n  switch (inspected.type) {\n    case EInspectErrorResultType.niceError:\n      // Already a NiceError instance — return as-is.\n      return inspected.niceError;\n\n    case EInspectErrorResultType.niceErrorObject: {\n      // Re-hydrate from a serialised NiceError JSON object.\n      const obj = inspected.niceErrorObject;\n      return new NiceError(obj);\n    }\n\n    case EInspectErrorResultType.jsError: {\n      // Wrap a native JS Error, preserving the original as context.\n      return err_cast_not_nice\n        .fromContext({\n          [EErrId_CastNotNice.js_error]: inspected,\n        })\n        .withOriginError(inspected.jsError);\n    }\n\n    case EInspectErrorResultType.jsErrorObject: {\n      const err = err_cast_not_nice.fromContext({\n        [EErrId_CastNotNice.js_error_like_object]: inspected,\n      });\n      err.cause = inspected.jsErrorObject;\n      return err;\n    }\n\n    case EInspectErrorResultType.nullish:\n      return err_cast_not_nice.fromContext({\n        [EErrId_CastNotNice.nullish_value]: inspected,\n      });\n\n    case EInspectErrorResultType.jsDataType: {\n      return err_cast_not_nice.fromContext({\n        [EErrId_CastNotNice.js_data_type]: inspected,\n      });\n    }\n\n    default:\n      return err_cast_not_nice.fromContext({\n        [EErrId_CastNotNice.js_other]: inspected,\n      });\n  }\n};\n","import { castNiceError } from \"../utils/castNiceError\";\nimport type { TNiceResult } from \"./TNiceResult\";\n\n/**\n * Run a synchronous function and capture the outcome as a {@link TNiceResult}.\n *\n * Any thrown value is run through {@link castNiceError}, so the `error` branch is\n * always a `NiceError` — a defined domain error passes through untouched; a native\n * throw / nullish / primitive becomes an `err_cast_not_nice` wrapper (`isUnhandled`).\n *\n * ```ts\n * const r = niceTry(() => JSON.parse(input));\n * if (!r.ok) report(r.error);\n * else use(r.output);\n * ```\n */\nexport function niceTry<OUT>(fn: () => OUT): TNiceResult<OUT> {\n  try {\n    return { ok: true, output: fn() };\n  } catch (error) {\n    return { ok: false, error: castNiceError(error) };\n  }\n}\n\n/**\n * Async counterpart of {@link niceTry}. Accepts a sync or async function and\n * awaits its result; a rejection is caught and `castNiceError`-d into the\n * `error` branch.\n */\nexport async function niceTryAsync<OUT>(fn: () => Promise<OUT> | OUT): Promise<TNiceResult<OUT>> {\n  try {\n    return { ok: true, output: await fn() };\n  } catch (error) {\n    return { ok: false, error: castNiceError(error) };\n  }\n}\n","import { err, err_nice } from \"@nice-code/error\";\n// Type-only (erased at compile time), so the runtime import stays one-way:\n// endpointEvidence → err_wire_connect.\nimport type { EWireConnectFailureKind } from \"./endpointEvidence\";\n\n/**\n * The Connect layer's error domain. Declared with the types\n * so Phases 2–6 throw against a fixed vocabulary instead of inventing ad-hoc `Error`s per phase;\n * each id notes the phase that starts raising it. (`protocol_unsupported` is the link-level\n * error `nice-realm`'s `err_realm` doc already points at as living here.)\n */\nexport const err_wire_connect = err_nice.createChildDomain({\n  domain: \"err_nice_wire_connect\",\n  schema: {\n    /** Phase 2 — `connect()` rejects: every transport in the preference chain failed. */\n    connect_exhausted: err<{ peerId: string; attempted: readonly string[] }>({\n      message: ({ peerId, attempted }) =>\n        `connect() to peer [${peerId}] exhausted its transport chain (tried: ${attempted.join(\", \") || \"none configured\"}).`,\n    }),\n    /** Phase 2 — `connect()` after `close()`; a closed client is terminal, build a new one. */\n    connect_closed: err<{ peerId: string }>({\n      message: ({ peerId }) =>\n        `connect() to peer [${peerId}] on a closed WireClient — closed is terminal; create a new client.`,\n    }),\n    /**\n     * Phase 2 — one transport's dial or handshake failed (the chain item detail inside\n     * `connect_exhausted`). `endpoint`/`kind` are the feedback W2/W3 additions: the URL actually\n     * dialed, and the typed class of failure (see `EWireConnectFailureKind`).\n     */\n    dial_failed: err<{\n      peerId: string;\n      carrierLabel: string;\n      reason: string;\n      endpoint?: string;\n      kind?: EWireConnectFailureKind;\n    }>({\n      message: ({ peerId, carrierLabel, reason, endpoint }) =>\n        `Dialing peer [${peerId}] over \"${carrierLabel}\"${endpoint != null ? ` against ${endpoint}` : \"\"} failed: ${reason}`,\n    }),\n    /**\n     * the resilience contract — the carrier has **no valid endpoint right now** (`createRequest`\n     * returned `null`, e.g. a torn-down session's mutable dial context). Not a failure: a policy\n     * signal. The transport selection rethrows it unwrapped, and a keep-alive redial loop PARKS on\n     * it — no dialing garbage, no backoff churn — until the next explicit `connect()`/dispatch.\n     */\n    dial_unavailable: err<{ carrierLabel: string }>({\n      message: ({ carrierLabel }) =>\n        `Dial over \"${carrierLabel}\" unavailable — createRequest returned null (no valid endpoint ` +\n        \"right now). A keep-alive redial parks on this until the next explicit connect()/dispatch.\",\n    }),\n    conflicting_connect_options: err<{ detail: string }>({\n      message: ({ detail }) => `Conflicting connection options: ${detail}`,\n    }),\n    /**\n     * Consumer feedback (meteor-connect-bridge W1/W3) — **something answered, and it is not\n     * nice-wire**. The dominant real-world causes are a wrong URL/port, an intercepting proxy or\n     * WAF, or an endpoint that is simply a different server. Thrown where the evidence still\n     * exists (the carrier holds the HTTP status; the handshake holds the frame), so the data\n     * carries what came back instead of only what we wanted. Branch on it with\n     * `err.hasId(\"endpoint_answered_non_protocol\")` — never on the message text.\n     */\n    endpoint_answered_non_protocol: err<{\n      /** The layer that judged the response, used as the message's `[marker]` — e.g. \"exchange-handshake\". */\n      stage: string;\n      /** What that layer was waiting for — e.g. \"a welcome frame\". */\n      expected?: string;\n      /** The endpoint actually dialed. */\n      url?: string;\n      /** Present when the carrier saw an HTTP response. */\n      httpStatus?: number;\n      contentType?: string;\n      /** The envelope kind that decoded, when the body *was* a protocol frame of the wrong sort. */\n      receivedKind?: string;\n      /** Bounded, sanitized head of the body (see `describeNonProtocolBody`). */\n      bodyPreview?: string;\n    }>({\n      message: ({ stage, expected, url, httpStatus, contentType, receivedKind, bodyPreview }) => {\n        const received =\n          httpStatus != null\n            ? `an HTTP ${httpStatus}${contentType != null ? ` ${contentType}` : \"\"} response`\n            : receivedKind != null\n              ? `a \"${receivedKind}\" frame`\n              : \"a response it could not decode\";\n        const diagnosis =\n          httpStatus != null && httpStatus >= 500\n            ? \"the server answered with an error instead of a nice-wire frame (check the \" +\n              \"server's logs: a crashed handler or an unavailable upstream answers this way)\"\n            : \"the endpoint answered but is not speaking the nice-wire protocol (wrong URL, an \" +\n              \"intercepting proxy/WAF, or a different server)\";\n        return (\n          `[${stage}] expected ${expected ?? \"a nice-wire frame\"} but received ${received} — ` +\n          diagnosis +\n          `${url != null ? `. Dialed: ${url}` : \"\"}` +\n          `${bodyPreview != null ? `. Body: ${JSON.stringify(bodyPreview)}` : \"\"}.`\n        );\n      },\n    }),\n    /**\n     * **No response was received**: DNS/refused/TLS/offline, a socket that errored before it\n     * opened, or a response the platform hid from the caller (a CORS-blocked answer, a refused\n     * WebSocket upgrade, an injected fetch/socket that threw). The sibling of\n     * `endpoint_answered_non_protocol`, which carries the response it did see.\n     */\n    endpoint_unreachable: err<{\n      /** The endpoint actually dialed. */\n      url?: string;\n      carrierLabel?: string;\n      /** The platform's own words (`ECONNREFUSED`, RN's \"Network request failed\", …). */\n      reason: string;\n    }>({\n      message: ({ url, carrierLabel, reason }) =>\n        `Could not reach ${url ?? (carrierLabel != null ? `the \"${carrierLabel}\" endpoint` : \"the endpoint\")}: ` +\n        `${reason} — no response was received (a network, DNS or TLS failure; a response the ` +\n        \"browser blocked or hid, such as a CORS rejection or a refused WebSocket upgrade; or the \" +\n        \"fetch/socket implementation threw).\",\n    }),\n    /**\n     * The carrier **opened**, then went away before the handshake finished — so the address\n     * reaches something (unlike `endpoint_unreachable`), and that something hung up without a\n     * protocol answer. Retried like any failed dial.\n     */\n    closed_during_handshake: err<{\n      stage: string;\n      /** What the handshake was waiting for when the carrier closed — e.g. \"a welcome frame\". */\n      awaiting: string;\n      /** The endpoint actually dialed. */\n      url?: string;\n    }>({\n      message: ({ stage, awaiting, url }) =>\n        `[${stage}] the connection closed while waiting for ${awaiting} — the endpoint accepted ` +\n        \"the connection and dropped it before the handshake finished (a server that restarted \" +\n        \"or failed mid-handshake, a proxy that cut the socket, or a peer that refuses by closing)\" +\n        `${url != null ? `. Dialed: ${url}` : \"\"}.`,\n    }),\n    /** The carrier stayed open and the peer never answered the handshake within `timeoutMs`. */\n    handshake_timeout: err<{\n      stage: string;\n      /** What the handshake was waiting for — e.g. \"a welcome frame\". */\n      awaiting: string;\n      timeoutMs: number;\n      /** The endpoint actually dialed. */\n      url?: string;\n    }>({\n      message: ({ stage, awaiting, timeoutMs, url }) =>\n        `[${stage}] timed out after ${timeoutMs} ms waiting for ${awaiting} — the connection is ` +\n        \"open but the peer did not answer the handshake\" +\n        `${url != null ? `. Dialed: ${url}` : \"\"}.`,\n    }),\n    /**\n     * The peer **is** a nice-code backend and refused the handshake for a reason that carries no\n     * machine-readable id of its own (an older peer, a dictionary/security mismatch, a custom\n     * gate). Typed so `classifyConnectFailure` can report `handshake_rejected` — a third\n     * developer response (\"fix the identity/version\"), distinct from a wrong URL or a dead host.\n     * `identity_pin_mismatch` stays its own id: it is permanent and the redial loop parks on it.\n     */\n    handshake_rejected: err<{ stage: string; reason: string }>({\n      message: ({ stage, reason }) => `[${stage}] rejected by peer: ${reason}`,\n    }),\n    /**\n     * The peer explicitly reported that the secure handshake has no compatible first-party wire\n     * generation. This is terminal for the current builds: transport fallback and automatic\n     * redial park until the application explicitly retries after an upgrade or rollback.\n     */\n    protocol_version_mismatch: err<{\n      reason: string;\n      observedProtocolVersion?: number;\n      localSupportedProtocolVersions: readonly number[];\n      remoteSupportedProtocolVersions?: readonly number[];\n    }>({\n      message: ({\n        reason,\n        observedProtocolVersion,\n        localSupportedProtocolVersions,\n        remoteSupportedProtocolVersions,\n      }) =>\n        `Handshake protocol version mismatch: ${reason}. ` +\n        `Local support: [${localSupportedProtocolVersions.join(\", \")}]` +\n        `${remoteSupportedProtocolVersions != null ? `; remote support: [${remoteSupportedProtocolVersions.join(\", \")}]` : \"\"}` +\n        `${observedProtocolVersion != null ? `; observed version: ${observedProtocolVersion}` : \"\"}. ` +\n        \"Carrier fallback and automatic redial are parked until an explicit retry.\",\n    }),\n    /**\n     * A secure endpoint answered as nice-wire but advertised a different runtime identity from the\n     * one the caller selected. This is terminal for the current endpoint selection, so fallback and\n     * automatic redial park until an explicit retry after the route or expectation changes.\n     */\n    peer_identity_mismatch: err<{\n      expected: { envId: string; perId?: string };\n      actual: { envId: string; perId?: string };\n      /** Sanitized destination (credentials/query/fragment removed), when known by the carrier. */\n      endpoint?: string;\n    }>({\n      message: ({ expected, actual, endpoint }) =>\n        `Secure peer identity mismatch: expected envId=${JSON.stringify(expected.envId)}` +\n        `${expected.perId != null ? `, perId=${JSON.stringify(expected.perId)}` : \"\"}; ` +\n        `received envId=${JSON.stringify(actual.envId)}` +\n        `${actual.perId != null ? `, perId=${JSON.stringify(actual.perId)}` : \"\"}. ` +\n        `${endpoint != null ? `Dialed ${endpoint}. ` : \"\"}` +\n        \"Carrier fallback and automatic redial are parked until an explicit retry.\",\n    }),\n    /**\n     * This runtime has no WebCrypto (`crypto.subtle`), so a secure transport cannot handshake.\n     * Raised before any dial. Not a network condition: transport selection moves on to a plain\n     * carrier when one is configured, and otherwise automatic redial parks on it.\n     */\n    crypto_unavailable: err<{\n      /**\n       * `insecure_context`: a browser page that is not a secure context (plain HTTP on anything\n       * but localhost). `no_webcrypto`: the runtime ships none (React Native before its polyfill).\n       */\n      reason: \"insecure_context\" | \"no_webcrypto\";\n      /** The insecure page's origin, when the runtime exposes one. */\n      pageOrigin?: string;\n    }>({\n      message: ({ reason, pageOrigin }) =>\n        reason === \"insecure_context\"\n          ? `A secure connection needs WebCrypto (crypto.subtle), which a browser provides only ` +\n            `to a secure context — and this page${pageOrigin != null ? ` (${pageOrigin})` : \"\"} ` +\n            \"is not one. Open it over HTTPS or on localhost. Automatic redial is parked.\"\n          : \"A secure connection needs WebCrypto (crypto.subtle), which this runtime does not \" +\n            \"provide. Install a WebCrypto polyfill before connecting (on React Native, \" +\n            \"react-native-quick-crypto), or set `secure: false` on the carrier for a plain \" +\n            \"connection. Automatic redial is parked.\",\n    }),\n    /** Phase 3 — a protocol sent on a connection whose peer did not advertise it (or the host never registered it). */\n    protocol_unsupported: err<{ protocolId: string }>({\n      message: ({ protocolId }) =>\n        `Protocol \"${protocolId}\" cannot speak on this connection — the peer did not advertise \"proto:${protocolId}\" (or it is not registered here).`,\n    }),\n    /** Phase 6 — a prefixed protocol registered on an exchange-only connection (protocols need duplex; the protocol contract). */\n    protocol_on_exchange_only: err<{ protocolId: string }>({\n      message: ({ protocolId }) =>\n        `Protocol \"${protocolId}\" needs a duplex transport — this connection is exchange-only (request/reply), which carries only the lane.`,\n    }),\n    /** Phase 4 — the acceptor security gate: protocol frame on a non-authenticated connection without `allowPlain`. */\n    protocol_security_blocked: err<{ protocolId: string; securityLevel: string }>({\n      message: ({ protocolId, securityLevel }) =>\n        `Protocol \"${protocolId}\" frame blocked: connection is at security level \"${securityLevel}\" and the protocol did not opt into allowPlain.`,\n    }),\n    /** Phase 4 — rehydrate saw a binding with an unknown schema version: treat the socket as fresh. */\n    binding_version_mismatch: err<{ found: unknown; expected: number }>({\n      message: ({ found, expected }) =>\n        `Persisted connection binding has schema version ${JSON.stringify(found)} (this build reads v${expected}) — the binding is invalidated; the connection must re-handshake.`,\n    }),\n    /**\n     * Inteleport feedback §3 — the peer rejected the handshake because this client's verify key does\n     * not match the one pinned for its identity (trust-on-first-use, keyed `envId::perId`). Permanent\n     * for this identity+key pair: retrying can never succeed, so the keep-alive redial loop PARKS on\n     * it (like `dial_unavailable`) instead of backing off forever. Note clearing the client's *crypto*\n     * storage alone does NOT recover — a fresh key under the SAME persistent id is exactly what the\n     * pin rejects. Recover by connecting under a new persistent id (and a fresh identity), or by\n     * removing the peer-side pin via the verify-key resolver's storage. Branch on it with\n     * `err.hasId(\"identity_pin_mismatch\")`.\n     */\n    identity_pin_mismatch: err<{ reason: string }>({\n      message: ({ reason }) =>\n        `Handshake rejected by peer: ${reason}. The peer has a different verify key pinned for this ` +\n        \"client identity (TOFU) — permanent until the client connects under a new persistent id or \" +\n        \"the peer's pin is removed; auto-redial parks on this.\",\n    }),\n  },\n});\n","import type { TFrame } from \"../Carrier.types\";\n\nexport interface IInboundFrameQueue {\n  /** Take one message event's data: a text or binary frame, or a `Blob` to read first. */\n  receive(data: unknown): void;\n  /** Run `step` once every frame received before it has been delivered (the carrier's close). */\n  afterFrames(step: () => void): void;\n}\n\n/**\n * Inbound frames in arrival order, for a carrier whose message listener must stay a plain function.\n * A string, `ArrayBuffer` or `Uint8Array` is delivered in the turn it arrived. Only a `Blob` has to\n * be read asynchronously, and while one is being read everything behind it waits its turn — a later\n * frame, and the close.\n */\nexport function createInboundFrameQueue(deliver: (frame: TFrame) => void): IInboundFrameQueue {\n  // Set only while a Blob is being read.\n  let reading: Promise<void> | undefined;\n\n  const later = (step: () => void | Promise<void>): void => {\n    const next: Promise<void> = (reading ?? Promise.resolve())\n      .then(step)\n      .catch((error: unknown) => {\n        console.error(\"[nice-wire] an inbound frame could not be delivered:\", error);\n      })\n      .then(() => {\n        if (reading === next) reading = undefined;\n      });\n    reading = next;\n  };\n\n  const inOrder = (step: () => void): void => {\n    if (reading == null) step();\n    else later(step);\n  };\n\n  return {\n    receive: (data) => {\n      if (typeof data === \"string\" || data instanceof ArrayBuffer || data instanceof Uint8Array) {\n        inOrder(() => deliver(data));\n        return;\n      }\n      if (typeof Blob !== \"undefined\" && data instanceof Blob) {\n        later(async () => deliver(await data.arrayBuffer()));\n      }\n    },\n    afterFrames: inOrder,\n  };\n}\n","/**\n * A destination safe to put in diagnostics. Credentials, query parameters, and fragments can carry\n * secrets (capability tokens, signed leases), so only the scheme, host, port, and path survive.\n */\nexport function sanitizeEndpoint(raw: string | undefined): string | undefined {\n  if (raw == null) return undefined;\n  try {\n    const url = new URL(raw);\n    // A host-less parse (`user:secret@host/…` reads as an opaque `user:` URL) gets the fallback.\n    if (url.host !== \"\") {\n      url.username = \"\";\n      url.password = \"\";\n      url.search = \"\";\n      url.hash = \"\";\n      return url.toString();\n    }\n  } catch {\n    // Relative or malformed: handled below.\n  }\n  const head = raw.split(/[?#]/, 1)[0] ?? \"\";\n  const authority = /^([a-z][a-z\\d+.-]*:)?\\/\\//i.exec(head);\n  if (authority != null) {\n    return authority[0] + head.slice(authority[0].length).replace(/^[^/@]*@/, \"\");\n  }\n  return head.replace(/^[^/]*@/, \"\");\n}\n","/**\n * Send a text or binary frame over a socket. A binary formatter may hand back a `Uint8Array` whose\n * backing buffer is typed as `ArrayBufferLike` (msgpackr pools buffers / may be `SharedArrayBuffer`),\n * which `WebSocket.send`'s `BufferSource` parameter rejects — copy it into a fresh `ArrayBuffer`-backed\n * view so the type (and the bytes) are safe to send.\n */\nexport function sendFrame(ws: WebSocket, data: string | Uint8Array | ArrayBuffer): void {\n  if (typeof data === \"string\" || data instanceof ArrayBuffer) {\n    ws.send(data);\n    return;\n  }\n  ws.send(new Uint8Array(data));\n}\n\n/** Compact a WebSocket URL to `host/pathname` for devtools display, falling back to the raw url. */\nexport function shortWs(url: string): string {\n  try {\n    const u = new URL(url);\n    return `${u.host}${u.pathname}`;\n  } catch {\n    return url;\n  }\n}\n","import { err_wire_connect } from \"../../../Connect/err_wire_connect\";\nimport { sanitizeEndpoint } from \"../../../Connect/sanitizeEndpoint\";\nimport type { IDuplexCarrier } from \"../../Carrier.types\";\nimport { createInboundFrameQueue } from \"../inboundFrameQueue\";\nimport { sendFrame } from \"./ws_util\";\n\n/**\n * Adapt a `WebSocket` to the carrier-agnostic {@link IDuplexCarrier}, so the WebSocket becomes\n * \"just another carrier\" under the shared secure session. It owns every WebSocket-specific concern —\n * awaiting `open`, normalizing `Blob` frames to bytes, suppressing the log on a deliberate `close`, and\n * buffering any frame that arrives before the session attaches its handler — leaving the session itself\n * carrier-neutral.\n */\nexport function webSocketByteChannel(ws: WebSocket): IDuplexCarrier {\n  let intentional = false;\n  /**\n   * True once the socket actually opened. A failure *before* this is a failed **dial**, not an\n   * outage: it is reported by rejecting `ready` (and the connector's keep-alive ladder retries it\n   * with backoff). Logging it here would spam the console on every attempt while a peer boots — the\n   * routine dev-restart race — so the pre-open path stays silent and lets `ready` do the talking.\n   */\n  let opened = ws.readyState === WebSocket.OPEN;\n  let onMessage: ((frame: string | ArrayBuffer | Uint8Array) => void) | undefined;\n  let onClose: (() => void) | undefined;\n  // Frames that land before the session calls `attach` (none expected in practice, but never lose one).\n  const preAttach: (string | ArrayBuffer | Uint8Array)[] = [];\n\n  const inbound = createInboundFrameQueue((frame) => {\n    if (onMessage != null) onMessage(frame);\n    else preAttach.push(frame);\n  });\n\n  ws.addEventListener(\"open\", () => {\n    opened = true;\n  });\n  // A plain function on purpose: a listener that returns a promise delivers every frame a few\n  // microtasks late, behind a close that arrived in the same turn.\n  ws.addEventListener(\"message\", (event) => {\n    inbound.receive(event.data);\n  });\n  ws.addEventListener(\"close\", (event) => {\n    if (opened && !intentional) console.warn(\"WebSocket closed:\", event);\n    inbound.afterFrames(() => onClose?.());\n  });\n  ws.addEventListener(\"error\", () => {\n    if (opened) console.warn(`WebSocket error: ${describeSocket(ws)}`);\n    inbound.afterFrames(() => onClose?.());\n  });\n\n  const ready = new Promise<void>((resolve, reject) => {\n    if (ws.readyState === WebSocket.OPEN) {\n      resolve();\n      return;\n    }\n    ws.addEventListener(\"open\", () => resolve(), { once: true });\n    // Reject with a real `Error`, never the raw DOM `Event` — an Event carries no message, so the\n    // error pipeline reports it as \"an unknown and unstructured error was thrown\".\n    ws.addEventListener(\"error\", () => reject(dialFailedError(ws)), { once: true });\n    ws.addEventListener(\n      \"close\",\n      (event) =>\n        reject(\n          unreachableError(ws, `WebSocket closed before open (code=${(event as CloseEvent).code})`),\n        ),\n      { once: true },\n    );\n  });\n\n  return {\n    ready,\n    isOpen: () => ws.readyState === WebSocket.OPEN,\n    send: (frame) => sendFrame(ws, frame),\n    attach: (handlers) => {\n      onMessage = handlers.onMessage;\n      onClose = handlers.onClose;\n      for (const frame of preAttach) handlers.onMessage(frame);\n      preAttach.length = 0;\n    },\n    close: () => {\n      intentional = true;\n      try {\n        ws.close();\n      } catch {\n        // already closing/closed — the close listener still runs cleanup\n      }\n    },\n    get label() {\n      return ws.url != null && ws.url !== \"\" ? ws.url : undefined;\n    },\n  };\n}\n\n/**\n * A failed dial, as a structured error the error pipeline (and a consumer's logs) can actually\n * read. A socket that errors or closes *before* it opened yields no readable response (the browser\n * also hides a refused upgrade's status), so it carries the same typed `endpoint_unreachable` id as\n * the HTTP carrier's `fetch` rejection — that is what\n * makes `EWireConnectFailureKind` trustworthy on both carriers rather than HTTP-only (feedback W3).\n */\nfunction dialFailedError(ws: WebSocket): Error {\n  return unreachableError(ws, \"WebSocket dial failed\");\n}\n\nfunction unreachableError(ws: WebSocket, reason: string): Error {\n  return err_wire_connect.fromId(\"endpoint_unreachable\", {\n    url: ws.url != null && ws.url !== \"\" ? sanitizeEndpoint(ws.url) : undefined,\n    carrierLabel: \"ws\",\n    reason,\n  });\n}\n\nfunction describeSocket(ws: WebSocket): string {\n  return (ws.url != null && ws.url !== \"\" ? sanitizeEndpoint(ws.url) : undefined) ?? \"(no url)\";\n}\n","import type {\n  IWireDialParams,\n  IWireDuplexCarrierSource,\n  IWireRouteInfo,\n} from \"../../../Connect/Connect.types\";\nimport { err_wire_connect } from \"../../../Connect/err_wire_connect\";\nimport { webSocketByteChannel } from \"./webSocketByteChannel\";\nimport { shortWs } from \"./ws_util\";\n\n/** The WebSocket a dial is opened against (derived per dial from the params + dial context). */\nexport interface IWsCarrierRequest {\n  url: string;\n}\n\nexport interface IWsCarrierOptions<TDial = undefined> {\n  /** Run this carrier plainly when used by a high-level client. Defaults to secure. */\n  secure?: boolean;\n  /** Override the reuse key (defaults to `[url]`, so one socket is shared per endpoint). */\n  getCacheKey?: (params: IWireDialParams<TDial>) => string[];\n  /** Override the devtools route info for a specific dial. */\n  getRouteInfo?: (params: IWireDialParams<TDial>) => IWireRouteInfo;\n  /**\n   * Construct the socket for a dial — the **testability seam**: inject a\n   * controllable/instrumented socket to simulate outage, latency, or drops without touching\n   * globals. Crucially, this gates **every** dial including keep-alive redials — which page-level\n   * `window.WebSocket` patching cannot. Must return a socket in CONNECTING state; the carrier sets\n   * `binaryType` itself. Production dials should not need this.\n   */\n  createWebSocket?: (url: string) => WebSocket;\n}\n\n/**\n * A WebSocket {@link IWireDuplexCarrierSource}: opens an `arraybuffer` socket (cached per endpoint)\n * and adapts it to a carrier — generalized over an opaque dial context (shared connection design,\n * E2), so the URL can be derived from whatever domain concept the consumer threads through\n * (nice-action passes the action being dispatched; a realm-only client passes e.g. a game id).\n *\n * `createRequest` derives the socket URL per dial (keep it simple with `() => ({ url })`), so\n * dynamic endpoints need no socket-construction hook for the URL. `createWebSocket` exists for\n * **testability** — injecting a controllable socket (it is not a URL mechanism).\n *\n * `createRequest` may return **`null`** to mean \"no valid endpoint right now\" — a dynamic-endpoint\n * carrier whose mutable dial context was torn down (`matchId` cleared)\n * signals that instead of dialing garbage. The dial throws `dial_unavailable`, which a keep-alive\n * redial loop parks on (resuming at the next explicit `connect()`/dispatch) — so teardown ordering\n * stops mattering.\n */\nexport function wsCarrier<TDial = undefined>(\n  request: string | ((params: IWireDialParams<TDial>) => IWsCarrierRequest | string | null),\n  options: IWsCarrierOptions<TDial> = {},\n): IWireDuplexCarrierSource<TDial> {\n  const createRequest = (params: IWireDialParams<TDial>): IWsCarrierRequest | null => {\n    const resolved = typeof request === \"string\" ? request : request(params);\n    if (resolved == null) return null;\n    return typeof resolved === \"string\" ? { url: resolved } : resolved;\n  };\n  const construct = options.createWebSocket ?? ((url: string) => new WebSocket(url));\n  return {\n    secure: options.secure,\n    carrierLabel: \"ws\",\n    open: (params) => {\n      const request = createRequest(params);\n      if (request == null) {\n        throw err_wire_connect.fromId(\"dial_unavailable\", { carrierLabel: \"ws\" });\n      }\n      const ws = construct(request.url);\n      // Binary responses as ArrayBuffer (not Blob) so the session unpacks them synchronously —\n      // set here (not in the constructor) so injected sockets get it too.\n      ws.binaryType = \"arraybuffer\";\n      return webSocketByteChannel(ws);\n    },\n    getCacheKey:\n      options.getCacheKey ?? ((params) => [createRequest(params)?.url ?? \"ws:(unavailable)\"]),\n    getRouteInfo:\n      options.getRouteInfo ??\n      ((params) => {\n        const url = createRequest(params)?.url;\n        if (url == null) return { carrierLabel: \"ws\", summary: \"ws (unavailable)\" };\n        return { carrierLabel: \"ws\", url, summary: `ws ${shortWs(url)}` };\n      }),\n  };\n}\n","import { err_wire_connect } from \"./err_wire_connect\";\nimport { sanitizeEndpoint } from \"./sanitizeEndpoint\";\n\nexport { sanitizeEndpoint } from \"./sanitizeEndpoint\";\n\n/**\n * What a failed dial actually *was* — the typed discriminator a consumer branches on instead of\n * matching error text (meteor-connect-bridge feedback W3). The values are distinct because each\n * one implies a different next step for the developer:\n *\n * - {@link endpoint_answered_non_protocol} — fix the URL, or the proxy/WAF in front of it.\n * - {@link endpoint_unreachable} — no response was received: check the network, the server, and\n *   (in a browser) CORS or a refused WebSocket upgrade, which the platform reports the same way.\n *   A connection that opened and then closed or stayed silent through the handshake\n *   (`closed_during_handshake`, `handshake_timeout`) is this kind too: nothing answered the\n *   protocol, and the next step is the same.\n * - {@link handshake_rejected} — it *is* a nice-code backend and it said no (e.g. a pinned\n *   identity): fix the identity or the version, not the address.\n * - {@link protocol_version_mismatch} — the peer explicitly reported no compatible secure-wire\n *   generation; upgrade or roll back one side, then retry explicitly.\n * - {@link crypto_unavailable} — nothing was dialed: this runtime has no WebCrypto. Serve the page\n *   over HTTPS, or install the polyfill.\n */\nexport enum EWireConnectFailureKind {\n  endpoint_answered_non_protocol = \"endpoint_answered_non_protocol\",\n  endpoint_unreachable = \"endpoint_unreachable\",\n  handshake_rejected = \"handshake_rejected\",\n  protocol_version_mismatch = \"protocol_version_mismatch\",\n  peer_identity_mismatch = \"peer_identity_mismatch\",\n  crypto_unavailable = \"crypto_unavailable\",\n  unknown = \"unknown\",\n}\n\n/**\n * How much of a non-protocol body an error message may carry. Deliberately short: a WAF's 40 KB\n * HTML page pasted into an error is worse DX than no preview at all.\n */\nconst BODY_PREVIEW_LIMIT = 200;\n\n/** Replace C0, DEL, and C1 characters that would corrupt terminals and log lines. */\nfunction replaceControlCharacters(raw: string): string {\n  return Array.from(raw, (character) => {\n    const codePoint = character.codePointAt(0)!;\n    return codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f) ? \" \" : character;\n  }).join(\"\");\n}\n\n/**\n * A bounded, single-line, control-character-free head of whatever a non-protocol endpoint sent\n * back — enough to recognize an HTML error page or a proxy banner on sight. Only the *response* is\n * ever summarized: no request headers, no request body.\n */\nexport function describeNonProtocolBody(raw: unknown): string | undefined {\n  if (typeof raw !== \"string\") return undefined;\n  const flattened = replaceControlCharacters(raw).replace(/\\s+/g, \" \").trim();\n  if (flattened.length === 0) return undefined;\n  return flattened.length > BODY_PREVIEW_LIMIT\n    ? `${flattened.slice(0, BODY_PREVIEW_LIMIT)}…`\n    : flattened;\n}\n\n/**\n * Classify a dial failure. Reads typed ids only — the ids are raised at the layer that still holds\n * the evidence precisely so this never has to sniff message text.\n */\nexport function classifyConnectFailure(error: unknown): EWireConnectFailureKind {\n  if (!err_wire_connect.isExact(error)) return EWireConnectFailureKind.unknown;\n  if (error.hasId(\"endpoint_answered_non_protocol\")) {\n    return EWireConnectFailureKind.endpoint_answered_non_protocol;\n  }\n  if (\n    error.hasId(\"endpoint_unreachable\") ||\n    error.hasId(\"closed_during_handshake\") ||\n    error.hasId(\"handshake_timeout\")\n  ) {\n    return EWireConnectFailureKind.endpoint_unreachable;\n  }\n  if (error.hasId(\"protocol_version_mismatch\")) {\n    return EWireConnectFailureKind.protocol_version_mismatch;\n  }\n  if (error.hasId(\"peer_identity_mismatch\")) {\n    return EWireConnectFailureKind.peer_identity_mismatch;\n  }\n  if (error.hasId(\"crypto_unavailable\")) return EWireConnectFailureKind.crypto_unavailable;\n  if (error.hasId(\"identity_pin_mismatch\") || error.hasId(\"handshake_rejected\")) {\n    return EWireConnectFailureKind.handshake_rejected;\n  }\n  return EWireConnectFailureKind.unknown;\n}\n\n/** The endpoint a failure names, when it carries one — the URL actually dialed, sanitized. */\nexport function endpointFromConnectFailure(error: unknown): string | undefined {\n  if (!err_wire_connect.isExact(error)) return undefined;\n  if (error.hasId(\"endpoint_answered_non_protocol\")) {\n    return sanitizeEndpoint(error.getContext(\"endpoint_answered_non_protocol\").url);\n  }\n  if (error.hasId(\"endpoint_unreachable\")) {\n    return sanitizeEndpoint(error.getContext(\"endpoint_unreachable\").url);\n  }\n  if (error.hasId(\"closed_during_handshake\")) {\n    return sanitizeEndpoint(error.getContext(\"closed_during_handshake\").url);\n  }\n  if (error.hasId(\"handshake_timeout\")) {\n    return sanitizeEndpoint(error.getContext(\"handshake_timeout\").url);\n  }\n  if (error.hasId(\"peer_identity_mismatch\")) {\n    return sanitizeEndpoint(error.getContext(\"peer_identity_mismatch\").endpoint);\n  }\n  return undefined;\n}\n","import {\n  classifyConnectFailure,\n  type EWireConnectFailureKind,\n  endpointFromConnectFailure,\n  sanitizeEndpoint,\n} from \"./endpointEvidence\";\nimport { err_wire_connect } from \"./err_wire_connect\";\nimport {\n  type ETransportShape,\n  ETransportStatus,\n  type IWireConnectionMethodsBase,\n  type IWireTransportReady,\n  type TTransportCache,\n  type TWireManagedConnection,\n} from \"./transportRuntime.types\";\n\n/**\n * Everything known about why a dial chain came up empty — enough for the thrown error to be\n * self-locating (feedback W2: *which* endpoint) and branchable (W3: *what kind* of failure)\n * without anyone parsing a message.\n */\nexport interface IWireTransportInitializationFailure {\n  /** The most relevant underlying failure, as text for the message. */\n  cause?: string;\n  /** The endpoint that failed — the URL the carrier actually dialed, when one is known. */\n  endpoint?: string;\n  /** Answered-wrongly vs unreachable vs rejected — the discriminator consumers branch on. */\n  kind: EWireConnectFailureKind;\n  /** The underlying error, attached as the origin so the full chain survives. */\n  origin: unknown;\n}\n\n/**\n * The selection-failure vocabulary, injected by the consumer so its errors keep their native\n * domain/ids (nice-action supplies `err_nice_transport` factories — its tests and consumers see\n * the exact same errors as before the move).\n */\nexport interface IWireTransportSelectionErrors<RP> {\n  /** Transport(s) found but every one reported unsupported/unavailable for this dispatch. */\n  unsupported(transportShapes: ETransportShape[]): Error;\n  /** No transports produced a candidate at all. */\n  notFound(input: RP): Error;\n  /** Every candidate failed to initialize; see {@link IWireTransportInitializationFailure}. */\n  initializationFailed(input: RP, failure: IWireTransportInitializationFailure): Error;\n}\n\n/**\n * Preference-ordered transport selection over a shared connection cache — moved from nice-action\n * with the routing params (`RP`), finalized methods\n * (`METHODS`), and connection type (`CONN`) generic. Behavior is byte-for-byte the pre-move\n * logic: strict preference order with parallel warm-up, cache adoption guarded against teardown\n * races, and disconnect-driven eviction.\n */\nexport class ConnectionTransportManager<\n  RP,\n  METHODS extends IWireConnectionMethodsBase,\n  CONN extends TWireManagedConnection<RP, METHODS> = TWireManagedConnection<RP, METHODS>,\n> {\n  private _transports: CONN[] = [];\n\n  constructor(\n    private _cache: TTransportCache<METHODS, CONN>,\n    private readonly _errors: IWireTransportSelectionErrors<RP>,\n  ) {}\n\n  addTransport(transport: CONN) {\n    this._transports.push(transport);\n  }\n\n  /**\n   * The highest-priority transport (first declared). Used to label a dispatch's route *before* the\n   * transport has finished connecting — so a still-connecting dispatch shows its (expected)\n   * destination instead of an \"unknown\" hop. {@link getReadyTransport} still decides the real winner,\n   * and the caller corrects the hop if a lower-priority transport ends up serving it.\n   */\n  getPreferredTransport(): CONN | undefined {\n    return this._transports[0];\n  }\n\n  async getReadyTransport(input: RP): Promise<IWireTransportReady<METHODS, CONN>> {\n    // The transports are declared in preference order. We honour that order strictly: a\n    // higher-priority transport that is still *initializing* (e.g. a WebSocket warming up its\n    // connection / handshake) takes precedence over a lower-priority transport that happens to be\n    // synchronously ready right now (e.g. plain HTTP). A lower-priority transport is only used as a\n    // fallback once every transport ahead of it has been exhausted (unsupported or failed). This is\n    // what lets a transport \"warm up\" on the first dispatch instead of racing — and quietly losing —\n    // to an always-ready fallback.\n    // Each candidate keeps a backref to the transport that produced it: without it a failure can\n    // report *that* the chain failed but never *where* it was dialing (feedback W2).\n    const candidates: ISelectionCandidate<METHODS, CONN>[] = [];\n    const unavailableTransports: CONN[] = [];\n    let cryptoUnavailable: unknown;\n\n    for (const transport of this._transports) {\n      // One transport's synchronous throw (an availability gate, a URL callback, a carrier `open`)\n      // is that candidate's failure, never the whole selection's.\n      let cacheKey: string | null = null;\n      try {\n        // Availability gate — consulted *before* cache-key resolution and `getTransport`. A\n        // transport that declares itself unavailable for this dispatch is skipped entirely, so its\n        // cache key is never computed and its carrier is never opened.\n        if (!transport.isAvailable(input)) {\n          unavailableTransports.push(transport);\n          continue;\n        }\n\n        cacheKey = transport.getCacheKey(input);\n\n        if (cacheKey != null) {\n          const cached = this._cache.get(cacheKey);\n          if (cached != null) {\n            if (cached instanceof Promise) {\n              candidates.push({ transport, promise: cached, cacheKey, fresh: false });\n              continue;\n            }\n            // A live, ready cached transport: nothing lower priority can outrank it, so stop scanning.\n            candidates.push({\n              transport,\n              promise: Promise.resolve({ ...cached, transport }),\n              cacheKey,\n              fresh: false,\n            });\n            break;\n          }\n        }\n\n        const statusInfo = transport.getTransport(input);\n\n        if (statusInfo.status === ETransportStatus.ready) {\n          const readyData = statusInfo.readyData;\n          if (cacheKey != null) {\n            const key = cacheKey;\n            const entry = { methods: readyData, transport };\n            this._cache.set(key, entry);\n            // Only evict if this exact entry is still cached — a socket that closes after the cache\n            // was re-populated (e.g. a teardown then reconnect under the same key) must not drop the\n            // new one.\n            readyData.addOnDisconnectListener?.(() => {\n              if (this._cache.get(key) === entry) this._cache.delete(key);\n            });\n          }\n          // A synchronously-ready transport is a terminal fallback: anything after it is unreachable.\n          candidates.push({\n            transport,\n            promise: Promise.resolve({ methods: readyData, transport }),\n            cacheKey,\n            fresh: true,\n          });\n          break;\n        }\n\n        if (statusInfo.status === ETransportStatus.unsupported) {\n          unavailableTransports.push(transport);\n          continue;\n        }\n\n        if (statusInfo.status === ETransportStatus.initializing) {\n          const key = cacheKey;\n          const promise: Promise<IWireTransportReady<METHODS, CONN>> =\n            statusInfo.initializationPromise\n              .then((info): IWireTransportReady<METHODS, CONN> => {\n                if (info.status === ETransportStatus.failed) {\n                  throw info.error;\n                }\n\n                if (info.status === ETransportStatus.unsupported) {\n                  throw this._errors.unsupported([transport.type]);\n                }\n\n                const readyData = info.readyData;\n                const entry = { methods: readyData, transport };\n                if (key != null) {\n                  // Adopt the cache slot only if our placeholder promise is still there. A teardown\n                  // (clearTransportCache) or a newer connection on the same key may have replaced it\n                  // while we were connecting — in that case this socket is orphaned, so close it\n                  // instead of clobbering the live entry. The awaiting dispatch then aborts cleanly\n                  // on the closed socket.\n                  if (this._cache.get(key) === promise) {\n                    this._cache.set(key, entry);\n                    readyData.addOnDisconnectListener?.(() => {\n                      if (this._cache.get(key) === entry) this._cache.delete(key);\n                    });\n                  } else {\n                    readyData.disconnect?.();\n                  }\n                }\n\n                return entry;\n              })\n              .catch((e) => {\n                // Only clear our own slot — a newer connection may already own the key.\n                if (key != null && this._cache.get(key) === promise) {\n                  this._cache.delete(key);\n                }\n                throw e;\n              });\n          // Warm-ups that lose selection are never awaited; their failures must not surface as\n          // unhandled rejections.\n          promise.catch(() => {});\n\n          if (key != null) {\n            this._cache.set(key, promise);\n          }\n\n          candidates.push({ transport, promise, cacheKey: key, fresh: true });\n        }\n      } catch (e) {\n        // `dial_unavailable` behind an earlier candidate only means this fallback has no endpoint\n        // for this dial; as the first candidate it stays the selection's park signal.\n        if (isDialUnavailable(e)) {\n          if (candidates.length === 0) throw e;\n          unavailableTransports.push(transport);\n          continue;\n        }\n        // A secure transport in a runtime without WebCrypto can never dial, while a plain one\n        // beside it still can: it is the selection's answer only when nothing else could serve.\n        if (isCryptoUnavailable(e)) {\n          cryptoUnavailable ??= e;\n          continue;\n        }\n        const failed = Promise.reject(e);\n        failed.catch(() => {});\n        candidates.push({ transport, promise: failed, cacheKey, fresh: true, callerThrew: true });\n      }\n    }\n\n    if (candidates.length === 0) {\n      // Rethrown unwrapped, so a keep-alive redial loop can recognize it and park.\n      if (cryptoUnavailable != null) throw cryptoUnavailable;\n      if (unavailableTransports.length > 0) {\n        throw this._errors.unsupported(unavailableTransports.map((t) => t.type));\n      }\n\n      throw this._errors.notFound(input);\n    }\n\n    // Resolve candidates in priority order, falling through to the next only when the preferred\n    // transport actually fails. Initialization for every candidate was already kicked off above, so\n    // they all warm up in parallel — we simply *select* the winner by declared preference.\n    let lastError: unknown;\n    let lastTransport: CONN | undefined;\n    let lastCallerThrew = false;\n    for (const candidate of candidates) {\n      let ready: IWireTransportReady<METHODS, CONN>;\n      try {\n        ready = await candidate.promise;\n      } catch (e) {\n        // A peer that explicitly reports a different identity or an incompatible protocol\n        // generation is authoritative for this dial target. Never continue into a lower-priority\n        // carrier (especially a plain HTTP fallback), and release the warm-ups this selection\n        // started, so nothing keeps talking to the endpoint behind the rejected one.\n        if (isTerminalSelectionError(e)) {\n          this._abandonWarmUps(candidates, candidate);\n          throw this._withDialedEndpoint(e, candidate.transport, input);\n        }\n        lastError = e;\n        lastTransport = candidate.transport;\n        lastCallerThrew = candidate.callerThrew === true;\n        continue;\n      }\n      ready.methods.onSelected?.();\n      return ready;\n    }\n\n    // `dial_unavailable` is a policy signal (\"no endpoint exists right now\"), not a failure —\n    // rethrown UNWRAPPED so a keep-alive redial loop can recognize it and park instead of backing\n    // off.\n    // Identity and protocol-version mismatches get the same treatment: they are terminal for the\n    // current identity/build pair, must stop carrier fallback, and must remain branchable so the\n    // redial loop can park until an explicit retry.\n    if (\n      err_wire_connect.isExact(lastError) &&\n      (lastError.hasId(\"dial_unavailable\") ||\n        lastError.hasId(\"identity_pin_mismatch\") ||\n        lastError.hasId(\"protocol_version_mismatch\") ||\n        lastError.hasId(\"peer_identity_mismatch\"))\n    ) {\n      throw lastError;\n    }\n    // The app's own callback threw (a fail-closed guard in a URL builder, say) and nothing else\n    // could serve: surface its error as-is rather than as a transport failure.\n    if (lastCallerThrew && !err_wire_connect.isExact(lastError)) throw lastError;\n    throw this._errors.initializationFailed(input, {\n      cause: describeTransportFailure(lastError),\n      // The carrier's own URL wins: it is the endpoint actually dialed, where the route info is\n      // only what the definition could resolve up front.\n      endpoint: endpointFromConnectFailure(lastError) ?? routeEndpoint(lastTransport, input),\n      kind: classifyConnectFailure(lastError),\n      origin: lastError,\n    });\n  }\n\n  /**\n   * Close the parallel warm-ups this selection started besides `failed`. Each one's cache slot is\n   * released so a later dispatch re-dials; a warm-up still connecting closes itself when it lands.\n   */\n  private _abandonWarmUps(\n    candidates: readonly ISelectionCandidate<METHODS, CONN>[],\n    failed: ISelectionCandidate<METHODS, CONN>,\n  ): void {\n    for (const candidate of candidates) {\n      if (candidate === failed || !candidate.fresh) continue;\n      const key = candidate.cacheKey;\n      if (key != null && this._cache.get(key) === candidate.promise) this._cache.delete(key);\n      candidate.promise.then(\n        (entry) => {\n          if (key == null) {\n            entry.methods.disconnect?.();\n            return;\n          }\n          const cached = this._cache.get(key);\n          if (cached != null && !(cached instanceof Promise) && cached.methods === entry.methods) {\n            this._cache.delete(key);\n            entry.methods.disconnect?.();\n          }\n        },\n        () => {},\n      );\n    }\n  }\n\n  /** Attach the sanitized dialed endpoint to a peer-identity mismatch that lacks one. */\n  private _withDialedEndpoint(error: unknown, transport: CONN, input: RP): unknown {\n    if (!err_wire_connect.isExact(error) || !error.hasId(\"peer_identity_mismatch\")) return error;\n    const context = error.getContext(\"peer_identity_mismatch\");\n    if (context.endpoint != null) return error;\n    // A URL callback that throws here (e.g. its target was torn down mid-handshake) must not\n    // replace the typed mismatch.\n    const endpoint = routeEndpoint(transport, input);\n    if (endpoint == null) return error;\n    return err_wire_connect\n      .fromId(\"peer_identity_mismatch\", { ...context, endpoint })\n      .withOriginError(error);\n  }\n}\n\ninterface ISelectionCandidate<METHODS extends IWireConnectionMethodsBase, CONN> {\n  transport: CONN;\n  promise: Promise<IWireTransportReady<METHODS, CONN>>;\n  cacheKey: string | null;\n  /** Started by this selection (not adopted from the cache), so this selection may release it. */\n  fresh: boolean;\n  /** Failed synchronously in the transport's own hooks (availability gate, URL callback, `open`). */\n  callerThrew?: boolean;\n}\n\nconst isDialUnavailable = (error: unknown): boolean =>\n  err_wire_connect.isExact(error) && error.hasId(\"dial_unavailable\");\n\nconst isCryptoUnavailable = (error: unknown): boolean =>\n  err_wire_connect.isExact(error) && error.hasId(\"crypto_unavailable\");\n\nconst isTerminalSelectionError = (error: unknown): boolean =>\n  err_wire_connect.isExact(error) &&\n  (error.hasId(\"peer_identity_mismatch\") || error.hasId(\"protocol_version_mismatch\"));\n\n/** The transport's sanitized route URL for diagnostics; a throwing route resolver yields none. */\nfunction routeEndpoint<RP>(\n  transport: { getRouteInfo(input: RP): { url?: string } | undefined } | undefined,\n  input: RP,\n): string | undefined {\n  if (transport == null) return undefined;\n  try {\n    return sanitizeEndpoint(transport.getRouteInfo(input)?.url);\n  } catch {\n    return undefined;\n  }\n}\n\n/**\n * A short, human-readable reason for a transport failing to connect — surfaced in the\n * consumer's initialization-failed message so the caller sees *why* (e.g. a rejected handshake) rather\n * than a bare \"not ready\". The full error is still attached as the origin error for the complete\n * chain/stack.\n */\nfunction describeTransportFailure(error: unknown): string | undefined {\n  if (error == null) return undefined;\n  if (error instanceof Error) return error.message;\n  if (typeof error === \"string\") return error;\n  return String(error);\n}\n","export const notNullEmpty = (str: string | null | undefined): str is string => {\n  return str != null && str.length > 0;\n};\n\nexport const nullEmpty = (str: string | null | undefined): str is null | undefined | \"\" => {\n  return !notNullEmpty(str);\n};\n\nexport const firstNotNullEmpty = (\n  ...strItems: (string | null | undefined)[]\n): string | undefined => {\n  for (const item of strItems) {\n    if (notNullEmpty(item)) {\n      return item;\n    }\n  }\n\n  return undefined;\n};\n","export const createSharedBitsFromX25519 = async ({\n  privateKey,\n  publicKey,\n}: {\n  privateKey: CryptoKey;\n  publicKey: CryptoKey;\n}): Promise<Uint8Array> => {\n  return new Uint8Array(\n    await crypto.subtle.deriveBits({ name: \"X25519\", public: publicKey }, privateKey, 256),\n  );\n};\n","import { notNullEmpty } from \"../../data_type/string/nullEmpty\";\nimport { createSharedBitsFromX25519 } from \"../x25519/createSharedBitsFromX25519\";\n\nconst DEFAULT_INFO_STRING = \"METEOR_BRIDGE_DEFAULT_INFO_STRING\";\n\nexport const createAesGcmKeyFromX25519Keys = async ({\n  externalX25519PublicKey,\n  internalX25519PrivateKey,\n  infoString,\n  saltString,\n}: {\n  internalX25519PrivateKey: CryptoKey;\n  externalX25519PublicKey: CryptoKey;\n  saltString?: string;\n  infoString?: string;\n}): Promise<CryptoKey> => {\n  const sharedBits = await createSharedBitsFromX25519({\n    privateKey: internalX25519PrivateKey,\n    publicKey: externalX25519PublicKey,\n  });\n\n  // Initial Key Material\n  const ikm = await crypto.subtle.importKey(\"raw\", new Uint8Array(sharedBits), \"HKDF\", false, [\n    \"deriveKey\",\n  ]);\n\n  const salt = notNullEmpty(saltString) ? new TextEncoder().encode(saltString) : new Uint8Array();\n  const info = new TextEncoder().encode(\n    notNullEmpty(infoString) ? infoString : DEFAULT_INFO_STRING,\n  );\n\n  // Run HKDF to get your final usable key (e.g., AES-GCM)\n  return await crypto.subtle.deriveKey(\n    {\n      name: \"HKDF\",\n      hash: \"SHA-256\",\n      salt, // Salt\n      info, // Context string\n    },\n    ikm,\n    { name: \"AES-GCM\", length: 256 },\n    false, // The final AES key shouldn't be exportable\n    [\"encrypt\", \"decrypt\"],\n  );\n};\n","import type { TEncryptedAesGcmBytes } from \"../crypto.schema\";\n\n/**\n * Decrypts a raw-bytes AES-GCM payload (binary nonce + ciphertext) back to bytes. The counterpart of\n * {@link decryptTextDataWithAesGcmKey}. AES-GCM verifies integrity, so a tampered ciphertext throws.\n */\nexport const decryptBytesWithAesGcmKey = async ({\n  aesGcmKey,\n  dataToDecrypt,\n}: {\n  aesGcmKey: CryptoKey;\n  dataToDecrypt: TEncryptedAesGcmBytes;\n}): Promise<Uint8Array> => {\n  const decryptedData = await crypto.subtle.decrypt(\n    // Re-view nonce + ciphertext over plain ArrayBuffers so WebCrypto's `BufferSource` is satisfied\n    // regardless of the source's backing buffer (msgpack output may be pooled / SharedArrayBuffer-typed).\n    { name: \"AES-GCM\", iv: new Uint8Array(dataToDecrypt.nonce) },\n    aesGcmKey,\n    new Uint8Array(dataToDecrypt.ciphertext),\n  );\n\n  return new Uint8Array(decryptedData);\n};\n","/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nfunction isBytes(a) {\n    // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases. The\n    // fallback still requires a real ArrayBuffer view, so plain JSON-deserialized\n    // `{ constructor: ... }` spoofing is rejected. `BYTES_PER_ELEMENT === 1` keeps the\n    // fallback on byte-oriented views.\n    return (a instanceof Uint8Array ||\n        (ArrayBuffer.isView(a) &&\n            a.constructor.name === 'Uint8Array' &&\n            'BYTES_PER_ELEMENT' in a &&\n            a.BYTES_PER_ELEMENT === 1));\n}\n/** Asserts something is Uint8Array. */\nfunction abytes(b) {\n    if (!isBytes(b))\n        throw new TypeError('Uint8Array expected');\n}\nfunction isArrayOf(isString, arr) {\n    if (!Array.isArray(arr))\n        return false;\n    if (arr.length === 0)\n        return true;\n    if (isString) {\n        return arr.every((item) => typeof item === 'string');\n    }\n    else {\n        return arr.every((item) => Number.isSafeInteger(item));\n    }\n}\nfunction afn(input) {\n    if (typeof input !== 'function')\n        throw new TypeError('function expected');\n    return true;\n}\nfunction astr(label, input) {\n    if (typeof input !== 'string')\n        throw new TypeError(`${label}: string expected`);\n    return true;\n}\nfunction anumber(n) {\n    if (typeof n !== 'number')\n        throw new TypeError(`number expected, got ${typeof n}`);\n    if (!Number.isSafeInteger(n))\n        throw new RangeError(`invalid integer: ${n}`);\n}\nfunction aArr(input) {\n    if (!Array.isArray(input))\n        throw new TypeError('array expected');\n}\nfunction astrArr(label, input) {\n    if (!isArrayOf(true, input))\n        throw new TypeError(`${label}: array of strings expected`);\n}\nfunction anumArr(label, input) {\n    if (!isArrayOf(false, input))\n        throw new TypeError(`${label}: array of numbers expected`);\n}\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction chain(...args) {\n    const id = (a) => a;\n    // Wrap call in closure so JIT can inline calls\n    const wrap = (a, b) => (c) => a(b(c));\n    // Construct chain of args[-1].encode(args[-2].encode([...]))\n    const encode = args.map((x) => x.encode).reduceRight(wrap, id);\n    // Construct chain of args[0].decode(args[1].decode(...))\n    const decode = args.map((x) => x.decode).reduce(wrap, id);\n    return { encode, decode };\n}\n/**\n * Encodes integer radix representation to array of strings using alphabet and back.\n * Could also be array of strings.\n * @__NO_SIDE_EFFECTS__\n */\nfunction alphabet(letters) {\n    // mapping 1 to \"b\"\n    const lettersA = typeof letters === 'string' ? letters.split('') : letters;\n    const len = lettersA.length;\n    astrArr('alphabet', lettersA);\n    // mapping \"b\" to 1\n    const indexes = new Map(lettersA.map((l, i) => [l, i]));\n    return {\n        encode: (digits) => {\n            aArr(digits);\n            return digits.map((i) => {\n                if (!Number.isSafeInteger(i) || i < 0 || i >= len)\n                    throw new Error(`alphabet.encode: digit index outside alphabet \"${i}\". Allowed: ${letters}`);\n                return lettersA[i];\n            });\n        },\n        decode: (input) => {\n            aArr(input);\n            return input.map((letter) => {\n                astr('alphabet.decode', letter);\n                const i = indexes.get(letter);\n                if (i === undefined)\n                    throw new Error(`Unknown letter: \"${letter}\". Allowed: ${letters}`);\n                return i;\n            });\n        },\n    };\n}\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction join(separator = '') {\n    astr('join', separator);\n    // join('') is only lossless when each chunk is already unambiguous, such as single-symbol alphabets.\n    // Multi-character tokens need a separator that cannot appear inside the chunks.\n    return {\n        encode: (from) => {\n            astrArr('join.decode', from);\n            return from.join(separator);\n        },\n        decode: (to) => {\n            astr('join.decode', to);\n            return to.split(separator);\n        },\n    };\n}\n/**\n * Pad strings array so it has integer number of bits\n * @__NO_SIDE_EFFECTS__\n */\nfunction padding(bits, chr = '=') {\n    anumber(bits);\n    astr('padding', chr);\n    return {\n        encode(data) {\n            astrArr('padding.encode', data);\n            // Mutates the intermediate token array in place while appending pad chars.\n            // utils.padding callers that need to preserve their input should pass a copy.\n            while ((data.length * bits) % 8)\n                data.push(chr);\n            return data;\n        },\n        decode(input) {\n            astrArr('padding.decode', input);\n            let end = input.length;\n            if ((end * bits) % 8)\n                throw new Error('padding: invalid, string should have whole number of bytes');\n            for (; end > 0 && input[end - 1] === chr; end--) {\n                const last = end - 1;\n                const byte = last * bits;\n                if (byte % 8 === 0)\n                    throw new Error('padding: invalid, string has too much padding');\n            }\n            return input.slice(0, end);\n        },\n    };\n}\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction normalize(fn) {\n    afn(fn);\n    return { encode: (from) => from, decode: (to) => fn(to) };\n}\n/**\n * Slow: O(n^2) time complexity\n */\nfunction convertRadix(data, from, to) {\n    // base 1 is impossible\n    if (from < 2)\n        throw new RangeError(`convertRadix: invalid from=${from}, base cannot be less than 2`);\n    if (to < 2)\n        throw new RangeError(`convertRadix: invalid to=${to}, base cannot be less than 2`);\n    aArr(data);\n    if (!data.length)\n        return [];\n    let pos = 0;\n    const res = [];\n    const digits = Array.from(data, (d) => {\n        anumber(d);\n        if (d < 0 || d >= from)\n            throw new Error(`invalid integer: ${d}`);\n        return d;\n    });\n    const dlen = digits.length;\n    while (true) {\n        let carry = 0;\n        let done = true;\n        for (let i = pos; i < dlen; i++) {\n            const digit = digits[i];\n            const fromCarry = from * carry;\n            const digitBase = fromCarry + digit;\n            if (!Number.isSafeInteger(digitBase) ||\n                fromCarry / from !== carry ||\n                digitBase - digit !== fromCarry) {\n                throw new Error('convertRadix: carry overflow');\n            }\n            const div = digitBase / to;\n            carry = digitBase % to;\n            const rounded = Math.floor(div);\n            digits[i] = rounded;\n            if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase)\n                throw new Error('convertRadix: carry overflow');\n            if (!done)\n                continue;\n            else if (!rounded)\n                pos = i;\n            else\n                done = false;\n        }\n        res.push(carry);\n        if (done)\n            break;\n    }\n    // Preserve explicit leading zero digits so callers like base58 keep zero-prefix semantics.\n    for (let i = 0; i < data.length - 1 && data[i] === 0; i++)\n        res.push(0);\n    return res.reverse();\n}\nconst gcd = (a, b) => (b === 0 ? a : gcd(b, a % b));\n// Maximum carry width before the `pos` cycle repeats.\n// Residues advance in gcd(from, to) steps, so the largest pre-drain width is from + (to - gcd).\nconst radix2carry = /* @__NO_SIDE_EFFECTS__ */ (from, to) => from + (to - gcd(from, to));\nconst powers = /* @__PURE__ */ (() => {\n    let res = [];\n    for (let i = 0; i < 40; i++)\n        res.push(2 ** i);\n    return res;\n})();\n/**\n * Implemented with numbers, because BigInt is 5x slower\n */\nfunction convertRadix2(data, from, to, padding) {\n    aArr(data);\n    if (from <= 0 || from > 32)\n        throw new RangeError(`convertRadix2: wrong from=${from}`);\n    if (to <= 0 || to > 32)\n        throw new RangeError(`convertRadix2: wrong to=${to}`);\n    if (radix2carry(from, to) > 32) {\n        throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`);\n    }\n    let carry = 0;\n    let pos = 0; // bitwise position in current element\n    const max = powers[from];\n    const mask = powers[to] - 1;\n    const res = [];\n    for (const n of data) {\n        anumber(n);\n        if (n >= max)\n            throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);\n        carry = (carry << from) | n;\n        if (pos + from > 32)\n            throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);\n        pos += from;\n        for (; pos >= to; pos -= to)\n            res.push(((carry >> (pos - to)) & mask) >>> 0);\n        const pow = powers[pos];\n        if (pow === undefined)\n            throw new Error('invalid carry');\n        carry &= pow - 1; // clean carry, otherwise it will cause overflow\n    }\n    carry = (carry << (to - pos)) & mask;\n    // Canonical decode paths reject leftover whole input words and non-zero pad bits.\n    // For Bech32 5->8 regrouping, this is the \"4 bits or less, all zeroes\" tail rule.\n    if (!padding && pos >= from)\n        throw new Error('Excess padding');\n    if (!padding && carry > 0)\n        throw new Error(`Non-zero padding: ${carry}`);\n    if (padding && pos > 0)\n        res.push(carry >>> 0);\n    return res;\n}\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction radix(num) {\n    anumber(num);\n    const _256 = 2 ** 8;\n    // Base-range and carry-overflow checks live in convertRadix so encode/decode reject unsupported bases symmetrically.\n    return {\n        encode: (bytes) => {\n            if (!isBytes(bytes))\n                throw new TypeError('radix.encode input should be Uint8Array');\n            return convertRadix(Array.from(bytes), _256, num);\n        },\n        decode: (digits) => {\n            anumArr('radix.decode', digits);\n            return Uint8Array.from(convertRadix(digits, num, _256));\n        },\n    };\n}\n/**\n * If both bases are power of same number (like `2**8 <-> 2**64`),\n * there is a linear algorithm. For now we have implementation for power-of-two bases only.\n * @__NO_SIDE_EFFECTS__\n */\nfunction radix2(bits, revPadding = false) {\n    anumber(bits);\n    if (bits <= 0 || bits > 32)\n        throw new RangeError('radix2: bits should be in (0..32]');\n    if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32)\n        throw new RangeError('radix2: carry overflow');\n    // revPadding flips which direction allows a partial zero tail.\n    // Default pads 8->bits and rejects extra bits on bits->8; `true` does the opposite.\n    return {\n        encode: (bytes) => {\n            if (!isBytes(bytes))\n                throw new TypeError('radix2.encode input should be Uint8Array');\n            return convertRadix2(Array.from(bytes), 8, bits, !revPadding);\n        },\n        decode: (digits) => {\n            anumArr('radix2.decode', digits);\n            return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));\n        },\n    };\n}\nfunction unsafeWrapper(fn) {\n    afn(fn);\n    return function (...args) {\n        // Only for *Unsafe APIs that intentionally collapse validation failures to `undefined`.\n        // Do not wrap code that needs to preserve exception details.\n        try {\n            return fn.apply(null, args);\n        }\n        catch (e) { }\n    };\n}\nfunction checksum(len, fn) {\n    anumber(len);\n    // Reject degenerate zero-byte checksums up front so callers don't accidentally\n    // build a no-op checksum stage.\n    if (len <= 0)\n        throw new RangeError(`checksum length must be positive: ${len}`);\n    afn(fn);\n    const _fn = fn;\n    // Uses the first `len` bytes of fn(data) in both directions.\n    // Current call sites rely on `len > 0` and checksum functions that return at least that many bytes.\n    return {\n        encode(data) {\n            if (!isBytes(data))\n                throw new TypeError('checksum.encode: input should be Uint8Array');\n            const sum = _fn(data).slice(0, len);\n            const res = new Uint8Array(data.length + len);\n            res.set(data);\n            res.set(sum, data.length);\n            return res;\n        },\n        decode(data) {\n            if (!isBytes(data))\n                throw new TypeError('checksum.decode: input should be Uint8Array');\n            const payload = data.slice(0, -len);\n            const oldChecksum = data.slice(-len);\n            const newChecksum = _fn(payload).slice(0, len);\n            for (let i = 0; i < len; i++)\n                if (newChecksum[i] !== oldChecksum[i])\n                    throw new Error('Invalid checksum');\n            return payload;\n        },\n    };\n}\n// prettier-ignore\n/**\n * Low-level building blocks used by the exported codecs.\n * @example\n * Build a radix-32 coder from the low-level helpers.\n * ```ts\n * import { utils } from '@scure/base';\n * utils.radix2(5).encode(Uint8Array.from([1, 2, 3]));\n * ```\n */\nexport const utils = /* @__PURE__ */ Object.freeze({\n    alphabet, chain, checksum, convertRadix, convertRadix2, radix, radix2, join, padding,\n});\n// RFC 4648 aka RFC 3548\n// ---------------------\n/**\n * base16 encoding from RFC 4648.\n * This codec uses RFC 4648 Table 5's uppercase alphabet directly.\n * RFC 4648 §8 calls base16 \"case-insensitive hex encoding\", but we intentionally do not case-fold decode input here.\n * Use `hex` for case-insensitive hex decoding.\n * @example\n * ```js\n * base16.encode(Uint8Array.from([0x12, 0xab]));\n * // => '12AB'\n * ```\n */\nexport const base16 = /* @__PURE__ */ Object.freeze(chain(radix2(4), alphabet('0123456789ABCDEF'), join('')));\n/**\n * base32 encoding from RFC 4648. Has padding.\n * RFC 4648 §6 Table 3 uses uppercase letters, and RFC 4648 §3.4 allows applications to choose\n * upper- or lowercase alphabets. We keep the published uppercase table and do not case-fold decode input.\n * Use `base32nopad` for unpadded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ===='\n * base32.decode('CKVQ====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32 = /* @__PURE__ */ Object.freeze(chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), padding(5), join('')));\n/**\n * base32 encoding from RFC 4648. No padding.\n * This variant inherits RFC 4648 base32's uppercase table and intentionally does not case-fold decode input.\n * Use `base32` for padded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ'\n * base32nopad.decode('CKVQ');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32nopad = /* @__PURE__ */ Object.freeze(chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), join('')));\n/**\n * base32 encoding from RFC 4648. Padded. Compared to ordinary `base32`, slightly different alphabet.\n * RFC 4648 §7 Table 4 uses uppercase letters, and we intentionally keep that table without case-folding decode input.\n * Use `base32hexnopad` for unpadded version.\n * @example\n * ```js\n * base32hex.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG===='\n * base32hex.decode('2ALG====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hex = /* @__PURE__ */ Object.freeze(chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), padding(5), join('')));\n/**\n * base32 encoding from RFC 4648. No padding. Compared to ordinary `base32`, slightly different alphabet.\n * This variant inherits RFC 4648 base32hex's uppercase table and intentionally does not case-fold decode input.\n * Use `base32hex` for padded version.\n * @example\n * ```js\n * base32hexnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG'\n * base32hexnopad.decode('2ALG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hexnopad = /* @__PURE__ */ Object.freeze(chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), join('')));\n/**\n * base32 encoding from RFC 4648. Doug Crockford's version.\n * See {@link https://www.crockford.com/base32.html | Douglas Crockford's Base32}.\n * @example\n * ```js\n * base32crockford.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ANG'\n * base32crockford.decode('2ANG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32crockford = /* @__PURE__ */ Object.freeze(chain(radix2(5), alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'), join(''), normalize((s) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1'))));\n// Built-in base64 conversion https://caniuse.com/mdn-javascript_builtins_uint8array_frombase64\n// Require both directions before taking the native fast path, so base64/base64url don't mix native and JS behavior.\n// prettier-ignore\nconst hasBase64Builtin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toBase64 === 'function' &&\n    typeof Uint8Array.fromBase64 === 'function')();\n// Native `Uint8Array.fromBase64()` accepts these ASCII whitespace chars.\n// Reject them first so the native base64 path still follows RFC 4648 §3.3.\n// ASCII whitespace is U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, or U+0020 SPACE\nconst ASCII_WHITESPACE = /[\\t\\n\\f\\r ]/;\nconst decodeBase64Builtin = (s, isUrl) => {\n    astr('base64', s);\n    const alphabet = isUrl ? 'base64url' : 'base64';\n    // Per spec, .fromBase64 already throws on any other non-alphabet symbols except ASCII whitespace\n    // And checking just for whitespace makes decoding about 3x faster than a full range check.\n    // lastChunkHandling: 'strict' rejects loose tails and non-zero pad bits so native decoding stays canonical.\n    if (s.length > 0 && ASCII_WHITESPACE.test(s))\n        throw new Error('invalid base64');\n    return Uint8Array.fromBase64(s, { alphabet, lastChunkHandling: 'strict' });\n};\n/**\n * base64 from RFC 4648. Padded.\n * Use `base64nopad` for unpadded version.\n * Also check out `base64url`, `base64urlnopad`.\n * Falls back to built-in function, when available.\n * @example\n * ```js\n * base64.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64 = /* @__PURE__ */ Object.freeze(hasBase64Builtin ? {\n    encode(b) { abytes(b); return b.toBase64(); },\n    decode(s) { return decodeBase64Builtin(s, false); },\n} : chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), padding(6), join('')));\n/**\n * base64 from RFC 4648. No padding.\n * Use `base64` for padded version.\n * @example\n * ```js\n * base64nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64nopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64nopad = /* @__PURE__ */ Object.freeze(chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), join('')));\n/**\n * base64 from RFC 4648, using URL-safe alphabet. Padded.\n * Use `base64urlnopad` for unpadded version.\n * Falls back to built-in function, when available.\n * @example\n * ```js\n * base64url.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64url.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64url = /* @__PURE__ */ Object.freeze(hasBase64Builtin ? {\n    encode(b) { abytes(b); return b.toBase64({ alphabet: 'base64url' }); },\n    decode(s) { return decodeBase64Builtin(s, true); },\n} : chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), padding(6), join('')));\n/**\n * base64 from RFC 4648, using URL-safe alphabet. No padding.\n * Use `base64url` for padded version.\n * @example\n * ```js\n * base64urlnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64urlnopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64urlnopad = /* @__PURE__ */ Object.freeze(chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), join('')));\n// base58 code\n// -----------\nconst genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc) => chain(radix(58), alphabet(abc), join(''));\n/**\n * base58: base64 without ambigous characters +, /, 0, O, I, l.\n * Quadratic (O(n^2)) - so, can't be used on large inputs.\n * @example\n * ```js\n * const text = base58.encode(Uint8Array.from([0, 1, 2]));\n * base58.decode(text);\n * // => Uint8Array.from([0, 1, 2])\n * ```\n */\nexport const base58 = /* @__PURE__ */ Object.freeze(genBase58('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'));\n/**\n * base58: flickr version. Check out `base58`.\n * @example\n * Round-trip bytes with the Flickr alphabet.\n * ```ts\n * const text = base58flickr.encode(Uint8Array.from([0, 1, 2]));\n * base58flickr.decode(text);\n * ```\n */\nexport const base58flickr = /* @__PURE__ */ Object.freeze(genBase58('123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'));\n/**\n * base58: XRP version. Check out `base58`.\n * @example\n * Round-trip bytes with the XRP alphabet.\n * ```ts\n * const text = base58xrp.encode(Uint8Array.from([0, 1, 2]));\n * base58xrp.decode(text);\n * ```\n */\nexport const base58xrp = /* @__PURE__ */ Object.freeze(genBase58('rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz'));\n// Data len (index) -> encoded block len.\n// Monero pads each 1..8-byte block to this fixed base58 width so decode can recover the tail length.\nconst XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11];\n/**\n * base58: XMR version. Check out `base58`.\n * Done in 8-byte blocks (which equals 11 chars in decoding). Last (non-full) block padded with '1' to size in XMR_BLOCK_LEN.\n * Block encoding significantly reduces quadratic complexity of base58.\n * @example\n * Round-trip bytes with the Monero block codec.\n * ```ts\n * const text = base58xmr.encode(Uint8Array.from([0, 1, 2]));\n * base58xmr.decode(text);\n * ```\n */\nexport const base58xmr = /* @__PURE__ */ Object.freeze({\n    encode(data) {\n        abytes(data);\n        let res = '';\n        for (let i = 0; i < data.length; i += 8) {\n            const block = data.subarray(i, i + 8);\n            res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length], '1');\n        }\n        return res;\n    },\n    decode(str) {\n        astr('base58xmr.decode', str);\n        let res = [];\n        for (let i = 0; i < str.length; i += 11) {\n            const slice = str.slice(i, i + 11);\n            const blockLen = XMR_BLOCK_LEN.indexOf(slice.length);\n            const block = base58.decode(slice);\n            for (let j = 0; j < block.length - blockLen; j++) {\n                if (block[j] !== 0)\n                    throw new Error('base58xmr: wrong padding');\n            }\n            res = res.concat(Array.from(block.slice(block.length - blockLen)));\n        }\n        return Uint8Array.from(res);\n    },\n});\n/**\n * Method, which creates base58check encoder.\n * Requires function, calculating sha256.\n * Callers must include any version bytes in `data`; this helper only applies the\n * 4-byte double-SHA256 checksum used by Bitcoin Base58Check.\n * @param sha256 - Function used to calculate the checksum hash.\n * @returns base58check codec using 4 checksum bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Create a base58check codec from a SHA-256 implementation.\n * ```ts\n * import { createBase58check } from '@scure/base';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const coder = createBase58check(sha256);\n * coder.encode(Uint8Array.from([1, 2, 3]));\n * ```\n */\nexport const createBase58check = (sha256) => {\n    // Validate the hash function at construction time so wrong inputs fail before returning a coder.\n    afn(sha256);\n    const _sha256 = sha256;\n    return chain(checksum(4, (data) => _sha256(_sha256(data))), base58);\n};\n/**\n * Use `createBase58check` instead.\n * @deprecated Use {@link createBase58check} instead.\n * Callers must include any version bytes in `data`; this alias keeps the same\n * 4-byte double-SHA256 checksum behavior as `createBase58check`.\n * @param sha256 - Function used to calculate the checksum hash.\n * @returns base58check codec using 4 checksum bytes.\n * @example\n * Create a base58check codec with the deprecated alias.\n * ```ts\n * import { base58check } from '@scure/base';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const coder = base58check(sha256);\n * coder.encode(Uint8Array.from([1, 2, 3]));\n * ```\n */\nexport const base58check = createBase58check;\n// BIP 173 character table: data values 0..31 map to `qpzry9x8gf2tvdw0s3jn54khce6mua7l`.\nconst BECH_ALPHABET = chain(alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'), join(''));\n// BIP 173 `bech32_polymod` GEN coefficients.\nconst POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];\n// BIP 173 step split: this applies the polymod state transition before callers xor in the next 5-bit value.\nfunction bech32Polymod(pre) {\n    const b = pre >> 25;\n    let chk = (pre & 0x1ffffff) << 5;\n    for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {\n        if (((b >> i) & 1) === 1)\n            chk ^= POLYMOD_GENERATORS[i];\n    }\n    return chk;\n}\nfunction bechChecksum(prefix, words, encodingConst = 1) {\n    const len = prefix.length;\n    let chk = 1;\n    for (let i = 0; i < len; i++) {\n        const c = prefix.charCodeAt(i);\n        if (c < 33 || c > 126)\n            throw new Error(`Invalid prefix (${prefix})`);\n        chk = bech32Polymod(chk) ^ (c >> 5);\n    }\n    chk = bech32Polymod(chk);\n    for (let i = 0; i < len; i++)\n        chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f);\n    for (let v of words)\n        chk = bech32Polymod(chk) ^ v;\n    for (let i = 0; i < 6; i++)\n        chk = bech32Polymod(chk);\n    // BIP 173/BIP 350: xor the final checksum constant, then emit the 30-bit state as six 5-bit symbols.\n    chk ^= encodingConst;\n    return BECH_ALPHABET.encode(convertRadix2([chk % powers[30]], 30, 5, false));\n}\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction genBech32(encoding) {\n    // BIP 173 uses final xor constant 1; BIP 350 swaps in 0x2bc830a3 for Bech32m.\n    const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3;\n    const _words = radix2(5);\n    const fromWords = _words.decode;\n    const toWords = _words.encode;\n    const fromWordsUnsafe = unsafeWrapper(fromWords);\n    function encode(prefix, words, limit = 90) {\n        astr('bech32.encode prefix', prefix);\n        if (isBytes(words))\n            words = Array.from(words);\n        anumArr('bech32.encode', words);\n        const plen = prefix.length;\n        if (plen === 0)\n            throw new TypeError(`Invalid prefix length ${plen}`);\n        // Total output is hrp + `1` separator + payload words + 6 checksum chars.\n        const actualLength = plen + 7 + words.length;\n        if (limit !== false && actualLength > limit)\n            throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);\n        const lowered = prefix.toLowerCase();\n        const sum = bechChecksum(lowered, words, ENCODING_CONST);\n        return `${lowered}1${BECH_ALPHABET.encode(words)}${sum}`;\n    }\n    function decode(str, limit = 90) {\n        astr('bech32.decode input', str);\n        const slen = str.length;\n        // Minimum length is 1-char hrp + `1` separator + 6-char checksum.\n        if (slen < 8 || (limit !== false && slen > limit))\n            throw new TypeError(`invalid string length: ${slen} (${str}). Expected (8..${limit})`);\n        // don't allow mixed case\n        const lowered = str.toLowerCase();\n        if (str !== lowered && str !== str.toUpperCase())\n            throw new Error(`String must be lowercase or uppercase`);\n        const sepIndex = lowered.lastIndexOf('1');\n        if (sepIndex === 0 || sepIndex === -1)\n            throw new Error(`Letter \"1\" must be present between prefix and data only`);\n        const prefix = lowered.slice(0, sepIndex);\n        const data = lowered.slice(sepIndex + 1);\n        if (data.length < 6)\n            throw new Error('Data must be at least 6 characters long');\n        const words = BECH_ALPHABET.decode(data).slice(0, -6);\n        const sum = bechChecksum(prefix, words, ENCODING_CONST);\n        if (!data.endsWith(sum))\n            throw new Error(`Invalid checksum in ${str}: expected \"${sum}\"`);\n        return { prefix, words };\n    }\n    const decodeUnsafe = unsafeWrapper(decode);\n    function decodeToBytes(str) {\n        // Keep the byte helper unbounded; callers that need the default BIP 173 length cap should use decode(str).\n        const { prefix, words } = decode(str, false);\n        return {\n            prefix,\n            words,\n            bytes: fromWords(words),\n        };\n    }\n    function encodeFromBytes(prefix, bytes) {\n        // Keep the convenience wrapper on encode()'s default 90-char cap; custom limits should call encode(prefix, toWords(bytes), limit).\n        return encode(prefix, toWords(bytes));\n    }\n    return {\n        encode,\n        decode,\n        encodeFromBytes,\n        decodeToBytes,\n        decodeUnsafe,\n        fromWords,\n        fromWordsUnsafe,\n        toWords,\n    };\n}\n/**\n * bech32 from BIP 173. Operates on words.\n * For high-level helpers, check out {@link https://github.com/paulmillr/scure-btc-signer | scure-btc-signer}.\n * @example\n * Convert bytes to words, encode them, then decode back.\n * ```ts\n * const words = bech32.toWords(Uint8Array.from([1, 2, 3]));\n * const text = bech32.encode('bc', words);\n * bech32.decode(text);\n * ```\n */\nexport const bech32 = /* @__PURE__ */ Object.freeze(genBech32('bech32'));\n/**\n * bech32m from BIP 350. Operates on words.\n * It was to mitigate `bech32` weaknesses.\n * For high-level helpers, check out {@link https://github.com/paulmillr/scure-btc-signer | scure-btc-signer}.\n * @example\n * Convert bytes to words, encode them with bech32m, then decode back.\n * ```ts\n * const words = bech32m.toWords(Uint8Array.from([1, 2, 3]));\n * const text = bech32m.encode('bc', words);\n * bech32m.decode(text);\n * ```\n */\nexport const bech32m = /* @__PURE__ */ Object.freeze(genBech32('bech32m'));\n/**\n * ASCII-to-byte decoder. Rejects non-ASCII text and bytes instead of doing UTF-8 replacement.\n * Method names follow `BytesCoder`, so `encode(bytes)` returns a string and `decode(string)` returns bytes.\n * @example\n * ```js\n * const b = ascii.decode(\"ABC\"); // => new Uint8Array([ 65, 66, 67 ])\n * const str = ascii.encode(b); // \"ABC\"\n * ```\n */\nexport const ascii = /* @__PURE__ */ Object.freeze({\n    encode(data) {\n        abytes(data);\n        let res = '';\n        for (let i = 0; i < data.length; i++) {\n            const byte = data[i];\n            // ASCII is 7-bit; reject bytes outside 0x00..0x7f instead of silently widening to\n            // Latin-1/UTF-8.\n            if (byte > 127)\n                throw new RangeError(`bytes contain non-ASCII byte ${byte} at position ${i}`);\n            res += String.fromCharCode(byte);\n        }\n        return res;\n    },\n    decode(str) {\n        if (typeof str !== 'string')\n            throw new TypeError('ascii string expected, got ' + typeof str);\n        const res = new Uint8Array(str.length);\n        for (let i = 0; i < str.length; i++) {\n            // Indexed access is much faster than Uint8Array.from(str, mapFn) here and keeps\n            // exact error positions.\n            const charCode = str.charCodeAt(i);\n            if (charCode > 127) {\n                throw new RangeError(`string contains non-ASCII character \"${str[i]}\" with code ${charCode} at position ${i}`);\n            }\n            res[i] = charCode;\n        }\n        return res;\n    },\n});\nconst _isWellFormedShim = (str) => {\n    // encodeURI rejects malformed UTF-16, giving a compact fallback that matches native\n    // isWellFormed on our tests/fuzz corpus.\n    try {\n        return encodeURI(str) !== null;\n    }\n    catch {\n        return false;\n    }\n};\nconst _isWellFormed = /* @__PURE__ */ (() => \n// Pick the native check once so utf8.decode doesn't re-probe String.prototype on every call.\ntypeof ''.isWellFormed === 'function'\n    ? (str) => str.isWellFormed()\n    : _isWellFormedShim)();\n// This fallback stays small because strict UTF-8 only needs fatal decoding plus well-formed\n// UTF-16 checks, not the replacement, streaming, or legacy-encoding behavior of full platform\n// text codecs.\nconst utf8Fallback = /* @__PURE__ */ Object.freeze({\n    encode(data) {\n        abytes(data);\n        let res = '';\n        for (let i = 0; i < data.length;) {\n            const a = data[i++];\n            if (a < 0b1000_0000) {\n                res += String.fromCharCode(a);\n                continue;\n            }\n            if (a < 0b1100_0010 || i >= data.length)\n                throw new TypeError(`invalid utf8 at byte ${i - 1}`);\n            const b = data[i++];\n            if ((b & 0b1100_0000) !== 0b1000_0000)\n                throw new TypeError(`invalid utf8 at byte ${i - 1}`);\n            let cp = ((a & 0b0001_1111) << 6) | (b & 0b0011_1111);\n            if (a >= 0b1110_0000) {\n                if (i >= data.length)\n                    throw new TypeError(`invalid utf8 at byte ${i - 1}`);\n                const c = data[i++];\n                if ((c & 0b1100_0000) !== 0b1000_0000 ||\n                    (a === 0b1110_0000 && b < 0b1010_0000) ||\n                    (a === 0xed && b >= 0b1010_0000))\n                    throw new TypeError(`invalid utf8 at byte ${i - 1}`);\n                cp = ((a & 0b0000_1111) << 12) | ((b & 0b0011_1111) << 6) | (c & 0b0011_1111);\n                if (a >= 0b1111_0000) {\n                    if (i >= data.length)\n                        throw new TypeError(`invalid utf8 at byte ${i - 1}`);\n                    const d = data[i++];\n                    if (a > 0b1111_0100 ||\n                        (d & 0b1100_0000) !== 0b1000_0000 ||\n                        (a === 0b1111_0000 && b < 0b1001_0000) ||\n                        (a === 0b1111_0100 && b >= 0b1001_0000))\n                        throw new TypeError(`invalid utf8 at byte ${i - 1}`);\n                    cp =\n                        ((a & 7) << 18) |\n                            ((b & 0b0011_1111) << 12) |\n                            ((c & 0b0011_1111) << 6) |\n                            (d & 0b0011_1111);\n                }\n            }\n            if (cp < 0x10000)\n                res += String.fromCharCode(cp);\n            else {\n                cp -= 0x10000;\n                res += String.fromCharCode((cp >> 10) + 0xd800, (cp & 0x3ff) + 0xdc00);\n            }\n        }\n        return res;\n    },\n    decode(str) {\n        astr('utf8', str);\n        if (!_isWellFormed(str))\n            throw new TypeError('utf8 expected well-formed string');\n        // Direct Uint8Array writes are much faster than number[] + Uint8Array.from on Hermes and\n        // large Node inputs.\n        const res = new Uint8Array(str.length * 3);\n        let pos = 0;\n        for (let i = 0; i < str.length; i++) {\n            let c = str.charCodeAt(i);\n            if (c < 0b1000_0000) {\n                res[pos++] = c;\n                continue;\n            }\n            if (c >= 0xd800 && c <= 0xdfff) {\n                const d = str.charCodeAt(++i);\n                c = 0x10000 + ((c - 0xd800) << 10) + d - 0xdc00;\n            }\n            if (c >= 0x10000) {\n                res[pos++] = (c >> 18) | 0b1111_0000;\n                res[pos++] = ((c >> 12) & 0b0011_1111) | 0b1000_0000;\n            }\n            else if (c >= 0x800)\n                res[pos++] = (c >> 12) | 0b1110_0000;\n            else\n                res[pos++] = (c >> 6) | 0b1100_0000;\n            if (c >= 0x800)\n                res[pos++] = ((c >> 6) & 0b0011_1111) | 0b1000_0000;\n            res[pos++] = (c & 0b0011_1111) | 0b1000_0000;\n        }\n        return res.subarray(0, pos);\n    },\n});\n/**\n * Strict UTF-8-to-byte decoder. Uses built-in TextDecoder / TextEncoder when available.\n * Method names follow `BytesCoder`, so `encode(bytes)` returns a string and\n * `decode(string)` returns bytes.\n * `encode(bytes)` requires Uint8Array input, preserves an explicit leading BOM, and\n *   throws on invalid UTF-8 bytes.\n * `decode(string)` requires a primitive string and throws on malformed UTF-16 strings with\n *   lone surrogates.\n * @example\n * ```js\n * const b = utf8.decode(\"hey\"); // => new Uint8Array([ 104, 101, 121 ])\n * const str = utf8.encode(b); // \"hey\"\n * ```\n */\nexport const utf8 = /* @__PURE__ */ (() => {\n    let _utf8Encoder;\n    let _utf8Decoder;\n    const utf8Builtin = {\n        // ignoreBOM preserves an explicit leading U+FEFF;\n        // fatal rejects invalid UTF-8 bytes instead of replacing them.\n        encode(data) {\n            abytes(data);\n            return (_utf8Decoder || (_utf8Decoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }))).decode(data);\n        },\n        decode(str) {\n            astr('utf8', str);\n            if (!_isWellFormed(str))\n                throw new TypeError('utf8 expected well-formed string');\n            return (_utf8Encoder || (_utf8Encoder = new TextEncoder())).encode(str);\n        },\n    };\n    return Object.freeze({\n        // Select each direction once at module init, since\n        // TextEncoder and TextDecoder can exist independently.\n        encode: typeof TextDecoder === 'function' ? utf8Builtin.encode : utf8Fallback.encode,\n        decode: typeof TextEncoder === 'function' ? utf8Builtin.decode : utf8Fallback.decode,\n    });\n})();\n// Keep fallback parity probes behind a test-only export until runtime fallback behavior is decided.\nexport const __TESTS = /* @__PURE__ */ Object.freeze({\n    utf8Fallback: utf8Fallback,\n    _isWellFormedShim: _isWellFormedShim,\n});\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\n// prettier-ignore\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// Require both directions before enabling the native hex path so encode/decode stay symmetric.\ntypeof Uint8Array.from([]).toHex === 'function' &&\n    typeof Uint8Array.fromHex === 'function')();\n// prettier-ignore\nconst hexBuiltin = {\n    // Keep local type guards so the native path preserves library-level input errors.\n    // Native toHex emits lowercase hex, matching the fallback alphabet and Node's hex strings.\n    encode(data) { abytes(data); return data.toHex(); },\n    // Native fromHex accepts either hex case and rejects odd-length / non-hex syntax.\n    decode(s) { astr('hex', s); return Uint8Array.fromHex(s); },\n};\n/**\n * hex string decoder. Uses built-in function, when available.\n * Lowercase codec; unlike `base16`, this variant accepts either hex case and emits lowercase.\n * @example\n * ```js\n * const b = hex.decode(\"0102ff\"); // => new Uint8Array([ 1, 2, 255 ])\n * const str = hex.encode(b); // \"0102ff\"\n * ```\n */\nexport const hex = /* @__PURE__ */ Object.freeze(hasHexBuiltin\n    ? hexBuiltin\n    : chain(radix2(4), alphabet('0123456789abcdef'), join(''), normalize((s) => {\n        if (typeof s !== 'string' || s.length % 2 !== 0)\n            throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`);\n        return s.toLowerCase();\n    })));\n// prettier-ignore\n// Keep this registry aligned with CoderType/coderTypeError; only byte<->string codecs belong here.\nconst CODERS = {\n    utf8, hex, base16, base32, base64, base64url, base58, base58xmr\n};\nconst coderTypeError = 'Invalid encoding type. Available types: utf8, hex, base16, base32, base64, base64url, base58, base58xmr';\n/**\n * Encodes bytes with one of the built-in codecs.\n * @deprecated Use the codec directly, for example `hex.encode(bytes)`.\n * @param type - Codec name.\n * @param bytes - Bytes to encode.\n * @returns Encoded string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * ```ts\n * bytesToString('hex', Uint8Array.from([1, 2, 255]));\n * ```\n */\nexport const bytesToString = (type, bytes) => {\n    if (typeof type !== 'string' || !CODERS.hasOwnProperty(type))\n        throw new TypeError(coderTypeError);\n    if (!isBytes(bytes))\n        throw new TypeError('bytesToString() expects Uint8Array');\n    return CODERS[type].encode(bytes);\n};\n/**\n * Alias for `bytesToString`.\n * @deprecated Use {@link bytesToString} or the codec directly instead.\n * @param type - Codec name.\n * @param bytes - Bytes to encode.\n * @returns Encoded string.\n * @example\n * ```ts\n * str('hex', Uint8Array.from([1, 2, 255]));\n * ```\n */\nexport const str = bytesToString; // as in python, but for bytes only\n/**\n * Decodes a string with one of the built-in codecs.\n * @deprecated Use the codec directly, for example `hex.decode(text)`.\n * @param type - Codec name.\n * @param str - Encoded string.\n * @returns Decoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * ```ts\n * stringToBytes('hex', '0102ff');\n * ```\n */\nexport const stringToBytes = (type, str) => {\n    // Match bytesToString's selector validation so hostile `toString()` coercions can't leak custom errors.\n    if (typeof type !== 'string' || !CODERS.hasOwnProperty(type))\n        throw new TypeError(coderTypeError);\n    if (typeof str !== 'string')\n        throw new TypeError('stringToBytes() expects string');\n    return CODERS[type].decode(str);\n};\n/**\n * Alias for `stringToBytes`.\n * @deprecated Use {@link stringToBytes} or the codec directly instead.\n * @param type - Codec name.\n * @param str - Encoded string.\n * @returns Decoded bytes.\n * @example\n * ```ts\n * bytes('hex', '0102ff');\n * ```\n */\nexport const bytes = stringToBytes;\n//# sourceMappingURL=index.js.map","import { base64 } from \"@scure/base\";\nimport type { TEncryptedAesGcmPayload } from \"../crypto.schema\";\n\nexport const decryptTextDataWithAesGcmKey = async ({\n  aesGcmKey,\n  dataToDecrypt,\n}: {\n  aesGcmKey: CryptoKey;\n  dataToDecrypt: TEncryptedAesGcmPayload;\n}): Promise<string> => {\n  const decryptedData = await crypto.subtle.decrypt(\n    {\n      name: \"AES-GCM\",\n      iv: new Uint8Array(base64.decode(dataToDecrypt.nonce)),\n    },\n    aesGcmKey,\n    new Uint8Array(base64.decode(dataToDecrypt.ciphertext)),\n  );\n\n  return new TextDecoder().decode(decryptedData);\n};\n","import type { TEncryptedAesGcmBytes } from \"../crypto.schema\";\n\n/**\n * Encrypts raw bytes with an AES-GCM key, returning the binary nonce + ciphertext. The bytes\n * counterpart of {@link encryptTextDataWithAesGcmKey} — use it for binary channels (msgpack frames)\n * to avoid base64 inflation. A fresh 12-byte nonce is generated per call (never reuse a nonce).\n */\nexport const encryptBytesWithAesGcmKey = async ({\n  aesGcmKey,\n  dataToEncrypt,\n}: {\n  aesGcmKey: CryptoKey;\n  dataToEncrypt: Uint8Array;\n}): Promise<TEncryptedAesGcmBytes> => {\n  const nonce = crypto.getRandomValues(new Uint8Array(12));\n\n  const encryptedData = await crypto.subtle.encrypt(\n    { name: \"AES-GCM\", iv: nonce },\n    aesGcmKey,\n    // Re-view over a plain ArrayBuffer so WebCrypto's `BufferSource` is satisfied regardless of the\n    // source's backing buffer (msgpack output may be pooled / SharedArrayBuffer-typed).\n    new Uint8Array(dataToEncrypt),\n  );\n\n  return { nonce, ciphertext: new Uint8Array(encryptedData) };\n};\n","import { base64 } from \"@scure/base\";\nimport type { TEncryptedAesGcmPayload } from \"../crypto.schema\";\n\nexport const encryptTextDataWithAesGcmKey = async ({\n  aesGcmKey,\n  dataToEncrypt,\n}: {\n  aesGcmKey: CryptoKey;\n  dataToEncrypt: string;\n}): Promise<TEncryptedAesGcmPayload> => {\n  const nonce = crypto.getRandomValues(new Uint8Array(12));\n\n  const encryptedData = await crypto.subtle.encrypt(\n    {\n      name: \"AES-GCM\",\n      iv: nonce,\n    },\n    aesGcmKey,\n    new TextEncoder().encode(dataToEncrypt),\n  );\n\n  return {\n    nonce: base64.encode(nonce),\n    ciphertext: base64.encode(new Uint8Array(encryptedData)),\n  };\n};\n","/**\n * Deterministic, signing-grade JSON serialization: the same data always produces the same bytes,\n * regardless of key insertion order — the foundation for content hashes, idempotency keys, and\n * signed challenges. This is a **frozen project contract** (guarded by byte-level test vectors),\n * not RFC 8785/JCS. The exact rules:\n *\n * - `null`, booleans, strings, and finite numbers serialize with native `JSON.stringify` spelling\n *   and escaping (so `-0` emits `0`).\n * - Objects contribute their **own enumerable string-keyed** entries only, sorted by UTF-16\n *   code-unit order; entries whose value is `undefined` are omitted. Symbol keys and prototype\n *   properties are ignored. `toJSON` is **never** invoked — a Date/Map/Set/class instance\n *   contributes only its own enumerable entries.\n * - Arrays retain element order. A sparse **hole** serializes as `null` (native JSON behavior); an\n *   **explicit** `undefined`/function/symbol/bigint element throws.\n * - Non-finite numbers, bigints, functions/symbols as values, top-level `undefined`, and circular\n *   references throw. Repeated (non-cyclic) references are allowed.\n *\n * Error *messages* are not part of the contract; accepted-value bytes are.\n */\nexport function stringifyCanonicalJson(value: unknown): string {\n  return writeCanonical(value, \"$\", new Set());\n}\n\nfunction writeCanonical(value: unknown, path: string, ancestors: Set<object>): string {\n  if (value === null) return \"null\";\n  switch (typeof value) {\n    case \"string\":\n      return JSON.stringify(value);\n    case \"boolean\":\n      return value ? \"true\" : \"false\";\n    case \"number\":\n      if (!Number.isFinite(value)) {\n        throw new Error(`stringifyCanonicalJson: non-finite number at ${path}`);\n      }\n      return JSON.stringify(value);\n    case \"undefined\":\n    case \"bigint\":\n    case \"function\":\n    case \"symbol\":\n      throw new Error(`stringifyCanonicalJson: unsupported ${typeof value} at ${path}`);\n    default:\n      break;\n  }\n\n  const obj = value as object;\n  if (ancestors.has(obj)) {\n    throw new Error(`stringifyCanonicalJson: circular reference at ${path}`);\n  }\n  ancestors.add(obj);\n  try {\n    if (Array.isArray(obj)) {\n      let out = \"[\";\n      for (let i = 0; i < obj.length; i++) {\n        if (i > 0) out += \",\";\n        // A hole (absent index) is native JSON's `null`; an explicit undefined element throws\n        // in the recursion — the `in` check is what tells them apart.\n        out += i in obj ? writeCanonical(obj[i], `${path}[${i}]`, ancestors) : \"null\";\n      }\n      return `${out}]`;\n    }\n    const record = obj as Record<string, unknown>;\n    const keys = Object.keys(record).sort();\n    const parts: string[] = [];\n    for (const key of keys) {\n      const entry = record[key];\n      if (entry === undefined) continue;\n      parts.push(`${JSON.stringify(key)}:${writeCanonical(entry, `${path}.${key}`, ancestors)}`);\n    }\n    return `{${parts.join(\",\")}}`;\n  } finally {\n    ancestors.delete(obj);\n  }\n}\n","import type { TCanonicalJsonValue } from \"./canonical.types\";\nimport { stringifyCanonicalJson } from \"./stringifyCanonicalJson\";\n\n/**\n * A signing challenge with unambiguous byte layout: a domain tag and version separate this\n * operation's signatures from every other operation's (and from future format revisions), and\n * canonical-JSON field encoding gives exact field boundaries — no delimiter-join ambiguity, no\n * key-order sensitivity. Pre-hash large members (ciphertexts, payload bodies) into `fields`\n * rather than embedding them whole.\n */\nexport interface ICanonicalChallenge {\n  /** Namespaces the signature to one operation, e.g. `\"meteor-connect-multi-action-submit\"`. */\n  readonly domainTag: string;\n  /** Versioned per challenge domain — bump it when this challenge's field contract changes. */\n  readonly version: number;\n  /** The signed fields. Strict JSON values only — validated at build time, not silently coerced. */\n  readonly fields: Readonly<Record<string, TCanonicalJsonValue>>;\n}\n\n/**\n * The canonical string a {@link ICanonicalChallenge} signs:\n * `stringifyCanonicalJson({ domainTag, version, fields })`. Both signer and verifier call this,\n * so the signed bytes are constructed one way, everywhere.\n *\n * Unlike the general serializer (which accepts `unknown` with documented compatibility\n * behaviors), this **rejects** anything that is not a strict {@link TCanonicalJsonValue}: values\n * that alias to the same JSON (`undefined` entries, sparse arrays, non-plain objects) are refused\n * rather than normalized — a signing API must not guess. An empty `domainTag` or a non-positive /\n * unsafe `version` throws.\n */\nexport function buildCanonicalChallenge(challenge: ICanonicalChallenge): string {\n  if (typeof challenge.domainTag !== \"string\" || challenge.domainTag.length === 0) {\n    throw new Error(\"buildCanonicalChallenge: domainTag must be a non-empty string\");\n  }\n  if (\n    typeof challenge.version !== \"number\" ||\n    !Number.isSafeInteger(challenge.version) ||\n    challenge.version < 1\n  ) {\n    throw new Error(\"buildCanonicalChallenge: version must be a positive safe integer\");\n  }\n  if (!isPlainObject(challenge.fields)) {\n    throw new Error(\"buildCanonicalChallenge: fields must be a plain object\");\n  }\n  for (const [key, value] of Object.entries(challenge.fields)) {\n    assertStrictCanonicalValue(value, `fields.${key}`);\n  }\n  return stringifyCanonicalJson({\n    domainTag: challenge.domainTag,\n    version: challenge.version,\n    fields: challenge.fields,\n  });\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n  if (typeof value !== \"object\" || value === null) return false;\n  const proto = Object.getPrototypeOf(value);\n  return proto === Object.prototype || proto === null;\n}\n\nfunction assertStrictCanonicalValue(value: unknown, path: string): void {\n  if (value === undefined) {\n    throw new Error(`buildCanonicalChallenge: undefined entry at ${path}`);\n  }\n  if (value === null || typeof value === \"string\" || typeof value === \"boolean\") return;\n  if (typeof value === \"number\") {\n    if (!Number.isFinite(value)) {\n      throw new Error(`buildCanonicalChallenge: non-finite number at ${path}`);\n    }\n    return;\n  }\n  if (Array.isArray(value)) {\n    for (let i = 0; i < value.length; i++) {\n      if (!(i in value)) {\n        throw new Error(`buildCanonicalChallenge: sparse array hole at ${path}[${i}]`);\n      }\n      assertStrictCanonicalValue(value[i], `${path}[${i}]`);\n    }\n    return;\n  }\n  if (isPlainObject(value)) {\n    for (const [key, entry] of Object.entries(value)) {\n      if (entry === undefined) {\n        throw new Error(`buildCanonicalChallenge: undefined entry at ${path}.${key}`);\n      }\n      assertStrictCanonicalValue(entry, `${path}.${key}`);\n    }\n    return;\n  }\n  throw new Error(\n    `buildCanonicalChallenge: unsupported value at ${path} — strict JSON values only (null, boolean, finite number, string, dense array, plain object)`,\n  );\n}\n","import { base64 } from \"@scure/base\";\n\n/**\n * Byte ⇄ base64 conversions that work in **every** JavaScript runtime — browsers, Node, Cloudflare\n * Workers, Deno, Bun, and React Native (Hermes) — without leaning on environment-specific interfaces:\n * the browser-only `btoa`/`atob` globals (absent in Hermes), or Node's `Buffer` (absent in browsers /\n * Workers / RN). Built on `@scure/base` (pure JS, audited, zero-dependency) — the same base64\n * implementation the crypto layer already uses, so the whole library stays consistent.\n *\n * Produces / consumes **standard** base64 (RFC 4648 §4: `+` and `/`, `=` padding) — byte-for-byte\n * interchangeable with `btoa`/`atob` and Node's `Buffer.toString(\"base64\")`, so it interoperates with\n * any peer regardless of how that peer encodes.\n *\n * NOTE: the TC39 `Uint8Array.prototype.toBase64()` / `Uint8Array.fromBase64()` methods would be the\n * \"native\" choice, but as of 2026 they are not yet available across all target runtimes (notably Hermes),\n * so a pure-JS implementation remains the portable option.\n */\nexport function bytesToBase64(bytes: Uint8Array): string {\n  return base64.encode(bytes);\n}\n\nexport function base64ToBytes(encoded: string): Uint8Array {\n  return base64.decode(encoded);\n}\n","import { bytesToBase64 } from \"../../data_type/bytes/base64\";\n\n/**\n * Synchronous SHA-256 (FIPS 180-4) over a UTF-8 string or raw bytes. Synchronous on purpose:\n * definition-time hashes (e.g. nice-realm's schema hash at `defineRealm`) must be computable\n * during module evaluation in both Node and workerd, and `crypto.subtle.digest` is async — a\n * small pure implementation keeps callers synchronous and platform-stable. Moved here from\n * nice-realm (which re-exports `sha256Hex` from its `/internals` for compatibility); verified\n * against the FIPS 180-4 test vectors in `canonical.test.ts`.\n */\n\nconst K = new Uint32Array([\n  0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n  0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n  0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n  0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n  0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n  0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n  0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n  0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,\n]);\n\nfunction rotr(x: number, n: number): number {\n  return (x >>> n) | (x << (32 - n));\n}\n\n/** SHA-256 of a UTF-8 string or raw bytes, as the 32-byte digest. */\nexport function sha256Bytes(input: string | Uint8Array): Uint8Array {\n  const bytes = typeof input === \"string\" ? new TextEncoder().encode(input) : input;\n  const bitLen = bytes.length * 8;\n\n  // Pad: 0x80, zeros, 64-bit big-endian length.\n  const paddedLen = (((bytes.length + 8) >> 6) + 1) << 6;\n  const padded = new Uint8Array(paddedLen);\n  padded.set(bytes);\n  padded[bytes.length] = 0x80;\n  const view = new DataView(padded.buffer);\n  // JS strings/buffers cap far below 2^53 bits; high word from the float division is exact enough here.\n  view.setUint32(paddedLen - 8, Math.floor(bitLen / 0x100000000), false);\n  view.setUint32(paddedLen - 4, bitLen >>> 0, false);\n\n  const h = new Uint32Array([\n    0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n  ]);\n  const w = new Uint32Array(64);\n\n  for (let offset = 0; offset < paddedLen; offset += 64) {\n    for (let i = 0; i < 16; i++) w[i] = view.getUint32(offset + i * 4, false);\n    for (let i = 16; i < 64; i++) {\n      const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >>> 3);\n      const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >>> 10);\n      w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0;\n    }\n\n    let a = h[0];\n    let b = h[1];\n    let c = h[2];\n    let d = h[3];\n    let e = h[4];\n    let f = h[5];\n    let g = h[6];\n    let hh = h[7];\n\n    for (let i = 0; i < 64; i++) {\n      const s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);\n      const ch = (e & f) ^ (~e & g);\n      const temp1 = (hh + s1 + ch + K[i] + w[i]) >>> 0;\n      const s0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);\n      const maj = (a & b) ^ (a & c) ^ (b & c);\n      const temp2 = (s0 + maj) >>> 0;\n      hh = g;\n      g = f;\n      f = e;\n      e = (d + temp1) >>> 0;\n      d = c;\n      c = b;\n      b = a;\n      a = (temp1 + temp2) >>> 0;\n    }\n\n    h[0] = (h[0] + a) >>> 0;\n    h[1] = (h[1] + b) >>> 0;\n    h[2] = (h[2] + c) >>> 0;\n    h[3] = (h[3] + d) >>> 0;\n    h[4] = (h[4] + e) >>> 0;\n    h[5] = (h[5] + f) >>> 0;\n    h[6] = (h[6] + g) >>> 0;\n    h[7] = (h[7] + hh) >>> 0;\n  }\n\n  const digest = new Uint8Array(32);\n  const digestView = new DataView(digest.buffer);\n  for (let i = 0; i < 8; i++) digestView.setUint32(i * 4, h[i], false);\n  return digest;\n}\n\n/** SHA-256 of a UTF-8 string or raw bytes, as lowercase hex. */\nexport function sha256Hex(input: string | Uint8Array): string {\n  const digest = sha256Bytes(input);\n  let hex = \"\";\n  for (const byte of digest) hex += byte.toString(16).padStart(2, \"0\");\n  return hex;\n}\n\n/** SHA-256 of a UTF-8 string or raw bytes, as standard padded base64 (RFC 4648 §4). */\nexport function sha256Base64(input: string | Uint8Array): string {\n  return bytesToBase64(sha256Bytes(input));\n}\n","export const signTextDataWithKeyEd25519 = async (\n  data: string,\n  cryptoKey: CryptoKey,\n): Promise<Uint8Array> => {\n  const dataBuffer = new TextEncoder().encode(data);\n  const signature = await crypto.subtle.sign(\n    {\n      name: \"ED25519\",\n    },\n    cryptoKey,\n    dataBuffer,\n  );\n\n  return new Uint8Array(signature);\n};\n","import { signTextDataWithKeyEd25519 } from \"./signTextDataWithKeyEd25519\";\n\nexport const DEFAULT_COMBINED_TEXT_DATA_SEPARATOR = \"::\";\n\n/**\n * ⚠ Separator-joining caller-controlled strings is a **concatenation-ambiguity** hazard: the parts\n * have no escaping, so `[\"a::b\"]` and `[\"a\",\"b\"]` sign identical bytes, and two operations'\n * challenges can collide unless every call site adds its own fixed tag. For new signing surfaces\n * prefer the canonical challenge form (`buildCanonicalChallenge` /\n * `ClientCryptoKeyLink.signChallengeCanonical`) — exact field boundaries by construction. This\n * helper stays byte-for-byte for deployed contracts.\n */\nexport const signCombinedTextDataWithKeyEd25519 = async (\n  data: string[],\n  cryptoKey: CryptoKey,\n  separator = DEFAULT_COMBINED_TEXT_DATA_SEPARATOR,\n): Promise<Uint8Array> => {\n  return await signTextDataWithKeyEd25519(data.join(separator), cryptoKey);\n};\n","import type { TSerializedCryptoKeyData_Ed25519_Raw } from \"../crypto.schema\";\nimport { DEFAULT_COMBINED_TEXT_DATA_SEPARATOR } from \"../ed25519/signCombinedTextDataWithKeyEd25519\";\n\ninterface IBuildVerifyKeyBoundInfoString_Input {\n  infoString?: string;\n  verifyPublicKeys: [TSerializedCryptoKeyData_Ed25519_Raw, TSerializedCryptoKeyData_Ed25519_Raw];\n}\n\n/**\n * The canonical HKDF `info` for a client-to-client shared key that binds both sides' verify\n * public keys into the derivation.\n *\n * When the two keys are relayed through an intermediary, a tampered key produces mismatched AES\n * keys on the two sides — the very first decryption fails, so key substitution is detected without\n * any extra signature ceremony.\n *\n * The keys are sorted lexicographically so the result is independent of which side is \"local\" —\n * both ends of a link compute the identical string without coordinating an order. Used internally\n * by ClientCryptoKeyLink (`bindVerifyKeysIntoDerivation`); exported for code that derives the same\n * key outside the link.\n */\nexport const buildVerifyKeyBoundInfoString = ({\n  infoString,\n  verifyPublicKeys,\n}: IBuildVerifyKeyBoundInfoString_Input): string => {\n  const sortedKeys = [...verifyPublicKeys].sort();\n\n  return [...(infoString != null ? [infoString] : []), ...sortedKeys].join(\n    DEFAULT_COMBINED_TEXT_DATA_SEPARATOR,\n  );\n};\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\n/**\n * A typed-storage read, default, write, or update failed schema validation. Always thrown —\n * validation is fail-closed; the `onInvalid` option observes, it never suppresses. Carries the\n * storage `key` and the schema's `issues` so callers can branch (e.g. treat a corrupt record as\n * absent, run a migration, or surface telemetry).\n */\nexport class StorageValidationError extends Error {\n  readonly key: string;\n  readonly issues: readonly StandardSchemaV1.Issue[];\n\n  constructor(key: string, issues: readonly StandardSchemaV1.Issue[]) {\n    const rendered = issues\n      .map((issue, index) => {\n        const path = issue.path\n          ?.map((segment) => (typeof segment === \"object\" ? String(segment.key) : String(segment)))\n          .join(\".\");\n        return ` (issue ${index + 1})${path ? ` [${path}]` : \"\"}: ${issue.message}`;\n      })\n      .join(\"\\n\");\n    super(`Typed storage validation failed for key \"${key}\":\\n${rendered}`);\n    this.name = \"StorageValidationError\";\n    this.key = key;\n    this.issues = issues;\n  }\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { StringKeys } from \"../../typescript/special_typescript_types\";\nimport type { StorageAdapter } from \"../StorageAdapter\";\nimport { StorageValidationError } from \"./StorageValidationError\";\n\nexport interface ITypedStorage<T extends Record<string, any>> {\n  getJson: <K extends StringKeys<T>>(key: K) => Promise<T[K] | undefined>;\n  getJsonOrDef: <K extends StringKeys<T>>(key: K, defVal: T[K]) => Promise<T[K]>;\n  setJson: <K extends StringKeys<T>>(key: K, val: T[K]) => Promise<void>;\n  removeItem: <K extends StringKeys<T>>(key: K) => Promise<void>;\n  updateJson: <K extends StringKeys<T>>(\n    key: K,\n    updater: (currentVal: T[K] | undefined) => T[K],\n  ) => Promise<void>;\n  updateJsonWithDef: <K extends StringKeys<T>>(\n    key: K,\n    defaultVal: T[K],\n    updater: (currentVal: T[K]) => T[K],\n  ) => Promise<void>;\n  clearAll: () => Promise<void>;\n}\n\n/** Per-key Standard Schemas — each schema's output type must match its storage field type. */\nexport type TTypedStorageSchemas<T extends Record<string, any>> = {\n  [K in StringKeys<T>]?: StandardSchemaV1<unknown, T[K]>;\n};\n\nexport interface ITypedStorageValidationOptions<T extends Record<string, any>> {\n  /**\n   * Opt-in, per key: when a key has a schema, every value crossing the storage boundary for it is\n   * validated **fail-closed** — reads, supplied defaults, writes, and both sides of an update\n   * (what the updater receives and what it returns). The schema's transformed/defaulted output\n   * (`result.value`) is what gets returned and persisted, so schema and storage never disagree.\n   * Keys without a schema keep the blind typed-cast behavior. Validation is synchronous-only: a\n   * schema returning a Promise fails validation.\n   */\n  schemas?: TTypedStorageSchemas<T>;\n  /**\n   * Observation hook (telemetry, logging) called with the error before it is thrown. The\n   * operation ALWAYS fails afterwards — this cannot suppress; a throwing hook fails it too.\n   */\n  onInvalid?: (error: StorageValidationError) => void;\n}\n\nexport interface ITypedStorage_Create_Input<T extends Record<string, any> = Record<string, any>>\n  extends ITypedStorageValidationOptions<T> {\n  storageAdapter: StorageAdapter;\n}\n\n/**\n * A typed view over a {@link StorageAdapter}. Without `schemas` it is types-only (the stored value\n * is trusted to match `T` — fine for values only your own code writes). With `schemas`, the\n * storage boundary gets the same treatment the action layer gives the wire: values are validated\n * on the way out **and** in, because durable storage is where stale shapes live longest — a value\n * written by version N and read by version N+3 has crossed every schema change in between.\n */\nexport function createTypedStorage<T extends Record<string, any>>({\n  storageAdapter,\n  schemas,\n  onInvalid,\n}: ITypedStorage_Create_Input<T>): ITypedStorage<T> {\n  const validate = <K extends StringKeys<T>>(key: K, value: unknown): T[K] => {\n    const schema = schemas?.[key];\n    // Callers only reach this with a schema present; the guard keeps the helper total.\n    if (schema == null) return value as T[K];\n    const result = schema[\"~standard\"].validate(value);\n    let issues: readonly StandardSchemaV1.Issue[];\n    if (result instanceof Promise) {\n      issues = [{ message: \"async schema validation is not supported for typed storage\" }];\n    } else if (result.issues != null) {\n      issues = result.issues;\n    } else {\n      return result.value;\n    }\n    const error = new StorageValidationError(key, issues);\n    onInvalid?.(error);\n    throw error;\n  };\n\n  const hasSchema = <K extends StringKeys<T>>(key: K): boolean => schemas?.[key] != null;\n\n  const getJson = async <K extends StringKeys<T>>(key: K): Promise<T[K] | undefined> => {\n    const stored = await storageAdapter.getJson<T[K]>(key);\n    if (stored === undefined || !hasSchema(key)) return stored;\n    return validate(key, stored);\n  };\n\n  const getJsonOrDef = async <K extends StringKeys<T>>(key: K, defVal: T[K]): Promise<T[K]> => {\n    const value = (await storageAdapter.getJson<T[K]>(key)) ?? defVal;\n    if (!hasSchema(key)) return value;\n    // The default validates too — a bad fallback must never reach the caller as \"valid\".\n    return validate(key, value);\n  };\n\n  const setJson = async <K extends StringKeys<T>>(key: K, val: T[K]): Promise<void> => {\n    return storageAdapter.setJson(key, hasSchema(key) ? validate(key, val) : val);\n  };\n\n  const removeItem = async <K extends StringKeys<T>>(key: K): Promise<void> => {\n    await storageAdapter.removeItem(key);\n  };\n\n  const updateJson = async <K extends StringKeys<T>>(\n    key: K,\n    updater: (currentVal: T[K] | undefined) => T[K],\n  ): Promise<void> => {\n    if (!hasSchema(key)) {\n      await storageAdapter.updateJson(key, updater);\n      return;\n    }\n    // Both directions validate: invalid stored data never reaches the updater, and an invalid\n    // updater result never reaches the adapter.\n    await storageAdapter.updateJson<T[K]>(key, (currentVal) =>\n      validate(key, updater(currentVal === undefined ? undefined : validate(key, currentVal))),\n    );\n  };\n\n  const updateJsonWithDef = async <K extends StringKeys<T>>(\n    key: K,\n    defaultVal: T[K],\n    updater: (currentVal: T[K]) => T[K],\n  ): Promise<void> => {\n    if (!hasSchema(key)) {\n      await storageAdapter.updateJsonOrDef(key, defaultVal, updater);\n      return;\n    }\n    await storageAdapter.updateJsonOrDef<T[K]>(key, defaultVal, (currentVal) =>\n      validate(key, updater(validate(key, currentVal))),\n    );\n  };\n\n  return {\n    getJson,\n    getJsonOrDef,\n    setJson,\n    removeItem,\n    updateJson,\n    updateJsonWithDef,\n    clearAll: async () => {\n      await storageAdapter.clearAll();\n    },\n  };\n}\n","export const generateEd25519KeyPair = async (): Promise<CryptoKeyPair> => {\n  const keyPair = (await crypto.subtle.generateKey({ name: \"Ed25519\" }, true, [\n    \"sign\",\n    \"verify\",\n  ])) as CryptoKeyPair;\n\n  return keyPair;\n};\n","import type { ECryptoKeyFormat } from \"../crypto/crypto.schema\";\n\ninterface ICreateDataStringConverter_StringToObject {\n  transformJsonForFormats?: ECryptoKeyFormat[];\n  transformJson?: boolean;\n}\n\nexport const createDataStringConverter_stringToObject =\n  <T extends string, F extends ECryptoKeyFormat, D = string>({\n    transformJsonForFormats = [],\n    transformJson = false,\n  }: ICreateDataStringConverter_StringToObject = {}) =>\n  (\n    inputDataString: `${T}::${F}::${string}`,\n  ): { formattedString: `${T}::${F}::${string}`; type: T; format: F; data: D } => {\n    const [type, format, dataString] = inputDataString.split(\"::\") as [\n      string,\n      ECryptoKeyFormat,\n      string,\n    ];\n    let parsedData: D = dataString as D;\n\n    if (transformJson || transformJsonForFormats.includes(format)) {\n      try {\n        parsedData = JSON.parse(dataString) as D;\n      } catch (error) {\n        const err = new Error(\n          `Failed to parse type and format data string. Given input: \"${inputDataString}\", expected JSON parsable \"data\" value in the format \"${type}::${format}::data\" ${error instanceof Error ? error.message : String(error)}`,\n        );\n\n        err.cause = error;\n        throw err;\n      }\n    }\n\n    return {\n      formattedString: inputDataString,\n      type: type as T,\n      format: format as F,\n      data: parsedData,\n    };\n  };\n","//#region src/storages/globalConfig/globalConfig.ts\nlet store$4;\nconst DEFAULT_CONFIG = {\n\tlang: void 0,\n\tmessage: void 0,\n\tabortEarly: void 0,\n\tabortPipeEarly: void 0\n};\n/**\n* Sets the global configuration.\n*\n* @param config The configuration.\n*/\nfunction setGlobalConfig(config$1) {\n\tstore$4 = {\n\t\t...store$4,\n\t\t...config$1\n\t};\n}\n/**\n* Returns the global configuration.\n*\n* @param config The config to merge.\n*\n* @returns The configuration.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction getGlobalConfig(config$1) {\n\tif (!config$1 && !store$4) return DEFAULT_CONFIG;\n\treturn {\n\t\tlang: config$1?.lang ?? store$4?.lang,\n\t\tmessage: config$1?.message,\n\t\tabortEarly: config$1?.abortEarly ?? store$4?.abortEarly,\n\t\tabortPipeEarly: config$1?.abortPipeEarly ?? store$4?.abortPipeEarly\n\t};\n}\n/**\n* Deletes the global configuration.\n*/\nfunction deleteGlobalConfig() {\n\tstore$4 = void 0;\n}\n\n//#endregion\n//#region src/storages/globalMessage/globalMessage.ts\nlet store$3;\n/**\n* Sets a global error message.\n*\n* @param message The error message.\n* @param lang The language of the message.\n*/\nfunction setGlobalMessage(message$1, lang) {\n\tif (!store$3) store$3 = /* @__PURE__ */ new Map();\n\tstore$3.set(lang, message$1);\n}\n/**\n* Returns a global error message.\n*\n* @param lang The language of the message.\n*\n* @returns The error message.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction getGlobalMessage(lang) {\n\treturn store$3?.get(lang);\n}\n/**\n* Deletes a global error message.\n*\n* @param lang The language of the message.\n*/\nfunction deleteGlobalMessage(lang) {\n\tstore$3?.delete(lang);\n}\n\n//#endregion\n//#region src/storages/schemaMessage/schemaMessage.ts\nlet store$2;\n/**\n* Sets a schema error message.\n*\n* @param message The error message.\n* @param lang The language of the message.\n*/\nfunction setSchemaMessage(message$1, lang) {\n\tif (!store$2) store$2 = /* @__PURE__ */ new Map();\n\tstore$2.set(lang, message$1);\n}\n/**\n* Returns a schema error message.\n*\n* @param lang The language of the message.\n*\n* @returns The error message.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction getSchemaMessage(lang) {\n\treturn store$2?.get(lang);\n}\n/**\n* Deletes a schema error message.\n*\n* @param lang The language of the message.\n*/\nfunction deleteSchemaMessage(lang) {\n\tstore$2?.delete(lang);\n}\n\n//#endregion\n//#region src/storages/specificMessage/specificMessage.ts\nlet store$1;\n/**\n* Sets a specific error message.\n*\n* @param reference The identifier reference.\n* @param message The error message.\n* @param lang The language of the message.\n*/\nfunction setSpecificMessage(reference, message$1, lang) {\n\tif (!store$1) store$1 = /* @__PURE__ */ new Map();\n\tif (!store$1.get(reference)) store$1.set(reference, /* @__PURE__ */ new Map());\n\tstore$1.get(reference).set(lang, message$1);\n}\n/**\n* Returns a specific error message.\n*\n* @param reference The identifier reference.\n* @param lang The language of the message.\n*\n* @returns The error message.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction getSpecificMessage(reference, lang) {\n\treturn store$1?.get(reference)?.get(lang);\n}\n/**\n* Deletes a specific error message.\n*\n* @param reference The identifier reference.\n* @param lang The language of the message.\n*/\nfunction deleteSpecificMessage(reference, lang) {\n\tstore$1?.get(reference)?.delete(lang);\n}\n\n//#endregion\n//#region src/utils/_stringify/_stringify.ts\n/**\n* Stringifies an unknown input to a literal or type string.\n*\n* @param input The unknown input.\n*\n* @returns A literal or type string.\n*\n* @internal\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction _stringify(input) {\n\tconst type = typeof input;\n\tif (type === \"string\") return `\"${input}\"`;\n\tif (type === \"number\" || type === \"bigint\" || type === \"boolean\") return `${input}`;\n\tif (type === \"object\" || type === \"function\") return (input && Object.getPrototypeOf(input)?.constructor?.name) ?? \"null\";\n\treturn type;\n}\n\n//#endregion\n//#region src/utils/_addIssue/_addIssue.ts\n/**\n* Adds an issue to the dataset.\n*\n* @param context The issue context.\n* @param label The issue label.\n* @param dataset The input dataset.\n* @param config The configuration.\n* @param other The optional props.\n*\n* @internal\n*/\nfunction _addIssue(context, label, dataset, config$1, other) {\n\tconst input = other && \"input\" in other ? other.input : dataset.value;\n\tconst expected = other?.expected ?? context.expects ?? null;\n\tconst received = other?.received ?? /* @__PURE__ */ _stringify(input);\n\tconst issue = {\n\t\tkind: context.kind,\n\t\ttype: context.type,\n\t\tinput,\n\t\texpected,\n\t\treceived,\n\t\tmessage: `Invalid ${label}: ${expected ? `Expected ${expected} but r` : \"R\"}eceived ${received}`,\n\t\trequirement: context.requirement,\n\t\tpath: other?.path,\n\t\tissues: other?.issues,\n\t\tlang: config$1.lang,\n\t\tabortEarly: config$1.abortEarly,\n\t\tabortPipeEarly: config$1.abortPipeEarly\n\t};\n\tconst isSchema = context.kind === \"schema\";\n\tconst message$1 = other?.message ?? context.message ?? /* @__PURE__ */ getSpecificMessage(context.reference, issue.lang) ?? (isSchema ? /* @__PURE__ */ getSchemaMessage(issue.lang) : null) ?? config$1.message ?? /* @__PURE__ */ getGlobalMessage(issue.lang);\n\tif (message$1 !== void 0) issue.message = typeof message$1 === \"function\" ? message$1(issue) : message$1;\n\tif (isSchema) dataset.typed = false;\n\tif (dataset.issues) dataset.issues.push(issue);\n\telse dataset.issues = [issue];\n}\n\n//#endregion\n//#region src/utils/_cloneDataset/_cloneDataset.ts\n/**\n* Creates a shallow copy of a dataset.\n*\n* Hint: The `value` is copied by reference, but the `issues` array is cloned\n* to avoid reusing mutable dataset state across multiple runs. Mutating a\n* returned object or array value can therefore affect later cache hits that\n* reuse the same cached output.\n*\n* @param dataset The output dataset.\n*\n* @returns The copied output dataset.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction _cloneDataset(dataset) {\n\treturn {\n\t\ttyped: dataset.typed,\n\t\tvalue: dataset.value,\n\t\tissues: dataset.issues && [...dataset.issues]\n\t};\n}\n\n//#endregion\n//#region src/utils/_formatCase/_formatCase.ts\n/**\n* Splits a string into lowercase words and rejoins them with the given\n* separator and capitalization rules.\n*\n* Words are separated by `_`, `-` and ASCII whitespace, as well as by case\n* and acronym boundaries. Whether the first or subsequent words are\n* capitalized is controlled by `capFirst` and `capRest`.\n*\n* Hint: Implemented in a single pass that emits directly to the result\n* string to avoid an intermediate `string[]` allocation. ASCII chars are\n* classified via char codes to skip `.toLowerCase()` and `.toUpperCase()`\n* method calls in the common case.\n*\n* Hint: Digits are treated as a separate character class, so `item2Name`\n* yields `item2` and `name` rather than `item`, `2` and `name`.\n*\n* @param input The input string.\n* @param separator The string inserted between words.\n* @param capFirst Whether to capitalize the first word.\n* @param capRest Whether to capitalize subsequent words.\n*\n* @returns The formatted string.\n*\n* @internal\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction _formatCase(input, separator, capFirst, capRest) {\n\tlet result = \"\";\n\tlet firstWord = true;\n\tlet start = 0;\n\tlet prev = 0;\n\tlet prevPrev = 0;\n\tconst flush = (end) => {\n\t\tif (end > start) {\n\t\t\tlet word = input.slice(start, end).toLowerCase();\n\t\t\tif (firstWord ? capFirst : capRest) {\n\t\t\t\tconst firstCode = word.charCodeAt(0);\n\t\t\t\tif (firstCode >= 97 && firstCode <= 122) word = String.fromCharCode(firstCode - 32) + word.slice(1);\n\t\t\t\telse {\n\t\t\t\t\tconst charLen = firstCode >= 55296 && firstCode <= 56319 ? 2 : 1;\n\t\t\t\t\tword = word.slice(0, charLen).toUpperCase() + word.slice(charLen);\n\t\t\t\t}\n\t\t\t}\n\t\t\tresult += firstWord ? word : separator + word;\n\t\t\tfirstWord = false;\n\t\t}\n\t};\n\tfor (let index = 0; index < input.length; index++) {\n\t\tconst code = input.charCodeAt(index);\n\t\tlet type;\n\t\tif (code === 32 || code === 9 || code === 10 || code === 11 || code === 12 || code === 13 || code === 45 || code === 95) {\n\t\t\tflush(index);\n\t\t\tstart = index + 1;\n\t\t\ttype = 0;\n\t\t} else if (code < 128) type = code >= 65 && code <= 90 ? 1 : code >= 97 && code <= 122 ? 2 : 3;\n\t\telse {\n\t\t\tconst char = input[index];\n\t\t\tconst charLower = char.toLowerCase();\n\t\t\ttype = charLower === char.toUpperCase() ? 3 : char === charLower ? 2 : 1;\n\t\t}\n\t\tif (type === 1 && (prev === 2 || prev === 3) && index > start) {\n\t\t\tflush(index);\n\t\t\tstart = index;\n\t\t} else if (type === 2 && prev === 1 && prevPrev === 1 && index - 1 > start) {\n\t\t\tflush(index - 1);\n\t\t\tstart = index - 1;\n\t\t}\n\t\tprevPrev = prev;\n\t\tprev = type;\n\t}\n\tflush(input.length);\n\treturn result;\n}\n\n//#endregion\n//#region src/utils/_getByteCount/_getByteCount.ts\nlet textEncoder;\n/**\n* Returns the byte count of the input.\n*\n* @param input The input to be measured.\n*\n* @returns The byte count.\n*\n* @internal\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction _getByteCount(input) {\n\tif (!textEncoder) textEncoder = new TextEncoder();\n\treturn textEncoder.encode(input).length;\n}\n\n//#endregion\n//#region src/utils/_getGraphemeCount/_getGraphemeCount.ts\nlet segmenter;\n/**\n* Returns the grapheme count of the input.\n*\n* @param input The input to be measured.\n*\n* @returns The grapheme count.\n*\n* @internal\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction _getGraphemeCount(input) {\n\tif (!segmenter) segmenter = new Intl.Segmenter();\n\tconst segments = segmenter.segment(input);\n\tlet count = 0;\n\tfor (const _ of segments) count++;\n\treturn count;\n}\n\n//#endregion\n//#region src/utils/_getLastMetadata/_getLastMetadata.ts\n/**\n* Returns the last top-level value of a given metadata type from a schema\n* using a breadth-first search that starts with the last item in the pipeline.\n*\n* @param schema The schema to search.\n* @param type The metadata type.\n*\n* @returns The value, if any.\n*\n* @internal\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction _getLastMetadata(schema, type) {\n\tif (\"pipe\" in schema) {\n\t\tconst nestedSchemas = [];\n\t\tfor (let index = schema.pipe.length - 1; index >= 0; index--) {\n\t\t\tconst item = schema.pipe[index];\n\t\t\tif (item.kind === \"schema\" && \"pipe\" in item) nestedSchemas.push(item);\n\t\t\telse if (item.kind === \"metadata\" && item.type === type) return item[type];\n\t\t}\n\t\tfor (const nestedSchema of nestedSchemas) {\n\t\t\tconst result = /* @__PURE__ */ _getLastMetadata(nestedSchema, type);\n\t\t\tif (result !== void 0) return result;\n\t\t}\n\t}\n}\n\n//#endregion\n//#region src/utils/_getStandardProps/_getStandardProps.ts\nconst _standardCache = /* @__PURE__ */ new WeakMap();\n/**\n* Returns the Standard Schema properties.\n*\n* @param context The schema context.\n*\n* @returns The Standard Schema properties.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction _getStandardProps(context) {\n\tlet cached = _standardCache.get(context);\n\tif (!cached) {\n\t\tcached = {\n\t\t\tversion: 1,\n\t\t\tvendor: \"valibot\",\n\t\t\tvalidate(value$1) {\n\t\t\t\treturn context[\"~run\"]({ value: value$1 }, /* @__PURE__ */ getGlobalConfig());\n\t\t\t}\n\t\t};\n\t\t_standardCache.set(context, cached);\n\t}\n\treturn cached;\n}\n\n//#endregion\n//#region src/utils/_getWordCount/_getWordCount.ts\nlet store;\n/**\n* Returns the word count of the input.\n*\n* @param locales The locales to be used.\n* @param input The input to be measured.\n*\n* @returns The word count.\n*\n* @internal\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction _getWordCount(locales, input) {\n\tif (!store) store = /* @__PURE__ */ new Map();\n\tconst key = String(locales);\n\tlet segmenter$1 = store.get(key);\n\tif (!segmenter$1) {\n\t\tsegmenter$1 = new Intl.Segmenter(locales, { granularity: \"word\" });\n\t\tstore.set(key, segmenter$1);\n\t}\n\tconst segments = segmenter$1.segment(input);\n\tlet count = 0;\n\tfor (const segment of segments) if (segment.isWordLike) count++;\n\treturn count;\n}\n\n//#endregion\n//#region src/utils/_isLuhnAlgo/_isLuhnAlgo.ts\n/**\n* Non-digit regex.\n*/\nconst NON_DIGIT_REGEX = /\\D/gu;\n/**\n* Checks whether a string with numbers corresponds to the luhn algorithm.\n*\n* @param input The input to be checked.\n*\n* @returns Whether input is valid.\n*\n* @internal\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction _isLuhnAlgo(input) {\n\tconst number$1 = input.replace(NON_DIGIT_REGEX, \"\");\n\tlet length$1 = number$1.length;\n\tlet bit = 1;\n\tlet sum = 0;\n\twhile (length$1) {\n\t\tconst value$1 = +number$1[--length$1];\n\t\tbit ^= 1;\n\t\tsum += bit ? [\n\t\t\t0,\n\t\t\t2,\n\t\t\t4,\n\t\t\t6,\n\t\t\t8,\n\t\t\t1,\n\t\t\t3,\n\t\t\t5,\n\t\t\t7,\n\t\t\t9\n\t\t][value$1] : value$1;\n\t}\n\treturn sum % 10 === 0;\n}\n\n//#endregion\n//#region src/utils/_isValidObjectKey/_isValidObjectKey.ts\n/**\n* Disallows inherited object properties and prevents object prototype\n* pollution by disallowing certain keys.\n*\n* @param object The object to check.\n* @param key The key to check.\n*\n* @returns Whether the key is allowed.\n*\n* @internal\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction _isValidObjectKey(object$1, key) {\n\treturn Object.prototype.hasOwnProperty.call(object$1, key) && key !== \"__proto__\" && key !== \"prototype\" && key !== \"constructor\";\n}\n\n//#endregion\n//#region src/utils/_joinExpects/_joinExpects.ts\n/**\n* Joins multiple `expects` values with the given separator.\n*\n* @param values The `expects` values.\n* @param separator The separator.\n*\n* @returns The joined `expects` property.\n*\n* @internal\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction _joinExpects(values$1, separator) {\n\tconst list = [...new Set(values$1)];\n\tif (list.length > 1) return `(${list.join(` ${separator} `)})`;\n\treturn list[0] ?? \"never\";\n}\n\n//#endregion\n//#region src/utils/entriesFromList/entriesFromList.ts\n/**\n* Creates an object entries definition from a list of keys and a schema.\n*\n* @param list A list of keys.\n* @param schema The schema of the keys.\n*\n* @returns The object entries.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction entriesFromList(list, schema) {\n\tconst entries$1 = {};\n\tfor (const key of list) entries$1[key] = schema;\n\treturn entries$1;\n}\n\n//#endregion\n//#region src/utils/entriesFromObjects/entriesFromObjects.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction entriesFromObjects(schemas) {\n\tconst entries$1 = {};\n\tfor (const schema of schemas) Object.assign(entries$1, schema.entries);\n\treturn entries$1;\n}\n\n//#endregion\n//#region src/utils/getDotPath/getDotPath.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction getDotPath(issue) {\n\tif (issue.path) {\n\t\tlet key = \"\";\n\t\tfor (const item of issue.path) if (typeof item.key === \"string\" || typeof item.key === \"number\") if (key) key += `.${item.key}`;\n\t\telse key += item.key;\n\t\telse return null;\n\t\treturn key;\n\t}\n\treturn null;\n}\n\n//#endregion\n//#region src/utils/isOfKind/isOfKind.ts\n/**\n* A generic type guard to check the kind of an object.\n*\n* @param kind The kind to check for.\n* @param object The object to check.\n*\n* @returns Whether it matches.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction isOfKind(kind, object$1) {\n\treturn object$1.kind === kind;\n}\n\n//#endregion\n//#region src/utils/isOfType/isOfType.ts\n/**\n* A generic type guard to check the type of an object.\n*\n* @param type The type to check for.\n* @param object The object to check.\n*\n* @returns Whether it matches.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction isOfType(type, object$1) {\n\treturn object$1.type === type;\n}\n\n//#endregion\n//#region src/utils/isValiError/isValiError.ts\n/**\n* A type guard to check if an error is a ValiError.\n*\n* @param error The error to check.\n*\n* @returns Whether its a ValiError.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction isValiError(error) {\n\treturn error instanceof ValiError;\n}\n\n//#endregion\n//#region src/utils/ValiError/ValiError.ts\n/**\n* A Valibot error with useful information.\n*/\nvar ValiError = class extends Error {\n\t/**\n\t* Creates a Valibot error with useful information.\n\t*\n\t* @param issues The error issues.\n\t*/\n\tconstructor(issues) {\n\t\tsuper(issues[0].message);\n\t\tthis.name = \"ValiError\";\n\t\tthis.issues = issues;\n\t}\n};\n\n//#endregion\n//#region src/actions/args/args.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction args(schema) {\n\treturn {\n\t\tkind: \"transformation\",\n\t\ttype: \"args\",\n\t\treference: args,\n\t\tasync: false,\n\t\tschema,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tconst func = dataset.value;\n\t\t\tdataset.value = (...args_) => {\n\t\t\t\tconst argsDataset = this.schema[\"~run\"]({ value: args_ }, config$1);\n\t\t\t\tif (argsDataset.issues) throw new ValiError(argsDataset.issues);\n\t\t\t\treturn func(...argsDataset.value);\n\t\t\t};\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/args/argsAsync.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction argsAsync(schema) {\n\treturn {\n\t\tkind: \"transformation\",\n\t\ttype: \"args\",\n\t\treference: argsAsync,\n\t\tasync: false,\n\t\tschema,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tconst func = dataset.value;\n\t\t\tdataset.value = async (...args$1) => {\n\t\t\t\tconst argsDataset = await schema[\"~run\"]({ value: args$1 }, config$1);\n\t\t\t\tif (argsDataset.issues) throw new ValiError(argsDataset.issues);\n\t\t\t\treturn func(...argsDataset.value);\n\t\t\t};\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/await/awaitAsync.ts\n/**\n* Creates an await transformation action.\n*\n* @returns An await action.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction awaitAsync() {\n\treturn {\n\t\tkind: \"transformation\",\n\t\ttype: \"await\",\n\t\treference: awaitAsync,\n\t\tasync: true,\n\t\tasync \"~run\"(dataset) {\n\t\t\tdataset.value = await dataset.value;\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/regex.ts\n/**\n* [Base64](https://en.wikipedia.org/wiki/Base64) regex.\n*/\nconst BASE64_REGEX = /^(?:[\\da-z+/]{4})*(?:[\\da-z+/]{2}==|[\\da-z+/]{3}=)?$/iu;\n/**\n* [BIC](https://en.wikipedia.org/wiki/ISO_9362) regex.\n*/\nconst BIC_REGEX = /^[A-Z]{6}(?!00)[\\dA-Z]{2}(?:[\\dA-Z]{3})?$/u;\n/**\n* [Cuid2](https://github.com/paralleldrive/cuid2) regex.\n*/\nconst CUID2_REGEX = /^[a-z][\\da-z]*$/u;\n/**\n* [Decimal](https://en.wikipedia.org/wiki/Decimal) regex.\n*/\nconst DECIMAL_REGEX = /^[+-]?(?:\\d*\\.)?\\d+$/u;\n/**\n* [Digits](https://en.wikipedia.org/wiki/Numerical_digit) regex.\n*/\nconst DIGITS_REGEX = /^\\d+$/u;\n/**\n* [Domain name](https://en.wikipedia.org/wiki/Domain_name) regex.\n*\n* Hint: We decided against the `i` flag for better JSON Schema compatibility.\n* ASCII-only validation. Internationalized domain names (IDNs) are not\n* supported, including Punycode-encoded labels.\n*/\nconst DOMAIN_REGEX = /^(?=.{1,253}$)(?:(?![Xx][Nn]--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\\.)+[A-Za-z]{2,63}$/u;\n/**\n* [Email address](https://en.wikipedia.org/wiki/Email_address) regex.\n*/\nconst EMAIL_REGEX = /^[\\w+-]+(?:\\.[\\w+-]+)*@[\\da-z]+(?:[.-][\\da-z]+)*\\.[a-z]{2,}$/iu;\n/**\n* Emoji regex from [emoji-regex-xs](https://github.com/slevithan/emoji-regex-xs) v1.0.0 (MIT license).\n*\n* Hint: We decided against the newer `/^\\p{RGI_Emoji}+$/v` regex because it is\n* not supported in older runtimes and does not match all emoji.\n*/\nconst EMOJI_REGEX = /^(?:[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|(?![\\p{Emoji_Modifier_Base}\\u{1F1E6}-\\u{1F1FF}])\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|(?![\\p{Emoji_Modifier_Base}\\u{1F1E6}-\\u{1F1FF}])\\p{Emoji_Presentation}))*)+$/u;\n/**\n* [Hexadecimal](https://en.wikipedia.org/wiki/Hexadecimal) regex.\n*\n* Hint: We decided against the `i` flag for better JSON Schema compatibility.\n*/\nconst HEXADECIMAL_REGEX = /^(?:0[hx])?[\\da-fA-F]+$/u;\n/**\n* [Hex color](https://en.wikipedia.org/wiki/Web_colors#Hex_triplet) regex.\n*\n* Hint: We decided against the `i` flag for better JSON Schema compatibility.\n*/\nconst HEX_COLOR_REGEX = /^#(?:[\\da-fA-F]{3,4}|[\\da-fA-F]{6}|[\\da-fA-F]{8})$/u;\n/**\n* [IMEI](https://en.wikipedia.org/wiki/International_Mobile_Equipment_Identity) regex.\n*/\nconst IMEI_REGEX = /^\\d{15}$|^\\d{2}-\\d{6}-\\d{6}-\\d$/u;\n/**\n* [IPv4](https://en.wikipedia.org/wiki/IPv4) regex.\n*/\nconst IPV4_REGEX = /^(?:(?:[1-9]|1\\d|2[0-4])?\\d|25[0-5])(?:\\.(?:(?:[1-9]|1\\d|2[0-4])?\\d|25[0-5])){3}$/u;\n/**\n* [IPv6](https://en.wikipedia.org/wiki/IPv6) regex.\n*/\nconst IPV6_REGEX = /^(?:(?:[\\da-f]{1,4}:){7}[\\da-f]{1,4}|(?:[\\da-f]{1,4}:){1,7}:|(?:[\\da-f]{1,4}:){1,6}:[\\da-f]{1,4}|(?:[\\da-f]{1,4}:){1,5}(?::[\\da-f]{1,4}){1,2}|(?:[\\da-f]{1,4}:){1,4}(?::[\\da-f]{1,4}){1,3}|(?:[\\da-f]{1,4}:){1,3}(?::[\\da-f]{1,4}){1,4}|(?:[\\da-f]{1,4}:){1,2}(?::[\\da-f]{1,4}){1,5}|[\\da-f]{1,4}:(?::[\\da-f]{1,4}){1,6}|:(?:(?::[\\da-f]{1,4}){1,7}|:)|fe80:(?::[\\da-f]{0,4}){0,4}%[\\da-z]+|::(?:f{4}(?::0{1,4})?:)?(?:(?:25[0-5]|(?:2[0-4]|1?\\d)?\\d)\\.){3}(?:25[0-5]|(?:2[0-4]|1?\\d)?\\d)|(?:[\\da-f]{1,4}:){1,4}:(?:(?:25[0-5]|(?:2[0-4]|1?\\d)?\\d)\\.){3}(?:25[0-5]|(?:2[0-4]|1?\\d)?\\d))$/iu;\n/**\n* [IP](https://en.wikipedia.org/wiki/IP_address) regex.\n*/\nconst IP_REGEX = /^(?:(?:[1-9]|1\\d|2[0-4])?\\d|25[0-5])(?:\\.(?:(?:[1-9]|1\\d|2[0-4])?\\d|25[0-5])){3}$|^(?:(?:[\\da-f]{1,4}:){7}[\\da-f]{1,4}|(?:[\\da-f]{1,4}:){1,7}:|(?:[\\da-f]{1,4}:){1,6}:[\\da-f]{1,4}|(?:[\\da-f]{1,4}:){1,5}(?::[\\da-f]{1,4}){1,2}|(?:[\\da-f]{1,4}:){1,4}(?::[\\da-f]{1,4}){1,3}|(?:[\\da-f]{1,4}:){1,3}(?::[\\da-f]{1,4}){1,4}|(?:[\\da-f]{1,4}:){1,2}(?::[\\da-f]{1,4}){1,5}|[\\da-f]{1,4}:(?::[\\da-f]{1,4}){1,6}|:(?:(?::[\\da-f]{1,4}){1,7}|:)|fe80:(?::[\\da-f]{0,4}){0,4}%[\\da-z]+|::(?:f{4}(?::0{1,4})?:)?(?:(?:25[0-5]|(?:2[0-4]|1?\\d)?\\d)\\.){3}(?:25[0-5]|(?:2[0-4]|1?\\d)?\\d)|(?:[\\da-f]{1,4}:){1,4}:(?:(?:25[0-5]|(?:2[0-4]|1?\\d)?\\d)\\.){3}(?:25[0-5]|(?:2[0-4]|1?\\d)?\\d))$/iu;\n/**\n* [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date regex.\n*/\nconst ISO_DATE_REGEX = /^\\d{4}-(?:0[1-9]|1[0-2])-(?:[12]\\d|0[1-9]|3[01])$/u;\n/**\n* [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time regex.\n*/\nconst ISO_DATE_TIME_REGEX = /^\\d{4}-(?:0[1-9]|1[0-2])-(?:[12]\\d|0[1-9]|3[01])[T ](?:0\\d|1\\d|2[0-3]):[0-5]\\d$/u;\n/**\n* [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with seconds regex.\n*/\nconst ISO_DATE_TIME_SECOND_REGEX = /^\\d{4}-(?:0[1-9]|1[0-2])-(?:[12]\\d|0[1-9]|3[01])[T ](?:0\\d|1\\d|2[0-3])(?::[0-5]\\d){2}$/u;\n/**\n* [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) time regex.\n*/\nconst ISO_TIME_REGEX = /^(?:0\\d|1\\d|2[0-3]):[0-5]\\d$/u;\n/**\n* [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) time with seconds regex.\n*/\nconst ISO_TIME_SECOND_REGEX = /^(?:0\\d|1\\d|2[0-3])(?::[0-5]\\d){2}$/u;\n/**\n* [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp regex. Allows a\n* space as a date/time separator and an optional space before the UTC offset.\n*/\nconst ISO_TIMESTAMP_REGEX = /^\\d{4}-(?:0[1-9]|1[0-2])-(?:[12]\\d|0[1-9]|3[01])[T ](?:0\\d|1\\d|2[0-3])(?::[0-5]\\d){2}(?:\\.\\d{1,9})?(?:Z| ?[+-](?:0\\d|1\\d|2[0-3])(?::?[0-5]\\d)?)$/u;\n/**\n* [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) week regex.\n*/\nconst ISO_WEEK_REGEX = /^\\d{4}-W(?:0[1-9]|[1-4]\\d|5[0-3])$/u;\n/**\n* [JWS compact serialization](https://datatracker.ietf.org/doc/html/rfc7515#section-3.1)\n* regex.\n*\n* Hint: Empty payload and signature segments are allowed because the\n* Base64URL-encoded representation of an empty octet sequence is an empty\n* string.\n*/\nconst JWS_COMPACT_REGEX = /^(?:[\\w-]{2,3}|(?:[\\w-]{4})+(?:[\\w-]{2,3})?)\\.(?:[\\w-]{2,3}|(?:[\\w-]{4})+(?:[\\w-]{2,3})?)?\\.(?:[\\w-]{2,3}|(?:[\\w-]{4})+(?:[\\w-]{2,3})?)?$/u;\n/**\n* [ISRC](https://en.wikipedia.org/wiki/International_Standard_Recording_Code) regex.\n*/\nconst ISRC_REGEX = /^(?:[A-Z]{2}[A-Z\\d]{3}\\d{7}|[A-Z]{2}-[A-Z\\d]{3}-\\d{2}-\\d{5})$/u;\n/**\n* [MAC](https://en.wikipedia.org/wiki/MAC_address) 48 bit regex.\n*\n* Hint: We decided against the `i` flag for better JSON Schema compatibility.\n*/\nconst MAC48_REGEX = /^(?:[\\da-fA-F]{2}:){5}[\\da-fA-F]{2}$|^(?:[\\da-fA-F]{2}-){5}[\\da-fA-F]{2}$|^(?:[\\da-fA-F]{4}\\.){2}[\\da-fA-F]{4}$/u;\n/**\n* [MAC](https://en.wikipedia.org/wiki/MAC_address) 64 bit regex.\n*\n* Hint: We decided against the `i` flag for better JSON Schema compatibility.\n*/\nconst MAC64_REGEX = /^(?:[\\da-fA-F]{2}:){7}[\\da-fA-F]{2}$|^(?:[\\da-fA-F]{2}-){7}[\\da-fA-F]{2}$|^(?:[\\da-fA-F]{4}\\.){3}[\\da-fA-F]{4}$|^(?:[\\da-fA-F]{4}:){3}[\\da-fA-F]{4}$/u;\n/**\n* [MAC](https://en.wikipedia.org/wiki/MAC_address) regex.\n*\n* Hint: We decided against the `i` flag for better JSON Schema compatibility.\n*/\nconst MAC_REGEX = /^(?:[\\da-fA-F]{2}:){5}[\\da-fA-F]{2}$|^(?:[\\da-fA-F]{2}-){5}[\\da-fA-F]{2}$|^(?:[\\da-fA-F]{4}\\.){2}[\\da-fA-F]{4}$|^(?:[\\da-fA-F]{2}:){7}[\\da-fA-F]{2}$|^(?:[\\da-fA-F]{2}-){7}[\\da-fA-F]{2}$|^(?:[\\da-fA-F]{4}\\.){3}[\\da-fA-F]{4}$|^(?:[\\da-fA-F]{4}:){3}[\\da-fA-F]{4}$/u;\n/**\n* [Nano ID](https://github.com/ai/nanoid) regex.\n*/\nconst NANO_ID_REGEX = /^[\\w-]+$/u;\n/**\n* [Octal](https://en.wikipedia.org/wiki/Octal) regex.\n*/\nconst OCTAL_REGEX = /^(?:0o)?[0-7]+$/u;\n/**\n* [RFC 5322 email address](https://datatracker.ietf.org/doc/html/rfc5322#section-3.4.1) regex.\n*\n* Hint: This regex was taken from the [HTML Living Standard Specification](https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address) and does not perfectly represent RFC 5322.\n*/\nconst RFC_EMAIL_REGEX = /^[a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n/**\n* [Slug](https://en.wikipedia.org/wiki/Clean_URL#Slug) regex.\n*/\nconst SLUG_REGEX = /^[\\da-z]+(?:[-_][\\da-z]+)*$/u;\n/**\n* [ULID](https://github.com/ulid/spec) regex.\n*\n* Hint: We decided against the `i` flag for better JSON Schema compatibility.\n*/\nconst ULID_REGEX = /^[\\da-hjkmnp-tv-zA-HJKMNP-TV-Z]{26}$/u;\n/**\n* [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier) regex.\n*/\nconst UUID_REGEX = /^[\\da-f]{8}(?:-[\\da-f]{4}){3}-[\\da-f]{12}$/iu;\n\n//#endregion\n//#region src/actions/base64/base64.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction base64(message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"base64\",\n\t\treference: base64,\n\t\tasync: false,\n\t\texpects: null,\n\t\trequirement: BASE64_REGEX,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement.test(dataset.value)) _addIssue(this, \"Base64\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/bic/bic.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction bic(message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"bic\",\n\t\treference: bic,\n\t\tasync: false,\n\t\texpects: null,\n\t\trequirement: BIC_REGEX,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement.test(dataset.value)) _addIssue(this, \"BIC\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/brand/brand.ts\n/**\n* Creates a brand transformation action.\n*\n* @param name The brand name.\n*\n* @returns A brand action.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction brand(name) {\n\treturn {\n\t\tkind: \"transformation\",\n\t\ttype: \"brand\",\n\t\treference: brand,\n\t\tasync: false,\n\t\tname,\n\t\t\"~run\"(dataset) {\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/bytes/bytes.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction bytes(requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"bytes\",\n\t\treference: bytes,\n\t\tasync: false,\n\t\texpects: `${requirement}`,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed) {\n\t\t\t\tconst length$1 = /* @__PURE__ */ _getByteCount(dataset.value);\n\t\t\t\tif (length$1 !== this.requirement) _addIssue(this, \"bytes\", dataset, config$1, { received: `${length$1}` });\n\t\t\t}\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/check/check.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction check(requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"check\",\n\t\treference: check,\n\t\tasync: false,\n\t\texpects: null,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement(dataset.value)) _addIssue(this, \"input\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/check/checkAsync.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction checkAsync(requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"check\",\n\t\treference: checkAsync,\n\t\tasync: true,\n\t\texpects: null,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\tasync \"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !await this.requirement(dataset.value)) _addIssue(this, \"input\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/checkItems/checkItems.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction checkItems(requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"check_items\",\n\t\treference: checkItems,\n\t\tasync: false,\n\t\texpects: null,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed) for (let index = 0; index < dataset.value.length; index++) {\n\t\t\t\tconst item = dataset.value[index];\n\t\t\t\tif (!this.requirement(item, index, dataset.value)) _addIssue(this, \"item\", dataset, config$1, {\n\t\t\t\t\tinput: item,\n\t\t\t\t\tpath: [{\n\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\torigin: \"value\",\n\t\t\t\t\t\tinput: dataset.value,\n\t\t\t\t\t\tkey: index,\n\t\t\t\t\t\tvalue: item\n\t\t\t\t\t}]\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/checkItems/checkItemsAsync.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction checkItemsAsync(requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"check_items\",\n\t\treference: checkItemsAsync,\n\t\tasync: true,\n\t\texpects: null,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\tasync \"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed) {\n\t\t\t\tconst requirementResults = await Promise.all(dataset.value.map(this.requirement));\n\t\t\t\tfor (let index = 0; index < dataset.value.length; index++) if (!requirementResults[index]) {\n\t\t\t\t\tconst item = dataset.value[index];\n\t\t\t\t\t_addIssue(this, \"item\", dataset, config$1, {\n\t\t\t\t\t\tinput: item,\n\t\t\t\t\t\tpath: [{\n\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\torigin: \"value\",\n\t\t\t\t\t\t\tinput: dataset.value,\n\t\t\t\t\t\t\tkey: index,\n\t\t\t\t\t\t\tvalue: item\n\t\t\t\t\t\t}]\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/creditCard/creditCard.ts\n/**\n* Credit card regex.\n*/\nconst CREDIT_CARD_REGEX = /^(?:\\d{13,19}|\\d{4}(?: \\d{3,6}){2,4}|\\d{4}(?:-\\d{3,6}){2,4})$/u;\n/**\n* Sanitize regex.\n*/\nconst SANITIZE_REGEX = /[- ]/gu;\n/**\n* Provider regex list.\n*/\nconst PROVIDER_REGEX_LIST = [\n\t/^3[47]\\d{13}$/u,\n\t/^3(?:0[0-5]|[68]\\d)\\d{11,13}$/u,\n\t/^6(?:011|5\\d{2})\\d{12,15}$/u,\n\t/^(?:2131|1800|35\\d{3})\\d{11}$/u,\n\t/^(?:5[1-5]\\d{2}|222\\d|22[3-9]\\d|2[3-6]\\d{2}|27[01]\\d|2720)\\d{12}$/u,\n\t/^(?:6[27]\\d{14,17}|81\\d{14,17})$/u,\n\t/^4\\d{12}(?:\\d{3,6})?$/u\n];\n/* @__NO_SIDE_EFFECTS__ */\nfunction creditCard(message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"credit_card\",\n\t\treference: creditCard,\n\t\tasync: false,\n\t\texpects: null,\n\t\trequirement(input) {\n\t\t\tlet sanitized;\n\t\t\treturn CREDIT_CARD_REGEX.test(input) && (sanitized = input.replace(SANITIZE_REGEX, \"\")) && PROVIDER_REGEX_LIST.some((regex$1) => regex$1.test(sanitized)) && /* @__PURE__ */ _isLuhnAlgo(sanitized);\n\t\t},\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement(dataset.value)) _addIssue(this, \"credit card\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/cuid2/cuid2.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction cuid2(message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"cuid2\",\n\t\treference: cuid2,\n\t\tasync: false,\n\t\texpects: null,\n\t\trequirement: CUID2_REGEX,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement.test(dataset.value)) _addIssue(this, \"Cuid2\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/decimal/decimal.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction decimal(message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"decimal\",\n\t\treference: decimal,\n\t\tasync: false,\n\t\texpects: null,\n\t\trequirement: DECIMAL_REGEX,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement.test(dataset.value)) _addIssue(this, \"decimal\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/description/description.ts\n/**\n* Creates a description metadata action.\n*\n* @param description_ The description text.\n*\n* @returns A description action.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction description(description_) {\n\treturn {\n\t\tkind: \"metadata\",\n\t\ttype: \"description\",\n\t\treference: description,\n\t\tdescription: description_\n\t};\n}\n\n//#endregion\n//#region src/actions/digits/digits.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction digits(message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"digits\",\n\t\treference: digits,\n\t\tasync: false,\n\t\texpects: null,\n\t\trequirement: DIGITS_REGEX,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement.test(dataset.value)) _addIssue(this, \"digits\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/domain/domain.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction domain(message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"domain\",\n\t\treference: domain,\n\t\texpects: null,\n\t\tasync: false,\n\t\trequirement: DOMAIN_REGEX,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement.test(dataset.value)) _addIssue(this, \"domain\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/email/email.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction email(message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"email\",\n\t\treference: email,\n\t\texpects: null,\n\t\tasync: false,\n\t\trequirement: EMAIL_REGEX,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement.test(dataset.value)) _addIssue(this, \"email\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/emoji/emoji.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction emoji(message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"emoji\",\n\t\treference: emoji,\n\t\tasync: false,\n\t\texpects: null,\n\t\trequirement: EMOJI_REGEX,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement.test(dataset.value)) _addIssue(this, \"emoji\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/empty/empty.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction empty(message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"empty\",\n\t\treference: empty,\n\t\tasync: false,\n\t\texpects: \"0\",\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && dataset.value.length > 0) _addIssue(this, \"length\", dataset, config$1, { received: `${dataset.value.length}` });\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/endsWith/endsWith.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction endsWith(requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"ends_with\",\n\t\treference: endsWith,\n\t\tasync: false,\n\t\texpects: `\"${requirement}\"`,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !dataset.value.endsWith(this.requirement)) _addIssue(this, \"end\", dataset, config$1, { received: `\"${dataset.value.slice(-this.requirement.length)}\"` });\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/entries/entries.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction entries(requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"entries\",\n\t\treference: entries,\n\t\tasync: false,\n\t\texpects: `${requirement}`,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (!dataset.typed) return dataset;\n\t\t\tconst count = Object.keys(dataset.value).length;\n\t\t\tif (dataset.typed && count !== this.requirement) _addIssue(this, \"entries\", dataset, config$1, { received: `${count}` });\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/everyItem/everyItem.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction everyItem(requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"every_item\",\n\t\treference: everyItem,\n\t\tasync: false,\n\t\texpects: null,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !dataset.value.every(this.requirement)) _addIssue(this, \"item\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/examples/examples.ts\n/**\n* Creates an examples metadata action.\n*\n* @param examples_ The examples.\n*\n* @returns An examples action.\n*\n* @beta\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction examples(examples_) {\n\treturn {\n\t\tkind: \"metadata\",\n\t\ttype: \"examples\",\n\t\treference: examples,\n\t\texamples: examples_\n\t};\n}\n\n//#endregion\n//#region src/actions/excludes/excludes.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction excludes(requirement, message$1) {\n\tconst received = /* @__PURE__ */ _stringify(requirement);\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"excludes\",\n\t\treference: excludes,\n\t\tasync: false,\n\t\texpects: `!${received}`,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && dataset.value.includes(this.requirement)) _addIssue(this, \"content\", dataset, config$1, { received });\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/filterItems/filterItems.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction filterItems(operation) {\n\treturn {\n\t\tkind: \"transformation\",\n\t\ttype: \"filter_items\",\n\t\treference: filterItems,\n\t\tasync: false,\n\t\toperation,\n\t\t\"~run\"(dataset) {\n\t\t\tdataset.value = dataset.value.filter(this.operation);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/findItem/findItem.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction findItem(operation) {\n\treturn {\n\t\tkind: \"transformation\",\n\t\ttype: \"find_item\",\n\t\treference: findItem,\n\t\tasync: false,\n\t\toperation,\n\t\t\"~run\"(dataset) {\n\t\t\tdataset.value = dataset.value.find(this.operation);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/finite/finite.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction finite(message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"finite\",\n\t\treference: finite,\n\t\tasync: false,\n\t\texpects: null,\n\t\trequirement: Number.isFinite,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement(dataset.value)) _addIssue(this, \"finite\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/flavor/flavor.ts\n/**\n* Creates a flavor transformation action.\n*\n* @param name The flavor name.\n*\n* @returns A flavor action.\n*\n* @beta\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction flavor(name) {\n\treturn {\n\t\tkind: \"transformation\",\n\t\ttype: \"flavor\",\n\t\treference: flavor,\n\t\tasync: false,\n\t\tname,\n\t\t\"~run\"(dataset) {\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/graphemes/graphemes.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction graphemes(requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"graphemes\",\n\t\treference: graphemes,\n\t\tasync: false,\n\t\texpects: `${requirement}`,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed) {\n\t\t\t\tconst count = /* @__PURE__ */ _getGraphemeCount(dataset.value);\n\t\t\t\tif (count !== this.requirement) _addIssue(this, \"graphemes\", dataset, config$1, { received: `${count}` });\n\t\t\t}\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/gtValue/gtValue.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction gtValue(requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"gt_value\",\n\t\treference: gtValue,\n\t\tasync: false,\n\t\texpects: `>${requirement instanceof Date ? requirement.toJSON() : /* @__PURE__ */ _stringify(requirement)}`,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !(dataset.value > this.requirement)) _addIssue(this, \"value\", dataset, config$1, { received: dataset.value instanceof Date ? dataset.value.toJSON() : /* @__PURE__ */ _stringify(dataset.value) });\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/guard/guard.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction guard(requirement, message$1) {\n\treturn {\n\t\tkind: \"transformation\",\n\t\ttype: \"guard\",\n\t\treference: guard,\n\t\tasync: false,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement(dataset.value)) {\n\t\t\t\t_addIssue(this, \"input\", dataset, config$1);\n\t\t\t\tdataset.typed = false;\n\t\t\t}\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/hash/hash.ts\n/**\n* Hash lengths object.\n*/\nconst HASH_LENGTHS = {\n\tmd4: 32,\n\tmd5: 32,\n\tsha1: 40,\n\tsha256: 64,\n\tsha384: 96,\n\tsha512: 128,\n\tripemd128: 32,\n\tripemd160: 40,\n\ttiger128: 32,\n\ttiger160: 40,\n\ttiger192: 48,\n\tcrc32: 8,\n\tcrc32b: 8,\n\tadler32: 8\n};\n/* @__NO_SIDE_EFFECTS__ */\nfunction hash(types, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"hash\",\n\t\treference: hash,\n\t\texpects: null,\n\t\tasync: false,\n\t\trequirement: RegExp(types.map((type) => `^[a-fA-F0-9]{${HASH_LENGTHS[type]}}$`).join(\"|\"), \"u\"),\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement.test(dataset.value)) _addIssue(this, \"hash\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/hexadecimal/hexadecimal.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction hexadecimal(message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"hexadecimal\",\n\t\treference: hexadecimal,\n\t\tasync: false,\n\t\texpects: null,\n\t\trequirement: HEXADECIMAL_REGEX,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement.test(dataset.value)) _addIssue(this, \"hexadecimal\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/hexColor/hexColor.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction hexColor(message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"hex_color\",\n\t\treference: hexColor,\n\t\tasync: false,\n\t\texpects: null,\n\t\trequirement: HEX_COLOR_REGEX,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement.test(dataset.value)) _addIssue(this, \"hex color\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/imei/imei.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction imei(message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"imei\",\n\t\treference: imei,\n\t\tasync: false,\n\t\texpects: null,\n\t\trequirement(input) {\n\t\t\treturn IMEI_REGEX.test(input) && /* @__PURE__ */ _isLuhnAlgo(input);\n\t\t},\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement(dataset.value)) _addIssue(this, \"IMEI\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/includes/includes.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction includes(requirement, message$1) {\n\tconst expects = /* @__PURE__ */ _stringify(requirement);\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"includes\",\n\t\treference: includes,\n\t\tasync: false,\n\t\texpects,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !dataset.value.includes(this.requirement)) _addIssue(this, \"content\", dataset, config$1, { received: `!${expects}` });\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/integer/integer.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction integer(message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"integer\",\n\t\treference: integer,\n\t\tasync: false,\n\t\texpects: null,\n\t\trequirement: Number.isInteger,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement(dataset.value)) _addIssue(this, \"integer\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/ip/ip.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction ip(message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"ip\",\n\t\treference: ip,\n\t\tasync: false,\n\t\texpects: null,\n\t\trequirement: IP_REGEX,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement.test(dataset.value)) _addIssue(this, \"IP\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/ipv4/ipv4.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction ipv4(message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"ipv4\",\n\t\treference: ipv4,\n\t\tasync: false,\n\t\texpects: null,\n\t\trequirement: IPV4_REGEX,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement.test(dataset.value)) _addIssue(this, \"IPv4\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/ipv6/ipv6.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction ipv6(message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"ipv6\",\n\t\treference: ipv6,\n\t\tasync: false,\n\t\texpects: null,\n\t\trequirement: IPV6_REGEX,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement.test(dataset.value)) _addIssue(this, \"IPv6\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/isbn/utils/_isIsbn10.ts\n/**\n* [Validates an ISBN-10](https://en.wikipedia.org/wiki/ISBN#ISBN-10_check_digits).\n*\n* @param input The input value.\n*\n* @returns `true` if the input is a valid ISBN-10, `false` otherwise.\n*\n* @internal\n*/\nfunction _isIsbn10(input) {\n\tconst digits$1 = input.split(\"\").map((c) => c === \"X\" ? 10 : parseInt(c));\n\tlet sum = 0;\n\tfor (let i = 0; i < 10; i++) sum += digits$1[i] * (10 - i);\n\treturn sum % 11 === 0;\n}\n\n//#endregion\n//#region src/actions/isbn/utils/_isIsbn13.ts\n/**\n* [Validates an ISBN-13](https://en.wikipedia.org/wiki/ISBN#ISBN-13_check_digit_calculation).\n*\n* @param input The input value.\n*\n* @returns `true` if the input is a valid ISBN-13, `false` otherwise.\n*\n* @internal\n*/\nfunction _isIsbn13(input) {\n\tconst digits$1 = input.split(\"\").map((c) => parseInt(c));\n\tlet sum = 0;\n\tfor (let i = 0; i < 13; i++) sum += digits$1[i] * (i % 2 === 0 ? 1 : 3);\n\treturn sum % 10 === 0;\n}\n\n//#endregion\n//#region src/actions/isbn/isbn.ts\n/**\n* ISBN separator regex.\n*/\nconst ISBN_SEPARATOR_REGEX = /[- ]/gu;\n/**\n* ISBN-10 detection regex.\n*/\nconst ISBN_10_DETECTION_REGEX = /^\\d{9}[\\dX]$/u;\n/**\n* ISBN-13 detection regex.\n*/\nconst ISBN_13_DETECTION_REGEX = /^\\d{13}$/u;\n/* @__NO_SIDE_EFFECTS__ */\nfunction isbn(message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"isbn\",\n\t\treference: isbn,\n\t\tasync: false,\n\t\texpects: null,\n\t\trequirement(input) {\n\t\t\tconst replacedInput = input.replace(ISBN_SEPARATOR_REGEX, \"\");\n\t\t\tif (ISBN_10_DETECTION_REGEX.test(replacedInput)) return _isIsbn10(replacedInput);\n\t\t\telse if (ISBN_13_DETECTION_REGEX.test(replacedInput)) return _isIsbn13(replacedInput);\n\t\t\treturn false;\n\t\t},\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement(dataset.value)) _addIssue(this, \"ISBN\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/isrc/isrc.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction isrc(message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"isrc\",\n\t\treference: isrc,\n\t\tasync: false,\n\t\texpects: null,\n\t\trequirement: ISRC_REGEX,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement.test(dataset.value)) _addIssue(this, \"ISRC\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/isoDate/isoDate.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction isoDate(message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"iso_date\",\n\t\treference: isoDate,\n\t\tasync: false,\n\t\texpects: null,\n\t\trequirement: ISO_DATE_REGEX,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement.test(dataset.value)) _addIssue(this, \"date\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/isoDateTime/isoDateTime.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction isoDateTime(message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"iso_date_time\",\n\t\treference: isoDateTime,\n\t\tasync: false,\n\t\texpects: null,\n\t\trequirement: ISO_DATE_TIME_REGEX,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement.test(dataset.value)) _addIssue(this, \"date-time\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/isoDateTimeSecond/isoDateTimeSecond.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction isoDateTimeSecond(message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"iso_date_time_second\",\n\t\treference: isoDateTimeSecond,\n\t\tasync: false,\n\t\texpects: null,\n\t\trequirement: ISO_DATE_TIME_SECOND_REGEX,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement.test(dataset.value)) _addIssue(this, \"date-time-second\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/isoTime/isoTime.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction isoTime(message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"iso_time\",\n\t\treference: isoTime,\n\t\tasync: false,\n\t\texpects: null,\n\t\trequirement: ISO_TIME_REGEX,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement.test(dataset.value)) _addIssue(this, \"time\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/isoTimeSecond/isoTimeSecond.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction isoTimeSecond(message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"iso_time_second\",\n\t\treference: isoTimeSecond,\n\t\tasync: false,\n\t\texpects: null,\n\t\trequirement: ISO_TIME_SECOND_REGEX,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement.test(dataset.value)) _addIssue(this, \"time-second\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/isoTimestamp/isoTimestamp.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction isoTimestamp(message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"iso_timestamp\",\n\t\treference: isoTimestamp,\n\t\tasync: false,\n\t\texpects: null,\n\t\trequirement: ISO_TIMESTAMP_REGEX,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement.test(dataset.value)) _addIssue(this, \"timestamp\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/isoWeek/isoWeek.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction isoWeek(message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"iso_week\",\n\t\treference: isoWeek,\n\t\tasync: false,\n\t\texpects: null,\n\t\trequirement: ISO_WEEK_REGEX,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement.test(dataset.value)) _addIssue(this, \"week\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/jwsCompact/jwsCompact.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction jwsCompact(message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"jws_compact\",\n\t\treference: jwsCompact,\n\t\tasync: false,\n\t\texpects: null,\n\t\trequirement: JWS_COMPACT_REGEX,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement.test(dataset.value)) _addIssue(this, \"JWS compact\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/length/length.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction length(requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"length\",\n\t\treference: length,\n\t\tasync: false,\n\t\texpects: `${requirement}`,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && dataset.value.length !== this.requirement) _addIssue(this, \"length\", dataset, config$1, { received: `${dataset.value.length}` });\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/ltValue/ltValue.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction ltValue(requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"lt_value\",\n\t\treference: ltValue,\n\t\tasync: false,\n\t\texpects: `<${requirement instanceof Date ? requirement.toJSON() : /* @__PURE__ */ _stringify(requirement)}`,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !(dataset.value < this.requirement)) _addIssue(this, \"value\", dataset, config$1, { received: dataset.value instanceof Date ? dataset.value.toJSON() : /* @__PURE__ */ _stringify(dataset.value) });\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/mac/mac.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction mac(message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"mac\",\n\t\treference: mac,\n\t\tasync: false,\n\t\texpects: null,\n\t\trequirement: MAC_REGEX,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement.test(dataset.value)) _addIssue(this, \"MAC\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/mac48/mac48.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction mac48(message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"mac48\",\n\t\treference: mac48,\n\t\tasync: false,\n\t\texpects: null,\n\t\trequirement: MAC48_REGEX,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement.test(dataset.value)) _addIssue(this, \"48-bit MAC\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/mac64/mac64.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction mac64(message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"mac64\",\n\t\treference: mac64,\n\t\tasync: false,\n\t\texpects: null,\n\t\trequirement: MAC64_REGEX,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement.test(dataset.value)) _addIssue(this, \"64-bit MAC\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/mapItems/mapItems.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction mapItems(operation) {\n\treturn {\n\t\tkind: \"transformation\",\n\t\ttype: \"map_items\",\n\t\treference: mapItems,\n\t\tasync: false,\n\t\toperation,\n\t\t\"~run\"(dataset) {\n\t\t\tdataset.value = dataset.value.map(this.operation);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/maxBytes/maxBytes.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction maxBytes(requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"max_bytes\",\n\t\treference: maxBytes,\n\t\tasync: false,\n\t\texpects: `<=${requirement}`,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed) {\n\t\t\t\tconst length$1 = /* @__PURE__ */ _getByteCount(dataset.value);\n\t\t\t\tif (length$1 > this.requirement) _addIssue(this, \"bytes\", dataset, config$1, { received: `${length$1}` });\n\t\t\t}\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/maxEntries/maxEntries.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction maxEntries(requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"max_entries\",\n\t\treference: maxEntries,\n\t\tasync: false,\n\t\texpects: `<=${requirement}`,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (!dataset.typed) return dataset;\n\t\t\tconst count = Object.keys(dataset.value).length;\n\t\t\tif (dataset.typed && count > this.requirement) _addIssue(this, \"entries\", dataset, config$1, { received: `${count}` });\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/maxGraphemes/maxGraphemes.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction maxGraphemes(requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"max_graphemes\",\n\t\treference: maxGraphemes,\n\t\tasync: false,\n\t\texpects: `<=${requirement}`,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed) {\n\t\t\t\tconst count = /* @__PURE__ */ _getGraphemeCount(dataset.value);\n\t\t\t\tif (count > this.requirement) _addIssue(this, \"graphemes\", dataset, config$1, { received: `${count}` });\n\t\t\t}\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/maxLength/maxLength.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction maxLength(requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"max_length\",\n\t\treference: maxLength,\n\t\tasync: false,\n\t\texpects: `<=${requirement}`,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && dataset.value.length > this.requirement) _addIssue(this, \"length\", dataset, config$1, { received: `${dataset.value.length}` });\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/maxSize/maxSize.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction maxSize(requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"max_size\",\n\t\treference: maxSize,\n\t\tasync: false,\n\t\texpects: `<=${requirement}`,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && dataset.value.size > this.requirement) _addIssue(this, \"size\", dataset, config$1, { received: `${dataset.value.size}` });\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/maxValue/maxValue.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction maxValue(requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"max_value\",\n\t\treference: maxValue,\n\t\tasync: false,\n\t\texpects: `<=${requirement instanceof Date ? requirement.toJSON() : /* @__PURE__ */ _stringify(requirement)}`,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !(dataset.value <= this.requirement)) _addIssue(this, \"value\", dataset, config$1, { received: dataset.value instanceof Date ? dataset.value.toJSON() : /* @__PURE__ */ _stringify(dataset.value) });\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/maxWords/maxWords.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction maxWords(locales, requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"max_words\",\n\t\treference: maxWords,\n\t\tasync: false,\n\t\texpects: `<=${requirement}`,\n\t\tlocales,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed) {\n\t\t\t\tconst count = /* @__PURE__ */ _getWordCount(this.locales, dataset.value);\n\t\t\t\tif (count > this.requirement) _addIssue(this, \"words\", dataset, config$1, { received: `${count}` });\n\t\t\t}\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/metadata/metadata.ts\n/**\n* Creates a custom metadata action.\n*\n* @param metadata_ The metadata object.\n*\n* @returns A metadata action.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction metadata(metadata_) {\n\treturn {\n\t\tkind: \"metadata\",\n\t\ttype: \"metadata\",\n\t\treference: metadata,\n\t\tmetadata: metadata_\n\t};\n}\n\n//#endregion\n//#region src/actions/mimeType/mimeType.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction mimeType(requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"mime_type\",\n\t\treference: mimeType,\n\t\tasync: false,\n\t\texpects: /* @__PURE__ */ _joinExpects(requirement.map((option) => `\"${option}\"`), \"|\"),\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement.includes(dataset.value.type)) _addIssue(this, \"MIME type\", dataset, config$1, { received: `\"${dataset.value.type}\"` });\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/minBytes/minBytes.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction minBytes(requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"min_bytes\",\n\t\treference: minBytes,\n\t\tasync: false,\n\t\texpects: `>=${requirement}`,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed) {\n\t\t\t\tconst length$1 = /* @__PURE__ */ _getByteCount(dataset.value);\n\t\t\t\tif (length$1 < this.requirement) _addIssue(this, \"bytes\", dataset, config$1, { received: `${length$1}` });\n\t\t\t}\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/minEntries/minEntries.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction minEntries(requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"min_entries\",\n\t\treference: minEntries,\n\t\tasync: false,\n\t\texpects: `>=${requirement}`,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (!dataset.typed) return dataset;\n\t\t\tconst count = Object.keys(dataset.value).length;\n\t\t\tif (dataset.typed && count < this.requirement) _addIssue(this, \"entries\", dataset, config$1, { received: `${count}` });\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/minGraphemes/minGraphemes.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction minGraphemes(requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"min_graphemes\",\n\t\treference: minGraphemes,\n\t\tasync: false,\n\t\texpects: `>=${requirement}`,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed) {\n\t\t\t\tconst count = /* @__PURE__ */ _getGraphemeCount(dataset.value);\n\t\t\t\tif (count < this.requirement) _addIssue(this, \"graphemes\", dataset, config$1, { received: `${count}` });\n\t\t\t}\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/minLength/minLength.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction minLength(requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"min_length\",\n\t\treference: minLength,\n\t\tasync: false,\n\t\texpects: `>=${requirement}`,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && dataset.value.length < this.requirement) _addIssue(this, \"length\", dataset, config$1, { received: `${dataset.value.length}` });\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/minSize/minSize.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction minSize(requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"min_size\",\n\t\treference: minSize,\n\t\tasync: false,\n\t\texpects: `>=${requirement}`,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && dataset.value.size < this.requirement) _addIssue(this, \"size\", dataset, config$1, { received: `${dataset.value.size}` });\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/minValue/minValue.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction minValue(requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"min_value\",\n\t\treference: minValue,\n\t\tasync: false,\n\t\texpects: `>=${requirement instanceof Date ? requirement.toJSON() : /* @__PURE__ */ _stringify(requirement)}`,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !(dataset.value >= this.requirement)) _addIssue(this, \"value\", dataset, config$1, { received: dataset.value instanceof Date ? dataset.value.toJSON() : /* @__PURE__ */ _stringify(dataset.value) });\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/minWords/minWords.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction minWords(locales, requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"min_words\",\n\t\treference: minWords,\n\t\tasync: false,\n\t\texpects: `>=${requirement}`,\n\t\tlocales,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed) {\n\t\t\t\tconst count = /* @__PURE__ */ _getWordCount(this.locales, dataset.value);\n\t\t\t\tif (count < this.requirement) _addIssue(this, \"words\", dataset, config$1, { received: `${count}` });\n\t\t\t}\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/multipleOf/multipleOf.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction multipleOf(requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"multiple_of\",\n\t\treference: multipleOf,\n\t\tasync: false,\n\t\texpects: `%${requirement}`,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && dataset.value % this.requirement != 0) _addIssue(this, \"multiple\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/nanoid/nanoid.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction nanoid(message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"nanoid\",\n\t\treference: nanoid,\n\t\tasync: false,\n\t\texpects: null,\n\t\trequirement: NANO_ID_REGEX,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement.test(dataset.value)) _addIssue(this, \"Nano ID\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/nonEmpty/nonEmpty.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction nonEmpty(message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"non_empty\",\n\t\treference: nonEmpty,\n\t\tasync: false,\n\t\texpects: \"!0\",\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && dataset.value.length === 0) _addIssue(this, \"length\", dataset, config$1, { received: \"0\" });\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/normalize/normalize.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction normalize(form) {\n\treturn {\n\t\tkind: \"transformation\",\n\t\ttype: \"normalize\",\n\t\treference: normalize,\n\t\tasync: false,\n\t\tform,\n\t\t\"~run\"(dataset) {\n\t\t\tdataset.value = dataset.value.normalize(this.form);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/notBytes/notBytes.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction notBytes(requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"not_bytes\",\n\t\treference: notBytes,\n\t\tasync: false,\n\t\texpects: `!${requirement}`,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed) {\n\t\t\t\tconst length$1 = /* @__PURE__ */ _getByteCount(dataset.value);\n\t\t\t\tif (length$1 === this.requirement) _addIssue(this, \"bytes\", dataset, config$1, { received: `${length$1}` });\n\t\t\t}\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/notEntries/notEntries.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction notEntries(requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"not_entries\",\n\t\treference: notEntries,\n\t\tasync: false,\n\t\texpects: `!${requirement}`,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (!dataset.typed) return dataset;\n\t\t\tconst count = Object.keys(dataset.value).length;\n\t\t\tif (dataset.typed && count === this.requirement) _addIssue(this, \"entries\", dataset, config$1, { received: `${count}` });\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/notGraphemes/notGraphemes.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction notGraphemes(requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"not_graphemes\",\n\t\treference: notGraphemes,\n\t\tasync: false,\n\t\texpects: `!${requirement}`,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed) {\n\t\t\t\tconst count = /* @__PURE__ */ _getGraphemeCount(dataset.value);\n\t\t\t\tif (count === this.requirement) _addIssue(this, \"graphemes\", dataset, config$1, { received: `${count}` });\n\t\t\t}\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/notLength/notLength.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction notLength(requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"not_length\",\n\t\treference: notLength,\n\t\tasync: false,\n\t\texpects: `!${requirement}`,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && dataset.value.length === this.requirement) _addIssue(this, \"length\", dataset, config$1, { received: `${dataset.value.length}` });\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/notSize/notSize.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction notSize(requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"not_size\",\n\t\treference: notSize,\n\t\tasync: false,\n\t\texpects: `!${requirement}`,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && dataset.value.size === this.requirement) _addIssue(this, \"size\", dataset, config$1, { received: `${dataset.value.size}` });\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/notValue/notValue.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction notValue(requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"not_value\",\n\t\treference: notValue,\n\t\tasync: false,\n\t\texpects: requirement instanceof Date ? `!${requirement.toJSON()}` : `!${/* @__PURE__ */ _stringify(requirement)}`,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && this.requirement <= dataset.value && this.requirement >= dataset.value) _addIssue(this, \"value\", dataset, config$1, { received: dataset.value instanceof Date ? dataset.value.toJSON() : /* @__PURE__ */ _stringify(dataset.value) });\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/notValues/notValues.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction notValues(requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"not_values\",\n\t\treference: notValues,\n\t\tasync: false,\n\t\texpects: `!${/* @__PURE__ */ _joinExpects(requirement.map((value$1) => value$1 instanceof Date ? value$1.toJSON() : /* @__PURE__ */ _stringify(value$1)), \"|\")}`,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && this.requirement.some((value$1) => value$1 <= dataset.value && value$1 >= dataset.value)) _addIssue(this, \"value\", dataset, config$1, { received: dataset.value instanceof Date ? dataset.value.toJSON() : /* @__PURE__ */ _stringify(dataset.value) });\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/notWords/notWords.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction notWords(locales, requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"not_words\",\n\t\treference: notWords,\n\t\tasync: false,\n\t\texpects: `!${requirement}`,\n\t\tlocales,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed) {\n\t\t\t\tconst count = /* @__PURE__ */ _getWordCount(this.locales, dataset.value);\n\t\t\t\tif (count === this.requirement) _addIssue(this, \"words\", dataset, config$1, { received: `${count}` });\n\t\t\t}\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/octal/octal.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction octal(message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"octal\",\n\t\treference: octal,\n\t\tasync: false,\n\t\texpects: null,\n\t\trequirement: OCTAL_REGEX,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement.test(dataset.value)) _addIssue(this, \"octal\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/parseBoolean/parseBoolean.ts\nconst TRUTHY = [\n\ttrue,\n\t1,\n\t\"true\",\n\t\"1\",\n\t\"yes\",\n\t\"y\",\n\t\"on\",\n\t\"enabled\"\n];\nconst FALSY = [\n\tfalse,\n\t0,\n\t\"false\",\n\t\"0\",\n\t\"no\",\n\t\"n\",\n\t\"off\",\n\t\"disabled\"\n];\n/* @__NO_SIDE_EFFECTS__ */\nfunction parseBoolean(config$1, message$1) {\n\tconst normalize$1 = (v) => typeof v === \"string\" ? v.toLowerCase() : v;\n\tconst truthyRaw = config$1?.truthy ?? TRUTHY;\n\tconst falsyRaw = config$1?.falsy ?? FALSY;\n\tconst truthy = config$1?.truthy ? config$1.truthy.map(normalize$1) : TRUTHY;\n\tconst falsy = config$1?.falsy ? config$1.falsy.map(normalize$1) : FALSY;\n\treturn {\n\t\tkind: \"transformation\",\n\t\ttype: \"parse_boolean\",\n\t\treference: parseBoolean,\n\t\texpects: /* @__PURE__ */ _joinExpects([...truthyRaw, ...falsyRaw].map(_stringify), \"|\"),\n\t\tconfig: config$1,\n\t\tmessage: message$1,\n\t\tasync: false,\n\t\t\"~run\"(dataset, config$2) {\n\t\t\tconst input = normalize$1(dataset.value);\n\t\t\tif (truthy.includes(input)) dataset.value = true;\n\t\t\telse if (falsy.includes(input)) dataset.value = false;\n\t\t\telse {\n\t\t\t\t_addIssue(this, \"boolean\", dataset, config$2);\n\t\t\t\tdataset.typed = false;\n\t\t\t}\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/parseJson/parseJson.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction parseJson(config$1, message$1) {\n\treturn {\n\t\tkind: \"transformation\",\n\t\ttype: \"parse_json\",\n\t\treference: parseJson,\n\t\tconfig: config$1,\n\t\tmessage: message$1,\n\t\tasync: false,\n\t\t\"~run\"(dataset, config$2) {\n\t\t\ttry {\n\t\t\t\tdataset.value = JSON.parse(dataset.value, this.config?.reviver);\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof Error) {\n\t\t\t\t\t_addIssue(this, \"JSON\", dataset, config$2, { received: `\"${error.message}\"` });\n\t\t\t\t\tdataset.typed = false;\n\t\t\t\t} else throw error;\n\t\t\t}\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/partialCheck/utils/_isPartiallyTyped/_isPartiallyTyped.ts\n/**\n* Checks if a dataset is partially typed.\n*\n* @param dataset The dataset to check.\n* @param paths The paths to check.\n*\n* @returns Whether it is partially typed.\n*\n* @internal\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction _isPartiallyTyped(dataset, paths) {\n\tif (dataset.issues) for (const path of paths) for (const issue of dataset.issues) {\n\t\tlet typed = false;\n\t\tconst bound = Math.min(path.length, issue.path?.length ?? 0);\n\t\tfor (let index = 0; index < bound; index++) if (path[index] !== issue.path[index].key && (path[index] !== \"$\" || issue.path[index].type !== \"array\")) {\n\t\t\ttyped = true;\n\t\t\tbreak;\n\t\t}\n\t\tif (!typed) return false;\n\t}\n\treturn true;\n}\n\n//#endregion\n//#region src/actions/partialCheck/partialCheck.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction partialCheck(paths, requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"partial_check\",\n\t\treference: partialCheck,\n\t\tasync: false,\n\t\texpects: null,\n\t\tpaths,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif ((dataset.typed || /* @__PURE__ */ _isPartiallyTyped(dataset, paths)) && !this.requirement(dataset.value)) _addIssue(this, \"input\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/partialCheck/partialCheckAsync.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction partialCheckAsync(paths, requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"partial_check\",\n\t\treference: partialCheckAsync,\n\t\tasync: true,\n\t\texpects: null,\n\t\tpaths,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\tasync \"~run\"(dataset, config$1) {\n\t\t\tif ((dataset.typed || /* @__PURE__ */ _isPartiallyTyped(dataset, paths)) && !await this.requirement(dataset.value)) _addIssue(this, \"input\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/rawCheck/rawCheck.ts\n/**\n* Creates a raw check validation action.\n*\n* @param action The validation action.\n*\n* @returns A raw check action.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction rawCheck(action) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"raw_check\",\n\t\treference: rawCheck,\n\t\tasync: false,\n\t\texpects: null,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\taction({\n\t\t\t\tdataset,\n\t\t\t\tconfig: config$1,\n\t\t\t\taddIssue: (info) => _addIssue(this, info?.label ?? \"input\", dataset, config$1, info)\n\t\t\t});\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/rawCheck/rawCheckAsync.ts\n/**\n* Creates a raw check validation action.\n*\n* @param action The validation action.\n*\n* @returns A raw check action.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction rawCheckAsync(action) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"raw_check\",\n\t\treference: rawCheckAsync,\n\t\tasync: true,\n\t\texpects: null,\n\t\tasync \"~run\"(dataset, config$1) {\n\t\t\tawait action({\n\t\t\t\tdataset,\n\t\t\t\tconfig: config$1,\n\t\t\t\taddIssue: (info) => _addIssue(this, info?.label ?? \"input\", dataset, config$1, info)\n\t\t\t});\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/rawTransform/rawTransform.ts\n/**\n* Creates a raw transformation action.\n*\n* @param action The transformation action.\n*\n* @returns A raw transform action.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction rawTransform(action) {\n\treturn {\n\t\tkind: \"transformation\",\n\t\ttype: \"raw_transform\",\n\t\treference: rawTransform,\n\t\tasync: false,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tconst output = action({\n\t\t\t\tdataset,\n\t\t\t\tconfig: config$1,\n\t\t\t\taddIssue: (info) => _addIssue(this, info?.label ?? \"input\", dataset, config$1, info),\n\t\t\t\tNEVER: null\n\t\t\t});\n\t\t\tif (dataset.issues) dataset.typed = false;\n\t\t\telse dataset.value = output;\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/rawTransform/rawTransformAsync.ts\n/**\n* Creates a raw transformation action.\n*\n* @param action The transformation action.\n*\n* @returns A raw transform action.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction rawTransformAsync(action) {\n\treturn {\n\t\tkind: \"transformation\",\n\t\ttype: \"raw_transform\",\n\t\treference: rawTransformAsync,\n\t\tasync: true,\n\t\tasync \"~run\"(dataset, config$1) {\n\t\t\tconst output = await action({\n\t\t\t\tdataset,\n\t\t\t\tconfig: config$1,\n\t\t\t\taddIssue: (info) => _addIssue(this, info?.label ?? \"input\", dataset, config$1, info),\n\t\t\t\tNEVER: null\n\t\t\t});\n\t\t\tif (dataset.issues) dataset.typed = false;\n\t\t\telse dataset.value = output;\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/readonly/readonly.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction readonly() {\n\treturn {\n\t\tkind: \"transformation\",\n\t\ttype: \"readonly\",\n\t\treference: readonly,\n\t\tasync: false,\n\t\t\"~run\"(dataset) {\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/reduceItems/reduceItems.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction reduceItems(operation, initial) {\n\treturn {\n\t\tkind: \"transformation\",\n\t\ttype: \"reduce_items\",\n\t\treference: reduceItems,\n\t\tasync: false,\n\t\toperation,\n\t\tinitial,\n\t\t\"~run\"(dataset) {\n\t\t\tdataset.value = dataset.value.reduce(this.operation, this.initial);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/regex/regex.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction regex(requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"regex\",\n\t\treference: regex,\n\t\tasync: false,\n\t\texpects: `${requirement}`,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement.test(dataset.value)) _addIssue(this, \"format\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/returns/returns.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction returns(schema) {\n\treturn {\n\t\tkind: \"transformation\",\n\t\ttype: \"returns\",\n\t\treference: returns,\n\t\tasync: false,\n\t\tschema,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tconst func = dataset.value;\n\t\t\tdataset.value = (...args_) => {\n\t\t\t\tconst returnsDataset = this.schema[\"~run\"]({ value: func(...args_) }, config$1);\n\t\t\t\tif (returnsDataset.issues) throw new ValiError(returnsDataset.issues);\n\t\t\t\treturn returnsDataset.value;\n\t\t\t};\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/returns/returnsAsync.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction returnsAsync(schema) {\n\treturn {\n\t\tkind: \"transformation\",\n\t\ttype: \"returns\",\n\t\treference: returnsAsync,\n\t\tasync: false,\n\t\tschema,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tconst func = dataset.value;\n\t\t\tdataset.value = async (...args_) => {\n\t\t\t\tconst returnsDataset = await this.schema[\"~run\"]({ value: await func(...args_) }, config$1);\n\t\t\t\tif (returnsDataset.issues) throw new ValiError(returnsDataset.issues);\n\t\t\t\treturn returnsDataset.value;\n\t\t\t};\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/rfcEmail/rfcEmail.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction rfcEmail(message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"rfc_email\",\n\t\treference: rfcEmail,\n\t\texpects: null,\n\t\tasync: false,\n\t\trequirement: RFC_EMAIL_REGEX,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement.test(dataset.value)) _addIssue(this, \"email\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/safeInteger/safeInteger.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction safeInteger(message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"safe_integer\",\n\t\treference: safeInteger,\n\t\tasync: false,\n\t\texpects: null,\n\t\trequirement: Number.isSafeInteger,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement(dataset.value)) _addIssue(this, \"safe integer\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/size/size.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction size(requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"size\",\n\t\treference: size,\n\t\tasync: false,\n\t\texpects: `${requirement}`,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && dataset.value.size !== this.requirement) _addIssue(this, \"size\", dataset, config$1, { received: `${dataset.value.size}` });\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/slug/slug.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction slug(message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"slug\",\n\t\treference: slug,\n\t\tasync: false,\n\t\texpects: null,\n\t\trequirement: SLUG_REGEX,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement.test(dataset.value)) _addIssue(this, \"slug\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/someItem/someItem.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction someItem(requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"some_item\",\n\t\treference: someItem,\n\t\tasync: false,\n\t\texpects: null,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !dataset.value.some(this.requirement)) _addIssue(this, \"item\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/sortItems/sortItems.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction sortItems(operation) {\n\treturn {\n\t\tkind: \"transformation\",\n\t\ttype: \"sort_items\",\n\t\treference: sortItems,\n\t\tasync: false,\n\t\toperation,\n\t\t\"~run\"(dataset) {\n\t\t\tdataset.value = dataset.value.sort(this.operation);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/startsWith/startsWith.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction startsWith(requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"starts_with\",\n\t\treference: startsWith,\n\t\tasync: false,\n\t\texpects: `\"${requirement}\"`,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !dataset.value.startsWith(this.requirement)) _addIssue(this, \"start\", dataset, config$1, { received: `\"${dataset.value.slice(0, this.requirement.length)}\"` });\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/stringifyJson/stringifyJson.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction stringifyJson(config$1, message$1) {\n\treturn {\n\t\tkind: \"transformation\",\n\t\ttype: \"stringify_json\",\n\t\treference: stringifyJson,\n\t\tmessage: message$1,\n\t\tconfig: config$1,\n\t\tasync: false,\n\t\t\"~run\"(dataset, config$2) {\n\t\t\ttry {\n\t\t\t\tconst output = JSON.stringify(dataset.value, this.config?.replacer, this.config?.space);\n\t\t\t\tif (output === void 0) {\n\t\t\t\t\t_addIssue(this, \"JSON\", dataset, config$2);\n\t\t\t\t\tdataset.typed = false;\n\t\t\t\t}\n\t\t\t\tdataset.value = output;\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof Error) {\n\t\t\t\t\t_addIssue(this, \"JSON\", dataset, config$2, { received: `\"${error.message}\"` });\n\t\t\t\t\tdataset.typed = false;\n\t\t\t\t} else throw error;\n\t\t\t}\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/title/title.ts\n/**\n* Creates a title metadata action.\n*\n* @param title_ The title text.\n*\n* @returns A title action.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction title(title_) {\n\treturn {\n\t\tkind: \"metadata\",\n\t\ttype: \"title\",\n\t\treference: title,\n\t\ttitle: title_\n\t};\n}\n\n//#endregion\n//#region src/actions/toBigint/toBigint.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction toBigint(message$1) {\n\treturn {\n\t\tkind: \"transformation\",\n\t\ttype: \"to_bigint\",\n\t\treference: toBigint,\n\t\tasync: false,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\ttry {\n\t\t\t\tdataset.value = BigInt(dataset.value);\n\t\t\t} catch {\n\t\t\t\t_addIssue(this, \"bigint\", dataset, config$1);\n\t\t\t\tdataset.typed = false;\n\t\t\t}\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/toBoolean/toBoolean.ts\n/**\n* Creates a to boolean transformation action.\n*\n* @returns A to boolean action.\n*\n* @beta\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction toBoolean() {\n\treturn {\n\t\tkind: \"transformation\",\n\t\ttype: \"to_boolean\",\n\t\treference: toBoolean,\n\t\tasync: false,\n\t\t\"~run\"(dataset) {\n\t\t\tdataset.value = Boolean(dataset.value);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/toCamelCase/toCamelCase.ts\n/**\n* Creates a to camel case transformation action.\n*\n* Words are separated by `_`, `-` and ASCII whitespace, as well as by case\n* and acronym boundaries.\n*\n* Hint: Acronym runs are normalized to lowercase (e.g. `parseURLValue` →\n* `parseUrlValue`) and digits stay attached to the preceding token (e.g.\n* `item2Name` → `item2Name`).\n*\n* @returns A to camel case action.\n*\n* @beta\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction toCamelCase() {\n\treturn {\n\t\tkind: \"transformation\",\n\t\ttype: \"to_camel_case\",\n\t\treference: toCamelCase,\n\t\tasync: false,\n\t\t\"~run\"(dataset) {\n\t\t\tdataset.value = /* @__PURE__ */ _formatCase(dataset.value, \"\", false, true);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/toDate/toDate.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction toDate(message$1) {\n\treturn {\n\t\tkind: \"transformation\",\n\t\ttype: \"to_date\",\n\t\treference: toDate,\n\t\tasync: false,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\ttry {\n\t\t\t\tdataset.value = new Date(dataset.value);\n\t\t\t\tif (isNaN(dataset.value)) {\n\t\t\t\t\t_addIssue(this, \"date\", dataset, config$1, { received: \"\\\"Invalid Date\\\"\" });\n\t\t\t\t\tdataset.typed = false;\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t_addIssue(this, \"date\", dataset, config$1);\n\t\t\t\tdataset.typed = false;\n\t\t\t}\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/toKebabCase/toKebabCase.ts\n/**\n* Creates a to kebab case transformation action.\n*\n* Words are separated by `_`, `-` and ASCII whitespace, as well as by case\n* and acronym boundaries.\n*\n* Hint: Acronym runs are normalized to lowercase (e.g. `parseURLValue` →\n* `parse-url-value`) and digits stay attached to the preceding token (e.g.\n* `item2Name` → `item2-name`).\n*\n* @returns A to kebab case action.\n*\n* @beta\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction toKebabCase() {\n\treturn {\n\t\tkind: \"transformation\",\n\t\ttype: \"to_kebab_case\",\n\t\treference: toKebabCase,\n\t\tasync: false,\n\t\t\"~run\"(dataset) {\n\t\t\tdataset.value = /* @__PURE__ */ _formatCase(dataset.value, \"-\", false, false);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/toLowerCase/toLowerCase.ts\n/**\n* Creates a to lower case transformation action.\n*\n* @returns A to lower case action.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction toLowerCase() {\n\treturn {\n\t\tkind: \"transformation\",\n\t\ttype: \"to_lower_case\",\n\t\treference: toLowerCase,\n\t\tasync: false,\n\t\t\"~run\"(dataset) {\n\t\t\tdataset.value = dataset.value.toLowerCase();\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/toMaxValue/toMaxValue.ts\n/**\n* Creates a to max value transformation action.\n*\n* @param requirement The maximum value.\n*\n* @returns A to max value action.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction toMaxValue(requirement) {\n\treturn {\n\t\tkind: \"transformation\",\n\t\ttype: \"to_max_value\",\n\t\treference: toMaxValue,\n\t\tasync: false,\n\t\trequirement,\n\t\t\"~run\"(dataset) {\n\t\t\tdataset.value = dataset.value > this.requirement ? this.requirement : dataset.value;\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/toMinValue/toMinValue.ts\n/**\n* Creates a to min value transformation action.\n*\n* @param requirement The minimum value.\n*\n* @returns A to min value action.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction toMinValue(requirement) {\n\treturn {\n\t\tkind: \"transformation\",\n\t\ttype: \"to_min_value\",\n\t\treference: toMinValue,\n\t\tasync: false,\n\t\trequirement,\n\t\t\"~run\"(dataset) {\n\t\t\tdataset.value = dataset.value < this.requirement ? this.requirement : dataset.value;\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/toNumber/toNumber.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction toNumber(message$1) {\n\treturn {\n\t\tkind: \"transformation\",\n\t\ttype: \"to_number\",\n\t\treference: toNumber,\n\t\tasync: false,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\ttry {\n\t\t\t\tdataset.value = Number(dataset.value);\n\t\t\t\tif (isNaN(dataset.value)) {\n\t\t\t\t\t_addIssue(this, \"number\", dataset, config$1);\n\t\t\t\t\tdataset.typed = false;\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t_addIssue(this, \"number\", dataset, config$1);\n\t\t\t\tdataset.typed = false;\n\t\t\t}\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/toPascalCase/toPascalCase.ts\n/**\n* Creates a to pascal case transformation action.\n*\n* Words are separated by `_`, `-` and ASCII whitespace, as well as by case\n* and acronym boundaries.\n*\n* Hint: Acronym runs are normalized to lowercase (e.g. `parseURLValue` →\n* `ParseUrlValue`) and digits stay attached to the preceding token (e.g.\n* `item2Name` → `Item2Name`).\n*\n* @returns A to pascal case action.\n*\n* @beta\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction toPascalCase() {\n\treturn {\n\t\tkind: \"transformation\",\n\t\ttype: \"to_pascal_case\",\n\t\treference: toPascalCase,\n\t\tasync: false,\n\t\t\"~run\"(dataset) {\n\t\t\tdataset.value = /* @__PURE__ */ _formatCase(dataset.value, \"\", true, true);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/toSnakeCase/toSnakeCase.ts\n/**\n* Creates a to snake case transformation action.\n*\n* Words are separated by `_`, `-` and ASCII whitespace, as well as by case\n* and acronym boundaries.\n*\n* Hint: Acronym runs are normalized to lowercase (e.g. `parseURLValue` →\n* `parse_url_value`) and digits stay attached to the preceding token (e.g.\n* `item2Name` → `item2_name`).\n*\n* @returns A to snake case action.\n*\n* @beta\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction toSnakeCase() {\n\treturn {\n\t\tkind: \"transformation\",\n\t\ttype: \"to_snake_case\",\n\t\treference: toSnakeCase,\n\t\tasync: false,\n\t\t\"~run\"(dataset) {\n\t\t\tdataset.value = /* @__PURE__ */ _formatCase(dataset.value, \"_\", false, false);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/toString/toString.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction toString(message$1) {\n\treturn {\n\t\tkind: \"transformation\",\n\t\ttype: \"to_string\",\n\t\treference: toString,\n\t\tasync: false,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\ttry {\n\t\t\t\tdataset.value = String(dataset.value);\n\t\t\t} catch {\n\t\t\t\t_addIssue(this, \"string\", dataset, config$1);\n\t\t\t\tdataset.typed = false;\n\t\t\t}\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/toUpperCase/toUpperCase.ts\n/**\n* Creates a to upper case transformation action.\n*\n* @returns A to upper case action.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction toUpperCase() {\n\treturn {\n\t\tkind: \"transformation\",\n\t\ttype: \"to_upper_case\",\n\t\treference: toUpperCase,\n\t\tasync: false,\n\t\t\"~run\"(dataset) {\n\t\t\tdataset.value = dataset.value.toUpperCase();\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/transform/transform.ts\n/**\n* Creates a custom transformation action.\n*\n* @param operation The transformation operation.\n*\n* @returns A transform action.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction transform(operation) {\n\treturn {\n\t\tkind: \"transformation\",\n\t\ttype: \"transform\",\n\t\treference: transform,\n\t\tasync: false,\n\t\toperation,\n\t\t\"~run\"(dataset) {\n\t\t\tdataset.value = this.operation(dataset.value);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/transform/transformAsync.ts\n/**\n* Creates a custom transformation action.\n*\n* @param operation The transformation operation.\n*\n* @returns A transform action.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction transformAsync(operation) {\n\treturn {\n\t\tkind: \"transformation\",\n\t\ttype: \"transform\",\n\t\treference: transformAsync,\n\t\tasync: true,\n\t\toperation,\n\t\tasync \"~run\"(dataset) {\n\t\t\tdataset.value = await this.operation(dataset.value);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/trim/trim.ts\n/**\n* Creates a trim transformation action.\n*\n* @returns A trim action.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction trim() {\n\treturn {\n\t\tkind: \"transformation\",\n\t\ttype: \"trim\",\n\t\treference: trim,\n\t\tasync: false,\n\t\t\"~run\"(dataset) {\n\t\t\tdataset.value = dataset.value.trim();\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/trimEnd/trimEnd.ts\n/**\n* Creates a trim end transformation action.\n*\n* @returns A trim end action.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction trimEnd() {\n\treturn {\n\t\tkind: \"transformation\",\n\t\ttype: \"trim_end\",\n\t\treference: trimEnd,\n\t\tasync: false,\n\t\t\"~run\"(dataset) {\n\t\t\tdataset.value = dataset.value.trimEnd();\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/trimStart/trimStart.ts\n/**\n* Creates a trim start transformation action.\n*\n* @returns A trim start action.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction trimStart() {\n\treturn {\n\t\tkind: \"transformation\",\n\t\ttype: \"trim_start\",\n\t\treference: trimStart,\n\t\tasync: false,\n\t\t\"~run\"(dataset) {\n\t\t\tdataset.value = dataset.value.trimStart();\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/ulid/ulid.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction ulid(message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"ulid\",\n\t\treference: ulid,\n\t\tasync: false,\n\t\texpects: null,\n\t\trequirement: ULID_REGEX,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement.test(dataset.value)) _addIssue(this, \"ULID\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/url/url.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction url(message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"url\",\n\t\treference: url,\n\t\tasync: false,\n\t\texpects: null,\n\t\trequirement(input) {\n\t\t\ttry {\n\t\t\t\tnew URL(input);\n\t\t\t\treturn true;\n\t\t\t} catch {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t},\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement(dataset.value)) _addIssue(this, \"URL\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/uuid/uuid.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction uuid(message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"uuid\",\n\t\treference: uuid,\n\t\tasync: false,\n\t\texpects: null,\n\t\trequirement: UUID_REGEX,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement.test(dataset.value)) _addIssue(this, \"UUID\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/value/value.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction value(requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"value\",\n\t\treference: value,\n\t\tasync: false,\n\t\texpects: requirement instanceof Date ? requirement.toJSON() : /* @__PURE__ */ _stringify(requirement),\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !(this.requirement <= dataset.value && this.requirement >= dataset.value)) _addIssue(this, \"value\", dataset, config$1, { received: dataset.value instanceof Date ? dataset.value.toJSON() : /* @__PURE__ */ _stringify(dataset.value) });\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/values/values.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction values(requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"values\",\n\t\treference: values,\n\t\tasync: false,\n\t\texpects: `${/* @__PURE__ */ _joinExpects(requirement.map((value$1) => value$1 instanceof Date ? value$1.toJSON() : /* @__PURE__ */ _stringify(value$1)), \"|\")}`,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed && !this.requirement.some((value$1) => value$1 <= dataset.value && value$1 >= dataset.value)) _addIssue(this, \"value\", dataset, config$1, { received: dataset.value instanceof Date ? dataset.value.toJSON() : /* @__PURE__ */ _stringify(dataset.value) });\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/actions/words/words.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction words(locales, requirement, message$1) {\n\treturn {\n\t\tkind: \"validation\",\n\t\ttype: \"words\",\n\t\treference: words,\n\t\tasync: false,\n\t\texpects: `${requirement}`,\n\t\tlocales,\n\t\trequirement,\n\t\tmessage: message$1,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.typed) {\n\t\t\t\tconst count = /* @__PURE__ */ _getWordCount(this.locales, dataset.value);\n\t\t\t\tif (count !== this.requirement) _addIssue(this, \"words\", dataset, config$1, { received: `${count}` });\n\t\t\t}\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/const.ts\nconst ABORT_EARLY_CONFIG = { abortEarly: true };\n\n//#endregion\n//#region src/methods/assert/assert.ts\n/**\n* Checks if the input matches the schema. As this is an assertion function, it\n* can be used as a type guard.\n*\n* @param schema The schema to be used.\n* @param input The input to be tested.\n*/\nfunction assert(schema, input) {\n\tconst issues = schema[\"~run\"]({ value: input }, ABORT_EARLY_CONFIG).issues;\n\tif (issues) throw new ValiError(issues);\n}\n\n//#endregion\n//#region src/methods/cache/_LruCache.ts\n/**\n* Efficient LRU cache using Map iteration order.\n*/\nvar _LruCache = class {\n\tconstructor(config$1) {\n\t\tthis.refCount = 0;\n\t\tthis.maxSize = config$1?.maxSize ?? 1e3;\n\t\tthis.maxAge = config$1?.maxAge ?? Infinity;\n\t\tthis.hasMaxAge = isFinite(this.maxAge);\n\t}\n\t/**\n\t* Stringifies an unknown input to a cache key component.\n\t*\n\t* @param input The unknown input.\n\t*\n\t* @returns A cache key component.\n\t*/\n\tstringify(input) {\n\t\tconst type = typeof input;\n\t\tif (type === \"string\") return `\"${input}\"`;\n\t\tif (type === \"number\" || type === \"boolean\") return `${input}`;\n\t\tif (type === \"bigint\") return `${input}n`;\n\t\tif (type === \"object\" || type === \"function\") {\n\t\t\tif (input) {\n\t\t\t\tthis.refIds ?? (this.refIds = /* @__PURE__ */ new WeakMap());\n\t\t\t\tlet id = this.refIds.get(input);\n\t\t\t\tif (!id) {\n\t\t\t\t\tid = ++this.refCount;\n\t\t\t\t\tthis.refIds.set(input, id);\n\t\t\t\t}\n\t\t\t\treturn `#${id}`;\n\t\t\t}\n\t\t\treturn \"null\";\n\t\t}\n\t\treturn type;\n\t}\n\t/**\n\t* Creates a cache key from input and config.\n\t*\n\t* @param input The input value.\n\t* @param config The parse configuration.\n\t*\n\t* @returns The cache key.\n\t*/\n\tkey(input, config$1 = {}) {\n\t\treturn `${this.stringify(input)}|${this.stringify(config$1.lang)}|${this.stringify(config$1.message)}|${this.stringify(config$1.abortEarly)}|${this.stringify(config$1.abortPipeEarly)}`;\n\t}\n\t/**\n\t* Gets a value from the cache by key.\n\t*\n\t* @param key The cache key.\n\t*\n\t* @returns The cached value.\n\t*/\n\tget(key) {\n\t\tif (!this.store) return void 0;\n\t\tconst entry = this.store.get(key);\n\t\tif (!entry) return void 0;\n\t\tif (this.hasMaxAge && Date.now() - entry[1] > this.maxAge) {\n\t\t\tthis.store.delete(key);\n\t\t\treturn;\n\t\t}\n\t\tthis.store.delete(key);\n\t\tthis.store.set(key, entry);\n\t\treturn entry[0];\n\t}\n\t/**\n\t* Sets a value in the cache by key.\n\t*\n\t* @param key The cache key.\n\t* @param value The cached value.\n\t*/\n\tset(key, value$1) {\n\t\tthis.store ?? (this.store = /* @__PURE__ */ new Map());\n\t\tthis.store.delete(key);\n\t\tconst timestamp = this.hasMaxAge ? Date.now() : 0;\n\t\tthis.store.set(key, [value$1, timestamp]);\n\t\tif (this.store.size > this.maxSize) this.store.delete(this.store.keys().next().value);\n\t}\n\t/**\n\t* Clears all entries from the cache.\n\t*/\n\tclear() {\n\t\tthis.store?.clear();\n\t}\n};\n\n//#endregion\n//#region src/methods/cache/cache.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction cache(schema, config$1) {\n\treturn {\n\t\t...schema,\n\t\tcacheConfig: config$1,\n\t\tcache: new _LruCache(config$1),\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, runConfig) {\n\t\t\tconst key = this.cache.key(dataset.value, runConfig);\n\t\t\tlet outputDataset = this.cache.get(key);\n\t\t\tif (!outputDataset) this.cache.set(key, outputDataset = schema[\"~run\"](dataset, runConfig));\n\t\t\treturn /* @__PURE__ */ _cloneDataset(outputDataset);\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/methods/cache/cacheAsync.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction cacheAsync(schema, config$1) {\n\tlet activeRuns;\n\treturn {\n\t\t...schema,\n\t\tasync: true,\n\t\tcacheConfig: config$1,\n\t\tcache: new _LruCache(config$1),\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\tasync \"~run\"(dataset, runConfig) {\n\t\t\tconst key = this.cache.key(dataset.value, runConfig);\n\t\t\tconst cached = this.cache.get(key);\n\t\t\tif (cached) return /* @__PURE__ */ _cloneDataset(cached);\n\t\t\tlet promise$1 = activeRuns?.get(key);\n\t\t\tif (!promise$1) {\n\t\t\t\tactiveRuns ?? (activeRuns = /* @__PURE__ */ new Map());\n\t\t\t\tpromise$1 = Promise.resolve(schema[\"~run\"](dataset, runConfig));\n\t\t\t\tactiveRuns.set(key, promise$1);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst outputDataset = await promise$1;\n\t\t\t\tthis.cache.set(key, outputDataset);\n\t\t\t\treturn /* @__PURE__ */ _cloneDataset(outputDataset);\n\t\t\t} finally {\n\t\t\t\tactiveRuns?.delete(key);\n\t\t\t}\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/methods/config/config.ts\n/**\n* Changes the local configuration of a schema.\n*\n* @param schema The schema to configure.\n* @param config The parse configuration.\n*\n* @returns The configured schema.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction config(schema, config$1) {\n\treturn {\n\t\t...schema,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config_) {\n\t\t\treturn schema[\"~run\"](dataset, {\n\t\t\t\t...config_,\n\t\t\t\t...config$1\n\t\t\t});\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/methods/getFallback/getFallback.ts\n/**\n* Returns the fallback value of the schema.\n*\n* @param schema The schema to get it from.\n* @param dataset The output dataset if available.\n* @param config The config if available.\n*\n* @returns The fallback value.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction getFallback(schema, dataset, config$1) {\n\treturn typeof schema.fallback === \"function\" ? schema.fallback(dataset, config$1) : schema.fallback;\n}\n\n//#endregion\n//#region src/methods/fallback/fallback.ts\n/**\n* Returns a fallback value as output if the input does not match the schema.\n*\n* @param schema The schema to catch.\n* @param fallback The fallback value.\n*\n* @returns The passed schema.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction fallback(schema, fallback$1) {\n\treturn {\n\t\t...schema,\n\t\tfallback: fallback$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tconst outputDataset = schema[\"~run\"](dataset, config$1);\n\t\t\treturn outputDataset.issues ? {\n\t\t\t\ttyped: true,\n\t\t\t\tvalue: /* @__PURE__ */ getFallback(this, outputDataset, config$1)\n\t\t\t} : outputDataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/methods/fallback/fallbackAsync.ts\n/**\n* Returns a fallback value as output if the input does not match the schema.\n*\n* @param schema The schema to catch.\n* @param fallback The fallback value.\n*\n* @returns The passed schema.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction fallbackAsync(schema, fallback$1) {\n\treturn {\n\t\t...schema,\n\t\tfallback: fallback$1,\n\t\tasync: true,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\tasync \"~run\"(dataset, config$1) {\n\t\t\tconst outputDataset = await schema[\"~run\"](dataset, config$1);\n\t\t\treturn outputDataset.issues ? {\n\t\t\t\ttyped: true,\n\t\t\t\tvalue: await /* @__PURE__ */ getFallback(this, outputDataset, config$1)\n\t\t\t} : outputDataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/methods/flatten/flatten.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction flatten(issues) {\n\tconst flatErrors = {};\n\tfor (const issue of issues) if (issue.path) {\n\t\tconst dotPath = /* @__PURE__ */ getDotPath(issue);\n\t\tif (dotPath) {\n\t\t\tif (!flatErrors.nested) flatErrors.nested = {};\n\t\t\tif (Object.prototype.hasOwnProperty.call(flatErrors.nested, dotPath)) flatErrors.nested[dotPath].push(issue.message);\n\t\t\telse flatErrors.nested[dotPath] = [issue.message];\n\t\t} else if (flatErrors.other) flatErrors.other.push(issue.message);\n\t\telse flatErrors.other = [issue.message];\n\t} else if (flatErrors.root) flatErrors.root.push(issue.message);\n\telse flatErrors.root = [issue.message];\n\treturn flatErrors;\n}\n\n//#endregion\n//#region src/methods/forward/forward.ts\n/**\n* Forwards the issues of the passed validation action.\n*\n* @param action The validation action.\n* @param path The path to forward the issues to.\n*\n* @returns The modified action.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction forward(action, path) {\n\treturn {\n\t\t...action,\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tconst prevIssues = dataset.issues && [...dataset.issues];\n\t\t\tdataset = action[\"~run\"](dataset, config$1);\n\t\t\tif (dataset.issues) {\n\t\t\t\tfor (const issue of dataset.issues) if (!prevIssues?.includes(issue)) {\n\t\t\t\t\tlet pathInput = dataset.value;\n\t\t\t\t\tfor (const key of path) {\n\t\t\t\t\t\tconst pathValue = pathInput[key];\n\t\t\t\t\t\tconst pathItem = {\n\t\t\t\t\t\t\ttype: \"unknown\",\n\t\t\t\t\t\t\torigin: \"value\",\n\t\t\t\t\t\t\tinput: pathInput,\n\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\tvalue: pathValue\n\t\t\t\t\t\t};\n\t\t\t\t\t\tif (issue.path) issue.path.push(pathItem);\n\t\t\t\t\t\telse issue.path = [pathItem];\n\t\t\t\t\t\tif (!pathValue) break;\n\t\t\t\t\t\tpathInput = pathValue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/methods/forward/forwardAsync.ts\n/**\n* Forwards the issues of the passed validation action.\n*\n* @param action The validation action.\n* @param path The path to forward the issues to.\n*\n* @returns The modified action.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction forwardAsync(action, path) {\n\treturn {\n\t\t...action,\n\t\tasync: true,\n\t\tasync \"~run\"(dataset, config$1) {\n\t\t\tconst prevIssues = dataset.issues && [...dataset.issues];\n\t\t\tdataset = await action[\"~run\"](dataset, config$1);\n\t\t\tif (dataset.issues) {\n\t\t\t\tfor (const issue of dataset.issues) if (!prevIssues?.includes(issue)) {\n\t\t\t\t\tlet pathInput = dataset.value;\n\t\t\t\t\tfor (const key of path) {\n\t\t\t\t\t\tconst pathValue = pathInput[key];\n\t\t\t\t\t\tconst pathItem = {\n\t\t\t\t\t\t\ttype: \"unknown\",\n\t\t\t\t\t\t\torigin: \"value\",\n\t\t\t\t\t\t\tinput: pathInput,\n\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\tvalue: pathValue\n\t\t\t\t\t\t};\n\t\t\t\t\t\tif (issue.path) issue.path.push(pathItem);\n\t\t\t\t\t\telse issue.path = [pathItem];\n\t\t\t\t\t\tif (!pathValue) break;\n\t\t\t\t\t\tpathInput = pathValue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/methods/getDefault/getDefault.ts\n/**\n* Returns the default value of the schema.\n*\n* @param schema The schema to get it from.\n* @param dataset The input dataset if available.\n* @param config The config if available.\n*\n* @returns The default value.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction getDefault(schema, dataset, config$1) {\n\treturn typeof schema.default === \"function\" ? schema.default(dataset, config$1) : schema.default;\n}\n\n//#endregion\n//#region src/methods/getDefaults/getDefaults.ts\n/**\n* Returns the default values of the schema.\n*\n* Hint: The difference to `getDefault` is that for object and tuple schemas\n* this function recursively returns the default values of the subschemas\n* instead of `undefined`.\n*\n* @param schema The schema to get them from.\n*\n* @returns The default values.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction getDefaults(schema) {\n\tif (\"entries\" in schema) {\n\t\tconst object$1 = {};\n\t\tfor (const key in schema.entries) object$1[key] = /* @__PURE__ */ getDefaults(schema.entries[key]);\n\t\treturn object$1;\n\t}\n\tif (\"items\" in schema) return schema.items.map(getDefaults);\n\treturn /* @__PURE__ */ getDefault(schema);\n}\n\n//#endregion\n//#region src/methods/getDefaults/getDefaultsAsync.ts\n/**\n* Returns the default values of the schema.\n*\n* Hint: The difference to `getDefault` is that for object and tuple schemas\n* this function recursively returns the default values of the subschemas\n* instead of `undefined`.\n*\n* @param schema The schema to get them from.\n*\n* @returns The default values.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nasync function getDefaultsAsync(schema) {\n\tif (\"entries\" in schema) return Object.fromEntries(await Promise.all(Object.entries(schema.entries).map(async ([key, value$1]) => [key, await /* @__PURE__ */ getDefaultsAsync(value$1)])));\n\tif (\"items\" in schema) return Promise.all(schema.items.map(getDefaultsAsync));\n\treturn /* @__PURE__ */ getDefault(schema);\n}\n\n//#endregion\n//#region src/methods/getDescription/getDescription.ts\n/**\n* Returns the description of the schema.\n*\n* If multiple descriptions are defined, the last one of the highest level is\n* returned. If no description is defined, `undefined` is returned.\n*\n* @param schema The schema to get the description from.\n*\n* @returns The description, if any.\n*\n* @beta\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction getDescription(schema) {\n\treturn /* @__PURE__ */ _getLastMetadata(schema, \"description\");\n}\n\n//#endregion\n//#region src/methods/getExamples/getExamples.ts\n/**\n* Returns the examples of a schema.\n*\n* If multiple examples are defined, it concatenates them using depth-first\n* search. If no examples are defined, an empty array is returned.\n*\n* @param schema The schema to get the examples from.\n*\n* @returns The examples, if any.\n*\n* @beta\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction getExamples(schema) {\n\tconst examples$1 = [];\n\tfunction depthFirstCollect(schema$1) {\n\t\tif (\"pipe\" in schema$1) {\n\t\t\tfor (const item of schema$1.pipe) if (item.kind === \"schema\" && \"pipe\" in item) depthFirstCollect(item);\n\t\t\telse if (item.kind === \"metadata\" && item.type === \"examples\") for (const example of item.examples) examples$1.push(example);\n\t\t}\n\t}\n\tdepthFirstCollect(schema);\n\treturn examples$1;\n}\n\n//#endregion\n//#region src/methods/getFallbacks/getFallbacks.ts\n/**\n* Returns the fallback values of the schema.\n*\n* Hint: The difference to `getFallback` is that for object and tuple schemas\n* this function recursively returns the fallback values of the subschemas\n* instead of `undefined`.\n*\n* @param schema The schema to get them from.\n*\n* @returns The fallback values.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction getFallbacks(schema) {\n\tif (\"entries\" in schema) {\n\t\tconst object$1 = {};\n\t\tfor (const key in schema.entries) object$1[key] = /* @__PURE__ */ getFallbacks(schema.entries[key]);\n\t\treturn object$1;\n\t}\n\tif (\"items\" in schema) return schema.items.map(getFallbacks);\n\treturn /* @__PURE__ */ getFallback(schema);\n}\n\n//#endregion\n//#region src/methods/getFallbacks/getFallbacksAsync.ts\n/**\n* Returns the fallback values of the schema.\n*\n* Hint: The difference to `getFallback` is that for object and tuple schemas\n* this function recursively returns the fallback values of the subschemas\n* instead of `undefined`.\n*\n* @param schema The schema to get them from.\n*\n* @returns The fallback values.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nasync function getFallbacksAsync(schema) {\n\tif (\"entries\" in schema) return Object.fromEntries(await Promise.all(Object.entries(schema.entries).map(async ([key, value$1]) => [key, await /* @__PURE__ */ getFallbacksAsync(value$1)])));\n\tif (\"items\" in schema) return Promise.all(schema.items.map(getFallbacksAsync));\n\treturn /* @__PURE__ */ getFallback(schema);\n}\n\n//#endregion\n//#region src/methods/getMetadata/getMetadata.ts\n/**\n* Returns the metadata of a schema.\n*\n* If multiple metadata are defined, it shallowly merges them using depth-first\n* search. If no metadata is defined, an empty object is returned.\n*\n* @param schema Schema to get the metadata from.\n*\n* @returns The metadata, if any.\n*\n* @beta\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction getMetadata(schema) {\n\tconst result = {};\n\tfunction depthFirstMerge(schema$1) {\n\t\tif (\"pipe\" in schema$1) {\n\t\t\tfor (const item of schema$1.pipe) if (item.kind === \"schema\" && \"pipe\" in item) depthFirstMerge(item);\n\t\t\telse if (item.kind === \"metadata\" && item.type === \"metadata\") Object.assign(result, item.metadata);\n\t\t}\n\t}\n\tdepthFirstMerge(schema);\n\treturn result;\n}\n\n//#endregion\n//#region src/methods/getTitle/getTitle.ts\n/**\n* Returns the title of the schema.\n*\n* If multiple titles are defined, the last one of the highest level is\n* returned. If no title is defined, `undefined` is returned.\n*\n* @param schema The schema to get the title from.\n*\n* @returns The title, if any.\n*\n* @beta\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction getTitle(schema) {\n\treturn /* @__PURE__ */ _getLastMetadata(schema, \"title\");\n}\n\n//#endregion\n//#region src/methods/is/is.ts\n/**\n* Checks if the input matches the schema. By using a type predicate, this\n* function can be used as a type guard.\n*\n* @param schema The schema to be used.\n* @param input The input to be tested.\n*\n* @returns Whether the input matches the schema.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction is(schema, input) {\n\treturn !schema[\"~run\"]({ value: input }, ABORT_EARLY_CONFIG).issues;\n}\n\n//#endregion\n//#region src/schemas/any/any.ts\n/**\n* Creates an any schema.\n*\n* Hint: This schema function exists only for completeness and is not\n* recommended in practice. Instead, `unknown` should be used to accept\n* unknown data.\n*\n* @returns An any schema.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction any() {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"any\",\n\t\treference: any,\n\t\texpects: \"any\",\n\t\tasync: false,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset) {\n\t\t\tdataset.typed = true;\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/array/array.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction array(item, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"array\",\n\t\treference: array,\n\t\texpects: \"Array\",\n\t\tasync: false,\n\t\titem,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tconst input = dataset.value;\n\t\t\tif (Array.isArray(input)) {\n\t\t\t\tdataset.typed = true;\n\t\t\t\tdataset.value = [];\n\t\t\t\tfor (let key = 0; key < input.length; key++) {\n\t\t\t\t\tconst value$1 = input[key];\n\t\t\t\t\tconst itemDataset = this.item[\"~run\"]({ value: value$1 }, config$1);\n\t\t\t\t\tif (itemDataset.issues) {\n\t\t\t\t\t\tconst pathItem = {\n\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\torigin: \"value\",\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\tvalue: value$1\n\t\t\t\t\t\t};\n\t\t\t\t\t\tfor (const issue of itemDataset.issues) {\n\t\t\t\t\t\t\tif (issue.path) issue.path.unshift(pathItem);\n\t\t\t\t\t\t\telse issue.path = [pathItem];\n\t\t\t\t\t\t\tdataset.issues?.push(issue);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!dataset.issues) dataset.issues = itemDataset.issues;\n\t\t\t\t\t\tif (config$1.abortEarly) {\n\t\t\t\t\t\t\tdataset.typed = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!itemDataset.typed) dataset.typed = false;\n\t\t\t\t\tdataset.value.push(itemDataset.value);\n\t\t\t\t}\n\t\t\t} else _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/array/arrayAsync.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction arrayAsync(item, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"array\",\n\t\treference: arrayAsync,\n\t\texpects: \"Array\",\n\t\tasync: true,\n\t\titem,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\tasync \"~run\"(dataset, config$1) {\n\t\t\tconst input = dataset.value;\n\t\t\tif (Array.isArray(input)) {\n\t\t\t\tdataset.typed = true;\n\t\t\t\tdataset.value = [];\n\t\t\t\tconst itemDatasets = await Promise.all(input.map((value$1) => this.item[\"~run\"]({ value: value$1 }, config$1)));\n\t\t\t\tfor (let key = 0; key < itemDatasets.length; key++) {\n\t\t\t\t\tconst itemDataset = itemDatasets[key];\n\t\t\t\t\tif (itemDataset.issues) {\n\t\t\t\t\t\tconst pathItem = {\n\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\torigin: \"value\",\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\tvalue: input[key]\n\t\t\t\t\t\t};\n\t\t\t\t\t\tfor (const issue of itemDataset.issues) {\n\t\t\t\t\t\t\tif (issue.path) issue.path.unshift(pathItem);\n\t\t\t\t\t\t\telse issue.path = [pathItem];\n\t\t\t\t\t\t\tdataset.issues?.push(issue);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!dataset.issues) dataset.issues = itemDataset.issues;\n\t\t\t\t\t\tif (config$1.abortEarly) {\n\t\t\t\t\t\t\tdataset.typed = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!itemDataset.typed) dataset.typed = false;\n\t\t\t\t\tdataset.value.push(itemDataset.value);\n\t\t\t\t}\n\t\t\t} else _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/bigint/bigint.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction bigint(message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"bigint\",\n\t\treference: bigint,\n\t\texpects: \"bigint\",\n\t\tasync: false,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (typeof dataset.value === \"bigint\") dataset.typed = true;\n\t\t\telse _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/blob/blob.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction blob(message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"blob\",\n\t\treference: blob,\n\t\texpects: \"Blob\",\n\t\tasync: false,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.value instanceof Blob) dataset.typed = true;\n\t\t\telse _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/boolean/boolean.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction boolean(message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"boolean\",\n\t\treference: boolean,\n\t\texpects: \"boolean\",\n\t\tasync: false,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (typeof dataset.value === \"boolean\") dataset.typed = true;\n\t\t\telse _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/custom/custom.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction custom(check$1, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"custom\",\n\t\treference: custom,\n\t\texpects: \"unknown\",\n\t\tasync: false,\n\t\tcheck: check$1,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (this.check(dataset.value)) dataset.typed = true;\n\t\t\telse _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/custom/customAsync.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction customAsync(check$1, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"custom\",\n\t\treference: customAsync,\n\t\texpects: \"unknown\",\n\t\tasync: true,\n\t\tcheck: check$1,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\tasync \"~run\"(dataset, config$1) {\n\t\t\tif (await this.check(dataset.value)) dataset.typed = true;\n\t\t\telse _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/date/date.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction date(message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"date\",\n\t\treference: date,\n\t\texpects: \"Date\",\n\t\tasync: false,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.value instanceof Date) if (!isNaN(dataset.value)) dataset.typed = true;\n\t\t\telse _addIssue(this, \"type\", dataset, config$1, { received: \"\\\"Invalid Date\\\"\" });\n\t\t\telse _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/enum/enum.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction enum_(enum__, message$1) {\n\tconst options = [];\n\tfor (const key in enum__) if (`${+key}` !== key || typeof enum__[key] !== \"string\" || !Object.is(enum__[enum__[key]], +key)) options.push(enum__[key]);\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"enum\",\n\t\treference: enum_,\n\t\texpects: /* @__PURE__ */ _joinExpects(options.map(_stringify), \"|\"),\n\t\tasync: false,\n\t\tenum: enum__,\n\t\toptions,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (this.options.includes(dataset.value)) dataset.typed = true;\n\t\t\telse _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/exactOptional/exactOptional.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction exactOptional(wrapped, default_) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"exact_optional\",\n\t\treference: exactOptional,\n\t\texpects: wrapped.expects,\n\t\tasync: false,\n\t\twrapped,\n\t\tdefault: default_,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\treturn this.wrapped[\"~run\"](dataset, config$1);\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/exactOptional/exactOptionalAsync.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction exactOptionalAsync(wrapped, default_) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"exact_optional\",\n\t\treference: exactOptionalAsync,\n\t\texpects: wrapped.expects,\n\t\tasync: true,\n\t\twrapped,\n\t\tdefault: default_,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\tasync \"~run\"(dataset, config$1) {\n\t\t\treturn this.wrapped[\"~run\"](dataset, config$1);\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/file/file.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction file(message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"file\",\n\t\treference: file,\n\t\texpects: \"File\",\n\t\tasync: false,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.value instanceof File) dataset.typed = true;\n\t\t\telse _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/function/function.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction function_(message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"function\",\n\t\treference: function_,\n\t\texpects: \"Function\",\n\t\tasync: false,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (typeof dataset.value === \"function\") dataset.typed = true;\n\t\t\telse _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/instance/instance.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction instance(class_, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"instance\",\n\t\treference: instance,\n\t\texpects: class_.name,\n\t\tasync: false,\n\t\tclass: class_,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.value instanceof this.class) dataset.typed = true;\n\t\t\telse _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/intersect/utils/_merge/_merge.ts\n/**\n* Merges two values into one single output.\n*\n* @param value1 First value.\n* @param value2 Second value.\n*\n* @returns The merge dataset.\n*\n* @internal\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction _merge(value1, value2) {\n\tif (typeof value1 === typeof value2) {\n\t\tif (value1 === value2 || value1 instanceof Date && value2 instanceof Date && +value1 === +value2) return { value: value1 };\n\t\tif (value1 && value2 && value1.constructor === Object && value2.constructor === Object) {\n\t\t\tconst nextValue = { ...value1 };\n\t\t\tfor (const key in value2) if (Object.prototype.hasOwnProperty.call(value1, key)) {\n\t\t\t\tconst dataset = /* @__PURE__ */ _merge(value1[key], value2[key]);\n\t\t\t\tif (dataset.issue) return dataset;\n\t\t\t\tnextValue[key] = dataset.value;\n\t\t\t} else nextValue[key] = value2[key];\n\t\t\treturn { value: nextValue };\n\t\t}\n\t\tif (Array.isArray(value1) && Array.isArray(value2)) {\n\t\t\tif (value1.length === value2.length) {\n\t\t\t\tconst nextValue = [...value1];\n\t\t\t\tfor (let index = 0; index < value1.length; index++) {\n\t\t\t\t\tconst dataset = /* @__PURE__ */ _merge(value1[index], value2[index]);\n\t\t\t\t\tif (dataset.issue) return dataset;\n\t\t\t\t\tnextValue[index] = dataset.value;\n\t\t\t\t}\n\t\t\t\treturn { value: nextValue };\n\t\t\t}\n\t\t}\n\t}\n\treturn { issue: true };\n}\n\n//#endregion\n//#region src/schemas/intersect/intersect.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction intersect(options, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"intersect\",\n\t\treference: intersect,\n\t\texpects: /* @__PURE__ */ _joinExpects(options.map((option) => option.expects), \"&\"),\n\t\tasync: false,\n\t\toptions,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (this.options.length) {\n\t\t\t\tconst input = dataset.value;\n\t\t\t\tlet outputs;\n\t\t\t\tdataset.typed = true;\n\t\t\t\tfor (const schema of this.options) {\n\t\t\t\t\tconst optionDataset = schema[\"~run\"]({ value: input }, config$1);\n\t\t\t\t\tif (optionDataset.issues) {\n\t\t\t\t\t\tif (dataset.issues) for (const issue of optionDataset.issues) dataset.issues.push(issue);\n\t\t\t\t\t\telse dataset.issues = optionDataset.issues;\n\t\t\t\t\t\tif (config$1.abortEarly) {\n\t\t\t\t\t\t\tdataset.typed = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!optionDataset.typed) dataset.typed = false;\n\t\t\t\t\tif (dataset.typed) if (outputs) outputs.push(optionDataset.value);\n\t\t\t\t\telse outputs = [optionDataset.value];\n\t\t\t\t}\n\t\t\t\tif (dataset.typed) {\n\t\t\t\t\tdataset.value = outputs[0];\n\t\t\t\t\tfor (let index = 1; index < outputs.length; index++) {\n\t\t\t\t\t\tconst mergeDataset = /* @__PURE__ */ _merge(dataset.value, outputs[index]);\n\t\t\t\t\t\tif (mergeDataset.issue) {\n\t\t\t\t\t\t\t_addIssue(this, \"type\", dataset, config$1, { received: \"unknown\" });\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdataset.value = mergeDataset.value;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/intersect/intersectAsync.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction intersectAsync(options, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"intersect\",\n\t\treference: intersectAsync,\n\t\texpects: /* @__PURE__ */ _joinExpects(options.map((option) => option.expects), \"&\"),\n\t\tasync: true,\n\t\toptions,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\tasync \"~run\"(dataset, config$1) {\n\t\t\tif (this.options.length) {\n\t\t\t\tconst input = dataset.value;\n\t\t\t\tlet outputs;\n\t\t\t\tdataset.typed = true;\n\t\t\t\tconst optionDatasets = await Promise.all(this.options.map((schema) => schema[\"~run\"]({ value: input }, config$1)));\n\t\t\t\tfor (const optionDataset of optionDatasets) {\n\t\t\t\t\tif (optionDataset.issues) {\n\t\t\t\t\t\tif (dataset.issues) for (const issue of optionDataset.issues) dataset.issues.push(issue);\n\t\t\t\t\t\telse dataset.issues = optionDataset.issues;\n\t\t\t\t\t\tif (config$1.abortEarly) {\n\t\t\t\t\t\t\tdataset.typed = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!optionDataset.typed) dataset.typed = false;\n\t\t\t\t\tif (dataset.typed) if (outputs) outputs.push(optionDataset.value);\n\t\t\t\t\telse outputs = [optionDataset.value];\n\t\t\t\t}\n\t\t\t\tif (dataset.typed) {\n\t\t\t\t\tdataset.value = outputs[0];\n\t\t\t\t\tfor (let index = 1; index < outputs.length; index++) {\n\t\t\t\t\t\tconst mergeDataset = /* @__PURE__ */ _merge(dataset.value, outputs[index]);\n\t\t\t\t\t\tif (mergeDataset.issue) {\n\t\t\t\t\t\t\t_addIssue(this, \"type\", dataset, config$1, { received: \"unknown\" });\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdataset.value = mergeDataset.value;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/lazy/lazy.ts\n/**\n* Creates a lazy schema.\n*\n* @param getter The schema getter.\n*\n* @returns A lazy schema.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction lazy(getter) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"lazy\",\n\t\treference: lazy,\n\t\texpects: \"unknown\",\n\t\tasync: false,\n\t\tgetter,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\treturn this.getter(dataset.value)[\"~run\"](dataset, config$1);\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/lazy/lazyAsync.ts\n/**\n* Creates a lazy schema.\n*\n* @param getter The schema getter.\n*\n* @returns A lazy schema.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction lazyAsync(getter) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"lazy\",\n\t\treference: lazyAsync,\n\t\texpects: \"unknown\",\n\t\tasync: true,\n\t\tgetter,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\tasync \"~run\"(dataset, config$1) {\n\t\t\treturn (await this.getter(dataset.value))[\"~run\"](dataset, config$1);\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/literal/literal.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction literal(literal_, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"literal\",\n\t\treference: literal,\n\t\texpects: /* @__PURE__ */ _stringify(literal_),\n\t\tasync: false,\n\t\tliteral: literal_,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.value === this.literal) dataset.typed = true;\n\t\t\telse _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/looseObject/looseObject.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction looseObject(entries$1, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"loose_object\",\n\t\treference: looseObject,\n\t\texpects: \"Object\",\n\t\tasync: false,\n\t\tentries: entries$1,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tconst input = dataset.value;\n\t\t\tif (input && typeof input === \"object\") {\n\t\t\t\tdataset.typed = true;\n\t\t\t\tdataset.value = {};\n\t\t\t\tfor (const key in this.entries) {\n\t\t\t\t\tconst valueSchema = this.entries[key];\n\t\t\t\t\tif (key in input || (valueSchema.type === \"exact_optional\" || valueSchema.type === \"optional\" || valueSchema.type === \"nullish\") && valueSchema.default !== void 0) {\n\t\t\t\t\t\tconst value$1 = key in input ? input[key] : /* @__PURE__ */ getDefault(valueSchema);\n\t\t\t\t\t\tconst valueDataset = valueSchema[\"~run\"]({ value: value$1 }, config$1);\n\t\t\t\t\t\tif (valueDataset.issues) {\n\t\t\t\t\t\t\tconst pathItem = {\n\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\torigin: \"value\",\n\t\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\t\tvalue: value$1\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tfor (const issue of valueDataset.issues) {\n\t\t\t\t\t\t\t\tif (issue.path) issue.path.unshift(pathItem);\n\t\t\t\t\t\t\t\telse issue.path = [pathItem];\n\t\t\t\t\t\t\t\tdataset.issues?.push(issue);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!dataset.issues) dataset.issues = valueDataset.issues;\n\t\t\t\t\t\t\tif (config$1.abortEarly) {\n\t\t\t\t\t\t\t\tdataset.typed = false;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!valueDataset.typed) dataset.typed = false;\n\t\t\t\t\t\tdataset.value[key] = valueDataset.value;\n\t\t\t\t\t} else if (valueSchema.fallback !== void 0) dataset.value[key] = /* @__PURE__ */ getFallback(valueSchema);\n\t\t\t\t\telse if (valueSchema.type !== \"exact_optional\" && valueSchema.type !== \"optional\" && valueSchema.type !== \"nullish\") {\n\t\t\t\t\t\t_addIssue(this, \"key\", dataset, config$1, {\n\t\t\t\t\t\t\tinput: void 0,\n\t\t\t\t\t\t\texpected: `\"${key}\"`,\n\t\t\t\t\t\t\tpath: [{\n\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\torigin: \"key\",\n\t\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\t\tvalue: input[key]\n\t\t\t\t\t\t\t}]\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (config$1.abortEarly) break;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!dataset.issues || !config$1.abortEarly) {\n\t\t\t\t\tfor (const key in input) if (/* @__PURE__ */ _isValidObjectKey(input, key) && !(key in this.entries)) dataset.value[key] = input[key];\n\t\t\t\t}\n\t\t\t} else _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/looseObject/looseObjectAsync.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction looseObjectAsync(entries$1, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"loose_object\",\n\t\treference: looseObjectAsync,\n\t\texpects: \"Object\",\n\t\tasync: true,\n\t\tentries: entries$1,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\tasync \"~run\"(dataset, config$1) {\n\t\t\tconst input = dataset.value;\n\t\t\tif (input && typeof input === \"object\") {\n\t\t\t\tdataset.typed = true;\n\t\t\t\tdataset.value = {};\n\t\t\t\tconst valueDatasets = await Promise.all(Object.entries(this.entries).map(async ([key, valueSchema]) => {\n\t\t\t\t\tif (key in input || (valueSchema.type === \"exact_optional\" || valueSchema.type === \"optional\" || valueSchema.type === \"nullish\") && valueSchema.default !== void 0) {\n\t\t\t\t\t\tconst value$1 = key in input ? input[key] : await /* @__PURE__ */ getDefault(valueSchema);\n\t\t\t\t\t\treturn [\n\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\tvalue$1,\n\t\t\t\t\t\t\tvalueSchema,\n\t\t\t\t\t\t\tawait valueSchema[\"~run\"]({ value: value$1 }, config$1)\n\t\t\t\t\t\t];\n\t\t\t\t\t}\n\t\t\t\t\treturn [\n\t\t\t\t\t\tkey,\n\t\t\t\t\t\tinput[key],\n\t\t\t\t\t\tvalueSchema,\n\t\t\t\t\t\tnull\n\t\t\t\t\t];\n\t\t\t\t}));\n\t\t\t\tfor (const [key, value$1, valueSchema, valueDataset] of valueDatasets) if (valueDataset) {\n\t\t\t\t\tif (valueDataset.issues) {\n\t\t\t\t\t\tconst pathItem = {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\torigin: \"value\",\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\tvalue: value$1\n\t\t\t\t\t\t};\n\t\t\t\t\t\tfor (const issue of valueDataset.issues) {\n\t\t\t\t\t\t\tif (issue.path) issue.path.unshift(pathItem);\n\t\t\t\t\t\t\telse issue.path = [pathItem];\n\t\t\t\t\t\t\tdataset.issues?.push(issue);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!dataset.issues) dataset.issues = valueDataset.issues;\n\t\t\t\t\t\tif (config$1.abortEarly) {\n\t\t\t\t\t\t\tdataset.typed = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!valueDataset.typed) dataset.typed = false;\n\t\t\t\t\tdataset.value[key] = valueDataset.value;\n\t\t\t\t} else if (valueSchema.fallback !== void 0) dataset.value[key] = await /* @__PURE__ */ getFallback(valueSchema);\n\t\t\t\telse if (valueSchema.type !== \"exact_optional\" && valueSchema.type !== \"optional\" && valueSchema.type !== \"nullish\") {\n\t\t\t\t\t_addIssue(this, \"key\", dataset, config$1, {\n\t\t\t\t\t\tinput: void 0,\n\t\t\t\t\t\texpected: `\"${key}\"`,\n\t\t\t\t\t\tpath: [{\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\torigin: \"key\",\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\tvalue: value$1\n\t\t\t\t\t\t}]\n\t\t\t\t\t});\n\t\t\t\t\tif (config$1.abortEarly) break;\n\t\t\t\t}\n\t\t\t\tif (!dataset.issues || !config$1.abortEarly) {\n\t\t\t\t\tfor (const key in input) if (/* @__PURE__ */ _isValidObjectKey(input, key) && !(key in this.entries)) dataset.value[key] = input[key];\n\t\t\t\t}\n\t\t\t} else _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/looseTuple/looseTuple.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction looseTuple(items, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"loose_tuple\",\n\t\treference: looseTuple,\n\t\texpects: \"Array\",\n\t\tasync: false,\n\t\titems,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tconst input = dataset.value;\n\t\t\tif (Array.isArray(input)) {\n\t\t\t\tdataset.typed = true;\n\t\t\t\tdataset.value = [];\n\t\t\t\tfor (let key = 0; key < this.items.length; key++) {\n\t\t\t\t\tconst value$1 = input[key];\n\t\t\t\t\tconst itemDataset = this.items[key][\"~run\"]({ value: value$1 }, config$1);\n\t\t\t\t\tif (itemDataset.issues) {\n\t\t\t\t\t\tconst pathItem = {\n\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\torigin: \"value\",\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\tvalue: value$1\n\t\t\t\t\t\t};\n\t\t\t\t\t\tfor (const issue of itemDataset.issues) {\n\t\t\t\t\t\t\tif (issue.path) issue.path.unshift(pathItem);\n\t\t\t\t\t\t\telse issue.path = [pathItem];\n\t\t\t\t\t\t\tdataset.issues?.push(issue);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!dataset.issues) dataset.issues = itemDataset.issues;\n\t\t\t\t\t\tif (config$1.abortEarly) {\n\t\t\t\t\t\t\tdataset.typed = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!itemDataset.typed) dataset.typed = false;\n\t\t\t\t\tdataset.value.push(itemDataset.value);\n\t\t\t\t}\n\t\t\t\tif (!dataset.issues || !config$1.abortEarly) for (let key = this.items.length; key < input.length; key++) dataset.value.push(input[key]);\n\t\t\t} else _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/looseTuple/looseTupleAsync.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction looseTupleAsync(items, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"loose_tuple\",\n\t\treference: looseTupleAsync,\n\t\texpects: \"Array\",\n\t\tasync: true,\n\t\titems,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\tasync \"~run\"(dataset, config$1) {\n\t\t\tconst input = dataset.value;\n\t\t\tif (Array.isArray(input)) {\n\t\t\t\tdataset.typed = true;\n\t\t\t\tdataset.value = [];\n\t\t\t\tconst itemDatasets = await Promise.all(this.items.map(async (item, key) => {\n\t\t\t\t\tconst value$1 = input[key];\n\t\t\t\t\treturn [\n\t\t\t\t\t\tkey,\n\t\t\t\t\t\tvalue$1,\n\t\t\t\t\t\tawait item[\"~run\"]({ value: value$1 }, config$1)\n\t\t\t\t\t];\n\t\t\t\t}));\n\t\t\t\tfor (const [key, value$1, itemDataset] of itemDatasets) {\n\t\t\t\t\tif (itemDataset.issues) {\n\t\t\t\t\t\tconst pathItem = {\n\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\torigin: \"value\",\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\tvalue: value$1\n\t\t\t\t\t\t};\n\t\t\t\t\t\tfor (const issue of itemDataset.issues) {\n\t\t\t\t\t\t\tif (issue.path) issue.path.unshift(pathItem);\n\t\t\t\t\t\t\telse issue.path = [pathItem];\n\t\t\t\t\t\t\tdataset.issues?.push(issue);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!dataset.issues) dataset.issues = itemDataset.issues;\n\t\t\t\t\t\tif (config$1.abortEarly) {\n\t\t\t\t\t\t\tdataset.typed = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!itemDataset.typed) dataset.typed = false;\n\t\t\t\t\tdataset.value.push(itemDataset.value);\n\t\t\t\t}\n\t\t\t\tif (!dataset.issues || !config$1.abortEarly) for (let key = this.items.length; key < input.length; key++) dataset.value.push(input[key]);\n\t\t\t} else _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/map/map.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction map(key, value$1, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"map\",\n\t\treference: map,\n\t\texpects: \"Map\",\n\t\tasync: false,\n\t\tkey,\n\t\tvalue: value$1,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tconst input = dataset.value;\n\t\t\tif (input instanceof Map) {\n\t\t\t\tdataset.typed = true;\n\t\t\t\tdataset.value = /* @__PURE__ */ new Map();\n\t\t\t\tfor (const [inputKey, inputValue] of input) {\n\t\t\t\t\tconst keyDataset = this.key[\"~run\"]({ value: inputKey }, config$1);\n\t\t\t\t\tif (keyDataset.issues) {\n\t\t\t\t\t\tconst pathItem = {\n\t\t\t\t\t\t\ttype: \"map\",\n\t\t\t\t\t\t\torigin: \"key\",\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\tkey: inputKey,\n\t\t\t\t\t\t\tvalue: inputValue\n\t\t\t\t\t\t};\n\t\t\t\t\t\tfor (const issue of keyDataset.issues) {\n\t\t\t\t\t\t\tif (issue.path) issue.path.unshift(pathItem);\n\t\t\t\t\t\t\telse issue.path = [pathItem];\n\t\t\t\t\t\t\tdataset.issues?.push(issue);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!dataset.issues) dataset.issues = keyDataset.issues;\n\t\t\t\t\t\tif (config$1.abortEarly) {\n\t\t\t\t\t\t\tdataset.typed = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tconst valueDataset = this.value[\"~run\"]({ value: inputValue }, config$1);\n\t\t\t\t\tif (valueDataset.issues) {\n\t\t\t\t\t\tconst pathItem = {\n\t\t\t\t\t\t\ttype: \"map\",\n\t\t\t\t\t\t\torigin: \"value\",\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\tkey: inputKey,\n\t\t\t\t\t\t\tvalue: inputValue\n\t\t\t\t\t\t};\n\t\t\t\t\t\tfor (const issue of valueDataset.issues) {\n\t\t\t\t\t\t\tif (issue.path) issue.path.unshift(pathItem);\n\t\t\t\t\t\t\telse issue.path = [pathItem];\n\t\t\t\t\t\t\tdataset.issues?.push(issue);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!dataset.issues) dataset.issues = valueDataset.issues;\n\t\t\t\t\t\tif (config$1.abortEarly) {\n\t\t\t\t\t\t\tdataset.typed = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!keyDataset.typed || !valueDataset.typed) dataset.typed = false;\n\t\t\t\t\tdataset.value.set(keyDataset.value, valueDataset.value);\n\t\t\t\t}\n\t\t\t} else _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/map/mapAsync.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction mapAsync(key, value$1, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"map\",\n\t\treference: mapAsync,\n\t\texpects: \"Map\",\n\t\tasync: true,\n\t\tkey,\n\t\tvalue: value$1,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\tasync \"~run\"(dataset, config$1) {\n\t\t\tconst input = dataset.value;\n\t\t\tif (input instanceof Map) {\n\t\t\t\tdataset.typed = true;\n\t\t\t\tdataset.value = /* @__PURE__ */ new Map();\n\t\t\t\tconst datasets = await Promise.all([...input].map(([inputKey, inputValue]) => Promise.all([\n\t\t\t\t\tinputKey,\n\t\t\t\t\tinputValue,\n\t\t\t\t\tthis.key[\"~run\"]({ value: inputKey }, config$1),\n\t\t\t\t\tthis.value[\"~run\"]({ value: inputValue }, config$1)\n\t\t\t\t])));\n\t\t\t\tfor (const [inputKey, inputValue, keyDataset, valueDataset] of datasets) {\n\t\t\t\t\tif (keyDataset.issues) {\n\t\t\t\t\t\tconst pathItem = {\n\t\t\t\t\t\t\ttype: \"map\",\n\t\t\t\t\t\t\torigin: \"key\",\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\tkey: inputKey,\n\t\t\t\t\t\t\tvalue: inputValue\n\t\t\t\t\t\t};\n\t\t\t\t\t\tfor (const issue of keyDataset.issues) {\n\t\t\t\t\t\t\tif (issue.path) issue.path.unshift(pathItem);\n\t\t\t\t\t\t\telse issue.path = [pathItem];\n\t\t\t\t\t\t\tdataset.issues?.push(issue);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!dataset.issues) dataset.issues = keyDataset.issues;\n\t\t\t\t\t\tif (config$1.abortEarly) {\n\t\t\t\t\t\t\tdataset.typed = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (valueDataset.issues) {\n\t\t\t\t\t\tconst pathItem = {\n\t\t\t\t\t\t\ttype: \"map\",\n\t\t\t\t\t\t\torigin: \"value\",\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\tkey: inputKey,\n\t\t\t\t\t\t\tvalue: inputValue\n\t\t\t\t\t\t};\n\t\t\t\t\t\tfor (const issue of valueDataset.issues) {\n\t\t\t\t\t\t\tif (issue.path) issue.path.unshift(pathItem);\n\t\t\t\t\t\t\telse issue.path = [pathItem];\n\t\t\t\t\t\t\tdataset.issues?.push(issue);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!dataset.issues) dataset.issues = valueDataset.issues;\n\t\t\t\t\t\tif (config$1.abortEarly) {\n\t\t\t\t\t\t\tdataset.typed = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!keyDataset.typed || !valueDataset.typed) dataset.typed = false;\n\t\t\t\t\tdataset.value.set(keyDataset.value, valueDataset.value);\n\t\t\t\t}\n\t\t\t} else _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/nan/nan.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction nan(message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"nan\",\n\t\treference: nan,\n\t\texpects: \"NaN\",\n\t\tasync: false,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (Number.isNaN(dataset.value)) dataset.typed = true;\n\t\t\telse _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/never/never.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction never(message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"never\",\n\t\treference: never,\n\t\texpects: \"never\",\n\t\tasync: false,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\t_addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/nonNullable/nonNullable.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction nonNullable(wrapped, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"non_nullable\",\n\t\treference: nonNullable,\n\t\texpects: \"!null\",\n\t\tasync: false,\n\t\twrapped,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.value !== null) dataset = this.wrapped[\"~run\"](dataset, config$1);\n\t\t\tif (dataset.value === null) _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/nonNullable/nonNullableAsync.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction nonNullableAsync(wrapped, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"non_nullable\",\n\t\treference: nonNullableAsync,\n\t\texpects: \"!null\",\n\t\tasync: true,\n\t\twrapped,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\tasync \"~run\"(dataset, config$1) {\n\t\t\tif (dataset.value !== null) dataset = await this.wrapped[\"~run\"](dataset, config$1);\n\t\t\tif (dataset.value === null) _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/nonNullish/nonNullish.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction nonNullish(wrapped, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"non_nullish\",\n\t\treference: nonNullish,\n\t\texpects: \"(!null & !undefined)\",\n\t\tasync: false,\n\t\twrapped,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (!(dataset.value === null || dataset.value === void 0)) dataset = this.wrapped[\"~run\"](dataset, config$1);\n\t\t\tif (dataset.value === null || dataset.value === void 0) _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/nonNullish/nonNullishAsync.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction nonNullishAsync(wrapped, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"non_nullish\",\n\t\treference: nonNullishAsync,\n\t\texpects: \"(!null & !undefined)\",\n\t\tasync: true,\n\t\twrapped,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\tasync \"~run\"(dataset, config$1) {\n\t\t\tif (!(dataset.value === null || dataset.value === void 0)) dataset = await this.wrapped[\"~run\"](dataset, config$1);\n\t\t\tif (dataset.value === null || dataset.value === void 0) _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/nonOptional/nonOptional.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction nonOptional(wrapped, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"non_optional\",\n\t\treference: nonOptional,\n\t\texpects: \"!undefined\",\n\t\tasync: false,\n\t\twrapped,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.value !== void 0) dataset = this.wrapped[\"~run\"](dataset, config$1);\n\t\t\tif (dataset.value === void 0) _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/nonOptional/nonOptionalAsync.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction nonOptionalAsync(wrapped, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"non_optional\",\n\t\treference: nonOptionalAsync,\n\t\texpects: \"!undefined\",\n\t\tasync: true,\n\t\twrapped,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\tasync \"~run\"(dataset, config$1) {\n\t\t\tif (dataset.value !== void 0) dataset = await this.wrapped[\"~run\"](dataset, config$1);\n\t\t\tif (dataset.value === void 0) _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/null/null.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction null_(message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"null\",\n\t\treference: null_,\n\t\texpects: \"null\",\n\t\tasync: false,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.value === null) dataset.typed = true;\n\t\t\telse _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/nullable/nullable.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction nullable(wrapped, default_) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"nullable\",\n\t\treference: nullable,\n\t\texpects: `(${wrapped.expects} | null)`,\n\t\tasync: false,\n\t\twrapped,\n\t\tdefault: default_,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.value === null) {\n\t\t\t\tif (this.default !== void 0) dataset.value = /* @__PURE__ */ getDefault(this, dataset, config$1);\n\t\t\t\tif (dataset.value === null) {\n\t\t\t\t\tdataset.typed = true;\n\t\t\t\t\treturn dataset;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn this.wrapped[\"~run\"](dataset, config$1);\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/nullable/nullableAsync.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction nullableAsync(wrapped, default_) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"nullable\",\n\t\treference: nullableAsync,\n\t\texpects: `(${wrapped.expects} | null)`,\n\t\tasync: true,\n\t\twrapped,\n\t\tdefault: default_,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\tasync \"~run\"(dataset, config$1) {\n\t\t\tif (dataset.value === null) {\n\t\t\t\tif (this.default !== void 0) dataset.value = await /* @__PURE__ */ getDefault(this, dataset, config$1);\n\t\t\t\tif (dataset.value === null) {\n\t\t\t\t\tdataset.typed = true;\n\t\t\t\t\treturn dataset;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn this.wrapped[\"~run\"](dataset, config$1);\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/nullish/nullish.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction nullish(wrapped, default_) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"nullish\",\n\t\treference: nullish,\n\t\texpects: `(${wrapped.expects} | null | undefined)`,\n\t\tasync: false,\n\t\twrapped,\n\t\tdefault: default_,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.value === null || dataset.value === void 0) {\n\t\t\t\tif (this.default !== void 0) dataset.value = /* @__PURE__ */ getDefault(this, dataset, config$1);\n\t\t\t\tif (dataset.value === null || dataset.value === void 0) {\n\t\t\t\t\tdataset.typed = true;\n\t\t\t\t\treturn dataset;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn this.wrapped[\"~run\"](dataset, config$1);\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/nullish/nullishAsync.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction nullishAsync(wrapped, default_) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"nullish\",\n\t\treference: nullishAsync,\n\t\texpects: `(${wrapped.expects} | null | undefined)`,\n\t\tasync: true,\n\t\twrapped,\n\t\tdefault: default_,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\tasync \"~run\"(dataset, config$1) {\n\t\t\tif (dataset.value === null || dataset.value === void 0) {\n\t\t\t\tif (this.default !== void 0) dataset.value = await /* @__PURE__ */ getDefault(this, dataset, config$1);\n\t\t\t\tif (dataset.value === null || dataset.value === void 0) {\n\t\t\t\t\tdataset.typed = true;\n\t\t\t\t\treturn dataset;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn this.wrapped[\"~run\"](dataset, config$1);\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/number/number.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction number(message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"number\",\n\t\treference: number,\n\t\texpects: \"number\",\n\t\tasync: false,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (typeof dataset.value === \"number\" && !isNaN(dataset.value)) dataset.typed = true;\n\t\t\telse _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/object/object.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction object(entries$1, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"object\",\n\t\treference: object,\n\t\texpects: \"Object\",\n\t\tasync: false,\n\t\tentries: entries$1,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tconst input = dataset.value;\n\t\t\tif (input && typeof input === \"object\") {\n\t\t\t\tdataset.typed = true;\n\t\t\t\tdataset.value = {};\n\t\t\t\tfor (const key in this.entries) {\n\t\t\t\t\tconst valueSchema = this.entries[key];\n\t\t\t\t\tif (key in input || (valueSchema.type === \"exact_optional\" || valueSchema.type === \"optional\" || valueSchema.type === \"nullish\") && valueSchema.default !== void 0) {\n\t\t\t\t\t\tconst value$1 = key in input ? input[key] : /* @__PURE__ */ getDefault(valueSchema);\n\t\t\t\t\t\tconst valueDataset = valueSchema[\"~run\"]({ value: value$1 }, config$1);\n\t\t\t\t\t\tif (valueDataset.issues) {\n\t\t\t\t\t\t\tconst pathItem = {\n\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\torigin: \"value\",\n\t\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\t\tvalue: value$1\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tfor (const issue of valueDataset.issues) {\n\t\t\t\t\t\t\t\tif (issue.path) issue.path.unshift(pathItem);\n\t\t\t\t\t\t\t\telse issue.path = [pathItem];\n\t\t\t\t\t\t\t\tdataset.issues?.push(issue);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!dataset.issues) dataset.issues = valueDataset.issues;\n\t\t\t\t\t\t\tif (config$1.abortEarly) {\n\t\t\t\t\t\t\t\tdataset.typed = false;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!valueDataset.typed) dataset.typed = false;\n\t\t\t\t\t\tdataset.value[key] = valueDataset.value;\n\t\t\t\t\t} else if (valueSchema.fallback !== void 0) dataset.value[key] = /* @__PURE__ */ getFallback(valueSchema);\n\t\t\t\t\telse if (valueSchema.type !== \"exact_optional\" && valueSchema.type !== \"optional\" && valueSchema.type !== \"nullish\") {\n\t\t\t\t\t\t_addIssue(this, \"key\", dataset, config$1, {\n\t\t\t\t\t\t\tinput: void 0,\n\t\t\t\t\t\t\texpected: `\"${key}\"`,\n\t\t\t\t\t\t\tpath: [{\n\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\torigin: \"key\",\n\t\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\t\tvalue: input[key]\n\t\t\t\t\t\t\t}]\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (config$1.abortEarly) break;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/object/objectAsync.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction objectAsync(entries$1, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"object\",\n\t\treference: objectAsync,\n\t\texpects: \"Object\",\n\t\tasync: true,\n\t\tentries: entries$1,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\tasync \"~run\"(dataset, config$1) {\n\t\t\tconst input = dataset.value;\n\t\t\tif (input && typeof input === \"object\") {\n\t\t\t\tdataset.typed = true;\n\t\t\t\tdataset.value = {};\n\t\t\t\tconst valueDatasets = await Promise.all(Object.entries(this.entries).map(async ([key, valueSchema]) => {\n\t\t\t\t\tif (key in input || (valueSchema.type === \"exact_optional\" || valueSchema.type === \"optional\" || valueSchema.type === \"nullish\") && valueSchema.default !== void 0) {\n\t\t\t\t\t\tconst value$1 = key in input ? input[key] : await /* @__PURE__ */ getDefault(valueSchema);\n\t\t\t\t\t\treturn [\n\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\tvalue$1,\n\t\t\t\t\t\t\tvalueSchema,\n\t\t\t\t\t\t\tawait valueSchema[\"~run\"]({ value: value$1 }, config$1)\n\t\t\t\t\t\t];\n\t\t\t\t\t}\n\t\t\t\t\treturn [\n\t\t\t\t\t\tkey,\n\t\t\t\t\t\tinput[key],\n\t\t\t\t\t\tvalueSchema,\n\t\t\t\t\t\tnull\n\t\t\t\t\t];\n\t\t\t\t}));\n\t\t\t\tfor (const [key, value$1, valueSchema, valueDataset] of valueDatasets) if (valueDataset) {\n\t\t\t\t\tif (valueDataset.issues) {\n\t\t\t\t\t\tconst pathItem = {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\torigin: \"value\",\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\tvalue: value$1\n\t\t\t\t\t\t};\n\t\t\t\t\t\tfor (const issue of valueDataset.issues) {\n\t\t\t\t\t\t\tif (issue.path) issue.path.unshift(pathItem);\n\t\t\t\t\t\t\telse issue.path = [pathItem];\n\t\t\t\t\t\t\tdataset.issues?.push(issue);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!dataset.issues) dataset.issues = valueDataset.issues;\n\t\t\t\t\t\tif (config$1.abortEarly) {\n\t\t\t\t\t\t\tdataset.typed = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!valueDataset.typed) dataset.typed = false;\n\t\t\t\t\tdataset.value[key] = valueDataset.value;\n\t\t\t\t} else if (valueSchema.fallback !== void 0) dataset.value[key] = await /* @__PURE__ */ getFallback(valueSchema);\n\t\t\t\telse if (valueSchema.type !== \"exact_optional\" && valueSchema.type !== \"optional\" && valueSchema.type !== \"nullish\") {\n\t\t\t\t\t_addIssue(this, \"key\", dataset, config$1, {\n\t\t\t\t\t\tinput: void 0,\n\t\t\t\t\t\texpected: `\"${key}\"`,\n\t\t\t\t\t\tpath: [{\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\torigin: \"key\",\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\tvalue: value$1\n\t\t\t\t\t\t}]\n\t\t\t\t\t});\n\t\t\t\t\tif (config$1.abortEarly) break;\n\t\t\t\t}\n\t\t\t} else _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/objectWithRest/objectWithRest.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction objectWithRest(entries$1, rest, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"object_with_rest\",\n\t\treference: objectWithRest,\n\t\texpects: \"Object\",\n\t\tasync: false,\n\t\tentries: entries$1,\n\t\trest,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tconst input = dataset.value;\n\t\t\tif (input && typeof input === \"object\") {\n\t\t\t\tdataset.typed = true;\n\t\t\t\tdataset.value = {};\n\t\t\t\tfor (const key in this.entries) {\n\t\t\t\t\tconst valueSchema = this.entries[key];\n\t\t\t\t\tif (key in input || (valueSchema.type === \"exact_optional\" || valueSchema.type === \"optional\" || valueSchema.type === \"nullish\") && valueSchema.default !== void 0) {\n\t\t\t\t\t\tconst value$1 = key in input ? input[key] : /* @__PURE__ */ getDefault(valueSchema);\n\t\t\t\t\t\tconst valueDataset = valueSchema[\"~run\"]({ value: value$1 }, config$1);\n\t\t\t\t\t\tif (valueDataset.issues) {\n\t\t\t\t\t\t\tconst pathItem = {\n\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\torigin: \"value\",\n\t\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\t\tvalue: value$1\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tfor (const issue of valueDataset.issues) {\n\t\t\t\t\t\t\t\tif (issue.path) issue.path.unshift(pathItem);\n\t\t\t\t\t\t\t\telse issue.path = [pathItem];\n\t\t\t\t\t\t\t\tdataset.issues?.push(issue);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!dataset.issues) dataset.issues = valueDataset.issues;\n\t\t\t\t\t\t\tif (config$1.abortEarly) {\n\t\t\t\t\t\t\t\tdataset.typed = false;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!valueDataset.typed) dataset.typed = false;\n\t\t\t\t\t\tdataset.value[key] = valueDataset.value;\n\t\t\t\t\t} else if (valueSchema.fallback !== void 0) dataset.value[key] = /* @__PURE__ */ getFallback(valueSchema);\n\t\t\t\t\telse if (valueSchema.type !== \"exact_optional\" && valueSchema.type !== \"optional\" && valueSchema.type !== \"nullish\") {\n\t\t\t\t\t\t_addIssue(this, \"key\", dataset, config$1, {\n\t\t\t\t\t\t\tinput: void 0,\n\t\t\t\t\t\t\texpected: `\"${key}\"`,\n\t\t\t\t\t\t\tpath: [{\n\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\torigin: \"key\",\n\t\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\t\tvalue: input[key]\n\t\t\t\t\t\t\t}]\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (config$1.abortEarly) break;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!dataset.issues || !config$1.abortEarly) {\n\t\t\t\t\tfor (const key in input) if (/* @__PURE__ */ _isValidObjectKey(input, key) && !(key in this.entries)) {\n\t\t\t\t\t\tconst valueDataset = this.rest[\"~run\"]({ value: input[key] }, config$1);\n\t\t\t\t\t\tif (valueDataset.issues) {\n\t\t\t\t\t\t\tconst pathItem = {\n\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\torigin: \"value\",\n\t\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\t\tvalue: input[key]\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tfor (const issue of valueDataset.issues) {\n\t\t\t\t\t\t\t\tif (issue.path) issue.path.unshift(pathItem);\n\t\t\t\t\t\t\t\telse issue.path = [pathItem];\n\t\t\t\t\t\t\t\tdataset.issues?.push(issue);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!dataset.issues) dataset.issues = valueDataset.issues;\n\t\t\t\t\t\t\tif (config$1.abortEarly) {\n\t\t\t\t\t\t\t\tdataset.typed = false;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!valueDataset.typed) dataset.typed = false;\n\t\t\t\t\t\tdataset.value[key] = valueDataset.value;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/objectWithRest/objectWithRestAsync.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction objectWithRestAsync(entries$1, rest, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"object_with_rest\",\n\t\treference: objectWithRestAsync,\n\t\texpects: \"Object\",\n\t\tasync: true,\n\t\tentries: entries$1,\n\t\trest,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\tasync \"~run\"(dataset, config$1) {\n\t\t\tconst input = dataset.value;\n\t\t\tif (input && typeof input === \"object\") {\n\t\t\t\tdataset.typed = true;\n\t\t\t\tdataset.value = {};\n\t\t\t\tconst [normalDatasets, restDatasets] = await Promise.all([Promise.all(Object.entries(this.entries).map(async ([key, valueSchema]) => {\n\t\t\t\t\tif (key in input || (valueSchema.type === \"exact_optional\" || valueSchema.type === \"optional\" || valueSchema.type === \"nullish\") && valueSchema.default !== void 0) {\n\t\t\t\t\t\tconst value$1 = key in input ? input[key] : await /* @__PURE__ */ getDefault(valueSchema);\n\t\t\t\t\t\treturn [\n\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\tvalue$1,\n\t\t\t\t\t\t\tvalueSchema,\n\t\t\t\t\t\t\tawait valueSchema[\"~run\"]({ value: value$1 }, config$1)\n\t\t\t\t\t\t];\n\t\t\t\t\t}\n\t\t\t\t\treturn [\n\t\t\t\t\t\tkey,\n\t\t\t\t\t\tinput[key],\n\t\t\t\t\t\tvalueSchema,\n\t\t\t\t\t\tnull\n\t\t\t\t\t];\n\t\t\t\t})), Promise.all(Object.entries(input).filter(([key]) => /* @__PURE__ */ _isValidObjectKey(input, key) && !(key in this.entries)).map(async ([key, value$1]) => [\n\t\t\t\t\tkey,\n\t\t\t\t\tvalue$1,\n\t\t\t\t\tawait this.rest[\"~run\"]({ value: value$1 }, config$1)\n\t\t\t\t]))]);\n\t\t\t\tfor (const [key, value$1, valueSchema, valueDataset] of normalDatasets) if (valueDataset) {\n\t\t\t\t\tif (valueDataset.issues) {\n\t\t\t\t\t\tconst pathItem = {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\torigin: \"value\",\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\tvalue: value$1\n\t\t\t\t\t\t};\n\t\t\t\t\t\tfor (const issue of valueDataset.issues) {\n\t\t\t\t\t\t\tif (issue.path) issue.path.unshift(pathItem);\n\t\t\t\t\t\t\telse issue.path = [pathItem];\n\t\t\t\t\t\t\tdataset.issues?.push(issue);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!dataset.issues) dataset.issues = valueDataset.issues;\n\t\t\t\t\t\tif (config$1.abortEarly) {\n\t\t\t\t\t\t\tdataset.typed = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!valueDataset.typed) dataset.typed = false;\n\t\t\t\t\tdataset.value[key] = valueDataset.value;\n\t\t\t\t} else if (valueSchema.fallback !== void 0) dataset.value[key] = await /* @__PURE__ */ getFallback(valueSchema);\n\t\t\t\telse if (valueSchema.type !== \"exact_optional\" && valueSchema.type !== \"optional\" && valueSchema.type !== \"nullish\") {\n\t\t\t\t\t_addIssue(this, \"key\", dataset, config$1, {\n\t\t\t\t\t\tinput: void 0,\n\t\t\t\t\t\texpected: `\"${key}\"`,\n\t\t\t\t\t\tpath: [{\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\torigin: \"key\",\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\tvalue: value$1\n\t\t\t\t\t\t}]\n\t\t\t\t\t});\n\t\t\t\t\tif (config$1.abortEarly) break;\n\t\t\t\t}\n\t\t\t\tif (!dataset.issues || !config$1.abortEarly) for (const [key, value$1, valueDataset] of restDatasets) {\n\t\t\t\t\tif (valueDataset.issues) {\n\t\t\t\t\t\tconst pathItem = {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\torigin: \"value\",\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\tvalue: value$1\n\t\t\t\t\t\t};\n\t\t\t\t\t\tfor (const issue of valueDataset.issues) {\n\t\t\t\t\t\t\tif (issue.path) issue.path.unshift(pathItem);\n\t\t\t\t\t\t\telse issue.path = [pathItem];\n\t\t\t\t\t\t\tdataset.issues?.push(issue);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!dataset.issues) dataset.issues = valueDataset.issues;\n\t\t\t\t\t\tif (config$1.abortEarly) {\n\t\t\t\t\t\t\tdataset.typed = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!valueDataset.typed) dataset.typed = false;\n\t\t\t\t\tdataset.value[key] = valueDataset.value;\n\t\t\t\t}\n\t\t\t} else _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/optional/optional.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction optional(wrapped, default_) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"optional\",\n\t\treference: optional,\n\t\texpects: `(${wrapped.expects} | undefined)`,\n\t\tasync: false,\n\t\twrapped,\n\t\tdefault: default_,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.value === void 0) {\n\t\t\t\tif (this.default !== void 0) dataset.value = /* @__PURE__ */ getDefault(this, dataset, config$1);\n\t\t\t\tif (dataset.value === void 0) {\n\t\t\t\t\tdataset.typed = true;\n\t\t\t\t\treturn dataset;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn this.wrapped[\"~run\"](dataset, config$1);\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/optional/optionalAsync.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction optionalAsync(wrapped, default_) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"optional\",\n\t\treference: optionalAsync,\n\t\texpects: `(${wrapped.expects} | undefined)`,\n\t\tasync: true,\n\t\twrapped,\n\t\tdefault: default_,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\tasync \"~run\"(dataset, config$1) {\n\t\t\tif (dataset.value === void 0) {\n\t\t\t\tif (this.default !== void 0) dataset.value = await /* @__PURE__ */ getDefault(this, dataset, config$1);\n\t\t\t\tif (dataset.value === void 0) {\n\t\t\t\t\tdataset.typed = true;\n\t\t\t\t\treturn dataset;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn this.wrapped[\"~run\"](dataset, config$1);\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/picklist/picklist.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction picklist(options, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"picklist\",\n\t\treference: picklist,\n\t\texpects: /* @__PURE__ */ _joinExpects(options.map(_stringify), \"|\"),\n\t\tasync: false,\n\t\toptions,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (this.options.includes(dataset.value)) dataset.typed = true;\n\t\t\telse _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/promise/promise.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction promise(message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"promise\",\n\t\treference: promise,\n\t\texpects: \"Promise\",\n\t\tasync: false,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.value instanceof Promise) dataset.typed = true;\n\t\t\telse _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/record/record.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction record(key, value$1, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"record\",\n\t\treference: record,\n\t\texpects: \"Object\",\n\t\tasync: false,\n\t\tkey,\n\t\tvalue: value$1,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tconst input = dataset.value;\n\t\t\tif (input && typeof input === \"object\") {\n\t\t\t\tdataset.typed = true;\n\t\t\t\tdataset.value = {};\n\t\t\t\tfor (const entryKey in input) if (/* @__PURE__ */ _isValidObjectKey(input, entryKey)) {\n\t\t\t\t\tconst entryValue = input[entryKey];\n\t\t\t\t\tconst keyDataset = this.key[\"~run\"]({ value: entryKey }, config$1);\n\t\t\t\t\tif (keyDataset.issues) {\n\t\t\t\t\t\tconst pathItem = {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\torigin: \"key\",\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\tkey: entryKey,\n\t\t\t\t\t\t\tvalue: entryValue\n\t\t\t\t\t\t};\n\t\t\t\t\t\tfor (const issue of keyDataset.issues) {\n\t\t\t\t\t\t\tissue.path = [pathItem];\n\t\t\t\t\t\t\tdataset.issues?.push(issue);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!dataset.issues) dataset.issues = keyDataset.issues;\n\t\t\t\t\t\tif (config$1.abortEarly) {\n\t\t\t\t\t\t\tdataset.typed = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tconst valueDataset = this.value[\"~run\"]({ value: entryValue }, config$1);\n\t\t\t\t\tif (valueDataset.issues) {\n\t\t\t\t\t\tconst pathItem = {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\torigin: \"value\",\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\tkey: entryKey,\n\t\t\t\t\t\t\tvalue: entryValue\n\t\t\t\t\t\t};\n\t\t\t\t\t\tfor (const issue of valueDataset.issues) {\n\t\t\t\t\t\t\tif (issue.path) issue.path.unshift(pathItem);\n\t\t\t\t\t\t\telse issue.path = [pathItem];\n\t\t\t\t\t\t\tdataset.issues?.push(issue);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!dataset.issues) dataset.issues = valueDataset.issues;\n\t\t\t\t\t\tif (config$1.abortEarly) {\n\t\t\t\t\t\t\tdataset.typed = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!keyDataset.typed || !valueDataset.typed) dataset.typed = false;\n\t\t\t\t\tif (keyDataset.typed) dataset.value[keyDataset.value] = valueDataset.value;\n\t\t\t\t}\n\t\t\t} else _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/record/recordAsync.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction recordAsync(key, value$1, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"record\",\n\t\treference: recordAsync,\n\t\texpects: \"Object\",\n\t\tasync: true,\n\t\tkey,\n\t\tvalue: value$1,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\tasync \"~run\"(dataset, config$1) {\n\t\t\tconst input = dataset.value;\n\t\t\tif (input && typeof input === \"object\") {\n\t\t\t\tdataset.typed = true;\n\t\t\t\tdataset.value = {};\n\t\t\t\tconst datasets = await Promise.all(Object.entries(input).filter(([key$1]) => /* @__PURE__ */ _isValidObjectKey(input, key$1)).map(([entryKey, entryValue]) => Promise.all([\n\t\t\t\t\tentryKey,\n\t\t\t\t\tentryValue,\n\t\t\t\t\tthis.key[\"~run\"]({ value: entryKey }, config$1),\n\t\t\t\t\tthis.value[\"~run\"]({ value: entryValue }, config$1)\n\t\t\t\t])));\n\t\t\t\tfor (const [entryKey, entryValue, keyDataset, valueDataset] of datasets) {\n\t\t\t\t\tif (keyDataset.issues) {\n\t\t\t\t\t\tconst pathItem = {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\torigin: \"key\",\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\tkey: entryKey,\n\t\t\t\t\t\t\tvalue: entryValue\n\t\t\t\t\t\t};\n\t\t\t\t\t\tfor (const issue of keyDataset.issues) {\n\t\t\t\t\t\t\tissue.path = [pathItem];\n\t\t\t\t\t\t\tdataset.issues?.push(issue);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!dataset.issues) dataset.issues = keyDataset.issues;\n\t\t\t\t\t\tif (config$1.abortEarly) {\n\t\t\t\t\t\t\tdataset.typed = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (valueDataset.issues) {\n\t\t\t\t\t\tconst pathItem = {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\torigin: \"value\",\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\tkey: entryKey,\n\t\t\t\t\t\t\tvalue: entryValue\n\t\t\t\t\t\t};\n\t\t\t\t\t\tfor (const issue of valueDataset.issues) {\n\t\t\t\t\t\t\tif (issue.path) issue.path.unshift(pathItem);\n\t\t\t\t\t\t\telse issue.path = [pathItem];\n\t\t\t\t\t\t\tdataset.issues?.push(issue);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!dataset.issues) dataset.issues = valueDataset.issues;\n\t\t\t\t\t\tif (config$1.abortEarly) {\n\t\t\t\t\t\t\tdataset.typed = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!keyDataset.typed || !valueDataset.typed) dataset.typed = false;\n\t\t\t\t\tif (keyDataset.typed) dataset.value[keyDataset.value] = valueDataset.value;\n\t\t\t\t}\n\t\t\t} else _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/set/set.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction set(value$1, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"set\",\n\t\treference: set,\n\t\texpects: \"Set\",\n\t\tasync: false,\n\t\tvalue: value$1,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tconst input = dataset.value;\n\t\t\tif (input instanceof Set) {\n\t\t\t\tdataset.typed = true;\n\t\t\t\tdataset.value = /* @__PURE__ */ new Set();\n\t\t\t\tfor (const inputValue of input) {\n\t\t\t\t\tconst valueDataset = this.value[\"~run\"]({ value: inputValue }, config$1);\n\t\t\t\t\tif (valueDataset.issues) {\n\t\t\t\t\t\tconst pathItem = {\n\t\t\t\t\t\t\ttype: \"set\",\n\t\t\t\t\t\t\torigin: \"value\",\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\tkey: null,\n\t\t\t\t\t\t\tvalue: inputValue\n\t\t\t\t\t\t};\n\t\t\t\t\t\tfor (const issue of valueDataset.issues) {\n\t\t\t\t\t\t\tif (issue.path) issue.path.unshift(pathItem);\n\t\t\t\t\t\t\telse issue.path = [pathItem];\n\t\t\t\t\t\t\tdataset.issues?.push(issue);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!dataset.issues) dataset.issues = valueDataset.issues;\n\t\t\t\t\t\tif (config$1.abortEarly) {\n\t\t\t\t\t\t\tdataset.typed = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!valueDataset.typed) dataset.typed = false;\n\t\t\t\t\tdataset.value.add(valueDataset.value);\n\t\t\t\t}\n\t\t\t} else _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/set/setAsync.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction setAsync(value$1, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"set\",\n\t\treference: setAsync,\n\t\texpects: \"Set\",\n\t\tasync: true,\n\t\tvalue: value$1,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\tasync \"~run\"(dataset, config$1) {\n\t\t\tconst input = dataset.value;\n\t\t\tif (input instanceof Set) {\n\t\t\t\tdataset.typed = true;\n\t\t\t\tdataset.value = /* @__PURE__ */ new Set();\n\t\t\t\tconst valueDatasets = await Promise.all([...input].map(async (inputValue) => [inputValue, await this.value[\"~run\"]({ value: inputValue }, config$1)]));\n\t\t\t\tfor (const [inputValue, valueDataset] of valueDatasets) {\n\t\t\t\t\tif (valueDataset.issues) {\n\t\t\t\t\t\tconst pathItem = {\n\t\t\t\t\t\t\ttype: \"set\",\n\t\t\t\t\t\t\torigin: \"value\",\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\tkey: null,\n\t\t\t\t\t\t\tvalue: inputValue\n\t\t\t\t\t\t};\n\t\t\t\t\t\tfor (const issue of valueDataset.issues) {\n\t\t\t\t\t\t\tif (issue.path) issue.path.unshift(pathItem);\n\t\t\t\t\t\t\telse issue.path = [pathItem];\n\t\t\t\t\t\t\tdataset.issues?.push(issue);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!dataset.issues) dataset.issues = valueDataset.issues;\n\t\t\t\t\t\tif (config$1.abortEarly) {\n\t\t\t\t\t\t\tdataset.typed = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!valueDataset.typed) dataset.typed = false;\n\t\t\t\t\tdataset.value.add(valueDataset.value);\n\t\t\t\t}\n\t\t\t} else _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/strictObject/strictObject.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction strictObject(entries$1, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"strict_object\",\n\t\treference: strictObject,\n\t\texpects: \"Object\",\n\t\tasync: false,\n\t\tentries: entries$1,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tconst input = dataset.value;\n\t\t\tif (input && typeof input === \"object\") {\n\t\t\t\tdataset.typed = true;\n\t\t\t\tdataset.value = {};\n\t\t\t\tfor (const key in this.entries) {\n\t\t\t\t\tconst valueSchema = this.entries[key];\n\t\t\t\t\tif (key in input || (valueSchema.type === \"exact_optional\" || valueSchema.type === \"optional\" || valueSchema.type === \"nullish\") && valueSchema.default !== void 0) {\n\t\t\t\t\t\tconst value$1 = key in input ? input[key] : /* @__PURE__ */ getDefault(valueSchema);\n\t\t\t\t\t\tconst valueDataset = valueSchema[\"~run\"]({ value: value$1 }, config$1);\n\t\t\t\t\t\tif (valueDataset.issues) {\n\t\t\t\t\t\t\tconst pathItem = {\n\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\torigin: \"value\",\n\t\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\t\tvalue: value$1\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tfor (const issue of valueDataset.issues) {\n\t\t\t\t\t\t\t\tif (issue.path) issue.path.unshift(pathItem);\n\t\t\t\t\t\t\t\telse issue.path = [pathItem];\n\t\t\t\t\t\t\t\tdataset.issues?.push(issue);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!dataset.issues) dataset.issues = valueDataset.issues;\n\t\t\t\t\t\t\tif (config$1.abortEarly) {\n\t\t\t\t\t\t\t\tdataset.typed = false;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!valueDataset.typed) dataset.typed = false;\n\t\t\t\t\t\tdataset.value[key] = valueDataset.value;\n\t\t\t\t\t} else if (valueSchema.fallback !== void 0) dataset.value[key] = /* @__PURE__ */ getFallback(valueSchema);\n\t\t\t\t\telse if (valueSchema.type !== \"exact_optional\" && valueSchema.type !== \"optional\" && valueSchema.type !== \"nullish\") {\n\t\t\t\t\t\t_addIssue(this, \"key\", dataset, config$1, {\n\t\t\t\t\t\t\tinput: void 0,\n\t\t\t\t\t\t\texpected: `\"${key}\"`,\n\t\t\t\t\t\t\tpath: [{\n\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\torigin: \"key\",\n\t\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\t\tvalue: input[key]\n\t\t\t\t\t\t\t}]\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (config$1.abortEarly) break;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!dataset.issues || !config$1.abortEarly) {\n\t\t\t\t\tfor (const key in input) if (!(key in this.entries)) {\n\t\t\t\t\t\t_addIssue(this, \"key\", dataset, config$1, {\n\t\t\t\t\t\t\tinput: key,\n\t\t\t\t\t\t\texpected: \"never\",\n\t\t\t\t\t\t\tpath: [{\n\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\torigin: \"key\",\n\t\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\t\tvalue: input[key]\n\t\t\t\t\t\t\t}]\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/strictObject/strictObjectAsync.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction strictObjectAsync(entries$1, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"strict_object\",\n\t\treference: strictObjectAsync,\n\t\texpects: \"Object\",\n\t\tasync: true,\n\t\tentries: entries$1,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\tasync \"~run\"(dataset, config$1) {\n\t\t\tconst input = dataset.value;\n\t\t\tif (input && typeof input === \"object\") {\n\t\t\t\tdataset.typed = true;\n\t\t\t\tdataset.value = {};\n\t\t\t\tconst valueDatasets = await Promise.all(Object.entries(this.entries).map(async ([key, valueSchema]) => {\n\t\t\t\t\tif (key in input || (valueSchema.type === \"exact_optional\" || valueSchema.type === \"optional\" || valueSchema.type === \"nullish\") && valueSchema.default !== void 0) {\n\t\t\t\t\t\tconst value$1 = key in input ? input[key] : await /* @__PURE__ */ getDefault(valueSchema);\n\t\t\t\t\t\treturn [\n\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\tvalue$1,\n\t\t\t\t\t\t\tvalueSchema,\n\t\t\t\t\t\t\tawait valueSchema[\"~run\"]({ value: value$1 }, config$1)\n\t\t\t\t\t\t];\n\t\t\t\t\t}\n\t\t\t\t\treturn [\n\t\t\t\t\t\tkey,\n\t\t\t\t\t\tinput[key],\n\t\t\t\t\t\tvalueSchema,\n\t\t\t\t\t\tnull\n\t\t\t\t\t];\n\t\t\t\t}));\n\t\t\t\tfor (const [key, value$1, valueSchema, valueDataset] of valueDatasets) if (valueDataset) {\n\t\t\t\t\tif (valueDataset.issues) {\n\t\t\t\t\t\tconst pathItem = {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\torigin: \"value\",\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\tvalue: value$1\n\t\t\t\t\t\t};\n\t\t\t\t\t\tfor (const issue of valueDataset.issues) {\n\t\t\t\t\t\t\tif (issue.path) issue.path.unshift(pathItem);\n\t\t\t\t\t\t\telse issue.path = [pathItem];\n\t\t\t\t\t\t\tdataset.issues?.push(issue);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!dataset.issues) dataset.issues = valueDataset.issues;\n\t\t\t\t\t\tif (config$1.abortEarly) {\n\t\t\t\t\t\t\tdataset.typed = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!valueDataset.typed) dataset.typed = false;\n\t\t\t\t\tdataset.value[key] = valueDataset.value;\n\t\t\t\t} else if (valueSchema.fallback !== void 0) dataset.value[key] = await /* @__PURE__ */ getFallback(valueSchema);\n\t\t\t\telse if (valueSchema.type !== \"exact_optional\" && valueSchema.type !== \"optional\" && valueSchema.type !== \"nullish\") {\n\t\t\t\t\t_addIssue(this, \"key\", dataset, config$1, {\n\t\t\t\t\t\tinput: void 0,\n\t\t\t\t\t\texpected: `\"${key}\"`,\n\t\t\t\t\t\tpath: [{\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\torigin: \"key\",\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\tvalue: value$1\n\t\t\t\t\t\t}]\n\t\t\t\t\t});\n\t\t\t\t\tif (config$1.abortEarly) break;\n\t\t\t\t}\n\t\t\t\tif (!dataset.issues || !config$1.abortEarly) {\n\t\t\t\t\tfor (const key in input) if (!(key in this.entries)) {\n\t\t\t\t\t\t_addIssue(this, \"key\", dataset, config$1, {\n\t\t\t\t\t\t\tinput: key,\n\t\t\t\t\t\t\texpected: \"never\",\n\t\t\t\t\t\t\tpath: [{\n\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\torigin: \"key\",\n\t\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\t\tvalue: input[key]\n\t\t\t\t\t\t\t}]\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/strictTuple/strictTuple.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction strictTuple(items, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"strict_tuple\",\n\t\treference: strictTuple,\n\t\texpects: \"Array\",\n\t\tasync: false,\n\t\titems,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tconst input = dataset.value;\n\t\t\tif (Array.isArray(input)) {\n\t\t\t\tdataset.typed = true;\n\t\t\t\tdataset.value = [];\n\t\t\t\tfor (let key = 0; key < this.items.length; key++) {\n\t\t\t\t\tconst value$1 = input[key];\n\t\t\t\t\tconst itemDataset = this.items[key][\"~run\"]({ value: value$1 }, config$1);\n\t\t\t\t\tif (itemDataset.issues) {\n\t\t\t\t\t\tconst pathItem = {\n\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\torigin: \"value\",\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\tvalue: value$1\n\t\t\t\t\t\t};\n\t\t\t\t\t\tfor (const issue of itemDataset.issues) {\n\t\t\t\t\t\t\tif (issue.path) issue.path.unshift(pathItem);\n\t\t\t\t\t\t\telse issue.path = [pathItem];\n\t\t\t\t\t\t\tdataset.issues?.push(issue);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!dataset.issues) dataset.issues = itemDataset.issues;\n\t\t\t\t\t\tif (config$1.abortEarly) {\n\t\t\t\t\t\t\tdataset.typed = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!itemDataset.typed) dataset.typed = false;\n\t\t\t\t\tdataset.value.push(itemDataset.value);\n\t\t\t\t}\n\t\t\t\tif (!(dataset.issues && config$1.abortEarly) && this.items.length < input.length) _addIssue(this, \"type\", dataset, config$1, {\n\t\t\t\t\tinput: input[this.items.length],\n\t\t\t\t\texpected: \"never\",\n\t\t\t\t\tpath: [{\n\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\torigin: \"value\",\n\t\t\t\t\t\tinput,\n\t\t\t\t\t\tkey: this.items.length,\n\t\t\t\t\t\tvalue: input[this.items.length]\n\t\t\t\t\t}]\n\t\t\t\t});\n\t\t\t} else _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/strictTuple/strictTupleAsync.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction strictTupleAsync(items, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"strict_tuple\",\n\t\treference: strictTupleAsync,\n\t\texpects: \"Array\",\n\t\tasync: true,\n\t\titems,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\tasync \"~run\"(dataset, config$1) {\n\t\t\tconst input = dataset.value;\n\t\t\tif (Array.isArray(input)) {\n\t\t\t\tdataset.typed = true;\n\t\t\t\tdataset.value = [];\n\t\t\t\tconst itemDatasets = await Promise.all(this.items.map(async (item, key) => {\n\t\t\t\t\tconst value$1 = input[key];\n\t\t\t\t\treturn [\n\t\t\t\t\t\tkey,\n\t\t\t\t\t\tvalue$1,\n\t\t\t\t\t\tawait item[\"~run\"]({ value: value$1 }, config$1)\n\t\t\t\t\t];\n\t\t\t\t}));\n\t\t\t\tfor (const [key, value$1, itemDataset] of itemDatasets) {\n\t\t\t\t\tif (itemDataset.issues) {\n\t\t\t\t\t\tconst pathItem = {\n\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\torigin: \"value\",\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\tvalue: value$1\n\t\t\t\t\t\t};\n\t\t\t\t\t\tfor (const issue of itemDataset.issues) {\n\t\t\t\t\t\t\tif (issue.path) issue.path.unshift(pathItem);\n\t\t\t\t\t\t\telse issue.path = [pathItem];\n\t\t\t\t\t\t\tdataset.issues?.push(issue);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!dataset.issues) dataset.issues = itemDataset.issues;\n\t\t\t\t\t\tif (config$1.abortEarly) {\n\t\t\t\t\t\t\tdataset.typed = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!itemDataset.typed) dataset.typed = false;\n\t\t\t\t\tdataset.value.push(itemDataset.value);\n\t\t\t\t}\n\t\t\t\tif (!(dataset.issues && config$1.abortEarly) && this.items.length < input.length) _addIssue(this, \"type\", dataset, config$1, {\n\t\t\t\t\tinput: input[this.items.length],\n\t\t\t\t\texpected: \"never\",\n\t\t\t\t\tpath: [{\n\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\torigin: \"value\",\n\t\t\t\t\t\tinput,\n\t\t\t\t\t\tkey: this.items.length,\n\t\t\t\t\t\tvalue: input[this.items.length]\n\t\t\t\t\t}]\n\t\t\t\t});\n\t\t\t} else _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/string/string.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction string(message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"string\",\n\t\treference: string,\n\t\texpects: \"string\",\n\t\tasync: false,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (typeof dataset.value === \"string\") dataset.typed = true;\n\t\t\telse _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/symbol/symbol.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction symbol(message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"symbol\",\n\t\treference: symbol,\n\t\texpects: \"symbol\",\n\t\tasync: false,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (typeof dataset.value === \"symbol\") dataset.typed = true;\n\t\t\telse _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/tuple/tuple.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction tuple(items, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"tuple\",\n\t\treference: tuple,\n\t\texpects: \"Array\",\n\t\tasync: false,\n\t\titems,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tconst input = dataset.value;\n\t\t\tif (Array.isArray(input)) {\n\t\t\t\tdataset.typed = true;\n\t\t\t\tdataset.value = [];\n\t\t\t\tfor (let key = 0; key < this.items.length; key++) {\n\t\t\t\t\tconst value$1 = input[key];\n\t\t\t\t\tconst itemDataset = this.items[key][\"~run\"]({ value: value$1 }, config$1);\n\t\t\t\t\tif (itemDataset.issues) {\n\t\t\t\t\t\tconst pathItem = {\n\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\torigin: \"value\",\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\tvalue: value$1\n\t\t\t\t\t\t};\n\t\t\t\t\t\tfor (const issue of itemDataset.issues) {\n\t\t\t\t\t\t\tif (issue.path) issue.path.unshift(pathItem);\n\t\t\t\t\t\t\telse issue.path = [pathItem];\n\t\t\t\t\t\t\tdataset.issues?.push(issue);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!dataset.issues) dataset.issues = itemDataset.issues;\n\t\t\t\t\t\tif (config$1.abortEarly) {\n\t\t\t\t\t\t\tdataset.typed = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!itemDataset.typed) dataset.typed = false;\n\t\t\t\t\tdataset.value.push(itemDataset.value);\n\t\t\t\t}\n\t\t\t} else _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/tuple/tupleAsync.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction tupleAsync(items, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"tuple\",\n\t\treference: tupleAsync,\n\t\texpects: \"Array\",\n\t\tasync: true,\n\t\titems,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\tasync \"~run\"(dataset, config$1) {\n\t\t\tconst input = dataset.value;\n\t\t\tif (Array.isArray(input)) {\n\t\t\t\tdataset.typed = true;\n\t\t\t\tdataset.value = [];\n\t\t\t\tconst itemDatasets = await Promise.all(this.items.map(async (item, key) => {\n\t\t\t\t\tconst value$1 = input[key];\n\t\t\t\t\treturn [\n\t\t\t\t\t\tkey,\n\t\t\t\t\t\tvalue$1,\n\t\t\t\t\t\tawait item[\"~run\"]({ value: value$1 }, config$1)\n\t\t\t\t\t];\n\t\t\t\t}));\n\t\t\t\tfor (const [key, value$1, itemDataset] of itemDatasets) {\n\t\t\t\t\tif (itemDataset.issues) {\n\t\t\t\t\t\tconst pathItem = {\n\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\torigin: \"value\",\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\tvalue: value$1\n\t\t\t\t\t\t};\n\t\t\t\t\t\tfor (const issue of itemDataset.issues) {\n\t\t\t\t\t\t\tif (issue.path) issue.path.unshift(pathItem);\n\t\t\t\t\t\t\telse issue.path = [pathItem];\n\t\t\t\t\t\t\tdataset.issues?.push(issue);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!dataset.issues) dataset.issues = itemDataset.issues;\n\t\t\t\t\t\tif (config$1.abortEarly) {\n\t\t\t\t\t\t\tdataset.typed = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!itemDataset.typed) dataset.typed = false;\n\t\t\t\t\tdataset.value.push(itemDataset.value);\n\t\t\t\t}\n\t\t\t} else _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/tupleWithRest/tupleWithRest.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction tupleWithRest(items, rest, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"tuple_with_rest\",\n\t\treference: tupleWithRest,\n\t\texpects: \"Array\",\n\t\tasync: false,\n\t\titems,\n\t\trest,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tconst input = dataset.value;\n\t\t\tif (Array.isArray(input)) {\n\t\t\t\tdataset.typed = true;\n\t\t\t\tdataset.value = [];\n\t\t\t\tfor (let key = 0; key < this.items.length; key++) {\n\t\t\t\t\tconst value$1 = input[key];\n\t\t\t\t\tconst itemDataset = this.items[key][\"~run\"]({ value: value$1 }, config$1);\n\t\t\t\t\tif (itemDataset.issues) {\n\t\t\t\t\t\tconst pathItem = {\n\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\torigin: \"value\",\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\tvalue: value$1\n\t\t\t\t\t\t};\n\t\t\t\t\t\tfor (const issue of itemDataset.issues) {\n\t\t\t\t\t\t\tif (issue.path) issue.path.unshift(pathItem);\n\t\t\t\t\t\t\telse issue.path = [pathItem];\n\t\t\t\t\t\t\tdataset.issues?.push(issue);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!dataset.issues) dataset.issues = itemDataset.issues;\n\t\t\t\t\t\tif (config$1.abortEarly) {\n\t\t\t\t\t\t\tdataset.typed = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!itemDataset.typed) dataset.typed = false;\n\t\t\t\t\tdataset.value.push(itemDataset.value);\n\t\t\t\t}\n\t\t\t\tif (!dataset.issues || !config$1.abortEarly) for (let key = this.items.length; key < input.length; key++) {\n\t\t\t\t\tconst value$1 = input[key];\n\t\t\t\t\tconst itemDataset = this.rest[\"~run\"]({ value: value$1 }, config$1);\n\t\t\t\t\tif (itemDataset.issues) {\n\t\t\t\t\t\tconst pathItem = {\n\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\torigin: \"value\",\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\tvalue: value$1\n\t\t\t\t\t\t};\n\t\t\t\t\t\tfor (const issue of itemDataset.issues) {\n\t\t\t\t\t\t\tif (issue.path) issue.path.unshift(pathItem);\n\t\t\t\t\t\t\telse issue.path = [pathItem];\n\t\t\t\t\t\t\tdataset.issues?.push(issue);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!dataset.issues) dataset.issues = itemDataset.issues;\n\t\t\t\t\t\tif (config$1.abortEarly) {\n\t\t\t\t\t\t\tdataset.typed = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!itemDataset.typed) dataset.typed = false;\n\t\t\t\t\tdataset.value.push(itemDataset.value);\n\t\t\t\t}\n\t\t\t} else _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/tupleWithRest/tupleWithRestAsync.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction tupleWithRestAsync(items, rest, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"tuple_with_rest\",\n\t\treference: tupleWithRestAsync,\n\t\texpects: \"Array\",\n\t\tasync: true,\n\t\titems,\n\t\trest,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\tasync \"~run\"(dataset, config$1) {\n\t\t\tconst input = dataset.value;\n\t\t\tif (Array.isArray(input)) {\n\t\t\t\tdataset.typed = true;\n\t\t\t\tdataset.value = [];\n\t\t\t\tconst [normalDatasets, restDatasets] = await Promise.all([Promise.all(this.items.map(async (item, key) => {\n\t\t\t\t\tconst value$1 = input[key];\n\t\t\t\t\treturn [\n\t\t\t\t\t\tkey,\n\t\t\t\t\t\tvalue$1,\n\t\t\t\t\t\tawait item[\"~run\"]({ value: value$1 }, config$1)\n\t\t\t\t\t];\n\t\t\t\t})), Promise.all(input.slice(this.items.length).map(async (value$1, key) => {\n\t\t\t\t\treturn [\n\t\t\t\t\t\tkey + this.items.length,\n\t\t\t\t\t\tvalue$1,\n\t\t\t\t\t\tawait this.rest[\"~run\"]({ value: value$1 }, config$1)\n\t\t\t\t\t];\n\t\t\t\t}))]);\n\t\t\t\tfor (const [key, value$1, itemDataset] of normalDatasets) {\n\t\t\t\t\tif (itemDataset.issues) {\n\t\t\t\t\t\tconst pathItem = {\n\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\torigin: \"value\",\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\tvalue: value$1\n\t\t\t\t\t\t};\n\t\t\t\t\t\tfor (const issue of itemDataset.issues) {\n\t\t\t\t\t\t\tif (issue.path) issue.path.unshift(pathItem);\n\t\t\t\t\t\t\telse issue.path = [pathItem];\n\t\t\t\t\t\t\tdataset.issues?.push(issue);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!dataset.issues) dataset.issues = itemDataset.issues;\n\t\t\t\t\t\tif (config$1.abortEarly) {\n\t\t\t\t\t\t\tdataset.typed = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!itemDataset.typed) dataset.typed = false;\n\t\t\t\t\tdataset.value.push(itemDataset.value);\n\t\t\t\t}\n\t\t\t\tif (!dataset.issues || !config$1.abortEarly) for (const [key, value$1, itemDataset] of restDatasets) {\n\t\t\t\t\tif (itemDataset.issues) {\n\t\t\t\t\t\tconst pathItem = {\n\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\torigin: \"value\",\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\tvalue: value$1\n\t\t\t\t\t\t};\n\t\t\t\t\t\tfor (const issue of itemDataset.issues) {\n\t\t\t\t\t\t\tif (issue.path) issue.path.unshift(pathItem);\n\t\t\t\t\t\t\telse issue.path = [pathItem];\n\t\t\t\t\t\t\tdataset.issues?.push(issue);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!dataset.issues) dataset.issues = itemDataset.issues;\n\t\t\t\t\t\tif (config$1.abortEarly) {\n\t\t\t\t\t\t\tdataset.typed = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!itemDataset.typed) dataset.typed = false;\n\t\t\t\t\tdataset.value.push(itemDataset.value);\n\t\t\t\t}\n\t\t\t} else _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/undefined/undefined.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction undefined_(message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"undefined\",\n\t\treference: undefined_,\n\t\texpects: \"undefined\",\n\t\tasync: false,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.value === void 0) dataset.typed = true;\n\t\t\telse _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/undefinedable/undefinedable.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction undefinedable(wrapped, default_) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"undefinedable\",\n\t\treference: undefinedable,\n\t\texpects: `(${wrapped.expects} | undefined)`,\n\t\tasync: false,\n\t\twrapped,\n\t\tdefault: default_,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.value === void 0) {\n\t\t\t\tif (this.default !== void 0) dataset.value = /* @__PURE__ */ getDefault(this, dataset, config$1);\n\t\t\t\tif (dataset.value === void 0) {\n\t\t\t\t\tdataset.typed = true;\n\t\t\t\t\treturn dataset;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn this.wrapped[\"~run\"](dataset, config$1);\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/undefinedable/undefinedableAsync.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction undefinedableAsync(wrapped, default_) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"undefinedable\",\n\t\treference: undefinedableAsync,\n\t\texpects: `(${wrapped.expects} | undefined)`,\n\t\tasync: true,\n\t\twrapped,\n\t\tdefault: default_,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\tasync \"~run\"(dataset, config$1) {\n\t\t\tif (dataset.value === void 0) {\n\t\t\t\tif (this.default !== void 0) dataset.value = await /* @__PURE__ */ getDefault(this, dataset, config$1);\n\t\t\t\tif (dataset.value === void 0) {\n\t\t\t\t\tdataset.typed = true;\n\t\t\t\t\treturn dataset;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn this.wrapped[\"~run\"](dataset, config$1);\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/union/utils/_subIssues/_subIssues.ts\n/**\n* Returns the sub issues of the provided datasets for the union issue.\n*\n* @param datasets The datasets.\n*\n* @returns The sub issues.\n*\n* @internal\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction _subIssues(datasets) {\n\tlet issues;\n\tif (datasets) for (const dataset of datasets) if (issues) for (const issue of dataset.issues) issues.push(issue);\n\telse issues = dataset.issues;\n\treturn issues;\n}\n\n//#endregion\n//#region src/schemas/union/union.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction union(options, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"union\",\n\t\treference: union,\n\t\texpects: /* @__PURE__ */ _joinExpects(options.map((option) => option.expects), \"|\"),\n\t\tasync: false,\n\t\toptions,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tlet validDataset;\n\t\t\tlet typedDatasets;\n\t\t\tlet untypedDatasets;\n\t\t\tfor (const schema of this.options) {\n\t\t\t\tconst optionDataset = schema[\"~run\"]({ value: dataset.value }, config$1);\n\t\t\t\tif (optionDataset.typed) if (optionDataset.issues) if (typedDatasets) typedDatasets.push(optionDataset);\n\t\t\t\telse typedDatasets = [optionDataset];\n\t\t\t\telse {\n\t\t\t\t\tvalidDataset = optionDataset;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\telse if (untypedDatasets) untypedDatasets.push(optionDataset);\n\t\t\t\telse untypedDatasets = [optionDataset];\n\t\t\t}\n\t\t\tif (validDataset) return validDataset;\n\t\t\tif (typedDatasets) {\n\t\t\t\tif (typedDatasets.length === 1) return typedDatasets[0];\n\t\t\t\t_addIssue(this, \"type\", dataset, config$1, { issues: /* @__PURE__ */ _subIssues(typedDatasets) });\n\t\t\t\tdataset.typed = true;\n\t\t\t} else if (untypedDatasets?.length === 1) return untypedDatasets[0];\n\t\t\telse _addIssue(this, \"type\", dataset, config$1, { issues: /* @__PURE__ */ _subIssues(untypedDatasets) });\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/union/unionAsync.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction unionAsync(options, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"union\",\n\t\treference: unionAsync,\n\t\texpects: /* @__PURE__ */ _joinExpects(options.map((option) => option.expects), \"|\"),\n\t\tasync: true,\n\t\toptions,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\tasync \"~run\"(dataset, config$1) {\n\t\t\tlet validDataset;\n\t\t\tlet typedDatasets;\n\t\t\tlet untypedDatasets;\n\t\t\tfor (const schema of this.options) {\n\t\t\t\tconst optionDataset = await schema[\"~run\"]({ value: dataset.value }, config$1);\n\t\t\t\tif (optionDataset.typed) if (optionDataset.issues) if (typedDatasets) typedDatasets.push(optionDataset);\n\t\t\t\telse typedDatasets = [optionDataset];\n\t\t\t\telse {\n\t\t\t\t\tvalidDataset = optionDataset;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\telse if (untypedDatasets) untypedDatasets.push(optionDataset);\n\t\t\t\telse untypedDatasets = [optionDataset];\n\t\t\t}\n\t\t\tif (validDataset) return validDataset;\n\t\t\tif (typedDatasets) {\n\t\t\t\tif (typedDatasets.length === 1) return typedDatasets[0];\n\t\t\t\t_addIssue(this, \"type\", dataset, config$1, { issues: /* @__PURE__ */ _subIssues(typedDatasets) });\n\t\t\t\tdataset.typed = true;\n\t\t\t} else if (untypedDatasets?.length === 1) return untypedDatasets[0];\n\t\t\telse _addIssue(this, \"type\", dataset, config$1, { issues: /* @__PURE__ */ _subIssues(untypedDatasets) });\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/unknown/unknown.ts\n/**\n* Creates a unknown schema.\n*\n* @returns A unknown schema.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction unknown() {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"unknown\",\n\t\treference: unknown,\n\t\texpects: \"unknown\",\n\t\tasync: false,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset) {\n\t\t\tdataset.typed = true;\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/variant/variant.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction variant(key, options, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"variant\",\n\t\treference: variant,\n\t\texpects: \"Object\",\n\t\tasync: false,\n\t\tkey,\n\t\toptions,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tconst input = dataset.value;\n\t\t\tif (input && typeof input === \"object\") {\n\t\t\t\tlet outputDataset;\n\t\t\t\tlet maxDiscriminatorPriority = 0;\n\t\t\t\tlet invalidDiscriminatorKey = this.key;\n\t\t\t\tlet expectedDiscriminators = [];\n\t\t\t\tconst parseOptions = (variant$1, allKeys) => {\n\t\t\t\t\tfor (const schema of variant$1.options) {\n\t\t\t\t\t\tif (schema.type === \"variant\") parseOptions(schema, new Set(allKeys).add(schema.key));\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tlet keysAreValid = true;\n\t\t\t\t\t\t\tlet currentPriority = 0;\n\t\t\t\t\t\t\tfor (const currentKey of allKeys) {\n\t\t\t\t\t\t\t\tconst discriminatorSchema = schema.entries[currentKey];\n\t\t\t\t\t\t\t\tif (currentKey in input ? discriminatorSchema[\"~run\"]({\n\t\t\t\t\t\t\t\t\ttyped: false,\n\t\t\t\t\t\t\t\t\tvalue: input[currentKey]\n\t\t\t\t\t\t\t\t}, ABORT_EARLY_CONFIG).issues : discriminatorSchema.type !== \"exact_optional\" && discriminatorSchema.type !== \"optional\" && discriminatorSchema.type !== \"nullish\") {\n\t\t\t\t\t\t\t\t\tkeysAreValid = false;\n\t\t\t\t\t\t\t\t\tif (invalidDiscriminatorKey !== currentKey && (maxDiscriminatorPriority < currentPriority || maxDiscriminatorPriority === currentPriority && currentKey in input && !(invalidDiscriminatorKey in input))) {\n\t\t\t\t\t\t\t\t\t\tmaxDiscriminatorPriority = currentPriority;\n\t\t\t\t\t\t\t\t\t\tinvalidDiscriminatorKey = currentKey;\n\t\t\t\t\t\t\t\t\t\texpectedDiscriminators = [];\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif (invalidDiscriminatorKey === currentKey) expectedDiscriminators.push(schema.entries[currentKey].expects);\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcurrentPriority++;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (keysAreValid) {\n\t\t\t\t\t\t\t\tconst optionDataset = schema[\"~run\"]({ value: input }, config$1);\n\t\t\t\t\t\t\t\tif (!outputDataset || !outputDataset.typed && optionDataset.typed) outputDataset = optionDataset;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (outputDataset && !outputDataset.issues) break;\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\tparseOptions(this, new Set([this.key]));\n\t\t\t\tif (outputDataset) return outputDataset;\n\t\t\t\t_addIssue(this, \"type\", dataset, config$1, {\n\t\t\t\t\tinput: input[invalidDiscriminatorKey],\n\t\t\t\t\texpected: /* @__PURE__ */ _joinExpects(expectedDiscriminators, \"|\"),\n\t\t\t\t\tpath: [{\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\torigin: \"value\",\n\t\t\t\t\t\tinput,\n\t\t\t\t\t\tkey: invalidDiscriminatorKey,\n\t\t\t\t\t\tvalue: input[invalidDiscriminatorKey]\n\t\t\t\t\t}]\n\t\t\t\t});\n\t\t\t} else _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/variant/variantAsync.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction variantAsync(key, options, message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"variant\",\n\t\treference: variantAsync,\n\t\texpects: \"Object\",\n\t\tasync: true,\n\t\tkey,\n\t\toptions,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\tasync \"~run\"(dataset, config$1) {\n\t\t\tconst input = dataset.value;\n\t\t\tif (input && typeof input === \"object\") {\n\t\t\t\tlet outputDataset;\n\t\t\t\tlet maxDiscriminatorPriority = 0;\n\t\t\t\tlet invalidDiscriminatorKey = this.key;\n\t\t\t\tlet expectedDiscriminators = [];\n\t\t\t\tconst parseOptions = async (variant$1, allKeys) => {\n\t\t\t\t\tfor (const schema of variant$1.options) {\n\t\t\t\t\t\tif (schema.type === \"variant\") await parseOptions(schema, new Set(allKeys).add(schema.key));\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tlet keysAreValid = true;\n\t\t\t\t\t\t\tlet currentPriority = 0;\n\t\t\t\t\t\t\tfor (const currentKey of allKeys) {\n\t\t\t\t\t\t\t\tconst discriminatorSchema = schema.entries[currentKey];\n\t\t\t\t\t\t\t\tif (currentKey in input ? (await discriminatorSchema[\"~run\"]({\n\t\t\t\t\t\t\t\t\ttyped: false,\n\t\t\t\t\t\t\t\t\tvalue: input[currentKey]\n\t\t\t\t\t\t\t\t}, ABORT_EARLY_CONFIG)).issues : discriminatorSchema.type !== \"exact_optional\" && discriminatorSchema.type !== \"optional\" && discriminatorSchema.type !== \"nullish\") {\n\t\t\t\t\t\t\t\t\tkeysAreValid = false;\n\t\t\t\t\t\t\t\t\tif (invalidDiscriminatorKey !== currentKey && (maxDiscriminatorPriority < currentPriority || maxDiscriminatorPriority === currentPriority && currentKey in input && !(invalidDiscriminatorKey in input))) {\n\t\t\t\t\t\t\t\t\t\tmaxDiscriminatorPriority = currentPriority;\n\t\t\t\t\t\t\t\t\t\tinvalidDiscriminatorKey = currentKey;\n\t\t\t\t\t\t\t\t\t\texpectedDiscriminators = [];\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif (invalidDiscriminatorKey === currentKey) expectedDiscriminators.push(schema.entries[currentKey].expects);\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcurrentPriority++;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (keysAreValid) {\n\t\t\t\t\t\t\t\tconst optionDataset = await schema[\"~run\"]({ value: input }, config$1);\n\t\t\t\t\t\t\t\tif (!outputDataset || !outputDataset.typed && optionDataset.typed) outputDataset = optionDataset;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (outputDataset && !outputDataset.issues) break;\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\tawait parseOptions(this, new Set([this.key]));\n\t\t\t\tif (outputDataset) return outputDataset;\n\t\t\t\t_addIssue(this, \"type\", dataset, config$1, {\n\t\t\t\t\tinput: input[invalidDiscriminatorKey],\n\t\t\t\t\texpected: /* @__PURE__ */ _joinExpects(expectedDiscriminators, \"|\"),\n\t\t\t\t\tpath: [{\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\torigin: \"value\",\n\t\t\t\t\t\tinput,\n\t\t\t\t\t\tkey: invalidDiscriminatorKey,\n\t\t\t\t\t\tvalue: input[invalidDiscriminatorKey]\n\t\t\t\t\t}]\n\t\t\t\t});\n\t\t\t} else _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/schemas/void/void.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction void_(message$1) {\n\treturn {\n\t\tkind: \"schema\",\n\t\ttype: \"void\",\n\t\treference: void_,\n\t\texpects: \"void\",\n\t\tasync: false,\n\t\tmessage: message$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tif (dataset.value === void 0) dataset.typed = true;\n\t\t\telse _addIssue(this, \"type\", dataset, config$1);\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/methods/keyof/keyof.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction keyof(schema, message$1) {\n\treturn /* @__PURE__ */ picklist(Object.keys(schema.entries), message$1);\n}\n\n//#endregion\n//#region src/methods/message/message.ts\n/**\n* Changes the local message configuration of a schema.\n*\n* @param schema The schema to configure.\n* @param message_ The error message.\n*\n* @returns The configured schema.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction message(schema, message_) {\n\treturn {\n\t\t...schema,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\treturn schema[\"~run\"](dataset, {\n\t\t\t\t...config$1,\n\t\t\t\tmessage: message_\n\t\t\t});\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/methods/omit/omit.ts\n/**\n* Creates a modified copy of an object schema that does not contain the\n* selected entries.\n*\n* @param schema The schema to omit from.\n* @param keys The selected entries.\n*\n* @returns An object schema.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction omit(schema, keys) {\n\tconst entries$1 = { ...schema.entries };\n\tfor (const key of keys) delete entries$1[key];\n\treturn {\n\t\t...schema,\n\t\tentries: entries$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/methods/parse/parse.ts\n/**\n* Parses an unknown input based on a schema.\n*\n* @param schema The schema to be used.\n* @param input The input to be parsed.\n* @param config The parse configuration.\n*\n* @returns The parsed input.\n*/\nfunction parse(schema, input, config$1) {\n\tconst dataset = schema[\"~run\"]({ value: input }, /* @__PURE__ */ getGlobalConfig(config$1));\n\tif (dataset.issues) throw new ValiError(dataset.issues);\n\treturn dataset.value;\n}\n\n//#endregion\n//#region src/methods/parse/parseAsync.ts\n/**\n* Parses an unknown input based on a schema.\n*\n* @param schema The schema to be used.\n* @param input The input to be parsed.\n* @param config The parse configuration.\n*\n* @returns The parsed input.\n*/\nasync function parseAsync(schema, input, config$1) {\n\tconst dataset = await schema[\"~run\"]({ value: input }, /* @__PURE__ */ getGlobalConfig(config$1));\n\tif (dataset.issues) throw new ValiError(dataset.issues);\n\treturn dataset.value;\n}\n\n//#endregion\n//#region src/methods/parser/parser.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction parser(schema, config$1) {\n\tconst func = (input) => parse(schema, input, config$1);\n\tfunc.schema = schema;\n\tfunc.config = config$1;\n\treturn func;\n}\n\n//#endregion\n//#region src/methods/parser/parserAsync.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction parserAsync(schema, config$1) {\n\tconst func = (input) => parseAsync(schema, input, config$1);\n\tfunc.schema = schema;\n\tfunc.config = config$1;\n\treturn func;\n}\n\n//#endregion\n//#region src/methods/partial/partial.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction partial(schema, keys) {\n\tconst entries$1 = {};\n\tfor (const key in schema.entries) entries$1[key] = !keys || keys.includes(key) ? /* @__PURE__ */ optional(schema.entries[key]) : schema.entries[key];\n\treturn {\n\t\t...schema,\n\t\tentries: entries$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/methods/partial/partialAsync.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction partialAsync(schema, keys) {\n\tconst entries$1 = {};\n\tfor (const key in schema.entries) entries$1[key] = !keys || keys.includes(key) ? /* @__PURE__ */ optionalAsync(schema.entries[key]) : schema.entries[key];\n\treturn {\n\t\t...schema,\n\t\tentries: entries$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/methods/pick/pick.ts\n/**\n* Creates a modified copy of an object schema that contains only the selected\n* entries.\n*\n* @param schema The schema to pick from.\n* @param keys The selected entries.\n*\n* @returns An object schema.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction pick(schema, keys) {\n\tconst entries$1 = {};\n\tfor (const key of keys) entries$1[key] = schema.entries[key];\n\treturn {\n\t\t...schema,\n\t\tentries: entries$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/methods/pipe/pipe.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction pipe(...pipe$1) {\n\treturn {\n\t\t...pipe$1[0],\n\t\tpipe: pipe$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\t\"~run\"(dataset, config$1) {\n\t\t\tfor (const item of pipe$1) if (item.kind !== \"metadata\") {\n\t\t\t\tif (dataset.issues && (item.kind === \"schema\" || item.kind === \"transformation\")) {\n\t\t\t\t\tdataset.typed = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (!dataset.issues || !config$1.abortEarly && !config$1.abortPipeEarly) dataset = item[\"~run\"](dataset, config$1);\n\t\t\t}\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/methods/pipe/pipeAsync.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction pipeAsync(...pipe$1) {\n\treturn {\n\t\t...pipe$1[0],\n\t\tpipe: pipe$1,\n\t\tasync: true,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t},\n\t\tasync \"~run\"(dataset, config$1) {\n\t\t\tfor (const item of pipe$1) if (item.kind !== \"metadata\") {\n\t\t\t\tif (dataset.issues && (item.kind === \"schema\" || item.kind === \"transformation\")) {\n\t\t\t\t\tdataset.typed = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (!dataset.issues || !config$1.abortEarly && !config$1.abortPipeEarly) dataset = await item[\"~run\"](dataset, config$1);\n\t\t\t}\n\t\t\treturn dataset;\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/methods/required/required.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction required(schema, arg2, arg3) {\n\tconst keys = Array.isArray(arg2) ? arg2 : void 0;\n\tconst message$1 = Array.isArray(arg2) ? arg3 : arg2;\n\tconst entries$1 = {};\n\tfor (const key in schema.entries) entries$1[key] = !keys || keys.includes(key) ? /* @__PURE__ */ nonOptional(schema.entries[key], message$1) : schema.entries[key];\n\treturn {\n\t\t...schema,\n\t\tentries: entries$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/methods/required/requiredAsync.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction requiredAsync(schema, arg2, arg3) {\n\tconst keys = Array.isArray(arg2) ? arg2 : void 0;\n\tconst message$1 = Array.isArray(arg2) ? arg3 : arg2;\n\tconst entries$1 = {};\n\tfor (const key in schema.entries) entries$1[key] = !keys || keys.includes(key) ? /* @__PURE__ */ nonOptionalAsync(schema.entries[key], message$1) : schema.entries[key];\n\treturn {\n\t\t...schema,\n\t\tentries: entries$1,\n\t\tget \"~standard\"() {\n\t\t\treturn /* @__PURE__ */ _getStandardProps(this);\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/methods/safeParse/safeParse.ts\n/**\n* Parses an unknown input based on a schema.\n*\n* @param schema The schema to be used.\n* @param input The input to be parsed.\n* @param config The parse configuration.\n*\n* @returns The parse result.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction safeParse(schema, input, config$1) {\n\tconst dataset = schema[\"~run\"]({ value: input }, /* @__PURE__ */ getGlobalConfig(config$1));\n\treturn {\n\t\ttyped: dataset.typed,\n\t\tsuccess: !dataset.issues,\n\t\toutput: dataset.value,\n\t\tissues: dataset.issues\n\t};\n}\n\n//#endregion\n//#region src/methods/safeParse/safeParseAsync.ts\n/**\n* Parses an unknown input based on a schema.\n*\n* @param schema The schema to be used.\n* @param input The input to be parsed.\n* @param config The parse configuration.\n*\n* @returns The parse result.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nasync function safeParseAsync(schema, input, config$1) {\n\tconst dataset = await schema[\"~run\"]({ value: input }, /* @__PURE__ */ getGlobalConfig(config$1));\n\treturn {\n\t\ttyped: dataset.typed,\n\t\tsuccess: !dataset.issues,\n\t\toutput: dataset.value,\n\t\tissues: dataset.issues\n\t};\n}\n\n//#endregion\n//#region src/methods/safeParser/safeParser.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction safeParser(schema, config$1) {\n\tconst func = (input) => /* @__PURE__ */ safeParse(schema, input, config$1);\n\tfunc.schema = schema;\n\tfunc.config = config$1;\n\treturn func;\n}\n\n//#endregion\n//#region src/methods/safeParser/safeParserAsync.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction safeParserAsync(schema, config$1) {\n\tconst func = (input) => /* @__PURE__ */ safeParseAsync(schema, input, config$1);\n\tfunc.schema = schema;\n\tfunc.config = config$1;\n\treturn func;\n}\n\n//#endregion\n//#region src/methods/summarize/summarize.ts\n/**\n* Summarize the error messages of issues in a pretty-printable multi-line string.\n*\n* @param issues The list of issues.\n*\n* @returns A summary of the issues.\n*\n* @beta\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction summarize(issues) {\n\tlet summary = \"\";\n\tfor (const issue of issues) {\n\t\tif (summary) summary += \"\\n\";\n\t\tsummary += `× ${issue.message}`;\n\t\tconst dotPath = /* @__PURE__ */ getDotPath(issue);\n\t\tif (dotPath) summary += `\\n  → at ${dotPath}`;\n\t}\n\treturn summary;\n}\n\n//#endregion\n//#region src/methods/unwrap/unwrap.ts\n/**\n* Unwraps the wrapped schema.\n*\n* @param schema The schema to be unwrapped.\n*\n* @returns The unwrapped schema.\n*/\n/* @__NO_SIDE_EFFECTS__ */\nfunction unwrap(schema) {\n\treturn schema.wrapped;\n}\n\n//#endregion\nexport { BASE64_REGEX, BIC_REGEX, CUID2_REGEX, DECIMAL_REGEX, DIGITS_REGEX, DOMAIN_REGEX, EMAIL_REGEX, EMOJI_REGEX, HEXADECIMAL_REGEX, HEX_COLOR_REGEX, IMEI_REGEX, IPV4_REGEX, IPV6_REGEX, IP_REGEX, ISO_DATE_REGEX, ISO_DATE_TIME_REGEX, ISO_DATE_TIME_SECOND_REGEX, ISO_TIMESTAMP_REGEX, ISO_TIME_REGEX, ISO_TIME_SECOND_REGEX, ISO_WEEK_REGEX, ISRC_REGEX, JWS_COMPACT_REGEX, MAC48_REGEX, MAC64_REGEX, MAC_REGEX, NANO_ID_REGEX, OCTAL_REGEX, RFC_EMAIL_REGEX, SLUG_REGEX, ULID_REGEX, UUID_REGEX, ValiError, _addIssue, _cloneDataset, _formatCase, _getByteCount, _getGraphemeCount, _getLastMetadata, _getStandardProps, _getWordCount, _isLuhnAlgo, _isValidObjectKey, _joinExpects, _stringify, any, args, argsAsync, array, arrayAsync, assert, awaitAsync, base64, bic, bigint, blob, boolean, brand, bytes, cache, cacheAsync, check, checkAsync, checkItems, checkItemsAsync, config, creditCard, cuid2, custom, customAsync, date, decimal, deleteGlobalConfig, deleteGlobalMessage, deleteSchemaMessage, deleteSpecificMessage, description, digits, domain, email, emoji, empty, endsWith, entries, entriesFromList, entriesFromObjects, enum_ as enum, enum_, everyItem, exactOptional, exactOptionalAsync, examples, excludes, fallback, fallbackAsync, file, filterItems, findItem, finite, flatten, flavor, forward, forwardAsync, function_ as function, function_, getDefault, getDefaults, getDefaultsAsync, getDescription, getDotPath, getExamples, getFallback, getFallbacks, getFallbacksAsync, getGlobalConfig, getGlobalMessage, getMetadata, getSchemaMessage, getSpecificMessage, getTitle, graphemes, gtValue, guard, hash, hexColor, hexadecimal, imei, includes, instance, integer, intersect, intersectAsync, ip, ipv4, ipv6, is, isOfKind, isOfType, isValiError, isbn, isoDate, isoDateTime, isoDateTimeSecond, isoTime, isoTimeSecond, isoTimestamp, isoWeek, isrc, jwsCompact, keyof, lazy, lazyAsync, length, literal, looseObject, looseObjectAsync, looseTuple, looseTupleAsync, ltValue, mac, mac48, mac64, map, mapAsync, mapItems, maxBytes, maxEntries, maxGraphemes, maxLength, maxSize, maxValue, maxWords, message, metadata, mimeType, minBytes, minEntries, minGraphemes, minLength, minSize, minValue, minWords, multipleOf, nan, nanoid, never, nonEmpty, nonNullable, nonNullableAsync, nonNullish, nonNullishAsync, nonOptional, nonOptionalAsync, normalize, notBytes, notEntries, notGraphemes, notLength, notSize, notValue, notValues, notWords, null_ as null, null_, nullable, nullableAsync, nullish, nullishAsync, number, object, objectAsync, objectWithRest, objectWithRestAsync, octal, omit, optional, optionalAsync, parse, parseAsync, parseBoolean, parseJson, parser, parserAsync, partial, partialAsync, partialCheck, partialCheckAsync, pick, picklist, pipe, pipeAsync, promise, rawCheck, rawCheckAsync, rawTransform, rawTransformAsync, readonly, record, recordAsync, reduceItems, regex, required, requiredAsync, returns, returnsAsync, rfcEmail, safeInteger, safeParse, safeParseAsync, safeParser, safeParserAsync, set, setAsync, setGlobalConfig, setGlobalMessage, setSchemaMessage, setSpecificMessage, size, slug, someItem, sortItems, startsWith, strictObject, strictObjectAsync, strictTuple, strictTupleAsync, string, stringifyJson, summarize, symbol, title, toBigint, toBoolean, toCamelCase, toDate, toKebabCase, toLowerCase, toMaxValue, toMinValue, toNumber, toPascalCase, toSnakeCase, toString, toUpperCase, transform, transformAsync, trim, trimEnd, trimStart, tuple, tupleAsync, tupleWithRest, tupleWithRestAsync, ulid, undefined_ as undefined, undefined_, undefinedable, undefinedableAsync, union, unionAsync, unknown, unwrap, url, uuid, value, values, variant, variantAsync, void_ as void, void_, words };","import * as v from \"valibot\";\n\n// export const vBase64HashSha256 = v.pipe(v.string(), v.base64());\nexport const vBase64 = v.pipe(v.string(), v.base64());\n\nexport const vCreateSchema_TypePrefixedDataString = <P extends string>(\n  typeValues: P[],\n  typeKind: string,\n) => {\n  const _typeKind = typeKind ?? \"data_type\";\n\n  return v.pipe(\n    v.custom<`${P}::${string}`>(\n      (input) => {\n        return (\n          typeof input === \"string\" && typeValues.some((prefix) => input.startsWith(`${prefix}::`))\n        );\n      },\n      `Invalid format, expected '<${_typeKind}>::<value>' where \"${_typeKind}\" is one of [${typeValues.join(\", \")}] and \"value\" is a string of base64-encoded data of that type`,\n    ),\n  );\n};\n\nexport interface ICreateTypePrefixedDataStringResult<T extends string, F extends string> {\n  type: T;\n  format: F;\n  typeKind: string;\n  formatKind?: string;\n  transformJson?: boolean;\n}\n\nexport const vCreateSchema_TypeAndFormatPrefixedDataString = <T extends string, F extends string>({\n  type,\n  format,\n  typeKind,\n  formatKind,\n  // transformJson = false,\n}: ICreateTypePrefixedDataStringResult<T, F>) => {\n  const _typeKind = typeKind ?? \"data_type\";\n  const _formatKind = formatKind ?? \"data_format\";\n\n  return v.pipe(\n    v.custom<`${T}::${F}::${string}`>((input) => {\n      if (typeof input !== \"string\") return false;\n\n      const [typePart, formatPart, dataPart] = input.split(\"::\") as [string, string, string];\n\n      return typePart === type && formatPart === format && typeof dataPart === \"string\";\n    }, `Invalid format, expected '<${_typeKind}>::<${_formatKind}>::<value>' where \"${_typeKind}\" is \"${type}\", \"${_formatKind}\" is \"${format}\", and \"value\" is a string in the specified format`),\n  );\n};\n\nexport const vCreateSchema_TypeAndId = <S extends string>(dataType: S | S[]) =>\n  v.pipe(\n    v.custom<`${S}::${string}`>((input) => {\n      if (typeof input !== \"string\") {\n        return false;\n      }\n\n      let checkDataTypes: string[];\n\n      if (typeof dataType === \"string\") {\n        checkDataTypes = [dataType];\n      } else if (Array.isArray(dataType)) {\n        checkDataTypes = dataType;\n      } else {\n        throw new Error(\n          \"Create Schema for TypeAndId: dataType must be a string or an array of strings\",\n        );\n      }\n\n      if (checkDataTypes.length > 0) {\n        return true;\n      }\n\n      for (const dataTypeCheck in checkDataTypes) {\n        if (input.startsWith(`${dataTypeCheck}::`)) return true;\n      }\n\n      return false;\n    }, `Invalid Type and ID formatted string, expected '<data_type>::<id>'`),\n  );\n\nexport type TTypeAndId<S extends string = string> = `${S}::${string}`;\n","import * as v from \"valibot\";\nimport {\n  vBase64,\n  vCreateSchema_TypeAndFormatPrefixedDataString,\n} from \"../core/core_valibot_schemas\";\n\nexport enum ECryptoKeyAlgo {\n  ed25519 = \"ed25519\",\n  x25519 = \"x25519\",\n}\n\nexport enum ECryptoKeyFormat {\n  raw_base64 = \"raw_base64\",\n  jwk = \"jwk\",\n}\n\nexport const vSerializedCryptoKeyDataEd25519_Raw = vCreateSchema_TypeAndFormatPrefixedDataString<\n  ECryptoKeyAlgo.ed25519,\n  ECryptoKeyFormat.raw_base64\n>({\n  format: ECryptoKeyFormat.raw_base64,\n  type: ECryptoKeyAlgo.ed25519,\n  typeKind: \"algo\",\n});\n\nexport const vSerializedCryptoKeyDataEd25519_Jwk = vCreateSchema_TypeAndFormatPrefixedDataString<\n  ECryptoKeyAlgo.ed25519,\n  ECryptoKeyFormat.jwk\n>({\n  format: ECryptoKeyFormat.jwk,\n  type: ECryptoKeyAlgo.ed25519,\n  typeKind: \"algo\",\n  transformJson: true,\n});\n\nexport type TSerializedCryptoKeyData_Ed25519_Raw = v.InferInput<\n  typeof vSerializedCryptoKeyDataEd25519_Raw\n>;\n\nexport type TSerializedCryptoKeyData_Ed25519_Raw_Transformed = {\n  formattedString: `${ECryptoKeyAlgo.ed25519}::${ECryptoKeyFormat.raw_base64}::${string}`;\n  type: ECryptoKeyAlgo.ed25519;\n  format: ECryptoKeyFormat.raw_base64;\n  data: string;\n};\n\nexport type TSerializedCryptoKeyData_Ed25519_Jwk = v.InferInput<\n  typeof vSerializedCryptoKeyDataEd25519_Jwk\n>;\n\nexport type TSerializedCryptoKeyData_Ed25519_Jwk_Transformed = {\n  formattedString: `${ECryptoKeyAlgo.ed25519}::${ECryptoKeyFormat.jwk}::${string}`;\n  type: ECryptoKeyAlgo.ed25519;\n  format: ECryptoKeyFormat.jwk;\n  data: JsonWebKey;\n};\n\nexport const vSerializedCryptoKeyDataX25519_Raw = vCreateSchema_TypeAndFormatPrefixedDataString<\n  ECryptoKeyAlgo.x25519,\n  ECryptoKeyFormat.raw_base64\n>({\n  format: ECryptoKeyFormat.raw_base64,\n  type: ECryptoKeyAlgo.x25519,\n  typeKind: \"algo\",\n});\n\nexport const vSerializedCryptoKeyDataX25519_Jwk = vCreateSchema_TypeAndFormatPrefixedDataString<\n  ECryptoKeyAlgo.x25519,\n  ECryptoKeyFormat.jwk\n>({\n  format: ECryptoKeyFormat.jwk,\n  type: ECryptoKeyAlgo.x25519,\n  typeKind: \"algo\",\n  transformJson: true,\n});\n\nexport const vCryptoKeyPairDataX25519 = v.object({\n  publicKey: vSerializedCryptoKeyDataX25519_Raw,\n  privateKey: vSerializedCryptoKeyDataX25519_Jwk,\n});\n\nexport type TSerializedCryptoKeyPairDataX25519 = v.InferInput<typeof vCryptoKeyPairDataX25519>;\n\nexport const vCryptoKeyPairDataEd25519 = v.object({\n  publicKey: vSerializedCryptoKeyDataEd25519_Raw,\n  privateKey: vSerializedCryptoKeyDataEd25519_Jwk,\n});\n\nexport type TSerializedCryptoKeyPairDataEd25519 = v.InferInput<typeof vCryptoKeyPairDataEd25519>;\n\nexport type TSerializedCryptoKeyData_X25519_Raw = v.InferInput<\n  typeof vSerializedCryptoKeyDataX25519_Raw\n>;\n\nexport type TSerializedCryptoKeyData_X25519_Raw_Transformed = {\n  formattedString: `${ECryptoKeyAlgo.x25519}::${ECryptoKeyFormat.raw_base64}::${string}`;\n  type: ECryptoKeyAlgo.x25519;\n  format: ECryptoKeyFormat.raw_base64;\n  data: string;\n};\n\nexport type TSerializedCryptoKeyData_X25519_Jwk = v.InferInput<\n  typeof vSerializedCryptoKeyDataX25519_Jwk\n>;\n\nexport type TSerializedCryptoKeyData_X25519_Jwk_Transformed = {\n  formattedString: `${ECryptoKeyAlgo.x25519}::${ECryptoKeyFormat.jwk}::${string}`;\n  type: ECryptoKeyAlgo.x25519;\n  format: ECryptoKeyFormat.jwk;\n  data: JsonWebKey;\n};\n\nexport const vVerifyChallengeWithSignature_Input = v.object({\n  challenge: v.string(),\n  signatureBase64: vBase64,\n});\n\nexport const vVerifyChallengeWithSignature_WithThrow_Input = v.intersect([\n  vVerifyChallengeWithSignature_Input,\n  v.object({\n    throwOnInvalid: v.optional(v.boolean()),\n  }),\n]);\n\nexport type TVerifyChallengeWithSignature_Input = v.InferInput<\n  typeof vVerifyChallengeWithSignature_Input\n>;\n\nexport type TVerifyChallengeWithSignature_WithThrow_Input = v.InferInput<\n  typeof vVerifyChallengeWithSignature_WithThrow_Input\n>;\n\nexport const vEncryptedAesGcmPayload = v.object({\n  nonce: vBase64,\n  ciphertext: vBase64,\n});\n\nexport type TEncryptedAesGcmPayload = v.InferInput<typeof vEncryptedAesGcmPayload>;\nexport type TEncryptedAesGcmPayload_Transformed = v.InferOutput<typeof vEncryptedAesGcmPayload>;\n\n/**\n * Raw-bytes counterpart of {@link TEncryptedAesGcmPayload} — keeps `nonce`/`ciphertext` as binary\n * instead of base64 strings. For binary channels (e.g. msgpack WebSocket frames) this avoids the\n * ~33% base64 inflation the text payload incurs.\n */\nexport type TEncryptedAesGcmBytes = {\n  nonce: Uint8Array;\n  ciphertext: Uint8Array;\n};\n\ninterface ISerializedKeyData<T, P> {\n  transformed: T;\n  prefixed: P;\n}\n\nexport interface ISerializedKeyData_Ed25519_Raw\n  extends ISerializedKeyData<\n    TSerializedCryptoKeyData_Ed25519_Raw_Transformed,\n    TSerializedCryptoKeyData_Ed25519_Raw\n  > {}\n\nexport interface ISerializedKeyData_Ed25519_Jwk\n  extends ISerializedKeyData<\n    TSerializedCryptoKeyData_Ed25519_Jwk_Transformed,\n    TSerializedCryptoKeyData_Ed25519_Jwk\n  > {}\n\nexport interface ISerializedKeyData_X25519_Raw\n  extends ISerializedKeyData<\n    TSerializedCryptoKeyData_X25519_Raw_Transformed,\n    TSerializedCryptoKeyData_X25519_Raw\n  > {}\n\nexport interface ISerializedKeyData_X25519_Jwk\n  extends ISerializedKeyData<\n    TSerializedCryptoKeyData_X25519_Jwk_Transformed,\n    TSerializedCryptoKeyData_X25519_Jwk\n  > {}\n\nexport type TSerializedKeyData =\n  | ISerializedKeyData_Ed25519_Raw\n  | ISerializedKeyData_Ed25519_Jwk\n  | ISerializedKeyData_X25519_Raw\n  | ISerializedKeyData_X25519_Jwk;\n","import { createDataStringConverter_stringToObject } from \"../core/createDataStringConverter_stringToObject\";\nimport {\n  type ECryptoKeyAlgo,\n  ECryptoKeyFormat,\n  type ISerializedKeyData_Ed25519_Jwk,\n  type ISerializedKeyData_Ed25519_Raw,\n  type ISerializedKeyData_X25519_Jwk,\n  type ISerializedKeyData_X25519_Raw,\n  type TSerializedCryptoKeyData_Ed25519_Jwk,\n  type TSerializedCryptoKeyData_Ed25519_Jwk_Transformed,\n  type TSerializedCryptoKeyData_Ed25519_Raw,\n  type TSerializedCryptoKeyData_Ed25519_Raw_Transformed,\n  type TSerializedCryptoKeyData_X25519_Jwk,\n  type TSerializedCryptoKeyData_X25519_Jwk_Transformed,\n  type TSerializedCryptoKeyData_X25519_Raw,\n  type TSerializedCryptoKeyData_X25519_Raw_Transformed,\n} from \"./crypto.schema\";\n\n/**\n *\n * [CRYPTO ALGO] ED25519\n *\n */\n\nexport const convertEd25519RawDataStringToObject = createDataStringConverter_stringToObject<\n  ECryptoKeyAlgo.ed25519,\n  ECryptoKeyFormat.raw_base64\n>();\n\nexport const convertEd25519JwkDataStringToObject = createDataStringConverter_stringToObject<\n  ECryptoKeyAlgo.ed25519,\n  ECryptoKeyFormat.jwk,\n  JsonWebKey\n>({ transformJson: true });\n\nexport const convertEd25519FormattedStringToObject = createDataStringConverter_stringToObject<\n  ECryptoKeyAlgo.ed25519,\n  ECryptoKeyFormat.raw_base64 | ECryptoKeyFormat.jwk\n>({\n  transformJsonForFormats: [ECryptoKeyFormat.jwk],\n});\n\nexport const convertEd25519RawDataStringToSerializedKeyData = (\n  input: TSerializedCryptoKeyData_Ed25519_Raw,\n): ISerializedKeyData_Ed25519_Raw => {\n  const transformed = convertEd25519RawDataStringToObject(input);\n\n  return {\n    prefixed: input,\n    transformed,\n  };\n};\n\nexport const convertEd25519JwkDataStringToSerializedKeyData = (\n  input: TSerializedCryptoKeyData_Ed25519_Jwk,\n): ISerializedKeyData_Ed25519_Jwk => {\n  const transformed = convertEd25519JwkDataStringToObject(input);\n\n  return {\n    prefixed: input,\n    transformed,\n  };\n};\n\nexport const convertEd25519FormattedStringToSerializedKeyData = <\n  I extends TSerializedCryptoKeyData_Ed25519_Raw | TSerializedCryptoKeyData_Ed25519_Jwk,\n  O extends I extends TSerializedCryptoKeyData_Ed25519_Raw\n    ? TSerializedCryptoKeyData_Ed25519_Raw_Transformed\n    : TSerializedCryptoKeyData_Ed25519_Jwk_Transformed,\n>(\n  input: I,\n): O => {\n  return convertEd25519FormattedStringToObject(input) as O;\n};\n\n/**\n *\n * [CRYPTO ALGO] X25519\n *\n */\n\nexport const convertX25519RawDataStringToObject = createDataStringConverter_stringToObject<\n  ECryptoKeyAlgo.x25519,\n  ECryptoKeyFormat.raw_base64\n>();\n\nexport const convertX25519JwkDataStringToObject = createDataStringConverter_stringToObject<\n  ECryptoKeyAlgo.x25519,\n  ECryptoKeyFormat.jwk,\n  JsonWebKey\n>({ transformJson: true });\n\nexport const convertX25519FormattedStringToObject = createDataStringConverter_stringToObject<\n  ECryptoKeyAlgo.x25519,\n  ECryptoKeyFormat.raw_base64 | ECryptoKeyFormat.jwk\n>({\n  transformJsonForFormats: [ECryptoKeyFormat.jwk],\n});\n\nexport const convertX25519RawDataStringToSerializedKeyData = (\n  input: TSerializedCryptoKeyData_X25519_Raw,\n): ISerializedKeyData_X25519_Raw => {\n  const transformed = convertX25519RawDataStringToObject(input);\n\n  return {\n    prefixed: input,\n    transformed,\n  };\n};\n\nexport const convertX25519JwkDataStringToSerializedKeyData = (\n  input: TSerializedCryptoKeyData_X25519_Jwk,\n): ISerializedKeyData_X25519_Jwk => {\n  const transformed = convertX25519JwkDataStringToObject(input);\n\n  return {\n    prefixed: input,\n    transformed,\n  };\n};\n\nexport const convertX25519FormattedStringToSerializedKeyData = <\n  I extends TSerializedCryptoKeyData_X25519_Raw | TSerializedCryptoKeyData_X25519_Jwk,\n  O extends I extends TSerializedCryptoKeyData_X25519_Raw\n    ? TSerializedCryptoKeyData_X25519_Raw_Transformed\n    : TSerializedCryptoKeyData_X25519_Jwk_Transformed,\n>(\n  input: I,\n): O => {\n  return convertX25519FormattedStringToObject(input) as O;\n};\n","import { base64 } from \"@scure/base\";\nimport { convertEd25519FormattedStringToSerializedKeyData } from \"../crypto.converters\";\nimport {\n  ECryptoKeyFormat,\n  type TSerializedCryptoKeyData_Ed25519_Jwk,\n  type TSerializedCryptoKeyData_Ed25519_Jwk_Transformed,\n  type TSerializedCryptoKeyData_Ed25519_Raw,\n  type TSerializedCryptoKeyData_Ed25519_Raw_Transformed,\n} from \"../crypto.schema\";\n\nconst fromBase64 = async (\n  dataBase64: string,\n  keyUsage: KeyUsage[],\n  extractable: boolean,\n): Promise<CryptoKey> => {\n  const keyBuffer = Uint8Array.from(base64.decode(dataBase64));\n\n  return await crypto.subtle.importKey(\n    \"raw\",\n    keyBuffer,\n    { name: \"Ed25519\" },\n    extractable,\n    keyUsage,\n  );\n};\n\nconst fromJwk = async (\n  jwk: JsonWebKey,\n  keyUsage: KeyUsage[],\n  extractable = true,\n): Promise<CryptoKey> => {\n  return await crypto.subtle.importKey(\"jwk\", jwk, { name: \"Ed25519\" }, extractable, keyUsage);\n};\n\nconst fromSerializedObject = async <\n  D extends\n    | TSerializedCryptoKeyData_Ed25519_Raw_Transformed\n    | TSerializedCryptoKeyData_Ed25519_Jwk_Transformed =\n    | TSerializedCryptoKeyData_Ed25519_Raw_Transformed\n    | TSerializedCryptoKeyData_Ed25519_Jwk_Transformed,\n>(\n  serialized: D,\n  keyUsage: KeyUsage[],\n  extractable = true,\n): Promise<CryptoKey> => {\n  if (serialized.format === ECryptoKeyFormat.jwk) {\n    return await fromJwk(serialized.data, keyUsage, extractable);\n  }\n\n  return await fromBase64(serialized.data, keyUsage, extractable);\n};\n\nconst fromFormattedString = async <\n  D extends TSerializedCryptoKeyData_Ed25519_Raw | TSerializedCryptoKeyData_Ed25519_Jwk =\n    | TSerializedCryptoKeyData_Ed25519_Raw\n    | TSerializedCryptoKeyData_Ed25519_Jwk,\n>(\n  dataString: D,\n  keyUsage: KeyUsage[],\n  extractable = true,\n): Promise<CryptoKey> => {\n  const transformed = convertEd25519FormattedStringToSerializedKeyData(dataString);\n  return await fromSerializedObject(transformed, keyUsage, extractable);\n};\n\nconst extractableOrNonExtractable = <I>(\n  keyUsage: KeyUsage[],\n  func: (input: I, keyUsage: KeyUsage[], extractable: boolean) => Promise<CryptoKey>,\n) =>\n  ({\n    extractable: (input: I) => func(input, keyUsage, true),\n    nonExtractable: (input: I) => func(input, keyUsage, false),\n  }) as const;\n\nexport const importEd25519Key = {\n  private: {\n    fromFormattedString: extractableOrNonExtractable(\n      [\"sign\"],\n      fromFormattedString<TSerializedCryptoKeyData_Ed25519_Jwk>,\n    ),\n    fromSerializedObject: extractableOrNonExtractable(\n      [\"sign\"],\n      fromSerializedObject<TSerializedCryptoKeyData_Ed25519_Jwk_Transformed>,\n    ),\n    fromJwk: extractableOrNonExtractable([\"sign\"], fromJwk),\n  },\n  public: {\n    fromBase64: extractableOrNonExtractable([\"verify\"], fromBase64),\n    fromFormattedString: extractableOrNonExtractable(\n      [\"verify\"],\n      fromFormattedString<\n        TSerializedCryptoKeyData_Ed25519_Raw | TSerializedCryptoKeyData_Ed25519_Jwk\n      >,\n    ),\n    fromSerializedObject: extractableOrNonExtractable(\n      [\"verify\"],\n      fromSerializedObject<\n        | TSerializedCryptoKeyData_Ed25519_Raw_Transformed\n        | TSerializedCryptoKeyData_Ed25519_Jwk_Transformed\n      >,\n    ),\n    fromJwk: extractableOrNonExtractable([\"verify\"], fromJwk),\n  },\n};\n","import {\n  ECryptoKeyAlgo,\n  ECryptoKeyFormat,\n  type ISerializedKeyData_Ed25519_Jwk,\n  type TSerializedCryptoKeyData_Ed25519_Jwk_Transformed,\n} from \"../crypto.schema\";\n\nexport const serializeEd25519Key_Jwk = async (\n  key: CryptoKey,\n): Promise<ISerializedKeyData_Ed25519_Jwk> => {\n  const keyJwk = await crypto.subtle.exportKey(\"jwk\", key);\n\n  const prefixed =\n    `${ECryptoKeyAlgo.ed25519}::${ECryptoKeyFormat.jwk}::${JSON.stringify(keyJwk)}` as const;\n\n  const transformed: TSerializedCryptoKeyData_Ed25519_Jwk_Transformed = {\n    formattedString: prefixed,\n    type: ECryptoKeyAlgo.ed25519,\n    data: keyJwk,\n    format: ECryptoKeyFormat.jwk,\n  };\n\n  return { transformed, prefixed };\n};\n","import { base64 } from \"@scure/base\";\nimport {\n  ECryptoKeyAlgo,\n  ECryptoKeyFormat,\n  type ISerializedKeyData_Ed25519_Raw,\n  type TSerializedCryptoKeyData_Ed25519_Raw_Transformed,\n} from \"../crypto.schema\";\n\nexport const serializeEd25519Key_Raw = async (\n  publicKey: CryptoKey,\n): Promise<ISerializedKeyData_Ed25519_Raw> => {\n  const publicKeyBuffer = await crypto.subtle.exportKey(\"raw\", publicKey);\n  const publicKeyBase64 = base64.encode(new Uint8Array(publicKeyBuffer));\n\n  const prefixed =\n    `${ECryptoKeyAlgo.ed25519}::${ECryptoKeyFormat.raw_base64}::${publicKeyBase64}` as const;\n\n  const transformed: TSerializedCryptoKeyData_Ed25519_Raw_Transformed = {\n    formattedString: prefixed,\n    type: ECryptoKeyAlgo.ed25519,\n    data: publicKeyBase64,\n    format: ECryptoKeyFormat.raw_base64,\n  };\n\n  return { transformed, prefixed };\n};\n","import { base64 } from \"@scure/base\";\n\nexport const verifyWithKeyEd25519 = async ({\n  challenge,\n  signatureBase64,\n  publicKey,\n}: {\n  challenge: string;\n  signatureBase64: string;\n  publicKey: CryptoKey;\n}): Promise<boolean> => {\n  const signatureBuffer = Uint8Array.from(base64.decode(signatureBase64));\n  const challengeBuffer = new TextEncoder().encode(challenge);\n\n  return await crypto.subtle.verify(\n    {\n      name: \"ED25519\",\n    },\n    publicKey,\n    signatureBuffer,\n    challengeBuffer,\n  );\n};\n","export const generateX25519KeyPair = async (): Promise<CryptoKeyPair> => {\n  const keyPair = (await crypto.subtle.generateKey({ name: \"X25519\" }, true, [\n    \"deriveKey\",\n    \"deriveBits\",\n  ])) as CryptoKeyPair;\n\n  return keyPair;\n};\n","import { base64 } from \"@scure/base\";\nimport { convertX25519FormattedStringToSerializedKeyData } from \"../crypto.converters\";\nimport {\n  ECryptoKeyFormat,\n  type TSerializedCryptoKeyData_X25519_Jwk,\n  type TSerializedCryptoKeyData_X25519_Jwk_Transformed,\n  type TSerializedCryptoKeyData_X25519_Raw,\n  type TSerializedCryptoKeyData_X25519_Raw_Transformed,\n} from \"../crypto.schema\";\n\nconst fromBase64 = async (\n  dataBase64: string,\n  keyUsage: KeyUsage[],\n  extractable: boolean,\n): Promise<CryptoKey> => {\n  const keyBuffer = Uint8Array.from(base64.decode(dataBase64));\n\n  return await crypto.subtle.importKey(\"raw\", keyBuffer, { name: \"X25519\" }, extractable, keyUsage);\n};\n\nconst fromJwk = async (\n  jwk: JsonWebKey,\n  keyUsage: KeyUsage[],\n  extractable = true,\n): Promise<CryptoKey> => {\n  return await crypto.subtle.importKey(\"jwk\", jwk, { name: \"X25519\" }, extractable, keyUsage);\n};\n\nconst fromSerializedObject = async <\n  D extends\n    | TSerializedCryptoKeyData_X25519_Raw_Transformed\n    | TSerializedCryptoKeyData_X25519_Jwk_Transformed =\n    | TSerializedCryptoKeyData_X25519_Raw_Transformed\n    | TSerializedCryptoKeyData_X25519_Jwk_Transformed,\n>(\n  serialized: D,\n  keyUsage: KeyUsage[],\n  extractable = true,\n): Promise<CryptoKey> => {\n  if (serialized.format === ECryptoKeyFormat.jwk) {\n    return await fromJwk(serialized.data, keyUsage, extractable);\n  }\n\n  return await fromBase64(serialized.data, keyUsage, extractable);\n};\n\nconst fromFormattedString = async <\n  D extends TSerializedCryptoKeyData_X25519_Raw | TSerializedCryptoKeyData_X25519_Jwk =\n    | TSerializedCryptoKeyData_X25519_Raw\n    | TSerializedCryptoKeyData_X25519_Jwk,\n>(\n  dataString: D,\n  keyUsage: KeyUsage[],\n  extractable = true,\n): Promise<CryptoKey> => {\n  const transformed = convertX25519FormattedStringToSerializedKeyData(dataString);\n  return await fromSerializedObject(transformed, keyUsage, extractable);\n};\n\nconst extractableOrNonExtractable = <I>(\n  keyUsage: KeyUsage[],\n  func: (input: I, keyUsage: KeyUsage[], extractable: boolean) => Promise<CryptoKey>,\n) =>\n  ({\n    extractable: (input: I) => func(input, keyUsage, true),\n    nonExtractable: (input: I) => func(input, keyUsage, false),\n  }) as const;\n\nexport const importX25519Key = {\n  private: {\n    fromFormattedString: extractableOrNonExtractable(\n      [\"deriveKey\", \"deriveBits\"],\n      fromFormattedString<TSerializedCryptoKeyData_X25519_Jwk>,\n    ),\n    fromSerializedObject: extractableOrNonExtractable(\n      [\"deriveKey\", \"deriveBits\"],\n      fromSerializedObject<TSerializedCryptoKeyData_X25519_Jwk_Transformed>,\n    ),\n    fromJwk: extractableOrNonExtractable([\"deriveKey\", \"deriveBits\"], fromJwk),\n  },\n  public: {\n    fromBase64: extractableOrNonExtractable([], fromBase64),\n    fromFormattedString: extractableOrNonExtractable(\n      [],\n      fromFormattedString<\n        TSerializedCryptoKeyData_X25519_Raw | TSerializedCryptoKeyData_X25519_Jwk\n      >,\n    ),\n    fromSerializedObject: extractableOrNonExtractable(\n      [],\n      fromSerializedObject<\n        | TSerializedCryptoKeyData_X25519_Raw_Transformed\n        | TSerializedCryptoKeyData_X25519_Jwk_Transformed\n      >,\n    ),\n    fromJwk: extractableOrNonExtractable([], fromJwk),\n  },\n};\n","import {\n  ECryptoKeyAlgo,\n  ECryptoKeyFormat,\n  type ISerializedKeyData_X25519_Jwk,\n  type TSerializedCryptoKeyData_X25519_Jwk_Transformed,\n} from \"../crypto.schema\";\n\nexport const serializeX25519Key_Jwk = async (\n  key: CryptoKey,\n): Promise<ISerializedKeyData_X25519_Jwk> => {\n  const publicKeyJwk = await crypto.subtle.exportKey(\"jwk\", key);\n\n  const prefixed =\n    `${ECryptoKeyAlgo.x25519}::${ECryptoKeyFormat.jwk}::${JSON.stringify(publicKeyJwk)}` as const;\n\n  const transformed: TSerializedCryptoKeyData_X25519_Jwk_Transformed = {\n    formattedString: prefixed,\n    type: ECryptoKeyAlgo.x25519,\n    data: publicKeyJwk,\n    format: ECryptoKeyFormat.jwk,\n  };\n\n  return { transformed, prefixed };\n};\n","import { base64 } from \"@scure/base\";\nimport {\n  ECryptoKeyAlgo,\n  ECryptoKeyFormat,\n  type ISerializedKeyData_X25519_Raw,\n  type TSerializedCryptoKeyData_X25519_Raw_Transformed,\n} from \"../crypto.schema\";\n\nexport const serializeX25519Key_Raw = async (\n  key: CryptoKey,\n): Promise<ISerializedKeyData_X25519_Raw> => {\n  const publicKeyBuffer = await crypto.subtle.exportKey(\"raw\", key);\n  const publicKeyBase64 = base64.encode(new Uint8Array(publicKeyBuffer));\n\n  const prefixed =\n    `${ECryptoKeyAlgo.x25519}::${ECryptoKeyFormat.raw_base64}::${publicKeyBase64}` as const;\n\n  const transformed: TSerializedCryptoKeyData_X25519_Raw_Transformed = {\n    formattedString: prefixed,\n    type: ECryptoKeyAlgo.x25519,\n    data: publicKeyBase64,\n    format: ECryptoKeyFormat.raw_base64,\n  };\n\n  return { transformed, prefixed };\n};\n","const queuedInProcess = new Map<string, Promise<unknown>>();\n\n/**\n * Run `mint` alone among everything minting under `name`. Web Locks, where the runtime has them,\n * hold off every tab and worker of the origin; without them (React Native, older runtimes) the turn\n * is taken within this JS realm only, and a caller narrows the rest by reading the store again\n * before it writes.\n */\nexport async function withKeyMintLock(\n  name: string,\n  mint: () => Promise<CryptoKeyPair>,\n): Promise<CryptoKeyPair> {\n  const locks = typeof navigator !== \"undefined\" ? navigator.locks : undefined;\n  if (locks != null) {\n    let entered = false;\n    try {\n      return await locks.request(name, () => {\n        entered = true;\n        return mint();\n      });\n    } catch (error) {\n      if (entered) throw error;\n      // The lock manager itself refused (an opaque origin, say): mint with the in-process turn.\n    }\n  }\n\n  const turn = (queuedInProcess.get(name) ?? Promise.resolve()).then(mint, mint);\n  queuedInProcess.set(name, turn);\n  const release = (): void => {\n    if (queuedInProcess.get(name) === turn) queuedInProcess.delete(name);\n  };\n  turn.then(release, release);\n  return await turn;\n}\n","import { base64 } from \"@scure/base\";\nimport type { TTypeAndId } from \"../../core/core_valibot_schemas\";\nimport type { StorageAdapter } from \"../../storage_adapter/StorageAdapter\";\nimport {\n  createTypedStorage,\n  type ITypedStorage,\n} from \"../../storage_adapter/typed_storage/createTypedStorage\";\nimport { createAesGcmKeyFromX25519Keys } from \"../aes_gcm/createAesGcmKeyFromX25519Keys\";\nimport { decryptBytesWithAesGcmKey } from \"../aes_gcm/decryptBytesWithAesGcmKey\";\nimport { decryptTextDataWithAesGcmKey } from \"../aes_gcm/decryptTextDataWithAesGcmKey\";\nimport { encryptBytesWithAesGcmKey } from \"../aes_gcm/encryptBytesWithAesGcmKey\";\nimport { encryptTextDataWithAesGcmKey } from \"../aes_gcm/encryptTextDataWithAesGcmKey\";\nimport {\n  buildCanonicalChallenge,\n  type ICanonicalChallenge,\n} from \"../canonical/buildCanonicalChallenge\";\nimport type {\n  TEncryptedAesGcmBytes,\n  TEncryptedAesGcmPayload,\n  TSerializedCryptoKeyData_Ed25519_Raw,\n  TSerializedCryptoKeyData_X25519_Raw,\n  TSerializedCryptoKeyPairDataEd25519,\n  TSerializedCryptoKeyPairDataX25519,\n} from \"../crypto.schema\";\nimport { generateEd25519KeyPair } from \"../ed25519/generateEd25519KeyPair\";\nimport { importEd25519Key } from \"../ed25519/importEd25519Key\";\nimport { serializeEd25519Key_Jwk } from \"../ed25519/serializeEd25519Key_Jwk\";\nimport { serializeEd25519Key_Raw } from \"../ed25519/serializeEd25519Key_Raw\";\nimport { signCombinedTextDataWithKeyEd25519 } from \"../ed25519/signCombinedTextDataWithKeyEd25519\";\nimport { signTextDataWithKeyEd25519 } from \"../ed25519/signTextDataWithKeyEd25519\";\nimport { verifyWithKeyEd25519 } from \"../ed25519/verifyWithKeyEd25519\";\nimport { generateX25519KeyPair } from \"../x25519/generateX25519KeyPair\";\nimport { importX25519Key } from \"../x25519/importX25519Key\";\nimport { serializeX25519Key_Jwk } from \"../x25519/serializeX25519Key_Jwk\";\nimport { serializeX25519Key_Raw } from \"../x25519/serializeX25519Key_Raw\";\nimport { buildVerifyKeyBoundInfoString } from \"./buildVerifyKeyBoundInfoString\";\nimport { withKeyMintLock } from \"./withKeyMintLock\";\n\n/**\n * How the local identity (the exchange + verify key pairs) is allowed to come into being:\n *\n * - `\"lazy\"` (default): generate + persist the identity on first use. Correct for frontend / ephemeral\n *   peers, and safe on a *strongly-consistent* store (a read miss genuinely means \"never written\").\n * - `\"required\"`: never auto-mint. `ensureLocal*` throws {@link IdentityNotProvisionedError} if no\n *   identity was loaded from storage; the only way to mint is the explicit one-shot\n *   {@link ClientCryptoKeyLink.provisionIdentity}. Use this for a shared backend identity that must\n *   stay stable across isolates: on an *eventually-consistent* store (e.g. Cloudflare KV) a transient\n *   read miss must NOT be allowed to silently fork a second identity — that would change the server's\n *   verify key and get it permanently rejected by every trust-on-first-use-pinned client.\n */\nexport type TIdentityMode = \"lazy\" | \"required\";\n\n/**\n * Thrown by the local-key getters when the link is in {@link TIdentityMode} `\"required\"` and no\n * identity has been provisioned. Surfacing this (instead of silently minting a fresh identity on a\n * storage miss) is what keeps a shared backend identity from forking across isolates.\n */\nexport class IdentityNotProvisionedError extends Error {\n  constructor(\n    message = \"ClientCryptoKeyLink: identity not provisioned (identityMode 'required'). Call provisionIdentity() once, out-of-band, before serving.\",\n  ) {\n    super(message);\n    this.name = \"IdentityNotProvisionedError\";\n  }\n}\n\ninterface IClientCryptoKeyLink_Constructor {\n  storageAdapter?: StorageAdapter;\n  /**\n   * Controls whether the local identity may be minted on first use. Defaults to `\"lazy\"` (unchanged\n   * behavior). Pass `\"required\"` for a stable shared backend identity — see {@link TIdentityMode}.\n   */\n  identityMode?: TIdentityMode;\n}\n\n/** One local key pair's mint: how to find it in the store, make it, hold it and persist it. */\ninterface ILocalKeyPairMint {\n  storageKey: \"localExchangeKeyPair\" | \"localVerifyKeyPair\";\n  readStored: () => Promise<CryptoKeyPair | undefined>;\n  generate: () => Promise<CryptoKeyPair>;\n  keep: (keyPair: CryptoKeyPair) => void;\n  store: (keyPair: CryptoKeyPair) => Promise<void>;\n}\n\ninterface ITypedStorage_ClientCryptoKeyLink {\n  localExchangeKeyPair?: TSerializedCryptoKeyPairDataX25519;\n  localVerifyKeyPair?: TSerializedCryptoKeyPairDataEd25519;\n  linkedClientPublicKeys: {\n    [key: TTypeAndId<string>]: {\n      verifyPublicKey?: TSerializedCryptoKeyData_Ed25519_Raw;\n      exchangePublicKey?: TSerializedCryptoKeyData_X25519_Raw;\n      // HKDF inputs for the shared-key derivation. Persisted only via linkClientAndStore — these\n      // are typically session secrets, so prefer the in-memory linkClient for ephemeral links.\n      saltString?: string;\n      infoString?: string;\n      bindVerifyKeysIntoDerivation?: boolean;\n    };\n  };\n}\n\ninterface IExternalClientCryptoKeys {\n  verify?: {\n    publicKey: CryptoKey;\n    publicKeySerialized: TSerializedCryptoKeyData_Ed25519_Raw;\n  };\n  exchange?: {\n    publicKey: CryptoKey;\n    // Serialized form retained so re-linking can detect a changed key and invalidate the cache.\n    publicKeySerialized: TSerializedCryptoKeyData_X25519_Raw;\n    saltString?: string;\n    infoString?: string;\n    bindVerifyKeysIntoDerivation?: boolean;\n    sharedEncryptKey?: CryptoKey;\n  };\n}\n\ninterface ILinkedClientPublicKeys {\n  verifyPublicKey?: TSerializedCryptoKeyData_Ed25519_Raw;\n  exchangePublicKey?: TSerializedCryptoKeyData_X25519_Raw;\n}\n\ninterface ILocalPublicKeys {\n  verifyPublicKey: TSerializedCryptoKeyData_Ed25519_Raw;\n  exchangePublicKey: TSerializedCryptoKeyData_X25519_Raw;\n}\n\ninterface ILinkClientKeys {\n  linkedClientId: TTypeAndId;\n  verifyPublicKey?: TSerializedCryptoKeyData_Ed25519_Raw;\n  exchangePublicKey?: TSerializedCryptoKeyData_X25519_Raw;\n  // HKDF salt/info bound into the shared AES-GCM key derivation with this client. Passing either\n  // (or a new exchange public key) invalidates a previously cached shared key for the link.\n  saltString?: string;\n  infoString?: string;\n  // When true, both sides' verify public keys (local + linked, sorted so both ends agree without\n  // coordinating an order) are folded into the HKDF info alongside `infoString`. If either relayed\n  // verify key was tampered with in transit, the two sides derive mismatched keys and the first\n  // decryption fails — authenticating the keys without extra signatures. Requires the linked\n  // client's verify key to be set. Both ends of the link must use the same setting.\n  bindVerifyKeysIntoDerivation?: boolean;\n}\n\ninterface IEncryptDataForLinkedClient {\n  linkedClientId: TTypeAndId;\n  dataToEncrypt: string;\n}\n\ninterface IDecryptDataFromLinkedClient {\n  linkedClientId: TTypeAndId;\n  dataToDecrypt: TEncryptedAesGcmPayload;\n}\n\ninterface IDecryptAndVerifyDataFromLinkedClient extends IDecryptDataFromLinkedClient {\n  signatureBase64: string;\n}\n\ninterface IVerifyChallengeFromLinkedClient {\n  linkedClientId: TTypeAndId;\n  challenge: string;\n  signatureBase64: string;\n}\n\nexport class ClientCryptoKeyLink {\n  private localExchangeKeyPair: CryptoKeyPair | undefined;\n  private localVerifyKeyPair: CryptoKeyPair | undefined;\n  private linkedClientKeys = new Map<TTypeAndId, IExternalClientCryptoKeys>();\n  private storage: ITypedStorage<ITypedStorage_ClientCryptoKeyLink> | undefined;\n  private readonly storageAdapter: StorageAdapter | undefined;\n  private readonly identityMode: TIdentityMode;\n  private initialized = false;\n  private reloadPending = false;\n  private initializePromise: Promise<void> | undefined;\n  private localExchangeKeyPairPromise: Promise<CryptoKeyPair> | undefined;\n  private localVerifyKeyPairPromise: Promise<CryptoKeyPair> | undefined;\n\n  constructor({ storageAdapter, identityMode }: IClientCryptoKeyLink_Constructor = {}) {\n    if (storageAdapter != null) {\n      this.storage = createTypedStorage({ storageAdapter });\n    }\n    this.storageAdapter = storageAdapter;\n    this.identityMode = identityMode ?? \"lazy\";\n  }\n\n  /**\n   * A namespace of this identity's own store (same backing storage, `prefix` appended), for state\n   * that belongs to this identity and must go wherever its keys go — e.g. a connector's established\n   * sessions. `undefined` when the link has no storage.\n   */\n  scopedStorage(prefix: string): StorageAdapter | undefined {\n    return this.storageAdapter?.withKeyPrefix(prefix);\n  }\n\n  /**\n   * Loads the local key pairs and any linked client public keys from storage (when a storage\n   * adapter was provided), generating and persisting fresh local key pairs if none exist yet.\n   *\n   * Must be called (and awaited) before any sign/verify/encrypt/decrypt operation.\n   */\n  async initialize(): Promise<void> {\n    if (this.initialized && !this.reloadPending) {\n      return;\n    }\n\n    // Guard against concurrent initialize() calls (e.g. parallel callers on the frontend, where\n    // there is no blockConcurrencyWhile) generating and persisting duplicate local key pairs.\n    this.initializePromise ??= this.runInitialize();\n\n    try {\n      await this.initializePromise;\n    } finally {\n      this.initializePromise = undefined;\n    }\n  }\n\n  private async runInitialize(): Promise<void> {\n    // Cleared first, so a caller arriving during a reload joins it and is not waved through.\n    this.initialized = false;\n    await this.loadStoredLocalKeys();\n    await this.loadLinkedClients();\n\n    this.initialized = true;\n  }\n\n  /**\n   * Have the next {@link initialize} read the store again and take it as the truth: a local identity\n   * the store holds now is adopted, and one it no longer holds is forgotten (the next use mints and\n   * persists a fresh one). For a link that outlives the code that made it — one shared by connections\n   * made at different times: a store cleared in between would otherwise leave an identity that is\n   * presented now and gone after the next reload. A no-op for a link with no storage.\n   */\n  reloadOnNextInitialize(): void {\n    if (this.storage == null) {\n      return;\n    }\n    this.reloadPending = true;\n  }\n\n  /**\n   * Provision the local identity once: load any persisted identity, then mint + persist the exchange\n   * and verify key pairs only if absent. Idempotent — a no-op when an identity already exists.\n   *\n   * This is the *only* way to mint when {@link TIdentityMode} is `\"required\"`. Run it from a single\n   * coordinated writer (a deploy hook, a first-boot path, a locked admin route) — **never on the hot\n   * request path** — because concurrent provisioning over an eventually-consistent store could read\n   * \"absent\" on two isolates at once and fork divergent identities. The serving path uses `\"required\"`,\n   * which never mints, so a transient storage miss fails that one request loudly instead of forking.\n   *\n   * A genuine storage *read error* propagates here (it is never coerced to \"absent\"), so an outage\n   * surfaces rather than silently minting a replacement identity.\n   */\n  async provisionIdentity(): Promise<void> {\n    await this.initialize();\n    await this.mintLocalExchangeKeyPair();\n    await this.mintLocalVerifyKeyPair();\n  }\n\n  /**\n   * Loads the local key pairs from storage if they were previously persisted. Does NOT generate\n   * fresh keys — local identity is created lazily on first use (see {@link ensureLocalExchangeKeyPair}\n   * / {@link ensureLocalVerifyKeyPair}), so a verify-only or otherwise key-less consumer never\n   * generates or stores keys it does not need.\n   */\n  private async loadStoredLocalKeys(): Promise<void> {\n    // Only a requested reload forgets a key the store lacks: a store that failed a write must not\n    // cost a running link the identity it is already using.\n    const forgetUnstored = this.reloadPending;\n    this.reloadPending = false;\n\n    try {\n      const storedExchange = await this.readStoredExchangeKeyPair();\n      const storedVerify = await this.readStoredVerifyKeyPair();\n      if (storedExchange != null || forgetUnstored) {\n        this.localExchangeKeyPair = storedExchange;\n      }\n      if (storedVerify != null || forgetUnstored) {\n        this.localVerifyKeyPair = storedVerify;\n      }\n    } catch (error) {\n      // A store that could not be read still owes the reload.\n      this.reloadPending ||= forgetUnstored;\n      throw error;\n    }\n  }\n\n  // NOTE (both readers): each `await` is hoisted to its own statement (rather than inlined as an\n  // object-literal property value) — Hermes (React Native) miscompiles an `await` of a member-chain\n  // call placed directly inside an object literal, storing `undefined` instead of the resolved key.\n  // See the same guard in `linkClient`.\n  private async readStoredExchangeKeyPair(): Promise<CryptoKeyPair | undefined> {\n    const stored = await this.storage?.getJson(\"localExchangeKeyPair\");\n    if (stored == null) {\n      return undefined;\n    }\n    const privateKey = await importX25519Key.private.fromFormattedString.extractable(\n      stored.privateKey,\n    );\n    const publicKey = await importX25519Key.public.fromFormattedString.extractable(\n      stored.publicKey,\n    );\n    return { privateKey, publicKey };\n  }\n\n  private async readStoredVerifyKeyPair(): Promise<CryptoKeyPair | undefined> {\n    const stored = await this.storage?.getJson(\"localVerifyKeyPair\");\n    if (stored == null) {\n      return undefined;\n    }\n    const privateKey = await importEd25519Key.private.fromFormattedString.extractable(\n      stored.privateKey,\n    );\n    const publicKey = await importEd25519Key.public.fromFormattedString.extractable(\n      stored.publicKey,\n    );\n    return { privateKey, publicKey };\n  }\n\n  /**\n   * Mint one local key pair — or adopt the one another link over the same storage minted first.\n   * Two links (or two tabs) that each found the store empty must not each persist a key of their\n   * own: a peer pins the first it sees and refuses the other for good.\n   */\n  private async mintOrAdopt(mint: ILocalKeyPairMint): Promise<CryptoKeyPair> {\n    const storageAdapter = this.storageAdapter;\n    if (storageAdapter == null) {\n      const keyPair = await mint.generate();\n      mint.keep(keyPair);\n      return keyPair;\n    }\n\n    const lockName = `nice-code:key-link:${storageAdapter.keyPrefix}${mint.storageKey}`;\n    return await withKeyMintLock(lockName, async () => {\n      const stored = await mint.readStored();\n      if (stored != null) {\n        mint.keep(stored);\n        return stored;\n      }\n\n      const generated = await mint.generate();\n      // Read once more before writing: without Web Locks, another tab was not held off meanwhile.\n      const storedMeanwhile = await mint.readStored();\n      if (storedMeanwhile != null) {\n        mint.keep(storedMeanwhile);\n        return storedMeanwhile;\n      }\n\n      mint.keep(generated);\n      await mint.store(generated);\n      return generated;\n    });\n  }\n\n  /**\n   * Returns the local exchange (X25519) key pair. In `\"lazy\"` mode it generates + persists it on first\n   * use; in `\"required\"` mode it throws {@link IdentityNotProvisionedError} when none was loaded (mint\n   * only via {@link provisionIdentity}). The read path of every encrypt/derive operation.\n   */\n  private async ensureLocalExchangeKeyPair(): Promise<CryptoKeyPair> {\n    if (this.localExchangeKeyPair != null) {\n      return this.localExchangeKeyPair;\n    }\n    if (this.identityMode === \"required\") {\n      throw new IdentityNotProvisionedError();\n    }\n    return this.mintLocalExchangeKeyPair();\n  }\n\n  /**\n   * Generates + persists the local exchange key pair if absent, returning an already-loaded pair\n   * untouched (so provisioning is idempotent). Bypasses the `\"required\"` guard by design — it is the\n   * sole minting path. Concurrent callers share a single generation, and a pair another link has\n   * stored since this one loaded is adopted instead (see {@link mintOrAdopt}).\n   */\n  private async mintLocalExchangeKeyPair(): Promise<CryptoKeyPair> {\n    if (this.localExchangeKeyPair != null) {\n      return this.localExchangeKeyPair;\n    }\n\n    this.localExchangeKeyPairPromise ??= this.mintOrAdopt({\n      storageKey: \"localExchangeKeyPair\",\n      readStored: () => this.readStoredExchangeKeyPair(),\n      generate: generateX25519KeyPair,\n      keep: (keyPair) => {\n        this.localExchangeKeyPair = keyPair;\n      },\n      store: async (keyPair) => {\n        const serialized = await this.serializeExchangeKeyPair(keyPair);\n        await this.storage?.setJson(\"localExchangeKeyPair\", serialized);\n      },\n    });\n\n    try {\n      return await this.localExchangeKeyPairPromise;\n    } finally {\n      this.localExchangeKeyPairPromise = undefined;\n    }\n  }\n\n  /**\n   * Returns the local verify (Ed25519) key pair. In `\"lazy\"` mode it generates + persists it on first\n   * use; in `\"required\"` mode it throws {@link IdentityNotProvisionedError} when none was loaded (mint\n   * only via {@link provisionIdentity}). The read path of every sign operation.\n   */\n  private async ensureLocalVerifyKeyPair(): Promise<CryptoKeyPair> {\n    if (this.localVerifyKeyPair != null) {\n      return this.localVerifyKeyPair;\n    }\n    if (this.identityMode === \"required\") {\n      throw new IdentityNotProvisionedError();\n    }\n    return this.mintLocalVerifyKeyPair();\n  }\n\n  /**\n   * Generates + persists the local verify key pair if absent, returning an already-loaded pair\n   * untouched (so provisioning is idempotent). Bypasses the `\"required\"` guard by design — it is the\n   * sole minting path. Concurrent callers share a single generation, and a pair another link has\n   * stored since this one loaded is adopted instead (see {@link mintOrAdopt}).\n   */\n  private async mintLocalVerifyKeyPair(): Promise<CryptoKeyPair> {\n    if (this.localVerifyKeyPair != null) {\n      return this.localVerifyKeyPair;\n    }\n\n    this.localVerifyKeyPairPromise ??= this.mintOrAdopt({\n      storageKey: \"localVerifyKeyPair\",\n      readStored: () => this.readStoredVerifyKeyPair(),\n      generate: generateEd25519KeyPair,\n      keep: (keyPair) => {\n        this.localVerifyKeyPair = keyPair;\n      },\n      store: async (keyPair) => {\n        const serialized = await this.serializeVerifyKeyPair(keyPair);\n        await this.storage?.setJson(\"localVerifyKeyPair\", serialized);\n      },\n    });\n\n    try {\n      return await this.localVerifyKeyPairPromise;\n    } finally {\n      this.localVerifyKeyPairPromise = undefined;\n    }\n  }\n\n  private async loadLinkedClients(): Promise<void> {\n    const storedLinkedClients = await this.storage?.getJson(\"linkedClientPublicKeys\");\n\n    if (storedLinkedClients == null) {\n      return;\n    }\n\n    for (const [linkedClientId, publicKeys] of Object.entries(storedLinkedClients) as [\n      TTypeAndId,\n      ITypedStorage_ClientCryptoKeyLink[\"linkedClientPublicKeys\"][TTypeAndId],\n    ][]) {\n      await this.linkClient({\n        linkedClientId,\n        verifyPublicKey: publicKeys.verifyPublicKey,\n        exchangePublicKey: publicKeys.exchangePublicKey,\n        saltString: publicKeys.saltString,\n        infoString: publicKeys.infoString,\n        bindVerifyKeysIntoDerivation: publicKeys.bindVerifyKeysIntoDerivation,\n      });\n    }\n  }\n\n  private async serializeExchangeKeyPair(\n    keyPair: CryptoKeyPair,\n  ): Promise<TSerializedCryptoKeyPairDataX25519> {\n    return {\n      publicKey: (await serializeX25519Key_Raw(keyPair.publicKey)).prefixed,\n      privateKey: (await serializeX25519Key_Jwk(keyPair.privateKey)).prefixed,\n    };\n  }\n\n  private async serializeVerifyKeyPair(\n    keyPair: CryptoKeyPair,\n  ): Promise<TSerializedCryptoKeyPairDataEd25519> {\n    return {\n      publicKey: (await serializeEd25519Key_Raw(keyPair.publicKey)).prefixed,\n      privateKey: (await serializeEd25519Key_Jwk(keyPair.privateKey)).prefixed,\n    };\n  }\n\n  /**\n   * The local public keys that should be shared with a linked client so that it can verify this\n   * client's signatures and derive a shared encryption key. Generates the local identity on first\n   * use.\n   */\n  async getLocalPublicKeys(): Promise<ILocalPublicKeys> {\n    return {\n      verifyPublicKey: await this.getLocalVerifyPublicKey(),\n      exchangePublicKey: await this.getLocalExchangePublicKey(),\n    };\n  }\n\n  /**\n   * The local exchange (X25519) public key, generating the exchange key pair on first use. Does not\n   * touch the verify key pair — useful for an exchange-only consumer (e.g. a bridge) that never\n   * signs.\n   */\n  async getLocalExchangePublicKey(): Promise<TSerializedCryptoKeyData_X25519_Raw> {\n    const exchangeKeyPair = await this.ensureLocalExchangeKeyPair();\n    return (await serializeX25519Key_Raw(exchangeKeyPair.publicKey)).prefixed;\n  }\n\n  /**\n   * The local verify (Ed25519) public key, generating the verify key pair on first use. Does not\n   * touch the exchange key pair.\n   */\n  async getLocalVerifyPublicKey(): Promise<TSerializedCryptoKeyData_Ed25519_Raw> {\n    const verifyKeyPair = await this.ensureLocalVerifyKeyPair();\n    return (await serializeEd25519Key_Raw(verifyKeyPair.publicKey)).prefixed;\n  }\n\n  /**\n   * Registers (or updates) the public keys of a linked client in memory only — nothing is written\n   * to storage. Use this for ephemeral links (e.g. a per-session bridge or end-to-end peer keyed by\n   * a session salt/info), so the derived shared key never outlives the process.\n   *\n   * Re-linking with a new exchange public key, salt, or info invalidates any previously cached\n   * shared key for the link.\n   */\n  async linkClient({\n    linkedClientId,\n    verifyPublicKey,\n    exchangePublicKey,\n    saltString,\n    infoString,\n    bindVerifyKeysIntoDerivation,\n  }: ILinkClientKeys): Promise<void> {\n    const existing = this.linkedClientKeys.get(linkedClientId);\n\n    // NOTE: the `await` is hoisted to its own statement on purpose — Hermes (React Native) miscompiles\n    // an `await` placed directly inside an object literal (and/or a ternary branch), yielding `undefined`\n    // instead of the resolved value. Building the imported key first, then the object, keeps this correct\n    // across engines.\n    let verify = existing?.verify;\n    if (verifyPublicKey != null) {\n      const verifyPublicKeyImported =\n        await importEd25519Key.public.fromFormattedString.extractable(verifyPublicKey);\n      verify = { publicKey: verifyPublicKeyImported, publicKeySerialized: verifyPublicKey };\n    }\n\n    const verifyKeyChanged =\n      verifyPublicKey != null && verifyPublicKey !== existing?.verify?.publicKeySerialized;\n\n    let exchange = existing?.exchange;\n\n    // `undefined` means \"leave as-is\"; only fields actually passed override the existing link.\n    const exchangeParamsProvided =\n      exchangePublicKey != null ||\n      saltString !== undefined ||\n      infoString !== undefined ||\n      bindVerifyKeysIntoDerivation !== undefined;\n\n    if (exchangeParamsProvided) {\n      const nextPublicKeySerialized = exchangePublicKey ?? existing?.exchange?.publicKeySerialized;\n\n      if (nextPublicKeySerialized == null) {\n        throw new Error(\n          `ClientCryptoKeyLink: Cannot set salt/info for ${linkedClientId} without an exchange public key`,\n        );\n      }\n\n      const nextSalt = saltString !== undefined ? saltString : existing?.exchange?.saltString;\n      const nextInfo = infoString !== undefined ? infoString : existing?.exchange?.infoString;\n      const nextBind =\n        bindVerifyKeysIntoDerivation !== undefined\n          ? bindVerifyKeysIntoDerivation\n          : existing?.exchange?.bindVerifyKeysIntoDerivation;\n\n      // Same Hermes hazard as the verify key above: hoist the `await` out of the ternary branch.\n      let publicKey: CryptoKey;\n      if (exchangePublicKey != null) {\n        publicKey = await importX25519Key.public.fromFormattedString.extractable(exchangePublicKey);\n      } else {\n        // Safe: nextPublicKeySerialized fell back to the existing key, so it exists.\n        publicKey = existing!.exchange!.publicKey;\n      }\n\n      const unchanged =\n        nextPublicKeySerialized === existing?.exchange?.publicKeySerialized &&\n        nextSalt === existing?.exchange?.saltString &&\n        nextInfo === existing?.exchange?.infoString &&\n        nextBind === existing?.exchange?.bindVerifyKeysIntoDerivation &&\n        // With verify keys bound into the derivation, a new verify key changes the derived key.\n        !(nextBind === true && verifyKeyChanged);\n\n      exchange = {\n        publicKey,\n        publicKeySerialized: nextPublicKeySerialized,\n        saltString: nextSalt,\n        infoString: nextInfo,\n        bindVerifyKeysIntoDerivation: nextBind,\n        // Keep the cached shared key only when no derivation input changed.\n        sharedEncryptKey: unchanged ? existing?.exchange?.sharedEncryptKey : undefined,\n      };\n    } else if (\n      exchange?.bindVerifyKeysIntoDerivation === true &&\n      verifyKeyChanged &&\n      exchange.sharedEncryptKey != null\n    ) {\n      // Verify-only re-link, but the verify key participates in this link's derivation.\n      exchange = { ...exchange, sharedEncryptKey: undefined };\n    }\n\n    this.linkedClientKeys.set(linkedClientId, { verify, exchange });\n  }\n\n  /**\n   * Like {@link linkClient}, but also persists the linked client's public keys (and salt/info) to\n   * storage so the link survives a reload.\n   *\n   * NOTE: salt/info are written in plaintext. When they are session secrets (e.g. a partner secret\n   * or bridge salt), prefer {@link linkClient} and re-establish the link per session instead.\n   */\n  async linkClientAndStore(input: ILinkClientKeys): Promise<void> {\n    await this.linkClient(input);\n\n    if (this.storage == null) {\n      return;\n    }\n\n    const {\n      linkedClientId,\n      verifyPublicKey,\n      exchangePublicKey,\n      saltString,\n      infoString,\n      bindVerifyKeysIntoDerivation,\n    } = input;\n\n    await this.storage.updateJsonWithDef(\"linkedClientPublicKeys\", {}, (current) => ({\n      ...current,\n      [linkedClientId]: {\n        ...current[linkedClientId],\n        ...(verifyPublicKey != null ? { verifyPublicKey } : {}),\n        ...(exchangePublicKey != null ? { exchangePublicKey } : {}),\n        ...(saltString !== undefined ? { saltString } : {}),\n        ...(infoString !== undefined ? { infoString } : {}),\n        ...(bindVerifyKeysIntoDerivation !== undefined ? { bindVerifyKeysIntoDerivation } : {}),\n      },\n    }));\n  }\n\n  /**\n   * Whether a linked client is currently registered (in memory) under this id.\n   */\n  hasLinkedClient(linkedClientId: TTypeAndId): boolean {\n    return this.linkedClientKeys.has(linkedClientId);\n  }\n\n  /**\n   * The serialized public keys registered for a linked client, or undefined when the client is not\n   * linked. Useful when a holder needs to relay a linked client's keys onward (e.g. a backend\n   * relaying a wallet's verify key to a partner).\n   */\n  getLinkedClientPublicKeys(linkedClientId: TTypeAndId): ILinkedClientPublicKeys | undefined {\n    const linkedClient = this.linkedClientKeys.get(linkedClientId);\n\n    if (linkedClient == null) {\n      return undefined;\n    }\n\n    return {\n      verifyPublicKey: linkedClient.verify?.publicKeySerialized,\n      exchangePublicKey: linkedClient.exchange?.publicKeySerialized,\n    };\n  }\n\n  /**\n   * Removes a single linked client from memory and, when storage is available, from persisted\n   * state. Any cached shared key for the link is dropped with it.\n   */\n  async unlinkClient(linkedClientId: TTypeAndId): Promise<void> {\n    this.linkedClientKeys.delete(linkedClientId);\n\n    if (this.storage != null) {\n      await this.storage.updateJson(\"linkedClientPublicKeys\", (current) => {\n        if (current == null) {\n          return {};\n        }\n\n        const { [linkedClientId]: _removed, ...rest } = current;\n        return rest;\n      });\n    }\n  }\n\n  /**\n   * Removes all linked clients from memory and persisted state, while keeping the local identity\n   * key pairs intact.\n   */\n  async unlinkAllClients(): Promise<void> {\n    this.linkedClientKeys.clear();\n\n    if (this.storage != null) {\n      await this.storage.setJson(\"linkedClientPublicKeys\", {});\n    }\n  }\n\n  /**\n   * Wipes everything this instance owns — local identity key pairs and all linked clients, in\n   * memory and in storage. After a reset, {@link initialize} must be called again before use (it\n   * will generate a fresh local identity).\n   *\n   * Only the keys owned by this util are removed, so a shared storage adapter's other data is left\n   * untouched.\n   */\n  async reset(): Promise<void> {\n    this.linkedClientKeys.clear();\n    this.localExchangeKeyPair = undefined;\n    this.localVerifyKeyPair = undefined;\n    this.initialized = false;\n\n    if (this.storage != null) {\n      await this.storage.removeItem(\"linkedClientPublicKeys\");\n      await this.storage.removeItem(\"localExchangeKeyPair\");\n      await this.storage.removeItem(\"localVerifyKeyPair\");\n    }\n  }\n\n  private getLinkedClient(linkedClientId: TTypeAndId): IExternalClientCryptoKeys {\n    const linkedClient = this.linkedClientKeys.get(linkedClientId);\n\n    if (linkedClient == null) {\n      throw new Error(`ClientCryptoKeyLink: No linked client for ${linkedClientId}`);\n    }\n\n    return linkedClient;\n  }\n\n  private async getAesGcmKeyForLinkedClient(\n    externalClientSourceId: TTypeAndId,\n  ): Promise<CryptoKey> {\n    const linkedClient = this.getLinkedClient(externalClientSourceId);\n\n    if (linkedClient.exchange?.sharedEncryptKey != null) {\n      return linkedClient.exchange.sharedEncryptKey;\n    }\n\n    if (linkedClient.exchange?.publicKey == null) {\n      throw new Error(\n        `ClientCryptoKeyLink: No public exchange key set for ${externalClientSourceId}`,\n      );\n    }\n\n    const localExchangeKeyPair = await this.ensureLocalExchangeKeyPair();\n\n    let infoString = linkedClient.exchange.infoString;\n\n    if (linkedClient.exchange.bindVerifyKeysIntoDerivation === true) {\n      const linkedVerifyPublicKey = linkedClient.verify?.publicKeySerialized;\n\n      if (linkedVerifyPublicKey == null) {\n        throw new Error(\n          `ClientCryptoKeyLink: Link for ${externalClientSourceId} binds verify keys into the derivation, but no verify public key is set`,\n        );\n      }\n\n      infoString = buildVerifyKeyBoundInfoString({\n        infoString: linkedClient.exchange.infoString,\n        verifyPublicKeys: [await this.getLocalVerifyPublicKey(), linkedVerifyPublicKey],\n      });\n    }\n\n    const sharedEncryptKey = await createAesGcmKeyFromX25519Keys({\n      internalX25519PrivateKey: localExchangeKeyPair.privateKey,\n      externalX25519PublicKey: linkedClient.exchange.publicKey,\n      saltString: linkedClient.exchange.saltString,\n      infoString,\n    });\n\n    this.linkedClientKeys.set(externalClientSourceId, {\n      ...linkedClient,\n      exchange: {\n        ...linkedClient.exchange,\n        sharedEncryptKey,\n      },\n    });\n\n    return sharedEncryptKey;\n  }\n\n  /**\n   * Derive the shared AES-GCM key from *explicit* key material + this link's local exchange private\n   * key, returning a standalone key that is **not** stored in (or read from) the per-`linkedClientId`\n   * cache. Use it to give a single session its own immutable key: two sessions that share one\n   * `linkedClientId` (e.g. a secure WebSocket and a secure HTTP exchange to the same peer) would\n   * otherwise clobber each other's cached shared key — the second handshake's re-link drops the\n   * first's key, so frames on the other transport fail to decrypt. Mirrors the derivation in\n   * {@link getAesGcmKeyForLinkedClient} exactly, so the resulting key matches the peer's.\n   *\n   * Requires the local identity to be loaded — call {@link initialize} first when resuming a link\n   * cold (the handshake paths have already initialized by the time they hold key material).\n   */\n  async deriveSharedAesGcmKey({\n    exchangePublicKey,\n    saltString,\n    infoString,\n    bindVerifyKeysIntoDerivation,\n    verifyPublicKey,\n  }: {\n    exchangePublicKey: TSerializedCryptoKeyData_X25519_Raw;\n    saltString?: string;\n    infoString?: string;\n    bindVerifyKeysIntoDerivation?: boolean;\n    /** The peer's verify public key — required when `bindVerifyKeysIntoDerivation` is true. */\n    verifyPublicKey?: TSerializedCryptoKeyData_Ed25519_Raw;\n  }): Promise<CryptoKey> {\n    const localExchangeKeyPair = await this.ensureLocalExchangeKeyPair();\n    const externalX25519PublicKey =\n      await importX25519Key.public.fromFormattedString.extractable(exchangePublicKey);\n\n    let derivedInfoString = infoString;\n    if (bindVerifyKeysIntoDerivation === true) {\n      if (verifyPublicKey == null) {\n        throw new Error(\n          \"ClientCryptoKeyLink.deriveSharedAesGcmKey: a verify public key is required when binding verify keys into the derivation\",\n        );\n      }\n      derivedInfoString = buildVerifyKeyBoundInfoString({\n        infoString,\n        verifyPublicKeys: [await this.getLocalVerifyPublicKey(), verifyPublicKey],\n      });\n    }\n\n    return await createAesGcmKeyFromX25519Keys({\n      internalX25519PrivateKey: localExchangeKeyPair.privateKey,\n      externalX25519PublicKey,\n      saltString,\n      infoString: derivedInfoString,\n    });\n  }\n\n  /**\n   * Derive a symmetric AES-GCM key bound to **this link's own identity** — for sealing data the server\n   * hands a client and reads back later (e.g. a stateless secure-exchange session ticket), where only\n   * this server (any isolate that loaded the same persisted identity) can open it.\n   *\n   * Deterministic: an X25519 ECDH of the local exchange private key against its own public key, fed\n   * through the same vetted HKDF as peer key derivation, with a fixed versioned info label. So every\n   * isolate sharing the persisted identity derives the identical key, and no raw private-key bytes are\n   * exposed. The {@link version} is part of the label, so a future rotation can run two keys during a\n   * grace window (old tickets opened with `v1` while new ones issue under `v2`).\n   *\n   * Requires the local identity (call {@link initialize} / {@link provisionIdentity} first); in\n   * `\"required\"` mode an unprovisioned link throws {@link IdentityNotProvisionedError}.\n   */\n  async deriveLocalSealKey(options?: { version?: string }): Promise<CryptoKey> {\n    const localExchangeKeyPair = await this.ensureLocalExchangeKeyPair();\n    return await createAesGcmKeyFromX25519Keys({\n      internalX25519PrivateKey: localExchangeKeyPair.privateKey,\n      externalX25519PublicKey: localExchangeKeyPair.publicKey,\n      infoString: `exchange-ticket-seal/${options?.version ?? \"v1\"}`,\n    });\n  }\n\n  async encryptDataForLinkedClient({\n    dataToEncrypt,\n    linkedClientId,\n  }: IEncryptDataForLinkedClient): Promise<TEncryptedAesGcmPayload> {\n    const key = await this.getAesGcmKeyForLinkedClient(linkedClientId);\n\n    return await encryptTextDataWithAesGcmKey({\n      dataToEncrypt,\n      aesGcmKey: key,\n    });\n  }\n\n  async decryptDataFromLinkedClient({\n    dataToDecrypt,\n    linkedClientId,\n  }: IDecryptDataFromLinkedClient): Promise<string> {\n    const key = await this.getAesGcmKeyForLinkedClient(linkedClientId);\n\n    return await decryptTextDataWithAesGcmKey({\n      dataToDecrypt,\n      aesGcmKey: key,\n    });\n  }\n\n  /**\n   * Bytes counterpart of {@link encryptDataForLinkedClient} — encrypts raw bytes with the shared\n   * AES-GCM key, returning a binary nonce + ciphertext. Use it for binary channels (e.g. msgpack\n   * WebSocket frames) to avoid base64 inflation.\n   */\n  async encryptBytesForLinkedClient({\n    dataToEncrypt,\n    linkedClientId,\n  }: {\n    dataToEncrypt: Uint8Array;\n    linkedClientId: TTypeAndId;\n  }): Promise<TEncryptedAesGcmBytes> {\n    const key = await this.getAesGcmKeyForLinkedClient(linkedClientId);\n\n    return await encryptBytesWithAesGcmKey({\n      dataToEncrypt,\n      aesGcmKey: key,\n    });\n  }\n\n  /** Bytes counterpart of {@link decryptDataFromLinkedClient}. */\n  async decryptBytesFromLinkedClient({\n    dataToDecrypt,\n    linkedClientId,\n  }: {\n    dataToDecrypt: TEncryptedAesGcmBytes;\n    linkedClientId: TTypeAndId;\n  }): Promise<Uint8Array> {\n    const key = await this.getAesGcmKeyForLinkedClient(linkedClientId);\n\n    return await decryptBytesWithAesGcmKey({\n      dataToDecrypt,\n      aesGcmKey: key,\n    });\n  }\n\n  async signAndEncryptDataForLinkedClient({\n    dataToEncrypt,\n    linkedClientId,\n  }: IEncryptDataForLinkedClient): Promise<{\n    encryptedData: TEncryptedAesGcmPayload;\n    signatureBase64: string;\n  }> {\n    const { signatureBase64 } = await this.signChallenge([dataToEncrypt]);\n    const encryptedData = await this.encryptDataForLinkedClient({\n      dataToEncrypt,\n      linkedClientId,\n    });\n\n    return {\n      encryptedData,\n      signatureBase64,\n    };\n  }\n\n  /**\n   * Decrypts a payload from a linked client and verifies that the decrypted plaintext was signed\n   * by that client. Counterpart to {@link signAndEncryptDataForLinkedClient}.\n   *\n   * Returns the decrypted `data` alongside `isValid` — the caller decides how to handle an invalid\n   * signature. (A tampered ciphertext fails earlier at AES-GCM decryption.)\n   */\n  async decryptAndVerifyDataFromLinkedClient({\n    dataToDecrypt,\n    linkedClientId,\n    signatureBase64,\n  }: IDecryptAndVerifyDataFromLinkedClient): Promise<{ data: string; isValid: boolean }> {\n    const data = await this.decryptDataFromLinkedClient({\n      dataToDecrypt,\n      linkedClientId,\n    });\n\n    const isValid = await this.verifyChallengeFromLinkedClient({\n      linkedClientId,\n      challenge: data,\n      signatureBase64,\n    });\n\n    return { data, isValid };\n  }\n\n  /**\n   * ⚠ Multi-part challenges join with `\"::\"` — a **concatenation-ambiguity** hazard: when a caller\n   * controls two adjacent parts, distinct tuples can produce identical signed bytes (`[\"a::b\"]`\n   * vs `[\"a\",\"b\"]`), and two operations' challenges can collide unless every call site remembers\n   * its own fixed tag. Prefer {@link signChallengeCanonical}: domain-tagged, versioned, exact\n   * field boundaries by construction. This method stays byte-for-byte for deployed contracts.\n   */\n  async signChallenge(challenge: [string, ...string[]]): Promise<{\n    signatureBase64: string;\n  }> {\n    if (challenge.length === 0) {\n      throw new Error(\"Challenge must contain at least one string\");\n    }\n\n    const localVerifyKeyPair = await this.ensureLocalVerifyKeyPair();\n\n    const signature =\n      challenge.length > 1\n        ? await signCombinedTextDataWithKeyEd25519(challenge, localVerifyKeyPair.privateKey)\n        : await signTextDataWithKeyEd25519(challenge[0], localVerifyKeyPair.privateKey);\n\n    return {\n      signatureBase64: base64.encode(signature),\n    };\n  }\n\n  /**\n   * Sign a {@link ICanonicalChallenge} — the canonical, domain-tagged, versioned challenge form\n   * ({@link buildCanonicalChallenge} defines the signed bytes). Same key and signature scheme as\n   * {@link signChallenge}, safer byte layout; the verify dual is\n   * {@link verifyChallengeCanonicalFromLinkedClient}, which takes the same structured challenge.\n   */\n  async signChallengeCanonical(challenge: ICanonicalChallenge): Promise<{\n    signatureBase64: string;\n  }> {\n    return this.signChallenge([buildCanonicalChallenge(challenge)]);\n  }\n\n  /**\n   * Verify a signature produced by {@link signChallengeCanonical} against the linked client's\n   * verify key. Takes the **structured** challenge and rebuilds the canonical string itself, so\n   * signer and verifier can never disagree on byte construction.\n   */\n  async verifyChallengeCanonicalFromLinkedClient({\n    linkedClientId,\n    challenge,\n    signatureBase64,\n  }: {\n    linkedClientId: TTypeAndId;\n    challenge: ICanonicalChallenge;\n    signatureBase64: string;\n  }): Promise<boolean> {\n    return this.verifyChallengeFromLinkedClient({\n      linkedClientId,\n      challenge: buildCanonicalChallenge(challenge),\n      signatureBase64,\n    });\n  }\n\n  /**\n   * Verifies a signature over `challenge` against the linked client's verify (Ed25519) public key.\n   */\n  async verifyChallengeFromLinkedClient({\n    linkedClientId,\n    challenge,\n    signatureBase64,\n  }: IVerifyChallengeFromLinkedClient): Promise<boolean> {\n    const linkedClient = this.getLinkedClient(linkedClientId);\n\n    if (linkedClient.verify?.publicKey == null) {\n      throw new Error(`ClientCryptoKeyLink: No verify public key set for ${linkedClientId}`);\n    }\n\n    return await verifyWithKeyEd25519({\n      challenge,\n      signatureBase64,\n      publicKey: linkedClient.verify.publicKey,\n    });\n  }\n}\n","import {\n  EStorageAdapterType,\n  type IStorageKeyGetterAndSetter,\n  type TStorageAdapterMethods,\n} from \"./storage_adapter.types\";\nimport { createTypedStorage, type ITypedStorage } from \"./typed_storage/createTypedStorage\";\n\nexport interface IStorageAdapterConstructor {\n  methods: TStorageAdapterMethods;\n  trackKeysForClearing?: boolean;\n  keyPrefix?: string;\n}\n\ninterface IStorageAdapterTypedStorage {\n  __usedKeys__: string[];\n}\n\nexport class StorageAdapter {\n  private implementation: TStorageAdapterMethods;\n  readonly keyPrefix: string;\n  /**\n   * Whether the backing store outlives a page reload / process restart (from the methods'\n   * {@link TStorageAdapterMethods} `durable` flag). `false` on the memory and web-session adapters,\n   * `true` on localStorage / Durable Object / KV, `undefined` (unknown) on custom methods.\n   */\n  readonly durable: boolean | undefined;\n  private readonly trackKeysForClearing: boolean;\n  private readonly adapterStorage?: ITypedStorage<IStorageAdapterTypedStorage>;\n\n  /**\n   * Serializes mutations of the `__usedKeys__` index so its read-modify-write cycles can't\n   * interleave. Without this, two overlapping `trackUsedKey`/`untrackUsedKey` calls each read the\n   * old index and the later write clobbers the earlier one (last-writer-wins), silently dropping\n   * entries — so `clearAll` leaves those keys behind. The window is negligible on synchronous\n   * stores (localStorage) but wide on real async I/O (React Native AsyncStorage), where it routinely\n   * corrupts a client-identity reset. See docs/issues/storage-adapter-clearall-react-native.md.\n   */\n  private indexMutationChain: Promise<unknown> = Promise.resolve();\n\n  constructor({ methods, keyPrefix, trackKeysForClearing: trackKeys }: IStorageAdapterConstructor) {\n    this.implementation = methods;\n    this.durable = methods.durable;\n    this.keyPrefix = keyPrefix ?? \"\";\n    const _trackKeys = trackKeys ?? true;\n    this.trackKeysForClearing = _trackKeys;\n    // Only create keyStorage when tracking is enabled; the inner adapter has trackKeys:false so\n    // its constructor skips this branch, breaking the infinite-recursion cycle.\n    this.adapterStorage = _trackKeys\n      ? createTypedStorage({\n          storageAdapter: new StorageAdapter({ methods, keyPrefix, trackKeysForClearing: false }),\n        })\n      : undefined;\n  }\n\n  private getPrefixedKey(rawKey: string): string {\n    return `${this.keyPrefix}${rawKey}`;\n  }\n\n  /**\n   * Runs `fn` after every previously-enqueued index mutation has settled, so the index's\n   * read-modify-write cycles execute one at a time per adapter instance. Failures don't break the\n   * chain — the next waiter still runs.\n   */\n  private withIndexLock<T>(fn: () => Promise<T>): Promise<T> {\n    const run = this.indexMutationChain.then(fn, fn);\n    this.indexMutationChain = run.then(\n      () => undefined,\n      () => undefined,\n    );\n    return run;\n  }\n\n  /**\n   * Derive a new adapter over the *same* backing store with an extra key-prefix segment appended.\n   * Lets an independent namespace (e.g. a second crypto identity) share one underlying storage without\n   * key collisions. Key-tracking policy is inherited: deriving from an intentionally untracked\n   * adapter must not silently create a `__usedKeys__` index.\n   */\n  withKeyPrefix(extraPrefix: string): StorageAdapter {\n    return new StorageAdapter({\n      methods: this.implementation,\n      keyPrefix: `${this.keyPrefix}${extraPrefix}`,\n      trackKeysForClearing: this.trackKeysForClearing,\n    });\n  }\n\n  private async trackUsedKey(rawKey: string): Promise<void> {\n    const adapterStorage = this.adapterStorage;\n    if (!adapterStorage) return;\n    await this.withIndexLock(() =>\n      adapterStorage.updateJsonWithDef(\"__usedKeys__\", [], (currentKeys) => {\n        if (!currentKeys.includes(rawKey)) {\n          return [...currentKeys, rawKey];\n        }\n        return currentKeys;\n      }),\n    );\n  }\n\n  private async untrackUsedKey(rawKey: string): Promise<void> {\n    const adapterStorage = this.adapterStorage;\n    if (!adapterStorage) return;\n    await this.withIndexLock(() =>\n      adapterStorage.updateJsonWithDef(\"__usedKeys__\", [], (currentKeys) => {\n        return currentKeys.filter((k) => k !== rawKey);\n      }),\n    );\n  }\n\n  async clearAll(): Promise<void> {\n    const adapterStorage = this.adapterStorage;\n    if (!adapterStorage) return;\n\n    // Read the index, delete its keys, and reset it as a single locked unit so the read can't race\n    // a concurrent track/untrack (which would otherwise re-add an entry we just observed as empty,\n    // or be clobbered by our reset). Keys are removed directly via the implementation rather than\n    // through `removeItem` — both to skip redundant per-key untracking (the whole index is reset to\n    // `[]` here) and to avoid re-entering this same lock, which would deadlock.\n    await this.withIndexLock(async () => {\n      const allKeys = (await adapterStorage.getJsonOrDef(\"__usedKeys__\", [])) ?? [];\n\n      await Promise.all(\n        allKeys.map((key) => this.implementation.removeItem(this.getPrefixedKey(key))),\n      );\n\n      // Remove the index key itself rather than resetting it to `[]`, so the namespace is left\n      // genuinely empty; a subsequent setJson re-creates it lazily.\n      await adapterStorage.removeItem(\"__usedKeys__\");\n    });\n  }\n\n  async removeItem(rawKey: string): Promise<void> {\n    await this.implementation.removeItem(this.getPrefixedKey(rawKey));\n    await this.untrackUsedKey(rawKey);\n  }\n\n  async setJson(rawKey: string, value: any) {\n    const key = this.getPrefixedKey(rawKey);\n\n    if (this.implementation.type === EStorageAdapterType.string) {\n      await this.implementation.setItem(key, JSON.stringify(value));\n    } else {\n      await this.implementation.setItem(key, value);\n    }\n\n    await this.trackUsedKey(rawKey);\n  }\n\n  async getJson<T>(rawKey: string): Promise<T | undefined> {\n    const key = this.getPrefixedKey(rawKey);\n\n    if (this.implementation.type === EStorageAdapterType.string) {\n      const val = await this.implementation.getItem(key);\n\n      if (val == null || val === \"undefined\" || val === \"null\") {\n        return undefined;\n      }\n\n      return JSON.parse(val);\n    } else {\n      const val = await this.implementation.getItem<T>(key);\n\n      if (val == null || val === \"undefined\" || val === \"null\") {\n        return undefined;\n      }\n\n      return val;\n    }\n  }\n\n  async getJsonOrDef<T>(rawKey: string, defVal: T): Promise<T> {\n    if (this.implementation.type === EStorageAdapterType.string) {\n      const val = await this.implementation.getItem(this.getPrefixedKey(rawKey));\n\n      if (val == null || val === \"undefined\" || val === \"null\") {\n        return defVal;\n      }\n\n      return JSON.parse(val);\n    }\n\n    const val = await this.implementation.getItem<T>(this.getPrefixedKey(rawKey));\n\n    if (val == null || val === \"undefined\" || val === \"null\") {\n      return defVal;\n    }\n\n    return val;\n  }\n\n  async updateJson<T>(rawKey: string, updater: (currentVal: T | undefined) => T): Promise<T> {\n    const currentVal = await this.getJson<T>(rawKey);\n    const newVal = updater(currentVal);\n    await this.setJson(rawKey, newVal);\n    return newVal;\n  }\n\n  async updateJsonOrDef<T>(rawKey: string, defVal: T, updater: (currentVal: T) => T): Promise<T> {\n    const currentVal = await this.getJsonOrDef<T>(rawKey, defVal);\n    const newVal = updater(currentVal);\n    await this.setJson(rawKey, newVal);\n    return newVal;\n  }\n\n  createJsonGetterSetter<T>(rawKey: string): IStorageKeyGetterAndSetter<T> {\n    return {\n      get: () => this.getJson(rawKey),\n      set: (value: T) => this.setJson(rawKey, value),\n    };\n  }\n}\n","import { type IStorageAdapterConstructor, StorageAdapter } from \"../../StorageAdapter\";\nimport {\n  EStorageAdapterType,\n  type IStorageAdapterMethods_Json,\n  type IStorageAdapterMethods_String,\n} from \"../../storage_adapter.types\";\nimport {\n  createTypedStorage,\n  type ITypedStorage,\n  type ITypedStorageValidationOptions,\n} from \"../../typed_storage/createTypedStorage\";\n\nexport type TMemoryStorage_string = Map<string, string>;\nexport type TMemoryStorage_json = Map<string, any>;\n\n/**\n *\n * Memory Storage [STRING]\n *\n */\n\ntype TCreateMemoryStorageOptions_string = Omit<IStorageAdapterConstructor, \"methods\"> & {\n  memoryStorageMap?: TMemoryStorage_string;\n};\n\nexport function createMemoryStorageMethods_string(\n  memoryStorageMap: TMemoryStorage_string = new Map(),\n): IStorageAdapterMethods_String {\n  return {\n    type: EStorageAdapterType.string,\n    durable: false,\n    getItem: async (key) => memoryStorageMap.get(key) ?? null,\n    setItem: async (key, value) => {\n      memoryStorageMap.set(key, value);\n    },\n    removeItem: async (key) => {\n      memoryStorageMap.delete(key);\n    },\n  };\n}\n\nexport const createMemoryStorageAdapter_string = (\n  options?: TCreateMemoryStorageOptions_string,\n): StorageAdapter => {\n  return new StorageAdapter({\n    methods: createMemoryStorageMethods_string(options?.memoryStorageMap),\n    ...options,\n  });\n};\n\nexport function createTypedMemoryStorage_string<T extends Record<string, any>>(\n  options?: TCreateMemoryStorageOptions_string & ITypedStorageValidationOptions<T>,\n): ITypedStorage<T> {\n  const { schemas, onInvalid, ...adapterOptions } = options ?? {};\n  return createTypedStorage<T>({\n    storageAdapter: createMemoryStorageAdapter_string(adapterOptions),\n    schemas,\n    onInvalid,\n  });\n}\n\n/**\n *\n * Memory Storage [JSON]\n *\n */\n\ntype TCreateMemoryStorageOptions_json = Omit<IStorageAdapterConstructor, \"methods\"> & {\n  memoryStorageMap?: TMemoryStorage_json;\n};\n\nexport function createMemoryStorageMethods_json(\n  memoryStorageMap: TMemoryStorage_json = new Map(),\n): IStorageAdapterMethods_Json {\n  return {\n    type: EStorageAdapterType.json,\n    durable: false,\n    getItem: async (key) => memoryStorageMap.get(key),\n    setItem: async (key, value) => {\n      memoryStorageMap.set(key, value);\n    },\n    removeItem: async (key) => {\n      memoryStorageMap.delete(key);\n    },\n  };\n}\n\nexport const createMemoryStorageAdapter_json = (\n  options?: TCreateMemoryStorageOptions_json,\n): StorageAdapter => {\n  return new StorageAdapter({\n    methods: createMemoryStorageMethods_json(options?.memoryStorageMap),\n    ...options,\n  });\n};\n\nexport function createTypedMemoryStorage_json<T extends Record<string, any>>(\n  options?: TCreateMemoryStorageOptions_json & ITypedStorageValidationOptions<T>,\n): ITypedStorage<T> {\n  const { schemas, onInvalid, ...adapterOptions } = options ?? {};\n  return createTypedStorage<T>({\n    storageAdapter: createMemoryStorageAdapter_json(adapterOptions),\n    schemas,\n    onInvalid,\n  });\n}\n","/**\n * Detach a pending timer from the event loop so it never, by itself, keeps a Node process (or a\n * test runner) alive — a no-op in browsers and Workers, where a timer handle is a plain `number`\n * with no `unref`.\n *\n * It exists to keep the one cross-environment shape difference in a single place instead of at every\n * timer site: the `ReturnType<typeof setTimeout>` a caller holds is `NodeJS.Timeout` under Node (it\n * carries `unref`) and a bare `number` under the DOM lib (it does not). Typing the parameter as the\n * union of both lets every `setTimeout` handle pass without a cast, and the `typeof` narrows to the\n * only arm that has the method.\n */\nexport function unrefTimer(timer: number | { unref?: () => void }): void {\n  if (typeof timer !== \"number\") timer.unref?.();\n}\n","export let urlAlphabet =\n  'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'\n","import { webcrypto as crypto } from 'node:crypto'\n\nimport { urlAlphabet as scopedUrlAlphabet } from './url-alphabet/index.js'\n\nexport { urlAlphabet } from './url-alphabet/index.js'\n\nconst POOL_SIZE_MULTIPLIER = 128\nlet pool, poolOffset\n\nfunction fillPool(bytes) {\n  if (bytes < 0) throw new RangeError('Wrong ID size')\n  try {\n    if (!pool || pool.length < bytes) {\n      pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER)\n      crypto.getRandomValues(pool)\n      poolOffset = 0\n    } else if (poolOffset + bytes > pool.length) {\n      crypto.getRandomValues(pool)\n      poolOffset = 0\n    }\n  } catch (e) {\n    pool = undefined\n    throw e\n  }\n  poolOffset += bytes\n}\n\nexport function random(bytes) {\n  fillPool((bytes |= 0))\n  return pool.subarray(poolOffset - bytes, poolOffset)\n}\n\nexport function customRandom(alphabet, defaultSize, getRandom) {\n  let safeByteCutoff = 256 - (256 % alphabet.length)\n\n  if (safeByteCutoff === 256) {\n    let mask = alphabet.length - 1\n\n    return (size = defaultSize) => {\n      if (!size) return ''\n      let id = ''\n      while (true) {\n        let bytes = getRandom(size)\n        let i = size\n        while (i--) {\n          id += alphabet[bytes[i] & mask]\n          if (id.length >= size) return id\n        }\n      }\n    }\n  }\n\n  let step = Math.ceil((1.6 * 256 * defaultSize) / safeByteCutoff)\n\n  return (size = defaultSize) => {\n    if (!size) return ''\n    let id = ''\n    while (true) {\n      let bytes = getRandom(step)\n      let i = step\n      while (i--) {\n        if (bytes[i] < safeByteCutoff) {\n          id += alphabet[bytes[i] % alphabet.length]\n          if (id.length >= size) return id\n        }\n      }\n    }\n  }\n}\n\nexport function customAlphabet(alphabet, size = 21) {\n  return customRandom(alphabet, size, random)\n}\n\nexport function nanoid(size = 21) {\n  fillPool((size |= 0))\n\n  let id = ''\n  for (let i = poolOffset - size; i < poolOffset; i++) {\n    id += scopedUrlAlphabet[pool[i] & 63]\n  }\n  return id\n}\n","/**\n * The first-party nice-code wire/action/realm format generation implemented by this build.\n *\n * Package releases may change without changing this number. A generation belongs in\n * {@link WIRE_SUPPORTED_PROTOCOL_VERSIONS} only while this build contains the complete encoder,\n * decoder, session, and persistence compatibility needed to speak it.\n */\nexport const WIRE_PROTOCOL_VERSION = 1 as const;\n\n/**\n * Protocol generations this build can actually speak, newest first. This release has one codec,\n * so it advertises only v1; the intended future window is the current and previous generation.\n */\nexport const WIRE_SUPPORTED_PROTOCOL_VERSIONS = [WIRE_PROTOCOL_VERSION] as const;\n","export const DEFAULT_TRANSPORT_TIMEOUT = 10000; // 10 seconds\nexport const UNSET_RUNTIME_ENV_ID = \"_unset_\";\nexport const UNSET_RUNTIME_PER_ID = \"_0_0_\";\n","import type { IRuntimeCoordinate, TRuntimeCoordinateStringId } from \"../RuntimeCoordinate\";\n\nexport function runtimeCoordinateToStringIds(\n  coordinate: IRuntimeCoordinate,\n): TRuntimeCoordinateStringId[] {\n  return [\n    `envId[${coordinate.envId}]perId[${coordinate.perId ?? \"_\"}]:insId[${coordinate.insId ?? \"_\"}]`,\n    `envId[${coordinate.envId}]perId[${coordinate.perId ?? \"_\"}]:insId[_]`,\n    `envId[${coordinate.envId}]perId[_]:insId[_]`,\n  ];\n}\n","import { UNSET_RUNTIME_ENV_ID } from \"./nice_wire.static\";\nimport { runtimeCoordinateToStringIds } from \"./utils/runtimeCoordinateToStringIds\";\n\nexport interface IRuntimeCoordinateSpecifics {\n  /**\n   * A unique and persistent client ID (should stay the same between runtime instance reloads).\n   *\n   * **This id keys the server's trust-on-first-use verify-key pin** (`envId::perId`): the first\n   * verify key a server sees for it is pinned, and a different key is rejected forever after\n   * (`identity_pin_mismatch`). So the connection's crypto-identity `storage` must persist **at\n   * least as long as this id does** — a persistent id read from localStorage paired with a\n   * memory-backed identity store bricks the client on its second load ({@link\n   * RuntimeCoordinate.withPersistentId}).\n   */\n  perId?: string;\n  /**\n   * A unique instance (or \"memory-only\") ID (unique for each instance of an action runtime, which should generally\n   * not persist between reloads, depending on the architecture).\n   *\n   * **Reliable-delivery epoch contract:** reliable streams are keyed by the *full* coordinate string\n   * (`envId`/`perId`/`insId`), and a receiver dedups any `seq` at or below its retained high-water. A\n   * fresh boot restarts its outbox at seq 0 — so a reloaded client presenting the *same* full coordinate\n   * would have its first frames silently swallowed as duplicates of the previous session. A fresh-per-boot\n   * `insId` is what makes that structurally impossible: `ActionRuntime` **generates a random one on\n   * first coordinate use when unset**. Only set `insId` yourself if it is genuinely unique per process boot.\n   */\n  insId?: string;\n}\n\nexport interface IRuntimeCoordinate extends IRuntimeCoordinateSpecifics {\n  /**\n   * A static runtime environment identifier (e.g. \"web_app_v1\", \"backend_analytics\")\n   */\n  envId: string;\n}\n\nexport type TRuntimeCoordinateEnvId = `envId[${string}]`;\n\nexport type TRuntimeCoordinateStringId =\n  `${TRuntimeCoordinateEnvId}perId[${string | \"_\"}]:insId[${string | \"_\"}]`;\n\nexport interface IRuntimeFullCoordinates extends Required<IRuntimeCoordinate> {}\n\nexport class RuntimeCoordinate implements IRuntimeCoordinate {\n  readonly envId: string;\n  readonly perId?: string;\n  readonly insId?: string;\n\n  /** Readable alias for {@link perId}; the serialized own field remains `perId`. */\n  get persistentId(): string | undefined {\n    return this.perId;\n  }\n\n  /** Readable alias for {@link insId}; the serialized own field remains `insId`. */\n  get instanceId(): string | undefined {\n    return this.insId;\n  }\n\n  static get unknown(): RuntimeCoordinate {\n    return new RuntimeCoordinate({\n      envId: UNSET_RUNTIME_ENV_ID,\n    });\n  }\n\n  static env(envId: string): RuntimeCoordinate {\n    return new RuntimeCoordinate({\n      envId: envId,\n    });\n  }\n\n  /**\n   * Env + persistent id — but not *merely* a routing name: on a secure connection this id\n   * keys the server's trust-on-first-use verify-key pin (see {@link IRuntimeCoordinateSpecifics.perId}).\n   * Pair it only with a crypto-identity `storage` that persists at least as long as the id itself,\n   * or every reload presents a new key for a pinned id and is rejected (`identity_pin_mismatch`).\n   */\n  withPersistentId(perId: string): RuntimeCoordinate {\n    return this.specify({ perId });\n  }\n\n  /**\n   * Derive a **per-connection** identity: same env and persistent id, with `connectionId` folded into\n   * the per-boot `insId`. For a runtime that opens *several duplex links to the same peer* — a store\n   * socket and a jobs socket on one backend — where one identity for both is a silent misroute: an\n   * acceptor binds a connection by the full coordinate string, so two links presenting the same one\n   * are indistinguishable and the peer's return path picks whichever bound first.\n   *\n   * Folding rather than replacing is the point: the runtime's `insId` stays the per-boot epoch\n   * reliable delivery needs (see {@link IRuntimeCoordinateSpecifics.insId}), so a per-connection id may\n   * safely be a *stable* label (`\"jobs\"`) — it discriminates connections without pinning the epoch.\n   * Reached from `connectChannel`'s `connectionId` option; rarely called directly.\n   */\n  withConnectionId(connectionId: string): RuntimeCoordinate {\n    if (connectionId.length === 0 || /[[\\]:~]/.test(connectionId)) {\n      throw new Error(\n        `RuntimeCoordinate.withConnectionId: \"${connectionId}\" is not a usable connection id — it must ` +\n          \"be non-empty and free of `[`, `]`, `:` and `~` (the coordinate's own string-form separators).\",\n      );\n    }\n    return this.specify({ insId: `${this.insId ?? \"_\"}~${connectionId}` });\n  }\n\n  constructor({ envId, perId, insId }: IRuntimeCoordinate) {\n    this.envId = envId;\n    this.perId = perId;\n    this.insId = insId;\n  }\n\n  specify(specifics: IRuntimeCoordinateSpecifics): RuntimeCoordinate {\n    return new RuntimeCoordinate({\n      envId: this.envId,\n      perId: this.perId,\n      insId: this.insId,\n      ...specifics,\n    });\n  }\n\n  specifyIfUnset(specifics: IRuntimeCoordinateSpecifics): RuntimeCoordinate {\n    return new RuntimeCoordinate({\n      envId: this.envId,\n      perId: this.perId ?? specifics.perId,\n      insId: this.insId ?? specifics.insId,\n    });\n  }\n\n  toJsonObject(): IRuntimeCoordinate {\n    return {\n      envId: this.envId,\n      perId: this.perId,\n      insId: this.insId,\n    };\n  }\n\n  isExactlySame(other: IRuntimeCoordinate): boolean {\n    return this.envId === other.envId && this.perId === other.perId && this.insId === other.insId;\n  }\n\n  isSameFor(other: IRuntimeCoordinate): { id: boolean; perId: boolean; insId: boolean } {\n    return {\n      id: this.envId === other.envId,\n      perId: this.envId === other.envId && this.perId === other.perId,\n      insId: this.envId === other.envId && this.perId === other.perId && this.insId === other.insId,\n    };\n  }\n\n  similarityLevel(other: IRuntimeCoordinate): number {\n    const sameFor = this.isSameFor(other);\n    if (sameFor.insId) return 3;\n    if (sameFor.perId) return 2;\n    if (sameFor.id) return 1;\n    return 0;\n  }\n\n  get stringId(): TRuntimeCoordinateStringId {\n    return `envId[${this.envId}]perId[${this.perId ?? \"_\"}]:insId[${this.insId ?? \"_\"}]`;\n  }\n\n  /**\n   * Takes the \"Runtime Coordinate\" and generates a list of full coordinate IDs representing the runtime\n   * with decreasing levels of specificity.\n   *\n   * The first full coordinate ID is the most specific (including instance ID), while the last ID is\n   * the least specific (only environment ID).\n   *\n   * Example output for a RuntimeCoordinate with envId \"web_app\", perId \"user123\", and insId \"instance456\":\n   * [\n   *   \"envId[web_app]perId[user123]:insId[instance456]\",\n   *   \"envId[web_app]perId[user123]:insId[_]\",\n   *   \"envId[web_app]perId[_]:insId[_]\"\n   * ]\n   *\n   * @returns a list of \"full\" runtime coordinate IDs with decreasing accuracy for targeting a runtime.\n   */\n  toStringIds(): TRuntimeCoordinateStringId[] {\n    return runtimeCoordinateToStringIds(this);\n  }\n}\n","import {\n  type ClientCryptoKeyLink,\n  createTypedStorage,\n  type StorageAdapter,\n  type TSerializedCryptoKeyData_Ed25519_Raw,\n  type TSerializedCryptoKeyData_X25519_Raw,\n  type TTypeAndId,\n} from \"@nice-code/util\";\nimport { nanoid } from \"nanoid\";\nimport * as v from \"valibot\";\nimport { err_wire_connect } from \"../Connect/err_wire_connect\";\nimport { WIRE_PROTOCOL_VERSION, WIRE_SUPPORTED_PROTOCOL_VERSIONS } from \"../protocolVersion\";\nimport { type IRuntimeCoordinate, RuntimeCoordinate } from \"../RuntimeCoordinate\";\n\n/**\n * Authenticated handshake for the WebSocket channel. Run once per connection, before any action\n * frames flow, it:\n * - exchanges each side's {@link RuntimeCoordinate} + public keys,\n * - checks both ends share the same wire dictionary version (closes the positional-dictionary footgun),\n * - has the client prove control of its verify (Ed25519) key by signing a fresh challenge that binds\n *   both nonces, both identities, the dictionary version, the level, and every exchanged public key,\n * - establishes a `ClientCryptoKeyLink` link on both sides (so the server can verify the signature and,\n *   for the `encrypted` level, both can derive a shared AES-GCM key with the verify keys folded in).\n *\n * This module is transport-agnostic: it produces/consumes message objects. The transport + server\n * handler drive the I/O and the connection phase (Step 4). Keep `none`-level connections from ever\n * reaching here — they skip the handshake entirely.\n */\n\n// Protocol v1 is the already-shipped nice-ws-hs/1 transcript. Deriving the tag from the public\n// constant pins that mapping without changing a byte of the hello, signed challenge, or KDF info.\nconst HANDSHAKE_PROTOCOL = `nice-ws-hs/${WIRE_PROTOCOL_VERSION}`;\nconst HANDSHAKE_PROTOCOL_PREFIX = \"nice-ws-hs/\";\n\n/**\n * Capability advertised by both peers in the handshake (`hello.caps` / `welcome.caps`) when they understand\n * the reliable-delivery wire (the 7-slot reliability frame). It lets a `.reliable()` sender detect a peer\n * that predates reliable support and warn + degrade to best-effort, instead of emitting frames the peer\n * can't interpret. Non-signed and optional, exactly like `channels` — an old peer simply omits it.\n */\nexport const CAP_RELIABLE = \"reliable\";\n\n/**\n * Capability (E3) advertised when a peer understands **keyed** reliable streams (the length-8 `streamKey`\n * frame + the `k` field on `rack`/`rsync` control frames). Lets a keyed `.reliable()` sender detect a peer\n * that predates per-key streams and warn (a keyed frame is a distinct length such a peer drops wholesale).\n * Non-signed and optional, layered on {@link CAP_RELIABLE}.\n */\nexport const CAP_RELIABLE_STREAMKEY = \"reliable-streamkey\";\n\n/** How much the channel protects after the handshake — chosen by the consumer (perf vs security). */\nexport enum ESecurityLevel {\n  /** No handshake; identity is self-asserted (fastest, dev / trusted networks). */\n  none = \"none\",\n  /** Handshake authenticates identity (sign/verify + key pin); frames stay plaintext over TLS. */\n  authenticated = \"authenticated\",\n  /** Authenticated handshake + every frame AES-GCM encrypted with the derived shared key. */\n  encrypted = \"encrypted\",\n}\n\nexport enum EHandshakeMessageType {\n  hello = \"hello\",\n  welcome = \"welcome\",\n  prove = \"prove\",\n  accept = \"accept\",\n  reject = \"reject\",\n}\n\n// --- wire message schemas (these arrive untrusted from the network) --------------------------------\n\nconst vEd25519Raw = v.custom<TSerializedCryptoKeyData_Ed25519_Raw>(\n  (val) => typeof val === \"string\" && val.startsWith(\"ed25519::raw_base64::\"),\n);\nconst vX25519Raw = v.custom<TSerializedCryptoKeyData_X25519_Raw>(\n  (val) => typeof val === \"string\" && val.startsWith(\"x25519::raw_base64::\"),\n);\nconst vCoordinate = v.object({\n  envId: v.string(),\n  perId: v.optional(v.string()),\n  insId: v.optional(v.string()),\n});\nconst vSecurityLevel = v.picklist([\n  ESecurityLevel.none,\n  ESecurityLevel.authenticated,\n  ESecurityLevel.encrypted,\n]);\n\nconst vHsHello = v.object({\n  t: v.literal(EHandshakeMessageType.hello),\n  protocol: v.string(),\n  securityLevel: vSecurityLevel,\n  dictionaryVersion: v.string(),\n  client: vCoordinate,\n  clientNonce: v.string(),\n  verifyPublicKey: vEd25519Raw,\n  exchangePublicKey: v.optional(vX25519Raw),\n  /**\n   * The channel tags this connection carries (`channel.tags`). A multi-channel acceptor composes the\n   * codec + dictionary version for exactly this subset; omitted by a plain single-channel client. Not part\n   * of the signed challenge — tampering would compose a different `dictionaryVersion` and fail the check.\n   */\n  channels: v.optional(v.array(v.string())),\n  /**\n   * Optional capability tags this client understands (e.g. {@link CAP_RELIABLE}). Not part of the signed\n   * challenge — purely a feature advertisement, so a peer that omits it is treated as not supporting them.\n   */\n  caps: v.optional(v.array(v.string())),\n});\n\nconst vHsWelcome = v.object({\n  t: v.literal(EHandshakeMessageType.welcome),\n  securityLevel: vSecurityLevel,\n  dictionaryVersion: v.string(),\n  server: vCoordinate,\n  serverNonce: v.string(),\n  verifyPublicKey: vEd25519Raw,\n  exchangePublicKey: v.optional(vX25519Raw),\n  /** Optional capability tags this server understands (e.g. {@link CAP_RELIABLE}); see {@link vHsHello.caps}. */\n  caps: v.optional(v.array(v.string())),\n});\n\nconst vHsProve = v.object({\n  t: v.literal(EHandshakeMessageType.prove),\n  signatureBase64: v.string(),\n});\n\nconst vHsAccept = v.object({\n  t: v.literal(EHandshakeMessageType.accept),\n  signatureBase64: v.optional(v.string()),\n});\n\nconst vHsReject = v.object({\n  t: v.literal(EHandshakeMessageType.reject),\n  reason: v.string(),\n  /**\n   * Optional machine-readable reject id (e.g. {@link HANDSHAKE_REJECT_ID_PIN_MISMATCH}) so the\n   * dialing side can *branch* on the cause instead of parsing the English `reason` (Inteleport\n   * feedback §3). Additive + optional: an old peer neither sends nor reads it (unknown keys are\n   * stripped on decode), so the frame stays wire-compatible in both directions.\n   */\n  id: v.optional(v.string()),\n  /** The unsupported generation observed by the rejecting peer, when the tag was well formed. */\n  observedProtocolVersion: v.optional(v.number()),\n  /** The generations the rejecting peer can actually speak, newest first. */\n  supportedProtocolVersions: v.optional(v.array(v.number())),\n});\n\nconst vHandshakeMessage = v.variant(\"t\", [vHsHello, vHsWelcome, vHsProve, vHsAccept, vHsReject]);\n\nexport type THsHello = v.InferOutput<typeof vHsHello>;\nexport type THsWelcome = v.InferOutput<typeof vHsWelcome>;\nexport type THsProve = v.InferOutput<typeof vHsProve>;\nexport type THsAccept = v.InferOutput<typeof vHsAccept>;\nexport type THsReject = v.InferOutput<typeof vHsReject>;\nexport type THandshakeMessage = v.InferOutput<typeof vHandshakeMessage>;\n\n/** Serialize a handshake message for the wire (handshake frames are JSON — they aren't the hot path). */\nexport function encodeHandshakeMessage(message: THandshakeMessage): string {\n  return JSON.stringify(message);\n}\n\n/** Parse + structurally validate an incoming handshake frame; `undefined` if it isn't one. */\nexport function decodeHandshakeMessage(raw: string): THandshakeMessage | undefined {\n  let parsed: unknown;\n  try {\n    parsed = JSON.parse(raw);\n  } catch {\n    return undefined;\n  }\n  const result = v.safeParse(vHandshakeMessage, parsed);\n  return result.success ? result.output : undefined;\n}\n\n// --- helpers ---------------------------------------------------------------------------------------\n\n/** Stable link id for a runtime coordinate — the key both the crypto link and the connection use. */\nexport function runtimeLinkId(coordinate: IRuntimeCoordinate): TTypeAndId {\n  return `runtime::${new RuntimeCoordinate(coordinate).stringId}`;\n}\n\nfunction coordId(coordinate: IRuntimeCoordinate): string {\n  return new RuntimeCoordinate(coordinate).stringId;\n}\n\nfunction sessionSalt(clientNonce: string, serverNonce: string): string {\n  return `${clientNonce}::${serverNonce}`;\n}\n\nfunction handshakeInfo(dictionaryVersion: string): string {\n  return `${HANDSHAKE_PROTOCOL}::${dictionaryVersion}`;\n}\n\n/**\n * The exact string both sides sign/verify. JSON-encoded ordered array so field boundaries are\n * unambiguous; binds identities, nonces (freshness), version, level, and all exchanged public keys\n * (authenticating the keys via the signature, complementing `bindVerifyKeysIntoDerivation`).\n */\nfunction buildHandshakeChallenge(parts: {\n  securityLevel: ESecurityLevel;\n  dictionaryVersion: string;\n  clientCoordId: string;\n  serverCoordId: string;\n  clientNonce: string;\n  serverNonce: string;\n  clientVerifyKey: string;\n  serverVerifyKey: string;\n  clientExchangeKey?: string;\n  serverExchangeKey?: string;\n}): string {\n  return JSON.stringify([\n    HANDSHAKE_PROTOCOL,\n    parts.securityLevel,\n    parts.dictionaryVersion,\n    parts.clientCoordId,\n    parts.serverCoordId,\n    parts.clientNonce,\n    parts.serverNonce,\n    parts.clientVerifyKey,\n    parts.serverVerifyKey,\n    parts.clientExchangeKey ?? \"_\",\n    parts.serverExchangeKey ?? \"_\",\n  ]);\n}\n\nfunction reject(reason: string, id?: string): THsReject {\n  return { t: EHandshakeMessageType.reject, reason, id };\n}\n\n/**\n * Everything needed to re-derive the shared AES-GCM key for an `encrypted` link after a restart —\n * the remote's public keys + the HKDF salt/info used at handshake time. The local (server) key pair is\n * recovered from its own persisted `ClientCryptoKeyLink` storage, so re-linking with this material\n * yields the identical shared key without a fresh handshake.\n */\nexport interface IHandshakeEncryptionKeyMaterial {\n  verifyPublicKey: TSerializedCryptoKeyData_Ed25519_Raw;\n  exchangePublicKey: TSerializedCryptoKeyData_X25519_Raw;\n  saltString: string;\n  infoString: string;\n  bindVerifyKeysIntoDerivation: boolean;\n}\n\n/** Outcome of a completed handshake — what the transport/handler needs to wire the channel. */\nexport interface IHandshakeResult {\n  /** The crypto-link id (and connection-registry key) for the authenticated remote. */\n  linkedClientId: TTypeAndId;\n  /** The remote's authenticated coordinate. */\n  remote: IRuntimeCoordinate;\n  securityLevel: ESecurityLevel;\n  /** For the `encrypted` level: material to restore the shared key after eviction (persist it). */\n  encryptionKeyMaterial?: IHandshakeEncryptionKeyMaterial;\n  /** Capability tags the remote advertised (`welcome.caps` for a client). Empty/absent = an old peer. */\n  remoteCaps?: readonly string[];\n}\n\n// --- pluggable trust (TOFU now, pre-provisioned later) ---------------------------------------------\n\nexport interface IClientVerifyKeyResolveInput {\n  client: IRuntimeCoordinate;\n  verifyPublicKey: TSerializedCryptoKeyData_Ed25519_Raw;\n}\n\n/**\n * The machine-readable reject id an untrusted verify key produces: the presented key differs from\n * the one pinned for this client identity (trust-on-first-use). Carried on the reject frame's `id`\n * and surfaced to the dialing side as `err_wire_connect` id `identity_pin_mismatch`, so an app can\n * branch on it (`err.hasId(\"identity_pin_mismatch\")`) — the obvious recovery being \"this identity\n * is unusable with this key: clear the client's identity storage / mint a new persistent id\".\n */\nexport const HANDSHAKE_REJECT_ID_PIN_MISMATCH = \"identity_pin_mismatch\";\n\n/** Machine-readable rejection for peers with no common first-party wire generation. */\nexport const HANDSHAKE_REJECT_ID_PROTOCOL_VERSION_MISMATCH = \"protocol_version_mismatch\";\n\nfunction handshakeProtocolVersion(protocol: string): number | undefined {\n  if (!protocol.startsWith(HANDSHAKE_PROTOCOL_PREFIX)) return undefined;\n  const raw = protocol.slice(HANDSHAKE_PROTOCOL_PREFIX.length);\n  if (!/^(0|[1-9]\\d*)$/.test(raw)) return undefined;\n  const parsed = Number(raw);\n  return Number.isSafeInteger(parsed) ? parsed : undefined;\n}\n\nexport interface IClientVerifyKeyResolver {\n  /**\n   * Decide whether a presented verify key is trusted for a client identity. The signature is already\n   * verified by the time this runs, so this is purely the identity-pinning decision. Swap in a\n   * persistent / pre-provisioned implementation without touching the protocol. An untrusted result\n   * may carry a machine-readable `rejectId` (e.g. {@link HANDSHAKE_REJECT_ID_PIN_MISMATCH}) beside\n   * the human `reason`; it rides the reject frame so the dialing side can branch on the cause.\n   */\n  resolve(\n    input: IClientVerifyKeyResolveInput,\n  ): Promise<{ trusted: boolean; reason?: string; rejectId?: string }>;\n}\n\nfunction tofuPinKey(client: IRuntimeCoordinate): string {\n  // Pin to the persistent identity (perId) so a client may reconnect with new instances (insId),\n  // but a changed verify key for the same persistent identity is rejected.\n  return `${client.envId}::${client.perId ?? client.insId ?? \"_\"}`;\n}\n\n/**\n * In-memory trust-on-first-use resolver: trusts (and pins) the first verify key seen for a client\n * identity, then rejects a different key for that identity. The default; replace with a storage-backed\n * resolver for cross-restart pinning (see Step 5).\n */\nexport function createInMemoryTofuVerifyKeyResolver(): IClientVerifyKeyResolver {\n  const pinned = new Map<string, string>();\n  return {\n    async resolve({ client, verifyPublicKey }) {\n      const key = tofuPinKey(client);\n      const existing = pinned.get(key);\n      if (existing == null) {\n        pinned.set(key, verifyPublicKey);\n        return { trusted: true };\n      }\n      if (existing === verifyPublicKey) return { trusted: true };\n      return {\n        trusted: false,\n        reason: \"verify key changed for client identity (pin mismatch)\",\n        rejectId: HANDSHAKE_REJECT_ID_PIN_MISMATCH,\n      };\n    },\n  };\n}\n\ninterface ITofuPinStorage {\n  pins: Record<string, TSerializedCryptoKeyData_Ed25519_Raw>;\n}\n\ninterface ITofuPinRecord {\n  identity: string;\n  verifyPublicKey: TSerializedCryptoKeyData_Ed25519_Raw;\n}\n\nexport interface IStorageTofuVerifyKeyResolverOptions {\n  /** `document` preserves the legacy `pins` map; `per_identity` avoids whole-map rewrite growth. */\n  layout?: \"document\" | \"per_identity\";\n}\n\nconst tofuPinStorageKey = async (identity: string): Promise<string> => {\n  const digest = new Uint8Array(\n    await crypto.subtle.digest(\n      \"SHA-256\",\n      new TextEncoder().encode(`nice-wire-tofu-v1:${identity}`),\n    ),\n  );\n  return `pin:${[...digest].map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")}`;\n};\n\nconst pinMismatch = (): { trusted: false; reason: string; rejectId: string } => ({\n  trusted: false,\n  reason: \"verify key changed for client identity (pin mismatch)\",\n  rejectId: HANDSHAKE_REJECT_ID_PIN_MISMATCH,\n});\n\n/**\n * Storage-backed trust-on-first-use resolver: pins survive process restarts / Durable Object eviction\n * (e.g. back it with `createDurableObjectStorageAdapter`). Same policy as the in-memory variant — trust\n * + pin the first verify key per client identity, reject a different one thereafter.\n *\n * Fail-closed by construction: a thrown storage read (`getJson`) or first-pin write (`updateJsonWithDef`)\n * propagates out of `resolve`, which makes `onProve` reject the handshake — a storage error can never be\n * mistaken for \"first use\" and silently trusted. (A genuine `undefined`/absent read is the only path to\n * a fresh pin; the underlying adapters never coerce a thrown read to `undefined`.) Keep it that way: do\n * not wrap the storage calls in a `try/catch` that swallows the error.\n *\n * On an *eventually-consistent* store a stale \"absent\" read re-pins the **same** verify key the client\n * just presented (it is signature-verified before this runs), so the worst case is a harmless re-write,\n * never a weakened trust decision. Cross-isolate-strong pinning still wants a strongly-consistent store.\n *\n * Switching an existing host from `document` to `per_identity` is safe: on each identity's next\n * contact the legacy pin is honored and migrated to its per-identity record. The reverse switch is\n * NOT migrated — pins recorded per-identity are invisible to the `document` layout.\n */\nexport function createStorageTofuVerifyKeyResolver(\n  storageAdapter: StorageAdapter,\n  options: IStorageTofuVerifyKeyResolverOptions = {},\n): IClientVerifyKeyResolver {\n  if (options.layout === \"per_identity\") {\n    // StorageAdapter deliberately abstracts over stores without transactions. Serialize first\n    // contact for each identity inside this resolver so two concurrent handshakes cannot both\n    // observe absence and choose different first keys.\n    const identityLocks = new Map<string, Promise<void>>();\n    return {\n      async resolve({ client, verifyPublicKey }) {\n        const identity = tofuPinKey(client);\n        const storageKey = await tofuPinStorageKey(identity);\n        const previous = identityLocks.get(storageKey) ?? Promise.resolve();\n        const operation = previous\n          .catch(() => undefined)\n          .then(async () => {\n            const existing = await storageAdapter.getJson<ITofuPinRecord>(storageKey);\n            if (existing == null) {\n              // Honor a pin recorded by the legacy `document` layout before granting first-use\n              // trust — switching layouts must never re-open first contact for a pinned identity.\n              // The pin migrates to its per-identity record; the legacy `pins` map is left\n              // untouched so rolling back to `document` stays safe.\n              const legacy = (await storageAdapter.getJson<ITofuPinStorage[\"pins\"]>(\"pins\"))?.[\n                identity\n              ];\n              if (legacy != null) {\n                await storageAdapter.setJson(storageKey, { identity, verifyPublicKey: legacy });\n                return legacy === verifyPublicKey ? ({ trusted: true } as const) : pinMismatch();\n              }\n              await storageAdapter.setJson(storageKey, { identity, verifyPublicKey });\n              return { trusted: true } as const;\n            }\n            if (existing.identity === identity && existing.verifyPublicKey === verifyPublicKey) {\n              return { trusted: true } as const;\n            }\n            return pinMismatch();\n          });\n        const tail = operation.then(\n          () => undefined,\n          () => undefined,\n        );\n        identityLocks.set(storageKey, tail);\n        try {\n          return await operation;\n        } finally {\n          if (identityLocks.get(storageKey) === tail) identityLocks.delete(storageKey);\n        }\n      },\n    };\n  }\n  const storage = createTypedStorage<ITofuPinStorage>({ storageAdapter });\n  return {\n    async resolve({ client, verifyPublicKey }) {\n      const key = tofuPinKey(client);\n      // A thrown read here intentionally propagates (fail-closed) — never caught and coerced to \"absent\".\n      const existing = (await storage.getJson(\"pins\"))?.[key];\n      if (existing == null) {\n        await storage.updateJsonWithDef(\"pins\", {}, (current) => ({\n          ...current,\n          [key]: verifyPublicKey,\n        }));\n        return { trusted: true };\n      }\n      if (existing === verifyPublicKey) return { trusted: true };\n      return pinMismatch();\n    },\n  };\n}\n\n// --- client side -----------------------------------------------------------------------------------\n\nexport interface IClientHandshakeConfig {\n  link: ClientCryptoKeyLink;\n  localCoordinate: IRuntimeCoordinate;\n  dictionaryVersion: string;\n  securityLevel: ESecurityLevel;\n  /** Expected peer identity. Matches envId plus perId when explicitly supplied; ignores insId. */\n  expectedPeer?: IRuntimeCoordinate;\n  /** Channel tags advertised to a multi-channel acceptor (`channel.tags`); omit for a single-channel peer. */\n  channelTags?: readonly string[];\n  /**\n   * Additional capability tags to advertise beyond the built-ins (e.g. frame-protocol tags like\n   * `proto:realm` from a {@link WireProtocolMux}). Additive: absent = byte-identical hello.\n   */\n  extraCaps?: readonly string[];\n}\n\nexport function createClientHandshake(config: IClientHandshakeConfig) {\n  const { link, localCoordinate, dictionaryVersion, securityLevel, channelTags } = config;\n  const wantsEncryption = securityLevel === ESecurityLevel.encrypted;\n  const clientNonce = nanoid();\n\n  let pending:\n    | {\n        linkedServerId: TTypeAndId;\n        server: IRuntimeCoordinate;\n        challenge: string;\n        encryptionKeyMaterial?: IHandshakeEncryptionKeyMaterial;\n        remoteCaps?: readonly string[];\n      }\n    | undefined;\n\n  return {\n    async createHello(): Promise<THsHello> {\n      return {\n        t: EHandshakeMessageType.hello,\n        protocol: HANDSHAKE_PROTOCOL,\n        securityLevel,\n        dictionaryVersion,\n        client: localCoordinate,\n        clientNonce,\n        verifyPublicKey: await link.getLocalVerifyPublicKey(),\n        exchangePublicKey: wantsEncryption ? await link.getLocalExchangePublicKey() : undefined,\n        channels: channelTags != null ? [...channelTags] : undefined,\n        caps: [CAP_RELIABLE, CAP_RELIABLE_STREAMKEY, ...(config.extraCaps ?? [])],\n      };\n    },\n\n    async onWelcome(welcome: THsWelcome): Promise<THsProve> {\n      if (welcome.dictionaryVersion !== dictionaryVersion) {\n        throw new Error(\"[ws-handshake] server dictionary version mismatch\");\n      }\n      if (welcome.securityLevel !== securityLevel) {\n        throw new Error(\"[ws-handshake] server security level mismatch\");\n      }\n      if (wantsEncryption && welcome.exchangePublicKey == null) {\n        throw new Error(\"[ws-handshake] server did not provide an exchange key for encryption\");\n      }\n      const expectedPeer = config.expectedPeer;\n      if (\n        expectedPeer != null &&\n        (welcome.server.envId !== expectedPeer.envId ||\n          (expectedPeer.perId != null && welcome.server.perId !== expectedPeer.perId))\n      ) {\n        throw err_wire_connect.fromId(\"peer_identity_mismatch\", {\n          expected: { envId: expectedPeer.envId, perId: expectedPeer.perId },\n          actual: { envId: welcome.server.envId, perId: welcome.server.perId },\n        });\n      }\n\n      const linkedServerId = runtimeLinkId(welcome.server);\n      await link.linkClient({\n        linkedClientId: linkedServerId,\n        verifyPublicKey: welcome.verifyPublicKey,\n        // Salt/info/exchange only matter for the encrypted level's shared-key derivation; the\n        // authenticated level links the verify key alone (passing salt without an exchange key throws).\n        ...(wantsEncryption\n          ? {\n              exchangePublicKey: welcome.exchangePublicKey,\n              saltString: sessionSalt(clientNonce, welcome.serverNonce),\n              infoString: handshakeInfo(dictionaryVersion),\n              bindVerifyKeysIntoDerivation: true,\n            }\n          : {}),\n      });\n\n      // Snapshot the key material so this session can derive its own AES-GCM key (independent of the\n      // link's shared per-`linkedClientId` cache) — mirrors the server side's `keyMaterial`.\n      const encryptionKeyMaterial: IHandshakeEncryptionKeyMaterial | undefined =\n        wantsEncryption && welcome.exchangePublicKey != null\n          ? {\n              verifyPublicKey: welcome.verifyPublicKey,\n              exchangePublicKey: welcome.exchangePublicKey,\n              saltString: sessionSalt(clientNonce, welcome.serverNonce),\n              infoString: handshakeInfo(dictionaryVersion),\n              bindVerifyKeysIntoDerivation: true,\n            }\n          : undefined;\n\n      const challenge = buildHandshakeChallenge({\n        securityLevel,\n        dictionaryVersion,\n        clientCoordId: coordId(localCoordinate),\n        serverCoordId: coordId(welcome.server),\n        clientNonce,\n        serverNonce: welcome.serverNonce,\n        clientVerifyKey: await link.getLocalVerifyPublicKey(),\n        serverVerifyKey: welcome.verifyPublicKey,\n        clientExchangeKey: wantsEncryption ? await link.getLocalExchangePublicKey() : undefined,\n        serverExchangeKey: welcome.exchangePublicKey,\n      });\n\n      pending = {\n        linkedServerId,\n        server: welcome.server,\n        challenge,\n        encryptionKeyMaterial,\n        remoteCaps: welcome.caps,\n      };\n      return {\n        t: EHandshakeMessageType.prove,\n        signatureBase64: (await link.signChallenge([challenge])).signatureBase64,\n      };\n    },\n\n    async onAccept(accept: THsAccept): Promise<IHandshakeResult> {\n      if (pending == null) throw new Error(\"[ws-handshake] accept before welcome\");\n\n      // Optional mutual auth: confirm the server signed the same challenge (liveness over TLS).\n      if (accept.signatureBase64 != null) {\n        const valid = await link.verifyChallengeFromLinkedClient({\n          linkedClientId: pending.linkedServerId,\n          challenge: pending.challenge,\n          signatureBase64: accept.signatureBase64,\n        });\n        if (!valid) throw new Error(\"[ws-handshake] server signature invalid\");\n      }\n\n      return {\n        linkedClientId: pending.linkedServerId,\n        remote: pending.server,\n        securityLevel,\n        encryptionKeyMaterial: pending.encryptionKeyMaterial,\n        remoteCaps: pending.remoteCaps,\n      };\n    },\n  };\n}\n\n// --- server side -----------------------------------------------------------------------------------\n\n/**\n * Resolve the dictionary version a connection should use from its `hello`. A multi-channel acceptor reads\n * `hello.channels` (the advertised tags), composes the matching channel set, and returns its\n * `dictionaryVersion` — or `null` when a tag is unknown (the handshake then rejects). A single-channel\n * acceptor passes a plain string instead. It sees only `channels`: an exchange acceptor re-resolves the\n * version on every act from the tags its session ticket kept.\n */\nexport type TServerDictionaryVersionResolver = (hello: Pick<THsHello, \"channels\">) => string | null;\n\nexport interface IServerHandshakeConfig {\n  link: ClientCryptoKeyLink;\n  localCoordinate: IRuntimeCoordinate;\n  /** A fixed version (single channel), or a resolver that composes it from `hello.channels` (multi-channel). */\n  dictionaryVersion: string | TServerDictionaryVersionResolver;\n  /**\n   * The level(s) this server accepts. A single level is strict (the client must match). An array is a\n   * negotiable allowed set — the server adopts whichever level the client requests, as long as it's in\n   * the set (lets one backend serve `authenticated` and `encrypted` clients at once). `none` in the set\n   * is handled by the transport/handler (a `none` client never reaches the handshake).\n   */\n  securityLevel: ESecurityLevel | readonly ESecurityLevel[];\n  /** Trust decision for a client's verify key. Defaults to in-memory TOFU. */\n  verifyKeyResolver?: IClientVerifyKeyResolver;\n  /**\n   * Additional capability tags to advertise beyond the built-ins (e.g. frame-protocol tags like\n   * `proto:realm` from a {@link WireProtocolMux}). Additive: absent = byte-identical welcome.\n   */\n  extraCaps?: readonly string[];\n}\n\n/**\n * The server handshake's in-flight state between `onHello` and `onProve` — everything `onProve` needs\n * to verify the client's proof and settle the result. Fully serializable (all JSON / serialized-key\n * strings), so a stateless server can {@link IServerHandshake.exportPending} it after `hello`, carry it\n * across requests (e.g. sealed into a continuation token), and {@link IServerHandshake.restorePending}\n * it on a *different* instance before `prove` — no in-memory handshake to co-locate. The `serverNonce`\n * is already folded into `challenge`, so it need not be carried separately.\n */\nexport interface IServerHandshakePending {\n  client: IRuntimeCoordinate;\n  linkedClientId: TTypeAndId;\n  challenge: string;\n  clientVerifyKey: TSerializedCryptoKeyData_Ed25519_Raw;\n  negotiatedLevel: ESecurityLevel;\n  keyMaterial?: IHandshakeEncryptionKeyMaterial;\n  /** The client's advertised `hello.caps` — persisted so a hibernation-restored session keeps them. */\n  remoteCaps?: readonly string[];\n}\n\nexport interface IServerHandshake {\n  onHello(hello: THsHello): Promise<THsWelcome | THsReject>;\n  onProve(prove: THsProve): Promise<THsAccept | THsReject>;\n  getResult(): IHandshakeResult | undefined;\n  /** The serializable in-flight state after `onHello` (else `undefined`). See {@link IServerHandshakePending}. */\n  exportPending(): IServerHandshakePending | undefined;\n  /**\n   * Restore exported `pending` onto a *fresh* handshake instance so `onProve` can run without the\n   * `onHello` that produced it (the stateless / cross-instance path). Re-links the client's verify key\n   * — `onHello`'s `linkClient` was in-memory only and won't exist on this instance — so the signature\n   * check in `onProve` succeeds. Build the instance with the same `config` (identity link + coordinate).\n   */\n  restorePending(pending: IServerHandshakePending): Promise<void>;\n}\n\nexport function createServerHandshake(config: IServerHandshakeConfig): IServerHandshake {\n  const { link, localCoordinate } = config;\n  const allowedLevels = Array.isArray(config.securityLevel)\n    ? config.securityLevel\n    : [config.securityLevel];\n  const verifyKeyResolver = config.verifyKeyResolver ?? createInMemoryTofuVerifyKeyResolver();\n  const serverNonce = nanoid();\n\n  let pending: IServerHandshakePending | undefined;\n  let result: IHandshakeResult | undefined;\n\n  return {\n    async onHello(hello: THsHello): Promise<THsWelcome | THsReject> {\n      if (hello.protocol !== HANDSHAKE_PROTOCOL) {\n        const observedProtocolVersion = handshakeProtocolVersion(hello.protocol);\n        return {\n          ...reject(\n            `unsupported handshake protocol; this server supports wire protocol v${WIRE_SUPPORTED_PROTOCOL_VERSIONS.join(\n              \", v\",\n            )}`,\n            HANDSHAKE_REJECT_ID_PROTOCOL_VERSION_MISMATCH,\n          ),\n          observedProtocolVersion,\n          supportedProtocolVersions: [...WIRE_SUPPORTED_PROTOCOL_VERSIONS],\n        };\n      }\n      // Resolve the version this connection should use: a fixed string (single channel), or composed from\n      // the advertised `hello.channels` tags (multi-channel) — `null` means an unknown/unserved channel.\n      const dictionaryVersion =\n        typeof config.dictionaryVersion === \"function\"\n          ? config.dictionaryVersion(hello)\n          : config.dictionaryVersion;\n      if (dictionaryVersion == null) return reject(\"unknown or unserved channel\");\n      if (hello.dictionaryVersion !== dictionaryVersion)\n        return reject(\"dictionary version mismatch\");\n\n      // Negotiate: adopt the client's requested level if this server allows it. `none` never\n      // handshakes, so it's not a valid negotiated level here.\n      const negotiatedLevel = hello.securityLevel;\n      if (negotiatedLevel === ESecurityLevel.none || !allowedLevels.includes(negotiatedLevel)) {\n        return reject(\"security level not allowed\");\n      }\n      const wantsEncryption = negotiatedLevel === ESecurityLevel.encrypted;\n      if (wantsEncryption && hello.exchangePublicKey == null) {\n        return reject(\"missing exchange key for encryption\");\n      }\n\n      const linkedClientId = runtimeLinkId(hello.client);\n      await link.linkClient({\n        linkedClientId,\n        verifyPublicKey: hello.verifyPublicKey,\n        // See client side: only the encrypted level needs the exchange key + HKDF salt/info.\n        ...(wantsEncryption\n          ? {\n              exchangePublicKey: hello.exchangePublicKey,\n              saltString: sessionSalt(hello.clientNonce, serverNonce),\n              infoString: handshakeInfo(dictionaryVersion),\n              bindVerifyKeysIntoDerivation: true,\n            }\n          : {}),\n      });\n\n      const serverVerifyKey = await link.getLocalVerifyPublicKey();\n      const serverExchangeKey = wantsEncryption\n        ? await link.getLocalExchangePublicKey()\n        : undefined;\n\n      const keyMaterial: IHandshakeEncryptionKeyMaterial | undefined =\n        wantsEncryption && hello.exchangePublicKey != null\n          ? {\n              verifyPublicKey: hello.verifyPublicKey,\n              exchangePublicKey: hello.exchangePublicKey,\n              saltString: sessionSalt(hello.clientNonce, serverNonce),\n              infoString: handshakeInfo(dictionaryVersion),\n              bindVerifyKeysIntoDerivation: true,\n            }\n          : undefined;\n\n      pending = {\n        client: hello.client,\n        linkedClientId,\n        clientVerifyKey: hello.verifyPublicKey,\n        negotiatedLevel,\n        keyMaterial,\n        remoteCaps: hello.caps,\n        challenge: buildHandshakeChallenge({\n          securityLevel: negotiatedLevel,\n          dictionaryVersion,\n          clientCoordId: coordId(hello.client),\n          serverCoordId: coordId(localCoordinate),\n          clientNonce: hello.clientNonce,\n          serverNonce,\n          clientVerifyKey: hello.verifyPublicKey,\n          serverVerifyKey,\n          clientExchangeKey: hello.exchangePublicKey,\n          serverExchangeKey,\n        }),\n      };\n\n      return {\n        t: EHandshakeMessageType.welcome,\n        securityLevel: negotiatedLevel,\n        dictionaryVersion,\n        server: localCoordinate,\n        serverNonce,\n        verifyPublicKey: serverVerifyKey,\n        exchangePublicKey: serverExchangeKey,\n        caps: [CAP_RELIABLE, CAP_RELIABLE_STREAMKEY, ...(config.extraCaps ?? [])],\n      };\n    },\n\n    async onProve(prove: THsProve): Promise<THsAccept | THsReject> {\n      if (pending == null) return reject(\"prove before hello\");\n\n      const signatureValid = await link.verifyChallengeFromLinkedClient({\n        linkedClientId: pending.linkedClientId,\n        challenge: pending.challenge,\n        signatureBase64: prove.signatureBase64,\n      });\n      if (!signatureValid) return reject(\"invalid client signature\");\n\n      const trust = await verifyKeyResolver.resolve({\n        client: pending.client,\n        verifyPublicKey: pending.clientVerifyKey,\n      });\n      if (!trust.trusted)\n        return reject(trust.reason ?? \"client verify key not trusted\", trust.rejectId);\n\n      result = {\n        linkedClientId: pending.linkedClientId,\n        remote: pending.client,\n        securityLevel: pending.negotiatedLevel,\n        encryptionKeyMaterial: pending.keyMaterial,\n        remoteCaps: pending.remoteCaps,\n      };\n\n      // Sign the same challenge back so the client can confirm server liveness (mutual auth).\n      return {\n        t: EHandshakeMessageType.accept,\n        signatureBase64: (await link.signChallenge([pending.challenge])).signatureBase64,\n      };\n    },\n\n    /** The completed handshake result once `onProve` has accepted, else `undefined`. */\n    getResult(): IHandshakeResult | undefined {\n      return result;\n    },\n\n    exportPending(): IServerHandshakePending | undefined {\n      return pending;\n    },\n\n    async restorePending(restored: IServerHandshakePending): Promise<void> {\n      pending = restored;\n      // `onHello`'s linkClient was in-memory only; re-link the client's verify key so the signature\n      // check in `onProve` works on this fresh instance. (Verify-only — the encrypted level's shared\n      // key is rebuilt later from `keyMaterial`, not needed for the proof.)\n      await link.linkClient({\n        linkedClientId: restored.linkedClientId,\n        verifyPublicKey: restored.clientVerifyKey,\n      });\n    },\n  };\n}\n","import { ESecurityLevel } from \"./actionHandshake\";\n\n/**\n * A total order over {@link ESecurityLevel}. The enum is **string**-valued (`\"none\"` /\n * `\"authenticated\"` / `\"encrypted\"`), so `>=` on the values themselves is meaningless — a consumer\n * comparing \"does this connection meet the required level\" needs an explicit rank. This is the one\n * shared rank so every caller (the realm attach gate, the client-side assertion) compares levels\n * identically; a divergent ad-hoc comparison is exactly how a security floor silently inverts.\n *\n * Higher rank = stronger protection: `none` (0) < `authenticated` (1) < `encrypted` (2).\n */\nexport const SECURITY_LEVEL_RANK: Record<ESecurityLevel, number> = {\n  [ESecurityLevel.none]: 0,\n  [ESecurityLevel.authenticated]: 1,\n  [ESecurityLevel.encrypted]: 2,\n};\n\n/** `true` when `actual` meets or exceeds the `required` level (the \"is this connection good enough\" test). */\nexport function securityLevelMeets(actual: ESecurityLevel, required: ESecurityLevel): boolean {\n  return SECURITY_LEVEL_RANK[actual] >= SECURITY_LEVEL_RANK[required];\n}\n","import { unrefTimer } from \"@nice-code/util\";\nimport { ESecurityLevel } from \"../crypto/actionHandshake\";\nimport type { WireProtocolMux } from \"../Mux/WireProtocolMux\";\nimport type { RuntimeCoordinate } from \"../RuntimeCoordinate\";\nimport type { IWireClientPair, TLinkEvent } from \"./Connect.types\";\nimport type { ConnectionTransportManager } from \"./ConnectionTransportManager\";\nimport { err_wire_connect } from \"./err_wire_connect\";\nimport type {\n  IWireConnectionMethodsBase,\n  IWireTransportReady,\n  TTransportCache,\n  TWireManagedConnection,\n} from \"./transportRuntime.types\";\n\n/**\n * The carrier said \"no valid endpoint right now\" (`createRequest` returned null). A policy signal,\n * not a failure: the redial loop PARKS on it (no backoff churn, no garbage\n * dial) and resumes at the next explicit `connect()`/dispatch. The transport selection rethrows it\n * unwrapped so this check is reliable.\n */\nconst isDialUnavailable = (e: unknown): boolean =>\n  err_wire_connect.isExact(e) && e.hasId(\"dial_unavailable\");\n\n/**\n * A dial failure the backoff ladder must PARK on instead of retrying: either no endpoint exists\n * right now ({@link isDialUnavailable}), or the peer rejected the handshake with\n * `identity_pin_mismatch` (the peer has a different key pinned) or\n * `protocol_version_mismatch` (the two builds have no compatible secure-wire generation), or this\n * runtime has no WebCrypto to handshake with at all (`crypto_unavailable`).\n * Parking is not terminal: the next explicit `connect()`/dispatch may try again after the app has\n * upgraded or changed endpoints. Other handshake rejections (e.g. a dictionary mismatch) retain\n * the existing retry behavior because a matching deploy can heal them.\n */\nconst isParkedDialRejection = (e: unknown): boolean =>\n  isDialUnavailable(e) ||\n  (err_wire_connect.isExact(e) &&\n    (e.hasId(\"identity_pin_mismatch\") ||\n      e.hasId(\"protocol_version_mismatch\") ||\n      e.hasId(\"peer_identity_mismatch\") ||\n      e.hasId(\"crypto_unavailable\")));\n\nexport interface IWireClientOptions<\n  RP,\n  METHODS extends IWireConnectionMethodsBase,\n  CONN extends TWireManagedConnection<RP, METHODS>,\n> {\n  /**\n   * Build the selection manager over the client-owned cache. Injected so the consumer's manager\n   * (nice-action's `ConnectionTransportManager` shim, which carries its error vocabulary) is the\n   * one that runs — wire owns the cache + lifecycle, the consumer owns the failure language.\n   */\n  createManager: (\n    cache: TTransportCache<METHODS, CONN>,\n  ) => ConnectionTransportManager<RP, METHODS, CONN>;\n  /**\n   * The frame-protocol mux riding this client's connections. The client *holds* it (one mux per\n   * client — protocol modules reach it here). Its registered-protocol count is also the auto\n   * keep-alive signal (a protocol-carrying link is kept alive; a lane-only one stays\n   * dispatch-driven).\n   */\n  mux?: WireProtocolMux;\n  /** The peer this client dials — its `externalClient` in every dial input. */\n  peer: RuntimeCoordinate;\n  /**\n   * The local runtime coordinate this connection dials out from — its authenticated identity to the\n   * peer, and what `connect()` uses when no override is passed. A protocol module (a realm client)\n   * also defaults its own identity from it.\n   */\n  localCoordinate?: RuntimeCoordinate;\n  /**\n   * The negotiated wire security level this connection's frame protocols (a realm) ride at. A realm\n   * client reads it and refuses to send below its required minimum. Defaults to\n   * {@link ESecurityLevel.none} (a bare-mux / loopback build).\n   */\n  securityLevel?: ESecurityLevel;\n  /**\n   * Whether any transport in this client's chain is push-capable (duplex). Computed by the caller\n   * from its transport list. Keep-alive requires it — an exchange-only client can never be redialed\n   * into a live link the peer can push over.\n   */\n  canPush: boolean;\n  /**\n   * Keep a **protocol-carrying** duplex link alive by auto-redialing it on an unexpected drop, with\n   * exponential backoff + jitter. `undefined` (default) = auto: on when the\n   * mux carries a registered protocol, off otherwise (a lane-only connection keeps dispatch-driven\n   * reconnect). `false` opts out; `true` forces it on for any duplex link. An explicit\n   * `clearTransportCache()`/`dispose()` always stops it.\n   */\n  /** @deprecated Use `reconnect`. */\n  keepLinkAlive?: boolean;\n  reconnect?: boolean;\n  /**\n   * Build an **actionless** dial input from the client pair. Wire holds the pair (this client's\n   * coordinate + its peer) but the routing-param shape is the consumer's (`RP`), so the consumer\n   * maps the pair onto it — nice-action's lane returns the pair itself (a valid actionless route\n   * param), a bare-mux build returns the pair too. Used by `connect()`/`reconnectLink()`.\n   */\n  buildConnectInput: (pair: IWireClientPair) => RP;\n  /**\n   * A last-resort local coordinate when none was configured — nice-action supplies\n   * `() => ActionRuntime.getDefault().coordinate` so its dispatch-driven default holds; a pure wire\n   * client omits it (a configured `localCoordinate` is then required to `connect()`).\n   */\n  defaultLocalCoordinate?: () => RuntimeCoordinate | undefined;\n}\n\n/**\n * The dial-out connection: owns the transport cache, preference-ordered selection, the protocol mux,\n * and the whole **connection lifecycle** — establishment bookkeeping, the keep-alive redial ladder\n * (backoff + jitter + park), link-state events, and the teardown verbs. A protocol module (a realm\n * client, via `realmConnection`) rides it structurally through `wireMux` + `localCoordinate` +\n * `securityLevel` + `requestReconnect` + `addLinkEventListener`; a lane (nice-action's\n * `ChannelConnector`) composes routing/reliability on top and delegates every lifecycle verb here.\n * `createWireClient` (the public facade) wraps one of these with the status model + DX.\n */\nexport class WireClient<\n  RP,\n  METHODS extends IWireConnectionMethodsBase,\n  CONN extends TWireManagedConnection<RP, METHODS> = TWireManagedConnection<RP, METHODS>,\n> {\n  readonly mux?: WireProtocolMux;\n  /** The peer this connection dials — `externalClient` for its dials, and the realm's devtools peer. */\n  readonly peer: RuntimeCoordinate;\n  /** This connection's local dial identity (see options). */\n  readonly localCoordinate?: RuntimeCoordinate;\n  /** The negotiated wire security level frame protocols ride at (realm reads it via `realmConnection`). */\n  readonly securityLevel: ESecurityLevel;\n  /** Whether this connection can carry an unsolicited push (any duplex transport). */\n  readonly canPush: boolean;\n\n  private readonly _cache: TTransportCache<METHODS, CONN> = new Map();\n  private readonly _manager: ConnectionTransportManager<RP, METHODS, CONN>;\n  private readonly _buildConnectInput: (pair: IWireClientPair) => RP;\n  private readonly _defaultLocalCoordinate?: () => RuntimeCoordinate | undefined;\n\n  // ── Link-state observation ──────────────────────────\n  private readonly _linkEventListeners = new Set<(event: TLinkEvent) => void>();\n  /** When the current outage began (the `link_down` instant); `undefined` while up / never dialed. */\n  private _downSince?: number;\n  /**\n   * The methods of the *current* link — dedups `link_up` (every dispatch re-runs\n   * `_onLinkEstablished` with the cached connection) and lets a stale connection's late close be\n   * ignored (a slow socket close arriving after the replacement link is already up must not read\n   * as an outage).\n   */\n  private _currentLinkMethods?: METHODS;\n  /**\n   * App-initiated teardown latch: `releaseLink()` / `clearTransportCache()` / `dispose()` are\n   * intentional releases, NOT outages — so a **late** carrier close from the released socket must\n   * emit no `link_down`. Set by those teardowns, cleared by the next `_onLinkEstablished` (a fresh\n   * link means we're back). `debug.dropLink` deliberately does NOT set it — a dropped link IS an\n   * outage, and it emits `link_down` at close.\n   */\n  private _tornDown = false;\n\n  // ── Reconnection ─────────────────────────────────────\n  /** Explicit opt-out; `undefined` = auto (on for a protocol-carrying duplex link). */\n  private readonly _reconnectOption?: boolean;\n  /** Connections we've hooked a reconnect listener onto (once per connection). */\n  private readonly _reconnectHooked = new WeakSet<METHODS>();\n  private _redialTimer?: ReturnType<typeof setTimeout>;\n  private _redialAttempts = 0;\n  /** Set by an explicit teardown so the resulting disconnect doesn't auto-redial; cleared on a fresh establish. */\n  private _suppressRedial = false;\n  /** Timer ending a `debug.dropLink` suppression window. */\n  private _debugResumeTimer?: ReturnType<typeof setTimeout>;\n  private _disposed = false;\n\n  /**\n   * Chaos/QA surface — stable API, but never for production control flow.\n   * The \"simulate airplane mode\" button: manual QA and consumer resilience tests use it to force\n   * the outages that page-level interception can't (the keep-alive redial heals straight through\n   * a `window.WebSocket` patch).\n   */\n  readonly debug = {\n    /**\n     * Force-close the live duplex link — a *real* close (the server observes it), unlike a\n     * browser's offline mode which leaves the socket half-open — and optionally suppress the\n     * keep-alive auto-redial for a window, simulating a sustained outage.\n     *\n     * - `suppressRedialMs` omitted/`0`: drop only — keep-alive (when active) heals on its\n     *   ordinary backoff ladder (first rung ~1 s), so a bare `dropLink({})` is a faithful\n     *   *fast-blip* simulator: the local close notifies the session immediately, it does NOT wait\n     *   for the carrier's platform close event.\n     * - `suppressRedialMs > 0`: no auto-redial until the window ends, then the backoff loop\n     *   resumes. A second `dropLink` during a window replaces it; an explicit `connect()` /\n     *   dispatch / `reconnectLink()` during the window ends it early (fresh establishment always\n     *   re-enables keep-alive); `dispose()` wins over a pending resume.\n     *\n     * `link_down` fires **now, at close** — synchronously, before the socket teardown — so the\n     * observation is truthful regardless of how long the underlying carrier takes to deliver its\n     * own close callback (a real WebSocket's `onclose` can lag the outage by seconds; the\n     * suppression window suppresses only the *redial*, never the *observation of the drop*). The\n     * heal is equally decoupled: a deliberate local close notifies the session's disconnect\n     * fan-out immediately (the auto-redial trigger), and the carrier's eventual platform close is\n     * deduped by the `_downSince` guard — so exactly one `link_down` is emitted, `link_up.downForMs`\n     * measures the full outage, and the redial does not wait out the platform's close lag.\n     *\n     * Resolves once the local teardown ran (in-flight dials are disconnected as they land).\n     */\n    dropLink: async (opts?: { suppressRedialMs?: number }): Promise<void> => {\n      if (this._disposed) return;\n      const windowMs = opts?.suppressRedialMs ?? 0;\n      this._cancelDebugResume();\n      // Report the outage this call performs at the moment it performs it — not coupled to the\n      // (possibly much later) carrier close callback. Guarded so a repeat drop or the eventual\n      // close callback can't double-emit. `_tornDown` stays false: a drop IS an outage.\n      if (this._currentLinkMethods != null && this._downSince == null) {\n        this._downSince = Date.now();\n        this._emitLinkEvent({ type: \"link_down\" });\n      }\n      if (windowMs > 0) {\n        this._suppressRedial = true;\n        this._cancelRedial();\n        const timer = setTimeout(() => {\n          this._debugResumeTimer = undefined;\n          if (this._disposed) return;\n          this._suppressRedial = false;\n          this._scheduleRedial(); // self-gates on reconnect (a lane-only client stays dispatch-driven)\n        }, windowMs);\n        unrefTimer(timer);\n        this._debugResumeTimer = timer;\n      }\n      this.clearCache(); // closes the live socket(s) — the peer observes a real close\n    },\n  };\n\n  constructor(options: IWireClientOptions<RP, METHODS, CONN>) {\n    this.mux = options.mux;\n    this.peer = options.peer;\n    this.localCoordinate = options.localCoordinate;\n    this.securityLevel = options.securityLevel ?? ESecurityLevel.none;\n    this.canPush = options.canPush;\n    if (options.reconnect != null && options.keepLinkAlive != null) {\n      throw err_wire_connect.fromId(\"conflicting_connect_options\", {\n        detail: \"WireClient: pass only `reconnect`; `keepLinkAlive` is deprecated\",\n      });\n    }\n    this._reconnectOption = options.reconnect ?? options.keepLinkAlive;\n    this._buildConnectInput = options.buildConnectInput;\n    this._defaultLocalCoordinate = options.defaultLocalCoordinate;\n    this._manager = options.createManager(this._cache);\n  }\n\n  /** Register one live connection, in preference order (first added = preferred). */\n  addTransport(connection: CONN): void {\n    this._manager.addTransport(connection);\n  }\n\n  /** The highest-priority transport (first declared) — see the manager's doc. */\n  getPreferredTransport(): CONN | undefined {\n    return this._manager.getPreferredTransport();\n  }\n\n  /**\n   * Select (establishing if needed) the transport that should carry this dispatch, and run the\n   * link-establishment bookkeeping as a side effect — so *any* caller (a lane dispatch or this\n   * client's own `connect()`) re-enables keep-alive, resets the backoff ladder, and emits `link_up`\n   * on a genuinely new link, without having to orchestrate it. Idempotent per link\n   * (`_onLinkEstablished` dedups on identity).\n   */\n  async getReadyTransport(input: RP): Promise<IWireTransportReady<METHODS, CONN>> {\n    const ready = await this._manager.getReadyTransport(input);\n    this._onLinkEstablished(ready.methods);\n    return ready;\n  }\n\n  /**\n   * The frame-protocol mux riding this connection's link — protocol modules (a realm client)\n   * register here. Register protocols *before* {@link connect} / the first dispatch so the\n   * handshake advertises them.\n   */\n  get wireMux(): WireProtocolMux | undefined {\n    return this.mux;\n  }\n\n  /** @deprecated Use {@link peer}. */\n  get peerClient(): RuntimeCoordinate {\n    return this.peer;\n  }\n\n  /**\n   * The re-dial hook a realm client rides:\n   * `realmConnection(client)` reads it and hands it to the realm engine as the connection\n   * adapter's `requestReconnect`, invoked on an unanswered staleness probe. A bound closure, so it\n   * survives being detached from `this` (the realm stores the reference and calls it later).\n   */\n  get requestReconnect(): () => void {\n    return () => void this.reconnectLink();\n  }\n\n  /** Keep-alive is active for a protocol-carrying duplex link (a realm) unless opted out (Phase 8b). */\n  private get _shouldReconnect(): boolean {\n    if (this._disposed || !this.canPush) return false;\n    if (this._reconnectOption != null) return this._reconnectOption;\n    // Auto: on when the mux carries at least one registered protocol (a realm rides it). A\n    // lane-only connection keeps dispatch-driven reconnect (no background redial).\n    return (this.mux?.localCaps().length ?? 0) > 0;\n  }\n\n  /** Called on every fresh link establishment (`connect()` / a redial): re-enable + hook keep-alive. */\n  private _onLinkEstablished(methods: METHODS): void {\n    // Every dispatch re-runs this with the cached connection — only a genuinely new link counts.\n    const isNewLink = methods !== this._currentLinkMethods;\n    this._currentLinkMethods = methods;\n    this._suppressRedial = false;\n    this._tornDown = false; // a fresh link: any prior app-initiated release is over\n    this._redialAttempts = 0;\n    this._cancelRedial();\n    this._cancelDebugResume(); // a fresh link ends any debug.dropLink suppression window\n    this._hookKeepAlive(methods);\n    if (isNewLink) {\n      const downForMs = this._downSince != null ? Date.now() - this._downSince : undefined;\n      this._downSince = undefined;\n      this._emitLinkEvent({ type: \"link_up\", downForMs });\n    }\n  }\n\n  /** Attach the auto-redial disconnect listener to one connection, once (Phase 8b). */\n  private _hookKeepAlive(methods: METHODS): void {\n    if (methods.addOnDisconnectListener == null || this._reconnectHooked.has(methods)) return;\n    this._reconnectHooked.add(methods);\n    methods.addOnDisconnectListener(() => {\n      // A stale connection's late close (the replacement link is already up) is not an outage.\n      if (methods !== this._currentLinkMethods) return;\n      // An app-initiated release (releaseLink/clearTransportCache/dispose) is not an outage either:\n      // its late carrier close must stay silent. `debug.dropLink` does not set `_tornDown`, so it\n      // still reports (it emits `link_down` synchronously at close — see below — and this late\n      // callback is deduped by the `_downSince` guard).\n      if (this._tornDown) return;\n      // Observation is unconditional — it must not depend on healing config.\n      if (this._downSince == null) {\n        this._downSince = Date.now();\n        this._emitLinkEvent({ type: \"link_down\" });\n      }\n      // Self-gates: a lane-only connection (no protocols) or an explicit teardown never redials.\n      if (this._shouldReconnect && !this._suppressRedial) this._scheduleRedial();\n    });\n  }\n\n  /** Schedule one backoff+jitter re-dial (Phase 8b); idempotent — one attempt pending at a time. */\n  private _scheduleRedial(): void {\n    if (!this._shouldReconnect || this._suppressRedial || this._redialTimer != null) return;\n    // 1 s → 2 s → 4 s … capped at 30 s, with ±50% jitter so a fleet doesn't reconnect in lockstep.\n    const ceiling = Math.min(1_000 * 2 ** this._redialAttempts, 30_000);\n    const delay = ceiling / 2 + Math.random() * (ceiling / 2);\n    this._redialAttempts += 1;\n    this._emitLinkEvent({\n      type: \"redial_scheduled\",\n      attempt: this._redialAttempts,\n      delayMs: Math.round(delay),\n    });\n    const timer = setTimeout(() => {\n      this._redialTimer = undefined;\n      // `connect()` resets the ladder + re-hooks on success (`_onLinkEstablished`), and re-arms it on\n      // failure — parking on `dial_unavailable`. So the loop continues with no extra handling here;\n      // the rejection is already accounted for.\n      void this.connect().catch(() => {});\n    }, delay);\n    unrefTimer(timer);\n    this._redialTimer = timer;\n  }\n\n  private _cancelRedial(): void {\n    if (this._redialTimer != null) {\n      clearTimeout(this._redialTimer);\n      this._redialTimer = undefined;\n    }\n  }\n\n  private _cancelDebugResume(): void {\n    if (this._debugResumeTimer != null) {\n      clearTimeout(this._debugResumeTimer);\n      this._debugResumeTimer = undefined;\n    }\n  }\n\n  /**\n   * Establish the connection without dispatching anything: dial the preferred transport, run its\n   * handshake, and attach the mux — so a realm-only (actionless) client can\n   * exist. Idempotent: the connection cache shares one in-flight establishment, so concurrent and\n   * repeat calls coalesce; resolves when the handshake completes, rejects when the transport\n   * chain is exhausted. The carriers receive actionless dial params.\n   *\n   * **A failed dial arms the keep-alive backoff ladder** (when keep-alive is on) rather than leaving\n   * the connection idle: the classic cold start — the app loads before the backend finished booting —\n   * heals on its own instead of needing a page reload. The rejection still propagates, so the caller\n   * still sees the first failure; the retries continue in the background (observe them via\n   * `addLinkEventListener`'s `redial_scheduled` / `link_up`).\n   *\n   * Two rejections park the ladder instead of arming it (no background retry follows):\n   * `dial_unavailable` (no endpoint right now) and `identity_pin_mismatch` (the peer has a\n   * different verify key pinned for this client identity — permanent for this identity+key pair).\n   */\n  async connect(config?: { localCoordinate?: RuntimeCoordinate }): Promise<void> {\n    const localClient =\n      config?.localCoordinate ?? this.localCoordinate ?? this._defaultLocalCoordinate?.();\n    if (localClient == null) {\n      throw err_wire_connect.fromId(\"connect_exhausted\", {\n        peerId: this.peer.stringId,\n        attempted: [],\n      });\n    }\n    try {\n      // getReadyTransport runs `_onLinkEstablished` as a side effect on success.\n      await this.getReadyTransport(\n        this._buildConnectInput({ localClient, externalClient: this.peer }),\n      );\n    } catch (e) {\n      // A cold-start dial failure (the peer is still booting) must not leave a keep-alive connection\n      // dead until the next explicit `connect()` / dispatch / reload — the redial ladder was only\n      // ever armed by a *drop*, which never happens if we never got up. Arm it here too. Self-gates\n      // inside `_scheduleRedial`; `dial_unavailable` / `identity_pin_mismatch` park instead.\n      if (!isParkedDialRejection(e)) this._scheduleRedial();\n      throw e;\n    }\n  }\n\n  /**\n   * Tear down the (possibly half-open) duplex link and immediately re-dial it (the reconnect contract / Phase\n   * 8b). Surfaced to a realm client as the connection adapter's `requestReconnect` (via\n   * {@link requestReconnect}) — the staleness-probe escalation calls it when a probe goes\n   * unanswered. On a successful re-dial the mux re-attaches and every realm re-hellos; a failure\n   * falls into the keep-alive backoff loop when enabled, else the next probe retries.\n   *\n   * **Awaitable** — resolves when the fresh link's handshake completes, rejects when the transport\n   * chain is exhausted (after which the keep-alive backoff continues, when enabled). Bind a\n   * \"retry now\" button to this instead of waiting out the backoff ladder.\n   */\n  async reconnectLink(): Promise<void> {\n    this._cancelRedial();\n    // The local-close fan-out is immediate: `clearCache()` below fires the disconnect listener on a\n    // microtask, which would otherwise schedule a ladder redial that races — and emits a phantom\n    // `redial_scheduled` against — our own explicit dial. Suppress the auto-redial across the\n    // teardown; `link_down` still reports (observation is unconditional), so observers see a clean\n    // link_down → link_up, or link_down → redial_scheduled only if OUR dial below fails.\n    this._suppressRedial = true;\n    this.clearCache(); // drop the dead/half-open socket so `connect()` establishes a fresh one\n    try {\n      await this.connect(); // clears _suppressRedial on success (via _onLinkEstablished)\n    } catch (e) {\n      // Our explicit dial failed — let the ladder resume: back into the loop (self-gates on\n      // reconnect), unless the carrier says no endpoint exists right now (`dial_unavailable`)\n      // or the peer permanently rejected this identity (`identity_pin_mismatch`) — then park.\n      this._suppressRedial = false;\n      if (!isParkedDialRejection(e)) this._scheduleRedial();\n    }\n  }\n\n  /**\n   * Stop the keep-alive auto-redial and release the current link — the intention-revealing\n   * teardown counterpart of `reconnect`. Call this when a session is\n   * over (leaving a match, logging out): the link closes and stays closed until the next explicit\n   * `connect()`/dispatch. Not terminal (unlike {@link dispose}) — the client is reusable.\n   */\n  releaseLink(): void {\n    this.clearTransportCache();\n  }\n\n  /**\n   * Drop the connection cache (closing any live socket) without the keep-alive auto-redial — the\n   * app asked for the link to drop; a later explicit `connect()`/dispatch re-enables keep-alive.\n   * (Contrast {@link reconnectLink}, which drops then re-dials.) An app-initiated release is not an\n   * outage, so the released socket's late close stays silent (no spurious `link_down`).\n   */\n  clearTransportCache(): void {\n    this._suppressRedial = true;\n    this._tornDown = true;\n    this._cancelRedial();\n    this._cancelDebugResume();\n    this.clearCache();\n  }\n\n  /**\n   * Permanently stop this client (Phase 8b): cancel any pending auto-redial and drop the connection\n   * cache. After this, keep-alive never re-dials again (an explicit, final teardown — distinct from\n   * {@link clearTransportCache}, which an app may use to force a fresh connection).\n   */\n  dispose(): void {\n    this._disposed = true;\n    this._tornDown = true; // a late close of the released socket must emit no link_down\n    this._cancelRedial();\n    this._cancelDebugResume();\n    this.clearCache();\n  }\n\n  /**\n   * Close any live long-lived connection (e.g. a WebSocket) before dropping it, so a teardown\n   * actually releases the socket instead of leaving it open until GC. HTTP/stateless transports\n   * don't implement `disconnect`, so they're simply forgotten.\n   *\n   * @internal Bare cache drop with no redial suppression. Apps call {@link clearTransportCache} or\n   * {@link releaseLink} instead.\n   */\n  clearCache(): void {\n    for (const entry of this._cache.values()) {\n      if (entry instanceof Promise) {\n        entry.then((ready) => ready.methods.disconnect?.()).catch(() => {});\n      } else {\n        entry.methods.disconnect?.();\n      }\n    }\n    this._cache.clear();\n  }\n\n  /**\n   * Observe transport link-state: `link_down`, `redial_scheduled`\n   * (attempt + delay — truthful \"retrying in N s\" UX), `link_up` (with `downForMs`). Returns an\n   * unsubscribe. See {@link TLinkEvent} for the contract (a healthy heal is silent at the realm's\n   * sync layer — this is where it's visible).\n   */\n  addLinkEventListener(listener: (event: TLinkEvent) => void): () => void {\n    this._linkEventListeners.add(listener);\n    return () => {\n      this._linkEventListeners.delete(listener);\n    };\n  }\n\n  private _emitLinkEvent(event: TLinkEvent): void {\n    for (const listener of this._linkEventListeners) {\n      try {\n        listener(event);\n      } catch (err) {\n        console.error(\"[link] onLinkEvent listener threw\", err);\n      }\n    }\n  }\n}\n","var decoder;\ntry {\n\tdecoder = new TextDecoder();\n} catch(error) {}\nvar src;\nvar srcEnd;\nvar position = 0;\nvar alreadySet;\nconst EMPTY_ARRAY = [];\nvar strings = EMPTY_ARRAY;\nvar stringPosition = 0;\nvar currentUnpackr = {};\nvar currentStructures;\nvar srcString;\nvar srcStringStart = 0;\nvar srcStringEnd = 0;\nvar bundledStrings;\nvar referenceMap;\nvar currentExtensions = [];\nvar dataView;\nvar defaultOptions = {\n\tuseRecords: false,\n\tmapsAsObjects: true\n};\nexport class C1Type {}\nexport const C1 = new C1Type();\nC1.name = 'MessagePack 0xC1';\nvar sequentialMode = false;\nvar inlineObjectReadThreshold = 2;\nvar BlockedFunction; // we use search and replace to change the next call to BlockedFunction to avoid CSP issues for\n\nexport class Unpackr {\n\tconstructor(options) {\n\t\tif (options) {\n\t\t\tif (options.useRecords === false && options.mapsAsObjects === undefined)\n\t\t\t\toptions.mapsAsObjects = true;\n\t\t\tif (options.sequential && options.trusted !== false) {\n\t\t\t\toptions.trusted = true;\n\t\t\t\tif (!options.structures && options.useRecords != false) {\n\t\t\t\t\toptions.structures = [];\n\t\t\t\t\tif (!options.maxSharedStructures)\n\t\t\t\t\t\toptions.maxSharedStructures = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (options.structures)\n\t\t\t\toptions.structures.sharedLength = options.structures.length;\n\t\t\telse if (options.getStructures) {\n\t\t\t\t(options.structures = []).uninitialized = true; // this is what we use to denote an uninitialized structures\n\t\t\t\toptions.structures.sharedLength = 0;\n\t\t\t}\n\t\t\tif (options.int64AsNumber) {\n\t\t\t\toptions.int64AsType = 'number';\n\t\t\t}\n\t\t}\n\t\tObject.assign(this, options);\n\t}\n\tunpack(source, options) {\n\t\tif (src) {\n\t\t\t// re-entrant execution, save the state and restore it after we do this unpack\n\t\t\treturn saveState(() => {\n\t\t\t\tclearSource();\n\t\t\t\treturn this ? this.unpack(source, options) : Unpackr.prototype.unpack.call(defaultOptions, source, options);\n\t\t\t});\n\t\t}\n\t\tif (!source.buffer && source.constructor === ArrayBuffer)\n\t\t\tsource = typeof Buffer !== 'undefined' ? Buffer.from(source) : new Uint8Array(source);\n\t\tif (typeof options === 'object') {\n\t\t\tsrcEnd = options.end || source.length;\n\t\t\tposition = options.start || 0;\n\t\t} else {\n\t\t\tposition = 0;\n\t\t\tsrcEnd = options > -1 ? options : source.length;\n\t\t}\n\t\tstringPosition = 0;\n\t\tsrcStringEnd = 0;\n\t\tsrcString = null;\n\t\tstrings = EMPTY_ARRAY;\n\t\tbundledStrings = null;\n\t\tsrc = source;\n\t\t// this provides cached access to the data view for a buffer if it is getting reused, which is a recommend\n\t\t// technique for getting data from a database where it can be copied into an existing buffer instead of creating\n\t\t// new ones\n\t\ttry {\n\t\t\tdataView = source.dataView || (source.dataView = new DataView(source.buffer, source.byteOffset, source.byteLength));\n\t\t} catch(error) {\n\t\t\t// if it doesn't have a buffer, maybe it is the wrong type of object\n\t\t\tsrc = null;\n\t\t\tif (source instanceof Uint8Array)\n\t\t\t\tthrow error;\n\t\t\tthrow new Error('Source must be a Uint8Array or Buffer but was a ' + ((source && typeof source == 'object') ? source.constructor.name : typeof source));\n\t\t}\n\t\tif (this instanceof Unpackr) {\n\t\t\tcurrentUnpackr = this;\n\t\t\tif (this.structures) {\n\t\t\t\tcurrentStructures = this.structures;\n\t\t\t\treturn checkedRead(options);\n\t\t\t} else if (!currentStructures || currentStructures.length > 0) {\n\t\t\t\tcurrentStructures = [];\n\t\t\t}\n\t\t} else {\n\t\t\tcurrentUnpackr = defaultOptions;\n\t\t\tif (!currentStructures || currentStructures.length > 0)\n\t\t\t\tcurrentStructures = [];\n\t\t}\n\t\treturn checkedRead(options);\n\t}\n\tunpackMultiple(source, forEach) {\n\t\tlet values, lastPosition = 0;\n\t\ttry {\n\t\t\tsequentialMode = true;\n\t\t\tlet size = source.length;\n\t\t\tlet value = this ? this.unpack(source, size) : defaultUnpackr.unpack(source, size);\n\t\t\tif (forEach) {\n\t\t\t\tif (forEach(value, lastPosition, position) === false) return;\n\t\t\t\twhile(position < size) {\n\t\t\t\t\tlastPosition = position;\n\t\t\t\t\tif (forEach(checkedRead(), lastPosition, position) === false) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tvalues = [ value ];\n\t\t\t\twhile(position < size) {\n\t\t\t\t\tlastPosition = position;\n\t\t\t\t\tvalues.push(checkedRead());\n\t\t\t\t}\n\t\t\t\treturn values;\n\t\t\t}\n\t\t} catch(error) {\n\t\t\terror.lastPosition = lastPosition;\n\t\t\terror.values = values;\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tsequentialMode = false;\n\t\t\tclearSource();\n\t\t}\n\t}\n\t_mergeStructures(loadedStructures, existingStructures) {\n\t\tif (this._onLoadedStructures)\n\t\t\tloadedStructures = this._onLoadedStructures(loadedStructures);\n\t\tloadedStructures = loadedStructures || [];\n\t\tif (Object.isFrozen(loadedStructures))\n\t\t\tloadedStructures = loadedStructures.map(structure => structure.slice(0));\n\t\tfor (let i = 0, l = loadedStructures.length; i < l; i++) {\n\t\t\tlet structure = loadedStructures[i];\n\t\t\tif (structure) {\n\t\t\t\tstructure.isShared = true;\n\t\t\t\tif (i >= 32)\n\t\t\t\t\tstructure.highByte = (i - 32) >> 5;\n\t\t\t}\n\t\t}\n\t\tloadedStructures.sharedLength = loadedStructures.length;\n\t\tfor (let id in existingStructures || []) {\n\t\t\tif (id >= 0) {\n\t\t\t\tlet structure = loadedStructures[id];\n\t\t\t\tlet existing = existingStructures[id];\n\t\t\t\tif (existing) {\n\t\t\t\t\tif (structure)\n\t\t\t\t\t\t(loadedStructures.restoreStructures || (loadedStructures.restoreStructures = []))[id] = structure;\n\t\t\t\t\tloadedStructures[id] = existing;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn this.structures = loadedStructures;\n\t}\n\tdecode(source, options) {\n\t\treturn this.unpack(source, options);\n\t}\n}\nexport function getPosition() {\n\treturn position;\n}\nexport function checkedRead(options) {\n\ttry {\n\t\tif (!currentUnpackr.trusted && !sequentialMode) {\n\t\t\tlet sharedLength = currentStructures.sharedLength || 0;\n\t\t\tif (sharedLength < currentStructures.length)\n\t\t\t\tcurrentStructures.length = sharedLength;\n\t\t}\n\t\tlet result;\n\t\tif (currentUnpackr._readStruct && src[position] < 0x40 && src[position] >= 0x20) {\n\t\t\tresult = currentUnpackr._readStruct(src, position, srcEnd);\n\t\t\tsrc = null; // dispose of this so that recursive unpack calls don't save state\n\t\t\tif (!(options && options.lazy) && result)\n\t\t\t\tresult = result.toJSON();\n\t\t\tposition = srcEnd;\n\t\t} else\n\t\t\tresult = read();\n\t\tif (bundledStrings) { // bundled strings to skip past\n\t\t\tposition = bundledStrings.postBundlePosition;\n\t\t\tbundledStrings = null;\n\t\t}\n\t\tif (sequentialMode)\n\t\t\t// we only need to restore the structures if there was an error, but if we completed a read,\n\t\t\t// we can clear this out and keep the structures we read\n\t\t\tcurrentStructures.restoreStructures = null;\n\n\t\tif (position == srcEnd) {\n\t\t\t// finished reading this source, cleanup references\n\t\t\tif (currentStructures && currentStructures.restoreStructures)\n\t\t\t\trestoreStructures();\n\t\t\tcurrentStructures = null;\n\t\t\tsrc = null;\n\t\t\tif (referenceMap)\n\t\t\t\treferenceMap = null;\n\t\t} else if (position > srcEnd) {\n\t\t\t// over read\n\t\t\tthrow new Error('Unexpected end of MessagePack data');\n\t\t} else if (!sequentialMode) {\n\t\t\tlet jsonView;\n\t\t\ttry {\n\t\t\t\tjsonView = JSON.stringify(result, (_, value) => typeof value === \"bigint\" ? `${value}n` : value).slice(0, 100);\n\t\t\t} catch(error) {\n\t\t\t\tjsonView = '(JSON view not available ' + error + ')';\n\t\t\t}\n\t\t\tthrow new Error('Data read, but end of buffer not reached ' + jsonView);\n\t\t}\n\t\t// else more to read, but we are reading sequentially, so don't clear source yet\n\t\treturn result;\n\t} catch(error) {\n\t\tif (currentStructures && currentStructures.restoreStructures)\n\t\t\trestoreStructures();\n\t\tclearSource();\n\t\tif (error instanceof RangeError || error.message.startsWith('Unexpected end of buffer') || position > srcEnd) {\n\t\t\terror.incomplete = true;\n\t\t}\n\t\tthrow error;\n\t}\n}\n\nfunction restoreStructures() {\n\tfor (let id in currentStructures.restoreStructures) {\n\t\tcurrentStructures[id] = currentStructures.restoreStructures[id];\n\t}\n\tcurrentStructures.restoreStructures = null;\n}\n\nexport function read() {\n\tlet token = src[position++];\n\tif (token < 0xa0) {\n\t\tif (token < 0x80) {\n\t\t\tif (token < 0x40)\n\t\t\t\treturn token;\n\t\t\telse {\n\t\t\t\tlet structure = currentStructures[token & 0x3f] ||\n\t\t\t\t\tcurrentUnpackr.getStructures && loadStructures()[token & 0x3f];\n\t\t\t\tif (structure) {\n\t\t\t\t\tif (!structure.read) {\n\t\t\t\t\t\tstructure.read = createStructureReader(structure, token & 0x3f);\n\t\t\t\t\t}\n\t\t\t\t\treturn structure.read();\n\t\t\t\t} else\n\t\t\t\t\treturn token;\n\t\t\t}\n\t\t} else if (token < 0x90) {\n\t\t\t// map\n\t\t\ttoken -= 0x80;\n\t\t\tif (currentUnpackr.mapsAsObjects) {\n\t\t\t\tlet object = {};\n\t\t\t\tfor (let i = 0; i < token; i++) {\n\t\t\t\t\tlet key = readKey();\n\t\t\t\t\tif (key === '__proto__')\n\t\t\t\t\t\tkey = '__proto_';\n\t\t\t\t\tobject[key] = read();\n\t\t\t\t}\n\t\t\t\treturn object;\n\t\t\t} else {\n\t\t\t\tlet map = new Map();\n\t\t\t\tfor (let i = 0; i < token; i++) {\n\t\t\t\t\tmap.set(read(), read());\n\t\t\t\t}\n\t\t\t\treturn map;\n\t\t\t}\n\t\t} else {\n\t\t\ttoken -= 0x90;\n\t\t\tlet array = new Array(token);\n\t\t\tfor (let i = 0; i < token; i++) {\n\t\t\t\tarray[i] = read();\n\t\t\t}\n\t\t\tif (currentUnpackr.freezeData)\n\t\t\t\treturn Object.freeze(array);\n\t\t\treturn array;\n\t\t}\n\t} else if (token < 0xc0) {\n\t\t// fixstr\n\t\tlet length = token - 0xa0;\n\t\tif (srcStringEnd >= position) {\n\t\t\treturn srcString.slice(position - srcStringStart, (position += length) - srcStringStart);\n\t\t}\n\t\tif (srcStringEnd == 0 && srcEnd < 140) {\n\t\t\t// for small blocks, avoiding the overhead of the extract call is helpful\n\t\t\tlet string = length < 16 ? shortStringInJS(length) : longStringInJS(length);\n\t\t\tif (string != null)\n\t\t\t\treturn string;\n\t\t}\n\t\treturn readFixedString(length);\n\t} else {\n\t\tlet value;\n\t\tswitch (token) {\n\t\t\tcase 0xc0: return null;\n\t\t\tcase 0xc1:\n\t\t\t\tif (bundledStrings) {\n\t\t\t\t\tvalue = read(); // followed by the length of the string in characters (not bytes!)\n\t\t\t\t\tif (value > 0)\n\t\t\t\t\t\treturn bundledStrings[1].slice(bundledStrings.position1, bundledStrings.position1 += value);\n\t\t\t\t\telse\n\t\t\t\t\t\treturn bundledStrings[0].slice(bundledStrings.position0, bundledStrings.position0 -= value);\n\t\t\t\t}\n\t\t\t\treturn C1; // \"never-used\", return special object to denote that\n\t\t\tcase 0xc2: return false;\n\t\t\tcase 0xc3: return true;\n\t\t\tcase 0xc4:\n\t\t\t\t// bin 8\n\t\t\t\tvalue = src[position++];\n\t\t\t\tif (value === undefined)\n\t\t\t\t\tthrow new Error('Unexpected end of buffer');\n\t\t\t\treturn readBin(value);\n\t\t\tcase 0xc5:\n\t\t\t\t// bin 16\n\t\t\t\tvalue = dataView.getUint16(position);\n\t\t\t\tposition += 2;\n\t\t\t\treturn readBin(value);\n\t\t\tcase 0xc6:\n\t\t\t\t// bin 32\n\t\t\t\tvalue = dataView.getUint32(position);\n\t\t\t\tposition += 4;\n\t\t\t\treturn readBin(value);\n\t\t\tcase 0xc7:\n\t\t\t\t// ext 8\n\t\t\t\treturn readExt(src[position++]);\n\t\t\tcase 0xc8:\n\t\t\t\t// ext 16\n\t\t\t\tvalue = dataView.getUint16(position);\n\t\t\t\tposition += 2;\n\t\t\t\treturn readExt(value);\n\t\t\tcase 0xc9:\n\t\t\t\t// ext 32\n\t\t\t\tvalue = dataView.getUint32(position);\n\t\t\t\tposition += 4;\n\t\t\t\treturn readExt(value);\n\t\t\tcase 0xca:\n\t\t\t\tvalue = dataView.getFloat32(position);\n\t\t\t\tif (currentUnpackr.useFloat32 > 2) {\n\t\t\t\t\t// this does rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved\n\t\t\t\t\tlet multiplier = mult10[((src[position] & 0x7f) << 1) | (src[position + 1] >> 7)];\n\t\t\t\t\tposition += 4;\n\t\t\t\t\treturn ((multiplier * value + (value > 0 ? 0.5 : -0.5)) >> 0) / multiplier;\n\t\t\t\t}\n\t\t\t\tposition += 4;\n\t\t\t\treturn value;\n\t\t\tcase 0xcb:\n\t\t\t\tvalue = dataView.getFloat64(position);\n\t\t\t\tposition += 8;\n\t\t\t\treturn value;\n\t\t\t// uint handlers\n\t\t\tcase 0xcc:\n\t\t\t\treturn src[position++];\n\t\t\tcase 0xcd:\n\t\t\t\tvalue = dataView.getUint16(position);\n\t\t\t\tposition += 2;\n\t\t\t\treturn value;\n\t\t\tcase 0xce:\n\t\t\t\tvalue = dataView.getUint32(position);\n\t\t\t\tposition += 4;\n\t\t\t\treturn value;\n\t\t\tcase 0xcf:\n\t\t\t\tif (currentUnpackr.int64AsType === 'number') {\n\t\t\t\t\tvalue = dataView.getUint32(position) * 0x100000000;\n\t\t\t\t\tvalue += dataView.getUint32(position + 4);\n\t\t\t\t} else if (currentUnpackr.int64AsType === 'string') {\n\t\t\t\t\tvalue = dataView.getBigUint64(position).toString();\n\t\t\t\t} else if (currentUnpackr.int64AsType === 'auto') {\n\t\t\t\t\tvalue = dataView.getBigUint64(position);\n\t\t\t\t\tif (value<=BigInt(2)<<BigInt(52)) value=Number(value);\n\t\t\t\t} else\n\t\t\t\t\tvalue = dataView.getBigUint64(position);\n\t\t\t\tposition += 8;\n\t\t\t\treturn value;\n\n\t\t\t// int handlers\n\t\t\tcase 0xd0:\n\t\t\t\treturn dataView.getInt8(position++);\n\t\t\tcase 0xd1:\n\t\t\t\tvalue = dataView.getInt16(position);\n\t\t\t\tposition += 2;\n\t\t\t\treturn value;\n\t\t\tcase 0xd2:\n\t\t\t\tvalue = dataView.getInt32(position);\n\t\t\t\tposition += 4;\n\t\t\t\treturn value;\n\t\t\tcase 0xd3:\n\t\t\t\tif (currentUnpackr.int64AsType === 'number') {\n\t\t\t\t\tvalue = dataView.getInt32(position) * 0x100000000;\n\t\t\t\t\tvalue += dataView.getUint32(position + 4);\n\t\t\t\t} else if (currentUnpackr.int64AsType === 'string') {\n\t\t\t\t\tvalue = dataView.getBigInt64(position).toString();\n\t\t\t\t} else if (currentUnpackr.int64AsType === 'auto') {\n\t\t\t\t\tvalue = dataView.getBigInt64(position);\n\t\t\t\t\tif (value>=BigInt(-2)<<BigInt(52)&&value<=BigInt(2)<<BigInt(52)) value=Number(value);\n\t\t\t\t} else\n\t\t\t\t\tvalue = dataView.getBigInt64(position);\n\t\t\t\tposition += 8;\n\t\t\t\treturn value;\n\n\t\t\tcase 0xd4:\n\t\t\t\t// fixext 1\n\t\t\t\tvalue = src[position++];\n\t\t\t\tif (value == 0x72) {\n\t\t\t\t\treturn recordDefinition(src[position++] & 0x3f);\n\t\t\t\t} else {\n\t\t\t\t\tlet extension = currentExtensions[value];\n\t\t\t\t\tif (extension) {\n\t\t\t\t\t\tif (extension.read) {\n\t\t\t\t\t\t\tposition++; // skip filler byte\n\t\t\t\t\t\t\treturn extension.read(read());\n\t\t\t\t\t\t} else if (extension.noBuffer) {\n\t\t\t\t\t\t\tposition++; // skip filler byte\n\t\t\t\t\t\t\treturn extension();\n\t\t\t\t\t\t} else\n\t\t\t\t\t\t\treturn extension(src.subarray(position, ++position));\n\t\t\t\t\t} else\n\t\t\t\t\t\tthrow new Error('Unknown extension ' + value);\n\t\t\t\t}\n\t\t\tcase 0xd5:\n\t\t\t\t// fixext 2\n\t\t\t\tvalue = src[position];\n\t\t\t\tif (value == 0x72) {\n\t\t\t\t\tposition++;\n\t\t\t\t\treturn recordDefinition(src[position++] & 0x3f, src[position++]);\n\t\t\t\t} else\n\t\t\t\t\treturn readExt(2);\n\t\t\tcase 0xd6:\n\t\t\t\t// fixext 4\n\t\t\t\treturn readExt(4);\n\t\t\tcase 0xd7:\n\t\t\t\t// fixext 8\n\t\t\t\treturn readExt(8);\n\t\t\tcase 0xd8:\n\t\t\t\t// fixext 16\n\t\t\t\treturn readExt(16);\n\t\t\tcase 0xd9:\n\t\t\t// str 8\n\t\t\t\tvalue = src[position++];\n\t\t\t\tif (srcStringEnd >= position) {\n\t\t\t\t\treturn srcString.slice(position - srcStringStart, (position += value) - srcStringStart);\n\t\t\t\t}\n\t\t\t\treturn readString8(value);\n\t\t\tcase 0xda:\n\t\t\t// str 16\n\t\t\t\tvalue = dataView.getUint16(position);\n\t\t\t\tposition += 2;\n\t\t\t\tif (srcStringEnd >= position) {\n\t\t\t\t\treturn srcString.slice(position - srcStringStart, (position += value) - srcStringStart);\n\t\t\t\t}\n\t\t\t\treturn readString16(value);\n\t\t\tcase 0xdb:\n\t\t\t// str 32\n\t\t\t\tvalue = dataView.getUint32(position);\n\t\t\t\tposition += 4;\n\t\t\t\tif (srcStringEnd >= position) {\n\t\t\t\t\treturn srcString.slice(position - srcStringStart, (position += value) - srcStringStart);\n\t\t\t\t}\n\t\t\t\treturn readString32(value);\n\t\t\tcase 0xdc:\n\t\t\t// array 16\n\t\t\t\tvalue = dataView.getUint16(position);\n\t\t\t\tposition += 2;\n\t\t\t\treturn readArray(value);\n\t\t\tcase 0xdd:\n\t\t\t// array 32\n\t\t\t\tvalue = dataView.getUint32(position);\n\t\t\t\tposition += 4;\n\t\t\t\treturn readArray(value);\n\t\t\tcase 0xde:\n\t\t\t// map 16\n\t\t\t\tvalue = dataView.getUint16(position);\n\t\t\t\tposition += 2;\n\t\t\t\treturn readMap(value);\n\t\t\tcase 0xdf:\n\t\t\t// map 32\n\t\t\t\tvalue = dataView.getUint32(position);\n\t\t\t\tposition += 4;\n\t\t\t\treturn readMap(value);\n\t\t\tdefault: // negative int\n\t\t\t\tif (token >= 0xe0)\n\t\t\t\t\treturn token - 0x100;\n\t\t\t\tif (token === undefined) {\n\t\t\t\t\tlet error = new Error('Unexpected end of MessagePack data');\n\t\t\t\t\terror.incomplete = true;\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tthrow new Error('Unknown MessagePack token ' + token);\n\n\t\t}\n\t}\n}\nconst validName = /^[a-zA-Z_$][a-zA-Z\\d_$]*$/;\nfunction createStructureReader(structure, firstId) {\n\tfunction readObject() {\n\t\t// This initial function is quick to instantiate, but runs slower. After several iterations pay the cost to build the faster function\n\t\tif (readObject.count++ > inlineObjectReadThreshold) {\n\t\t\tlet optimizedReadObject;\n\t\t\ttry {\n\t\t\t\toptimizedReadObject = structure.read = (new Function('r', 'return function(){return ' + (currentUnpackr.freezeData ? 'Object.freeze' : '') +\n\t\t\t\t\t'({' + structure.map(key => key === '__proto__' ? '__proto_:r()' : validName.test(key) ? key + ':r()' : ('[' + JSON.stringify(key) + ']:r()')).join(',') + '})}'))(read);\n\t\t\t} catch(error) {\n\t\t\t\t// in CF workers, the new Function call could begin to fail at any point in time\n\t\t\t\tinlineObjectReadThreshold = Infinity; // disable going forward\n\t\t\t\treturn readObject(); // recursively try again\n\t\t\t}\n\t\t\tstructure.read0 = optimizedReadObject; // keep the un-wrapped body reader in sync\n\t\t\tif (structure.highByte === 0)\n\t\t\t\tstructure.read = createSecondByteReader(firstId, structure.read);\n\t\t\treturn optimizedReadObject(); // second byte is already read, if there is one so immediately read object\n\t\t}\n\t\tlet object = {};\n\t\tfor (let i = 0, l = structure.length; i < l; i++) {\n\t\t\tlet key = structure[i];\n\t\t\tif (key === '__proto__')\n\t\t\t\tkey = '__proto_';\n\t\t\tobject[key] = read();\n\t\t}\n\t\tif (currentUnpackr.freezeData)\n\t\t\treturn Object.freeze(object);\n\t\treturn object;\n\t}\n\treadObject.count = 0;\n\t// read0 is the un-wrapped body reader: it reads the record's values directly without\n\t// consuming a leading high byte. recordDefinition uses it for the immediate read that follows\n\t// a record definition (the high byte, if present, was already consumed). For highByte === 0\n\t// structures the public reader is a second-byte reader (used by later references), but the\n\t// definition read itself must not consume that byte.\n\tstructure.read0 = readObject;\n\tif (structure.highByte === 0) {\n\t\treturn createSecondByteReader(firstId, readObject);\n\t}\n\treturn readObject;\n}\n\nconst createSecondByteReader = (firstId, read0) => {\n\treturn function() {\n\t\tlet highByte = src[position++];\n\t\tif (highByte === 0)\n\t\t\treturn read0();\n\t\tlet id = firstId < 32 ? -(firstId + (highByte << 5)) : firstId + (highByte << 5);\n\t\tlet structure = currentStructures[id] || loadStructures()[id];\n\t\tif (!structure) {\n\t\t\tthrow new Error('Record id is not defined for ' + id);\n\t\t}\n\t\tif (!structure.read)\n\t\t\tstructure.read = createStructureReader(structure, firstId);\n\t\treturn structure.read();\n\t};\n};\n\nexport function loadStructures() {\n\tlet loadedStructures = saveState(() => {\n\t\t// save the state in case getStructures modifies our buffer\n\t\tsrc = null;\n\t\treturn currentUnpackr.getStructures();\n\t});\n\treturn currentStructures = currentUnpackr._mergeStructures(loadedStructures, currentStructures);\n}\n\nvar readFixedString = readStringJS;\nvar readString8 = readStringJS;\nvar readString16 = readStringJS;\nvar readString32 = readStringJS;\nexport let isNativeAccelerationEnabled = false;\n\nexport function setExtractor(extractStrings) {\n\tisNativeAccelerationEnabled = true;\n\treadFixedString = readString(1);\n\treadString8 = readString(2);\n\treadString16 = readString(3);\n\treadString32 = readString(5);\n\tfunction readString(headerLength) {\n\t\treturn function readString(length) {\n\t\t\tlet string = strings[stringPosition++];\n\t\t\tif (string == null) {\n\t\t\t\tif (bundledStrings)\n\t\t\t\t\treturn readStringJS(length);\n\t\t\t\tlet byteOffset = src.byteOffset;\n\t\t\t\tlet extraction = extractStrings(position - headerLength + byteOffset, srcEnd + byteOffset, src.buffer);\n\t\t\t\tif (typeof extraction == 'string') {\n\t\t\t\t\tstring = extraction;\n\t\t\t\t\tstrings = EMPTY_ARRAY;\n\t\t\t\t} else {\n\t\t\t\t\tstrings = extraction;\n\t\t\t\t\tstringPosition = 1;\n\t\t\t\t\tsrcStringEnd = 1; // even if a utf-8 string was decoded, must indicate we are in the midst of extracted strings and can't skip strings\n\t\t\t\t\tstring = strings[0];\n\t\t\t\t\tif (string === undefined)\n\t\t\t\t\t\tthrow new Error('Unexpected end of buffer');\n\t\t\t\t}\n\t\t\t}\n\t\t\tlet srcStringLength = string.length;\n\t\t\tif (srcStringLength <= length) {\n\t\t\t\tposition += length;\n\t\t\t\treturn string;\n\t\t\t}\n\t\t\tsrcString = string;\n\t\t\tsrcStringStart = position;\n\t\t\tsrcStringEnd = position + srcStringLength;\n\t\t\tposition += length;\n\t\t\treturn string.slice(0, length); // we know we just want the beginning\n\t\t};\n\t}\n}\nfunction readStringJS(length) {\n\tlet result;\n\tif (length < 16) {\n\t\tif (result = shortStringInJS(length))\n\t\t\treturn result;\n\t}\n\tif (length > 64 && decoder)\n\t\treturn decoder.decode(src.subarray(position, position += length));\n\tconst end = position + length;\n\tconst units = [];\n\tresult = '';\n\twhile (position < end) {\n\t\tconst byte1 = src[position++];\n\t\tif ((byte1 & 0x80) === 0) {\n\t\t\t// 1 byte\n\t\t\tunits.push(byte1);\n\t\t} else if ((byte1 & 0xe0) === 0xc0) {\n\t\t\t// 2 bytes\n\t\t\tconst byte2 = src[position++] & 0x3f;\n\t\t\tconst codePoint = ((byte1 & 0x1f) << 6) | byte2;\n\t\t\t// Reject overlong encoding: 2-byte sequences must encode values >= 0x80\n\t\t\tif (codePoint < 0x80) {\n\t\t\t\tunits.push(0xFFFD); // replacement character\n\t\t\t} else {\n\t\t\t\tunits.push(codePoint);\n\t\t\t}\n\t\t} else if ((byte1 & 0xf0) === 0xe0) {\n\t\t\t// 3 bytes\n\t\t\tconst byte2 = src[position++] & 0x3f;\n\t\t\tconst byte3 = src[position++] & 0x3f;\n\t\t\tconst codePoint = ((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3;\n\t\t\t// Reject overlong encoding: 3-byte sequences must encode values >= 0x800\n\t\t\t// Also reject surrogates (0xD800-0xDFFF)\n\t\t\tif (codePoint < 0x800 || (codePoint >= 0xD800 && codePoint <= 0xDFFF)) {\n\t\t\t\tunits.push(0xFFFD); // replacement character\n\t\t\t} else {\n\t\t\t\tunits.push(codePoint);\n\t\t\t}\n\t\t} else if ((byte1 & 0xf8) === 0xf0) {\n\t\t\t// 4 bytes\n\t\t\tconst byte2 = src[position++] & 0x3f;\n\t\t\tconst byte3 = src[position++] & 0x3f;\n\t\t\tconst byte4 = src[position++] & 0x3f;\n\t\t\tlet unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;\n\t\t\t// Reject overlong encoding: 4-byte sequences must encode values >= 0x10000\n\t\t\t// Also reject values > 0x10FFFF (maximum valid Unicode)\n\t\t\tif (unit < 0x10000 || unit > 0x10FFFF) {\n\t\t\t\tunits.push(0xFFFD); // replacement character\n\t\t\t} else if (unit > 0xffff) {\n\t\t\t\tunit -= 0x10000;\n\t\t\t\tunits.push(((unit >>> 10) & 0x3ff) | 0xd800);\n\t\t\t\tunit = 0xdc00 | (unit & 0x3ff);\n\t\t\t\tunits.push(unit);\n\t\t\t} else {\n\t\t\t\tunits.push(unit);\n\t\t\t}\n\t\t} else {\n\t\t\tunits.push(0xFFFD); // replacement character for invalid lead byte\n\t\t}\n\n\t\tif (units.length >= 0x1000) {\n\t\t\tresult += fromCharCode.apply(String, units);\n\t\t\tunits.length = 0;\n\t\t}\n\t}\n\n\tif (units.length > 0) {\n\t\tresult += fromCharCode.apply(String, units);\n\t}\n\n\treturn result;\n}\nexport function readString(source, start, length) {\n\tlet existingSrc = src;\n\tsrc = source;\n\tposition = start;\n\ttry {\n\t\treturn readStringJS(length);\n\t} finally {\n\t\tsrc = existingSrc;\n\t}\n}\n\nfunction readArray(length) {\n\tlet array = new Array(length);\n\tfor (let i = 0; i < length; i++) {\n\t\tarray[i] = read();\n\t}\n\tif (currentUnpackr.freezeData)\n\t\treturn Object.freeze(array);\n\treturn array;\n}\n\nfunction readMap(length) {\n\tif (currentUnpackr.mapsAsObjects) {\n\t\tlet object = {};\n\t\tfor (let i = 0; i < length; i++) {\n\t\t\tlet key = readKey();\n\t\t\tif (key === '__proto__')\n\t\t\t\tkey = '__proto_';\n\t\t\tobject[key] = read();\n\t\t}\n\t\treturn object;\n\t} else {\n\t\tlet map = new Map();\n\t\tfor (let i = 0; i < length; i++) {\n\t\t\tmap.set(read(), read());\n\t\t}\n\t\treturn map;\n\t}\n}\n\nvar fromCharCode = String.fromCharCode;\nfunction longStringInJS(length) {\n\tlet start = position;\n\tlet bytes = new Array(length);\n\tfor (let i = 0; i < length; i++) {\n\t\tconst byte = src[position++];\n\t\tif ((byte & 0x80) > 0) {\n\t\t\t\tposition = start;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tbytes[i] = byte;\n\t\t}\n\t\treturn fromCharCode.apply(String, bytes);\n}\nfunction shortStringInJS(length) {\n\tif (length < 4) {\n\t\tif (length < 2) {\n\t\t\tif (length === 0)\n\t\t\t\treturn '';\n\t\t\telse {\n\t\t\t\tlet a = src[position++];\n\t\t\t\tif ((a & 0x80) > 1) {\n\t\t\t\t\tposition -= 1;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\treturn fromCharCode(a);\n\t\t\t}\n\t\t} else {\n\t\t\tlet a = src[position++];\n\t\t\tlet b = src[position++];\n\t\t\tif ((a & 0x80) > 0 || (b & 0x80) > 0) {\n\t\t\t\tposition -= 2;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (length < 3)\n\t\t\t\treturn fromCharCode(a, b);\n\t\t\tlet c = src[position++];\n\t\t\tif ((c & 0x80) > 0) {\n\t\t\t\tposition -= 3;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\treturn fromCharCode(a, b, c);\n\t\t}\n\t} else {\n\t\tlet a = src[position++];\n\t\tlet b = src[position++];\n\t\tlet c = src[position++];\n\t\tlet d = src[position++];\n\t\tif ((a & 0x80) > 0 || (b & 0x80) > 0 || (c & 0x80) > 0 || (d & 0x80) > 0) {\n\t\t\tposition -= 4;\n\t\t\treturn;\n\t\t}\n\t\tif (length < 6) {\n\t\t\tif (length === 4)\n\t\t\t\treturn fromCharCode(a, b, c, d);\n\t\t\telse {\n\t\t\t\tlet e = src[position++];\n\t\t\t\tif ((e & 0x80) > 0) {\n\t\t\t\t\tposition -= 5;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\treturn fromCharCode(a, b, c, d, e);\n\t\t\t}\n\t\t} else if (length < 8) {\n\t\t\tlet e = src[position++];\n\t\t\tlet f = src[position++];\n\t\t\tif ((e & 0x80) > 0 || (f & 0x80) > 0) {\n\t\t\t\tposition -= 6;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (length < 7)\n\t\t\t\treturn fromCharCode(a, b, c, d, e, f);\n\t\t\tlet g = src[position++];\n\t\t\tif ((g & 0x80) > 0) {\n\t\t\t\tposition -= 7;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\treturn fromCharCode(a, b, c, d, e, f, g);\n\t\t} else {\n\t\t\tlet e = src[position++];\n\t\t\tlet f = src[position++];\n\t\t\tlet g = src[position++];\n\t\t\tlet h = src[position++];\n\t\t\tif ((e & 0x80) > 0 || (f & 0x80) > 0 || (g & 0x80) > 0 || (h & 0x80) > 0) {\n\t\t\t\tposition -= 8;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (length < 10) {\n\t\t\t\tif (length === 8)\n\t\t\t\t\treturn fromCharCode(a, b, c, d, e, f, g, h);\n\t\t\t\telse {\n\t\t\t\t\tlet i = src[position++];\n\t\t\t\t\tif ((i & 0x80) > 0) {\n\t\t\t\t\t\tposition -= 9;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\treturn fromCharCode(a, b, c, d, e, f, g, h, i);\n\t\t\t\t}\n\t\t\t} else if (length < 12) {\n\t\t\t\tlet i = src[position++];\n\t\t\t\tlet j = src[position++];\n\t\t\t\tif ((i & 0x80) > 0 || (j & 0x80) > 0) {\n\t\t\t\t\tposition -= 10;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (length < 11)\n\t\t\t\t\treturn fromCharCode(a, b, c, d, e, f, g, h, i, j);\n\t\t\t\tlet k = src[position++];\n\t\t\t\tif ((k & 0x80) > 0) {\n\t\t\t\t\tposition -= 11;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\treturn fromCharCode(a, b, c, d, e, f, g, h, i, j, k);\n\t\t\t} else {\n\t\t\t\tlet i = src[position++];\n\t\t\t\tlet j = src[position++];\n\t\t\t\tlet k = src[position++];\n\t\t\t\tlet l = src[position++];\n\t\t\t\tif ((i & 0x80) > 0 || (j & 0x80) > 0 || (k & 0x80) > 0 || (l & 0x80) > 0) {\n\t\t\t\t\tposition -= 12;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (length < 14) {\n\t\t\t\t\tif (length === 12)\n\t\t\t\t\t\treturn fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l);\n\t\t\t\t\telse {\n\t\t\t\t\t\tlet m = src[position++];\n\t\t\t\t\t\tif ((m & 0x80) > 0) {\n\t\t\t\t\t\t\tposition -= 13;\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tlet m = src[position++];\n\t\t\t\t\tlet n = src[position++];\n\t\t\t\t\tif ((m & 0x80) > 0 || (n & 0x80) > 0) {\n\t\t\t\t\t\tposition -= 14;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (length < 15)\n\t\t\t\t\t\treturn fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n);\n\t\t\t\t\tlet o = src[position++];\n\t\t\t\t\tif ((o & 0x80) > 0) {\n\t\t\t\t\t\tposition -= 15;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\treturn fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction readOnlyJSString() {\n\tlet token = src[position++];\n\tlet length;\n\tif (token < 0xc0) {\n\t\t// fixstr\n\t\tlength = token - 0xa0;\n\t} else {\n\t\tswitch(token) {\n\t\t\tcase 0xd9:\n\t\t\t// str 8\n\t\t\t\tlength = src[position++];\n\t\t\t\tbreak;\n\t\t\tcase 0xda:\n\t\t\t// str 16\n\t\t\t\tlength = dataView.getUint16(position);\n\t\t\t\tposition += 2;\n\t\t\t\tbreak;\n\t\t\tcase 0xdb:\n\t\t\t// str 32\n\t\t\t\tlength = dataView.getUint32(position);\n\t\t\t\tposition += 4;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow new Error('Expected string');\n\t\t}\n\t}\n\treturn readStringJS(length);\n}\n\n\nfunction readBin(length) {\n\treturn currentUnpackr.copyBuffers ?\n\t\t// specifically use the copying slice (not the node one)\n\t\tUint8Array.prototype.slice.call(src, position, position += length) :\n\t\tsrc.subarray(position, position += length);\n}\nfunction readExt(length) {\n\tlet type = src[position++];\n\tif (currentExtensions[type]) {\n\t\tlet end;\n\t\treturn currentExtensions[type](src.subarray(position, end = (position += length)), (readPosition) => {\n\t\t\tposition = readPosition;\n\t\t\ttry {\n\t\t\t\treturn read();\n\t\t\t} finally {\n\t\t\t\tposition = end;\n\t\t\t}\n\t\t});\n\t}\n\telse\n\t\tthrow new Error('Unknown extension type ' + type);\n}\n\nvar keyCache = new Array(4096);\nfunction readKey() {\n\tlet length = src[position++];\n\tif (length >= 0xa0 && length < 0xc0) {\n\t\t// fixstr, potentially use key cache\n\t\tlength = length - 0xa0;\n\t\tif (srcStringEnd >= position) // if it has been extracted, must use it (and faster anyway)\n\t\t\treturn srcString.slice(position - srcStringStart, (position += length) - srcStringStart);\n\t\telse if (!(srcStringEnd == 0 && srcEnd < 180))\n\t\t\treturn readFixedString(length);\n\t} else { // not cacheable, go back and do a standard read\n\t\tposition--;\n\t\treturn asSafeString(read());\n\t}\n\tlet key = ((length << 5) ^ (length > 1 ? dataView.getUint16(position) : length > 0 ? src[position] : 0)) & 0xfff;\n\tlet entry = keyCache[key];\n\tlet checkPosition = position;\n\tlet end = position + length - 3;\n\tlet chunk;\n\tlet i = 0;\n\tif (entry && entry.bytes == length) {\n\t\twhile (checkPosition < end) {\n\t\t\tchunk = dataView.getUint32(checkPosition);\n\t\t\tif (chunk != entry[i++]) {\n\t\t\t\tcheckPosition = 0x70000000;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcheckPosition += 4;\n\t\t}\n\t\tend += 3;\n\t\twhile (checkPosition < end) {\n\t\t\tchunk = src[checkPosition++];\n\t\t\tif (chunk != entry[i++]) {\n\t\t\t\tcheckPosition = 0x70000000;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (checkPosition === end) {\n\t\t\tposition = checkPosition;\n\t\t\treturn entry.string;\n\t\t}\n\t\tend -= 3;\n\t\tcheckPosition = position;\n\t}\n\tentry = [];\n\tkeyCache[key] = entry;\n\tentry.bytes = length;\n\twhile (checkPosition < end) {\n\t\tchunk = dataView.getUint32(checkPosition);\n\t\tentry.push(chunk);\n\t\tcheckPosition += 4;\n\t}\n\tend += 3;\n\twhile (checkPosition < end) {\n\t\tchunk = src[checkPosition++];\n\t\tentry.push(chunk);\n\t}\n\t// for small blocks, avoiding the overhead of the extract call is helpful\n\tlet string = length < 16 ? shortStringInJS(length) : longStringInJS(length);\n\tif (string != null)\n\t\treturn entry.string = string;\n\treturn entry.string = readFixedString(length);\n}\n\nfunction asSafeString(property) {\n\t// protect against expensive (DoS) string conversions\n\tif (typeof property === 'string') return property;\n\tif (typeof property === 'number' || typeof property === 'boolean' || typeof property === 'bigint') return property.toString();\n\tif (property == null) return property + '';\n\tif (currentUnpackr.allowArraysInMapKeys && Array.isArray(property) && property.flat().every(item => ['string', 'number', 'boolean', 'bigint'].includes(typeof item))) {\n\t\treturn property.flat().toString();\n\t}\n\tthrow new Error(`Invalid property type for record: ${typeof property}`);\n}\n// the registration of the record definition extension (as \"r\")\nconst recordDefinition = (id, highByte) => {\n\tlet structure = read().map(asSafeString); // ensure that all keys are strings and\n\t// that the array is mutable\n\tlet firstByte = id;\n\tif (highByte !== undefined) {\n\t\tid = id < 32 ? -((highByte << 5) + id) : ((highByte << 5) + id);\n\t\tstructure.highByte = highByte;\n\t}\n\tlet existingStructure = currentStructures[id];\n\t// If it is a shared structure, we need to restore any changes after reading.\n\t// Also in sequential mode, we may get incomplete reads and thus errors, and we need to restore\n\t// to the state prior to an incomplete read in order to properly resume.\n\tif (existingStructure && (existingStructure.isShared || sequentialMode)) {\n\t\t(currentStructures.restoreStructures || (currentStructures.restoreStructures = []))[id] = existingStructure;\n\t}\n\tcurrentStructures[id] = structure;\n\tstructure.read = createStructureReader(structure, firstByte);\n\t// The high byte (if any) was already consumed as the `highByte` argument above, so read the\n\t// record body directly. Going through structure.read (a second-byte reader when highByte === 0)\n\t// would misinterpret the first value byte as a high byte — corrupting two-byte own-record\n\t// definitions (0xd5 0x72 ...). createStructureReader stashes the un-wrapped body reader on\n\t// structure.read0 precisely for this immediate post-definition read.\n\treturn (structure.read0 || structure.read)();\n};\ncurrentExtensions[0] = () => {}; // notepack defines extension 0 to mean undefined, so use that as the default here\ncurrentExtensions[0].noBuffer = true;\n\ncurrentExtensions[0x42] = data => {\n\tlet headLength = (data.byteLength % 8) || 8;\n\tlet head = BigInt(data[0] & 0x80 ? data[0] - 0x100 : data[0]);\n\tfor (let i = 1; i < headLength; i++) {\n\t\thead <<= BigInt(8);\n\t\thead += BigInt(data[i]);\n\t}\n\tif (data.byteLength !== headLength) {\n\t\tlet view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n\t\tlet decode = (start, end) => {\n\t\t\tlet length = end - start;\n\t\t\tif (length <= 40) {\n\t\t\t\tlet out = view.getBigUint64(start);\n\t\t\t\tfor (let i = start + 8; i < end; i += 8) {\n\t\t\t\t\tout <<= BigInt(64);\n\t\t\t\t\tout |= view.getBigUint64(i);\n\t\t\t\t}\n\t\t\t\treturn out;\n\t\t\t}\n\t\t\t// if (length === 8) return view.getBigUint64(start)\n\t\t\tlet middle = start + (length >> 4 << 3);\n\t\t\tlet left = decode(start, middle);\n\t\t\tlet right = decode(middle, end);\n\t\t\treturn (left << BigInt((end - middle) * 8)) | right;\n\t\t};\n\t\thead = (head << BigInt((view.byteLength - headLength) * 8)) | decode(headLength, view.byteLength);\n\t}\n\treturn head;\n};\n\nlet errors = {\n\tError, EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError, AggregateError: typeof AggregateError === 'function' ? AggregateError : null,\n};\ncurrentExtensions[0x65] = () => {\n\tlet data = read();\n\tif (!errors[data[0]]) {\n\t\tlet error = Error(data[1], { cause: data[2] });\n\t\terror.name = data[0];\n\t\treturn error;\n\t}\n\treturn errors[data[0]](data[1], { cause: data[2] });\n};\n\ncurrentExtensions[0x69] = (data) => {\n\t// id extension (for structured clones)\n\tif (currentUnpackr.structuredClone === false) throw new Error('Structured clone extension is disabled');\n\tlet id = dataView.getUint32(position - 4);\n\tif (!referenceMap)\n\t\treferenceMap = new Map();\n\tlet token = src[position];\n\tlet target;\n\t// TODO: handle any other types that can cycle and make the code more robust if there are other extensions\n\tif (token >= 0x90 && token < 0xa0 || token == 0xdc || token == 0xdd)\n\t\ttarget = [];\n\telse if (token >= 0x80 && token < 0x90 || token == 0xde || token == 0xdf)\n\t\ttarget = new Map();\n\telse if ((token >= 0xc7 && token <= 0xc9 || token >= 0xd4 && token <= 0xd8) && src[position + 1] === 0x73)\n\t\ttarget = new Set();\n\telse\n\t\ttarget = {};\n\n\tlet refEntry = { target }; // a placeholder object\n\treferenceMap.set(id, refEntry);\n\tlet targetProperties = read(); // read the next value as the target object to id\n\tif (!refEntry.used) {\n\t\t// no cycle, can just use the returned read object\n\t\treturn refEntry.target = targetProperties; // replace the placeholder with the real one\n\t} else {\n\t\t// there is a cycle, so we have to assign properties to original target\n\t\tObject.assign(target, targetProperties);\n\t}\n\n\t// copy over map/set entries if we're able to\n\tif (target instanceof Map)\n\t\tfor (let [k, v] of targetProperties.entries()) target.set(k, v);\n\tif (target instanceof Set)\n\t\tfor (let i of Array.from(targetProperties)) target.add(i);\n\treturn target;\n};\n\ncurrentExtensions[0x70] = (data) => {\n\t// pointer extension (for structured clones)\n\tif (currentUnpackr.structuredClone === false) throw new Error('Structured clone extension is disabled');\n\tlet id = dataView.getUint32(position - 4);\n\tlet refEntry = referenceMap.get(id);\n\trefEntry.used = true;\n\treturn refEntry.target;\n};\n\ncurrentExtensions[0x73] = () => new Set(read());\n\nexport const typedArrays = ['Int8','Uint8','Uint8Clamped','Int16','Uint16','Int32','Uint32','Float32','Float64','BigInt64','BigUint64'].map(type => type + 'Array');\n\nlet glbl = typeof globalThis === 'object' ? globalThis : window;\ncurrentExtensions[0x74] = (data) => {\n\tlet typeCode = data[0];\n\t// we always have to slice to get a new ArrayBuffer that is aligned\n\tlet buffer = Uint8Array.prototype.slice.call(data, 1).buffer;\n\n\tlet typedArrayName = typedArrays[typeCode];\n\tif (!typedArrayName) {\n\t\tif (typeCode === 16) return buffer;\n\t\tif (typeCode === 17) return new DataView(buffer);\n\t\tthrow new Error('Could not find typed array for code ' + typeCode);\n\t}\n\treturn new glbl[typedArrayName](buffer);\n};\ncurrentExtensions[0x78] = () => {\n\tlet data = read();\n\treturn new RegExp(data[0], data[1]);\n};\nconst TEMP_BUNDLE = [];\ncurrentExtensions[0x62] = (data) => {\n\tlet dataSize = (data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3];\n\tlet dataPosition = position;\n\tposition += dataSize - data.length;\n\tbundledStrings = TEMP_BUNDLE;\n\tbundledStrings = [readOnlyJSString(), readOnlyJSString()];\n\tbundledStrings.position0 = 0;\n\tbundledStrings.position1 = 0;\n\tbundledStrings.postBundlePosition = position;\n\tposition = dataPosition;\n\treturn read();\n};\n\ncurrentExtensions[0xff] = (data) => {\n\t// 32-bit date extension\n\tif (data.length == 4)\n\t\treturn new Date((data[0] * 0x1000000 + (data[1] << 16) + (data[2] << 8) + data[3]) * 1000);\n\telse if (data.length == 8)\n\t\treturn new Date(\n\t\t\t((data[0] << 22) + (data[1] << 14) + (data[2] << 6) + (data[3] >> 2)) / 1000000 +\n\t\t\t((data[3] & 0x3) * 0x100000000 + data[4] * 0x1000000 + (data[5] << 16) + (data[6] << 8) + data[7]) * 1000);\n\telse if (data.length == 12)\n\t\treturn new Date(\n\t\t\t((data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3]) / 1000000 +\n\t\t\t(((data[4] & 0x80) ? -0x1000000000000 : 0) + data[6] * 0x10000000000 + data[7] * 0x100000000 + data[8] * 0x1000000 + (data[9] << 16) + (data[10] << 8) + data[11]) * 1000);\n\telse\n\t\treturn new Date('invalid');\n};\n// registration of bulk record definition?\n// currentExtensions[0x52] = () =>\n\nfunction saveState(callback) {\n\tif (currentUnpackr && currentUnpackr._onSaveState)\n\t\tcurrentUnpackr._onSaveState();\n\tlet savedSrcEnd = srcEnd;\n\tlet savedPosition = position;\n\tlet savedStringPosition = stringPosition;\n\tlet savedSrcStringStart = srcStringStart;\n\tlet savedSrcStringEnd = srcStringEnd;\n\tlet savedSrcString = srcString;\n\tlet savedStrings = strings;\n\tlet savedReferenceMap = referenceMap;\n\tlet savedBundledStrings = bundledStrings;\n\n\t// TODO: We may need to revisit this if we do more external calls to user code (since it could be slow)\n\tlet savedSrc = new Uint8Array(src.slice(0, srcEnd)); // we copy the data in case it changes while external data is processed\n\tlet savedStructures = currentStructures;\n\tlet savedStructuresContents = currentStructures.slice(0, currentStructures.length);\n\tlet savedPackr = currentUnpackr;\n\tlet savedSequentialMode = sequentialMode;\n\tlet value = callback();\n\tsrcEnd = savedSrcEnd;\n\tposition = savedPosition;\n\tstringPosition = savedStringPosition;\n\tsrcStringStart = savedSrcStringStart;\n\tsrcStringEnd = savedSrcStringEnd;\n\tsrcString = savedSrcString;\n\tstrings = savedStrings;\n\treferenceMap = savedReferenceMap;\n\tbundledStrings = savedBundledStrings;\n\tsrc = savedSrc;\n\tsequentialMode = savedSequentialMode;\n\tcurrentStructures = savedStructures;\n\tcurrentStructures.splice(0, currentStructures.length, ...savedStructuresContents);\n\tcurrentUnpackr = savedPackr;\n\tdataView = new DataView(src.buffer, src.byteOffset, src.byteLength);\n\treturn value;\n}\nexport function clearSource() {\n\tsrc = null;\n\treferenceMap = null;\n\tcurrentStructures = null;\n}\n\nexport function addExtension(extension) {\n\tif (extension.unpack)\n\t\tcurrentExtensions[extension.type] = extension.unpack;\n\telse\n\t\tcurrentExtensions[extension.type] = extension;\n}\n\nexport const mult10 = new Array(147); // this is a table matching binary exponents to the multiplier to determine significant digit rounding\nfor (let i = 0; i < 256; i++) {\n\tmult10[i] = +('1e' + Math.floor(45.15 - i * 0.30103));\n}\nexport const Decoder = Unpackr;\nvar defaultUnpackr = new Unpackr({ useRecords: false });\nexport const unpack = defaultUnpackr.unpack;\nexport const unpackMultiple = defaultUnpackr.unpackMultiple;\nexport const decode = defaultUnpackr.unpack;\nexport const FLOAT32_OPTIONS = {\n\tNEVER: 0,\n\tALWAYS: 1,\n\tDECIMAL_ROUND: 3,\n\tDECIMAL_FIT: 4\n};\nlet f32Array = new Float32Array(1);\nlet u8Array = new Uint8Array(f32Array.buffer, 0, 4);\nexport function roundFloat32(float32Number) {\n\tf32Array[0] = float32Number;\n\tlet multiplier = mult10[((u8Array[3] & 0x7f) << 1) | (u8Array[2] >> 7)];\n\treturn ((multiplier * float32Number + (float32Number > 0 ? 0.5 : -0.5)) >> 0) / multiplier;\n}\n// Marker for downstream libraries (e.g. structon) to detect per-instance\n// struct-decoding hooks (this._readStruct, this._onLoadedStructures,\n// this._onSaveState).  See `checkedRead` for the dispatch.\nUnpackr.SUPPORTS_STRUCT_HOOKS = true;\n","import { Unpackr, mult10, C1Type, typedArrays, addExtension as unpackAddExtension } from './unpack.js';\nlet textEncoder;\ntry {\n\ttextEncoder = new TextEncoder();\n} catch (error) {}\nlet extensions, extensionClasses;\nconst hasNodeBuffer = typeof Buffer !== 'undefined';\nconst ByteArrayAllocate = hasNodeBuffer ?\n\tfunction(length) { return Buffer.allocUnsafeSlow(length); } : Uint8Array;\nconst ByteArray = hasNodeBuffer ? Buffer : Uint8Array;\nconst MAX_BUFFER_SIZE = hasNodeBuffer ? 0x100000000 : 0x7fd00000;\nlet target, keysTarget;\nlet targetView;\nlet position = 0;\nlet safeEnd;\nlet bundledStrings = null;\nconst MAX_BUNDLE_SIZE = 0x5500; // maximum characters such that the encoded bytes fits in 16 bits.\nconst hasNonLatin = /[\\u0080-\\uFFFF]/;\nexport const RECORD_SYMBOL = Symbol('record-id');\nexport class Packr extends Unpackr {\n\tconstructor(options) {\n\t\tsuper(options);\n\t\tthis.offset = 0;\n\t\tlet typeBuffer;\n\t\tlet start;\n\t\tlet hasSharedUpdate;\n\t\tlet structures;\n\t\tlet referenceMap;\n\t\tlet encodeUtf8 = ByteArray.prototype.utf8Write ? function(string, position) {\n\t\t\treturn target.utf8Write(string, position, target.byteLength - position);\n\t\t} : (textEncoder && textEncoder.encodeInto) ?\n\t\t\tfunction(string, position) {\n\t\t\t\treturn textEncoder.encodeInto(string, target.subarray(position)).written;\n\t\t\t} : false;\n\n\t\tlet packr = this;\n\t\tif (!options)\n\t\t\toptions = {};\n\t\tlet isSequential = options && options.sequential;\n\t\tlet hasSharedStructures = options.structures || options.saveStructures;\n\t\tlet maxSharedStructures = options.maxSharedStructures;\n\t\tif (maxSharedStructures == null)\n\t\t\tmaxSharedStructures = hasSharedStructures ? 32 : 0;\n\t\tif (maxSharedStructures > 8160)\n\t\t\tthrow new Error('Maximum maxSharedStructure is 8160');\n\t\tif (options.structuredClone && options.moreTypes == undefined) {\n\t\t\tthis.moreTypes = true;\n\t\t}\n\t\tlet maxOwnStructures = options.maxOwnStructures;\n\t\tif (maxOwnStructures == null)\n\t\t\tmaxOwnStructures = hasSharedStructures ? 32 : 64;\n\t\tif (!this.structures && options.useRecords != false)\n\t\t\tthis.structures = [];\n\t\t// two byte record ids for shared structures\n\t\tlet useTwoByteRecords = maxSharedStructures > 32 || (maxOwnStructures + maxSharedStructures > 64);\n\t\tlet sharedLimitId = maxSharedStructures + 0x40;\n\t\tlet maxStructureId = maxSharedStructures + maxOwnStructures + 0x40;\n\t\tif (maxStructureId > 8256) {\n\t\t\tthrow new Error('Maximum maxSharedStructure + maxOwnStructure is 8192');\n\t\t}\n\t\tlet recordIdsToRemove = [];\n\t\tlet transitionsCount = 0;\n\t\tlet serializationsSinceTransitionRebuild = 0;\n\n\t\tthis.pack = this.encode = function(value, encodeOptions) {\n\t\t\tif (!target) {\n\t\t\t\ttarget = new ByteArrayAllocate(8192);\n\t\t\t\ttargetView = target.dataView || (target.dataView = new DataView(target.buffer, 0, 8192));\n\t\t\t\tposition = 0;\n\t\t\t}\n\t\t\tsafeEnd = target.length - 10;\n\t\t\tif (safeEnd - position < 0x800) {\n\t\t\t\t// don't start too close to the end,\n\t\t\t\ttarget = new ByteArrayAllocate(target.length);\n\t\t\t\ttargetView = target.dataView || (target.dataView = new DataView(target.buffer, 0, target.length));\n\t\t\t\tsafeEnd = target.length - 10;\n\t\t\t\tposition = 0;\n\t\t\t} else\n\t\t\t\tposition = (position + 7) & 0x7ffffff8; // Word align to make any future copying of this buffer faster\n\t\t\tstart = position;\n\t\t\tif (encodeOptions & RESERVE_START_SPACE) position += (encodeOptions & 0xff);\n\t\t\treferenceMap = packr.structuredClone ? new Map() : null;\n\t\t\tif (packr.bundleStrings && typeof value !== 'string') {\n\t\t\t\tbundledStrings = [];\n\t\t\t\tbundledStrings.size = Infinity; // force a new bundle start on first string\n\t\t\t} else\n\t\t\t\tbundledStrings = null;\n\t\t\tstructures = packr.structures;\n\t\t\tif (structures) {\n\t\t\t\tif (structures.uninitialized)\n\t\t\t\t\tstructures = packr._mergeStructures(packr.getStructures());\n\t\t\t\tlet sharedLength = structures.sharedLength || 0;\n\t\t\t\tif (sharedLength > maxSharedStructures) {\n\t\t\t\t\t//if (maxSharedStructures <= 32 && structures.sharedLength > 32) // TODO: could support this, but would need to update the limit ids\n\t\t\t\t\tthrow new Error('Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to ' + structures.sharedLength);\n\t\t\t\t}\n\t\t\t\tif (!structures.transitions) {\n\t\t\t\t\t// rebuild our structure transitions\n\t\t\t\t\tstructures.transitions = Object.create(null);\n\t\t\t\t\tfor (let i = 0; i < sharedLength; i++) {\n\t\t\t\t\t\tlet keys = structures[i];\n\t\t\t\t\t\tif (!keys)\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\tlet nextTransition, transition = structures.transitions;\n\t\t\t\t\t\tfor (let j = 0, l = keys.length; j < l; j++) {\n\t\t\t\t\t\t\tlet key = keys[j];\n\t\t\t\t\t\t\tnextTransition = transition[key];\n\t\t\t\t\t\t\tif (!nextTransition) {\n\t\t\t\t\t\t\t\tnextTransition = transition[key] = Object.create(null);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttransition = nextTransition;\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttransition[RECORD_SYMBOL] = i + 0x40;\n\t\t\t\t\t}\n\t\t\t\t\tthis.lastNamedStructuresLength = sharedLength;\n\t\t\t\t}\n\t\t\t\tif (!isSequential) {\n\t\t\t\t\tstructures.nextId = sharedLength + 0x40;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (hasSharedUpdate)\n\t\t\t\thasSharedUpdate = false;\n\t\t\tlet encodingError;\n\t\t\ttry {\n\t\t\t\tif (packr._writeStruct && value && typeof value === 'object') {\n\t\t\t\t\tif (value.constructor === Object) writeStruct(value); // simple object\n\t\t\t\t\telse if (value.constructor !== Map && !Array.isArray(value) && !extensionClasses.some(extClass => value instanceof extClass)) {\n\t\t\t\t\t\t// allow user classes, if they don't need special handling (but do use toJSON if available)\n\t\t\t\t\t\twriteStruct(value.toJSON ? value.toJSON() : value);\n\t\t\t\t\t} else pack(value);\n\t\t\t\t} else\n\t\t\t\t\tpack(value);\n\t\t\t\tlet lastBundle = bundledStrings;\n\t\t\t\tif (bundledStrings)\n\t\t\t\t\twriteBundles(start, pack, 0);\n\t\t\t\tif (referenceMap && referenceMap.idsToInsert) {\n\t\t\t\t\tlet idsToInsert = referenceMap.idsToInsert.sort((a, b) => a.offset > b.offset ? 1 : -1);\n\t\t\t\t\tlet i = idsToInsert.length;\n\t\t\t\t\tlet incrementPosition = -1;\n\t\t\t\t\twhile (lastBundle && i > 0) {\n\t\t\t\t\t\tlet insertionPoint = idsToInsert[--i].offset + start;\n\t\t\t\t\t\tif (insertionPoint < (lastBundle.stringsPosition + start) && incrementPosition === -1)\n\t\t\t\t\t\t\tincrementPosition = 0;\n\t\t\t\t\t\tif (insertionPoint > (lastBundle.position + start)) {\n\t\t\t\t\t\t\tif (incrementPosition >= 0)\n\t\t\t\t\t\t\t\tincrementPosition += 6;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tif (incrementPosition >= 0) {\n\t\t\t\t\t\t\t\t// update the bundle reference now\n\t\t\t\t\t\t\t\ttargetView.setUint32(lastBundle.position + start,\n\t\t\t\t\t\t\t\t\ttargetView.getUint32(lastBundle.position + start) + incrementPosition);\n\t\t\t\t\t\t\t\tincrementPosition = -1; // reset\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tlastBundle = lastBundle.previous;\n\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (incrementPosition >= 0 && lastBundle) {\n\t\t\t\t\t\t// update the bundle reference now\n\t\t\t\t\t\ttargetView.setUint32(lastBundle.position + start,\n\t\t\t\t\t\t\ttargetView.getUint32(lastBundle.position + start) + incrementPosition);\n\t\t\t\t\t}\n\t\t\t\t\tposition += idsToInsert.length * 6;\n\t\t\t\t\tif (position > safeEnd)\n\t\t\t\t\t\tmakeRoom(position);\n\t\t\t\t\tpackr.offset = position;\n\t\t\t\t\tlet serialized = insertIds(target.subarray(start, position), idsToInsert);\n\t\t\t\t\treferenceMap = null;\n\t\t\t\t\treturn serialized;\n\t\t\t\t}\n\t\t\t\tpackr.offset = position; // update the offset so next serialization doesn't write over our buffer, but can continue writing to same buffer sequentially\n\t\t\t\tif (encodeOptions & REUSE_BUFFER_MODE) {\n\t\t\t\t\ttarget.start = start;\n\t\t\t\t\ttarget.end = position;\n\t\t\t\t\treturn target;\n\t\t\t\t}\n\t\t\t\treturn target.subarray(start, position); // position can change if we call pack again in saveStructures, so we get the buffer now\n\t\t\t} catch(error) {\n\t\t\t\tencodingError = error;\n\t\t\t\tthrow error;\n\t\t\t} finally {\n\t\t\t\tif (structures) {\n\t\t\t\t\tresetStructures();\n\t\t\t\t\tif (hasSharedUpdate && packr.saveStructures) {\n\t\t\t\t\t\tlet sharedLength = structures.sharedLength || 0;\n\t\t\t\t\t\t// we can't rely on start/end with REUSE_BUFFER_MODE since they will (probably) change when we save\n\t\t\t\t\t\tlet returnBuffer = target.subarray(start, position);\n\t\t\t\t\t\tlet newSharedData = (packr._prepareStructures || prepareStructures)(structures, packr);\n\t\t\t\t\t\tif (!encodingError) { // TODO: If there is an encoding error, should make the structures as uninitialized so they get rebuilt next time\n\t\t\t\t\t\t\tif (packr.saveStructures(newSharedData, newSharedData.isCompatible) === false) {\n\t\t\t\t\t\t\t\t// The save was declined (a concurrent writer updated the shared structures,\n\t\t\t\t\t\t\t\t// or the store transaction did not durably commit). Our in-memory\n\t\t\t\t\t\t\t\t// structures + transition trie may now reference record ids that were\n\t\t\t\t\t\t\t\t// never persisted; re-packing as-is would re-emit the same record pointing\n\t\t\t\t\t\t\t\t// at an unpersisted structure (-> \"Record id is not defined\" on decode).\n\t\t\t\t\t\t\t\t// Mark structures uninitialized so the re-pack reloads durable structures\n\t\t\t\t\t\t\t\t// via getStructures, rebuilds the transition trie, and re-mints + re-saves.\n\t\t\t\t\t\t\t\tstructures.uninitialized = true;\n\t\t\t\t\t\t\t\treturn packr.pack(value, encodeOptions);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tpackr.lastNamedStructuresLength = sharedLength;\n\t\t\t\t\t\t\t// don't keep large buffers around\n\t\t\t\t\t\t\tif (target.length > 0x40000000) target = null;\n\t\t\t\t\t\t\treturn returnBuffer;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// don't keep large buffers around, they take too much memory and cause problems (limit at 1GB)\n\t\t\t\tif (target.length > 0x40000000) target = null;\n\t\t\t\tif (encodeOptions & RESET_BUFFER_MODE)\n\t\t\t\t\tposition = start;\n\t\t\t}\n\t\t};\n\t\tconst resetStructures = () => {\n\t\t\tif (serializationsSinceTransitionRebuild < 10)\n\t\t\t\tserializationsSinceTransitionRebuild++;\n\t\t\tlet sharedLength = structures.sharedLength || 0;\n\t\t\tif (structures.length > sharedLength && !isSequential)\n\t\t\t\tstructures.length = sharedLength;\n\t\t\tif (transitionsCount > 10000) {\n\t\t\t\t// force a rebuild occasionally after a lot of transitions so it can get cleaned up\n\t\t\t\tstructures.transitions = null;\n\t\t\t\tserializationsSinceTransitionRebuild = 0;\n\t\t\t\ttransitionsCount = 0;\n\t\t\t\tif (recordIdsToRemove.length > 0)\n\t\t\t\t\trecordIdsToRemove = [];\n\t\t\t} else if (recordIdsToRemove.length > 0 && !isSequential) {\n\t\t\t\tfor (let i = 0, l = recordIdsToRemove.length; i < l; i++) {\n\t\t\t\t\trecordIdsToRemove[i][RECORD_SYMBOL] = 0;\n\t\t\t\t}\n\t\t\t\trecordIdsToRemove = [];\n\t\t\t}\n\t\t};\n\t\tconst packArray = (value) => {\n\t\t\tvar length = value.length;\n\t\t\tif (length < 0x10) {\n\t\t\t\ttarget[position++] = 0x90 | length;\n\t\t\t} else if (length < 0x10000) {\n\t\t\t\ttarget[position++] = 0xdc;\n\t\t\t\ttarget[position++] = length >> 8;\n\t\t\t\ttarget[position++] = length & 0xff;\n\t\t\t} else {\n\t\t\t\ttarget[position++] = 0xdd;\n\t\t\t\ttargetView.setUint32(position, length);\n\t\t\t\tposition += 4;\n\t\t\t}\n\t\t\tfor (let i = 0; i < length; i++) {\n\t\t\t\tpack(value[i]);\n\t\t\t}\n\t\t};\n\t\tconst pack = (value) => {\n\t\t\tif (position > safeEnd)\n\t\t\t\ttarget = makeRoom(position);\n\n\t\t\tvar type = typeof value;\n\t\t\tvar length;\n\t\t\tif (type === 'string') {\n\t\t\t\tlet strLength = value.length;\n\t\t\t\tif (bundledStrings && strLength >= 4 && strLength < 0x1000) {\n\t\t\t\t\tif ((bundledStrings.size += strLength) > MAX_BUNDLE_SIZE) {\n\t\t\t\t\t\tlet extStart;\n\t\t\t\t\t\tlet maxBytes = (bundledStrings[0] ? bundledStrings[0].length * 3 + bundledStrings[1].length : 0) + 10;\n\t\t\t\t\t\tif (position + maxBytes > safeEnd)\n\t\t\t\t\t\t\ttarget = makeRoom(position + maxBytes);\n\t\t\t\t\t\tlet lastBundle;\n\t\t\t\t\t\tif (bundledStrings.position) { // here we use the 0x62 extension to write the last bundle and reserve space for the reference pointer to the next/current bundle\n\t\t\t\t\t\t\tlastBundle = bundledStrings;\n\t\t\t\t\t\t\ttarget[position] = 0xc8; // ext 16\n\t\t\t\t\t\t\tposition += 3; // reserve for the writing bundle size\n\t\t\t\t\t\t\ttarget[position++] = 0x62; // 'b'\n\t\t\t\t\t\t\textStart = position - start;\n\t\t\t\t\t\t\tposition += 4; // reserve for writing bundle reference\n\t\t\t\t\t\t\twriteBundles(start, pack, 0); // write the last bundles\n\t\t\t\t\t\t\ttargetView.setUint16(extStart + start - 3, position - start - extStart);\n\t\t\t\t\t\t} else { // here we use the 0x62 extension just to reserve the space for the reference pointer to the bundle (will be updated once the bundle is written)\n\t\t\t\t\t\t\ttarget[position++] = 0xd6; // fixext 4\n\t\t\t\t\t\t\ttarget[position++] = 0x62; // 'b'\n\t\t\t\t\t\t\textStart = position - start;\n\t\t\t\t\t\t\tposition += 4; // reserve for writing bundle reference\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbundledStrings = ['', '']; // create new ones\n\t\t\t\t\t\tbundledStrings.previous = lastBundle;\n\t\t\t\t\t\tbundledStrings.size = 0;\n\t\t\t\t\t\tbundledStrings.position = extStart;\n\t\t\t\t\t}\n\t\t\t\t\tlet twoByte = hasNonLatin.test(value);\n\t\t\t\t\tbundledStrings[twoByte ? 0 : 1] += value;\n\t\t\t\t\ttarget[position++] = 0xc1;\n\t\t\t\t\tpack(twoByte ? -strLength : strLength);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tlet headerSize;\n\t\t\t\t// first we estimate the header size, so we can write to the correct location\n\t\t\t\tif (strLength < 0x20) {\n\t\t\t\t\theaderSize = 1;\n\t\t\t\t} else if (strLength < 0x100) {\n\t\t\t\t\theaderSize = 2;\n\t\t\t\t} else if (strLength < 0x10000) {\n\t\t\t\t\theaderSize = 3;\n\t\t\t\t} else {\n\t\t\t\t\theaderSize = 5;\n\t\t\t\t}\n\t\t\t\tlet maxBytes = strLength * 3;\n\t\t\t\tif (position + maxBytes > safeEnd)\n\t\t\t\t\ttarget = makeRoom(position + maxBytes);\n\n\t\t\t\tif (strLength < 0x40 || !encodeUtf8) {\n\t\t\t\t\tlet i, c1, c2, strPosition = position + headerSize;\n\t\t\t\t\tfor (i = 0; i < strLength; i++) {\n\t\t\t\t\t\tc1 = value.charCodeAt(i);\n\t\t\t\t\t\tif (c1 < 0x80) {\n\t\t\t\t\t\t\ttarget[strPosition++] = c1;\n\t\t\t\t\t\t} else if (c1 < 0x800) {\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 >> 6 | 0xc0;\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 & 0x3f | 0x80;\n\t\t\t\t\t\t} else if (\n\t\t\t\t\t\t\t(c1 & 0xfc00) === 0xd800 &&\n\t\t\t\t\t\t\t((c2 = value.charCodeAt(i + 1)) & 0xfc00) === 0xdc00\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tc1 = 0x10000 + ((c1 & 0x03ff) << 10) + (c2 & 0x03ff);\n\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 >> 18 | 0xf0;\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 >> 12 & 0x3f | 0x80;\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 >> 6 & 0x3f | 0x80;\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 & 0x3f | 0x80;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 >> 12 | 0xe0;\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 >> 6 & 0x3f | 0x80;\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 & 0x3f | 0x80;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tlength = strPosition - position - headerSize;\n\t\t\t\t} else {\n\t\t\t\t\tlength = encodeUtf8(value, position + headerSize);\n\t\t\t\t}\n\n\t\t\t\tif (length < 0x20) {\n\t\t\t\t\ttarget[position++] = 0xa0 | length;\n\t\t\t\t} else if (length < 0x100) {\n\t\t\t\t\tif (headerSize < 2) {\n\t\t\t\t\t\ttarget.copyWithin(position + 2, position + 1, position + 1 + length);\n\t\t\t\t\t}\n\t\t\t\t\ttarget[position++] = 0xd9;\n\t\t\t\t\ttarget[position++] = length;\n\t\t\t\t} else if (length < 0x10000) {\n\t\t\t\t\tif (headerSize < 3) {\n\t\t\t\t\t\ttarget.copyWithin(position + 3, position + 2, position + 2 + length);\n\t\t\t\t\t}\n\t\t\t\t\ttarget[position++] = 0xda;\n\t\t\t\t\ttarget[position++] = length >> 8;\n\t\t\t\t\ttarget[position++] = length & 0xff;\n\t\t\t\t} else {\n\t\t\t\t\tif (headerSize < 5) {\n\t\t\t\t\t\ttarget.copyWithin(position + 5, position + 3, position + 3 + length);\n\t\t\t\t\t}\n\t\t\t\t\ttarget[position++] = 0xdb;\n\t\t\t\t\ttargetView.setUint32(position, length);\n\t\t\t\t\tposition += 4;\n\t\t\t\t}\n\t\t\t\tposition += length;\n\t\t\t} else if (type === 'number') {\n\t\t\t\tif (value >>> 0 === value) {// positive integer, 32-bit or less\n\t\t\t\t\t// positive uint\n\t\t\t\t\tif (value < 0x20 || (value < 0x80 && this.useRecords === false) || (value < 0x40 && !this._writeStruct)) {\n\t\t\t\t\t\ttarget[position++] = value;\n\t\t\t\t\t} else if (value < 0x100) {\n\t\t\t\t\t\ttarget[position++] = 0xcc;\n\t\t\t\t\t\ttarget[position++] = value;\n\t\t\t\t\t} else if (value < 0x10000) {\n\t\t\t\t\t\ttarget[position++] = 0xcd;\n\t\t\t\t\t\ttarget[position++] = value >> 8;\n\t\t\t\t\t\ttarget[position++] = value & 0xff;\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttarget[position++] = 0xce;\n\t\t\t\t\t\ttargetView.setUint32(position, value);\n\t\t\t\t\t\tposition += 4;\n\t\t\t\t\t}\n\t\t\t\t} else if (value >> 0 === value) { // negative integer\n\t\t\t\t\tif (value >= -0x20) {\n\t\t\t\t\t\ttarget[position++] = 0x100 + value;\n\t\t\t\t\t} else if (value >= -0x80) {\n\t\t\t\t\t\ttarget[position++] = 0xd0;\n\t\t\t\t\t\ttarget[position++] = value + 0x100;\n\t\t\t\t\t} else if (value >= -0x8000) {\n\t\t\t\t\t\ttarget[position++] = 0xd1;\n\t\t\t\t\t\ttargetView.setInt16(position, value);\n\t\t\t\t\t\tposition += 2;\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttarget[position++] = 0xd2;\n\t\t\t\t\t\ttargetView.setInt32(position, value);\n\t\t\t\t\t\tposition += 4;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tlet useFloat32;\n\t\t\t\t\tif ((useFloat32 = this.useFloat32) > 0 && value < 0x100000000 && value >= -0x80000000) {\n\t\t\t\t\t\ttarget[position++] = 0xca;\n\t\t\t\t\t\ttargetView.setFloat32(position, value);\n\t\t\t\t\t\tlet xShifted;\n\t\t\t\t\t\tif (useFloat32 < 4 ||\n\t\t\t\t\t\t\t\t// this checks for rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved\n\t\t\t\t\t\t\t\t((xShifted = value * mult10[((target[position] & 0x7f) << 1) | (target[position + 1] >> 7)]) >> 0) === xShifted) {\n\t\t\t\t\t\t\tposition += 4;\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t} else\n\t\t\t\t\t\t\tposition--; // move back into position for writing a double\n\t\t\t\t\t}\n\t\t\t\t\ttarget[position++] = 0xcb;\n\t\t\t\t\ttargetView.setFloat64(position, value);\n\t\t\t\t\tposition += 8;\n\t\t\t\t}\n\t\t\t} else if (type === 'object' || type === 'function') {\n\t\t\t\tif (!value)\n\t\t\t\t\ttarget[position++] = 0xc0;\n\t\t\t\telse {\n\t\t\t\t\tif (referenceMap) {\n\t\t\t\t\t\tlet referee = referenceMap.get(value);\n\t\t\t\t\t\tif (referee) {\n\t\t\t\t\t\t\tif (!referee.id) {\n\t\t\t\t\t\t\t\tlet idsToInsert = referenceMap.idsToInsert || (referenceMap.idsToInsert = []);\n\t\t\t\t\t\t\t\treferee.id = idsToInsert.push(referee);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttarget[position++] = 0xd6; // fixext 4\n\t\t\t\t\t\t\ttarget[position++] = 0x70; // \"p\" for pointer\n\t\t\t\t\t\t\ttargetView.setUint32(position, referee.id);\n\t\t\t\t\t\t\tposition += 4;\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t} else\n\t\t\t\t\t\t\treferenceMap.set(value, { offset: position - start });\n\t\t\t\t\t}\n\t\t\t\t\tlet constructor = value.constructor;\n\t\t\t\t\tif (constructor === Object) {\n\t\t\t\t\t\twriteObject(value);\n\t\t\t\t\t} else if (constructor === Array) {\n\t\t\t\t\t\tpackArray(value);\n\t\t\t\t\t} else if (constructor === Map) {\n\t\t\t\t\t\tif (this.mapAsEmptyObject) target[position++] = 0x80;\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tlength = value.size;\n\t\t\t\t\t\t\tif (length < 0x10) {\n\t\t\t\t\t\t\t\ttarget[position++] = 0x80 | length;\n\t\t\t\t\t\t\t} else if (length < 0x10000) {\n\t\t\t\t\t\t\t\ttarget[position++] = 0xde;\n\t\t\t\t\t\t\t\ttarget[position++] = length >> 8;\n\t\t\t\t\t\t\t\ttarget[position++] = length & 0xff;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\ttarget[position++] = 0xdf;\n\t\t\t\t\t\t\t\ttargetView.setUint32(position, length);\n\t\t\t\t\t\t\t\tposition += 4;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tfor (let [key, entryValue] of value) {\n\t\t\t\t\t\t\t\tpack(key);\n\t\t\t\t\t\t\t\tpack(entryValue);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfor (let i = 0, l = extensions.length; i < l; i++) {\n\t\t\t\t\t\t\tlet extensionClass = extensionClasses[i];\n\t\t\t\t\t\t\tif (value instanceof extensionClass) {\n\t\t\t\t\t\t\t\tlet extension = extensions[i];\n\t\t\t\t\t\t\t\tif (extension.write) {\n\t\t\t\t\t\t\t\t\tif (extension.type) {\n\t\t\t\t\t\t\t\t\t\ttarget[position++] = 0xd4; // one byte \"tag\" extension\n\t\t\t\t\t\t\t\t\t\ttarget[position++] = extension.type;\n\t\t\t\t\t\t\t\t\t\ttarget[position++] = 0;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tlet writeResult = extension.write.call(this, value);\n\t\t\t\t\t\t\t\t\tif (writeResult === value) { // avoid infinite recursion\n\t\t\t\t\t\t\t\t\t\tif (Array.isArray(value)) {\n\t\t\t\t\t\t\t\t\t\t\tpackArray(value);\n\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\twriteObject(value);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tpack(writeResult);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tlet currentTarget = target;\n\t\t\t\t\t\t\t\tlet currentTargetView = targetView;\n\t\t\t\t\t\t\t\tlet currentPosition = position;\n\t\t\t\t\t\t\t\ttarget = null;\n\t\t\t\t\t\t\t\tlet result;\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tresult = extension.pack.call(this, value, (size) => {\n\t\t\t\t\t\t\t\t\t\t// restore target and use it\n\t\t\t\t\t\t\t\t\t\ttarget = currentTarget;\n\t\t\t\t\t\t\t\t\t\tcurrentTarget = null;\n\t\t\t\t\t\t\t\t\t\tposition += size;\n\t\t\t\t\t\t\t\t\t\tif (position > safeEnd)\n\t\t\t\t\t\t\t\t\t\t\tmakeRoom(position);\n\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\ttarget, targetView, position: position - size\n\t\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t\t}, pack);\n\t\t\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\t\t\t// restore current target information (unless already restored)\n\t\t\t\t\t\t\t\t\tif (currentTarget) {\n\t\t\t\t\t\t\t\t\t\ttarget = currentTarget;\n\t\t\t\t\t\t\t\t\t\ttargetView = currentTargetView;\n\t\t\t\t\t\t\t\t\t\tposition = currentPosition;\n\t\t\t\t\t\t\t\t\t\tsafeEnd = target.length - 10;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (result) {\n\t\t\t\t\t\t\t\t\tif (result.length + position > safeEnd)\n\t\t\t\t\t\t\t\t\t\tmakeRoom(result.length + position);\n\t\t\t\t\t\t\t\t\tposition = writeExtensionData(result, target, position, extension.type);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// check isArray after extensions, because extensions can extend Array\n\t\t\t\t\t\tif (Array.isArray(value)) {\n\t\t\t\t\t\t\tpackArray(value);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// use this as an alternate mechanism for expressing how to serialize\n\t\t\t\t\t\t\tif (value.toJSON) {\n\t\t\t\t\t\t\t\tconst json = value.toJSON();\n\t\t\t\t\t\t\t\t// if for some reason value.toJSON returns itself it'll loop forever\n\t\t\t\t\t\t\t\tif (json !== value)\n\t\t\t\t\t\t\t\t\treturn pack(json);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// if there is a writeFunction, use it, otherwise just encode as undefined\n\t\t\t\t\t\t\tif (type === 'function')\n\t\t\t\t\t\t\t\treturn pack(this.writeFunction && this.writeFunction(value));\n\n\t\t\t\t\t\t\t// no extension found, write as plain object\n\t\t\t\t\t\t\twriteObject(value);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (type === 'boolean') {\n\t\t\t\ttarget[position++] = value ? 0xc3 : 0xc2;\n\t\t\t} else if (type === 'bigint') {\n\t\t\t\tif (value < 0x8000000000000000 && value >= -0x8000000000000000) {\n\t\t\t\t\t// use a signed int as long as it fits\n\t\t\t\t\ttarget[position++] = 0xd3;\n\t\t\t\t\ttargetView.setBigInt64(position, value);\n\t\t\t\t} else if (value < 0x10000000000000000 && value > 0) {\n\t\t\t\t\t// if we can fit an unsigned int, use that\n\t\t\t\t\ttarget[position++] = 0xcf;\n\t\t\t\t\ttargetView.setBigUint64(position, value);\n\t\t\t\t} else {\n\t\t\t\t\t// overflow\n\t\t\t\t\tif (this.largeBigIntToFloat) {\n\t\t\t\t\t\ttarget[position++] = 0xcb;\n\t\t\t\t\t\ttargetView.setFloat64(position, Number(value));\n\t\t\t\t\t} else if (this.largeBigIntToString) {\n\t\t\t\t\t\treturn pack(value.toString());\n\t\t\t\t\t} else if (this.useBigIntExtension || this.moreTypes) {\n\t\t\t\t\t\tlet empty = value < 0 ? BigInt(-1) : BigInt(0);\n\n\t\t\t\t\t\tlet array;\n\t\t\t\t\t\tif (value >> BigInt(0x10000) === empty) {\n\t\t\t\t\t\t\tlet mask = BigInt(0x10000000000000000) - BigInt(1); // literal would overflow\n\t\t\t\t\t\t\tlet chunks = [];\n\t\t\t\t\t\t\twhile (true) {\n\t\t\t\t\t\t\t\tchunks.push(value & mask);\n\t\t\t\t\t\t\t\tif ((value >> BigInt(63)) === empty) break;\n\t\t\t\t\t\t\t\tvalue >>= BigInt(64);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tarray = new Uint8Array(new BigUint64Array(chunks).buffer);\n\t\t\t\t\t\t\tarray.reverse();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tlet invert = value < 0;\n\t\t\t\t\t\t\tlet string = (invert ? ~value : value).toString(16);\n\t\t\t\t\t\t\tif (string.length % 2) {\n\t\t\t\t\t\t\t\tstring = '0' + string;\n\t\t\t\t\t\t\t} else if (parseInt(string.charAt(0), 16) >= 8) {\n\t\t\t\t\t\t\t\tstring = '00' + string;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (hasNodeBuffer) {\n\t\t\t\t\t\t\t\tarray = Buffer.from(string, 'hex');\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tarray = new Uint8Array(string.length / 2);\n\t\t\t\t\t\t\t\tfor (let i = 0; i < array.length; i++) {\n\t\t\t\t\t\t\t\t\tarray[i] = parseInt(string.slice(i * 2, i * 2 + 2), 16);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (invert) {\n\t\t\t\t\t\t\t\tfor (let i = 0; i < array.length; i++) array[i] = ~array[i];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (array.length + position > safeEnd)\n\t\t\t\t\t\t\tmakeRoom(array.length + position);\n\t\t\t\t\t\tposition = writeExtensionData(array, target, position, 0x42);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthrow new RangeError(value + ' was too large to fit in MessagePack 64-bit integer format, use' +\n\t\t\t\t\t\t\t' useBigIntExtension, or set largeBigIntToFloat to convert to float-64, or set' +\n\t\t\t\t\t\t\t' largeBigIntToString to convert to string');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tposition += 8;\n\t\t\t} else if (type === 'undefined') {\n\t\t\t\tif (this.encodeUndefinedAsNil)\n\t\t\t\t\ttarget[position++] = 0xc0;\n\t\t\t\telse {\n\t\t\t\t\ttarget[position++] = 0xd4; // a number of implementations use fixext1 with type 0, data 0 to denote undefined, so we follow suite\n\t\t\t\t\ttarget[position++] = 0;\n\t\t\t\t\ttarget[position++] = 0;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthrow new Error('Unknown type: ' + type);\n\t\t\t}\n\t\t};\n\n\t\tconst writePlainObject = (this.variableMapSize || this.coercibleKeyAsNumber || this.skipValues) ? (object) => {\n\t\t\t// this method is slightly slower, but generates \"preferred serialization\" (optimally small for smaller objects)\n\t\t\tlet keys;\n\t\t\tif (this.skipValues) {\n\t\t\t\tkeys = [];\n\t\t\t\tfor (let key in object) {\n\t\t\t\t\tif ((typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) &&\n\t\t\t\t\t\t!this.skipValues.includes(object[key]))\n\t\t\t\t\t\tkeys.push(key);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tkeys = Object.keys(object);\n\t\t\t}\n\t\t\tlet length = keys.length;\n\t\t\tif (length < 0x10) {\n\t\t\t\ttarget[position++] = 0x80 | length;\n\t\t\t} else if (length < 0x10000) {\n\t\t\t\ttarget[position++] = 0xde;\n\t\t\t\ttarget[position++] = length >> 8;\n\t\t\t\ttarget[position++] = length & 0xff;\n\t\t\t} else {\n\t\t\t\ttarget[position++] = 0xdf;\n\t\t\t\ttargetView.setUint32(position, length);\n\t\t\t\tposition += 4;\n\t\t\t}\n\t\t\tlet key;\n\t\t\tif (this.coercibleKeyAsNumber) {\n\t\t\t\tfor (let i = 0; i < length; i++) {\n\t\t\t\t\tkey = keys[i];\n\t\t\t\t\tlet num = Number(key);\n\t\t\t\t\tpack(isNaN(num) ? key : num);\n\t\t\t\t\tpack(object[key]);\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\tfor (let i = 0; i < length; i++) {\n\t\t\t\t\tpack(key = keys[i]);\n\t\t\t\t\tpack(object[key]);\n\t\t\t\t}\n\t\t\t}\n\t\t} :\n\t\t(object) => {\n\t\t\ttarget[position++] = 0xde; // always using map 16, so we can preallocate and set the length afterwards\n\t\t\tlet objectOffset = position - start;\n\t\t\tposition += 2;\n\t\t\tlet size = 0;\n\t\t\tfor (let key in object) {\n\t\t\t\tif (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {\n\t\t\t\t\tpack(key);\n\t\t\t\t\tpack(object[key]);\n\t\t\t\t\tsize++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (size > 0xffff) {\n\t\t\t\tthrow new Error('Object is too large to serialize with fast 16-bit map size,' +\n\t\t\t\t' use the \"variableMapSize\" option to serialize this object');\n\t\t\t}\n\t\t\ttarget[objectOffset++ + start] = size >> 8;\n\t\t\ttarget[objectOffset + start] = size & 0xff;\n\t\t};\n\n\t\tconst writeRecord = this.useRecords === false ? writePlainObject :\n\t\t(options.progressiveRecords && !useTwoByteRecords) ?  // this is about 2% faster for highly stable structures, since it only requires one for-in loop (but much more expensive when new structure needs to be written)\n\t\t(object) => {\n\t\t\tlet nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null));\n\t\t\tlet objectOffset = position++ - start;\n\t\t\tlet wroteKeys;\n\t\t\tfor (let key in object) {\n\t\t\t\tif (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {\n\t\t\t\t\tnextTransition = transition[key];\n\t\t\t\t\tif (nextTransition)\n\t\t\t\t\t\ttransition = nextTransition;\n\t\t\t\t\telse {\n\t\t\t\t\t\t// record doesn't exist, create full new record and insert it\n\t\t\t\t\t\tlet keys = Object.keys(object);\n\t\t\t\t\t\tlet lastTransition = transition;\n\t\t\t\t\t\ttransition = structures.transitions;\n\t\t\t\t\t\tlet newTransitions = 0;\n\t\t\t\t\t\tfor (let i = 0, l = keys.length; i < l; i++) {\n\t\t\t\t\t\t\tlet key = keys[i];\n\t\t\t\t\t\t\tnextTransition = transition[key];\n\t\t\t\t\t\t\tif (!nextTransition) {\n\t\t\t\t\t\t\t\tnextTransition = transition[key] = Object.create(null);\n\t\t\t\t\t\t\t\tnewTransitions++;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttransition = nextTransition;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (objectOffset + start + 1 == position) {\n\t\t\t\t\t\t\t// first key, so we don't need to insert, we can just write record directly\n\t\t\t\t\t\t\tposition--;\n\t\t\t\t\t\t\tnewRecord(transition, keys, newTransitions);\n\t\t\t\t\t\t} else // otherwise we need to insert the record, moving existing data after the record\n\t\t\t\t\t\t\tinsertNewRecord(transition, keys, objectOffset, newTransitions);\n\t\t\t\t\t\twroteKeys = true;\n\t\t\t\t\t\ttransition = lastTransition[key];\n\t\t\t\t\t}\n\t\t\t\t\tpack(object[key]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!wroteKeys) {\n\t\t\t\tlet recordId = transition[RECORD_SYMBOL];\n\t\t\t\tif (recordId)\n\t\t\t\t\ttarget[objectOffset + start] = recordId;\n\t\t\t\telse\n\t\t\t\t\tinsertNewRecord(transition, Object.keys(object), objectOffset, 0);\n\t\t\t}\n\t\t} :\n\t\t(object) => {\n\t\t\tlet nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null));\n\t\t\tlet newTransitions = 0;\n\t\t\tfor (let key in object) if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {\n\t\t\t\tnextTransition = transition[key];\n\t\t\t\tif (!nextTransition) {\n\t\t\t\t\tnextTransition = transition[key] = Object.create(null);\n\t\t\t\t\tnewTransitions++;\n\t\t\t\t}\n\t\t\t\ttransition = nextTransition;\n\t\t\t}\n\t\t\tlet recordId = transition[RECORD_SYMBOL];\n\t\t\tif (recordId) {\n\t\t\t\tif (recordId >= 0x60 && useTwoByteRecords) {\n\t\t\t\t\ttarget[position++] = ((recordId -= 0x60) & 0x1f) + 0x60;\n\t\t\t\t\ttarget[position++] = recordId >> 5;\n\t\t\t\t} else\n\t\t\t\t\ttarget[position++] = recordId;\n\t\t\t} else {\n\t\t\t\tnewRecord(transition, transition.__keys__ || Object.keys(object), newTransitions);\n\t\t\t}\n\t\t\t// now write the values\n\t\t\tfor (let key in object)\n\t\t\t\tif (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {\n\t\t\t\t\tpack(object[key]);\n\t\t\t\t}\n\t\t};\n\n\t\t// create reference to useRecords if useRecords is a function\n\t\tconst checkUseRecords = typeof this.useRecords == 'function' && this.useRecords;\n\n\t\tconst writeObject = checkUseRecords ? (object) => {\n\t\t\tcheckUseRecords(object) ? writeRecord(object) : writePlainObject(object);\n\t\t} : writeRecord;\n\n\t\tconst writeStruct = (object) => {\n\t\t\tlet newPosition = packr._writeStruct(object, target, start, position, structures, makeRoom, (value, newPosition, notifySharedUpdate) => {\n\t\t\t\tif (notifySharedUpdate)\n\t\t\t\t\treturn hasSharedUpdate = true;\n\t\t\t\tposition = newPosition;\n\t\t\t\tlet startTarget = target;\n\t\t\t\tpack(value);\n\t\t\t\tresetStructures();\n\t\t\t\tif (startTarget !== target) {\n\t\t\t\t\treturn { position, targetView, target }; // indicate the buffer was re-allocated\n\t\t\t\t}\n\t\t\t\treturn position;\n\t\t\t});\n\t\t\tif (newPosition === 0) // bail and go to a msgpack object\n\t\t\t\treturn writeObject(object);\n\t\t\tposition = newPosition;\n\t\t};\n\n\t\tconst makeRoom = (end) => {\n\t\t\tlet newSize;\n\t\t\tif (end > 0x1000000) {\n\t\t\t\t// special handling for really large buffers\n\t\t\t\tif ((end - start) > MAX_BUFFER_SIZE)\n\t\t\t\t\tthrow new Error('Packed buffer would be larger than maximum buffer size');\n\t\t\t\tnewSize = Math.min(MAX_BUFFER_SIZE,\n\t\t\t\t\tMath.round(Math.max((end - start) * (end > 0x4000000 ? 1.25 : 2), 0x400000) / 0x1000) * 0x1000);\n\t\t\t} else // faster handling for smaller buffers\n\t\t\t\tnewSize = ((Math.max((end - start) << 2, target.length - 1) >> 12) + 1) << 12;\n\t\t\tlet newBuffer = new ByteArrayAllocate(newSize);\n\t\t\ttargetView = newBuffer.dataView || (newBuffer.dataView = new DataView(newBuffer.buffer, 0, newSize));\n\t\t\tend = Math.min(end, target.length);\n\t\t\tif (target.copy)\n\t\t\t\ttarget.copy(newBuffer, 0, start, end);\n\t\t\telse\n\t\t\t\tnewBuffer.set(target.slice(start, end));\n\t\t\tposition -= start;\n\t\t\tstart = 0;\n\t\t\tsafeEnd = newBuffer.length - 10;\n\t\t\treturn target = newBuffer;\n\t\t};\n\t\tconst newRecord = (transition, keys, newTransitions) => {\n\t\t\tlet recordId = structures.nextId;\n\t\t\tif (!recordId)\n\t\t\t\trecordId = 0x40;\n\t\t\tif (recordId < sharedLimitId && this.shouldShareStructure && !this.shouldShareStructure(keys)) {\n\t\t\t\trecordId = structures.nextOwnId;\n\t\t\t\tif (!(recordId < maxStructureId))\n\t\t\t\t\trecordId = sharedLimitId;\n\t\t\t\tstructures.nextOwnId = recordId + 1;\n\t\t\t} else {\n\t\t\t\tif (recordId >= maxStructureId)// cycle back around\n\t\t\t\t\trecordId = sharedLimitId;\n\t\t\t\tstructures.nextId = recordId + 1;\n\t\t\t}\n\t\t\tlet highByte = keys.highByte = recordId >= 0x60 && useTwoByteRecords ? (recordId - 0x60) >> 5 : -1;\n\t\t\ttransition[RECORD_SYMBOL] = recordId;\n\t\t\ttransition.__keys__ = keys;\n\t\t\tstructures[recordId - 0x40] = keys;\n\n\t\t\tif (recordId < sharedLimitId) {\n\t\t\t\tkeys.isShared = true;\n\t\t\t\tstructures.sharedLength = recordId - 0x3f;\n\t\t\t\thasSharedUpdate = true;\n\t\t\t\tif (highByte >= 0) {\n\t\t\t\t\ttarget[position++] = (recordId & 0x1f) + 0x60;\n\t\t\t\t\ttarget[position++] = highByte;\n\t\t\t\t} else {\n\t\t\t\t\ttarget[position++] = recordId;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (highByte >= 0) {\n\t\t\t\t\ttarget[position++] = 0xd5; // fixext 2\n\t\t\t\t\ttarget[position++] = 0x72; // \"r\" record defintion extension type\n\t\t\t\t\ttarget[position++] = (recordId & 0x1f) + 0x60;\n\t\t\t\t\ttarget[position++] = highByte;\n\t\t\t\t} else {\n\t\t\t\t\ttarget[position++] = 0xd4; // fixext 1\n\t\t\t\t\ttarget[position++] = 0x72; // \"r\" record defintion extension type\n\t\t\t\t\ttarget[position++] = recordId;\n\t\t\t\t}\n\n\t\t\t\tif (newTransitions)\n\t\t\t\t\ttransitionsCount += serializationsSinceTransitionRebuild * newTransitions;\n\t\t\t\t// record the removal of the id, we can maintain our shared structure\n\t\t\t\tif (recordIdsToRemove.length >= maxOwnStructures)\n\t\t\t\t\trecordIdsToRemove.shift()[RECORD_SYMBOL] = 0; // we are cycling back through, and have to remove old ones\n\t\t\t\trecordIdsToRemove.push(transition);\n\t\t\t\tpack(keys);\n\t\t\t}\n\t\t};\n\t\tconst insertNewRecord = (transition, keys, insertionOffset, newTransitions) => {\n\t\t\tlet mainTarget = target;\n\t\t\tlet mainPosition = position;\n\t\t\tlet mainSafeEnd = safeEnd;\n\t\t\tlet mainStart = start;\n\t\t\ttarget = keysTarget;\n\t\t\tposition = 0;\n\t\t\tstart = 0;\n\t\t\tif (!target)\n\t\t\t\tkeysTarget = target = new ByteArrayAllocate(8192);\n\t\t\tsafeEnd = target.length - 10;\n\t\t\tnewRecord(transition, keys, newTransitions);\n\t\t\tkeysTarget = target;\n\t\t\tlet keysPosition = position;\n\t\t\ttarget = mainTarget;\n\t\t\tposition = mainPosition;\n\t\t\tsafeEnd = mainSafeEnd;\n\t\t\tstart = mainStart;\n\t\t\tif (keysPosition > 1) {\n\t\t\t\tlet newEnd = position + keysPosition - 1;\n\t\t\t\tif (newEnd > safeEnd)\n\t\t\t\t\tmakeRoom(newEnd);\n\t\t\t\tlet insertionPosition = insertionOffset + start;\n\t\t\t\ttarget.copyWithin(insertionPosition + keysPosition, insertionPosition + 1, position);\n\t\t\t\ttarget.set(keysTarget.slice(0, keysPosition), insertionPosition);\n\t\t\t\tposition = newEnd;\n\t\t\t} else {\n\t\t\t\ttarget[insertionOffset + start] = keysTarget[0];\n\t\t\t}\n\t\t};\n\t}\n\tuseBuffer(buffer) {\n\t\t// this means we are finished using our own buffer and we can write over it safely\n\t\ttarget = buffer;\n\t\ttarget.dataView || (target.dataView = new DataView(target.buffer, target.byteOffset, target.byteLength));\n\t\ttargetView = target.dataView;\n\t\tposition = 0;\n\t}\n\tset position (value) {\n\t\tposition = value;\n\t}\n\tget position() {\n\t\treturn position;\n\t}\n\tclearSharedData() {\n\t\tif (this.structures)\n\t\t\tthis.structures = [];\n\t\tif (this.typedStructs)\n\t\t\tthis.typedStructs = [];\n\t}\n}\n\nextensionClasses = [ Date, Set, Error, RegExp, ArrayBuffer, Object.getPrototypeOf(Uint8Array.prototype).constructor /*TypedArray*/, DataView, C1Type ];\nextensions = [{\n\tpack(date, allocateForWrite, pack) {\n\t\tlet seconds = date.getTime() / 1000;\n\t\tif ((this.useTimestamp32 || date.getMilliseconds() === 0) && seconds >= 0 && seconds < 0x100000000) {\n\t\t\t// Timestamp 32\n\t\t\tlet { target, targetView, position} = allocateForWrite(6);\n\t\t\ttarget[position++] = 0xd6;\n\t\t\ttarget[position++] = 0xff;\n\t\t\ttargetView.setUint32(position, seconds);\n\t\t} else if (seconds > 0 && seconds < 0x100000000) {\n\t\t\t// Timestamp 64\n\t\t\tlet { target, targetView, position} = allocateForWrite(10);\n\t\t\ttarget[position++] = 0xd7;\n\t\t\ttarget[position++] = 0xff;\n\t\t\ttargetView.setUint32(position, date.getMilliseconds() * 4000000 + ((seconds / 1000 / 0x100000000) >> 0));\n\t\t\ttargetView.setUint32(position + 4, seconds);\n\t\t} else if (isNaN(seconds)) {\n\t\t\tif (this.onInvalidDate) {\n\t\t\t\tallocateForWrite(0);\n\t\t\t\treturn pack(this.onInvalidDate());\n\t\t\t}\n\t\t\t// Intentionally invalid timestamp\n\t\t\tlet { target, targetView, position} = allocateForWrite(3);\n\t\t\ttarget[position++] = 0xd4;\n\t\t\ttarget[position++] = 0xff;\n\t\t\ttarget[position++] = 0xff;\n\t\t} else {\n\t\t\t// Timestamp 96\n\t\t\tlet { target, targetView, position} = allocateForWrite(15);\n\t\t\ttarget[position++] = 0xc7;\n\t\t\ttarget[position++] = 12;\n\t\t\ttarget[position++] = 0xff;\n\t\t\ttargetView.setUint32(position, date.getMilliseconds() * 1000000);\n\t\t\ttargetView.setBigInt64(position + 4, BigInt(Math.floor(seconds)));\n\t\t}\n\t}\n}, {\n\tpack(set, allocateForWrite, pack) {\n\t\tif (this.setAsEmptyObject) {\n\t\t\tallocateForWrite(0);\n\t\t\treturn pack({});\n\t\t}\n\t\tlet array = Array.from(set);\n\t\tlet { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);\n\t\tif (this.moreTypes) {\n\t\t\ttarget[position++] = 0xd4;\n\t\t\ttarget[position++] = 0x73; // 's' for Set\n\t\t\ttarget[position++] = 0;\n\t\t}\n\t\tpack(array);\n\t}\n}, {\n\tpack(error, allocateForWrite, pack) {\n\t\tlet { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);\n\t\tif (this.moreTypes) {\n\t\t\ttarget[position++] = 0xd4;\n\t\t\ttarget[position++] = 0x65; // 'e' for error\n\t\t\ttarget[position++] = 0;\n\t\t}\n\t\tpack([ error.name, error.message, error.cause ]);\n\t}\n}, {\n\tpack(regex, allocateForWrite, pack) {\n\t\tlet { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);\n\t\tif (this.moreTypes) {\n\t\t\ttarget[position++] = 0xd4;\n\t\t\ttarget[position++] = 0x78; // 'x' for regeXp\n\t\t\ttarget[position++] = 0;\n\t\t}\n\t\tpack([ regex.source, regex.flags ]);\n\t}\n}, {\n\tpack(arrayBuffer, allocateForWrite) {\n\t\tif (this.moreTypes)\n\t\t\twriteExtBuffer(arrayBuffer, 0x10, allocateForWrite);\n\t\telse\n\t\t\twriteBuffer(hasNodeBuffer ? Buffer.from(arrayBuffer) : new Uint8Array(arrayBuffer), allocateForWrite);\n\t}\n}, {\n\tpack(typedArray, allocateForWrite) {\n\t\tlet constructor = typedArray.constructor;\n\t\tif (constructor !== ByteArray && this.moreTypes)\n\t\t\twriteExtBuffer(typedArray, typedArrays.indexOf(constructor.name), allocateForWrite);\n\t\telse\n\t\t\twriteBuffer(typedArray, allocateForWrite);\n\t}\n}, {\n\tpack(arrayBuffer, allocateForWrite) {\n\t\tif (this.moreTypes)\n\t\t\twriteExtBuffer(arrayBuffer, 0x11, allocateForWrite);\n\t\telse\n\t\t\twriteBuffer(hasNodeBuffer ? Buffer.from(arrayBuffer) : new Uint8Array(arrayBuffer), allocateForWrite);\n\t}\n}, {\n\tpack(c1, allocateForWrite) { // specific 0xC1 object\n\t\tlet { target, position} = allocateForWrite(1);\n\t\ttarget[position] = 0xc1;\n\t}\n}];\n\nfunction writeExtBuffer(typedArray, type, allocateForWrite, encode) {\n\tlet length = typedArray.byteLength;\n\tif (length + 1 < 0x100) {\n\t\tvar { target, position } = allocateForWrite(4 + length);\n\t\ttarget[position++] = 0xc7;\n\t\ttarget[position++] = length + 1;\n\t} else if (length + 1 < 0x10000) {\n\t\tvar { target, position } = allocateForWrite(5 + length);\n\t\ttarget[position++] = 0xc8;\n\t\ttarget[position++] = (length + 1) >> 8;\n\t\ttarget[position++] = (length + 1) & 0xff;\n\t} else {\n\t\tvar { target, position, targetView } = allocateForWrite(7 + length);\n\t\ttarget[position++] = 0xc9;\n\t\ttargetView.setUint32(position, length + 1); // plus one for the type byte\n\t\tposition += 4;\n\t}\n\ttarget[position++] = 0x74; // \"t\" for typed array\n\ttarget[position++] = type;\n\tif (!typedArray.buffer) typedArray = new Uint8Array(typedArray);\n\ttarget.set(new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength), position);\n}\nfunction writeBuffer(buffer, allocateForWrite) {\n\tlet length = buffer.byteLength;\n\tvar target, position;\n\tif (length < 0x100) {\n\t\tvar { target, position } = allocateForWrite(length + 2);\n\t\ttarget[position++] = 0xc4;\n\t\ttarget[position++] = length;\n\t} else if (length < 0x10000) {\n\t\tvar { target, position } = allocateForWrite(length + 3);\n\t\ttarget[position++] = 0xc5;\n\t\ttarget[position++] = length >> 8;\n\t\ttarget[position++] = length & 0xff;\n\t} else {\n\t\tvar { target, position, targetView } = allocateForWrite(length + 5);\n\t\ttarget[position++] = 0xc6;\n\t\ttargetView.setUint32(position, length);\n\t\tposition += 4;\n\t}\n\ttarget.set(buffer, position);\n}\n\nfunction writeExtensionData(result, target, position, type) {\n\tlet length = result.length;\n\tswitch (length) {\n\t\tcase 1:\n\t\t\ttarget[position++] = 0xd4;\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\ttarget[position++] = 0xd5;\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\ttarget[position++] = 0xd6;\n\t\t\tbreak;\n\t\tcase 8:\n\t\t\ttarget[position++] = 0xd7;\n\t\t\tbreak;\n\t\tcase 16:\n\t\t\ttarget[position++] = 0xd8;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (length < 0x100) {\n\t\t\t\ttarget[position++] = 0xc7;\n\t\t\t\ttarget[position++] = length;\n\t\t\t} else if (length < 0x10000) {\n\t\t\t\ttarget[position++] = 0xc8;\n\t\t\t\ttarget[position++] = length >> 8;\n\t\t\t\ttarget[position++] = length & 0xff;\n\t\t\t} else {\n\t\t\t\ttarget[position++] = 0xc9;\n\t\t\t\ttarget[position++] = length >> 24;\n\t\t\t\ttarget[position++] = (length >> 16) & 0xff;\n\t\t\t\ttarget[position++] = (length >> 8) & 0xff;\n\t\t\t\ttarget[position++] = length & 0xff;\n\t\t\t}\n\t}\n\ttarget[position++] = type;\n\ttarget.set(result, position);\n\tposition += length;\n\treturn position;\n}\n\nfunction insertIds(serialized, idsToInsert) {\n\t// insert the ids that need to be referenced for structured clones\n\tlet nextId;\n\tlet distanceToMove = idsToInsert.length * 6;\n\tlet lastEnd = serialized.length - distanceToMove;\n\twhile (nextId = idsToInsert.pop()) {\n\t\tlet offset = nextId.offset;\n\t\tlet id = nextId.id;\n\t\tserialized.copyWithin(offset + distanceToMove, offset, lastEnd);\n\t\tdistanceToMove -= 6;\n\t\tlet position = offset + distanceToMove;\n\t\tserialized[position++] = 0xd6;\n\t\tserialized[position++] = 0x69; // 'i'\n\t\tserialized[position++] = id >> 24;\n\t\tserialized[position++] = (id >> 16) & 0xff;\n\t\tserialized[position++] = (id >> 8) & 0xff;\n\t\tserialized[position++] = id & 0xff;\n\t\tlastEnd = offset;\n\t}\n\treturn serialized;\n}\n\nfunction writeBundles(start, pack, incrementPosition) {\n\tif (bundledStrings.length > 0) {\n\t\ttargetView.setUint32(bundledStrings.position + start, position + incrementPosition - bundledStrings.position - start);\n\t\tbundledStrings.stringsPosition = position - start;\n\t\tlet writeStrings = bundledStrings;\n\t\tbundledStrings = null;\n\t\tpack(writeStrings[0]);\n\t\tpack(writeStrings[1]);\n\t}\n}\n\nexport function addExtension(extension) {\n\tif (extension.Class) {\n\t\tif (!extension.pack && !extension.write)\n\t\t\tthrow new Error('Extension has no pack or write function');\n\t\tif (extension.pack && !extension.type)\n\t\t\tthrow new Error('Extension has no type (numeric code to identify the extension)');\n\t\textensionClasses.unshift(extension.Class);\n\t\textensions.unshift(extension);\n\t}\n\tunpackAddExtension(extension);\n}\nfunction prepareStructures(structures, packr) {\n\tstructures.isCompatible = (existingStructures) => {\n\t\tlet compatible = !existingStructures || ((packr.lastNamedStructuresLength || 0) === existingStructures.length);\n\t\tif (!compatible) // we want to merge these existing structures immediately since we already have it and we are in the right transaction\n\t\t\tpackr._mergeStructures(existingStructures);\n\t\treturn compatible;\n\t};\n\treturn structures;\n}\n\n// Marker for downstream libraries (e.g. structon) to detect that this Packr\n// supports per-instance struct-encoding hooks (this._writeStruct,\n// this._prepareStructures).  See `pack` for the dispatch.\nPackr.SUPPORTS_STRUCT_HOOKS = true;\n\nlet defaultPackr = new Packr({ useRecords: false });\nexport const pack = defaultPackr.pack;\nexport const encode = defaultPackr.pack;\nexport const Encoder = Packr;\nexport { FLOAT32_OPTIONS } from './unpack.js';\nimport { FLOAT32_OPTIONS } from './unpack.js';\nexport const { NEVER, ALWAYS, DECIMAL_ROUND, DECIMAL_FIT } = FLOAT32_OPTIONS;\nexport const REUSE_BUFFER_MODE = 512;\nexport const RESET_BUFFER_MODE = 1024;\nexport const RESERVE_START_SPACE = 2048;\n","// Copyright 2017 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\nconst isLinux = () => process.platform === 'linux';\n\nlet report = null;\nconst getReport = () => {\n  if (!report) {\n    /* istanbul ignore next */\n    if (isLinux() && process.report) {\n      const orig = process.report.excludeNetwork;\n      process.report.excludeNetwork = true;\n      report = process.report.getReport();\n      process.report.excludeNetwork = orig;\n    } else {\n      report = {};\n    }\n  }\n  return report;\n};\n\nmodule.exports = { isLinux, getReport };\n","// Copyright 2017 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\nconst fs = require('fs');\n\nconst LDD_PATH = '/usr/bin/ldd';\nconst SELF_PATH = '/proc/self/exe';\nconst MAX_LENGTH = 2048;\n\n/**\n * Read the content of a file synchronous\n *\n * @param {string} path\n * @returns {Buffer}\n */\nconst readFileSync = (path) => {\n  const fd = fs.openSync(path, 'r');\n  const buffer = Buffer.alloc(MAX_LENGTH);\n  const bytesRead = fs.readSync(fd, buffer, 0, MAX_LENGTH, 0);\n  fs.close(fd, () => {});\n  return buffer.subarray(0, bytesRead);\n};\n\n/**\n * Read the content of a file\n *\n * @param {string} path\n * @returns {Promise<Buffer>}\n */\nconst readFile = (path) => new Promise((resolve, reject) => {\n  fs.open(path, 'r', (err, fd) => {\n    if (err) {\n      reject(err);\n    } else {\n      const buffer = Buffer.alloc(MAX_LENGTH);\n      fs.read(fd, buffer, 0, MAX_LENGTH, 0, (_, bytesRead) => {\n        resolve(buffer.subarray(0, bytesRead));\n        fs.close(fd, () => {});\n      });\n    }\n  });\n});\n\nmodule.exports = {\n  LDD_PATH,\n  SELF_PATH,\n  readFileSync,\n  readFile\n};\n","// Copyright 2017 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\nconst interpreterPath = (elf) => {\n  if (elf.length < 64) {\n    return null;\n  }\n  if (elf.readUInt32BE(0) !== 0x7F454C46) {\n    // Unexpected magic bytes\n    return null;\n  }\n  if (elf.readUInt8(4) !== 2) {\n    // Not a 64-bit ELF\n    return null;\n  }\n  if (elf.readUInt8(5) !== 1) {\n    // Not little-endian\n    return null;\n  }\n  const offset = elf.readUInt32LE(32);\n  const size = elf.readUInt16LE(54);\n  const count = elf.readUInt16LE(56);\n  for (let i = 0; i < count; i++) {\n    const headerOffset = offset + (i * size);\n    const type = elf.readUInt32LE(headerOffset);\n    if (type === 3) {\n      const fileOffset = elf.readUInt32LE(headerOffset + 8);\n      const fileSize = elf.readUInt32LE(headerOffset + 32);\n      return elf.subarray(fileOffset, fileOffset + fileSize).toString().replace(/\\0.*$/g, '');\n    }\n  }\n  return null;\n};\n\nmodule.exports = {\n  interpreterPath\n};\n","// Copyright 2017 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\nconst childProcess = require('child_process');\nconst { isLinux, getReport } = require('./process');\nconst { LDD_PATH, SELF_PATH, readFile, readFileSync } = require('./filesystem');\nconst { interpreterPath } = require('./elf');\n\nlet cachedFamilyInterpreter;\nlet cachedFamilyFilesystem;\nlet cachedVersionFilesystem;\n\nconst command = 'getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true';\nlet commandOut = '';\n\nconst safeCommand = () => {\n  if (!commandOut) {\n    return new Promise((resolve) => {\n      childProcess.exec(command, (err, out) => {\n        commandOut = err ? ' ' : out;\n        resolve(commandOut);\n      });\n    });\n  }\n  return commandOut;\n};\n\nconst safeCommandSync = () => {\n  if (!commandOut) {\n    try {\n      commandOut = childProcess.execSync(command, { encoding: 'utf8' });\n    } catch (_err) {\n      commandOut = ' ';\n    }\n  }\n  return commandOut;\n};\n\n/**\n * A String constant containing the value `glibc`.\n * @type {string}\n * @public\n */\nconst GLIBC = 'glibc';\n\n/**\n * A Regexp constant to get the GLIBC Version.\n * @type {string}\n */\nconst RE_GLIBC_VERSION = /LIBC[a-z0-9 \\-).]*?(\\d+\\.\\d+)/i;\n\n/**\n * A String constant containing the value `musl`.\n * @type {string}\n * @public\n */\nconst MUSL = 'musl';\n\nconst isFileMusl = (f) => f.includes('libc.musl-') || f.includes('ld-musl-');\n\nconst familyFromReport = () => {\n  const report = getReport();\n  if (report.header && report.header.glibcVersionRuntime) {\n    return GLIBC;\n  }\n  if (Array.isArray(report.sharedObjects)) {\n    if (report.sharedObjects.some(isFileMusl)) {\n      return MUSL;\n    }\n  }\n  return null;\n};\n\nconst familyFromCommand = (out) => {\n  const [getconf, ldd1] = out.split(/[\\r\\n]+/);\n  if (getconf && getconf.includes(GLIBC)) {\n    return GLIBC;\n  }\n  if (ldd1 && ldd1.includes(MUSL)) {\n    return MUSL;\n  }\n  return null;\n};\n\nconst familyFromInterpreterPath = (path) => {\n  if (path) {\n    if (path.includes('/ld-musl-')) {\n      return MUSL;\n    } else if (path.includes('/ld-linux-')) {\n      return GLIBC;\n    }\n  }\n  return null;\n};\n\nconst getFamilyFromLddContent = (content) => {\n  content = content.toString();\n  if (content.includes('musl')) {\n    return MUSL;\n  }\n  if (content.includes('GNU C Library')) {\n    return GLIBC;\n  }\n  return null;\n};\n\nconst familyFromFilesystem = async () => {\n  if (cachedFamilyFilesystem !== undefined) {\n    return cachedFamilyFilesystem;\n  }\n  cachedFamilyFilesystem = null;\n  try {\n    const lddContent = await readFile(LDD_PATH);\n    cachedFamilyFilesystem = getFamilyFromLddContent(lddContent);\n  } catch (e) {}\n  return cachedFamilyFilesystem;\n};\n\nconst familyFromFilesystemSync = () => {\n  if (cachedFamilyFilesystem !== undefined) {\n    return cachedFamilyFilesystem;\n  }\n  cachedFamilyFilesystem = null;\n  try {\n    const lddContent = readFileSync(LDD_PATH);\n    cachedFamilyFilesystem = getFamilyFromLddContent(lddContent);\n  } catch (e) {}\n  return cachedFamilyFilesystem;\n};\n\nconst familyFromInterpreter = async () => {\n  if (cachedFamilyInterpreter !== undefined) {\n    return cachedFamilyInterpreter;\n  }\n  cachedFamilyInterpreter = null;\n  try {\n    const selfContent = await readFile(SELF_PATH);\n    const path = interpreterPath(selfContent);\n    cachedFamilyInterpreter = familyFromInterpreterPath(path);\n  } catch (e) {}\n  return cachedFamilyInterpreter;\n};\n\nconst familyFromInterpreterSync = () => {\n  if (cachedFamilyInterpreter !== undefined) {\n    return cachedFamilyInterpreter;\n  }\n  cachedFamilyInterpreter = null;\n  try {\n    const selfContent = readFileSync(SELF_PATH);\n    const path = interpreterPath(selfContent);\n    cachedFamilyInterpreter = familyFromInterpreterPath(path);\n  } catch (e) {}\n  return cachedFamilyInterpreter;\n};\n\n/**\n * Resolves with the libc family when it can be determined, `null` otherwise.\n * @returns {Promise<?string>}\n */\nconst family = async () => {\n  let family = null;\n  if (isLinux()) {\n    family = await familyFromInterpreter();\n    if (!family) {\n      family = await familyFromFilesystem();\n      if (!family) {\n        family = familyFromReport();\n      }\n      if (!family) {\n        const out = await safeCommand();\n        family = familyFromCommand(out);\n      }\n    }\n  }\n  return family;\n};\n\n/**\n * Returns the libc family when it can be determined, `null` otherwise.\n * @returns {?string}\n */\nconst familySync = () => {\n  let family = null;\n  if (isLinux()) {\n    family = familyFromInterpreterSync();\n    if (!family) {\n      family = familyFromFilesystemSync();\n      if (!family) {\n        family = familyFromReport();\n      }\n      if (!family) {\n        const out = safeCommandSync();\n        family = familyFromCommand(out);\n      }\n    }\n  }\n  return family;\n};\n\n/**\n * Resolves `true` only when the platform is Linux and the libc family is not `glibc`.\n * @returns {Promise<boolean>}\n */\nconst isNonGlibcLinux = async () => isLinux() && await family() !== GLIBC;\n\n/**\n * Returns `true` only when the platform is Linux and the libc family is not `glibc`.\n * @returns {boolean}\n */\nconst isNonGlibcLinuxSync = () => isLinux() && familySync() !== GLIBC;\n\nconst versionFromFilesystem = async () => {\n  if (cachedVersionFilesystem !== undefined) {\n    return cachedVersionFilesystem;\n  }\n  cachedVersionFilesystem = null;\n  try {\n    const lddContent = await readFile(LDD_PATH);\n    const versionMatch = lddContent.match(RE_GLIBC_VERSION);\n    if (versionMatch) {\n      cachedVersionFilesystem = versionMatch[1];\n    }\n  } catch (e) {}\n  return cachedVersionFilesystem;\n};\n\nconst versionFromFilesystemSync = () => {\n  if (cachedVersionFilesystem !== undefined) {\n    return cachedVersionFilesystem;\n  }\n  cachedVersionFilesystem = null;\n  try {\n    const lddContent = readFileSync(LDD_PATH);\n    const versionMatch = lddContent.match(RE_GLIBC_VERSION);\n    if (versionMatch) {\n      cachedVersionFilesystem = versionMatch[1];\n    }\n  } catch (e) {}\n  return cachedVersionFilesystem;\n};\n\nconst versionFromReport = () => {\n  const report = getReport();\n  if (report.header && report.header.glibcVersionRuntime) {\n    return report.header.glibcVersionRuntime;\n  }\n  return null;\n};\n\nconst versionSuffix = (s) => s.trim().split(/\\s+/)[1];\n\nconst versionFromCommand = (out) => {\n  const [getconf, ldd1, ldd2] = out.split(/[\\r\\n]+/);\n  if (getconf && getconf.includes(GLIBC)) {\n    return versionSuffix(getconf);\n  }\n  if (ldd1 && ldd2 && ldd1.includes(MUSL)) {\n    return versionSuffix(ldd2);\n  }\n  return null;\n};\n\n/**\n * Resolves with the libc version when it can be determined, `null` otherwise.\n * @returns {Promise<?string>}\n */\nconst version = async () => {\n  let version = null;\n  if (isLinux()) {\n    version = await versionFromFilesystem();\n    if (!version) {\n      version = versionFromReport();\n    }\n    if (!version) {\n      const out = await safeCommand();\n      version = versionFromCommand(out);\n    }\n  }\n  return version;\n};\n\n/**\n * Returns the libc version when it can be determined, `null` otherwise.\n * @returns {?string}\n */\nconst versionSync = () => {\n  let version = null;\n  if (isLinux()) {\n    version = versionFromFilesystemSync();\n    if (!version) {\n      version = versionFromReport();\n    }\n    if (!version) {\n      const out = safeCommandSync();\n      version = versionFromCommand(out);\n    }\n  }\n  return version;\n};\n\nmodule.exports = {\n  GLIBC,\n  MUSL,\n  family,\n  familySync,\n  isNonGlibcLinux,\n  isNonGlibcLinuxSync,\n  version,\n  versionSync\n};\n","var fs = require('fs')\nvar path = require('path')\nvar url = require('url')\nvar os = require('os')\n// Workaround to fix webpack's build warnings: 'the request of a dependency is an expression'\nvar runtimeRequire = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require // eslint-disable-line\n\nvar vars = (process.config && process.config.variables) || {}\nvar prebuildsOnly = !!process.env.PREBUILDS_ONLY\nvar versions = process.versions\nvar abi = versions.modules\nif (versions.deno || process.isBun) {\n  // both Deno and Bun made the very poor decision to shoot themselves in the foot and lie about support for ABI\n  // (which they do not have)\n  abi = 'unsupported'\n}\nvar runtime = isElectron() ? 'electron' : (isNwjs() ? 'node-webkit' : 'node')\nvar arch = process.env.npm_config_arch || os.arch()\nvar platform = process.env.npm_config_platform || os.platform()\nvar libc = process.env.LIBC || (isMusl(platform) ? 'musl' : 'glibc')\n\nvar armv = process.env.ARM_VERSION || (arch === 'arm64' ? '8' : vars.arm_version) || ''\nvar uv = (versions.uv || '').split('.')[0]\n\nmodule.exports = load\n\nfunction load (dir) {\n  return runtimeRequire(load.resolve(dir))\n}\n\nload.resolve = load.path = function (dir) {\n  dir = path.resolve(dir || '.')\n  var packageName = ''\n  var packageNameError\n  try {\n    packageName = runtimeRequire(path.join(dir, 'package.json')).name;\n    var varName = packageName.toUpperCase().replace(/-/g, '_')\n    if (process.env[varName + '_PREBUILD']) dir = process.env[varName + '_PREBUILD']\n  } catch (err) {\n    packageNameError = err;\n  }\n  if (!prebuildsOnly) {\n    var release = getFirst(path.join(dir, 'build/Release'), matchBuild)\n    if (release) return release\n\n    var debug = getFirst(path.join(dir, 'build/Debug'), matchBuild)\n    if (debug) return debug\n  }\n\n  var prebuild = resolve(dir)\n  if (prebuild) return prebuild\n\n  var nearby = resolve(path.dirname(process.execPath))\n  if (nearby) return nearby\n\n  var platformPackage = (packageName[0] == '@' ? '' : '@' + packageName + '/') + packageName + '-' + platform + '-' + arch\n  var packageResolutionError\n  try {\n    var prebuildPackage = path.dirname(require('module').createRequire(url.pathToFileURL(path.join(dir, 'package.json'))).resolve(platformPackage))\n    return resolveFile(prebuildPackage)\n  } catch(error) {\n    packageResolutionError = error\n  }\n\n  var target = [\n    'platform=' + platform,\n    'arch=' + arch,\n    'runtime=' + runtime,\n    'abi=' + abi,\n    'uv=' + uv,\n    armv ? 'armv=' + armv : '',\n    'libc=' + libc,\n    'node=' + process.versions.node,\n    process.versions.electron ? 'electron=' + process.versions.electron : '',\n    typeof __webpack_require__ === 'function' ? 'webpack=true' : '' // eslint-disable-line\n  ].filter(Boolean).join(' ')\n  let errMessage = 'No native build was found for ' + target + '\\n    attempted loading from: ' + dir + ' and package:' +\n    ' ' + platformPackage + '\\n';\n  if (packageNameError) {\n    errMessage += 'Error finding package.json: ' + packageNameError.message + '\\n';\n  }\n  if (packageResolutionError) {\n    errMessage += 'Error resolving package: ' + packageResolutionError.message + '\\n';\n  }\n  throw new Error(errMessage)\n\n  function resolve (dir) {\n    // Find matching \"prebuilds/<platform>-<arch>\" directory\n    var tuples = readdirSync(path.join(dir, 'prebuilds')).map(parseTuple)\n    var tuple = tuples.filter(matchTuple(platform, arch)).sort(compareTuples)[0]\n    if (!tuple) return\n    return resolveFile(path.join(dir, 'prebuilds', tuple.name))\n  }\n  function resolveFile (prebuilds) {\n    // Find most specific flavor first\n    var parsed = readdirSync(prebuilds).map(parseTags)\n    var candidates = parsed.filter(matchTags(runtime, abi))\n    var winner = candidates.sort(compareTags(runtime))[0]\n    if (winner) return path.join(prebuilds, winner.file)\n  }\n}\n\nfunction readdirSync (dir) {\n  try {\n    return fs.readdirSync(dir)\n  } catch (err) {\n    return []\n  }\n}\n\nfunction getFirst (dir, filter) {\n  var files = readdirSync(dir).filter(filter)\n  return files[0] && path.join(dir, files[0])\n}\n\nfunction matchBuild (name) {\n  return /\\.node$/.test(name)\n}\n\nfunction parseTuple (name) {\n  // Example: darwin-x64+arm64\n  var arr = name.split('-')\n  if (arr.length !== 2) return\n\n  var platform = arr[0]\n  var architectures = arr[1].split('+')\n\n  if (!platform) return\n  if (!architectures.length) return\n  if (!architectures.every(Boolean)) return\n\n  return { name, platform, architectures }\n}\n\nfunction matchTuple (platform, arch) {\n  return function (tuple) {\n    if (tuple == null) return false\n    if (tuple.platform !== platform) return false\n    return tuple.architectures.includes(arch)\n  }\n}\n\nfunction compareTuples (a, b) {\n  // Prefer single-arch prebuilds over multi-arch\n  return a.architectures.length - b.architectures.length\n}\n\nfunction parseTags (file) {\n  var arr = file.split('.')\n  var extension = arr.pop()\n  var tags = { file: file, specificity: 0 }\n\n  if (extension !== 'node') return\n\n  for (var i = 0; i < arr.length; i++) {\n    var tag = arr[i]\n\n    if (tag === 'node' || tag === 'electron' || tag === 'node-webkit') {\n      tags.runtime = tag\n    } else if (tag === 'napi') {\n      tags.napi = true\n    } else if (tag.slice(0, 3) === 'abi') {\n      tags.abi = tag.slice(3)\n    } else if (tag.slice(0, 2) === 'uv') {\n      tags.uv = tag.slice(2)\n    } else if (tag.slice(0, 4) === 'armv') {\n      tags.armv = tag.slice(4)\n    } else if (tag === 'glibc' || tag === 'musl') {\n      tags.libc = tag\n    } else {\n      continue\n    }\n\n    tags.specificity++\n  }\n\n  return tags\n}\n\nfunction matchTags (runtime, abi) {\n  return function (tags) {\n    if (tags == null) return false\n    if (tags.runtime !== runtime && !runtimeAgnostic(tags)) return false\n    if (tags.abi !== abi && !tags.napi) return false\n    if (tags.uv && tags.uv !== uv) return false\n    if (tags.armv && tags.armv !== armv) return false\n    if (tags.libc && tags.libc !== libc) return false\n\n    return true\n  }\n}\n\nfunction runtimeAgnostic (tags) {\n  return tags.runtime === 'node' && tags.napi\n}\n\nfunction compareTags (runtime) {\n  // Precedence: non-agnostic runtime, abi over napi, then by specificity.\n  return function (a, b) {\n    if (a.runtime !== b.runtime) {\n      return a.runtime === runtime ? -1 : 1\n    } else if (a.abi !== b.abi) {\n      return a.abi ? -1 : 1\n    } else if (a.specificity !== b.specificity) {\n      return a.specificity > b.specificity ? -1 : 1\n    } else {\n      return 0\n    }\n  }\n}\n\nfunction isNwjs () {\n  return !!(process.versions && process.versions.nw)\n}\n\nfunction isElectron () {\n  if (process.versions && process.versions.electron) return true\n  if (process.env.ELECTRON_RUN_AS_NODE) return true\n  return typeof window !== 'undefined' && window.process && window.process.type === 'renderer'\n}\n\nfunction isMusl (platform) {\n  if (platform !== 'linux') return false;\n  const { familySync, MUSL } = require('detect-libc');\n  return familySync() === MUSL;\n}\n\n// Exposed for unit tests\n// TODO: move to lib\nload.parseTags = parseTags\nload.matchTags = matchTags\nload.compareTags = compareTags\nload.parseTuple = parseTuple\nload.matchTuple = matchTuple\nload.compareTuples = compareTuples\n\n","const runtimeRequire = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require // eslint-disable-line\nif (typeof runtimeRequire.addon === 'function') { // if the platform supports native resolving prefer that\n  module.exports = runtimeRequire.addon.bind(runtimeRequire)\n} else { // else use the runtime version here\n  module.exports = require('./node-gyp-build.js')\n}\n","module.exports = require('node-gyp-build-optional-packages')(__dirname);","export { Packr, Encoder, addExtension, pack, encode, NEVER, ALWAYS, DECIMAL_ROUND, DECIMAL_FIT, REUSE_BUFFER_MODE, RESET_BUFFER_MODE, RESERVE_START_SPACE } from './pack.js';\nexport { Unpackr, Decoder, C1, unpack, unpackMultiple, decode, FLOAT32_OPTIONS, clearSource, roundFloat32, isNativeAccelerationEnabled } from './unpack.js';\nexport { PackrStream, UnpackrStream, PackrStream as EncoderStream, UnpackrStream as DecoderStream } from './stream.js';\nexport { decodeIter, encodeIter } from './iterators.js';\nexport const useRecords = false;\nexport const mapsAsObjects = true;\nimport { setExtractor } from './unpack.js';\nimport { createRequire } from 'module';\n\nconst nativeAccelerationDisabled = process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED !== undefined && process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED.toLowerCase() === 'true';\n\nif (!nativeAccelerationDisabled) {\n\tlet extractor;\n\ttry {\n\t\tif (typeof require == 'function')\n\t\t\textractor = require('msgpackr-extract');\n\t\telse\n\t\t\textractor = createRequire(import.meta.url)('msgpackr-extract');\n\t\tif (extractor)\n\t\t\tsetExtractor(extractor.extractStrings);\n\t} catch (error) {\n\t\t// native module is optional\n\t}\n}","import {\n  type ClientCryptoKeyLink,\n  decryptBytesWithAesGcmKey,\n  encryptBytesWithAesGcmKey,\n} from \"@nice-code/util\";\nimport { pack, unpack } from \"msgpackr\";\nimport type { IHandshakeEncryptionKeyMaterial } from \"./actionHandshake\";\n\n/**\n * Async AES-GCM transform for the `encrypted` security level. It wraps the opaque binary frame a\n * session codec produces (it does NOT look inside it), encrypting on the way out and decrypting on the\n * way in with the shared key established by the handshake.\n *\n * It is deliberately separate from the (synchronous) session `formatMessage`: WebCrypto is always\n * Promise-based, so encryption has to happen at the transport's async I/O boundary — the connection\n * encrypts after `session.outgoing()` and decrypts before `session.incoming()`. The `authenticated`\n * and `none` levels use no crypto transform at all (frames go out as the session produced them).\n *\n * Wire shape of an encrypted frame: `pack([nonceBytes, ciphertextBytes])` — msgpack carries the two\n * binary fields with a couple of bytes of overhead, no base64 inflation.\n */\nexport interface IActionFrameCrypto {\n  /** Encrypt one session frame for sending. */\n  encryptFrame(frame: Uint8Array): Promise<Uint8Array>;\n  /** Decrypt one received frame back to the session frame. Throws on a non-binary / malformed /\n   * tampered frame — the caller (transport) decides how to react (drop / close). */\n  decryptFrame(frame: string | ArrayBuffer | Uint8Array): Promise<Uint8Array>;\n}\n\nexport interface IActionFrameCryptoConfig {\n  link: ClientCryptoKeyLink;\n  /**\n   * This session's handshake key material. The shared AES-GCM key is derived from it **once** and held\n   * for the life of the connection — it is NOT re-read per frame from the link's per-`linkedClientId`\n   * cache, so a second secure session to the same peer (e.g. a secure HTTP exchange beside a secure\n   * WebSocket, both sharing one DO crypto identity) can't overwrite this connection's key.\n   */\n  keyMaterial: IHandshakeEncryptionKeyMaterial;\n}\n\nconst ENCRYPTED_ENVELOPE_LENGTH = 2;\n\n/**\n * Build the encrypt/decrypt transform for a connection whose handshake settled on the `encrypted`\n * level. The shared key is derived once from {@link IActionFrameCryptoConfig.keyMaterial} and captured\n * for this connection alone, decoupling it from the link's shared key cache.\n */\nexport function createActionFrameCrypto({\n  link,\n  keyMaterial,\n}: IActionFrameCryptoConfig): IActionFrameCrypto {\n  // Derive this session's key once and hold the promise — every frame reuses it, so a concurrent\n  // session sharing the same `linkedClientId` on this link can't clobber it.\n  const keyPromise = link.deriveSharedAesGcmKey(keyMaterial);\n\n  return {\n    async encryptFrame(frame: Uint8Array): Promise<Uint8Array> {\n      const { nonce, ciphertext } = await encryptBytesWithAesGcmKey({\n        dataToEncrypt: frame,\n        aesGcmKey: await keyPromise,\n      });\n      return pack([nonce, ciphertext]);\n    },\n\n    async decryptFrame(frame: string | ArrayBuffer | Uint8Array): Promise<Uint8Array> {\n      if (typeof frame === \"string\") {\n        throw new Error(\"[ws-crypto] expected an encrypted binary frame, received text\");\n      }\n\n      const buffer = frame instanceof ArrayBuffer ? new Uint8Array(frame) : frame;\n      const envelope = unpack(buffer);\n      if (!Array.isArray(envelope) || envelope.length !== ENCRYPTED_ENVELOPE_LENGTH) {\n        throw new Error(\"[ws-crypto] malformed encrypted frame envelope\");\n      }\n\n      const [nonce, ciphertext] = envelope;\n      if (!(nonce instanceof Uint8Array) || !(ciphertext instanceof Uint8Array)) {\n        throw new Error(\"[ws-crypto] malformed encrypted frame fields\");\n      }\n\n      // AES-GCM verifies integrity — a tampered ciphertext throws here.\n      return await decryptBytesWithAesGcmKey({\n        dataToDecrypt: { nonce, ciphertext },\n        aesGcmKey: await keyPromise,\n      });\n    },\n  };\n}\n","import type { TFrame } from \"../Carrier/Carrier.types\";\n\n/**\n * Frame-protocol prefix bytes (realm protocol design §3.1). A registered protocol frame is\n * `[prefixByte, ...payload]` with the prefix drawn from the reserved range `0x00`–`0x0F` —\n * bytes no legacy frame can start with: binary action envelopes are msgpack fixarrays\n * (`0x96`–`0x98`), control frames are msgpack maps (`0x80`–`0x8f`, `0xde`, `0xdf`), and\n * handshake frames are text JSON (`{` = `0x7b`). Frames without a reserved prefix fall through\n * to the legacy sniffing untouched, so old peers stay byte-identical (pinned by the\n * byte-compat goldens).\n *\n * The registry is **closed** — same philosophy as the control-message registry: protocols are\n * library-level concerns assigned here, never user-claimable ad hoc.\n */\nexport const WIRE_PROTOCOL_PREFIX = {\n  /** `0x00` is reserved/invalid — a zero prefix is treated as a decode error, never dispatched. */\n  invalid: 0x00,\n  /** `@nice-code/realm` state-sync frames. */\n  realm: 0x01,\n  /**\n   * `@nice-code/devtools` observation frames. Assigned here so the prefix space has one\n   * authoritative catalogue; `@nice-code/devtools-core` (a zero-runtime-dependency package that\n   * cannot import wire) mirrors it structurally as its own `DEVTOOLS_WIRE_PREFIX = 0x02`.\n   */\n  devtools: 0x02,\n} as const;\n\n/** Highest byte of the reserved prefix range (inclusive). */\nexport const WIRE_PROTOCOL_PREFIX_MAX = 0x0f;\n\n/**\n * Peek a frame's protocol prefix: the byte when it is a binary frame starting in the reserved\n * range, else `undefined` (a legacy frame — handshake/control/action — or a text frame).\n */\nexport function peekProtocolPrefix(frame: TFrame): number | undefined {\n  let first: number | undefined;\n  if (frame instanceof Uint8Array) first = frame.length > 0 ? frame[0] : undefined;\n  else if (frame instanceof ArrayBuffer) {\n    first = frame.byteLength > 0 ? new Uint8Array(frame, 0, 1)[0] : undefined;\n  } else return undefined; // text frames are never protocol frames\n  if (first == null || first > WIRE_PROTOCOL_PREFIX_MAX) return undefined;\n  return first;\n}\n\n/** Wrap a protocol payload with its prefix byte. */\nexport function encodeProtocolFrame(prefixByte: number, payload: Uint8Array): Uint8Array {\n  if (prefixByte <= 0x00 || prefixByte > WIRE_PROTOCOL_PREFIX_MAX) {\n    throw new Error(\n      `encodeProtocolFrame: prefix 0x${prefixByte.toString(16)} outside reserved range`,\n    );\n  }\n  const framed = new Uint8Array(payload.length + 1);\n  framed[0] = prefixByte;\n  framed.set(payload, 1);\n  return framed;\n}\n\n/** Strip the prefix byte off an already-peeked protocol frame. */\nexport function protocolFramePayload(frame: TFrame): Uint8Array {\n  const bytes = frame instanceof Uint8Array ? frame : new Uint8Array(frame as ArrayBuffer);\n  return bytes.subarray(1);\n}\n\n/** The handshake capability tag advertising a frame protocol (`hello.caps` / `welcome.caps`). */\nexport function protocolCap(protocolId: string): string {\n  return `proto:${protocolId}`;\n}\n\n/** Extract the advertised protocol ids from a peer's handshake caps. */\nexport function protocolsFromCaps(caps: readonly string[] | undefined): ReadonlySet<string> {\n  const ids = new Set<string>();\n  for (const cap of caps ?? []) {\n    if (cap.startsWith(\"proto:\")) ids.add(cap.slice(\"proto:\".length));\n  }\n  return ids;\n}\n","import type { TFrame } from \"../Carrier/Carrier.types\";\n\n/** Normalize any frame form to bytes (for the AES-GCM layer, which works on `Uint8Array`). */\nexport function toFrameBytes(frame: TFrame): Uint8Array {\n  if (typeof frame === \"string\") return new TextEncoder().encode(frame);\n  if (frame instanceof ArrayBuffer) return new Uint8Array(frame);\n  return frame;\n}\n","import type { TFrame } from \"../Carrier/Carrier.types\";\nimport type { IActionFrameCrypto } from \"../crypto/actionFrameCrypto\";\nimport { toFrameBytes } from \"../crypto/frameBytes\";\n\n/**\n * Ordered frame crypto over a single channel/connection — the one place the encrypt-on-send /\n * decrypt-on-receive logic lives, shared by both link roles:\n *\n * - the **connector** (one carrier, one crypto) — see `establishLinkSession`;\n * - the **acceptor** (one per accepted connection, crypto re-derived asynchronously after a hibernation\n *   wake) — see `ChannelAcceptor`.\n *\n * Outbound frames go on an ordered chain so async AES-GCM never reorders them, and the chain gates once\n * on `crypto` — which, when `crypto` is a promise, also gates the first send on the post-wake key\n * re-derivation. With no `crypto` it's a plaintext passthrough.\n */\nexport interface IFrameCryptoPipe {\n  /**\n   * Encrypt (if secured) and write `frame`, preserving dispatch order. Dropped if `isOpen` is false.\n   * `tapLane` is opaque metadata carried through to the write — the wire-tap seam uses it to label\n   * the frame's lane (a dropped/failed frame never reaches the write, so it is never tapped).\n   */\n  send(frame: TFrame, tapLane?: string): void;\n  /** Decrypt an inbound frame; resolves `undefined` (frame dropped) if decryption fails. */\n  decryptIncoming(frame: TFrame): Promise<TFrame | undefined>;\n}\n\nexport interface IFrameCryptoPipeConfig {\n  /** Raw frame writer — the carrier's `send`, or the acceptor's per-connection send. */\n  write: (frame: TFrame, tapLane?: string) => void;\n  /** Optional synchronous open-guard; when it returns `false`, sends are dropped (a closed carrier). */\n  isOpen?: () => boolean;\n  /**\n   * The AES-GCM transform, or a promise of it. `undefined` ⇒ plaintext passthrough. A promise lets the\n   * acceptor gate the connection's first frame on an async key re-derivation after a hibernation wake.\n   */\n  crypto?: IActionFrameCrypto | Promise<IActionFrameCrypto>;\n  /** Short label for the encrypt/decrypt failure logs (e.g. `\"link\"`, `\"ws-server\"`). */\n  label?: string;\n}\n\nexport function createFrameCryptoPipe(config: IFrameCryptoPipeConfig): IFrameCryptoPipe {\n  const { write, isOpen, crypto, label = \"link\" } = config;\n\n  // Ordered send chain: async encryption must keep frames in dispatch order.\n  let sendChain: Promise<void> = Promise.resolve();\n\n  const send = (frame: TFrame, tapLane?: string): void => {\n    if (isOpen != null && !isOpen()) return;\n    if (crypto == null) {\n      write(frame, tapLane);\n      return;\n    }\n    const bytes = toFrameBytes(frame);\n    sendChain = sendChain\n      .then(() => crypto)\n      .then((c) => c.encryptFrame(bytes))\n      .then((encrypted) => {\n        if (isOpen == null || isOpen()) write(encrypted, tapLane);\n      })\n      .catch((err) => console.error(`[${label}] failed to encrypt/send frame`, err));\n  };\n\n  const decryptIncoming = async (frame: TFrame): Promise<TFrame | undefined> => {\n    if (crypto == null) return frame;\n    try {\n      return await (await crypto).decryptFrame(frame);\n    } catch (err) {\n      console.error(`[${label}] failed to decrypt incoming frame`, err);\n      return undefined;\n    }\n  };\n\n  return { send, decryptIncoming };\n}\n","// The wire-observation seam: a transport host\n// (nice-action's connectChannel / serveChannel) may hand the sessions a tap\n// function, and every frame that actually crosses the carrier is reported to it\n// with its TRUE wire byte size — measured post-encryption, exactly what the\n// platform's per-message billing and egress metering see. Sizes only, never\n// payload contents. With no tap attached the cost is a single null check per\n// frame.\n\n/** Well-known lanes; mux-carried protocol frames report their protocol id (e.g. `\"realm\"`). */\nexport type TWireTapLane = \"handshake\" | \"keepalive\" | \"action\" | \"http\" | (string & {});\n\nexport interface IWireTapEvent {\n  dir: \"in\" | \"out\";\n  /** Bytes as sent to / received from the carrier (UTF-8 length for text frames). */\n  bytes: number;\n  lane: TWireTapLane;\n  /** Connection identity, when the host distinguishes links (server side / multi-link). */\n  linkId?: string;\n}\n\nexport type TWireTapFn = (event: IWireTapEvent) => void;\n\n/**\n * Wrap a tap so every event it receives is attributed to `linkId` unless the emitter already named\n * one. This is how the **connector** side gets per-link attribution: an acceptor knows many peers\n * and tags each frame with the bound client as it emits, whereas a connector has exactly one peer\n * for the whole connection — so stamping once at the seam beats threading an id through the pipe,\n * the session, the keepalive and the exchange carrier.\n *\n * Both ends therefore answer the same question with `linkId`: *who is on the other end of this\n * frame*. A client's core can then split its traffic per backend it dials, exactly as a server's\n * splits per client it serves.\n */\nexport function withLinkIdTap(tap: TWireTapFn, linkId: string): TWireTapFn {\n  return (event) => {\n    tap(event.linkId != null ? event : { ...event, linkId });\n  };\n}\n\n/**\n * Wrap an exchange (HTTP) carrier so every request/reply pair is reported to the\n * tap under the `\"http\"` lane — the exchange path's equivalent of the duplex\n * session's pipe/dispatch taps. Envelope bytes as handed to the carrier (the\n * HTTP layer's own headers are outside the library's sight and not counted).\n */\nexport function withExchangeTap(\n  carrier: import(\"../Carrier/Carrier.types\").IExchangeCarrier,\n  tap: TWireTapFn,\n  linkId?: string,\n): import(\"../Carrier/Carrier.types\").IExchangeCarrier {\n  return {\n    exchange: async (frame, opts) => {\n      tap({ dir: \"out\", bytes: wireFrameByteSize(frame), lane: \"http\", linkId });\n      const reply = await carrier.exchange(frame, opts);\n      tap({ dir: \"in\", bytes: wireFrameByteSize(reply), lane: \"http\", linkId });\n      return reply;\n    },\n    get label() {\n      return carrier.label;\n    },\n  };\n}\n\n// Local copy of nice-devtools-shared's frameByteSize — wire must not depend on\n// the devtools package. The shared FRAME_BYTE_SIZE_VECTORS test pins the two\n// implementations to identical results.\nlet encoder: TextEncoder | undefined;\n\n/** The transmitted size of one frame: `byteLength` for binary, UTF-8 length for strings. */\nexport function wireFrameByteSize(frame: unknown): number {\n  if (typeof frame === \"string\") {\n    if (encoder == null) encoder = new TextEncoder();\n    return encoder.encode(frame).byteLength;\n  }\n  if (frame instanceof Uint8Array) return frame.byteLength;\n  if (frame instanceof ArrayBuffer) return frame.byteLength;\n  if (typeof SharedArrayBuffer !== \"undefined\" && frame instanceof SharedArrayBuffer) {\n    return frame.byteLength;\n  }\n  if (ArrayBuffer.isView(frame)) return frame.byteLength;\n  return 0;\n}\n","import {\n  HANDSHAKE_REJECT_ID_PIN_MISMATCH,\n  HANDSHAKE_REJECT_ID_PROTOCOL_VERSION_MISMATCH,\n  type THsReject,\n} from \"../crypto/actionHandshake\";\nimport { WIRE_SUPPORTED_PROTOCOL_VERSIONS } from \"../protocolVersion\";\nimport { err_wire_connect } from \"./err_wire_connect\";\n\nconst sanitizeVersions = (\n  versions: readonly number[] | undefined,\n): readonly number[] | undefined => {\n  if (versions == null) return undefined;\n  const safe: number[] = [];\n  for (const version of versions) {\n    if (Number.isSafeInteger(version) && version >= 1 && version <= 0xffff) safe.push(version);\n    if (safe.length === 2) break;\n  }\n  return safe.length > 0 ? safe : undefined;\n};\n\n/**\n * Map a peer's handshake reject frame to the error the dialing side throws. A reject carrying a machine-readable `id` becomes the matching typed `err_wire_connect`\n * error — `identity_pin_mismatch` or `protocol_version_mismatch` — which transport selection\n * rethrows unwrapped so callers can branch on it and the keep-alive redial loop can park. A\n * reject without an id (an older peer,\n * whose frames never carry one) becomes `handshake_rejected` — same message text, now typed, so\n * `classifyConnectFailure` can tell \"the backend said no\" from \"wrong address\" (feedback W3).\n */\nexport function handshakeRejectError(stage: string, rejectFrame: THsReject): Error {\n  if (rejectFrame.id === HANDSHAKE_REJECT_ID_PIN_MISMATCH) {\n    return err_wire_connect.fromId(\"identity_pin_mismatch\", { reason: rejectFrame.reason });\n  }\n  if (rejectFrame.id === HANDSHAKE_REJECT_ID_PROTOCOL_VERSION_MISMATCH) {\n    const observedProtocolVersion = sanitizeVersions(\n      rejectFrame.observedProtocolVersion == null\n        ? undefined\n        : [rejectFrame.observedProtocolVersion],\n    )?.[0];\n    return err_wire_connect.fromId(\"protocol_version_mismatch\", {\n      reason: rejectFrame.reason,\n      observedProtocolVersion,\n      localSupportedProtocolVersions: [...WIRE_SUPPORTED_PROTOCOL_VERSIONS],\n      remoteSupportedProtocolVersions: sanitizeVersions(rejectFrame.supportedProtocolVersions),\n    });\n  }\n  return err_wire_connect.fromId(\"handshake_rejected\", { stage, reason: rejectFrame.reason });\n}\n","import { unrefTimer } from \"@nice-code/util\";\nimport type { IDuplexCarrier, TFrame } from \"../Carrier/Carrier.types\";\nimport { createActionFrameCrypto, type IActionFrameCrypto } from \"../crypto/actionFrameCrypto\";\nimport {\n  createClientHandshake,\n  decodeHandshakeMessage,\n  EHandshakeMessageType,\n  ESecurityLevel,\n  encodeHandshakeMessage,\n  type THandshakeMessage,\n} from \"../crypto/actionHandshake\";\nimport { peekProtocolPrefix, protocolsFromCaps } from \"../Mux/protocolFrame\";\nimport type { WireProtocolMux } from \"../Mux/WireProtocolMux\";\nimport { createFrameCryptoPipe, type IFrameCryptoPipe } from \"../SecureSession/frameCryptoPipe\";\nimport { type TWireTapFn, wireFrameByteSize } from \"../tap/wireTap\";\nimport type {\n  IWireLaneEndpoint,\n  IWireLanePort,\n  IWireLaneProtocol,\n  IWireSecureClientConfig,\n} from \"./Connect.types\";\nimport { describeNonProtocolBody } from \"./endpointEvidence\";\nimport { err_wire_connect } from \"./err_wire_connect\";\nimport { handshakeRejectError } from \"./handshakeRejectError\";\nimport { sanitizeEndpoint } from \"./sanitizeEndpoint\";\n\nconst HANDSHAKE_TIMEOUT_MS = 15_000;\nconst LINK_HANDSHAKE_STAGE = \"link-handshake\";\nconst AWAITING_WELCOME = \"a welcome frame\";\nconst AWAITING_ACCEPT = \"an accept frame\";\n\n/** One pending wait for the peer's next handshake message. */\ninterface IHandshakeWaiter {\n  awaiting: string;\n  resolve(message: THandshakeMessage): void;\n  reject(error: Error): void;\n}\n\n/** The duplex twin of the exchange path's `nonProtocolReply` — same typed id, so a consumer's\n * `kind` branch means the same thing whichever carrier served the dial. */\nfunction wrongHandshakeFrame(\n  channel: IDuplexCarrier,\n  expected: string,\n  receivedKind: string,\n): Error {\n  return err_wire_connect.fromId(\"endpoint_answered_non_protocol\", {\n    stage: LINK_HANDSHAKE_STAGE,\n    expected,\n    url: sanitizeEndpoint(channel.label),\n    receivedKind: `hs/${receivedKind}`,\n  });\n}\n\n/** The literal wire keepalive frames — the acceptor answers raw, before any session dispatch. */\nconst KEEPALIVE_PING = \"ping\";\nconst KEEPALIVE_PONG = \"pong\";\n\n/**\n * Wire-level link keepalive — the client half of the\n * acceptor's `\"ping\"`→`\"pong\"` answer: after `idleMs` with **no inbound frame**, send a raw\n * `\"ping\"`; if nothing (pong or otherwise) arrives within `pongTimeoutMs`, close the carrier\n * locally — converting a *half-open* socket (browser offline, NAT death: `isOpen()` true, sends\n * into the void) into the ordinary close → auto-redial path, for every protocol on the link at\n * once. A busy link never pings; outbound traffic deliberately does NOT count as liveness (sends\n * \"succeed\" locally on a half-open socket — that's the failure mode being detected).\n */\nexport interface IWireHeartbeat {\n  /** Quiet window (no inbound frame) before a ping is sent. */\n  idleMs: number;\n  /** How long after the ping to wait for ANY inbound frame before declaring the link half-open. */\n  pongTimeoutMs: number;\n}\n\n/** @deprecated Use `IWireHeartbeat`. */\nexport type IWireLinkKeepalive = IWireHeartbeat;\n\n/** One keepalive loop per live link — created by the session, stopped with it. */\nfunction startHeartbeat(\n  channel: IDuplexCarrier,\n  config: IWireHeartbeat,\n  tap?: TWireTapFn,\n): { noteInbound(): void; stop(): void } {\n  let lastInboundAt = Date.now();\n  let pingSentAt: number | undefined;\n  let timer: ReturnType<typeof setTimeout> | undefined;\n  let stopped = false;\n\n  const arm = (delayMs: number): void => {\n    timer = setTimeout(tick, delayMs);\n    unrefTimer(timer);\n  };\n\n  const tick = (): void => {\n    if (stopped || !channel.isOpen()) return; // closed under us — the close handler owns cleanup\n    if (pingSentAt != null) {\n      // The ping's window elapsed with zero inbound (noteInbound would have cleared it): the\n      // link is half-open. A local close fires the ordinary onClose → disconnect fan-out →\n      // keep-alive redial — no new reconnect path (8b.3's whole point).\n      channel.close();\n      return;\n    }\n    const idleFor = Date.now() - lastInboundAt;\n    if (idleFor >= config.idleMs) {\n      pingSentAt = Date.now();\n      try {\n        channel.send(KEEPALIVE_PING); // raw text — the acceptor answers before any dispatch\n        tap?.({ dir: \"out\", bytes: KEEPALIVE_PING.length, lane: \"keepalive\" });\n      } catch {\n        // send threw ⇒ the socket is already dying; the pong window converts it to a close\n      }\n      arm(config.pongTimeoutMs);\n    } else {\n      arm(config.idleMs - idleFor);\n    }\n  };\n\n  arm(config.idleMs);\n  return {\n    /** Any inbound frame is liveness — it refreshes the idle clock and satisfies a pending ping. */\n    noteInbound: (): void => {\n      lastInboundAt = Date.now();\n      pingSentAt = undefined;\n    },\n    stop: (): void => {\n      stopped = true;\n      if (timer != null) clearTimeout(timer);\n    },\n  };\n}\n\n/**\n * Connector-side (dial-out) duplex session over an {@link IDuplexCarrier} — the wire half of what\n * used to be nice-action's `establishLinkSession` (shared connection design, Phase 2; lane\n * protocol formalized at Phase 5). Owns everything between \"carrier attached\" and \"lane frames\n * flow\": the client handshake (with its message pump + timeout), the frame-crypto pipe, pre-ready\n * frame buffering, the protocol mux bind/detach, and the disconnect-listener fan-out. What it\n * does NOT own is the lane: every decrypted inbound frame the mux doesn't claim goes to the\n * {@link IWireLaneEndpoint} verbatim (E5 — the lane's namespace is \"everything unprefixed\"), the\n * lane supplies the handshake payload via {@link IWireLaneProtocol.handshakeConfig}, and its\n * `onDetach` fires when the channel closes (after the disconnect listeners, matching the\n * pre-split abort ordering).\n */\nexport interface IWireDuplexSessionContext {\n  channel: IDuplexCarrier;\n}\n\n/** The live session the lane talks through once establishment completes. */\nexport interface IWireDuplexSession {\n  /** Send one lane frame (encrypted + ordered by the pipe at the `encrypted` level). */\n  send(frame: TFrame): void;\n  isOpen(): boolean;\n  /** Deliberately close the underlying carrier (the close handler still runs cleanup). */\n  close(): void;\n  addOnDisconnectListener(listener: () => void): void;\n  /** The peer's negotiated caps; `undefined` on the plain path (no caps negotiation). */\n  readonly remoteCaps?: readonly string[];\n  /**\n   * Attach the mux to this link (idempotent; a closed link never attaches). Only needed when the\n   * session was built with `deferMuxAttach` — until then inbound protocol frames wait in order.\n   */\n  attachMux?(): void;\n}\n\n/** One link's hold on the shared mux: inbound protocol dispatch, plus attach on demand. */\ninterface IMuxBinding {\n  readonly mux: WireProtocolMux;\n  /** `true` when the decrypted frame belongs to the mux (dispatched, or held until attach). */\n  dispatch(frame: TFrame): boolean;\n  attach(): void;\n}\n\nfunction bindMux(\n  mux: WireProtocolMux,\n  remoteIds: () => ReadonlySet<string>,\n  pipe: IFrameCryptoPipe,\n  disconnectListeners: (() => void)[],\n  tap: TWireTapFn | undefined,\n): IMuxBinding {\n  let attached = false;\n  let closed = false;\n  const held: TFrame[] = [];\n  // Registered at bind time so the detach keeps its place first in the disconnect fan-out.\n  disconnectListeners.push(() => {\n    closed = true;\n    held.length = 0;\n    if (attached) mux.detach();\n  });\n  return {\n    mux,\n    dispatch: (frame) => {\n      if (attached) return mux.dispatchIncoming(frame);\n      if (peekProtocolPrefix(frame) == null) return false;\n      if (!closed) held.push(frame);\n      return true;\n    },\n    attach: () => {\n      if (attached || closed) return;\n      attached = true;\n      mux.setRemoteProtocolIds(remoteIds());\n      // The tap lane label rides the pipe with the frame: the prefix byte is still readable here,\n      // before encryption, so the eventual write reports the right lane.\n      mux.attach(\n        tap != null\n          ? (bytes) => pipe.send(bytes, mux.protocolIdFor(bytes) ?? \"protocol\")\n          : (bytes) => pipe.send(bytes),\n      );\n      for (const frame of held.splice(0)) mux.dispatchIncoming(frame);\n    },\n  };\n}\n\n/**\n * Wrap a carrier so a **deliberate local** `close()` notifies the session immediately and exactly\n * once, rather than waiting for the platform's close event. On a real WebSocket that event lags a\n * locally-initiated close by seconds against a dead peer, so a fan-out coupled to it — the\n * auto-redial trigger — stalls. Two paths hit exactly that shape: a deliberate teardown\n * (`clearCache()` → `session.close()`) and the half-open keepalive detector's local\n * `channel.close()`. Here a local `close()` fires the session's `onClose` on a **microtask** —\n * immediate enough to heal fast, deferred enough not to re-enter a synchronous teardown loop (the\n * caller may be mid-iteration over its connection cache), and matching the in-memory pair's\n * semantics. The carrier's eventual platform close/error event routes to the same latch and is\n * deduped, so the fan-out (and thus `lane.onDetach`) runs exactly once. (resilience-v2 — Overshot's\n * bare-`dropLink({})` and half-open heal lag.)\n */\nfunction withNotifyingClose(inner: IDuplexCarrier): IDuplexCarrier {\n  let firedClose = false;\n  let sessionOnClose: (() => void) | undefined;\n  const fireClose = (): void => {\n    if (firedClose) return;\n    firedClose = true;\n    sessionOnClose?.();\n  };\n  return {\n    ready: inner.ready,\n    isOpen: () => inner.isOpen(),\n    send: (frame) => inner.send(frame),\n    attach: (handlers) => {\n      sessionOnClose = handlers.onClose;\n      // Collapse the carrier's own close AND error signals into the one latch — either means \"the\n      // carrier is gone\", and firing the fan-out twice would run the disconnect listeners twice.\n      inner.attach({ onMessage: handlers.onMessage, onClose: fireClose, onError: fireClose });\n    },\n    close: () => {\n      inner.close(); // really close the socket now — the peer observes a real close immediately\n      queueMicrotask(fireClose); // notify the session now, not at the platform's leisure\n    },\n    get label() {\n      return inner.label;\n    },\n  };\n}\n\n/**\n * Plain path (no handshake): route every inbound frame to the lane; send without crypto. The\n * lane is the bare {@link IWireLaneEndpoint} — a plain connection negotiates nothing, so there is\n * no handshake config to supply and no `onAttach` fires.\n */\nexport function establishPlainDuplexSession(\n  ctx: IWireDuplexSessionContext & {\n    lane: IWireLaneEndpoint;\n    /**\n     * Optional frame-protocol mux (Phase 2.5): prefixed inbound frames dispatch to it before the\n     * lane, and it attaches to the (plaintext) send path immediately — a plain connection\n     * negotiates nothing, so the mux's remote ids are **assumed** from its own registrations\n     * rather than learned from a handshake. That is safe by construction: the *peer's* side is the\n     * real filter (the acceptor's A.6 security gate admits only `allowPlain` protocols on a plain\n     * connection, and an unregistered prefix is consumed-and-dropped, never mis-decoded).\n     */\n    mux?: WireProtocolMux;\n    /** Hold the mux off this link until `session.attachMux()` (e.g. until selection picks it). */\n    deferMuxAttach?: boolean;\n    heartbeat?: IWireHeartbeat;\n    /** Wire-traffic observation (devtools) — reports every frame's true carrier bytes. */\n    tap?: TWireTapFn;\n  },\n): IWireDuplexSession {\n  const channel = withNotifyingClose(ctx.channel);\n  const disconnectListeners: (() => void)[] = [];\n  const tap = ctx.tap;\n  const pipe = makePipe(channel, undefined, tap);\n  const port = makeLanePort(channel, pipe);\n  const mux = ctx.mux;\n\n  const heartbeat = ctx.heartbeat != null ? startHeartbeat(channel, ctx.heartbeat, tap) : undefined;\n  if (heartbeat != null) disconnectListeners.push(heartbeat.stop);\n\n  // Mux bind — mirrors the secure path, minus the negotiation (there is none to have). Remote ids\n  // are assumed = local registrations, so `port.isOpen()` reflects only the link's own state; the\n  // peer's gate decides what actually lands. Detach on close so protocol `onAttach`/`onDetach`\n  // fire once per link, exactly as on a secure connection.\n  const muxBinding =\n    mux == null\n      ? undefined\n      : bindMux(mux, () => protocolsFromCaps(mux.localCaps()), pipe, disconnectListeners, tap);\n\n  channel.attach({\n    onMessage: (frame) => {\n      heartbeat?.noteInbound();\n      if (frame === KEEPALIVE_PONG) {\n        tap?.({ dir: \"in\", bytes: KEEPALIVE_PONG.length, lane: \"keepalive\" });\n        return; // wire keepalive answer — never a lane/protocol frame\n      }\n      void handleIncomingFrame(pipe, frame, muxBinding, ctx.lane, port, tap);\n    },\n    onClose: () => onChannelClosed(disconnectListeners, ctx.lane),\n    onError: () => onChannelClosed(disconnectListeners, ctx.lane),\n  });\n\n  if (ctx.deferMuxAttach !== true) muxBinding?.attach();\n\n  return makeSession(channel, pipe, disconnectListeners, undefined, muxBinding);\n}\n\n/**\n * Secure path: a single message handler feeds the handshake until it completes, then routes lane\n * frames (decrypting at the `encrypted` level). Frames that race ahead of activation are buffered\n * and flushed once the handshake lands, so nothing is lost. The lane supplies the handshake\n * payload (`dictionaryVersion`/`channels`, E5 — emitted under the byte-frozen wire names; the\n * version is signed into the challenge) and gets `onAttach` with the negotiated caps before any\n * buffered frame is delivered.\n */\nexport async function establishSecureDuplexSession(\n  ctx: IWireDuplexSessionContext & {\n    secure: IWireSecureClientConfig;\n    /** The lane protocol (E5) — handshake payload supplier + unprefixed-frame consumer. */\n    lane: IWireLaneProtocol;\n    /**\n     * Optional frame-protocol mux: its registered protocols are advertised as `proto:<id>`\n     * handshake caps, prefixed frames dispatch to it before the lane, and it attaches to the\n     * (encrypting) send path once the handshake lands.\n     */\n    mux?: WireProtocolMux;\n    /** Hold the mux off this link until `session.attachMux()` (e.g. until selection picks it). */\n    deferMuxAttach?: boolean;\n    /** Half-open detection (8b.3) — armed only after the handshake completes. */\n    heartbeat?: IWireHeartbeat;\n    /** Wire-traffic observation (devtools) — reports every frame's true carrier bytes. */\n    tap?: TWireTapFn;\n  },\n): Promise<IWireDuplexSession> {\n  const channel = withNotifyingClose(ctx.channel);\n  const disconnectListeners: (() => void)[] = [];\n  const tap = ctx.tap;\n\n  // Holder so the (synchronously-attached) message handler can reach the pipe once the handshake\n  // builds it, without a single-assignment `let`.\n  const session: { pipe?: IFrameCryptoPipe; port?: IWireLanePort; muxBinding?: IMuxBinding } = {};\n  let active = false;\n  const handshakeQueue: THandshakeMessage[] = [];\n  const handshakeWaiters: IHandshakeWaiter[] = [];\n  // Latched by the carrier's close or error: a wait that starts afterwards rejects at once.\n  let carrierClosed = false;\n  const pendingFrames: TFrame[] = [];\n  // The first text frame that arrived mid-handshake and was *not* a handshake message. A server\n  // that is not nice-wire (a WAF login page, a different protocol) leaves exactly this trace, and\n  // it is better evidence than \"closed\" or \"timed out\".\n  let nonProtocolFrame: string | undefined;\n  // Armed post-handshake (never ping mid-handshake); the handler below still notes inbound from\n  // frame one, so the reference lives here.\n  let heartbeat: { noteInbound(): void; stop(): void } | undefined;\n\n  const unansweredError = (awaiting: string, cause: \"closed\" | \"timeout\"): Error => {\n    const url = sanitizeEndpoint(channel.label);\n    if (nonProtocolFrame != null) {\n      return err_wire_connect.fromId(\"endpoint_answered_non_protocol\", {\n        stage: LINK_HANDSHAKE_STAGE,\n        expected: awaiting,\n        url,\n        bodyPreview: describeNonProtocolBody(nonProtocolFrame),\n      });\n    }\n    return cause === \"closed\"\n      ? err_wire_connect.fromId(\"closed_during_handshake\", {\n          stage: LINK_HANDSHAKE_STAGE,\n          awaiting,\n          url,\n        })\n      : err_wire_connect.fromId(\"handshake_timeout\", {\n          stage: LINK_HANDSHAKE_STAGE,\n          awaiting,\n          timeoutMs: HANDSHAKE_TIMEOUT_MS,\n          url,\n        });\n  };\n\n  const onCarrierClosed = (): void => {\n    carrierClosed = true;\n    for (const waiter of handshakeWaiters.splice(0)) {\n      waiter.reject(unansweredError(waiter.awaiting, \"closed\"));\n    }\n    onChannelClosed(disconnectListeners, ctx.lane);\n  };\n\n  const mux = ctx.mux;\n  channel.attach({\n    onMessage: (frame) => {\n      heartbeat?.noteInbound();\n      if (frame === KEEPALIVE_PONG) {\n        tap?.({ dir: \"in\", bytes: KEEPALIVE_PONG.length, lane: \"keepalive\" });\n        return; // wire keepalive answer — never a session frame\n      }\n      if (active && session.pipe != null && session.port != null) {\n        void handleIncomingFrame(\n          session.pipe,\n          frame,\n          session.muxBinding,\n          ctx.lane,\n          session.port,\n          tap,\n        );\n        return;\n      }\n      // Handshake phase: text frames are control messages; buffer anything else for after activation.\n      if (typeof frame === \"string\") {\n        const message = decodeHandshakeMessage(frame);\n        if (message != null) {\n          tap?.({ dir: \"in\", bytes: wireFrameByteSize(frame), lane: \"handshake\" });\n          const waiter = handshakeWaiters.shift();\n          if (waiter != null) waiter.resolve(message);\n          else handshakeQueue.push(message);\n          return;\n        }\n        nonProtocolFrame ??= frame;\n      }\n      pendingFrames.push(frame);\n    },\n    onClose: onCarrierClosed,\n    onError: onCarrierClosed,\n  });\n\n  const nextHandshakeMessage = (awaiting: string): Promise<THandshakeMessage> => {\n    // A frame that arrived before the close is still the peer's answer: it is read first.\n    const queued = handshakeQueue.shift();\n    if (queued != null) return Promise.resolve(queued);\n    if (carrierClosed) return Promise.reject(unansweredError(awaiting, \"closed\"));\n    return new Promise<THandshakeMessage>((resolve, reject) => {\n      const timeout = setTimeout(() => {\n        const index = handshakeWaiters.indexOf(waiter);\n        if (index !== -1) handshakeWaiters.splice(index, 1);\n        reject(unansweredError(awaiting, \"timeout\"));\n      }, HANDSHAKE_TIMEOUT_MS);\n      const waiter: IHandshakeWaiter = {\n        awaiting,\n        resolve: (message) => {\n          clearTimeout(timeout);\n          resolve(message);\n        },\n        reject: (error) => {\n          clearTimeout(timeout);\n          reject(error);\n        },\n      };\n      handshakeWaiters.push(waiter);\n    });\n  };\n\n  try {\n    const { crypto, remoteCaps } = await runClientHandshake(\n      { ...ctx, channel },\n      nextHandshakeMessage,\n    );\n    const pipe = makePipe(channel, crypto, tap);\n    const port = makeLanePort(channel, pipe);\n    session.pipe = pipe;\n    session.port = port;\n\n    // Bind the frame-protocol mux: negotiated protocols may speak through the same\n    // (encrypting) pipe lane frames use; detach rides the connection's disconnect listeners.\n    const muxBinding =\n      mux == null\n        ? undefined\n        : bindMux(mux, () => protocolsFromCaps(remoteCaps), pipe, disconnectListeners, tap);\n    session.muxBinding = muxBinding;\n    if (ctx.deferMuxAttach !== true) muxBinding?.attach();\n\n    // The lane attaches with the negotiated outcome BEFORE any buffered frame is delivered.\n    ctx.lane.onAttach?.(port, { remoteCaps: remoteCaps ?? [] });\n\n    active = true;\n    for (const frame of pendingFrames) {\n      await handleIncomingFrame(pipe, frame, muxBinding, ctx.lane, port, tap);\n    }\n    pendingFrames.length = 0;\n\n    // Arm the keepalive only now — a handshake in flight must never be pinged over (8b.3).\n    if (ctx.heartbeat != null) {\n      heartbeat = startHeartbeat(channel, ctx.heartbeat, tap);\n      disconnectListeners.push(heartbeat.stop);\n    }\n\n    return makeSession(channel, pipe, disconnectListeners, remoteCaps, muxBinding);\n  } catch (error) {\n    // A dial that never became a session must not keep its socket (or the peer's) open.\n    closeQuietly(channel);\n    throw error;\n  }\n}\n\nfunction makePipe(\n  channel: IDuplexCarrier,\n  crypto: IActionFrameCrypto | undefined,\n  tap: TWireTapFn | undefined,\n): IFrameCryptoPipe {\n  return createFrameCryptoPipe({\n    // The one write every session frame funnels through — measured HERE, after encryption, so the\n    // tap reports the frame exactly as the carrier transmits it. `tapLane` rode the pipe from the\n    // producer (mux protocol frames label themselves; everything else is the action lane).\n    write:\n      tap != null\n        ? (frame, tapLane) => {\n            tap({ dir: \"out\", bytes: wireFrameByteSize(frame), lane: tapLane ?? \"action\" });\n            channel.send(frame);\n          }\n        : (frame) => channel.send(frame),\n    isOpen: () => channel.isOpen(),\n    crypto,\n  });\n}\n\n/** The lane's talk-back surface: raw sends through the (possibly encrypting) pipe, no prefixing. */\nfunction makeLanePort(channel: IDuplexCarrier, pipe: IFrameCryptoPipe): IWireLanePort {\n  return {\n    send: (frame) => pipe.send(frame),\n    isOpen: () => channel.isOpen(),\n  };\n}\n\nfunction closeQuietly(channel: IDuplexCarrier): void {\n  try {\n    channel.close();\n  } catch {\n    // already closing/closed — the close handler still runs cleanup\n  }\n}\n\nfunction makeSession(\n  channel: IDuplexCarrier,\n  pipe: IFrameCryptoPipe,\n  disconnectListeners: (() => void)[],\n  remoteCaps: readonly string[] | undefined,\n  muxBinding: IMuxBinding | undefined,\n): IWireDuplexSession {\n  return {\n    send: (frame) => pipe.send(frame),\n    isOpen: () => channel.isOpen(),\n    close: () => closeQuietly(channel),\n    addOnDisconnectListener: (listener) => {\n      disconnectListeners.push(listener);\n    },\n    remoteCaps,\n    attachMux: muxBinding == null ? undefined : () => muxBinding.attach(),\n  };\n}\n\nasync function runClientHandshake(\n  ctx: {\n    channel: IDuplexCarrier;\n    secure: IWireSecureClientConfig;\n    lane: IWireLaneProtocol;\n    mux?: WireProtocolMux;\n    tap?: TWireTapFn;\n  },\n  nextHandshakeMessage: (awaiting: string) => Promise<THandshakeMessage>,\n): Promise<{\n  crypto: IActionFrameCrypto | undefined;\n  remoteCaps: readonly string[] | undefined;\n}> {\n  const secure = ctx.secure;\n  const sendHandshake = (encoded: string): void => {\n    // A carrier that already closed takes no frame (some throw on the attempt): the wait that\n    // follows reports the close.\n    if (!ctx.channel.isOpen()) return;\n    ctx.channel.send(encoded);\n    ctx.tap?.({ dir: \"out\", bytes: wireFrameByteSize(encoded), lane: \"handshake\" });\n  };\n  await secure.link.initialize();\n\n  // The lane supplies the handshake payload (E5) — wire threads it through opaquely under the\n  // byte-frozen wire names. Lane caps (if any) ride ahead of the protocol caps; the lane's\n  // `reliable`/`reliable-streamkey` defaults stay baked into the handshake machine (byte-frozen).\n  const handshakeConfig = ctx.lane.handshakeConfig();\n  const handshake = createClientHandshake({\n    link: secure.link,\n    localCoordinate: secure.localCoordinate,\n    expectedPeer: secure.expectedPeer,\n    dictionaryVersion: handshakeConfig.dictionaryVersion,\n    securityLevel: secure.securityLevel,\n    channelTags: handshakeConfig.channels,\n    extraCaps: [...(ctx.lane.caps?.() ?? []), ...(ctx.mux?.localCaps() ?? [])],\n  });\n\n  sendHandshake(encodeHandshakeMessage(await handshake.createHello()));\n\n  const welcome = await nextHandshakeMessage(AWAITING_WELCOME);\n  if (welcome.t === EHandshakeMessageType.reject) {\n    throw handshakeRejectError(LINK_HANDSHAKE_STAGE, welcome);\n  }\n  if (welcome.t !== EHandshakeMessageType.welcome) {\n    throw wrongHandshakeFrame(ctx.channel, AWAITING_WELCOME, welcome.t);\n  }\n\n  sendHandshake(encodeHandshakeMessage(await handshake.onWelcome(welcome)));\n\n  const accept = await nextHandshakeMessage(AWAITING_ACCEPT);\n  if (accept.t === EHandshakeMessageType.reject) {\n    throw handshakeRejectError(LINK_HANDSHAKE_STAGE, accept);\n  }\n  if (accept.t !== EHandshakeMessageType.accept) {\n    throw wrongHandshakeFrame(ctx.channel, AWAITING_ACCEPT, accept.t);\n  }\n\n  const result = await handshake.onAccept(accept);\n  const crypto =\n    result.securityLevel === ESecurityLevel.encrypted && result.encryptionKeyMaterial != null\n      ? createActionFrameCrypto({ link: secure.link, keyMaterial: result.encryptionKeyMaterial })\n      : undefined;\n  return { crypto, remoteCaps: result.remoteCaps };\n}\n\n/** Decrypt → mux dispatch → the lane. Awaited by the pre-ready flush so frame order holds. */\nasync function handleIncomingFrame(\n  pipe: IFrameCryptoPipe,\n  frame: TFrame,\n  muxBinding: IMuxBinding | undefined,\n  lane: IWireLaneEndpoint,\n  port: IWireLanePort,\n  tap?: TWireTapFn,\n): Promise<void> {\n  // Measured pre-decrypt: the size as the carrier received it (true wire bytes); the lane label\n  // comes from the dispatch below, once the decrypted frame reveals where it belongs.\n  const wireBytes = tap != null ? wireFrameByteSize(frame) : 0;\n  const decoded = await pipe.decryptIncoming(frame);\n  if (decoded === undefined) return;\n\n  // Frame-protocol dispatch (M1): a reserved-prefix frame (`0x00`–`0x0F`) belongs to a registered\n  // protocol riding this connection (realm, …) and never falls through to the lane.\n  if (muxBinding?.dispatch(decoded)) {\n    tap?.({\n      dir: \"in\",\n      bytes: wireBytes,\n      lane: muxBinding.mux.protocolIdFor(decoded) ?? \"protocol\",\n    });\n    return;\n  }\n\n  tap?.({ dir: \"in\", bytes: wireBytes, lane: \"action\" });\n  await lane.onLaneFrame(decoded, port);\n}\n\n/** Disconnect fan-out order (pre-split contract): mux detach → external listeners → the lane. */\nfunction onChannelClosed(disconnectListeners: (() => void)[], lane: IWireLaneEndpoint): void {\n  for (const cb of disconnectListeners) cb();\n  lane.onDetach?.();\n}\n","import { err_wire_connect } from \"./err_wire_connect\";\n\n/**\n * The one check before a secure transport dials. A browser gives `crypto.subtle` only to a secure\n * context (HTTPS, or localhost), and some runtimes ship none until a polyfill is installed; either\n * way the handshake cannot run, and no retry will change that.\n */\nexport function assertWebCryptoAvailable(): void {\n  // Read through a widened view: the DOM types promise `crypto.subtle` always exists.\n  const runtime: {\n    crypto?: { subtle?: unknown };\n    isSecureContext?: boolean;\n    location?: { origin?: string };\n  } = globalThis;\n  if (runtime.crypto?.subtle != null) return;\n  if (runtime.isSecureContext === false) {\n    throw err_wire_connect.fromId(\"crypto_unavailable\", {\n      reason: \"insecure_context\",\n      pageOrigin: runtime.location?.origin,\n    });\n  }\n  throw err_wire_connect.fromId(\"crypto_unavailable\", { reason: \"no_webcrypto\" });\n}\n","import type { IWireRouteInfo } from \"./Connect.types\";\nimport {\n  type ETransportShape,\n  ETransportStatus,\n  type IWireConnectionMethodsBase,\n  type IWireTransportDef,\n  type IWireTransportInitialized,\n  type TTransportInitializationFinishedInfo,\n  type TTransportStatusInfo,\n  type TTransportStatusInfo_GetTransport_Output,\n} from \"./transportRuntime.types\";\nimport { assertWebCryptoAvailable } from \"./webCryptoPreflight\";\n\nlet transportOrd = 0;\n\n/**\n * The stateless definition a live {@link TransportConnection} points back at — used for devtools\n * route info. nice-action's `Transport` definition class satisfies this structurally; wire never\n * needs the definition's construction side (building connections binds lane resolvers, which is\n * the protocol module's job).\n */\nexport interface IWireTransportDefinition<RP> {\n  getRouteInfo(input: RP): IWireRouteInfo | undefined;\n}\n\n/**\n * Live, per-handler transport runtime built from a reusable transport definition. Holds the\n * connection-scoped state (ordinal, initialized config, sockets / abort sets) that must not be shared\n * across handlers. Moved from nice-action with the action types\n * inverted into generics: `RP` (per-dispatch routing params), `RD` (the raw ready-data a definition\n * yields), and `METHODS` (the finalized send surface subclasses build) are opaque to wire.\n */\nexport abstract class TransportConnection<\n  T extends ETransportShape = ETransportShape,\n  RP = unknown,\n  RD = unknown,\n  METHODS extends IWireConnectionMethodsBase = IWireConnectionMethodsBase,\n  I extends IWireTransportInitialized<RP, RD> = IWireTransportInitialized<RP, RD>,\n  DEF extends IWireTransportDef<T, I> = IWireTransportDef<T, I>,\n> {\n  readonly transOrd = transportOrd++;\n  readonly type: T;\n  readonly initialized: I;\n\n  /** Backref to the public definition that created this connection (used for devtools route info). */\n  definition?: IWireTransportDefinition<RP>;\n\n  constructor(readonly def: DEF) {\n    this.type = def.type;\n    this.initialized = def.initialize();\n  }\n\n  /**\n   * Devtools route info for a dispatch routed through this live connection. Defaults to the stateless\n   * {@link definition}'s info; connections override to enrich it from live state (e.g. the actual\n   * resolved socket URL) when the definition couldn't resolve it on its own.\n   */\n  getRouteInfo(input: RP): IWireRouteInfo | undefined {\n    return this.definition?.getRouteInfo(input);\n  }\n\n  /**\n   * Build the live send/receive methods from a `ready` readyData, synchronously. This is the plain\n   * (no-handshake) path and the only required per-transport hook. Stream carriers that must await the\n   * carrier opening and/or run a handshake additionally override {@link _needsAsyncBringUp},\n   * {@link _awaitCarrierReady}, and {@link _finalizeReady}.\n   */\n  protected abstract _finalizeTransportMethods(inputs: RD): METHODS;\n\n  /**\n   * Whether a `ready`-status transport still needs asynchronous bring-up before its methods exist —\n   * awaiting the carrier to open and/or running a handshake. Default `false`: a stateless transport\n   * (HTTP) is usable the instant `getTransport` reports `ready`, so it stays a terminal *synchronous*\n   * fallback in the selection manager. Stream carriers (Link/WS) override to `true`.\n   */\n  protected _needsAsyncBringUp(_readyData: RD): boolean {\n    return false;\n  }\n\n  /** Await the carrier becoming ready to send (e.g. a socket `open`). Default: nothing to await. */\n  protected _awaitCarrierReady(_readyData: RD): Promise<void> {\n    return Promise.resolve();\n  }\n\n  /**\n   * Finalize during async bring-up — may run a handshake, so it can be async. Defaults to the\n   * synchronous {@link _finalizeTransportMethods}; secure stream carriers override to branch plain/secure.\n   */\n  protected _finalizeReady(readyData: RD): METHODS | Promise<METHODS> {\n    return this._finalizeTransportMethods(readyData);\n  }\n\n  protected _getCacheKey(input: RP): string | null {\n    const parts = this.initialized.getCacheKey?.(input);\n    if (parts == null) return null;\n    return parts.join(\"\\x00\");\n  }\n\n  getCacheKey(input: RP): string | null {\n    const inner = this._getCacheKey(input);\n    if (inner == null) return null;\n    return `${this.transOrd}:${inner}`;\n  }\n\n  /**\n   * Whether this transport can serve the given dispatch right now. Consulted by the manager before\n   * cache-key resolution and `getTransport`; a `false` result skips this transport (treated as\n   * `unsupported`) and the manager falls through to the next in preference order. Defaults to `true`\n   * when the transport declares no gate.\n   */\n  isAvailable(input: RP): boolean {\n    return this.initialized.isAvailable?.(input) ?? true;\n  }\n\n  getTransport(input: RP): TTransportStatusInfo<METHODS> {\n    return this._processTransportStatus(input);\n  }\n\n  protected _processTransportStatus(input: RP): TTransportStatusInfo<METHODS> {\n    if (this.initialized.requiresWebCrypto === true) assertWebCryptoAvailable();\n    const statusInfo = addTransportStatusMetadata(this.initialized.getTransport(input));\n\n    if (statusInfo.status === ETransportStatus.ready) {\n      // Already-usable + stateless → finalize synchronously (terminal fallback). Otherwise report\n      // `initializing` and bring the carrier up (await open, run handshake) off the dispatch path.\n      if (!this._needsAsyncBringUp(statusInfo.readyData)) {\n        return {\n          status: ETransportStatus.ready,\n          readyData: this._finalizeTransportMethods(statusInfo.readyData),\n        };\n      }\n      return {\n        status: ETransportStatus.initializing,\n        timeStarted: Date.now(),\n        initializationPromise: this._bringUp(statusInfo.readyData),\n      };\n    }\n\n    if (statusInfo.status === ETransportStatus.initializing) {\n      const initializationPromise: Promise<TTransportInitializationFinishedInfo<METHODS>> =\n        statusInfo.initializationPromise.then((result) =>\n          result.status === ETransportStatus.ready ? this._bringUp(result.readyData) : result,\n        );\n      return {\n        status: ETransportStatus.initializing,\n        timeStarted: statusInfo.timeStarted,\n        initializationPromise,\n      };\n    }\n\n    // unsupported / failed / uninitialized — pass through.\n    return statusInfo;\n  }\n\n  /** Await carrier readiness, then finalize (possibly running a handshake) into the live methods. */\n  private async _bringUp(readyData: RD): Promise<TTransportInitializationFinishedInfo<METHODS>> {\n    await this._awaitCarrierReady(readyData);\n    return {\n      status: ETransportStatus.ready,\n      readyData: await this._finalizeReady(readyData),\n    };\n  }\n}\n\n/** Stamp the wall-clock metadata a definition's raw status output omits. */\nexport function addTransportStatusMetadata<READY>(\n  transportStatus: TTransportStatusInfo_GetTransport_Output<READY>,\n): TTransportStatusInfo<READY> {\n  if (transportStatus.status === ETransportStatus.ready) {\n    return {\n      status: ETransportStatus.ready,\n      readyData: transportStatus.readyData,\n    };\n  }\n\n  if (transportStatus.status === ETransportStatus.initializing) {\n    return {\n      status: ETransportStatus.initializing,\n      initializationPromise: transportStatus.initializationPromise,\n      timeStarted: Date.now(),\n    };\n  }\n\n  if (transportStatus.status === ETransportStatus.failed) {\n    return {\n      status: ETransportStatus.failed,\n      error: transportStatus.error,\n      timeFailed: Date.now(),\n    };\n  }\n\n  if (transportStatus.status === ETransportStatus.unsupported) {\n    return {\n      status: ETransportStatus.unsupported,\n    };\n  }\n\n  return {\n    status: ETransportStatus.uninitialized,\n  };\n}\n","import type { TFrame } from \"../Carrier/Carrier.types\";\nimport {\n  encodeProtocolFrame,\n  peekProtocolPrefix,\n  protocolCap,\n  WIRE_PROTOCOL_PREFIX,\n  WIRE_PROTOCOL_PREFIX_MAX,\n} from \"./protocolFrame\";\n\n/**\n * The frame-protocol multiplex seam (realm protocol design §3 / M1). One secure connection carries several\n * protocols: frames with a reserved prefix byte (`0x01`–`0x0F`) dispatch to the registered\n * protocol; everything else falls through to the host transport's legacy sniffing\n * (handshake / control / action — byte-identical, pinned by the byte-compat goldens).\n *\n * The mux itself knows nothing about realms or actions. The **host transport** (today:\n * nice-action's connector link session + acceptor handler) owns it and calls:\n * - `dispatchIncoming(frame)` first on every decrypted/plain inbound frame — `true` = consumed;\n * - `localCaps()` when building its handshake hello/welcome caps;\n * - `setRemoteCaps(caps)` when the peer's handshake arrives;\n * - `attach(send)` once the connection can carry frames (post-handshake), `detach()` on close.\n *\n * Protocols (realm's client/server engines) register via {@link registerProtocol} and speak only\n * through their {@link IWireProtocolPort}.\n */\n\n/** What a registered protocol receives to talk on the shared connection. */\nexport interface IWireProtocolPort {\n  /** Send one protocol payload (prefix added here; encrypted by the host when secure). */\n  send(payload: Uint8Array): void;\n  /** Whether the connection is attached and the peer advertised this protocol. */\n  isOpen(): boolean;\n}\n\n/** A protocol registration (realm protocol design §3.2). */\nexport interface IWireFrameProtocol {\n  /** Stable id — advertised in handshake caps as `proto:<id>`. */\n  readonly id: string;\n  /** Reserved prefix byte from {@link WIRE_PROTOCOL_PREFIX}. */\n  readonly prefixByte: number;\n  /** One inbound protocol payload (prefix already stripped). */\n  onFrame(payload: Uint8Array, port: IWireProtocolPort): void;\n  /** Connection (re)established for this protocol — peer advertised it, frames may flow. */\n  onAttach?(port: IWireProtocolPort): void;\n  /** Connection lost — the protocol handles its own resume on the next attach. */\n  onDetach?(): void;\n}\n\ninterface IRegisteredProtocol {\n  protocol: IWireFrameProtocol;\n  port: IWireProtocolPort;\n}\n\nexport class WireProtocolMux {\n  private readonly _byPrefix = new Map<number, IRegisteredProtocol>();\n  private _send: ((frame: Uint8Array) => void) | undefined;\n  private _remoteProtocolIds: ReadonlySet<string> = new Set();\n  private _attached = false;\n\n  /** Register a protocol (before or after attach; late registrants get an immediate attach). */\n  registerProtocol(protocol: IWireFrameProtocol): IWireProtocolPort {\n    if (this._attached) {\n      // A.2.2: the handshake advertised `localCaps()` when the\n      // connection came up, and the acceptor persisted them on the binding — a protocol\n      // registered after attach is NOT in that list, so a hibernation-woken host will not re-fire\n      // its lifecycle (the \"rehello\" wake resume). Live traffic still flows, which is what makes\n      // this bug silent. Register at construction (connectChannel `protocols`, or before\n      // `connect()` / the first dispatch).\n      console.warn(\n        `[wire] registerProtocol(\"${protocol.id}\"): the connection is already attached — this protocol missed the handshake's caps advertisement and will not be resumed after a host wake. Register it before connecting.`,\n      );\n    }\n    if (\n      protocol.prefixByte <= WIRE_PROTOCOL_PREFIX.invalid ||\n      protocol.prefixByte > WIRE_PROTOCOL_PREFIX_MAX\n    ) {\n      throw new Error(\n        `registerProtocol(\"${protocol.id}\"): prefix 0x${protocol.prefixByte.toString(16)} outside the reserved range`,\n      );\n    }\n    if (this._byPrefix.has(protocol.prefixByte)) {\n      throw new Error(\n        `registerProtocol(\"${protocol.id}\"): prefix 0x${protocol.prefixByte.toString(16)} already registered`,\n      );\n    }\n    const port: IWireProtocolPort = {\n      send: (payload) => {\n        if (!this._canSpeak(protocol)) {\n          throw new Error(\n            `protocol \"${protocol.id}\": connection not attached or peer did not advertise \"${protocolCap(protocol.id)}\"`,\n          );\n        }\n        this._send?.(encodeProtocolFrame(protocol.prefixByte, payload));\n      },\n      isOpen: () => this._canSpeak(protocol),\n    };\n    this._byPrefix.set(protocol.prefixByte, { protocol, port });\n    if (this._attached && this._canSpeak(protocol)) protocol.onAttach?.(port);\n    return port;\n  }\n\n  /** The `proto:<id>` caps to advertise in this side's handshake. */\n  localCaps(): string[] {\n    return [...this._byPrefix.values()].map(({ protocol }) => protocolCap(protocol.id));\n  }\n\n  /** Record the peer's advertised protocol ids (from its handshake caps). */\n  setRemoteProtocolIds(ids: ReadonlySet<string>): void {\n    this._remoteProtocolIds = ids;\n  }\n\n  /** Connection ready: give protocols their send path and fire attach for negotiated ones. */\n  attach(send: (frame: Uint8Array) => void): void {\n    this._send = send;\n    this._attached = true;\n    for (const { protocol, port } of this._byPrefix.values()) {\n      if (this._canSpeak(protocol)) protocol.onAttach?.(port);\n    }\n  }\n\n  /** Connection lost: notify protocols; sends now throw until the next attach. */\n  detach(): void {\n    if (!this._attached) return;\n    this._attached = false;\n    this._send = undefined;\n    for (const { protocol } of this._byPrefix.values()) protocol.onDetach?.();\n  }\n\n  /**\n   * The registered protocol id a frame belongs to, by its prefix byte — `undefined` for a legacy\n   * (unprefixed) frame or an unregistered prefix. Attribution only (the wire-tap lane label);\n   * dispatch stays with {@link dispatchIncoming}.\n   */\n  protocolIdFor(frame: TFrame): string | undefined {\n    const prefix = peekProtocolPrefix(frame);\n    if (prefix == null) return undefined;\n    return this._byPrefix.get(prefix)?.protocol.id;\n  }\n\n  /**\n   * Offer one inbound (already-decrypted) frame. Returns `true` when consumed as a protocol\n   * frame — including an unknown/unregistered prefix, which is dropped (a prefixed frame is\n   * *never* a legacy frame, so falling through would mis-decode it).\n   */\n  dispatchIncoming(frame: TFrame): boolean {\n    const prefix = peekProtocolPrefix(frame);\n    if (prefix == null) return false;\n    const registered = this._byPrefix.get(prefix);\n    if (prefix === WIRE_PROTOCOL_PREFIX.invalid || registered == null) {\n      // Consumed-and-dropped: the peer sent a protocol we didn't register (or an invalid 0x00).\n      // Negotiation should prevent this; dropping beats letting the legacy decoders chew on it.\n      return true;\n    }\n    const bytes = frame instanceof Uint8Array ? frame : new Uint8Array(frame as ArrayBuffer);\n    registered.protocol.onFrame(bytes.subarray(1), registered.port);\n    return true;\n  }\n\n  private _canSpeak(protocol: IWireFrameProtocol): boolean {\n    return this._attached && this._remoteProtocolIds.has(protocol.id);\n  }\n}\n","import { ClientCryptoKeyLink, type StorageAdapter } from \"@nice-code/util\";\nimport { type IWireFrameProtocol, WireProtocolMux } from \"../Mux/WireProtocolMux\";\nimport type { RuntimeCoordinate } from \"../RuntimeCoordinate\";\nimport { type TWireTapFn, withLinkIdTap } from \"../tap/wireTap\";\nimport type { IWireHeartbeat } from \"./duplexLinkSession\";\nimport { err_wire_connect } from \"./err_wire_connect\";\n\n/** 8b.3 defaults: ≈20 s worst-case half-open detection, quiet enough for a healthy idle tab. */\nconst DEFAULT_HEARTBEAT_IDLE_MS = 15_000;\nconst DEFAULT_HEARTBEAT_PONG_TIMEOUT_MS = 5_000;\n\nconst ephemeralIdentityWarned = new Set<string>();\n\nconst linksByStorage = new WeakMap<StorageAdapter, ClientCryptoKeyLink>();\n\n/**\n * The one identity link over a storage: every connection built from the same adapter presents the\n * same keys. A link apiece would each find a fresh store empty and mint a key of its own, and the\n * peer pins only the first it sees.\n */\nfunction linkOverStorage(storage: StorageAdapter): ClientCryptoKeyLink {\n  const shared = linksByStorage.get(storage);\n  if (shared != null) {\n    // The store may have been cleared since the last connection (a sign-out): what this one\n    // presents must be what a reload will find there.\n    shared.reloadOnNextInitialize();\n    return shared;\n  }\n  const link = new ClientCryptoKeyLink({ storageAdapter: storage });\n  linksByStorage.set(storage, link);\n  return link;\n}\n\n/**\n * The ephemeral-identity trap: a coordinate with a persistent id whose\n * crypto identity lives in non-durable storage keys the peer's trust-on-first-use verify-key pin but\n * regenerates a new key on every reload — so every reload after the first is rejected\n * `identity_pin_mismatch`, forever. It type-checks and the first load works, so nothing else surfaces\n * it. Warn once per pinned identity (module-global dedupe — one warning per identity per process, not\n * per connection). Both `durable === false` and unknown durability are warning-worthy; a deliberately\n * per-session id opts out with `ephemeralIdentity: true`. Shared by every dial-out entry point\n * (`createWireClient`, `connectChannel`), so the check lives once.\n */\nfunction warnOnEphemeralPinnedIdentity(\n  callerName: string,\n  coordinate: RuntimeCoordinate,\n  storage: StorageAdapter,\n): void {\n  if (storage.durable === true || coordinate.perId == null) return;\n  const pinKey = `${coordinate.envId}::${coordinate.perId}`;\n  if (ephemeralIdentityWarned.has(pinKey)) return;\n  ephemeralIdentityWarned.add(pinKey);\n  console.warn(\n    `${callerName}: the runtime coordinate [${pinKey}] carries a persistent id, which keys the ` +\n      \"peer's trust-on-first-use verify-key pin — but the `storage` passed here is not known to be \" +\n      \"durable, so this client's crypto identity may regenerate on reload. The \" +\n      \"peer will pin the first key it sees and reject every reconnect after the first reload \" +\n      \"(identity_pin_mismatch). Back the connection with a durable adapter (e.g. \" +\n      \"createWebLocalStorageAdapter) that persists at least as long as the persistent id, or set \" +\n      \"`ephemeralIdentity: true` if the id is minted fresh per session. Memory adapters are for tests.\",\n  );\n}\n\nconst sessionReuseWarned = new Set<string>();\n\n/**\n * `reuseExchangeSessions` where it cannot do what it says. Nothing fails, so nothing else would\n * tell: the option is ignored on a plain carrier, a link with no storage keeps the session in\n * memory only, and a per-session identity files it under an id no later load will have. Warned\n * once per connection identity, peer and cause.\n */\nfunction warnOnUnusableSessionReuse(\n  options: IWireConnectionPartsOptions,\n  link: ClientCryptoKeyLink | undefined,\n): void {\n  const exchangeCarriers = options.exchangeCarrierSecurity ?? [];\n  // No request/reply carrier at all: a socket holds one session for its own life.\n  if (exchangeCarriers.length === 0) return;\n\n  const connection =\n    `[${options.identity.envId}::${options.identity.perId ?? \"-\"} → ` +\n    `${options.peer.envId}::${options.peer.perId ?? \"-\"}]`;\n  const warn = (cause: string, detail: string): void => {\n    const key = `${cause}|${connection}`;\n    if (sessionReuseWarned.has(key)) return;\n    sessionReuseWarned.add(key);\n    console.warn(`${options.callerName}: \\`reuseExchangeSessions\\` ${detail}`);\n  };\n\n  if (!exchangeCarriers.includes(true)) {\n    warn(\n      \"plain\",\n      `does nothing on the connection ${connection}: every request/reply carrier on it is ` +\n        \"`secure: false`, and a plain carrier has no session to keep. Drop the option, or make \" +\n        \"the carrier secure.\",\n    );\n    return;\n  }\n  if (link?.scopedStorage(\"\") == null) {\n    warn(\n      \"no-storage\",\n      `is on for the connection ${connection}, but its crypto identity has no \\`storage\\`, so a ` +\n        \"session is kept in memory only: shared between this page's connections, and gone on \" +\n        \"reload. Pass `storage` (or a `link` built over one) to keep sessions across page loads.\",\n    );\n    return;\n  }\n  if (options.ephemeralIdentity === true && options.identity.perId != null) {\n    warn(\n      \"per-session-identity\",\n      `is on for the connection ${connection} together with \\`ephemeralIdentity: true\\`. A kept ` +\n        \"session is filed under the identity's persistent id, and a per-session id is new on \" +\n        \"every load, so no later load can find it: sessions are reused within this page only. \" +\n        \"Use an id that survives reloads if a reload should skip the handshake.\",\n    );\n  }\n}\n\n/** The wire-connection facts every dial-out entry point assembles the same way (E2/8b.3). */\nexport interface IWireConnectionPartsOptions {\n  /** The entry point building this connection — `\"createWireClient\"` / `\"connectChannel\"` (for the warning). */\n  callerName: string;\n  /** The peer this connection dials — stamps `wireTap` events with its `stringId`. */\n  peer: RuntimeCoordinate;\n  /** This client's coordinate — checked for the ephemeral-identity pin trap. */\n  identity: RuntimeCoordinate;\n  /** A caller-supplied mux to populate + return; a fresh one is created when absent. */\n  mux?: WireProtocolMux;\n  /** Frame protocols to register on the mux at construction (before the handshake advertises them). */\n  protocols?: readonly IWireFrameProtocol[];\n  /** Whether any transport on this connection is secure — gates building the crypto identity. */\n  anySecure: boolean;\n  /** Durable backing for the crypto identity (required when secure unless `ephemeralIdentity`). */\n  storage?: StorageAdapter;\n  /** A caller-supplied crypto identity, shared across the secure transports. */\n  link?: ClientCryptoKeyLink;\n  /** Suppress the ephemeral-identity warning for a deliberately per-session id. */\n  ephemeralIdentity?: boolean;\n  /** The caller's `reuseExchangeSessions`, checked here for the cases where it cannot work. */\n  reuseExchangeSessions?: boolean;\n  /** Whether each request/reply (exchange) carrier on the connection is secure — for that check. */\n  exchangeCarrierSecurity?: readonly boolean[];\n  reconnect?: boolean;\n  heartbeat?: false | { idleMs?: number; pongTimeoutMs?: number };\n  /** @deprecated Use `reconnect`. */\n  keepLinkAlive?: boolean;\n  /** @deprecated Use `heartbeat`. */\n  linkKeepalive?: false | { idleMs?: number; pongTimeoutMs?: number };\n  wireTap?: TWireTapFn;\n}\n\n/** The assembled facts a dial-out entry point threads into its transports. */\nexport interface IWireConnectionParts {\n  /** The connection's mux (caller-supplied or freshly created), with `protocols` registered. */\n  mux: WireProtocolMux;\n  /** The crypto identity fanned across every secure transport (`undefined` for a fully-plain one). */\n  link?: ClientCryptoKeyLink;\n  /**\n   * The heartbeat resolver is a thunk because its automatic default mirrors `reconnect`\n   * (\"on for a protocol-carrying link\") and protocols may register on the mux *after* this runs\n   * (`realmConnection(client)` / `realmConnection(connector)` runs before `connect()`).\n   */\n  resolveHeartbeat: () => IWireHeartbeat | undefined;\n  /** The per-link-attributed traffic tap (`wireTap` stamped with the peer's `stringId`), or `undefined`. */\n  wireTap?: TWireTapFn;\n}\n\n/**\n * Assemble the connection facts a dial-out entry point shares — the one implementation of \"how a\n * wire connection's mux, crypto identity, keepalive, and traffic tap are set up\" (first-production\n * the connection design). `createWireClient` and `connectChannel` both call this; each then builds its own\n * transports (mux-only `WireLinkConnection`s vs action `Transport`s with the codec lane) around the\n * shared result, so a fix to any of these lands once.\n */\nexport function assembleWireConnectionParts(\n  options: IWireConnectionPartsOptions,\n): IWireConnectionParts {\n  const mux = options.mux ?? new WireProtocolMux();\n  if (options.reconnect != null && options.keepLinkAlive != null) {\n    throw err_wire_connect.fromId(\"conflicting_connect_options\", {\n      detail: `${options.callerName}: pass only \\`reconnect\\`; \\`keepLinkAlive\\` is deprecated`,\n    });\n  }\n  if (options.heartbeat != null && options.linkKeepalive != null) {\n    throw err_wire_connect.fromId(\"conflicting_connect_options\", {\n      detail: `${options.callerName}: pass only \\`heartbeat\\`; \\`linkKeepalive\\` is deprecated`,\n    });\n  }\n  const reconnect = options.reconnect ?? options.keepLinkAlive;\n  const heartbeat = options.heartbeat ?? options.linkKeepalive;\n  for (const protocol of options.protocols ?? []) {\n    mux.registerProtocol(protocol);\n  }\n\n  let link = options.link;\n  if (options.anySecure && link == null) {\n    if (options.storage == null && options.ephemeralIdentity !== true) {\n      throw new Error(\n        `${options.callerName}: a secure transport requires \\`storage\\` (or \\`link\\`) for the crypto ` +\n          \"identity. Pass it, declare a per-session identity with `ephemeralIdentity: true`, or set \" +\n          \"`secure: false` on the carrier for a plain connection.\",\n      );\n    }\n    if (options.storage != null && options.ephemeralIdentity !== true) {\n      warnOnEphemeralPinnedIdentity(options.callerName, options.identity, options.storage);\n    }\n    link = options.storage != null ? linkOverStorage(options.storage) : new ClientCryptoKeyLink();\n  }\n  if (options.reuseExchangeSessions === true) warnOnUnusableSessionReuse(options, link);\n\n  const resolveHeartbeat = (): IWireHeartbeat | undefined => {\n    if (heartbeat === false) return undefined;\n    const explicit = heartbeat;\n    const active =\n      explicit != null || reconnect === true || (reconnect !== false && mux.localCaps().length > 0);\n    if (!active) return undefined;\n    return {\n      idleMs: explicit?.idleMs ?? DEFAULT_HEARTBEAT_IDLE_MS,\n      pongTimeoutMs: explicit?.pongTimeoutMs ?? DEFAULT_HEARTBEAT_PONG_TIMEOUT_MS,\n    };\n  };\n\n  const wireTap =\n    options.wireTap != null ? withLinkIdTap(options.wireTap, options.peer.stringId) : undefined;\n\n  return { mux, link, resolveHeartbeat, wireTap };\n}\n","/**\n * The wire envelope for secure traffic over an `IExchangeCarrier` (HTTP) — re-homed from\n * nice-action's `exchangeProtocol.ts`. An exchange carrier\n * only moves one request frame → one reply frame with no unsolicited push, so the handshake and\n * the per-request token + crypto all ride in this envelope (a JSON string body) rather than on a\n * persistent channel. The three security levels share it:\n *\n * - `none` — no handshake, no token: an `act` envelope carries the plaintext lane wire both ways.\n * - `authenticated` — a one-time handshake yields a session `t`oken; each later `act` carries it\n *   plus the plaintext wire.\n * - `encrypted` — same, but the wire is AES-GCM ciphertext, base64 in the `c` field.\n *\n * The handshake runs as two `hs` exchanges (hello→welcome, prove→accept). The acceptor keeps\n * **no** in-flight state between them: the `welcome` reply carries a sealed handshake-continuation\n * token `hsc` (the acceptor's `pending` state, opaque to the client), which the connector echoes\n * on the `prove` request. The `accept` reply then carries the (sealed) session `t`oken replayed on\n * every later `act`. All server-side continuity rides these sealed tokens, so no request needs to\n * co-locate with another.\n *\n * The `w` slot is the **lane's** wire (E5) — opaque JSON to this layer; nice-action's typed view\n * of the same envelope stays in its `exchangeProtocol.ts`. The field names + literal order are\n * byte-frozen (pinned end-to-end by the exchange integration suites).\n */\n\n/**\n * Connector → acceptor request envelope. `i` (beside a `t`) is the connector's current `insId`: a\n * kept session outlives the boot that made it, so the acceptor names the client by this boot.\n */\nexport type TWireExchangeRequest =\n  | { k: \"hs\"; m: string; hsc?: string }\n  | { k: \"act\"; t?: string; i?: string; w: unknown }\n  | { k: \"act\"; t?: string; i?: string; c: string };\n\n/**\n * The `err` id an acceptor sends when it refused the session itself (expired, tampered or\n * wrong-key ticket, or an act at the wrong level) — before any lane ran, so the connector may\n * drop the session, handshake again and resend the same act.\n */\nexport const WIRE_EXCHANGE_SESSION_REFUSED = \"session_refused\";\n\n/** Acceptor → connector reply envelope. */\nexport type TWireExchangeReply =\n  /** `ttl` (on the accept that carries `t`): how long the session ticket stays valid, in ms. */\n  | { k: \"hs\"; m: string; hsc?: string; t?: string; ttl?: number }\n  | { k: \"act\"; w: unknown }\n  | { k: \"act\"; c: string }\n  | { k: \"err\"; message: string; id?: typeof WIRE_EXCHANGE_SESSION_REFUSED };\n\nexport function encodeExchange(envelope: TWireExchangeRequest | TWireExchangeReply): string {\n  return JSON.stringify(envelope);\n}\n\nexport function decodeExchangeRequest(raw: string): TWireExchangeRequest | undefined {\n  const value = parseJson(raw);\n  return isRequestEnvelope(value) ? value : undefined;\n}\n\nexport function decodeExchangeReply(raw: string): TWireExchangeReply | undefined {\n  const value = parseJson(raw);\n  return isReplyEnvelope(value) ? value : undefined;\n}\n\nfunction parseJson(raw: string): unknown {\n  try {\n    return JSON.parse(raw);\n  } catch {\n    return undefined;\n  }\n}\n\n// The decoders validate only the `k` discriminant — every deeper field is checked where it is\n// consumed (`decodeHandshakeMessage` for `m`, the sealer for tokens, the lane for `w`), so a\n// missing/odd field degrades to the same \"malformed …\" replies as before the move.\nfunction isRequestEnvelope(value: unknown): value is TWireExchangeRequest {\n  return hasEnvelopeKind(value) && (value.k === \"hs\" || value.k === \"act\");\n}\n\nfunction isReplyEnvelope(value: unknown): value is TWireExchangeReply {\n  return hasEnvelopeKind(value) && (value.k === \"hs\" || value.k === \"act\" || value.k === \"err\");\n}\n\nfunction hasEnvelopeKind(value: unknown): value is { k: unknown } {\n  return typeof value === \"object\" && value != null && \"k\" in value;\n}\n","import {\n  base64ToBytes,\n  bytesToBase64,\n  type ClientCryptoKeyLink,\n  decryptBytesWithAesGcmKey,\n  encryptBytesWithAesGcmKey,\n} from \"@nice-code/util\";\nimport { pack, unpack } from \"msgpackr\";\n\n/**\n * Seals/opens the small server-only state of a *stateless* secure exchange — the handshake continuation\n * (`pending`) and the session ticket — into opaque blobs the client round-trips, so the acceptor keeps\n * **no** in-memory or stored session state. Only a server that holds the same persisted identity can open\n * a blob (the AES-GCM key is derived from that identity via {@link ClientCryptoKeyLink.deriveLocalSealKey}),\n * so any isolate sharing the identity is interchangeable.\n *\n * Each blob embeds an absolute expiry; {@link IExchangeTicketSealer.open} returns `undefined` for an\n * expired, tampered, wrong-key, or malformed blob (the caller treats all of these as \"no valid session\").\n *\n * Wire shape: `base64( pack([nonce, ciphertext]) )`, where the plaintext is `pack({ v, exp })`.\n */\nexport interface IExchangeTicketSealer {\n  /** Seal `value` into a blob valid for `ttlMs` from now. */\n  seal(value: unknown, ttlMs: number): Promise<string>;\n  /** Open + validate a blob, or `undefined` if expired / tampered / wrong key / malformed. */\n  open<T>(blob: string): Promise<T | undefined>;\n}\n\nconst SEALED_ENVELOPE_LENGTH = 2;\n\ninterface ISealedPayload {\n  /** The sealed value. */\n  v: unknown;\n  /** Absolute expiry (epoch ms). */\n  exp: number;\n}\n\nexport function createExchangeTicketSealer(\n  link: ClientCryptoKeyLink,\n  options: { version?: string } = {},\n): IExchangeTicketSealer {\n  // Derive the identity-bound seal key lazily (on first seal/open) and reuse it thereafter. Lazy so an\n  // unprovisioned `\"required\"`-mode link doesn't reject this promise before any request arrives.\n  let keyPromise: Promise<CryptoKey> | undefined;\n  const getKey = (): Promise<CryptoKey> => {\n    if (keyPromise == null) {\n      keyPromise = link.deriveLocalSealKey({ version: options.version }).catch((err) => {\n        keyPromise = undefined; // clear the memo so a retry after provisioning can succeed\n        throw err;\n      });\n    }\n    return keyPromise;\n  };\n\n  return {\n    async seal(value: unknown, ttlMs: number): Promise<string> {\n      const payload: ISealedPayload = { v: value, exp: Date.now() + ttlMs };\n      const { nonce, ciphertext } = await encryptBytesWithAesGcmKey({\n        dataToEncrypt: pack(payload),\n        aesGcmKey: await getKey(),\n      });\n      return bytesToBase64(pack([nonce, ciphertext]));\n    },\n\n    async open<T>(blob: string): Promise<T | undefined> {\n      try {\n        const envelope = unpack(base64ToBytes(blob));\n        if (!Array.isArray(envelope) || envelope.length !== SEALED_ENVELOPE_LENGTH)\n          return undefined;\n        const [nonce, ciphertext] = envelope;\n        if (!(nonce instanceof Uint8Array) || !(ciphertext instanceof Uint8Array)) return undefined;\n\n        // AES-GCM verifies integrity — a tampered blob or wrong key throws here and falls to `undefined`.\n        const plain = await decryptBytesWithAesGcmKey({\n          dataToDecrypt: { nonce, ciphertext },\n          aesGcmKey: await getKey(),\n        });\n        const payload = unpack(plain) as ISealedPayload;\n        if (payload == null || typeof payload.exp !== \"number\" || payload.exp < Date.now()) {\n          return undefined;\n        }\n        return payload.v as T;\n      } catch {\n        return undefined;\n      }\n    },\n  };\n}\n","import type { ClientCryptoKeyLink, StorageAdapter } from \"@nice-code/util\";\nimport { createActionFrameCrypto, type IActionFrameCrypto } from \"../crypto/actionFrameCrypto\";\nimport type { ESecurityLevel, IHandshakeEncryptionKeyMaterial } from \"../crypto/actionHandshake\";\nimport {\n  createExchangeTicketSealer,\n  type IExchangeTicketSealer,\n} from \"../SecureSession/exchangeTicketSeal\";\nimport type { IWireLaneHandshakeConfig, IWireSecureClientConfig } from \"./Connect.types\";\n\n/** What an established secure exchange holds: the acceptor's ticket and, at `encrypted`, its crypto. */\nexport interface IExchangeSecureState {\n  token?: string;\n  crypto?: IActionFrameCrypto;\n  /** Epoch ms from which the ticket counts as lapsed; absent when the acceptor gave no lifetime. */\n  expiresAt?: number;\n  /** The facts a stored copy rebuilds the state from; absent on the plain path. */\n  record?: IExchangeSessionRecord;\n}\n\n/** A session as kept between page loads — only ever stored sealed under the link's own key. */\nexport interface IExchangeSessionRecord {\n  t: string;\n  level: ESecurityLevel;\n  km?: IHandshakeEncryptionKeyMaterial;\n  exp?: number;\n}\n\n/** Where a session exchange gets its ticket, and how it gets another once the acceptor refused one. */\nexport interface IExchangeSessionSource {\n  current(): Promise<IExchangeSecureState>;\n  /** The acceptor refused `stale`: forget it and establish afresh (concurrent callers share one). */\n  renew(stale: IExchangeSecureState): Promise<IExchangeSecureState>;\n}\n\ntype THandshake = () => Promise<IExchangeSecureState>;\n\n/** Lapse a little before the acceptor would, so a request is never sent on its last second. */\nexport function expiryFor(receivedAt: number, ttlMs: number | undefined): number | undefined {\n  if (ttlMs == null || !(ttlMs > 0)) return undefined;\n  return receivedAt + ttlMs - Math.min(60_000, ttlMs / 10);\n}\n\nexport function stateFromRecord(\n  link: ClientCryptoKeyLink,\n  record: IExchangeSessionRecord,\n): IExchangeSecureState {\n  const crypto =\n    record.km != null ? createActionFrameCrypto({ link, keyMaterial: record.km }) : undefined;\n  return { token: record.t, crypto, expiresAt: record.exp, record };\n}\n\nfunction isLapsed(state: IExchangeSecureState): boolean {\n  return state.expiresAt != null && Date.now() >= state.expiresAt;\n}\n\n/**\n * One session's lifecycle: at most one handshake in flight, shared by every caller; a refused or\n * lapsed session is replaced once, however many requests noticed it.\n */\nclass ExchangeSessionSlot {\n  private _entry:\n    | { promise: Promise<IExchangeSecureState>; state?: IExchangeSecureState }\n    | undefined;\n\n  current(initial: THandshake, replacement: THandshake): Promise<IExchangeSecureState> {\n    const entry = this._entry;\n    if (entry == null) return this._start(initial);\n    if (entry.state != null && isLapsed(entry.state)) return this.renew(entry.state, replacement);\n    return entry.promise;\n  }\n\n  renew(stale: IExchangeSecureState, replacement: THandshake): Promise<IExchangeSecureState> {\n    const entry = this._entry;\n    // Already replaced (or replacing) by another caller: join it.\n    if (entry != null && entry.state !== stale) return entry.promise;\n    return this._start(replacement);\n  }\n\n  private _start(establish: THandshake): Promise<IExchangeSecureState> {\n    const entry: { promise: Promise<IExchangeSecureState>; state?: IExchangeSecureState } = {\n      promise: establish(),\n    };\n    this._entry = entry;\n    entry.promise.then(\n      (state) => {\n        entry.state = state;\n      },\n      () => {\n        if (this._entry === entry) this._entry = undefined;\n      },\n    );\n    return entry.promise;\n  }\n}\n\n/** A session source for one transport alone — today's behaviour, plus renewal on refusal. */\nexport function privateSessionSource(handshake: THandshake): IExchangeSessionSource {\n  const slot = new ExchangeSessionSlot();\n  return {\n    current: () => slot.current(handshake, handshake),\n    renew: (stale) => slot.renew(stale, handshake),\n  };\n}\n\nconst STORE_KEY = \"sessions\";\nconst SEAL_VERSION = \"connector-exchange-session/v1\";\n\ntype TStoredSessions = Record<string, { exp: number; sealed: string }>;\n\n/**\n * Every session one crypto identity holds with its peers, keyed by peer identity: shared in memory\n * by all of the link's transports, and kept in the link's own storage so a reload restores it.\n * Stored copies are sealed with a key derived from the link's private key — useless to another\n * device, and unopenable once the identity is reset.\n */\nclass ExchangeSessionShelf {\n  private readonly _slots = new Map<string, ExchangeSessionSlot>();\n  private readonly _storage: StorageAdapter | undefined;\n  private readonly _sealer: IExchangeTicketSealer;\n\n  constructor(private readonly _link: ClientCryptoKeyLink) {\n    this._storage = _link.scopedStorage(\"wire-exchange/\");\n    this._sealer = createExchangeTicketSealer(_link, { version: SEAL_VERSION });\n  }\n\n  source(key: string, handshake: THandshake): IExchangeSessionSource {\n    let slot = this._slots.get(key);\n    if (slot == null) {\n      slot = new ExchangeSessionSlot();\n      this._slots.set(key, slot);\n    }\n    const held = slot;\n    // Keeping is best-effort: a storage that fails to read or write costs a handshake, never a request.\n    const handshakeAndKeep: THandshake = async () => {\n      const state = await handshake();\n      await this._keep(key, state).catch(() => undefined);\n      return state;\n    };\n    const restoreOrHandshake: THandshake = async () => {\n      const restored = await this._restore(key).catch(() => undefined);\n      return restored ?? (await handshakeAndKeep());\n    };\n    const replace: THandshake = async () => {\n      await this._forget(key).catch(() => undefined);\n      return await handshakeAndKeep();\n    };\n    return {\n      current: () => held.current(restoreOrHandshake, replace),\n      renew: (stale) => held.renew(stale, replace),\n    };\n  }\n\n  private async _restore(key: string): Promise<IExchangeSecureState | undefined> {\n    const storage = this._storage;\n    if (storage == null) return undefined;\n    const stored = (await storage.getJson<TStoredSessions>(STORE_KEY))?.[key];\n    // Checked before opening, so a fresh device never derives (or mints) a key just to look.\n    if (stored == null || stored.exp <= Date.now()) return undefined;\n    await this._link.initialize();\n    const record = await this._sealer.open<IExchangeSessionRecord>(stored.sealed);\n    if (record == null || typeof record.t !== \"string\") return undefined;\n    return stateFromRecord(this._link, record);\n  }\n\n  private async _keep(key: string, state: IExchangeSecureState): Promise<void> {\n    const storage = this._storage;\n    const record = state.record;\n    if (storage == null || record?.exp == null) return;\n    const ttl = record.exp - Date.now();\n    if (ttl <= 0) return;\n    const sealed = await this._sealer.seal(record, ttl);\n    await this._update(storage, (sessions) => ({\n      ...sessions,\n      [key]: { exp: record.exp ?? 0, sealed },\n    }));\n  }\n\n  private async _forget(key: string): Promise<void> {\n    const storage = this._storage;\n    if (storage == null) return;\n    await this._update(storage, (sessions) => {\n      const { [key]: _dropped, ...rest } = sessions;\n      return rest;\n    });\n  }\n\n  private async _update(\n    storage: StorageAdapter,\n    change: (sessions: TStoredSessions) => TStoredSessions,\n  ): Promise<void> {\n    await storage.updateJsonOrDef<TStoredSessions>(STORE_KEY, {}, (current) => {\n      const now = Date.now();\n      const live: TStoredSessions = {};\n      for (const [key, entry] of Object.entries(change(current))) {\n        if (entry.exp > now) live[key] = entry;\n      }\n      return live;\n    });\n  }\n}\n\nconst shelves = new WeakMap<ClientCryptoKeyLink, ExchangeSessionShelf>();\n\n/**\n * The source a secure exchange draws its session from: shared by peer identity when the config asks\n * for reuse and names the peer, private to this transport otherwise.\n */\nexport function exchangeSessionSource(\n  secure: IWireSecureClientConfig,\n  lane: IWireLaneHandshakeConfig,\n  handshake: THandshake,\n): IExchangeSessionSource {\n  const peer = secure.expectedPeer;\n  if (secure.reuseExchangeSessions !== true || peer == null) {\n    return privateSessionSource(handshake);\n  }\n  let shelf = shelves.get(secure.link);\n  if (shelf == null) {\n    shelf = new ExchangeSessionShelf(secure.link);\n    shelves.set(secure.link, shelf);\n  }\n  // `insId` is left out on both sides: a session belongs to the identity, not to one boot of it.\n  // The dictionary version stays in: the acceptor checks a ticket against its own version only, so\n  // a client whose dictionary changed must not bring back a session agreed under the old one.\n  const key = JSON.stringify([\n    secure.localCoordinate.envId,\n    secure.localCoordinate.perId ?? null,\n    peer.envId,\n    peer.perId ?? null,\n    secure.securityLevel,\n    lane.dictionaryVersion,\n    [...(lane.channels ?? [])].sort(),\n  ]);\n  return shelf.source(key, handshake);\n}\n","import { base64ToBytes, bytesToBase64 } from \"@nice-code/util\";\nimport type { IExchangeCarrier, TFrame } from \"../Carrier/Carrier.types\";\nimport {\n  createClientHandshake,\n  decodeHandshakeMessage,\n  EHandshakeMessageType,\n  ESecurityLevel,\n  encodeHandshakeMessage,\n} from \"../crypto/actionHandshake\";\nimport type { IWireLaneHandshakeConfig, IWireSecureClientConfig } from \"./Connect.types\";\nimport { describeNonProtocolBody } from \"./endpointEvidence\";\nimport { err_wire_connect } from \"./err_wire_connect\";\nimport {\n  decodeExchangeReply,\n  encodeExchange,\n  type TWireExchangeReply,\n  type TWireExchangeRequest,\n  WIRE_EXCHANGE_SESSION_REFUSED,\n} from \"./exchangeEnvelope\";\nimport {\n  exchangeSessionSource,\n  expiryFor,\n  type IExchangeSecureState,\n  type IExchangeSessionSource,\n  stateFromRecord,\n} from \"./exchangeSessionShelf\";\nimport { handshakeRejectError } from \"./handshakeRejectError\";\nimport { sanitizeEndpoint } from \"./sanitizeEndpoint\";\n\n/**\n * Connector-side (dial-out) session over an {@link IExchangeCarrier} (HTTP) — the request →\n * single correlated reply sibling of `establishSecureDuplexSession` (shared connection design,\n * Phase 6). The secure session is identical in spirit — the same handshake, then per-frame\n * crypto — but carried by independent exchanges rather than a push channel, so it can deliver no\n * unsolicited frame: each lane wire's reply rides the response to its own request, and there is\n * no return path.\n *\n * The exchange path is **lane-only**: no protocol mux rides here — prefixed protocols\n * need a duplex carrier (`err_wire_connect.protocol_on_exchange_only`). Accordingly the lane\n * contributes only its handshake payload ({@link IWireLaneHandshakeConfig}); there is no frame\n * callback surface — the lane consumes each reply where it awaited it.\n *\n * At `none` there is no handshake or token: an `act` envelope carries the plaintext wire both\n * ways. At `authenticated`/`encrypted` a one-time handshake (two `hs` exchanges) yields a session\n * token replayed on every later `act`; at `encrypted` the wire is AES-GCM ciphertext. When the\n * acceptor refuses the token (expired, or sealed by another identity) the session handshakes again\n * and resends that act once; `reuseExchangeSessions` shares the session by peer identity.\n */\nexport interface IWireExchangeSession {\n  /** Send one lane wire, await its correlated reply, and open it (decrypting when encrypted). */\n  exchange(wire: unknown, opts?: { signal?: AbortSignal }): Promise<TWireExchangeOutcome>;\n  /** Send one lane wire and ignore the reply body (no unsolicited frame rides an exchange). */\n  send(wire: unknown, opts?: { signal?: AbortSignal }): Promise<void>;\n}\n\n/** One exchange's opened reply — the lane maps failures onto its own error vocabulary. */\nexport type TWireExchangeOutcome =\n  /** The reply's lane wire (opaque JSON to this layer). */\n  | { ok: true; wire: unknown }\n  /** No decodable reply envelope (or ciphertext on a session without crypto). */\n  | { ok: false; reason: \"malformed_reply\" }\n  /** The acceptor answered with its `err` envelope. */\n  | { ok: false; reason: \"peer_error\"; message: string };\n\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\n\nconst PLAIN_STATE: IExchangeSecureState = {};\n\n/** Plain path (no handshake/token): every wire rides a bare `act` envelope, plaintext both ways. */\nexport function establishPlainExchangeSession(carrier: IExchangeCarrier): IWireExchangeSession {\n  return makeSession(carrier, {\n    current: async () => PLAIN_STATE,\n    renew: async () => PLAIN_STATE,\n  });\n}\n\n/**\n * Secure path: run the handshake (two exchanges) at bring-up — or restore a kept session — then\n * reuse the token + crypto. The lane supplies the handshake payload (`dictionaryVersion`/`channels`,\n * E5 — emitted under the byte-frozen wire names; the version is signed into the challenge).\n */\nexport async function establishSecureExchangeSession(ctx: {\n  carrier: IExchangeCarrier;\n  secure: IWireSecureClientConfig;\n  lane: IWireLaneHandshakeConfig;\n}): Promise<IWireExchangeSession> {\n  const source = exchangeSessionSource(ctx.secure, ctx.lane, () =>\n    runConnectorExchangeHandshake(ctx.carrier, ctx.secure, ctx.lane),\n  );\n  await source.current();\n  return makeSession(ctx.carrier, source, ctx.secure.localCoordinate.insId);\n}\n\nfunction makeSession(\n  carrier: IExchangeCarrier,\n  source: IExchangeSessionSource,\n  insId?: string,\n): IWireExchangeSession {\n  const post = async (\n    state: IExchangeSecureState,\n    wire: unknown,\n    signal: AbortSignal | undefined,\n  ): Promise<TWireExchangeReply | undefined> => {\n    const request = await buildRequestEnvelope(state, wire, insId);\n    const raw = await carrier.exchange(encodeExchange(request), { signal });\n    return decodeExchangeReply(asString(raw));\n  };\n\n  // The acceptor refuses a session before any lane runs, so resending the act once is safe.\n  const roundTrip = async (\n    wire: unknown,\n    signal: AbortSignal | undefined,\n  ): Promise<{ state: IExchangeSecureState; reply: TWireExchangeReply | undefined }> => {\n    const state = await source.current();\n    const reply = await post(state, wire, signal);\n    if (reply?.k !== \"err\" || reply.id !== WIRE_EXCHANGE_SESSION_REFUSED || state.token == null) {\n      return { state, reply };\n    }\n    const renewed = await source.renew(state);\n    const retried = await post(renewed, wire, signal);\n    return { state: renewed, reply: retried };\n  };\n\n  return {\n    send: async (wire, opts) => {\n      await roundTrip(wire, opts?.signal);\n    },\n    exchange: async (wire, opts) => {\n      const { state, reply } = await roundTrip(wire, opts?.signal);\n      if (reply == null) return { ok: false, reason: \"malformed_reply\" };\n      if (reply.k === \"err\") return { ok: false, reason: \"peer_error\", message: reply.message };\n      const replyWire = await extractReplyWire(state, reply);\n      if (replyWire === undefined) return { ok: false, reason: \"malformed_reply\" };\n      return { ok: true, wire: replyWire };\n    },\n  };\n}\n\nasync function buildRequestEnvelope(\n  state: IExchangeSecureState,\n  wire: unknown,\n  insId: string | undefined,\n): Promise<TWireExchangeRequest> {\n  const i = state.token != null ? insId : undefined;\n  if (state.crypto != null) {\n    const ciphertext = await state.crypto.encryptFrame(textEncoder.encode(JSON.stringify(wire)));\n    return { k: \"act\", t: state.token, i, c: bytesToBase64(ciphertext) };\n  }\n  return { k: \"act\", t: state.token, i, w: wire };\n}\n\nasync function extractReplyWire(\n  state: IExchangeSecureState,\n  reply: TWireExchangeReply,\n): Promise<unknown> {\n  if (reply.k !== \"act\") return undefined;\n  if (\"c\" in reply) {\n    if (state.crypto == null) return undefined;\n    const plain = await state.crypto.decryptFrame(base64ToBytes(reply.c));\n    return JSON.parse(textDecoder.decode(plain));\n  }\n  return reply.w;\n}\n\nasync function runConnectorExchangeHandshake(\n  carrier: IExchangeCarrier,\n  secure: IWireSecureClientConfig,\n  lane: IWireLaneHandshakeConfig,\n): Promise<IExchangeSecureState> {\n  await secure.link.initialize();\n\n  const handshake = createClientHandshake({\n    link: secure.link,\n    localCoordinate: secure.localCoordinate,\n    expectedPeer: secure.expectedPeer,\n    dictionaryVersion: lane.dictionaryVersion,\n    securityLevel: secure.securityLevel,\n    channelTags: lane.channels,\n  });\n\n  // Exchange 1: hello → welcome (+ the sealed handshake-continuation token `hsc`).\n  const hello = await handshake.createHello();\n  const welcomeReply = await exchangeHandshakeFrame(\n    carrier,\n    { k: \"hs\", m: encodeHandshakeMessage(hello) },\n    \"a welcome frame\",\n  );\n  const welcome = decodeHandshakeMessage(welcomeReply.m);\n  if (welcome == null) throw nonProtocolReply(carrier, \"a welcome frame\", \"hs (undecodable)\");\n  if (welcome.t === EHandshakeMessageType.reject) {\n    throw handshakeRejectError(HANDSHAKE_STAGE, welcome);\n  }\n  if (welcome.t !== EHandshakeMessageType.welcome) {\n    throw nonProtocolReply(carrier, \"a welcome frame\", `hs/${welcome.t}`);\n  }\n  if (welcomeReply.hsc == null) {\n    throw new Error(\n      `[${HANDSHAKE_STAGE}] welcome missing handshake continuation token${at(carrier)}`,\n    );\n  }\n\n  // Exchange 2: prove (echoing `hsc`) → accept (+ session token).\n  const prove = await handshake.onWelcome(welcome);\n  const acceptReply = await exchangeHandshakeFrame(\n    carrier,\n    { k: \"hs\", m: encodeHandshakeMessage(prove), hsc: welcomeReply.hsc },\n    \"an accept frame\",\n  );\n  const accept = decodeHandshakeMessage(acceptReply.m);\n  if (accept == null) throw nonProtocolReply(carrier, \"an accept frame\", \"hs (undecodable)\");\n  if (accept.t === EHandshakeMessageType.reject) {\n    throw handshakeRejectError(HANDSHAKE_STAGE, accept);\n  }\n  if (accept.t !== EHandshakeMessageType.accept) {\n    throw nonProtocolReply(carrier, \"an accept frame\", `hs/${accept.t}`);\n  }\n  if (acceptReply.t == null) {\n    throw new Error(`[${HANDSHAKE_STAGE}] accept missing session token${at(carrier)}`);\n  }\n\n  const result = await handshake.onAccept(accept);\n  const keyMaterial =\n    result.securityLevel === ESecurityLevel.encrypted ? result.encryptionKeyMaterial : undefined;\n  return stateFromRecord(secure.link, {\n    t: acceptReply.t,\n    level: result.securityLevel,\n    km: keyMaterial,\n    exp: expiryFor(Date.now(), acceptReply.ttl),\n  });\n}\n\nconst HANDSHAKE_STAGE = \"exchange-handshake\";\n\n/**\n * One handshake exchange, with the failure told from the *reply's* point of view (feedback W1).\n * The reply is in hand at the throw site, so the error says what came back — a frame kind, or a\n * bounded preview of a body that was never a protocol frame at all — instead of only what we\n * hoped for. A body preview is attached ONLY when nothing decoded: a decodable `act` envelope may\n * carry application data, which has no business in a connection error.\n */\nasync function exchangeHandshakeFrame(\n  carrier: IExchangeCarrier,\n  request: TWireExchangeRequest,\n  expected: string,\n): Promise<Extract<TWireExchangeReply, { k: \"hs\" }>> {\n  const raw = asString(await carrier.exchange(encodeExchange(request)));\n  const reply = decodeExchangeReply(raw);\n\n  if (reply == null) {\n    throw err_wire_connect.fromId(\"endpoint_answered_non_protocol\", {\n      stage: HANDSHAKE_STAGE,\n      expected,\n      url: sanitizeEndpoint(carrier.label),\n      bodyPreview: describeNonProtocolBody(raw),\n    });\n  }\n  // An `err` envelope means the peer *is* nice-wire and refused — a different fix entirely.\n  if (reply.k === \"err\") {\n    throw err_wire_connect.fromId(\"handshake_rejected\", {\n      stage: HANDSHAKE_STAGE,\n      reason: reply.message,\n    });\n  }\n  if (reply.k !== \"hs\") throw nonProtocolReply(carrier, expected, reply.k);\n\n  return reply;\n}\n\nfunction nonProtocolReply(\n  carrier: IExchangeCarrier,\n  expected: string,\n  receivedKind: string,\n): Error {\n  return err_wire_connect.fromId(\"endpoint_answered_non_protocol\", {\n    stage: HANDSHAKE_STAGE,\n    expected,\n    url: sanitizeEndpoint(carrier.label),\n    receivedKind,\n  });\n}\n\n/** Make a peer-bug message self-locating without inventing a typed id for it. */\nfunction at(carrier: IExchangeCarrier): string {\n  const endpoint = sanitizeEndpoint(carrier.label);\n  return endpoint != null ? ` (endpoint: ${endpoint})` : \"\";\n}\n\nfunction asString(frame: TFrame): string {\n  if (typeof frame === \"string\") return frame;\n  return textDecoder.decode(frame instanceof ArrayBuffer ? new Uint8Array(frame) : frame);\n}\n","import type { ClientCryptoKeyLink, TTypeAndId } from \"@nice-code/util\";\nimport type { TFrame } from \"../Carrier/Carrier.types\";\nimport { createActionFrameCrypto } from \"../crypto/actionFrameCrypto\";\nimport {\n  createServerHandshake,\n  decodeHandshakeMessage,\n  EHandshakeMessageType,\n  ESecurityLevel,\n  encodeHandshakeMessage,\n  type IClientVerifyKeyResolver,\n  type IHandshakeEncryptionKeyMaterial,\n  type IHandshakeResult,\n  type TServerDictionaryVersionResolver,\n} from \"../crypto/actionHandshake\";\nimport { type IRuntimeCoordinate, RuntimeCoordinate } from \"../RuntimeCoordinate\";\nimport type { TWireTapFn } from \"../tap/wireTap\";\nimport { createFrameCryptoPipe, type IFrameCryptoPipe } from \"./frameCryptoPipe\";\n\n/** What the handshake authenticated — the handler binds this identity + persists it for resumption. */\nexport interface IAcceptorAuthResult {\n  /** The peer's *authenticated* coordinate — the only identity inbound frames are bound to. */\n  client: RuntimeCoordinate;\n  securityLevel: ESecurityLevel;\n  linkedClientId: TTypeAndId;\n  /** Present at the `encrypted` level — persist it so an evicted connection re-derives its key. */\n  keyMaterial?: IHandshakeEncryptionKeyMaterial;\n  /** The channel tags the client advertised in its `hello` — the handler selects the matching codec. */\n  channelTags?: readonly string[];\n  /** The capability tags the client advertised in its `hello` (e.g. `proto:realm` frame protocols). */\n  remoteCaps?: readonly string[];\n}\n\n/** The persisted secure state replayed to resume an authenticated connection after eviction. */\nexport interface IAcceptorSecureResumeState {\n  securityLevel: ESecurityLevel;\n  linkedClientId: TTypeAndId;\n  keyMaterial?: IHandshakeEncryptionKeyMaterial;\n}\n\nexport interface IAcceptorSecureSessionConfig {\n  /** This acceptor's crypto identity (verify + exchange key pairs, optionally persisted). */\n  link: ClientCryptoKeyLink;\n  /** This acceptor's coordinate — its identity to clients during the handshake. */\n  localCoordinate: IRuntimeCoordinate;\n  /** Wire dictionary version — a fixed string (single channel), or a resolver composing it from the\n   * `hello.channels` tags (multi-channel). The handshake rejects on a mismatch / unknown channel. */\n  dictionaryVersion: string | TServerDictionaryVersionResolver;\n  /** Accepted level(s) — a single level is strict, an array is a negotiable allowed set. */\n  securityLevel: ESecurityLevel | readonly ESecurityLevel[];\n  /** Trust decision for a client's verify key (defaults to in-memory TOFU inside the handshake). */\n  verifyKeyResolver?: IClientVerifyKeyResolver;\n  /** Additional capability tags to advertise in the `welcome` (e.g. `proto:realm` frame protocols). */\n  extraCaps?: readonly string[];\n  /** Whether a plain (`none`) client may be served on this endpoint (i.e. `none` is in the set). */\n  noneAllowed: boolean;\n  /**\n   * Raw frame writer to this one connection. `tapLane` is opaque metadata forwarded from the\n   * caller (or from the crypto pipe) so the acceptor's wire tap can label the encrypted frame it\n   * eventually writes; a bare handshake write passes none.\n   */\n  send: (frame: TFrame, tapLane?: string) => void;\n  /** Close this connection; called right after a handshake reject so a refused peer cannot hold it. */\n  close?: () => void;\n  /** The acceptor's wire tap, used here only for the handshake frames the session consumes itself. */\n  tap?: TWireTapFn;\n  /** Called once the handshake authenticates the peer — the handler binds identity + persists it. */\n  onAuthenticated: (auth: IAcceptorAuthResult) => void;\n  /**\n   * Route a frame from a `none`-negotiated connection through the handler's plain (self-asserted)\n   * path. `wireBytes` is the frame's size as the carrier delivered it (see {@link receive}).\n   */\n  routePlain: (frame: TFrame, wireBytes?: number) => void;\n  /** Route a decrypted, ready-to-decode action frame from an authenticated connection. */\n  routeAction: (bytes: TFrame, wireBytes?: number) => void;\n}\n\n/**\n * The acceptor (accept-in) counterpart to the connector's `establishLinkSession`: one connection's\n * secure session — the server-side handshake driving, the ordered frame crypto, and the per-connection\n * phase (undecided → plain | authenticated). The crypto itself (ordered encrypt-send / decrypt) lives in\n * the shared {@link createFrameCryptoPipe}, the same primitive the connector uses — so the secure logic\n * lives once for both link roles.\n *\n * The handler owns one of these per accepted connection and feeds it inbound frames via {@link receive};\n * identity binding, persistence, codec, and return routing stay in the handler (driven through the\n * config callbacks). Inbound processing is serialized per connection because the handshake and decryption\n * are async — this keeps handshake ordering and frame order intact.\n */\nexport class AcceptorSecureSession {\n  private _handshake?: ReturnType<typeof createServerHandshake>;\n  /** The ordered encrypt-send / decrypt pipe — present only for an `encrypted` connection. */\n  private _pipe?: IFrameCryptoPipe;\n  private _authed = false;\n  private _plain = false;\n  private _handshakeStarted = false;\n  private _handshakeFailed = false;\n  /** The channel tags the client advertised in its `hello`, captured for the handler's codec selection. */\n  private _helloChannels?: readonly string[];\n  /** Serializes inbound processing (handshake + decryption are async). */\n  private _inboundChain: Promise<void> = Promise.resolve();\n\n  constructor(private readonly config: IAcceptorSecureSessionConfig) {}\n\n  /**\n   * Feed one inbound frame. Serialized per connection; routes back through the config callbacks.\n   * `wireBytes` is the frame's size as the carrier delivered it (pre-decryption) — measured by the\n   * acceptor and carried through here because only the decrypted frame reveals its lane.\n   */\n  receive(frame: TFrame, wireBytes?: number): void {\n    this._inboundChain = this._inboundChain\n      .then(() => {\n        if (!this._handshakeFailed) return this._receive(frame, wireBytes);\n      })\n      .catch((err) => {\n        console.error(\"[ws-server] failed to process inbound frame\", err);\n        if (!this._handshakeStarted || this._authed || this._handshakeFailed) return;\n        this._handshakeFailed = true;\n        // A crypto/storage failure used to leave a valid hello unanswered until timeout.\n        // Keep internal error details in the server log, but give the peer a real refusal.\n        try {\n          this.config.send(\n            encodeHandshakeMessage({\n              t: EHandshakeMessageType.reject,\n              reason: \"server handshake failed; check server logs\",\n            }),\n          );\n          this.config.close?.();\n        } catch {\n          // The socket may already be gone; never reject the inbound processing chain.\n        }\n      });\n  }\n\n  private async _receive(frame: TFrame, wireBytes?: number): Promise<void> {\n    // A connection that already negotiated `none` is routed plainly (self-asserted identity).\n    if (this._plain) {\n      this.config.routePlain(frame, wireBytes);\n      return;\n    }\n\n    if (!this._authed) {\n      // Undecided first frame: a handshake control frame → drive the secure handshake; anything else,\n      // when `none` is allowed, means a plain client → route it plainly from here on.\n      const message = typeof frame === \"string\" ? decodeHandshakeMessage(frame) : undefined;\n      if (message == null) {\n        if (this.config.noneAllowed) {\n          this._plain = true;\n          this.config.routePlain(frame, wireBytes);\n        }\n        return;\n      }\n\n      // A handshake frame is consumed here and never routed, so this is its only tap point.\n      this.config.tap?.({ dir: \"in\", bytes: wireBytes ?? 0, lane: \"handshake\" });\n\n      this._handshakeStarted = true;\n      await this.config.link.initialize();\n      if (this._handshake == null) {\n        this._handshake = createServerHandshake({\n          link: this.config.link,\n          localCoordinate: this.config.localCoordinate,\n          dictionaryVersion: this.config.dictionaryVersion,\n          securityLevel: this.config.securityLevel,\n          verifyKeyResolver: this.config.verifyKeyResolver,\n          extraCaps: this.config.extraCaps,\n        });\n      }\n\n      if (message.t === EHandshakeMessageType.hello) {\n        // Remember the advertised channel subset so `_complete` can tell the handler which codec to bind.\n        this._helloChannels = message.channels;\n        const reply = await this._handshake.onHello(message);\n        this.config.send(encodeHandshakeMessage(reply));\n        if (reply.t === EHandshakeMessageType.reject) this._refuse();\n      } else if (message.t === EHandshakeMessageType.prove) {\n        const reply = await this._handshake.onProve(message);\n        this.config.send(encodeHandshakeMessage(reply));\n        const result = this._handshake.getResult();\n        if (reply.t === EHandshakeMessageType.accept && result != null) this._complete(result);\n        else if (reply.t === EHandshakeMessageType.reject) this._refuse();\n      }\n      return;\n    }\n\n    // Authenticated phase: decrypt (if encrypted), then hand the bytes to the handler to decode + route.\n    const bytes = this._pipe != null ? await this._pipe.decryptIncoming(frame) : frame;\n    if (bytes === undefined) return; // decryption failed (logged inside the pipe) — drop the frame\n    this.config.routeAction(bytes, wireBytes);\n  }\n\n  /** A refused handshake ends this connection: later frames are ignored and the socket closes. */\n  private _refuse(): void {\n    this._handshakeFailed = true;\n    this.config.close?.();\n  }\n\n  private _complete(result: IHandshakeResult): void {\n    this._authed = true;\n    this._handshake = undefined;\n\n    if (result.securityLevel === ESecurityLevel.encrypted && result.encryptionKeyMaterial != null) {\n      this._pipe = this._buildPipe(\n        createActionFrameCrypto({\n          link: this.config.link,\n          keyMaterial: result.encryptionKeyMaterial,\n        }),\n      );\n    }\n\n    this.config.onAuthenticated({\n      client: new RuntimeCoordinate(result.remote),\n      securityLevel: result.securityLevel,\n      linkedClientId: result.linkedClientId,\n      keyMaterial: result.encryptionKeyMaterial,\n      channelTags: this._helloChannels,\n      remoteCaps: result.remoteCaps,\n    });\n  }\n\n  /**\n   * Restore an already-authenticated session after eviction — no handshake. For an `encrypted`\n   * connection the shared key is re-derived asynchronously (the acceptor re-links the client off its own\n   * persisted identity); the pipe's crypto IS that promise, so the connection's first in/out frame\n   * naturally waits for the key before encrypt/decrypt — no separate gate.\n   */\n  rehydrate(state: IAcceptorSecureResumeState): void {\n    this._authed = true;\n\n    if (state.securityLevel !== ESecurityLevel.encrypted || state.keyMaterial == null) return;\n\n    const { link } = this.config;\n    const { keyMaterial } = state;\n    // Re-derive this connection's own shared key off the acceptor's persisted identity + the stored\n    // material — `initialize()` first so the local exchange key pair is loaded, then the frame crypto\n    // captures its own key (no shared per-`linkedClientId` cache involved, so a concurrent session to\n    // the same client can't disturb it).\n    const cryptoReady = link\n      .initialize()\n      .then(() => createActionFrameCrypto({ link, keyMaterial }));\n\n    // Surface a re-derivation failure clearly (the pipe also logs per-frame, but this names the cause).\n    cryptoReady.catch((err) =>\n      console.error(\"[ws-server] failed to restore encrypted session\", err),\n    );\n    this._pipe = this._buildPipe(cryptoReady);\n  }\n\n  /**\n   * Send an outbound frame: through the encrypt pipe when encrypted, otherwise raw. `tapLane` rides\n   * both branches — an `authenticated` (unencrypted) connection has no pipe but its frames are just\n   * as much action/protocol traffic, and must not be mislabelled.\n   */\n  send(frame: TFrame, tapLane?: string): void {\n    if (this._pipe != null) {\n      this._pipe.send(frame, tapLane);\n      return;\n    }\n    this.config.send(frame, tapLane);\n  }\n\n  private _buildPipe(\n    crypto: Parameters<typeof createFrameCryptoPipe>[0][\"crypto\"],\n  ): IFrameCryptoPipe {\n    return createFrameCryptoPipe({ write: this.config.send, crypto, label: \"ws-server\" });\n  }\n}\n","import type { ClientCryptoKeyLink } from \"@nice-code/util\";\nimport type { TFrame } from \"../Carrier/Carrier.types\";\nimport {\n  ESecurityLevel,\n  type IClientVerifyKeyResolver,\n  type TServerDictionaryVersionResolver,\n} from \"../crypto/actionHandshake\";\nimport {\n  encodeProtocolFrame,\n  peekProtocolPrefix,\n  protocolCap,\n  protocolsFromCaps,\n  WIRE_PROTOCOL_PREFIX,\n  WIRE_PROTOCOL_PREFIX_MAX,\n} from \"../Mux/protocolFrame\";\nimport { type IRuntimeCoordinate, RuntimeCoordinate } from \"../RuntimeCoordinate\";\nimport {\n  AcceptorSecureSession,\n  type IAcceptorAuthResult,\n} from \"../SecureSession/acceptorSecureSession\";\nimport { type TWireTapFn, wireFrameByteSize } from \"../tap/wireTap\";\nimport type {\n  IWireAcceptor,\n  IWireConnectionBinding,\n  TWireOnConnectionBound,\n} from \"./Connect.types\";\n\n/**\n * Wire-level keepalive: the acceptor answers a literal `\"ping\"` text frame with\n * `\"pong\"` before any other dispatch, so connection health never involves the lane or a protocol.\n * On Cloudflare the DO host answers it below this layer (`setWebSocketAutoResponse`) and the frame\n * never reaches {@link WireAcceptor.receive} — this path makes every other host behave the same.\n */\nconst KEEPALIVE_PING = \"ping\";\nconst KEEPALIVE_PONG = \"pong\";\n\n/**\n * An acceptor-side wire protocol (the server half of {@link IWireProtocol}): a protocol module\n * riding an acceptor's connections beside the lane. The connection-scoped twin of the client\n * mux's `IWireFrameProtocol` — `onFrame` receives the originating connection because one acceptor\n * serves many peers. Register at construction (`protocols`) or via\n * {@link WireAcceptor.registerProtocol}; the acceptor dispatches reserved-prefix frames\n * (`0x01`–`0x0F`) here per connection, advertises `proto:<id>` in its handshake welcome, and fires\n * attach/detach around the connection lifecycle (including hibernation resume). `send` writes one\n * protocol payload back to that connection — prefixed here, encrypted by the secure session.\n */\nexport interface IWireAcceptorProtocol<TConn> {\n  readonly id: string;\n  readonly prefixByte: number;\n  onFrame(\n    connection: TConn,\n    payload: Uint8Array,\n    send: (payload: Uint8Array) => void,\n    context?: IWireAcceptorProtocolContext,\n  ): void;\n  onAttach?(\n    connection: TConn,\n    send: (payload: Uint8Array) => void,\n    context?: IWireAcceptorProtocolContext,\n  ): void;\n  onDetach?(connection: TConn, context?: IWireAcceptorProtocolContext): void;\n  /**\n   * Security gate opt-in: by default the acceptor drops protocol frames — and skips\n   * lifecycle hooks — on connections at the `none` level, where the peer identity is\n   * self-asserted. A protocol that genuinely works on plain (dev/trusted-network) connections\n   * opts in here.\n   */\n  allowPlain?: boolean;\n}\n\n/** Trusted connection facts supplied by `WireAcceptor` to protocol hooks. */\nexport interface IWireAcceptorProtocolContext {\n  /** Bound peer identity; undefined before authentication or plain-lane binding. */\n  client: RuntimeCoordinate | undefined;\n  /** Negotiated security level; `none` for plain or not-yet-authenticated connections. */\n  level: ESecurityLevel;\n}\n\n/**\n * Server-side secure-channel config — the acceptor twin of `IWireSecureClientConfig`. When set,\n * each connection negotiates a level from {@link securityLevel}: an `authenticated`/`encrypted`\n * client must complete the handshake (and is then bound to its *authenticated* coordinate) before\n * any lane or protocol frame is accepted. A `none` client (only when `none` is in the allowed\n * set) is accepted as-is with a self-asserted identity.\n */\nexport interface IWireAcceptorSecurity {\n  /**\n   * Accepted level(s). A single level is strict; an array is a negotiable allowed set — the server\n   * adopts whichever level each client requests (e.g. `[none, authenticated, encrypted]` serves\n   * all three over one endpoint).\n   */\n  securityLevel: ESecurityLevel | readonly ESecurityLevel[];\n  /** This server's crypto identity (verify + exchange key pairs, optionally persisted). */\n  link: ClientCryptoKeyLink;\n  /** This server's coordinate — its identity to clients during the handshake. */\n  localCoordinate: IRuntimeCoordinate;\n  /** Trust decision for a client's verify key (defaults to in-memory TOFU inside the handshake). */\n  verifyKeyResolver?: IClientVerifyKeyResolver;\n}\n\n/**\n * The lane protocol's acceptor-side hooks (E5, transitional until Phase 5 formalizes\n * `IWireLaneProtocol` on both sides): the one consumer of every frame the prefix registry doesn't\n * claim, plus the owner of the binding's opaque {@link IWireConnectionBinding.lane} slot. Action's\n * `ChannelAcceptor` is the only production implementation.\n */\nexport interface IWireAcceptorLane<TConn> {\n  /**\n   * The lane's handshake version payload (E5, formalized at the connection design) — a fixed string, or a\n   * resolver composing it from the peer's hello (a multi-channel lane). Wire treats it opaquely\n   * but signs it into the challenge under its byte-frozen wire name; the handshake rejects on a\n   * mismatch. Required when the acceptor has a security config (the handshake cannot run\n   * without it); irrelevant on a plain acceptor.\n   */\n  dictionaryVersion?: string | TServerDictionaryVersionResolver;\n  /**\n   * One inbound lane frame (anything unprefixed), already decrypted, with the connection's\n   * negotiated security level. On a plain connection the level is `none` and the frame's identity\n   * is self-asserted — the lane binds it via {@link WireAcceptor.bindPlainConnection}.\n   */\n  onFrame(connection: TConn, frame: TFrame, level: ESecurityLevel): void;\n  /**\n   * The connection's handshake completed — fired after the identity is bound but before protocols\n   * attach and the binding persists, so the lane can capture its negotiated facts (encoding,\n   * channel tags) in time for {@link bindingState}.\n   */\n  onAuthenticated?(connection: TConn, auth: IAcceptorAuthResult): void;\n  /** The lane's opaque slot persisted on the connection's binding — read at every persist. */\n  bindingState?(connection: TConn): unknown;\n  /** Restore the lane slot from a rehydrated binding (fired before protocols re-attach). */\n  restoreBindingState?(connection: TConn, lane: unknown): void;\n  /**\n   * The connection is being dropped — fired with its bound client (if any) before the acceptor\n   * fans protocol `onDetach` and forgets the identity, so lane cleanup keyed by the client\n   * (reliable-stream latches, codecs) still resolves it.\n   */\n  onDrop?(connection: TConn, client: RuntimeCoordinate | undefined): void;\n}\n\nexport interface IWireAcceptorOptions<TConn> {\n  /** Write a raw frame to a specific live connection (e.g. `(ws, frame) => ws.send(frame)`). */\n  send: (connection: TConn, frame: TFrame) => void;\n  /**\n   * Close a live connection (e.g. `(ws) => ws.close(1008)`). Used after a handshake reject so a\n   * refused peer cannot keep the socket open; without it the socket stays open until the peer leaves.\n   */\n  close?: (connection: TConn) => void;\n  /**\n   * Enable the authenticated (optionally encrypted) handshake. When omitted, connections are\n   * trusted as-is (identity self-asserted) — fine for dev / trusted networks.\n   */\n  security?: IWireAcceptorSecurity;\n  /** The lane protocol's hooks — the consumer of every unprefixed frame (E5). */\n  lane: IWireAcceptorLane<TConn>;\n  /** Protocol modules registered at construction (the A.2-safe path). */\n  protocols?: readonly IWireAcceptorProtocol<TConn>[];\n  /** Binding persistence hook (see {@link TWireOnConnectionBound}). */\n  onConnectionBound?: TWireOnConnectionBound<TConn>;\n  /**\n   * The server-side wire-observation seam — the acceptor's mirror of the connector's\n   * `connectChannel({ wireTap })`. Every frame that actually crosses a carrier is reported with its\n   * TRUE wire byte size (measured post-encryption on the way out, pre-decryption on the way in:\n   * exactly what the platform bills) and its lane (`handshake`, `keepalive`, `action`, or a\n   * protocol id such as `realm`), tagged with the connection's bound client as `linkId`.\n   * Sizes only, never payload contents. With no tap the cost is one null check per frame.\n   */\n  tap?: TWireTapFn;\n}\n\n/**\n * The acceptor backbone: everything between \"an inbound frame arrived on a\n * connection\" and \"a protocol module (or the lane) may handle it\" — handshake accept +\n * secure-session-per-connection, security levels, the client-identity registry, the protocol\n * registry with prefix dispatch, the **security gate** (the connection contract: protocol traffic requires an\n * authenticated connection unless the protocol opts into `allowPlain`), the **un-gated lifecycle\n * fan-out** (the connection contract: attach/detach fire for every registered protocol the gate admits, not\n * just the caps-advertised ones — both hooks are idempotent by contract, so a missing cap is a\n * non-event instead of a silent liveness hole), the versioned {@link IWireConnectionBinding}\n * persistence + {@link rehydrate} (hibernation), and the wire keepalive.\n *\n * The lane (action serving, codecs, reliability) composes on top through\n * {@link IWireAcceptorLane}; nothing here names an action or a realm.\n */\nexport class WireAcceptor<TConn> implements IWireAcceptor<TConn> {\n  private readonly _send: (connection: TConn, frame: TFrame) => void;\n  private readonly _close?: (connection: TConn) => void;\n  private readonly _tap?: TWireTapFn;\n  private readonly _security?: IWireAcceptorSecurity;\n  private readonly _lane: IWireAcceptorLane<TConn>;\n  /** Normalized accepted levels; whether `none` (plain) is allowed; whether any level needs a handshake. */\n  private readonly _allowedLevels: readonly ESecurityLevel[];\n  private readonly _noneAllowed: boolean;\n  private readonly _handshakeMode: boolean;\n  private _onConnectionBound?: TWireOnConnectionBound<TConn>;\n  private _disposed = false;\n\n  // Per-connection identity + security registries — the acceptor's backbone state (census §6).\n  private readonly _connByClient = new Map<string, TConn>();\n  private readonly _clientByConn = new Map<TConn, RuntimeCoordinate>();\n  private readonly _levelByConn = new Map<TConn, ESecurityLevel>();\n  private readonly _sessionByConn = new Map<TConn, AcceptorSecureSession>();\n  /** The last persisted (or rehydrated) binding per connection — re-persists merge through it. */\n  private readonly _bindingByConn = new Map<TConn, IWireConnectionBinding>();\n\n  /** Registered protocols by prefix byte. */\n  private readonly _protocols = new Map<number, IWireAcceptorProtocol<TConn>>();\n  /** Per-connection protocol ids the client advertised (persisted informationally on the binding). */\n  private readonly _protoIdsByConn = new Map<TConn, ReadonlySet<string>>();\n  /** Protocols already warned for gated (plain-connection) frame drops — one warning per id. */\n  private readonly _gateWarned = new Set<string>();\n\n  constructor(options: IWireAcceptorOptions<TConn>) {\n    this._send = options.send;\n    this._close = options.close;\n    this._tap = options.tap;\n    this._security = options.security;\n    this._lane = options.lane;\n    if (options.security != null && options.lane.dictionaryVersion == null) {\n      throw new Error(\n        \"WireAcceptor: a security config needs the lane's `dictionaryVersion` (E5 — the lane \" +\n          \"supplies the handshake's version payload; wire signs it into the challenge).\",\n      );\n    }\n    this._onConnectionBound = options.onConnectionBound;\n    this._allowedLevels =\n      options.security == null\n        ? []\n        : Array.isArray(options.security.securityLevel)\n          ? options.security.securityLevel\n          : [options.security.securityLevel];\n    this._noneAllowed = this._allowedLevels.includes(ESecurityLevel.none);\n    this._handshakeMode = this._allowedLevels.some((level) => level !== ESecurityLevel.none);\n    for (const protocol of options.protocols ?? []) this.registerProtocol(protocol);\n  }\n\n  /* ============================== RECEIVE ============================== */\n\n  /** Feed one inbound frame from a connection: keepalive, then handshake/session, then dispatch. */\n  receive(connection: TConn, frame: TFrame): void {\n    if (this._disposed) return;\n    // Measured HERE — before decryption — so the tap reports the frame exactly as the carrier\n    // delivered it. The lane label can only be read once the plaintext reveals its prefix, so the\n    // size rides along to the routing callbacks below (the connector does the same in its pipe).\n    const wireBytes = this._tap != null ? wireFrameByteSize(frame) : 0;\n\n    // Wire keepalive: answered here so it never consults the session (a plain \"ping\" must not\n    // flip an undecided secure connection to plain) and never reaches the lane.\n    if (frame === KEEPALIVE_PING) {\n      this._tapIn(connection, wireBytes, \"keepalive\");\n      this._writeTapped(connection, KEEPALIVE_PONG, \"keepalive\");\n      return;\n    }\n\n    const security = this._security;\n    // No security configured, or only `none` accepted → always plain (synchronous, self-asserted).\n    if (security == null || !this._handshakeMode) {\n      this._receivePlain(connection, frame, wireBytes);\n      return;\n    }\n\n    // A secure host may also expose an explicitly `allowPlain` side protocol (the token-gated\n    // devtools dial-in is the concrete case). Route that protocol before creating a secure session:\n    // once a connection has entered the handshake/session path, every frame must continue through\n    // that session and only its decrypted plaintext may reach protocols.\n    if (!this._sessionByConn.has(connection)) {\n      const prefix = peekProtocolPrefix(frame);\n      const protocol = prefix == null ? undefined : this._protocols.get(prefix);\n      if (protocol?.allowPlain === true) {\n        this._tapIn(connection, wireBytes, protocol.id);\n        const bytes = frame instanceof Uint8Array ? frame : new Uint8Array(frame as ArrayBuffer);\n        protocol.onFrame(\n          connection,\n          bytes.subarray(1),\n          this.protocolSendFor(connection, protocol),\n          this._protocolContext(connection),\n        );\n        return;\n      }\n    }\n\n    // Secure mode: the per-connection session drives the handshake + decryption (serialized\n    // internally) and routes back through the callbacks wired in `_sessionFor`.\n    this._sessionFor(connection, security).receive(frame, wireBytes);\n  }\n\n  private _receivePlain(connection: TConn, frame: TFrame, wireBytes = 0): void {\n    if (this._disposed) return;\n    this._tapIn(connection, wireBytes, this._laneFor(frame));\n    if (this._dispatchProtocolFrame(connection, frame)) return;\n    this._lane.onFrame(connection, frame, ESecurityLevel.none);\n  }\n\n  /** Route a decrypted frame from an authenticated connection: protocols first, then the lane. */\n  private _routeAuthed(connection: TConn, bytes: TFrame, wireBytes = 0): void {\n    if (this._disposed) return;\n    this._tapIn(connection, wireBytes, this._laneFor(bytes));\n    if (this._dispatchProtocolFrame(connection, bytes)) return;\n    this._lane.onFrame(\n      connection,\n      bytes,\n      this._levelByConn.get(connection) ?? ESecurityLevel.authenticated,\n    );\n  }\n\n  /* ============================== WIRE TAP ============================== */\n\n  /**\n   * The lane a *plaintext* frame belongs to: a reserved-prefix frame names its protocol\n   * (`realm`, …); everything else is the action lane. Mirrors the connector's\n   * `mux.protocolIdFor(frame) ?? \"protocol\"` / `\"action\"` split so both ends label alike.\n   */\n  private _laneFor(frame: TFrame): string {\n    const prefix = peekProtocolPrefix(frame);\n    if (prefix == null) return \"action\";\n    return this._protocols.get(prefix)?.id ?? \"protocol\";\n  }\n\n  /** A connection's bound client, so a multi-client server attributes traffic per link. */\n  private _linkId(connection: TConn): string | undefined {\n    return this._clientByConn.get(connection)?.stringId;\n  }\n\n  private _tapIn(connection: TConn, bytes: number, lane: string): void {\n    this._tap?.({ dir: \"in\", bytes, lane, linkId: this._linkId(connection) });\n  }\n\n  /** The one outbound write: measured post-encryption, exactly as the carrier transmits it. */\n  private _writeTapped(connection: TConn, frame: TFrame, lane: string): void {\n    this._tap?.({\n      dir: \"out\",\n      bytes: wireFrameByteSize(frame),\n      lane,\n      linkId: this._linkId(connection),\n    });\n    this._send(connection, frame);\n  }\n\n  /* ============================== PROTOCOLS ============================== */\n\n  /**\n   * Register a protocol module. Prefer registration at construction (`protocols`) — this method\n   * exists for composition layers that assemble the acceptor before its protocols (it is safe\n   * until the first connection's handshake, which snapshots the advertised caps).\n   */\n  registerProtocol(protocol: IWireAcceptorProtocol<TConn>): void {\n    if (\n      protocol.prefixByte <= WIRE_PROTOCOL_PREFIX.invalid ||\n      protocol.prefixByte > WIRE_PROTOCOL_PREFIX_MAX\n    ) {\n      throw new Error(\n        `registerFrameProtocol(\"${protocol.id}\"): prefix 0x${protocol.prefixByte.toString(16)} outside the reserved range`,\n      );\n    }\n    if (this._protocols.has(protocol.prefixByte)) {\n      throw new Error(\n        `registerFrameProtocol(\"${protocol.id}\"): prefix 0x${protocol.prefixByte.toString(16)} already registered`,\n      );\n    }\n    this._protocols.set(protocol.prefixByte, protocol);\n  }\n\n  /** The `proto:<id>` caps to advertise in this acceptor's handshake welcome. */\n  private _protocolCaps(): string[] | undefined {\n    if (this._protocols.size === 0) return undefined;\n    return [...this._protocols.values()].map((protocol) => protocolCap(protocol.id));\n  }\n\n  /** Per-connection protocol send: prefix here, encrypt via the secure session when present. */\n  protocolSendFor(\n    connection: TConn,\n    protocol: IWireAcceptorProtocol<TConn>,\n  ): (payload: Uint8Array) => void {\n    return (payload: Uint8Array): void => {\n      this.sendTo(connection, encodeProtocolFrame(protocol.prefixByte, payload));\n    };\n  }\n\n  /**\n   * Whether a protocol may speak on a connection — the security gate (A.6). Protocol traffic and\n   * lifecycle require an authenticated peer: on a `none`-level connection the binding identity is\n   * self-asserted, so `allowPlain` is the explicit opt-in for dev/trusted-network setups.\n   */\n  private _gateAdmits(connection: TConn, protocol: IWireAcceptorProtocol<TConn>): boolean {\n    if (protocol.allowPlain === true) return true;\n    const level = this._levelByConn.get(connection) ?? ESecurityLevel.none;\n    return level !== ESecurityLevel.none;\n  }\n\n  /**\n   * Protocol frame dispatch: a reserved-prefix frame belongs to a registered protocol and never\n   * falls through to the lane — an unknown prefix is consumed-and-dropped (negotiation should\n   * prevent it; mis-decoding it would be worse), and so is a frame the security gate blocks.\n   */\n  private _dispatchProtocolFrame(connection: TConn, frame: TFrame): boolean {\n    const prefix = peekProtocolPrefix(frame);\n    if (prefix == null) return false;\n    const protocol = this._protocols.get(prefix);\n    if (prefix === WIRE_PROTOCOL_PREFIX.invalid || protocol == null) return true;\n    if (!this._gateAdmits(connection, protocol)) {\n      if (!this._gateWarned.has(protocol.id)) {\n        this._gateWarned.add(protocol.id);\n        console.warn(\n          `[wire-acceptor] dropped a \"${protocol.id}\" protocol frame from an unauthenticated ` +\n            \"(plain) connection — protocol traffic requires an authenticated peer. Set \" +\n            \"`allowPlain: true` on the protocol if this endpoint is deliberately plain (A.6).\",\n        );\n      }\n      return true;\n    }\n    const bytes = frame instanceof Uint8Array ? frame : new Uint8Array(frame as ArrayBuffer);\n    protocol.onFrame(\n      connection,\n      bytes.subarray(1),\n      this.protocolSendFor(connection, protocol),\n      this._protocolContext(connection),\n    );\n    return true;\n  }\n\n  /**\n   * Fire `onAttach` for **every registered protocol the gate admits** (fresh handshake or\n   * rehydrate) — deliberately not filtered by the client's advertised caps (A.2.3): the hooks are\n   * idempotent by contract, so an empty/missing caps list degrades to a no-op on the peer instead\n   * of a silently missed wake resume. The advertised ids are still recorded (and persisted on the\n   * binding) as the negotiation facts.\n   */\n  private _attachProtocols(connection: TConn, advertisedIds: ReadonlySet<string>): void {\n    this._protoIdsByConn.set(connection, advertisedIds);\n    for (const protocol of this._protocols.values()) {\n      if (!this._gateAdmits(connection, protocol)) continue;\n      protocol.onAttach?.(\n        connection,\n        this.protocolSendFor(connection, protocol),\n        this._protocolContext(connection),\n      );\n    }\n  }\n\n  /* ============================== SECURE SESSION ============================== */\n\n  /**\n   * The secure session for a connection (built lazily on its first secure-mode frame). The\n   * session owns all crypto/handshake/chain state; the acceptor keeps only the registries.\n   */\n  private _sessionFor(connection: TConn, security: IWireAcceptorSecurity): AcceptorSecureSession {\n    let session = this._sessionByConn.get(connection);\n    if (session == null) {\n      // The lane supplies the handshake's version payload (E5) — non-null by the constructor\n      // guard whenever a security config exists.\n      const dictionaryVersion = this._lane.dictionaryVersion;\n      if (dictionaryVersion == null) {\n        throw new Error(\"WireAcceptor: missing lane dictionaryVersion for a secure session\");\n      }\n      session = new AcceptorSecureSession({\n        link: security.link,\n        localCoordinate: security.localCoordinate,\n        dictionaryVersion,\n        securityLevel: security.securityLevel,\n        verifyKeyResolver: security.verifyKeyResolver,\n        extraCaps: this._protocolCaps(),\n        noneAllowed: this._noneAllowed,\n        // A pipe-originated write carries its lane; a bare handshake write has none (it IS the\n        // handshake), so that is the honest default here.\n        send: (frame, tapLane) => this._writeTapped(connection, frame, tapLane ?? \"handshake\"),\n        close: this._close == null ? undefined : () => this._close?.(connection),\n        tap: this._tap,\n        onAuthenticated: (auth) => this._onAuthenticated(connection, auth),\n        routePlain: (frame, wireBytes) => this._receivePlain(connection, frame, wireBytes),\n        routeAction: (bytes, wireBytes) => this._routeAuthed(connection, bytes, wireBytes),\n      });\n      this._sessionByConn.set(connection, session);\n    }\n    return session;\n  }\n\n  /** Bind + persist a connection's authenticated identity once its handshake completes. */\n  private _onAuthenticated(connection: TConn, auth: IAcceptorAuthResult): void {\n    if (this._disposed) return;\n    this._bind(connection, auth.client, auth.securityLevel);\n    this._levelByConn.set(connection, auth.securityLevel);\n\n    // The lane captures its negotiated facts (encoding, channel tags) before anything reads them.\n    this._lane.onAuthenticated?.(connection, auth);\n\n    // Lifecycle fan-out (A.2.3) — protocols may now speak on this connection.\n    const advertisedIds = protocolsFromCaps(auth.remoteCaps);\n    this._attachProtocols(connection, advertisedIds);\n\n    // Persist the binding so an evicted connection can resume without re-handshaking.\n    this._persist(connection, {\n      v: 1,\n      client: auth.client.toJsonObject(),\n      secure: {\n        securityLevel: auth.securityLevel,\n        linkedClientId: auth.linkedClientId,\n        keyMaterial: auth.keyMaterial,\n      },\n      protocols: advertisedIds.size > 0 ? [...advertisedIds] : undefined,\n      lane: this._lane.bindingState?.(connection),\n    });\n  }\n\n  /* ============================== BINDINGS ============================== */\n\n  /** Install (or replace) the binding persistence hook after construction. */\n  setOnConnectionBound(onConnectionBound: TWireOnConnectionBound<TConn>): void {\n    this._onConnectionBound = onConnectionBound;\n  }\n\n  /**\n   * Plain-path identity binding: bind the connection to a self-asserted client coordinate (the\n   * lane decoded it off an inbound frame) and persist a fresh binding when the identity is new.\n   * Secure mode never calls this — the handshake binds the authenticated coordinate instead. While\n   * another live connection holds that coordinate through a handshake, pushes and\n   * `connectionForClient` keep resolving to it; the plain claim takes over only once it drops.\n   */\n  bindPlainConnection(connection: TConn, client: RuntimeCoordinate): void {\n    if (this._disposed) return;\n    const isNewBinding = this._clientByConn.get(connection)?.stringId !== client.stringId;\n    this._bind(connection, client, ESecurityLevel.none);\n    if (isNewBinding) {\n      this._persist(connection, {\n        v: 1,\n        client: client.toJsonObject(),\n        lane: this._lane.bindingState?.(connection),\n      });\n    }\n  }\n\n  /**\n   * Restore a connection→client binding without an inbound frame — for transports that resume\n   * after eviction. Pair it with `onConnectionBound`: persist the binding there, then replay each\n   * live connection here when the channel comes back (e.g. a Durable Object iterating\n   * `ctx.getWebSockets()` as it wakes from hibernation). A binding of an unknown schema version\n   * is ignored with a warning — the socket is simply treated as fresh (its client re-handshakes).\n   */\n  rehydrate(connection: TConn, binding: IWireConnectionBinding): void {\n    if (this._disposed) return;\n    if (binding.v !== 1) {\n      console.warn(\n        `[wire-acceptor] ignored a persisted connection binding of unknown schema version ` +\n          `${JSON.stringify((binding as { v?: unknown }).v)} (expected 1) — treating the ` +\n          \"connection as fresh (err_nice_wire_connect.binding_version_mismatch).\",\n      );\n      return;\n    }\n    const secure = binding.secure;\n    const security = this._security;\n    const level = secure != null && security != null ? secure.securityLevel : ESecurityLevel.none;\n    this._bind(connection, new RuntimeCoordinate(binding.client), level);\n    this._bindingByConn.set(connection, binding);\n    this._lane.restoreBindingState?.(connection, binding.lane);\n\n    if (secure != null && security != null) {\n      this._levelByConn.set(connection, secure.securityLevel);\n      // The connection had already authenticated before eviction — resume its secure session (no\n      // handshake; an encrypted session re-derives its shared key off the persisted identity).\n      this._sessionFor(connection, security).rehydrate(secure);\n    }\n\n    // Re-fire the lifecycle for every registered protocol the gate admits (A.2.3) so a\n    // hibernation-resumed connection gets its wake resume even if its persisted caps were empty.\n    this._attachProtocols(connection, new Set(binding.protocols ?? []));\n  }\n\n  private _persist(connection: TConn, binding: IWireConnectionBinding): void {\n    if (this._disposed) return;\n    this._bindingByConn.set(connection, binding);\n    this._onConnectionBound?.(connection, binding);\n  }\n\n  private _bind(connection: TConn, client: RuntimeCoordinate, level: ESecurityLevel): void {\n    const previous = this._clientByConn.get(connection);\n    if (\n      previous != null &&\n      previous.stringId !== client.stringId &&\n      this._connByClient.get(previous.stringId) === connection\n    ) {\n      this._connByClient.delete(previous.stringId);\n    }\n    this._clientByConn.set(connection, client);\n    // A self-asserted identity never takes the client→connection slot (pushes, return routing)\n    // from a live connection that authenticated as that coordinate.\n    const holder = this._connByClient.get(client.stringId);\n    if (\n      level === ESecurityLevel.none &&\n      holder != null &&\n      holder !== connection &&\n      this.levelFor(holder) !== ESecurityLevel.none\n    ) {\n      return;\n    }\n    this._connByClient.set(client.stringId, connection);\n  }\n\n  /* ============================== LIFECYCLE + LOOKUPS ============================== */\n\n  /** Forget a connection (call on socket close) so stale entries don't misroute later traffic. */\n  drop(connection: TConn): void {\n    if (this._disposed) return;\n    this._drop(connection);\n  }\n\n  /** Internal detach path used once during terminal disposal after public entry points are closed. */\n  private _drop(connection: TConn): void {\n    const client = this._clientByConn.get(connection);\n    // Guard the reverse entry: the client may already have reconnected on a newer socket.\n    if (client != null && this._connByClient.get(client.stringId) === connection) {\n      this._connByClient.delete(client.stringId);\n    }\n\n    // Lane cleanup first — it may still need the bound client (stream latches are keyed by it).\n    this._lane.onDrop?.(connection, client);\n\n    // Protocol detach fan-out (A.2.3): every registered protocol, un-gated — detach is cleanup\n    // and must never be skipped; the hooks are idempotent no-ops for a connection they never saw.\n    for (const protocol of this._protocols.values()) {\n      protocol.onDetach?.(connection, this._protocolContext(connection));\n    }\n\n    this._protoIdsByConn.delete(connection);\n    this._clientByConn.delete(connection);\n    this._sessionByConn.delete(connection);\n    this._levelByConn.delete(connection);\n    this._bindingByConn.delete(connection);\n  }\n\n  /** Send a raw (already lane/protocol-encoded) frame — through the secure session when present. */\n  sendTo(connection: TConn, frame: TFrame): void {\n    if (this._disposed) return;\n    // Read the lane off the plaintext here; it rides the session/pipe so the eventual (encrypted)\n    // write reports the right lane with the right byte count.\n    const lane = this._laneFor(frame);\n    const session = this._sessionByConn.get(connection);\n    if (session == null) {\n      this._writeTapped(connection, frame, lane);\n      return;\n    }\n    session.send(frame, lane);\n  }\n\n  /** Live connection for a client coordinate's stringId, if currently registered. */\n  connectionForClient(clientStringId: string): TConn | undefined {\n    return this._connByClient.get(clientStringId);\n  }\n\n  /** The bound client coordinate for a connection, if any. */\n  clientForConnection(connection: TConn): RuntimeCoordinate | undefined {\n    return this._clientByConn.get(connection);\n  }\n\n  /** Whether this acceptor currently holds a live connection bound to the client. */\n  ownsLiveConnectionFor(clientStringId: string): boolean {\n    return this._connByClient.has(clientStringId);\n  }\n\n  /** Whether this acceptor currently tracks `connection`. */\n  hasConnection(connection: TConn): boolean {\n    return this._clientByConn.has(connection);\n  }\n\n  /** Every currently-bound connection (mid-handshake sockets are not yet bound). */\n  connections(): IterableIterator<TConn> {\n    return this._clientByConn.keys();\n  }\n\n  /** The number of currently-bound connections. */\n  get connectionCount(): number {\n    return this._clientByConn.size;\n  }\n\n  /** The connection's negotiated security level (`none` when plain / not yet handshaken). */\n  levelFor(connection: TConn): ESecurityLevel {\n    return this._levelByConn.get(connection) ?? ESecurityLevel.none;\n  }\n\n  private _protocolContext(connection: TConn): IWireAcceptorProtocolContext {\n    return {\n      client: this._clientByConn.get(connection),\n      level: this._levelByConn.get(connection) ?? ESecurityLevel.none,\n    };\n  }\n\n  /** The last persisted (or rehydrated) binding for a connection, if any. */\n  bindingFor(connection: TConn): IWireConnectionBinding | undefined {\n    return this._bindingByConn.get(connection);\n  }\n\n  /** Quiesce permanently: detach every known connection and ignore late/in-flight traffic. */\n  dispose(): void {\n    if (this._disposed) return;\n    this._disposed = true;\n    const connections = new Set<TConn>([\n      ...this._clientByConn.keys(),\n      ...this._sessionByConn.keys(),\n      ...this._bindingByConn.keys(),\n    ]);\n    for (const connection of connections) this._drop(connection);\n  }\n\n  get disposed(): boolean {\n    return this._disposed;\n  }\n}\n\nexport const createWireAcceptor = <TConn>(\n  options: IWireAcceptorOptions<TConn>,\n): WireAcceptor<TConn> => {\n  return new WireAcceptor<TConn>(options);\n};\n","import { ClientCryptoKeyLink, type StorageAdapter } from \"@nice-code/util\";\nimport type { IDuplexAcceptorCarrier } from \"../Carrier/AcceptorCarrier\";\nimport type { TFrame } from \"../Carrier/Carrier.types\";\nimport {\n  createStorageTofuVerifyKeyResolver,\n  ESecurityLevel,\n  type IClientVerifyKeyResolver,\n} from \"../crypto/actionHandshake\";\nimport type { RuntimeCoordinate } from \"../RuntimeCoordinate\";\nimport type { TWireTapFn } from \"../tap/wireTap\";\nimport { wireBindingFromAttachment } from \"./connectionBinding\";\nimport { lanelessAcceptorLane } from \"./lanelessLane\";\nimport {\n  type IWireAcceptorProtocol,\n  type IWireAcceptorSecurity,\n  WireAcceptor,\n} from \"./WireAcceptor\";\n\nconst DEFAULT_SERVER_SECURITY_LEVELS = [\n  ESecurityLevel.none,\n  ESecurityLevel.authenticated,\n  ESecurityLevel.encrypted,\n] as const;\n\nexport interface IServeWireOptions<TConn> {\n  identity: RuntimeCoordinate;\n  /** Exactly one duplex carrier. Protocols require a push-capable connection. */\n  carriers: readonly IDuplexAcceptorCarrier<TConn>[];\n  protocols?: readonly IWireAcceptorProtocol<TConn>[];\n  storage?: StorageAdapter;\n  link?: ClientCryptoKeyLink;\n  verifyKeyResolver?: IClientVerifyKeyResolver;\n  securityLevel?: ESecurityLevel | readonly ESecurityLevel[];\n  wireTap?: TWireTapFn;\n}\n\nexport interface IWireServer<TConn> {\n  acceptor: WireAcceptor<TConn>;\n  fetch(request: Request): Promise<Response>;\n  receive(connection: TConn, frame: TFrame): void;\n  drop(connection: TConn): void;\n  close(): void;\n}\n\n/**\n * Serve a lane-less wire connection on Bun, Node, or any custom host. The caller owns socket\n * upgrades and forwards frames through the returned carrier/server lifecycle. No action runtime or\n * empty action channel is involved.\n */\nexport function serveWire<TConn>(options: IServeWireOptions<TConn>): IWireServer<TConn> {\n  if (options.carriers.length !== 1) {\n    throw new Error(\"serveWire requires exactly one duplex carrier\");\n  }\n  const carrier = options.carriers[0];\n  const secure = carrier.secure ?? true;\n  let security: IWireAcceptorSecurity | undefined;\n  if (secure) {\n    if (options.storage == null && (options.link == null || options.verifyKeyResolver == null)) {\n      throw new Error(\n        \"serveWire: a secure carrier requires `storage`, or both `link` and `verifyKeyResolver`\",\n      );\n    }\n    const storage = options.storage;\n    security = {\n      securityLevel: options.securityLevel ?? DEFAULT_SERVER_SECURITY_LEVELS,\n      link: options.link ?? new ClientCryptoKeyLink({ storageAdapter: storage as StorageAdapter }),\n      localCoordinate: options.identity,\n      verifyKeyResolver:\n        options.verifyKeyResolver ??\n        (storage != null ? createStorageTofuVerifyKeyResolver(storage) : undefined),\n    };\n  }\n\n  const asObject = (value: unknown): object =>\n    typeof value === \"object\" && value != null ? value : {};\n  const attachmentStore = carrier.attachmentStore;\n  const acceptor = new WireAcceptor<TConn>({\n    send: carrier.send,\n    close: carrier.close,\n    tap: options.wireTap,\n    security,\n    lane: lanelessAcceptorLane<TConn>(),\n    protocols: options.protocols,\n    onConnectionBound:\n      attachmentStore == null\n        ? undefined\n        : (connection, binding) =>\n            attachmentStore.write(connection, {\n              ...asObject(attachmentStore.read(connection)),\n              binding,\n            }),\n  });\n\n  try {\n    if (attachmentStore != null) {\n      for (const connection of attachmentStore.getConnections()) {\n        const binding = wireBindingFromAttachment(attachmentStore.read(connection));\n        if (binding != null) acceptor.rehydrate(connection, binding);\n      }\n    }\n\n    carrier._activate({\n      receive: (connection, frame) => acceptor.receive(connection, frame),\n      drop: (connection) => acceptor.drop(connection),\n    });\n  } catch (error) {\n    try {\n      carrier._dispose?.();\n    } finally {\n      acceptor.dispose();\n    }\n    throw error;\n  }\n\n  let closed = false;\n  return {\n    acceptor,\n    fetch: async (request) => {\n      if (closed) return new Response(\"Wire server closed\", { status: 503 });\n      const url = new URL(request.url);\n      const isUpgrade = carrier.isUpgrade?.(request, url) ?? false;\n      if (isUpgrade && carrier.upgrade != null) return carrier.upgrade(request, url);\n      return new Response(\"Expected a duplex carrier upgrade\", {\n        status: carrier.upgrade == null ? 501 : 426,\n      });\n    },\n    receive: (connection, frame) => carrier.receive(connection, frame),\n    drop: (connection) => carrier.drop(connection),\n    close: () => {\n      if (closed) return;\n      closed = true;\n      try {\n        carrier._dispose?.();\n      } finally {\n        acceptor.dispose();\n      }\n    },\n  };\n}\n","import { base64ToBytes, bytesToBase64 } from \"@nice-code/util\";\nimport { createActionFrameCrypto, type IActionFrameCrypto } from \"../crypto/actionFrameCrypto\";\nimport {\n  createServerHandshake,\n  decodeHandshakeMessage,\n  EHandshakeMessageType,\n  ESecurityLevel,\n  encodeHandshakeMessage,\n  type IHandshakeEncryptionKeyMaterial,\n  type IServerHandshake,\n  type IServerHandshakePending,\n  type TServerDictionaryVersionResolver,\n} from \"../crypto/actionHandshake\";\nimport { type IRuntimeCoordinate, RuntimeCoordinate } from \"../RuntimeCoordinate\";\nimport {\n  createExchangeTicketSealer,\n  type IExchangeTicketSealer,\n} from \"../SecureSession/exchangeTicketSeal\";\nimport {\n  decodeExchangeRequest,\n  encodeExchange,\n  type TWireExchangeReply,\n  WIRE_EXCHANGE_SESSION_REFUSED,\n} from \"./exchangeEnvelope\";\nimport type { IWireAcceptorSecurity } from \"./WireAcceptor\";\n\n/** The default session-ticket lifetime — see {@link IWireExchangeAcceptorOptions.sessionTtlMs}. */\nconst DEFAULT_SESSION_TTL_MS = 12 * 60 * 60 * 1000;\n/** The handshake continuation (`hsc`) only bridges the two handshake POSTs, so it expires quickly. */\nconst HANDSHAKE_CONTINUATION_TTL_MS = 2 * 60 * 1000;\n\n/**\n * One authenticated `act` request as the lane sees it: the opened (decrypted) lane wire plus the\n * session facts the acceptor resolved from the ticket.\n */\nexport interface IWireExchangeLaneRequest {\n  /** The decoded lane wire from the `act` envelope (opaque JSON to wire — E5). */\n  wire: unknown;\n  /** The handshake-authenticated client coordinate; absent on a plain (`none`, tokenless) request. */\n  client?: RuntimeCoordinate;\n  /** The level this request actually arrived at — `encrypted` only for a decrypted ciphertext act. */\n  securityLevel: ESecurityLevel;\n  /** Whether this request arrived as ciphertext (its reply rides the same crypto). */\n  encrypted: boolean;\n}\n\n/** The lane's reply: its result wire, or a message wire answers as the `err` envelope. */\nexport type TWireExchangeLaneReply = { ok: true; wire: unknown } | { ok: false; message: string };\n\n/**\n * The lane's acceptor-side hooks for the exchange path — the request/reply twin of\n * `IWireAcceptorLane`. The exchange is **lane-only**: no protocol registry rides\n * here, so the whole surface is the handshake payload plus one request handler.\n */\nexport interface IWireExchangeAcceptorLane {\n  /**\n   * The lane's handshake version payload (E5) — a fixed string, or a resolver composing it from\n   * the peer's hello `channels` (a multi-channel lane). Wire treats it opaquely but signs it into\n   * the challenge under its byte-frozen wire name; the handshake rejects on a mismatch.\n   */\n  dictionaryVersion: string | TServerDictionaryVersionResolver;\n  /**\n   * Serve one opened `act` request, returning the lane's reply wire (it rides the same response,\n   * encrypted when the request was). The identity in {@link IWireExchangeLaneRequest.client} is\n   * the handshake-authenticated one — the lane binds it onto its wire, never the self-asserted.\n   */\n  onExchange(request: IWireExchangeLaneRequest): Promise<TWireExchangeLaneReply>;\n}\n\nexport interface IWireExchangeAcceptorOptions {\n  /** The acceptor's crypto identity + accepted level(s) — same shape the duplex acceptor uses. */\n  security: IWireAcceptorSecurity;\n  /** The lane's hooks — the exchange path's one consumer (lane-only, no protocols). */\n  lane: IWireExchangeAcceptorLane;\n  /**\n   * How long a minted session ticket stays valid (ms), told to the client on accept. After it\n   * expires the acceptor refuses it and the client handshakes again. Defaults to 12h — long enough for an ordinary session's\n   * life, since a sealed ticket carries no server state to revoke before then. Keep it shorter for\n   * a more tightly time-boxed session.\n   */\n  sessionTtlMs?: number;\n}\n\n/** The sealed session ticket: everything a later `act` POST needs to authenticate + decrypt, opaque\n * to the client. It IS the session — no server-side entry exists to look up or revoke. */\ninterface IWireExchangeSessionTicket {\n  /** The handshake-authenticated client coordinate (bound onto each request, never the wire's). */\n  client: IRuntimeCoordinate;\n  securityLevel: ESecurityLevel;\n  /** For the `encrypted` level: material to rebuild the per-session frame crypto on any isolate. */\n  keyMaterial?: IHandshakeEncryptionKeyMaterial;\n  /**\n   * The dictionary version agreed at the handshake; a ticket from another version is refused.\n   * Absent when sealed by an acceptor that predates it: served until it expires, since a client that\n   * predates `session_refused` cannot renew it.\n   */\n  dv?: string;\n  /** The channel tags the hello advertised, to resolve the version this acceptor serves now. */\n  ch?: readonly string[];\n}\n\n/**\n * The `hsc` continuation: the handshake's pending state with the version beside it — flat, so the\n * two handshake POSTs may land on acceptors either side of an upgrade.\n */\ntype TWireExchangeContinuation = IServerHandshakePending & { dv?: string; ch?: readonly string[] };\n\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\n\n/**\n * The exchange (request/reply) acceptor backbone — the HTTP counterpart to `WireAcceptor`'s\n * duplex sessions, re-homed from nice-action's `ExchangeAcceptor` (shared connection design,\n * Phase 6). Each POST body is one exchange envelope; the acceptor drives the server handshake\n * over the two `hs` POSTs, mints a session **token** on accept, and on every later `act` POST\n * resolves the session by token, decrypts the body (at `encrypted`), hands the opened lane wire\n * to {@link IWireExchangeAcceptorLane.onExchange}, and returns the (encrypted) reply inline.\n *\n * **Stateless.** It holds no in-memory handshakes or sessions: the in-flight handshake `pending`\n * is sealed into the `hsc` continuation token returned on `welcome` and echoed back on `prove`,\n * and the live session is sealed into the `t` token replayed on every `act`. Both are sealed\n * under the acceptor's own persisted identity ({@link createExchangeTicketSealer}), so any\n * isolate that loaded the same identity can serve any POST — no request needs to co-locate with\n * another. A tampered, wrong-key, or expired token opens to \"no valid session\".\n */\nexport class WireExchangeAcceptor {\n  private readonly _security: IWireAcceptorSecurity;\n  private readonly _lane: IWireExchangeAcceptorLane;\n  private readonly _allowedLevels: readonly ESecurityLevel[];\n  private readonly _noneAllowed: boolean;\n  private readonly _sealer: IExchangeTicketSealer;\n  private readonly _sessionTtlMs: number;\n\n  constructor(options: IWireExchangeAcceptorOptions) {\n    this._security = options.security;\n    this._lane = options.lane;\n    this._allowedLevels = Array.isArray(options.security.securityLevel)\n      ? options.security.securityLevel\n      : [options.security.securityLevel];\n    this._noneAllowed = this._allowedLevels.includes(ESecurityLevel.none);\n    this._sealer = createExchangeTicketSealer(options.security.link);\n    this._sessionTtlMs = options.sessionTtlMs ?? DEFAULT_SESSION_TTL_MS;\n  }\n\n  /** Process one POST body (an exchange envelope), returning the reply body to send back. */\n  async handlePost(body: string): Promise<string> {\n    const request = decodeExchangeRequest(body);\n    if (request == null) return this._err(\"malformed exchange request\");\n\n    // Load the persisted identity up front so this (possibly cold / stateless) instance opens sealed\n    // tokens with the *same* seal key that minted them — never a freshly forked identity. A thrown read\n    // propagates (fails the request closed); a `required`-mode link that was never provisioned throws.\n    await this._security.link.initialize();\n\n    if (request.k === \"hs\") return encodeExchange(await this._handleHandshake(request));\n    return encodeExchange(await this._handleAction(request));\n  }\n\n  private _makeHandshake(): IServerHandshake {\n    const security = this._security;\n    return createServerHandshake({\n      link: security.link,\n      localCoordinate: security.localCoordinate,\n      dictionaryVersion: this._lane.dictionaryVersion,\n      securityLevel: security.securityLevel,\n      verifyKeyResolver: security.verifyKeyResolver,\n    });\n  }\n\n  private async _handleHandshake(request: {\n    m: string;\n    hsc?: string;\n  }): Promise<TWireExchangeReply> {\n    const message = decodeHandshakeMessage(request.m);\n    if (message == null) return { k: \"err\", message: \"malformed handshake message\" };\n\n    if (message.t === EHandshakeMessageType.hello) {\n      // Fresh handshake: run hello, then seal the resulting `pending` into the `hsc` continuation token\n      // so the (stateless) prove POST can restore it on any isolate.\n      const handshake = this._makeHandshake();\n      const reply = await handshake.onHello(message);\n      if (reply.t === EHandshakeMessageType.reject) {\n        return { k: \"hs\", m: encodeHandshakeMessage(reply) };\n      }\n      const pending = handshake.exportPending();\n      const dv = this._dictionaryVersion(message.channels);\n      if (pending == null || dv == null) {\n        return { k: \"err\", message: \"handshake produced no continuation state\" };\n      }\n      const continuation: TWireExchangeContinuation = { ...pending, dv, ch: message.channels };\n      const hsc = await this._sealer.seal(continuation, HANDSHAKE_CONTINUATION_TTL_MS);\n      return { k: \"hs\", m: encodeHandshakeMessage(reply), hsc };\n    }\n\n    if (message.t === EHandshakeMessageType.prove) {\n      if (request.hsc == null) return { k: \"err\", message: \"prove missing continuation token\" };\n      const continuation = await this._sealer.open<TWireExchangeContinuation>(request.hsc);\n      if (continuation == null) {\n        return { k: \"err\", message: \"invalid or expired continuation token\" };\n      }\n      const { dv, ch, ...pending } = continuation;\n\n      const handshake = this._makeHandshake();\n      await handshake.restorePending(pending);\n      const reply = await handshake.onProve(message);\n      const result = handshake.getResult();\n      if (reply.t === EHandshakeMessageType.accept && result != null) {\n        const ticket: IWireExchangeSessionTicket = {\n          client: result.remote,\n          securityLevel: result.securityLevel,\n          keyMaterial: result.encryptionKeyMaterial,\n          dv,\n          ch,\n        };\n        const t = await this._sealer.seal(ticket, this._sessionTtlMs);\n        return { k: \"hs\", m: encodeHandshakeMessage(reply), t, ttl: this._sessionTtlMs };\n      }\n      return { k: \"hs\", m: encodeHandshakeMessage(reply) };\n    }\n\n    return { k: \"err\", message: `unexpected handshake message ${message.t}` };\n  }\n\n  private _dictionaryVersion(channels: readonly string[] | undefined): string | null {\n    const version = this._lane.dictionaryVersion;\n    return typeof version === \"function\"\n      ? version({ channels: channels == null ? undefined : [...channels] })\n      : version;\n  }\n\n  private async _handleAction(\n    request: { t?: string; i?: string } & ({ w: unknown } | { c: string }),\n  ): Promise<TWireExchangeReply> {\n    let client: RuntimeCoordinate | undefined;\n    // The per-session frame crypto, rebuilt from the ticket's key material — used to decrypt the request\n    // and (symmetrically) encrypt the reply, so an encrypted session is opened/derived exactly once.\n    let crypto: IActionFrameCrypto | undefined;\n    let wire: unknown;\n    let securityLevel: ESecurityLevel = ESecurityLevel.none;\n\n    if (request.t != null) {\n      const ticket = await this._sealer.open<IWireExchangeSessionTicket>(request.t);\n      if (ticket == null) return refused(\"unknown or expired session token\");\n      // A deploy that changed the dictionary ends its sessions; the renewed handshake says why.\n      if (ticket.dv != null && ticket.dv !== this._dictionaryVersion(ticket.ch)) {\n        return refused(\"session was agreed under another dictionary version\");\n      }\n\n      // The ticket names the principal (envId/perId); `i` names which boot of it is asking now.\n      client = new RuntimeCoordinate(\n        typeof request.i === \"string\" ? { ...ticket.client, insId: request.i } : ticket.client,\n      );\n      securityLevel = ticket.securityLevel;\n\n      if (ticket.securityLevel === ESecurityLevel.encrypted) {\n        // The ticket alone is not the session at this level: only ciphertext under its key is. A\n        // plaintext `w` here would let a lifted ticket act without the client's private key.\n        if (!(\"c\" in request)) return refused(\"encrypted session refuses a plaintext act\");\n        if (ticket.keyMaterial == null) return refused(\"encrypted session has no key material\");\n        crypto = createActionFrameCrypto({\n          link: this._security.link,\n          keyMaterial: ticket.keyMaterial,\n        });\n        try {\n          const plain = await crypto.decryptFrame(base64ToBytes(request.c));\n          wire = JSON.parse(textDecoder.decode(plain));\n        } catch {\n          return refused(\"undecryptable act\");\n        }\n      } else {\n        if (\"c\" in request) return refused(\"session is not encrypted\");\n        wire = request.w;\n      }\n    } else {\n      // No token → a plain (`none`) client; only honoured when `none` is in the allowed set.\n      if (!this._noneAllowed || \"c\" in request) {\n        return { k: \"err\", message: \"missing session token\" };\n      }\n      wire = request.w;\n    }\n\n    const laneReply = await this._lane.onExchange({\n      wire,\n      client,\n      securityLevel,\n      encrypted: crypto != null,\n    });\n    if (!laneReply.ok) return { k: \"err\", message: laneReply.message };\n\n    // An encrypted request → encrypted reply, using the same per-session crypto we decrypted with.\n    if (crypto != null) {\n      const ciphertext = await crypto.encryptFrame(\n        textEncoder.encode(JSON.stringify(laneReply.wire)),\n      );\n      return { k: \"act\", c: bytesToBase64(ciphertext) };\n    }\n    return { k: \"act\", w: laneReply.wire };\n  }\n\n  private _err(message: string): string {\n    return encodeExchange({ k: \"err\", message });\n  }\n}\n\nfunction refused(message: string): TWireExchangeReply {\n  return { k: \"err\", message, id: WIRE_EXCHANGE_SESSION_REFUSED };\n}\n","import { pack, unpack } from \"msgpackr\";\n\n/**\n * The transport **control channel** — a lightweight frame category that rides the same secure connection\n * *beside* action frames, carrying connection/transport metadata that has no business going through the\n * action machinery (no schema, no hydration, no request/response correlation, no per-channel dictionary).\n *\n * Reliability acks are the first message type; the same channel is the reusable seam for future metadata\n * (flow-control/backpressure, presence, an app-level keepalive for carriers without a native ping, …).\n *\n * ## Wire shape & why it's byte-safe next to action frames\n * A control frame is a msgpack **object** (`{ $c: <type>, … }`); the binary action codecs emit fixed-length\n * msgpack **arrays**. So a control frame never decodes as an action frame (`incoming` requires an array of\n * the envelope length) and an action frame never decodes as a control frame — best-effort action frames\n * stay byte-identical. Handshake frames are text JSON with a `t` field, also distinct.\n *\n * Keep {@link TControlMessage} a **small, closed, typed registry** of library/transport concerns — it is\n * deliberately *not* an open user side-channel (that's what actions/pushes are for).\n */\n\n/** Reliable-delivery ack: cumulative contiguous high-water the sender has for the `domain:id` stream. */\nexport interface IControlMessage_ReliableAck {\n  $c: \"rack\";\n  /** The action route the ack is for; the receiver rebuilds `reliableStreamId(peer, domain, id, k)`. */\n  domain: string;\n  id: string;\n  /** Highest contiguous seq the peer has stored for this stream. */\n  ack: number;\n  /** Optional streamKey (E3) — set for a keyed stream so the receiver rebuilds the same keyed id. */\n  k?: string;\n}\n\n/**\n * Reliable-delivery re-sync request: the receiver has **no state** for a `domain:id` stream whose incoming\n * `seq` is already past 0 — a session-tier reset (fresh process / evicted server) mid-stream. It asks the\n * sender to renumber its still-unacked frames from seq 0 and resend, so the stream continues instead of\n * stalling on an unfillable gap. Session-tier self-heal; the persisted tier resumes from storage and never\n * sends this. Route-only, like {@link IControlMessage_ReliableAck} (the stream id never rides the wire).\n */\nexport interface IControlMessage_ReliableResync {\n  $c: \"rsync\";\n  domain: string;\n  id: string;\n  /** Optional streamKey (E3) — set for a keyed stream so the sender re-syncs the same keyed stream. */\n  k?: string;\n}\n\n/**\n * Reliable-delivery skip notice (sender → receiver): every frame of the `domain:id` stream with\n * `seq <= seq` that hasn't arrived **will never arrive** — the sender abandoned it (its action aborted or\n * its delivery deadline expired) and pruned it from its outbox. The receiver advances the stream's\n * high-water past the abandoned seqs and drains anything it had buffered behind the gap, so the stream\n * *continues* instead of wedging on an unfillable gap forever. Cumulative like an ack (the sender drops\n * everything `<= seq` when it abandons a frame, so ordering among *delivered* frames is preserved).\n * Route-only + optional key, like the other reliable control messages.\n */\nexport interface IControlMessage_ReliableSkip {\n  $c: \"rskip\";\n  domain: string;\n  id: string;\n  /** Highest abandoned seq — the receiver treats all seqs `<= seq` as settled (delivered or abandoned). */\n  seq: number;\n  /** Optional streamKey (E3) — set for a keyed stream so the receiver skips the same keyed stream. */\n  k?: string;\n}\n\n/**\n * Reliable-delivery stream close (sender → receiver): the sender closed the `domain:id [+ k]` stream for\n * good (`closeReliableStream`) — the receiver should **release its state** for it (in-memory inbox entry\n * or persisted log rows + high-water) and free the key's slot in the keyed-stream quota. Purely a memory\n * reclaim: it is safe to lose (the sender's retained `rskip` already settles delivery, and a later send\n * on a receiver that *did* forget self-heals through the normal `rsync` re-sync), and safe to receive\n * twice (forgetting an unknown stream is a no-op).\n */\nexport interface IControlMessage_ReliableClose {\n  $c: \"rclose\";\n  domain: string;\n  id: string;\n  /** Optional streamKey (E3) — set for a keyed stream so the receiver releases the same keyed stream. */\n  k?: string;\n}\n\nexport type TControlMessage =\n  | IControlMessage_ReliableAck\n  | IControlMessage_ReliableResync\n  | IControlMessage_ReliableSkip\n  | IControlMessage_ReliableClose;\n\n/** msgpack map (object) first-byte prefixes — fixmap `0x80–0x8f`, map16 `0xde`, map32 `0xdf`. */\nfunction looksLikeControlFrame(buffer: Uint8Array): boolean {\n  if (buffer.length === 0) return false;\n  const b = buffer[0];\n  return (b >= 0x80 && b <= 0x8f) || b === 0xde || b === 0xdf;\n}\n\nfunction isControlMessage(value: unknown): value is TControlMessage {\n  if (value == null || typeof value !== \"object\" || Array.isArray(value)) return false;\n  if (!(\"$c\" in value && \"domain\" in value && \"id\" in value)) return false;\n  if (typeof value.domain !== \"string\" || typeof value.id !== \"string\") return false;\n  // Optional streamKey (E3), if present, must be a string.\n  if (\"k\" in value && value.k != null && typeof value.k !== \"string\") return false;\n  // Discriminate per `$c` so each type validates its own fields — and an unknown `$c` (e.g. from a newer\n  // peer) is rejected here and safely dropped rather than mis-decoded.\n  if (value.$c === \"rack\") return \"ack\" in value && typeof value.ack === \"number\";\n  if (value.$c === \"rsync\") return true;\n  if (value.$c === \"rskip\") return \"seq\" in value && typeof value.seq === \"number\";\n  if (value.$c === \"rclose\") return true;\n  return false;\n}\n\nexport function encodeControlFrame(message: TControlMessage): Uint8Array {\n  return pack(message);\n}\n\n/**\n * Decode a frame as a control message, or `undefined` if it isn't one (a best-effort peek — action frames\n * short-circuit on the first byte without a full unpack). Only binary frames are considered.\n */\nexport function decodeControlFrame(\n  frame: string | ArrayBuffer | Uint8Array | Blob,\n): TControlMessage | undefined {\n  let buffer: Uint8Array;\n  if (frame instanceof ArrayBuffer) buffer = new Uint8Array(frame);\n  else if (frame instanceof Uint8Array) buffer = frame;\n  else return undefined;\n\n  if (!looksLikeControlFrame(buffer)) return undefined;\n  try {\n    const decoded = unpack(buffer);\n    return isControlMessage(decoded) ? decoded : undefined;\n  } catch {\n    return undefined;\n  }\n}\n","/**\n * Server-side receive bookkeeping for the `.reliable()` tier — the ordered, dedup half that the\n * {@link ChannelAcceptor} drives. It is **pure**: given a stream's incoming `seq` it decides what to\n * dispatch now, buffers out-of-order frames until the gap fills, and reports the cumulative contiguous\n * high-water to ack. It never touches the network or the runtime — the acceptor owns dispatch + acks —\n * which keeps it exhaustively unit-testable.\n *\n * ## Guarantee\n * Ordered, at-least-once, dedup-by-seq **within a live inbox** (one server process/session):\n * - a **new in-order** seq (`contiguous + 1`) is delivered, then any buffered contiguous run drains;\n * - an **out-of-order** seq (`> contiguous + 1`) is buffered (ordering — head-of-line by design) and the\n *   current high-water is acked, signalling the client to resend the gap;\n * - a **duplicate** seq (`<= contiguous`) is dropped from dispatch (the handler never sees a retry) and\n *   the current high-water is re-acked, so the client's outbox drains after a reconnect.\n *\n * Across a session reset (fresh process / evicted DO) the inbox starts empty at `contiguous = -1`. If a\n * stream's *first* frame arrives already past seq 0, the client is mid-stream against a receiver that lost\n * its state: `receive` returns `needsResync` (creating no state) so the acceptor can request a re-sync —\n * the client renumbers its unacked frames from 0 and resends, and the in-flight tail continues in order\n * instead of stalling. Frames the old receiver already acked are gone (correctly — they were delivered\n * before the reset); the persisted tier (Phase 5) persists the high-water to also survive eviction outright.\n * Reliable handlers must still be idempotent (a reconnect resend can redeliver an in-flight frame).\n */\n\ninterface IReliableStreamState<T> {\n  /** Highest contiguous seq delivered; `-1` = nothing yet. */\n  contiguousSeq: number;\n  /** Out-of-order frames waiting for the gap before them to fill, keyed by seq. */\n  pending: Map<number, T>;\n}\n\nexport interface IReliableInboxResult<T> {\n  /** Payloads to dispatch now, in ascending seq order (the new in-order one + any drained buffered). */\n  deliver: T[];\n  /** Cumulative contiguous high-water after processing — the ack to return to the sender. */\n  ack: number;\n  /** `true` when the seq was already contiguous (a resend): nothing delivered, caller re-acks. */\n  duplicate: boolean;\n  /**\n   * `true` when the receiver saw a stream **mid-stream with no prior state** (first-ever `seq > 0`) — a\n   * session-tier reset (fresh process / evicted server). Nothing is delivered or buffered; the caller should\n   * ask the sender to re-sync (renumber its unacked frames from 0 and resend) rather than let this land as an\n   * unfillable gap. The persisted receiver never sets it (it resumes its high-water from storage).\n   */\n  needsResync?: boolean;\n}\n\n/**\n * The receive-side contract the {@link ChannelAcceptor} drives for a `.reliable()` stream — ordered dedup\n * + a cumulative high-water to ack. {@link ReliableInbox} implements it in-memory (session tier); the\n * `persisted` tier's SQL-backed `ReliableLog` implements the *same* shape so the acceptor can swap one for\n * the other per stream without any other change. See {@link ReliableInbox} for the three-case semantics.\n */\nexport interface IReliableReceiver<T> {\n  /** Feed one reliable frame's `seq` + `payload`; get what to deliver now, the ack, and whether it was a dup. */\n  receive(streamId: string, seq: number, payload: T): IReliableInboxResult<T>;\n  /**\n   * The sender abandoned every undelivered frame `<= seq` (an `rskip` control message): advance the\n   * stream's high-water past them and drain anything buffered/stored behind the gap, so the stream\n   * continues instead of waiting forever on frames that will never arrive. Returns what the drain\n   * released (deliver in order) + the new cumulative ack. A backwards/stale skip is a no-op re-ack.\n   */\n  skipTo(streamId: string, seq: number): IReliableInboxResult<T>;\n  /** The current contiguous high-water for a stream (`-1` if unseen) — used to piggyback an ack on a reply. */\n  contiguousSeq(streamId: string): number;\n  /** Whether this receiver is tracking a stream (has accepted at least one reliable frame for it). */\n  hasStream(streamId: string): boolean;\n  /**\n   * Optional — release **all** state for a stream (high-water + buffered/stored frames): the sender\n   * closed it for good (an `rclose`). Purely a reclaim; forgetting an unknown stream is a no-op, and a\n   * later send on the released stream self-heals through the normal mid-stream re-sync path.\n   */\n  forgetStream?(streamId: string): void;\n}\n\nexport interface IReliableInboxOptions {\n  /** Max out-of-order frames buffered per stream before further gaps are dropped (resend heals). Default 1024. */\n  maxPendingPerStream?: number;\n}\n\nconst DEFAULT_MAX_PENDING = 1024;\n\nexport class ReliableInbox<T> implements IReliableReceiver<T> {\n  private readonly _streams = new Map<string, IReliableStreamState<T>>();\n  private readonly _maxPending: number;\n\n  constructor(options?: IReliableInboxOptions) {\n    this._maxPending = options?.maxPendingPerStream ?? DEFAULT_MAX_PENDING;\n  }\n\n  private _stream(streamId: string): IReliableStreamState<T> {\n    let state = this._streams.get(streamId);\n    if (state == null) {\n      state = { contiguousSeq: -1, pending: new Map() };\n      this._streams.set(streamId, state);\n    }\n    return state;\n  }\n\n  /**\n   * Feed one reliable frame's `seq` (plus the caller's `payload` to dispatch) and get the decision:\n   * what to deliver now, the ack to return, and whether it was a duplicate. See the class doc for the\n   * three cases.\n   */\n  receive(streamId: string, seq: number, payload: T): IReliableInboxResult<T> {\n    // Session-reset detection: a stream this inbox has never seen whose *first* frame isn't seq 0 means the\n    // receiver has no prior state (fresh process / evicted session) while the client is already mid-stream.\n    // Buffering it would create an unfillable gap (the client won't resend already-acked earlier frames), so\n    // instead signal `needsResync` and create **no** state — the caller (acceptor) asks the client to\n    // renumber its unacked frames from 0 and resend, which then arrives on a clean stream.\n    if (seq > 0 && !this._streams.has(streamId)) {\n      return { deliver: [], ack: -1, duplicate: false, needsResync: true };\n    }\n\n    const state = this._stream(streamId);\n\n    // Duplicate: already contiguous — drop from dispatch, re-ack the high-water.\n    if (seq <= state.contiguousSeq) {\n      return { deliver: [], ack: state.contiguousSeq, duplicate: true };\n    }\n\n    // New in-order: deliver it, then drain any contiguous run that was waiting behind it.\n    if (seq === state.contiguousSeq + 1) {\n      const deliver: T[] = [payload];\n      state.contiguousSeq = seq;\n      while (state.pending.has(state.contiguousSeq + 1)) {\n        const next = state.contiguousSeq + 1;\n        deliver.push(state.pending.get(next) as T);\n        state.pending.delete(next);\n        state.contiguousSeq = next;\n      }\n      return { deliver, ack: state.contiguousSeq, duplicate: false };\n    }\n\n    // Out-of-order gap: buffer (bounded) and ack the current high-water so the client resends the gap.\n    if (!state.pending.has(seq) && state.pending.size < this._maxPending) {\n      state.pending.set(seq, payload);\n    }\n    return { deliver: [], ack: state.contiguousSeq, duplicate: false };\n  }\n\n  /**\n   * Sender-abandoned skip (see {@link IReliableReceiver.skipTo}): advance `contiguousSeq` to at least\n   * `seq` — the abandoned frames count as settled — then drain the buffered contiguous run that was\n   * waiting behind the gap. Creates the stream when unseen (the sender is mid-stream; tracking it from the\n   * skip point means the following frames arrive in-order instead of tripping the re-sync detection).\n   */\n  skipTo(streamId: string, seq: number): IReliableInboxResult<T> {\n    const state = this._stream(streamId);\n    if (seq <= state.contiguousSeq) {\n      return { deliver: [], ack: state.contiguousSeq, duplicate: true };\n    }\n\n    const deliver: T[] = [];\n    state.contiguousSeq = seq;\n    // Skipped seqs may have been sitting in the gap buffer (delivered-then-abandoned races) — discard\n    // those, then drain the live contiguous run past the skip point.\n    for (const pendingSeq of [...state.pending.keys()]) {\n      if (pendingSeq <= seq) state.pending.delete(pendingSeq);\n    }\n    while (state.pending.has(state.contiguousSeq + 1)) {\n      const next = state.contiguousSeq + 1;\n      deliver.push(state.pending.get(next) as T);\n      state.pending.delete(next);\n      state.contiguousSeq = next;\n    }\n    return { deliver, ack: state.contiguousSeq, duplicate: false };\n  }\n\n  /** The current contiguous high-water for a stream (`-1` if unseen) — used to piggyback an ack on a reply. */\n  contiguousSeq(streamId: string): number {\n    return this._streams.get(streamId)?.contiguousSeq ?? -1;\n  }\n\n  /** Whether this inbox is tracking a stream (i.e. has seen at least one reliable frame for it). */\n  hasStream(streamId: string): boolean {\n    return this._streams.has(streamId);\n  }\n\n  /** Forget a stream's state (e.g. when its connection drops). */\n  forget(streamId: string): void {\n    this._streams.delete(streamId);\n  }\n\n  /** {@link IReliableReceiver.forgetStream} — same as {@link forget} (all session-tier state is in-memory). */\n  forgetStream(streamId: string): void {\n    this.forget(streamId);\n  }\n}\n","import type { IReliableInboxResult, IReliableReceiver } from \"./ReliableInbox\";\n\n/**\n * The **durable** tier's receive-side primitive — the persisted counterpart of {@link ReliableInbox}. It\n * implements the same {@link IReliableReceiver} contract (ordered dedup + a cumulative high-water to ack),\n * but every frame and the per-stream high-water live in a backing store instead of in-memory maps. Because\n * the store survives process eviction (a Durable Object waking from hibernation, a redeploy), a *fresh*\n * `ReliableLog` over the same store resumes each stream's high-water — so a replayed stream dedups instead\n * of redelivering, and a gap-free prefix can be served to a late joiner. That is the one guarantee the\n * session tier can't give (see {@link ReliableInbox}: it restarts at `contiguous = -1` on eviction).\n *\n * It is deliberately storage-agnostic: the algorithm here (contiguous advance, dedup by high-water) is the\n * same one {@link ReliableInbox} runs, lifted over an {@link IReliableLogStore} port. A Durable Object backs\n * that port with synchronous `ctx.storage.sql` (see the cloudflare platform helper); tests back it with an\n * in-memory map that persists across a simulated eviction. Payloads are (de)serialized through the\n * `serialize`/`deserialize` pair so the log can reconstruct a buffered out-of-order frame when its gap\n * fills — even after a wake.\n *\n * The store is assumed **synchronous** — true for a Durable Object's SQLite (`sql.exec` returns its cursor\n * synchronously), which keeps this on the same synchronous receive path as the in-memory inbox.\n */\n\n/** The storage port a {@link ReliableLog} drives — a tiny synchronous key/value + high-water surface. */\nexport interface IReliableLogStore {\n  /** Store one frame's serialized payload keyed by `(stream, seq)`; a no-op if that pair already exists. */\n  insertIgnore(streamId: string, seq: number, payload: string): void;\n  /** Whether a frame for `(stream, seq)` is stored. */\n  has(streamId: string, seq: number): boolean;\n  /** The stored serialized payload for `(stream, seq)`, or `undefined` if absent. */\n  getPayload(streamId: string, seq: number): string | undefined;\n  /** The persisted contiguous high-water for a stream (`-1` if the stream is unseen). */\n  getHighWater(streamId: string): number;\n  /** Persist a stream's advanced contiguous high-water. */\n  setHighWater(streamId: string, seq: number): void;\n  /**\n   * Optional — delete every stored frame of a stream with `seq <= through`. Enables the log's\n   * `keepDelivered` retention (compacting delivered history); a store without it simply keeps everything,\n   * exactly as before the option existed.\n   */\n  deleteThrough?(streamId: string, through: number): void;\n  /**\n   * Optional — delete **all** state for a stream: every stored frame *and* its high-water row. Enables\n   * `forgetStream` (a sender's `rclose` reclaim); a store without it keeps the stream, exactly as before.\n   */\n  deleteStream?(streamId: string): void;\n}\n\nexport interface IReliableLogOptions<T> {\n  /** Serialize a payload for storage (default `JSON.stringify`). */\n  serialize?: (payload: T) => string;\n  /** Reconstruct a payload from storage (default `JSON.parse`) — used when a buffered gap frame drains. */\n  deserialize?: (raw: string) => T;\n  /**\n   * Max distance past the high-water an out-of-order frame may be **persisted** at (default 1024 —\n   * mirroring the in-memory inbox's pending cap). A frame further out is not stored (the sender's ordered\n   * resend heals the gap first), bounding what one client can force into storage. `Infinity` disables.\n   */\n  maxGapWindow?: number;\n  /**\n   * Retention: how many **delivered** frames to keep behind the high-water. Default `false` = keep\n   * everything (the `contiguousPrefix()` replay recipe needs full history). Set a number to compact —\n   * frames `<= highWater - keepDelivered` are deleted as the high-water advances (needs a store with\n   * `deleteThrough`; silently keeps everything otherwise). `0` keeps only undelivered/pending frames.\n   */\n  keepDelivered?: number | false;\n}\n\n/** One stored frame of a stream, as {@link ReliableLog.contiguousEntries} returns it. */\nexport interface IReliableLogEntry<T> {\n  seq: number;\n  payload: T;\n}\n\nconst DEFAULT_MAX_GAP_WINDOW = 1024;\n\nexport class ReliableLog<T> implements IReliableReceiver<T> {\n  private readonly _store: IReliableLogStore;\n  private readonly _serialize: (payload: T) => string;\n  private readonly _deserialize: (raw: string) => T;\n  private readonly _maxGapWindow: number;\n  private readonly _keepDelivered: number | false;\n\n  constructor(store: IReliableLogStore, options?: IReliableLogOptions<T>) {\n    this._store = store;\n    this._serialize = options?.serialize ?? ((payload) => JSON.stringify(payload));\n    this._deserialize = options?.deserialize ?? ((raw) => JSON.parse(raw) as T);\n    this._maxGapWindow = options?.maxGapWindow ?? DEFAULT_MAX_GAP_WINDOW;\n    this._keepDelivered = options?.keepDelivered ?? false;\n  }\n\n  /** Compact delivered history behind the advanced high-water, when retention is configured. */\n  private _compact(streamId: string, highWater: number): void {\n    if (this._keepDelivered === false) return;\n    const through = highWater - this._keepDelivered;\n    if (through >= 0) this._store.deleteThrough?.(streamId, through);\n  }\n\n  /**\n   * Feed one reliable frame. Same three cases as {@link ReliableInbox}, but the frame is persisted first\n   * (idempotent `insertIgnore`, so a resend is stored once) and the high-water is read from / written to\n   * the store — so the decision is stable across an eviction:\n   * - **duplicate** (`seq <= high-water`): dropped from dispatch, re-ack the persisted high-water;\n   * - **in-order** (`seq === high-water + 1`): deliver it, then drain any persisted contiguous run behind it;\n   * - **gap** (`seq > high-water + 1`): persist the frame and ack the current high-water (client resends the gap).\n   */\n  receive(streamId: string, seq: number, payload: T): IReliableInboxResult<T> {\n    const highWater = this._store.getHighWater(streamId);\n\n    // Duplicate: already contiguous — the frame is already stored, re-ack the high-water.\n    if (seq <= highWater) {\n      return { deliver: [], ack: highWater, duplicate: true };\n    }\n\n    // A gap frame further out than the window is not persisted — the sender's ordered resend heals the\n    // gap first — bounding what one (buggy/hostile) client can force into storage. The re-ack still\n    // drives the resend, exactly like the in-memory inbox dropping past its pending cap.\n    if (seq > highWater + 1 && seq - highWater > this._maxGapWindow) {\n      return { deliver: [], ack: highWater, duplicate: false };\n    }\n\n    // Persist the frame (idempotent) so a buffered gap survives a wake and a resend stores once.\n    this._store.insertIgnore(streamId, seq, this._serialize(payload));\n\n    // Out-of-order gap: it's persisted; ack the current high-water so the client resends the filler.\n    if (seq !== highWater + 1) {\n      return { deliver: [], ack: highWater, duplicate: false };\n    }\n\n    // New in-order: deliver it, then drain the persisted contiguous run that was waiting behind it.\n    const deliver: T[] = [];\n    let contiguous = highWater;\n    while (this._store.has(streamId, contiguous + 1)) {\n      contiguous += 1;\n      const raw = this._store.getPayload(streamId, contiguous);\n      if (raw != null) deliver.push(this._deserialize(raw));\n    }\n    this._store.setHighWater(streamId, contiguous);\n    this._compact(streamId, contiguous);\n    return { deliver, ack: contiguous, duplicate: false };\n  }\n\n  /**\n   * Sender-abandoned skip (see {@link IReliableReceiver.skipTo}): persist the high-water at least past\n   * `seq`, then drain any *stored* contiguous run that was waiting behind the gap. Stored frames `<= seq`\n   * that were never delivered stay below the high-water (settled-as-abandoned, never drained) — the skip\n   * marks them settled without delivering them, mirroring the in-memory inbox.\n   */\n  skipTo(streamId: string, seq: number): IReliableInboxResult<T> {\n    const highWater = this._store.getHighWater(streamId);\n    if (seq <= highWater) {\n      return { deliver: [], ack: highWater, duplicate: true };\n    }\n\n    const deliver: T[] = [];\n    let contiguous = seq;\n    while (this._store.has(streamId, contiguous + 1)) {\n      contiguous += 1;\n      const raw = this._store.getPayload(streamId, contiguous);\n      if (raw != null) deliver.push(this._deserialize(raw));\n    }\n    this._store.setHighWater(streamId, contiguous);\n    this._compact(streamId, contiguous);\n    return { deliver, ack: contiguous, duplicate: false };\n  }\n\n  contiguousSeq(streamId: string): number {\n    return this._store.getHighWater(streamId);\n  }\n\n  hasStream(streamId: string): boolean {\n    return this._store.getHighWater(streamId) >= 0;\n  }\n\n  /**\n   * {@link IReliableReceiver.forgetStream}: release the stream's rows + high-water (a sender's `rclose`\n   * reclaim). Needs a store with `deleteStream`; without one the stream is kept, exactly as before.\n   */\n  forgetStream(streamId: string): void {\n    this._store.deleteStream?.(streamId);\n  }\n\n  /**\n   * **Producer-side** append: store `payload` as the next in-order frame of a stream and return its\n   * assigned `seq`. This is the offline/reliable-push recipe's write path — a server appending its own\n   * pushes to a per-client log (carrying the returned `seq` in the push payload so the client can dedup)\n   * — replacing the `log.receive(id, log.contiguousSeq(id) + 1, u)` contortion. In-order by\n   * construction, so it never buffers; if live out-of-order frames were already stored *ahead* of the\n   * high-water, filling the gap drains them (high-water advances past the run), exactly as `receive`.\n   */\n  append(streamId: string, payload: T): { seq: number } {\n    const seq = this._store.getHighWater(streamId) + 1;\n    this.receive(streamId, seq, payload);\n    return { seq };\n  }\n\n  /**\n   * The gap-free prefix of a stream — every contiguous payload `0..high-water` in order. This is the\n   * safe-to-replay catch-up a late joiner (or a reconnecting client that lost its own state) can be sent,\n   * and the building block the offline server→client push recipe (Phase 6) is assembled from.\n   */\n  contiguousPrefix(streamId: string): T[] {\n    const highWater = this._store.getHighWater(streamId);\n    const prefix: T[] = [];\n    for (let seq = 0; seq <= highWater; seq++) {\n      const raw = this._store.getPayload(streamId, seq);\n      if (raw != null) prefix.push(this._deserialize(raw));\n    }\n    return prefix;\n  }\n\n  /**\n   * {@link contiguousPrefix} with each payload's `seq` attached, optionally only the entries after\n   * `afterSeq`. Pruned or compacted seqs are absent, so the first entry's `seq` says where the stored\n   * history now starts.\n   */\n  contiguousEntries(streamId: string, afterSeq = -1): IReliableLogEntry<T>[] {\n    const highWater = this._store.getHighWater(streamId);\n    const entries: IReliableLogEntry<T>[] = [];\n    for (let seq = Math.max(afterSeq + 1, 0); seq <= highWater; seq++) {\n      const raw = this._store.getPayload(streamId, seq);\n      if (raw != null) entries.push({ seq, payload: this._deserialize(raw) });\n    }\n    return entries;\n  }\n\n  /**\n   * Delete a stream's stored frames with `seq <= through` (the replay recipe's prune, once the consumer\n   * confirmed them). Clamped to the high-water, so a too-large `through` never touches undelivered frames.\n   * Returns `false` when the store has no `deleteThrough` and nothing was pruned.\n   */\n  pruneThrough(streamId: string, through: number): boolean {\n    if (this._store.deleteThrough == null) return false;\n    const clamped = Math.min(through, this._store.getHighWater(streamId));\n    if (clamped >= 0) this._store.deleteThrough(streamId, clamped);\n    return true;\n  }\n}\n\n/**\n * An in-memory {@link IReliableLogStore} — used by tests to stand in for a Durable Object's SQL storage. It\n * persists in its own maps, so building a *new* {@link ReliableLog} over the same store instance models an\n * eviction (the process-side log is gone, the storage survives). Not for production — a real deployment\n * backs the port with durable storage (e.g. `ctx.storage.sql`).\n */\nexport function createMemoryReliableLogStore(): IReliableLogStore {\n  const frames = new Map<string, string>();\n  const highWater = new Map<string, number>();\n  const key = (streamId: string, seq: number): string => `${streamId}\\u0000${seq}`;\n\n  return {\n    insertIgnore: (streamId, seq, payload) => {\n      const k = key(streamId, seq);\n      if (!frames.has(k)) frames.set(k, payload);\n    },\n    has: (streamId, seq) => frames.has(key(streamId, seq)),\n    getPayload: (streamId, seq) => frames.get(key(streamId, seq)),\n    getHighWater: (streamId) => highWater.get(streamId) ?? -1,\n    setHighWater: (streamId, seq) => void highWater.set(streamId, seq),\n    deleteThrough: (streamId, through) => {\n      for (let seq = 0; seq <= through; seq++) frames.delete(key(streamId, seq));\n    },\n    deleteStream: (streamId) => {\n      const prefix = `${streamId}\\u0000`;\n      for (const k of frames.keys()) {\n        if (k.startsWith(prefix)) frames.delete(k);\n      }\n      highWater.delete(streamId);\n    },\n  };\n}\n","import type { RuntimeCoordinate } from \"../RuntimeCoordinate\";\n\n/**\n * Local key for a reliable stream — `(peer identity + domain:id route [+ #streamKey])`. It is *never*\n * serialized whole: each side reconstructs it from the connection (the peer) and the frame's route, so only\n * the per-frame `seq`/`ack` integers (and the optional `streamKey` discriminator) ride the wire. The\n * connector keys by its server peer; the acceptor keys by the originating client — the two ids need not\n * match textually, only be internally consistent per side. An optional `streamKey` (E3) appends `#<key>` so\n * several independent ordered streams of the same action (e.g. one per room id) stay separate.\n */\nexport function reliableStreamId(\n  peer: RuntimeCoordinate,\n  domain: string,\n  actionId: string,\n  streamKey?: string,\n): string {\n  const base = `${peer.stringId}::${domain}:${actionId}`;\n  return streamKey == null ? base : `${base}#${streamKey}`;\n}\n\n/** Routes already warned about a reliability downgrade, so a hot stream warns once, not per frame. */\nconst _warnedReliableDowngradeRoutes = new Set<string>();\n\n/**\n * One-time dev warning that a `.reliable()` frame is going out a transport with **no binary codec**, so its\n * reliability metadata (the `seq`/`ack` slot) — which rides the binary wire only — is silently dropped and\n * the frame degrades to best-effort (no ordering, dedup, or resend). The high-level `connectChannel` always\n * supplies a codec, so this only fires for a hand-rolled transport with none; surfacing it turns an invisible\n * downgrade into one visible line. Warns once per `domain:id` route (a reliable stream is high-frequency).\n */\nexport function warnReliableWireUnavailableOnce(domain: string, actionId: string): void {\n  const route = `${domain}:${actionId}`;\n  if (_warnedReliableDowngradeRoutes.has(route)) return;\n  _warnedReliableDowngradeRoutes.add(route);\n  console.warn(\n    `[reliable] \"${route}\" is .reliable() but this transport has no binary codec, so its reliability ` +\n      \"metadata can't be sent — the frame is delivered best-effort (no ordering/dedup/resend). Reliable \" +\n      \"delivery requires the binary wire codec (use a channel-based transport).\",\n  );\n}\n\n/** Routes already warned about an unsupported reliable peer, so the warning is once, not per frame. */\nconst _warnedReliablePeerRoutes = new Set<string>();\n\n/**\n * One-time dev warning that a `.reliable()` frame is going to a peer whose handshake did **not** advertise\n * the reliable capability ({@link CAP_RELIABLE}) — an older server that predates reliable delivery. The frame\n * is still sent (best-effort), but the peer won't apply ordering/dedup/resend, so surface the version skew\n * instead of silently emitting frames it may not interpret. Warns once per `domain:id` route.\n */\nexport function warnReliablePeerUnsupportedOnce(domain: string, actionId: string): void {\n  const route = `${domain}:${actionId}`;\n  if (_warnedReliablePeerRoutes.has(route)) return;\n  _warnedReliablePeerRoutes.add(route);\n  console.warn(\n    `[reliable] \"${route}\" is .reliable() but the connected peer did not advertise reliable support ` +\n      \"(an older server) — the frame is sent best-effort (no ordering/dedup/resend). Upgrade the peer to \" +\n      \"enable reliable delivery.\",\n  );\n}\n\n/** Routes already warned about a peer lacking streamkey support, so the warning is once, not per frame. */\nconst _warnedReliableStreamKeyRoutes = new Set<string>();\n\n/**\n * One-time dev warning that a keyed (`streamKey`) `.reliable()` frame (E3) is going to a peer whose\n * handshake did **not** advertise the streamkey capability ({@link CAP_RELIABLE_STREAMKEY}) — a peer that\n * predates per-key streams. The keyed frame is a distinct length the peer rejects wholesale (it isn't\n * mis-decoded), so it simply won't be delivered; surface the version skew instead of failing silently.\n * Warns once per `domain:id` route.\n */\nexport function warnReliableStreamKeyUnsupportedOnce(domain: string, actionId: string): void {\n  const route = `${domain}:${actionId}`;\n  if (_warnedReliableStreamKeyRoutes.has(route)) return;\n  _warnedReliableStreamKeyRoutes.add(route);\n  console.warn(\n    `[reliable] \"${route}\" was sent with a streamKey but the connected peer did not advertise streamkey ` +\n      \"support (an older peer) — a keyed reliable frame it can't interpret is dropped, not delivered. \" +\n      \"Upgrade the peer, or drop the streamKey to use the single default stream.\",\n  );\n}\n\n/** Routes already warned about a reliable-declared server push, so the warning is once, not per push. */\nconst _warnedReliablePushRoutes = new Set<string>();\n\n/**\n * One-time dev warning that a **server-initiated push** (`pushToClient` / `broadcast` / an acceptor's\n * `handleActionRequest`) is sending a `.reliable()`-declared action: reliability engages in the\n * **connector → acceptor** direction only, so this push is delivered best-effort — no outbox, no seq, no\n * resend. Surfacing it turns a silent direction downgrade into one visible line. For a push stream that\n * must all arrive, build the persisted-log recipe (append + replay-on-reconnect); for a single push that\n * needs confirmation, await `pushToClient(...).waitForResultPayload()` and retry.\n */\nexport function warnReliablePushUnsupportedOnce(domain: string, actionId: string): void {\n  const route = `${domain}:${actionId}`;\n  if (_warnedReliablePushRoutes.has(route)) return;\n  _warnedReliablePushRoutes.add(route);\n  console.warn(\n    `[reliable] \"${route}\" is .reliable() but server→client pushes are best-effort (reliability is ` +\n      \"connector→acceptor only) — no outbox, seq, or resend on this push. For a guaranteed push stream \" +\n      \"see the reliable-push recipe (per-client ReliableLog + replay on reconnect); for a single \" +\n      \"confirmed push, await waitForResultPayload() and retry.\",\n  );\n}\n\n/** Routes already warned about an abandoned reply-less delivery, so the warning is once, not per frame. */\nconst _warnedReliableAbandonedRoutes = new Set<string>();\n\n/**\n * One-time dev warning that a **reply-less** reliable send was abandoned: its delivery deadline expired\n * (or an aborted newer frame swept it) while unacked. Its caller was already told \"success on send\" —\n * that's the reply-less contract — so this is the only place the non-delivery becomes visible: the frame\n * was dropped, an `rskip` told the receiver to continue past it. Reply-carrying sends don't need this\n * (their action aborts loudly with `reliable_delivery_abandoned`). Warns once per `domain:id` route.\n */\nexport function warnReliableDeliveryAbandonedOnce(domain: string, actionId: string): void {\n  const route = `${domain}:${actionId}`;\n  if (_warnedReliableAbandonedRoutes.has(route)) return;\n  _warnedReliableAbandonedRoutes.add(route);\n  console.warn(\n    `[reliable] a reply-less \"${route}\" frame was abandoned — not acknowledged within the delivery ` +\n      \"deadline. The stream skips past it and continues; the frame may not have been delivered. \" +\n      \"(Reply-less reliable sends report success on send; this warning is where a bounded non-delivery \" +\n      \"surfaces.)\",\n  );\n}\n\n/** Test-only: clear the warn-once latches so each test observes the first warning. */\nexport function _resetReliableDowngradeWarnings(): void {\n  _warnedReliableDowngradeRoutes.clear();\n  _warnedReliablePeerRoutes.clear();\n  _warnedReliableStreamKeyRoutes.clear();\n  _warnedReliableAbandonedRoutes.clear();\n  _warnedReliablePushRoutes.clear();\n}\n","import type { ActionDomain } from \"../Domain/ActionDomain\";\nimport type { IActionDomain } from \"../Domain/ActionDomain.types\";\nimport type { EActionForm, IActionBase, IActionBase_JsonObject } from \"./ActionBase.types\";\n\nexport abstract class ActionBase<\n  FORM extends EActionForm,\n  DOM extends IActionDomain,\n  ID extends keyof DOM[\"actionSchema\"] & string = keyof DOM[\"actionSchema\"] & string,\n> implements IActionBase<FORM, DOM, ID>\n{\n  readonly domain: DOM[\"domain\"];\n  readonly allDomains: DOM[\"allDomains\"];\n  readonly schema: DOM[\"actionSchema\"][ID];\n\n  constructor(\n    readonly form: FORM,\n    readonly _domain: ActionDomain<DOM>,\n    readonly id: ID,\n  ) {\n    this.domain = _domain.domain;\n    this.allDomains = _domain.allDomains;\n    this.schema = _domain.actionSchema[id];\n  }\n\n  protected toJsonObject(): IActionBase_JsonObject<FORM, DOM, ID> {\n    return {\n      form: this.form,\n      domain: this.domain,\n      allDomains: this.allDomains,\n      id: this.id,\n    };\n  }\n\n  protected toJsonString(): string {\n    return JSON.stringify(this.toJsonObject());\n  }\n}\n","import { RuntimeCoordinate } from \"@nice-code/wire\";\nimport type { ActionDomain } from \"../../Domain/ActionDomain\";\nimport type {\n  IActionDomain,\n  TInferInputFromSchema,\n  TInferOutputFromSchema,\n} from \"../../Domain/ActionDomain.types\";\nimport { ActionBase } from \"../ActionBase\";\nimport { EActionForm } from \"../ActionBase.types\";\nimport type {\n  IActionContext,\n  IActionContext_Data,\n  IActionContext_Data_JsonObject,\n  IActionContext_JsonObject,\n  IActionReceiverMetadata,\n  IActionRouteItem,\n  IHandledReliability,\n} from \"./ActionContext.types\";\n\nexport class ActionContext<\n    DOM extends IActionDomain,\n    ID extends keyof DOM[\"actionSchema\"] & string = keyof DOM[\"actionSchema\"] & string,\n  >\n  extends ActionBase<EActionForm.context, DOM, ID>\n  implements IActionContext<DOM, ID>\n{\n  readonly form = EActionForm.context;\n  readonly _routing: IActionRouteItem[];\n  readonly timeCreated: number;\n  readonly cuid: string;\n  originClient: RuntimeCoordinate;\n  /**\n   * Local-only receiver-side reliable-delivery facts for the frame this context arrived on —\n   * `(seq, streamKey, redelivered)`, the free idempotency key for exactly-once effects. Present only\n   * inside the executing handler of a `.reliable()` action; `undefined` for best-effort actions and on\n   * the sending side. Never serialized (see {@link IHandledReliability}).\n   */\n  readonly reliability?: IHandledReliability;\n  private _receiverMetadata?: IActionReceiverMetadata;\n\n  constructor(\n    readonly _domain: ActionDomain<DOM>,\n    id: ID,\n    hydrationData: IActionContext_Data,\n  ) {\n    super(EActionForm.context, _domain, id);\n    this.timeCreated = hydrationData.timeCreated;\n    this.cuid = hydrationData.cuid;\n    this._routing = hydrationData.routing;\n    this.originClient = hydrationData.originClient;\n    this.reliability = undefined;\n  }\n\n  /** @internal Installed by the receiving runtime from out-of-band transport facts. */\n  _setReceiverMetadata(metadata: IActionReceiverMetadata): void {\n    Object.defineProperty(this, \"_receiverMetadata\", {\n      configurable: true,\n      enumerable: false,\n      value: metadata,\n      writable: true,\n    });\n    Object.defineProperty(this, \"reliability\", {\n      configurable: true,\n      enumerable: false,\n      value: metadata.reliability,\n    });\n  }\n\n  /** @internal Read only by the acceptor that owns the arrival. */\n  _getReceiverMetadata(): IActionReceiverMetadata | undefined {\n    return this._receiverMetadata;\n  }\n\n  _setOriginClient(client: RuntimeCoordinate): void {\n    this.originClient = client;\n  }\n\n  toJsonString(): string {\n    return JSON.stringify(this.toJsonObject());\n  }\n\n  toContextDataJsonObject(): IActionContext_Data_JsonObject {\n    // `reliability` is deliberately NOT written: it is a local-only receiver-side stamp (see\n    // IHandledReliability) — a reply serialized off this context must be byte-identical whether or not\n    // the frame arrived reliably.\n    return {\n      timeCreated: this.timeCreated,\n      cuid: this.cuid,\n      routing: this.routing.map((item) => ({\n        runtime: item.runtime.toJsonObject(),\n        handler: item.handler,\n        time: item.time,\n      })),\n      originClient: this.originClient.toJsonObject(),\n    };\n  }\n\n  toJsonObject(): IActionContext_JsonObject<DOM, ID> {\n    return {\n      ...super.toJsonObject(),\n      ...this.toContextDataJsonObject(),\n    };\n  }\n\n  get routing(): IActionRouteItem[] {\n    return this._routing;\n  }\n\n  addRouteItem(item: IActionRouteItem): void {\n    this._routing.push(item);\n  }\n\n  deserializeInput(\n    serialized: TInferInputFromSchema<DOM[\"actionSchema\"][ID]>[\"SerdeInput\"],\n  ): TInferInputFromSchema<DOM[\"actionSchema\"][ID]>[\"Input\"] {\n    return this.schema.deserializeInput(serialized);\n  }\n\n  serializeInput(\n    raw: TInferInputFromSchema<DOM[\"actionSchema\"][ID]>[\"Input\"],\n  ): TInferInputFromSchema<DOM[\"actionSchema\"][ID]>[\"SerdeInput\"] {\n    return this.schema.serializeInput(raw);\n  }\n\n  validateInput(input: unknown): TInferInputFromSchema<DOM[\"actionSchema\"][ID]>[\"Input\"] {\n    return this.schema.validateInput(input, {\n      domain: this.domain,\n      actionId: this.id,\n    });\n  }\n\n  validateOutput(output: unknown): TInferOutputFromSchema<DOM[\"actionSchema\"][ID]>[\"Output\"] {\n    return this.schema.validateOutput(output, {\n      domain: this.domain,\n      actionId: this.id,\n    });\n  }\n}\n","import type { IActionDomain } from \"../../Domain/ActionDomain.types\";\nimport { ActionBase } from \"../ActionBase\";\nimport { EActionForm } from \"../ActionBase.types\";\nimport type { ActionContext } from \"../Context/ActionContext\";\nimport type {\n  EActionPayloadType,\n  IActionPayload_Base,\n  IActionPayload_Base_JsonObject,\n  IActionPayload_Data_Base,\n} from \"./ActionPayload.types\";\n\nexport abstract class ActionPayload<\n    DT extends EActionPayloadType,\n    DOM extends IActionDomain,\n    ID extends keyof DOM[\"actionSchema\"] & string = keyof DOM[\"actionSchema\"] & string,\n  >\n  extends ActionBase<EActionForm.data, DOM, ID>\n  implements IActionPayload_Base<DT, DOM, ID>\n{\n  readonly form: EActionForm.data = EActionForm.data;\n  readonly type: DT;\n  readonly context: ActionContext<DOM, ID>;\n  readonly time: number;\n\n  protected constructor(context: ActionContext<DOM, ID>, type: DT, data: IActionPayload_Data_Base) {\n    super(EActionForm.data, context._domain, context.id);\n    this.context = context;\n    this.type = type;\n    this.time = data.time;\n  }\n\n  protected toBaseJsonObject(): IActionPayload_Base_JsonObject<DT, DOM, ID> {\n    return {\n      ...super.toJsonObject(),\n      type: this.type,\n      context: this.context.toContextDataJsonObject(),\n      time: this.time,\n    };\n  }\n\n  abstract toJsonObject(): IActionPayload_Base_JsonObject<DT, DOM, ID>;\n}\n","function stableStringify(value: unknown): string {\n  if (value === null || value === undefined) return String(value);\n  if (typeof value !== \"object\") return JSON.stringify(value) ?? \"undefined\";\n  if (Array.isArray(value)) return `[${value.map(stableStringify).join(\",\")}]`;\n  const keys = Object.keys(value as object).sort();\n  return (\n    \"{\" +\n    keys\n      .map((k) => `${JSON.stringify(k)}:${stableStringify((value as Record<string, unknown>)[k])}`)\n      .join(\",\") +\n    \"}\"\n  );\n}\n\nfunction fnv1a32(str: string): string {\n  let hash = 2166136261;\n  for (let i = 0; i < str.length; i++) {\n    hash = ((hash ^ str.charCodeAt(i)) * 16777619) >>> 0;\n  }\n  return hash.toString(16).padStart(8, \"0\");\n}\n\n/**\n * Produces a deterministic 8-char hex hash of any JSON-serializable value.\n * Useful for grouping/comparing action inputs, outputs, and progress payloads.\n */\nexport function hashPayloadData(data: unknown): string {\n  return fnv1a32(stableStringify(data));\n}\n","import type { IActionDomain } from \"../../Domain/ActionDomain.types\";\nimport type { ActionContext } from \"../Context/ActionContext\";\nimport { ActionPayload } from \"./ActionPayload\";\nimport type {\n  IActionPayload_Data_Base,\n  IActionPayload_Progress,\n  IActionPayload_Progress_JsonObject,\n  TActionProgress,\n} from \"./ActionPayload.types\";\nimport { EActionPayloadType } from \"./ActionPayload.types\";\nimport { ActionPayload_Request } from \"./ActionPayload_Request\";\n\nexport class ActionPayload_Progress<\n    DOM extends IActionDomain,\n    ID extends keyof DOM[\"actionSchema\"] & string = keyof DOM[\"actionSchema\"] & string,\n  >\n  extends ActionPayload<EActionPayloadType.progress, DOM, ID>\n  implements IActionPayload_Progress<DOM, ID>\n{\n  readonly progress: TActionProgress;\n\n  constructor(\n    params: { context: ActionContext<DOM, ID> } | ActionPayload_Request<DOM, ID>,\n    progress: TActionProgress,\n    data: IActionPayload_Data_Base,\n  ) {\n    super(params.context, EActionPayloadType.progress, data);\n    this.progress = progress;\n  }\n\n  toJsonObject(): IActionPayload_Progress_JsonObject<DOM, ID> {\n    return {\n      ...this.toBaseJsonObject(),\n      progress: this.progress,\n    };\n  }\n\n  toJsonString(): string {\n    return JSON.stringify(this.toJsonObject());\n  }\n\n  toHttpResponse(): Response {\n    return new Response(this.toJsonString(), {\n      status: 200,\n      headers: { \"Content-Type\": \"application/json\" },\n    });\n  }\n}\n","import type { NiceError } from \"@nice-code/error\";\nimport { hashPayloadData } from \"../../../utils/hashPayloadData\";\nimport type { IActionDomain, TInferOutputFromSchema } from \"../../Domain/ActionDomain.types\";\nimport type { TInferActionError } from \"../../Schema/ActionSchema\";\nimport type { ActionContext } from \"../Context/ActionContext\";\nimport { ActionPayload } from \"./ActionPayload\";\nimport type { IActionPayload_Data_Base, TActionResultOutcome } from \"./ActionPayload.types\";\nimport { EActionPayloadType, type IActionPayload_Result_JsonObject } from \"./ActionPayload.types\";\nimport { ActionPayload_Request } from \"./ActionPayload_Request\";\n\nexport class ActionPayload_Result<\n  DOM extends IActionDomain,\n  ID extends keyof DOM[\"actionSchema\"] & string = keyof DOM[\"actionSchema\"] & string,\n> extends ActionPayload<EActionPayloadType.result, DOM, ID> {\n  readonly result: TActionResultOutcome<\n    TInferOutputFromSchema<DOM[\"actionSchema\"][ID]>[\"Output\"],\n    TInferActionError<DOM[\"actionSchema\"][ID]>\n  >;\n  readonly outputHash: string;\n\n  constructor(\n    params: { context: ActionContext<DOM, ID> } | ActionPayload_Request<DOM, ID>,\n    // Raw outcome — `expected` is derived here (against this side's own schema) so it\n    // is always type-sound, never trusted from the wire.\n    result:\n      | { ok: true; output: TInferOutputFromSchema<DOM[\"actionSchema\"][ID]>[\"Output\"] }\n      | { ok: false; error: NiceError<any, any> },\n    data: IActionPayload_Data_Base,\n  ) {\n    super(params.context, EActionPayloadType.result, data);\n\n    if (result.ok) {\n      this.result = result;\n      this.outputHash = hashPayloadData(this.context.schema.serializeOutput(result.output));\n    } else {\n      const expected = this.context.schema.isExpectedError(result.error);\n      this.result = expected\n        ? {\n            ok: false,\n            expected: true,\n            error: result.error as TInferActionError<DOM[\"actionSchema\"][ID]>,\n          }\n        : { ok: false, expected: false, error: result.error };\n      this.outputHash = hashPayloadData(result.error.message);\n    }\n  }\n\n  toJsonObject(): IActionPayload_Result_JsonObject<DOM, ID> {\n    // Serialize the error to its JSON-object form here — never let a live `NiceError`\n    // instance reach the wire. `JSON.stringify` would call its `toJSON()`, but binary\n    // codecs (msgpackr) serialize the instance via their built-in Error extension into\n    // a tuple that `castNiceError` can't rehydrate. Emitting the plain object keeps the\n    // frame transport-agnostic.\n    const wireResult = this.result.ok\n      ? { ok: true as const, output: this.context.schema.serializeOutput(this.result.output) }\n      : {\n          ok: false as const,\n          expected: this.result.expected,\n          error: this.result.error.toJsonObject(),\n        };\n    return {\n      ...this.toBaseJsonObject(),\n      result: wireResult,\n      outputHash: this.outputHash,\n    };\n  }\n\n  toJsonString(): string {\n    return JSON.stringify(this.toJsonObject());\n  }\n\n  toHttpResponse({ useErrorStatus = true }: { useErrorStatus?: boolean } = {}): Response {\n    return new Response(this.toJsonString(), {\n      status: this.result.ok ? 200 : useErrorStatus ? this.result.error.httpStatusCode : 500,\n      headers: { \"Content-Type\": \"application/json\" },\n    });\n  }\n}\n","import type { NiceError } from \"@nice-code/error\";\nimport type { IExecuteActionOptions } from \"../../../ActionRuntime/Handler/ActionHandler.types\";\nimport { hashPayloadData } from \"../../../utils/hashPayloadData\";\nimport type {\n  IActionDomain,\n  TInferInputFromSchema,\n  TInferOutputFromSchema,\n} from \"../../Domain/ActionDomain.types\";\nimport type { ActionContext } from \"../Context/ActionContext\";\nimport type { RunningAction } from \"../RunningAction\";\nimport { ActionPayload } from \"./ActionPayload\";\nimport type { IActionPayload_Data_Base, TActionProgress } from \"./ActionPayload.types\";\nimport { EActionPayloadType, type IActionPayload_Request_JsonObject } from \"./ActionPayload.types\";\nimport { ActionPayload_Progress } from \"./ActionPayload_Progress\";\nimport { ActionPayload_Result } from \"./ActionPayload_Result\";\n\nexport class ActionPayload_Request<\n  DOM extends IActionDomain,\n  ID extends keyof DOM[\"actionSchema\"] & string = keyof DOM[\"actionSchema\"] & string,\n> extends ActionPayload<EActionPayloadType.request, DOM, ID> {\n  readonly input: TInferInputFromSchema<DOM[\"actionSchema\"][ID]>[\"Input\"];\n  readonly inputHash: string;\n  _callSite?: string;\n\n  constructor(\n    params: { context: ActionContext<DOM, ID> },\n    input: TInferInputFromSchema<DOM[\"actionSchema\"][ID]>[\"Input\"],\n    data: IActionPayload_Data_Base,\n  ) {\n    super(params.context, EActionPayloadType.request, data);\n    this.input = input;\n    this.inputHash = hashPayloadData(this.context.schema.serializeInput(input));\n  }\n\n  successResult(\n    ...args: [TInferOutputFromSchema<DOM[\"actionSchema\"][ID]>[\"Output\"]] extends [never]\n      ? [] | [output: TInferOutputFromSchema<DOM[\"actionSchema\"][ID]>[\"Output\"]]\n      : [output: TInferOutputFromSchema<DOM[\"actionSchema\"][ID]>[\"Output\"]]\n  ): ActionPayload_Result<DOM, ID> {\n    const output = args[0];\n    const finalOutput = this.context.schema.validateOutput(output, {\n      domain: this.domain,\n      actionId: this.id,\n    });\n    return new ActionPayload_Result(this, { ok: true, output: finalOutput }, { time: Date.now() });\n  }\n\n  /**\n   * Build a failed result from any `NiceError`. The result's `expected` flag is\n   * derived from the action's `.throws()` declarations during construction, so\n   * declared errors surface as `expected: true` (typed) and everything else as\n   * `expected: false`.\n   */\n  errorResult(err: NiceError<any, any>): ActionPayload_Result<DOM, ID> {\n    return new ActionPayload_Result(this, { ok: false, error: err }, { time: Date.now() });\n  }\n\n  progress(progress: TActionProgress): ActionPayload_Progress<DOM, ID> {\n    return new ActionPayload_Progress(this, progress, { time: Date.now() });\n  }\n\n  toJsonObject(): IActionPayload_Request_JsonObject<DOM, ID> {\n    return {\n      ...super.toBaseJsonObject(),\n      input: this.context.schema.serializeInput(this.input),\n      inputHash: this.inputHash,\n    };\n  }\n\n  toJsonString(): string {\n    return JSON.stringify(this.toJsonObject());\n  }\n\n  async runToOutput(\n    options?: IExecuteActionOptions<DOM, ID>,\n  ): Promise<TInferOutputFromSchema<DOM[\"actionSchema\"][ID]>[\"Output\"]> {\n    const running = await this.run(options);\n    const result = await running.waitForResultPayload();\n    if (result.result.ok) return result.result.output;\n    throw result.result.error;\n  }\n\n  async runToResultPayload(\n    options?: IExecuteActionOptions<DOM, ID>,\n  ): Promise<ActionPayload_Result<DOM, ID>> {\n    const value = await this.run(options);\n    return value.waitForResultPayload();\n  }\n\n  /**\n   * Run and resolve to the bare result outcome (`{ ok } | { ok:false; expected; error }`)\n   * — the ergonomic way to handle expected vs unexpected errors without throwing.\n   */\n  async runToResult(\n    options?: IExecuteActionOptions<DOM, ID>,\n  ): Promise<ActionPayload_Result<DOM, ID>[\"result\"]> {\n    return (await this.runToResultPayload(options)).result;\n  }\n\n  async run(options?: IExecuteActionOptions<DOM, ID>): Promise<RunningAction<DOM, ID>> {\n    return this._domain.runAction(this, options);\n  }\n}\n","import { isNiceError } from \"@nice-code/error\";\nimport { RuntimeCoordinate } from \"@nice-code/wire\";\nimport { nanoid } from \"nanoid\";\nimport type { ActionDomain } from \"../../Domain/ActionDomain\";\nimport type {\n  IActionDomain,\n  TInferInputFromSchema,\n  TInferOutputFromSchema,\n} from \"../../Domain/ActionDomain.types\";\nimport type { TInferActionError } from \"../../Schema/ActionSchema\";\nimport type { TNarrowActionType } from \"../Action.combined.types\";\nimport { ActionBase } from \"../ActionBase\";\nimport { EActionForm, type IActionBase, type IActionBase_JsonObject } from \"../ActionBase.types\";\nimport { ActionContext } from \"../Context/ActionContext\";\nimport { ActionPayload } from \"../Payload/ActionPayload\";\nimport { ActionPayload_Request } from \"../Payload/ActionPayload_Request\";\nimport type { IActionCore } from \"./ActionCore.types\";\n\nexport class ActionCore<\n    DOM extends IActionDomain,\n    ID extends keyof DOM[\"actionSchema\"] & string = keyof DOM[\"actionSchema\"] & string,\n  >\n  extends ActionBase<EActionForm.core, DOM, ID>\n  implements IActionCore<DOM, ID>\n{\n  readonly form = EActionForm.core;\n\n  constructor(\n    readonly _domain: ActionDomain<DOM>,\n    id: ID,\n  ) {\n    super(EActionForm.core, _domain, id);\n  }\n\n  is<ACT extends IActionBase<any, any, any>>(\n    action: ACT | unknown | null | undefined,\n  ): action is TNarrowActionType<DOM, ACT, ID> {\n    return (\n      action instanceof ActionPayload && action.domain === this.domain && action.id === this.id\n    );\n  }\n\n  /**\n   * Type-guard for the throw-style path (`runToOutput` rethrows on failure):\n   * narrows a caught value to this action's declared error union when it is one\n   * the action declared via `.throws()`. Everything else (foreign throws,\n   * undeclared `NiceError`s) returns `false`.\n   */\n  isExpectedError(error: unknown): error is TInferActionError<DOM[\"actionSchema\"][ID]> {\n    return isNiceError(error) && this.schema.isExpectedError(error);\n  }\n\n  toJsonObject(): IActionBase_JsonObject<EActionForm.core, DOM, ID> {\n    return {\n      id: this.id,\n      form: this.form,\n      domain: this.domain,\n      allDomains: this.allDomains,\n    };\n  }\n\n  request(\n    ...args: [TInferInputFromSchema<DOM[\"actionSchema\"][ID]>[\"Input\"]] extends [never]\n      ? [input?: never]\n      : [input: TInferInputFromSchema<DOM[\"actionSchema\"][ID]>[\"Input\"]]\n  ): ActionPayload_Request<DOM, ID> {\n    const input: unknown = args[0];\n    const validatedInput = this.schema.validateInput(input, {\n      actionId: this.id,\n      domain: this.domain,\n    });\n\n    const context = new ActionContext(this._domain, this.id, {\n      cuid: nanoid(),\n      timeCreated: Date.now(),\n      routing: [],\n      originClient: RuntimeCoordinate.unknown,\n    });\n\n    return new ActionPayload_Request({ context }, validatedInput, {\n      time: Date.now(),\n    });\n  }\n\n  deserializeInput(\n    serialized: TInferInputFromSchema<DOM[\"actionSchema\"][ID]>[\"SerdeInput\"],\n  ): TInferInputFromSchema<DOM[\"actionSchema\"][ID]>[\"Input\"] {\n    return this.schema.deserializeInput(serialized);\n  }\n\n  serializeInput(\n    raw: TInferInputFromSchema<DOM[\"actionSchema\"][ID]>[\"Input\"],\n  ): TInferInputFromSchema<DOM[\"actionSchema\"][ID]>[\"SerdeInput\"] {\n    return this.schema.serializeInput(raw);\n  }\n\n  validateInput(input: unknown): TInferInputFromSchema<DOM[\"actionSchema\"][ID]>[\"Input\"] {\n    return this.schema.validateInput(input, {\n      domain: this.domain,\n      actionId: this.id,\n    });\n  }\n\n  validateOutput(output: unknown): TInferOutputFromSchema<DOM[\"actionSchema\"][ID]>[\"Output\"] {\n    return this.schema.validateOutput(output, {\n      domain: this.domain,\n      actionId: this.id,\n    });\n  }\n}\n","import type { ActionDomain } from \"../..\";\nimport type { IActionDomain } from \"../Domain/ActionDomain.types\";\nimport type { EReliabilityTier } from \"../Schema/ActionSchema\";\nimport type { ActionContext } from \"./Context/ActionContext\";\nimport { type IActionPayload_Result_JsonObject } from \"./Payload/ActionPayload.types\";\nimport type { ActionPayload_Progress } from \"./Payload/ActionPayload_Progress\";\nimport type { ActionPayload_Result } from \"./Payload/ActionPayload_Result\";\nimport {\n  ERunningActionFinishedType,\n  ERunningActionUpdateType,\n  type IRunningActionState,\n  type IRunningActionState_ConstructorParams,\n  type IRunningActionUserMethods,\n  type TRunningActionUpdate,\n  type TRunningActionUpdateListener,\n} from \"./RunningAction.types\";\n\n/** Reliable-delivery facts an observer (devtools) can show for a reliable action, stamped by the connector. */\nexport interface IRunningActionReliability {\n  /** The reliability tier this action opted into (`session` / `persisted`). */\n  tier: EReliabilityTier;\n  /** This frame's per-stream sequence number (the sender's outbox seq). */\n  seq?: number;\n  /** The `streamKey` this send rode on (E3), when the stream is keyed. */\n  streamKey?: string;\n  /**\n   * Set `true` when the peer's cumulative ack covered this frame — the sender-side proof of delivery.\n   * Stamped by the connector when its outbox prunes the send (a reply's piggyback or a standalone `rack`).\n   * Flipping it emits an {@link ERunningActionUpdateType.reliability} update; `waitForAck()` awaits it.\n   */\n  acked?: boolean;\n}\n\nexport class RunningAction<\n  DOM extends IActionDomain,\n  ID extends keyof DOM[\"actionSchema\"] & string = keyof DOM[\"actionSchema\"] & string,\n> implements IRunningActionUserMethods<DOM, ID>\n{\n  protected _state: IRunningActionState<DOM, ID>;\n\n  /**\n   * Reliability facts for a `.reliable()` action (tier + this frame's seq), stamped by the connector when it\n   * assigns the outbox seq. `undefined` for a best-effort action. Read by devtools to surface a reliable chip;\n   * the cumulative `ack` / `redelivered` are receiver-side facts (see the server serve-logger), not the\n   * sender's to report.\n   */\n  reliability?: IRunningActionReliability;\n\n  readonly context: ActionContext<DOM, ID>;\n  readonly cuid: string;\n  readonly id: ID;\n  readonly _domain: ActionDomain<DOM>;\n  readonly domain: DOM[\"domain\"];\n  readonly allDomains: DOM[\"allDomains\"];\n  readonly parentCuid?: string;\n  readonly callSite?: string;\n\n  private readonly _resultPayloadPromise: Promise<ActionPayload_Result<DOM, ID>>;\n  private _resolveResult!: (response: ActionPayload_Result<DOM, ID>) => void;\n  private _rejectResult!: (reason?: unknown) => void;\n\n  private _isAborted = false;\n\n  private readonly _updates: TRunningActionUpdate<DOM, ID>[] = [];\n\n  private readonly _updateListeners: TRunningActionUpdateListener<DOM, ID>[] = [];\n\n  /**\n   * Delivery-settlement state for {@link waitForAck}, recorded even when nobody is waiting so a late\n   * `waitForAck()` still settles correctly. The promise itself is created lazily on first call —\n   * otherwise every abandoned reliable send would raise unhandled-rejection noise for the callers\n   * (the overwhelming majority) that never ask.\n   */\n  private _ackOutcome?: { ok: true } | { ok: false; reason: unknown };\n  private _ackPromise?: Promise<void>;\n  private _resolveAck?: () => void;\n  private _rejectAck?: (reason?: unknown) => void;\n\n  constructor(initialState: IRunningActionState_ConstructorParams<DOM, ID>) {\n    this.context = initialState.context;\n    this.cuid = initialState.context.cuid;\n    this.id = initialState.context.id;\n    this.domain = initialState.context.domain;\n    this.allDomains = initialState.context.allDomains;\n    this._domain = initialState.context._domain;\n    this.parentCuid = initialState.parentCuid;\n    this.callSite = initialState.callSite;\n\n    this._resultPayloadPromise = new Promise<ActionPayload_Result<DOM, ID>>((resolve, reject) => {\n      this._resolveResult = resolve;\n      this._rejectResult = reject;\n    });\n    // Prevent unhandled rejection when this RunningAction is aborted/failed but\n    // waitForResultPayload() is never called (e.g. error-path in _runAction).\n    this._resultPayloadPromise.catch(() => {});\n\n    this._state = {\n      request: initialState.request,\n      progress: initialState.progress ?? [],\n      result: initialState.result,\n    };\n\n    this._sendUpdate({\n      type: ERunningActionUpdateType.started,\n      runningAction: this,\n      time: Date.now(),\n    });\n  }\n\n  get state(): IRunningActionState<DOM, ID> {\n    return this._state;\n  }\n\n  /** Whether this action has reached a terminal state (resolved, aborted, or failed) — no more updates. */\n  get isSettled(): boolean {\n    return this._state.result != null || this._isAborted;\n  }\n\n  /**\n   * Whether this action was aborted (deadline, overflow, or an explicit abort) — as opposed to having\n   * completed successfully. A reliable **reply-less** action completes *on send* (so it's `isSettled`), yet\n   * the outbox must keep delivering it in the background until the peer acks; only an *abort* should stop\n   * those resends. Resend/resync gating uses this, not {@link isSettled}.\n   */\n  get isAborted(): boolean {\n    return this._isAborted;\n  }\n\n  /** Stamp this action's reliability facts (tier + seq) — the connector calls it when it assigns the seq. */\n  _setReliability(reliability: IRunningActionReliability): void {\n    this.reliability = reliability;\n  }\n\n  /**\n   * Await this send's **delivery settlement** — the sender-side proof of what became of the frame,\n   * distinct from the action's own promise (a reply-less reliable action resolves *on send* while\n   * delivery continues in the background; this is how you await that delivery):\n   *\n   * - **Reliable action** — resolves when the peer's cumulative ack covers this frame; rejects with the\n   *   abandon reason when the frame is dropped undelivered (delivery deadline, explicit `abort()`, a\n   *   newer frame's cumulative sweep, or a `closeReliableStream`).\n   * - **Best-effort action** — there is no ack concept, so it mirrors the action itself: resolves when\n   *   the action settles successfully (for fire-and-forget: on send), rejects when it aborts/fails.\n   *   Callers compose without branching on the tier.\n   *\n   * Note the at-least-once caveat: a *rejected* `waitForAck` means the sender stopped trying, not that\n   * the frame provably never arrived (the ack itself may have been lost).\n   */\n  waitForAck(): Promise<void> {\n    if (this._ackPromise == null) {\n      this._ackPromise = new Promise<void>((resolve, reject) => {\n        this._resolveAck = resolve;\n        this._rejectAck = reject;\n      });\n      // Same guard as the result promise: a caller may request the promise and then not await it.\n      this._ackPromise.catch(() => {});\n      // Settled before anyone asked — replay the recorded outcome into the fresh promise.\n      const outcome = this._ackOutcome;\n      if (outcome != null) {\n        if (outcome.ok) this._resolveAck?.();\n        else this._rejectAck?.(outcome.reason);\n      }\n    }\n    return this._ackPromise;\n  }\n\n  /** Record a delivery-settlement outcome (first one wins) and settle {@link waitForAck} if it exists. */\n  private _settleAck(outcome: { ok: true } | { ok: false; reason: unknown }): boolean {\n    if (this._ackOutcome != null) return false;\n    this._ackOutcome = outcome;\n    if (outcome.ok) this._resolveAck?.();\n    else this._rejectAck?.(outcome.reason);\n    return true;\n  }\n\n  /**\n   * The peer's cumulative ack covered this frame — the connector calls it when its outbox prunes the\n   * send. Stamps `reliability.acked` and emits a {@link ERunningActionUpdateType.reliability} update so\n   * observers (devtools) refresh, then settles {@link waitForAck}.\n   */\n  _notifyAcked(): void {\n    if (this.reliability != null && this.reliability.acked !== true) {\n      this.reliability.acked = true;\n      this._sendUpdate({\n        type: ERunningActionUpdateType.reliability,\n        runningAction: this,\n        time: Date.now(),\n      });\n    }\n    this._settleAck({ ok: true });\n  }\n\n  /**\n   * This frame was dropped undelivered (deadline / abort / sweep / stream close) — the connector calls\n   * it from the outbox's drop hook. Rejects {@link waitForAck} with the abandon reason.\n   */\n  _notifyAckAbandoned(reason: unknown): void {\n    this._settleAck({ ok: false, reason });\n  }\n\n  abort(reason?: unknown): void {\n    this._abort(reason);\n  }\n\n  addUpdateListeners(listeners: TRunningActionUpdateListener<DOM, ID>[]): () => void {\n    this._updateListeners.push(...listeners);\n    // Emit all past events to the new listeners\n    for (const event of this._updates) {\n      for (const listener of listeners) {\n        listener(event);\n      }\n    }\n    return () => {\n      for (const listener of listeners) {\n        const i = this._updateListeners.indexOf(listener);\n        if (i !== -1) this._updateListeners.splice(i, 1);\n      }\n    };\n  }\n\n  async *iterateUpdates(): AsyncIterable<TRunningActionUpdate<DOM, ID>> {\n    const queue: TRunningActionUpdate<DOM, ID>[] = [];\n    let resolveWaiter: (() => void) | null = null;\n\n    const unsubscribe = this.addUpdateListeners([\n      (event) => {\n        queue.push(event);\n        // Wake up the while-loop if it's currently paused waiting for an event\n        if (resolveWaiter) {\n          resolveWaiter();\n          resolveWaiter = null;\n        }\n      },\n    ]);\n\n    try {\n      while (true) {\n        if (queue.length === 0) {\n          await new Promise<void>((resolve) => {\n            resolveWaiter = resolve;\n          });\n        }\n\n        const event = queue.shift()!;\n        yield event;\n\n        // Safely terminate the generator when the action concludes\n        if (event.type === ERunningActionUpdateType.finished) {\n          break;\n        }\n      }\n    } finally {\n      unsubscribe();\n    }\n  }\n\n  _sendUpdate(update: TRunningActionUpdate<DOM, ID>): void {\n    this._updates.push(update);\n    for (const listener of this._updateListeners) listener(update);\n  }\n\n  _completeWithResult(result: ActionPayload_Result<DOM, ID>): boolean {\n    if (this._state.result != null || this._isAborted) return false;\n\n    this._state = {\n      request: this._state.request,\n      progress: this._state.progress,\n      result: result,\n    };\n\n    this._resolveResult(result);\n    this._sendUpdate({\n      type: ERunningActionUpdateType.finished,\n      finishType: ERunningActionFinishedType.success,\n      runningAction: this,\n      time: Date.now(),\n      response: result,\n    });\n\n    // Best-effort settlement mirror: with no ack concept, `waitForAck` follows the action itself. A\n    // *reliable* action's settlement is owned by the outbox hooks instead (a reply-less one completes\n    // on send while its delivery is still pending — success here must not imply delivery).\n    if (this.reliability == null) this._settleAck({ ok: true });\n\n    return true;\n  }\n\n  _abort(reason?: unknown): boolean {\n    if (this._state.result != null || this._isAborted) return false;\n    this._isAborted = true;\n    this._rejectResult(reason);\n\n    this._sendUpdate({\n      type: ERunningActionUpdateType.finished,\n      finishType: ERunningActionFinishedType.aborted,\n      runningAction: this,\n      time: Date.now(),\n      reason,\n    });\n\n    // Best-effort mirror (see _completeWithResult). A reliable action's abort settles delivery through\n    // the outbox's drop hook (abandon-and-skip) with the same reason.\n    if (this.reliability == null) this._settleAck({ ok: false, reason });\n\n    return true;\n  }\n\n  _failWithError(error: unknown): boolean {\n    if (this._state.result != null || this._isAborted) return false;\n    this._isAborted = true;\n    this._rejectResult(error);\n\n    this._sendUpdate({\n      type: ERunningActionUpdateType.finished,\n      finishType: ERunningActionFinishedType.failed,\n      runningAction: this,\n      time: Date.now(),\n      error,\n    } as any);\n\n    // Best-effort mirror (see _completeWithResult).\n    if (this.reliability == null) this._settleAck({ ok: false, reason: error });\n\n    return true;\n  }\n\n  _updateProgress(progress: ActionPayload_Progress<DOM, ID>): void {\n    if (this._state.result != null || this._isAborted) return;\n    this._state.progress.push(progress);\n\n    this._sendUpdate({\n      type: ERunningActionUpdateType.progress,\n      runningAction: this,\n      time: Date.now(),\n      progress: progress.progress,\n    });\n  }\n\n  waitForResultPayload(): Promise<ActionPayload_Result<DOM, ID>> {\n    return this._resultPayloadPromise;\n  }\n\n  _resolveFromJson(resultJson: IActionPayload_Result_JsonObject<DOM, ID>): boolean {\n    if (this._state.result != null || this._isAborted) return false;\n    const result = this._domain.hydrateResultPayload(resultJson);\n    return this._completeWithResult(result as unknown as ActionPayload_Result<DOM, ID>);\n  }\n}\n","import { err, err_nice } from \"@nice-code/error\";\nimport type { RuntimeCoordinate } from \"@nice-code/wire\";\nimport { EActionForm } from \"../ActionDefinition/Action/ActionBase.types\";\nimport { EActionPayloadType } from \"../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport type { IActionRuntimeManagerContext } from \"../ActionRuntime/ActionRuntime.types\";\n\nexport enum EErrId_NiceAction {\n  not_implemented = \"not_implemented\",\n  action_id_not_in_domain = \"action_id_not_in_domain\",\n  domain_already_exists_in_hierarchy = \"domain_already_exists_in_hierarchy\",\n  domain_name_collision = \"domain_name_collision\",\n  domain_no_handler = \"domain_no_handler\",\n  hydration_domain_mismatch = \"hydration_domain_mismatch\",\n  hydration_action_state_mismatch = \"hydration_action_state_mismatch\",\n  hydration_action_id_not_found = \"hydration_action_id_not_found\",\n  no_action_execution_handler = \"no_action_execution_handler\",\n  wire_action_not_payload = \"wire_action_not_payload\",\n  wire_not_action_data = \"wire_not_action_data\",\n  runtime_reset = \"runtime_reset\",\n  runtime_disposed = \"runtime_disposed\",\n  ambiguous_action_runtime = \"ambiguous_action_runtime\",\n  invalid_server_runtime_scope = \"invalid_server_runtime_scope\",\n  conflicting_server_options = \"conflicting_server_options\",\n  conflicting_connect_options = \"conflicting_connect_options\",\n  duplicate_action_executor = \"duplicate_action_executor\",\n  peer_handler_already_bound = \"peer_handler_already_bound\",\n  no_client_runtimes_registered = \"no_client_runtimes_registered\",\n  action_input_validation_failed = \"action_input_validation_failed\",\n  action_input_validation_promise = \"action_input_validation_promise\",\n  action_output_validation_failed = \"action_output_validation_failed\",\n  action_output_validation_promise = \"action_output_validation_promise\",\n  connection_required = \"connection_required\",\n}\n\nexport const err_nice_action = err_nice.createChildDomain({\n  domain: \"err_nice_action\",\n  defaultHttpStatusCode: 500,\n  schema: {\n    [EErrId_NiceAction.not_implemented]: err<{ label: string }>({\n      message: ({ label }) => `The \"${label}\" functionality is not implemented yet.`,\n    }),\n    [EErrId_NiceAction.action_id_not_in_domain]: err<{ domain: string; actionId: string }>({\n      message: ({ actionId, domain }) =>\n        `Action with id \"${actionId}\" does not exist in domain \"${domain}\".`,\n    }),\n    [EErrId_NiceAction.domain_already_exists_in_hierarchy]: err<{\n      domain: string;\n      allParentDomains: string[];\n      parentDomain: string;\n    }>({\n      message: ({ domain, allParentDomains, parentDomain }) =>\n        `Domain \"${domain}\" already exists in the hierarchy under the parent \"${parentDomain}\". All parent domains [\"${allParentDomains.join(\", \")}\"]`,\n    }),\n    [EErrId_NiceAction.domain_name_collision]: err<{\n      domain: string;\n      existingParentDomains: string[];\n      incomingParentDomains: string[];\n    }>({\n      message: ({ domain, existingParentDomains, incomingParentDomains }) =>\n        `Two different domain definitions named \"${domain}\" were registered on one runtime router (existing under [${existingParentDomains.join(\" > \")}], incoming under [${incomingParentDomains.join(\" > \")}]). Wire routing is by name only, so the later registration would silently shadow the earlier one — give the domains distinct names, or register the same instance.`,\n    }),\n    [EErrId_NiceAction.domain_no_handler]: err<{ domain: string }>({\n      message: ({ domain }) => `Domain \"${domain}\" has no action handler registered.`,\n    }),\n    [EErrId_NiceAction.hydration_domain_mismatch]: err<{\n      expected: string;\n      received: string;\n    }>({\n      message: ({ expected, received }) =>\n        `Cannot hydrate action: domain mismatch. Expected \"${expected}\", got \"${received}\".`,\n    }),\n    [EErrId_NiceAction.hydration_action_state_mismatch]: err<{\n      expected: string;\n      received: string;\n    }>({\n      message: ({ expected, received }) =>\n        `Cannot hydrate action: action state type mismatch. Expected \"${expected}\", got \"${received}\".`,\n    }),\n    [EErrId_NiceAction.hydration_action_id_not_found]: err<{\n      domain: string;\n      actionId: string;\n    }>({\n      message: ({ domain, actionId }) =>\n        `Cannot hydrate action: id \"${actionId}\" does not exist in domain \"${domain}\".`,\n    }),\n    [EErrId_NiceAction.no_action_execution_handler]: err<{\n      domain: string;\n      actionId: string;\n      specifiedClient?: RuntimeCoordinate;\n    }>({\n      message: ({ domain, actionId, specifiedClient }) =>\n        `${specifiedClient ? ` The targeted client runtime [${specifiedClient.stringId}] has no` : \"No\"} action handler registered for \"${actionId}\" in domain \"${domain}\".`,\n    }),\n    [EErrId_NiceAction.wire_action_not_payload]: err<{\n      domain: string;\n      actionId: string;\n      actionState: string | undefined;\n    }>({\n      message: ({ domain, actionId, actionState }) =>\n        `Cannot handle wire for action \"${actionId}\" in domain \"${domain}\": expected action form of \"${EActionForm.data}\" and type of \"${EActionPayloadType.request}\", \"${EActionPayloadType.progress}\" or \"${EActionPayloadType.result}\", got \"${actionState}\".`,\n    }),\n    [EErrId_NiceAction.wire_not_action_data]: err({\n      message: () =>\n        `Cannot handle wire for action: expected an object with a \"domain\" property of type string, a \"form\" property of \"${EActionForm.data}\" and a \"type\" property of \"${EActionPayloadType.request}\", \"${EActionPayloadType.progress}\" or \"${EActionPayloadType.result}\".`,\n    }),\n    [EErrId_NiceAction.connection_required]: err<{ operation: string }>({\n      message: ({ operation }) =>\n        `Cannot ${operation}: this action did not arrive on a live duplex connection.`,\n    }),\n    [EErrId_NiceAction.runtime_reset]: err({\n      message: () => `Runtime has been reset.`,\n    }),\n    [EErrId_NiceAction.runtime_disposed]: err<{ runtime: string }>({\n      message: ({ runtime }) =>\n        `Action runtime [${runtime}] has been disposed and cannot be reused.`,\n    }),\n    [EErrId_NiceAction.ambiguous_action_runtime]: err<{\n      domain: string;\n      actionId: string;\n      runtimes: string[];\n    }>({\n      message: ({ domain, actionId, runtimes }) =>\n        `Several runtimes can execute \"${domain}:${actionId}\" (${runtimes.join(\", \")}). Target one explicitly with runtime.run(request) or request.run({ targetLocalRuntime: runtime }).`,\n    }),\n    [EErrId_NiceAction.invalid_server_runtime_scope]: err<{\n      runtime: string;\n      actualScope: string;\n    }>({\n      message: ({ runtime, actualScope }) =>\n        `Server runtime [${runtime}] has scope \"${actualScope}\". Server hosts require new ActionRuntime(identity, { scope: \"instance\" }) so isolate-local instances never enter global dispatch.`,\n    }),\n    [EErrId_NiceAction.conflicting_server_options]: err<{ detail: string }>({\n      message: ({ detail }) => `Invalid server construction options: ${detail}`,\n    }),\n    [EErrId_NiceAction.conflicting_connect_options]: err<{ detail: string }>({\n      message: ({ detail }) => `Invalid connection options: ${detail}`,\n    }),\n    [EErrId_NiceAction.duplicate_action_executor]: err<{ route: string }>({\n      message: ({ route }) =>\n        `More than one local executor was registered for the same route priority (${route}). Keep one executor at that exact route; an action-specific executor may still override a domain fallback.`,\n    }),\n    [EErrId_NiceAction.peer_handler_already_bound]: err({\n      message: () =>\n        `A stateful peer handler is already bound to another runtime. Create one connector or acceptor per runtime.`,\n    }),\n    [EErrId_NiceAction.no_client_runtimes_registered]: err<{\n      context?: IActionRuntimeManagerContext;\n    }>({\n      message: ({ context }) =>\n        `No runtimes registered${context?.domain ? ` on domain \"${context.domain}\"` : \"\"}. Add handlers to a runtime via runtime.addHandlers([handler]) before executing actions.`,\n    }),\n    [EErrId_NiceAction.action_input_validation_failed]: err<{\n      domain: string;\n      actionId: string;\n      validationMessage: string;\n    }>({\n      message: ({ domain, actionId, validationMessage }) =>\n        `Input validation failed for action \"${actionId}\" in domain \"${domain}\":\\n${validationMessage}`,\n      httpStatusCode: 400,\n    }),\n    [EErrId_NiceAction.action_input_validation_promise]: err<{\n      domain: string;\n      actionId: string;\n    }>({\n      message: ({ domain, actionId }) =>\n        `Input validation for action \"${actionId}\" in domain \"${domain}\" returned a promise, which is not supported.`,\n      httpStatusCode: 400,\n    }),\n    [EErrId_NiceAction.action_output_validation_failed]: err<{\n      domain: string;\n      actionId: string;\n      validationMessage: string;\n    }>({\n      message: ({ domain, actionId, validationMessage }) =>\n        `Output validation failed for action \"${actionId}\" in domain \"${domain}\":\\n${validationMessage}`,\n      httpStatusCode: 500,\n    }),\n    [EErrId_NiceAction.action_output_validation_promise]: err<{\n      domain: string;\n      actionId: string;\n    }>({\n      message: ({ domain, actionId }) =>\n        `Output validation for action \"${actionId}\" in domain \"${domain}\" returned a promise, which is not supported.`,\n      httpStatusCode: 500,\n    }),\n  },\n});\n","import type { IActionBase_JsonObject } from \"../ActionDefinition/Action/ActionBase.types\";\n\nexport const isAction_Base_JsonObject = (obj: unknown): obj is IActionBase_JsonObject => {\n  return (\n    typeof obj === \"object\" &&\n    obj !== null &&\n    typeof (obj as any).domain === \"string\" &&\n    typeof (obj as any).id === \"string\" &&\n    typeof (obj as any).form === \"string\"\n  );\n};\n","import { EActionForm } from \"../ActionDefinition/Action/ActionBase.types\";\nimport type { IActionPayload_Result_JsonObject } from \"../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport { EActionPayloadType } from \"../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport { isAction_Base_JsonObject } from \"./isAction_Base_JsonObject\";\n\nexport const isActionPayload_Result_JsonObject = (\n  obj: unknown,\n): obj is IActionPayload_Result_JsonObject => {\n  return (\n    isAction_Base_JsonObject(obj) &&\n    (obj as any).result != null &&\n    (obj as any).form === EActionForm.data &&\n    (obj as any).type === EActionPayloadType.result\n  );\n};\n","\"use strict\";\n// Exporting constants directly to maintain compatability with v1\n// These are deprecated. Please don't add any new codes here.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.USE_PROXY = exports.UNSUPPORTED_MEDIA_TYPE = exports.UNPROCESSABLE_ENTITY = exports.UNAUTHORIZED = exports.TOO_MANY_REQUESTS = exports.TEMPORARY_REDIRECT = exports.SWITCHING_PROTOCOLS = exports.SERVICE_UNAVAILABLE = exports.SEE_OTHER = exports.RESET_CONTENT = exports.REQUESTED_RANGE_NOT_SATISFIABLE = exports.REQUEST_URI_TOO_LONG = exports.REQUEST_TOO_LONG = exports.REQUEST_TIMEOUT = exports.REQUEST_HEADER_FIELDS_TOO_LARGE = exports.PROXY_AUTHENTICATION_REQUIRED = exports.PROCESSING = exports.PRECONDITION_REQUIRED = exports.PRECONDITION_FAILED = exports.PERMANENT_REDIRECT = exports.PAYMENT_REQUIRED = exports.PARTIAL_CONTENT = exports.OK = exports.NOT_MODIFIED = exports.NOT_IMPLEMENTED = exports.NOT_FOUND = exports.NOT_ACCEPTABLE = exports.NON_AUTHORITATIVE_INFORMATION = exports.NO_CONTENT = exports.NETWORK_AUTHENTICATION_REQUIRED = exports.MULTIPLE_CHOICES = exports.MULTI_STATUS = exports.MOVED_TEMPORARILY = exports.MOVED_PERMANENTLY = exports.METHOD_NOT_ALLOWED = exports.METHOD_FAILURE = exports.LOCKED = exports.LENGTH_REQUIRED = exports.INTERNAL_SERVER_ERROR = exports.INSUFFICIENT_STORAGE = exports.INSUFFICIENT_SPACE_ON_RESOURCE = exports.IM_A_TEAPOT = exports.HTTP_VERSION_NOT_SUPPORTED = exports.GONE = exports.GATEWAY_TIMEOUT = exports.FORBIDDEN = exports.FAILED_DEPENDENCY = exports.EXPECTATION_FAILED = exports.CREATED = exports.CONTINUE = exports.CONFLICT = exports.BAD_REQUEST = exports.BAD_GATEWAY = exports.ACCEPTED = void 0;\n/**\n * @deprecated Please use StatusCodes.ACCEPTED\n *\n * */\nexports.ACCEPTED = 202;\n/**\n * @deprecated Please use StatusCodes.BAD_GATEWAY\n *\n * */\nexports.BAD_GATEWAY = 502;\n/**\n * @deprecated Please use StatusCodes.BAD_REQUEST\n *\n * */\nexports.BAD_REQUEST = 400;\n/**\n * @deprecated Please use StatusCodes.CONFLICT\n *\n * */\nexports.CONFLICT = 409;\n/**\n * @deprecated Please use StatusCodes.CONTINUE\n *\n * */\nexports.CONTINUE = 100;\n/**\n * @deprecated Please use StatusCodes.CREATED\n *\n * */\nexports.CREATED = 201;\n/**\n * @deprecated Please use StatusCodes.EXPECTATION_FAILED\n *\n * */\nexports.EXPECTATION_FAILED = 417;\n/**\n * @deprecated Please use StatusCodes.FAILED_DEPENDENCY\n *\n * */\nexports.FAILED_DEPENDENCY = 424;\n/**\n * @deprecated Please use StatusCodes.FORBIDDEN\n *\n * */\nexports.FORBIDDEN = 403;\n/**\n * @deprecated Please use StatusCodes.GATEWAY_TIMEOUT\n *\n * */\nexports.GATEWAY_TIMEOUT = 504;\n/**\n * @deprecated Please use StatusCodes.GONE\n *\n * */\nexports.GONE = 410;\n/**\n * @deprecated Please use StatusCodes.HTTP_VERSION_NOT_SUPPORTED\n *\n * */\nexports.HTTP_VERSION_NOT_SUPPORTED = 505;\n/**\n * @deprecated Please use StatusCodes.IM_A_TEAPOT\n *\n * */\nexports.IM_A_TEAPOT = 418;\n/**\n * @deprecated Please use StatusCodes.INSUFFICIENT_SPACE_ON_RESOURCE\n *\n * */\nexports.INSUFFICIENT_SPACE_ON_RESOURCE = 419;\n/**\n * @deprecated Please use StatusCodes.INSUFFICIENT_STORAGE\n *\n * */\nexports.INSUFFICIENT_STORAGE = 507;\n/**\n * @deprecated Please use StatusCodes.INTERNAL_SERVER_ERROR\n *\n * */\nexports.INTERNAL_SERVER_ERROR = 500;\n/**\n * @deprecated Please use StatusCodes.LENGTH_REQUIRED\n *\n * */\nexports.LENGTH_REQUIRED = 411;\n/**\n * @deprecated Please use StatusCodes.LOCKED\n *\n * */\nexports.LOCKED = 423;\n/**\n * @deprecated Please use StatusCodes.METHOD_FAILURE\n *\n * */\nexports.METHOD_FAILURE = 420;\n/**\n * @deprecated Please use StatusCodes.METHOD_NOT_ALLOWED\n *\n * */\nexports.METHOD_NOT_ALLOWED = 405;\n/**\n * @deprecated Please use StatusCodes.MOVED_PERMANENTLY\n *\n * */\nexports.MOVED_PERMANENTLY = 301;\n/**\n * @deprecated Please use StatusCodes.MOVED_TEMPORARILY\n *\n * */\nexports.MOVED_TEMPORARILY = 302;\n/**\n * @deprecated Please use StatusCodes.MULTI_STATUS\n *\n * */\nexports.MULTI_STATUS = 207;\n/**\n * @deprecated Please use StatusCodes.MULTIPLE_CHOICES\n *\n * */\nexports.MULTIPLE_CHOICES = 300;\n/**\n * @deprecated Please use StatusCodes.NETWORK_AUTHENTICATION_REQUIRED\n *\n * */\nexports.NETWORK_AUTHENTICATION_REQUIRED = 511;\n/**\n * @deprecated Please use StatusCodes.NO_CONTENT\n *\n * */\nexports.NO_CONTENT = 204;\n/**\n * @deprecated Please use StatusCodes.NON_AUTHORITATIVE_INFORMATION\n *\n * */\nexports.NON_AUTHORITATIVE_INFORMATION = 203;\n/**\n * @deprecated Please use StatusCodes.NOT_ACCEPTABLE\n *\n * */\nexports.NOT_ACCEPTABLE = 406;\n/**\n * @deprecated Please use StatusCodes.NOT_FOUND\n *\n * */\nexports.NOT_FOUND = 404;\n/**\n * @deprecated Please use StatusCodes.NOT_IMPLEMENTED\n *\n * */\nexports.NOT_IMPLEMENTED = 501;\n/**\n * @deprecated Please use StatusCodes.NOT_MODIFIED\n *\n * */\nexports.NOT_MODIFIED = 304;\n/**\n * @deprecated Please use StatusCodes.OK\n *\n * */\nexports.OK = 200;\n/**\n * @deprecated Please use StatusCodes.PARTIAL_CONTENT\n *\n * */\nexports.PARTIAL_CONTENT = 206;\n/**\n * @deprecated Please use StatusCodes.PAYMENT_REQUIRED\n *\n * */\nexports.PAYMENT_REQUIRED = 402;\n/**\n * @deprecated Please use StatusCodes.PERMANENT_REDIRECT\n *\n * */\nexports.PERMANENT_REDIRECT = 308;\n/**\n * @deprecated Please use StatusCodes.PRECONDITION_FAILED\n *\n * */\nexports.PRECONDITION_FAILED = 412;\n/**\n * @deprecated Please use StatusCodes.PRECONDITION_REQUIRED\n *\n * */\nexports.PRECONDITION_REQUIRED = 428;\n/**\n * @deprecated Please use StatusCodes.PROCESSING\n *\n * */\nexports.PROCESSING = 102;\n/**\n * @deprecated Please use StatusCodes.PROXY_AUTHENTICATION_REQUIRED\n *\n * */\nexports.PROXY_AUTHENTICATION_REQUIRED = 407;\n/**\n * @deprecated Please use StatusCodes.REQUEST_HEADER_FIELDS_TOO_LARGE\n *\n * */\nexports.REQUEST_HEADER_FIELDS_TOO_LARGE = 431;\n/**\n * @deprecated Please use StatusCodes.REQUEST_TIMEOUT\n *\n * */\nexports.REQUEST_TIMEOUT = 408;\n/**\n * @deprecated Please use StatusCodes.REQUEST_TOO_LONG\n *\n * */\nexports.REQUEST_TOO_LONG = 413;\n/**\n * @deprecated Please use StatusCodes.REQUEST_URI_TOO_LONG\n *\n * */\nexports.REQUEST_URI_TOO_LONG = 414;\n/**\n * @deprecated Please use StatusCodes.REQUESTED_RANGE_NOT_SATISFIABLE\n *\n * */\nexports.REQUESTED_RANGE_NOT_SATISFIABLE = 416;\n/**\n * @deprecated Please use StatusCodes.RESET_CONTENT\n *\n * */\nexports.RESET_CONTENT = 205;\n/**\n * @deprecated Please use StatusCodes.SEE_OTHER\n *\n * */\nexports.SEE_OTHER = 303;\n/**\n * @deprecated Please use StatusCodes.SERVICE_UNAVAILABLE\n *\n * */\nexports.SERVICE_UNAVAILABLE = 503;\n/**\n * @deprecated Please use StatusCodes.SWITCHING_PROTOCOLS\n *\n * */\nexports.SWITCHING_PROTOCOLS = 101;\n/**\n * @deprecated Please use StatusCodes.TEMPORARY_REDIRECT\n *\n * */\nexports.TEMPORARY_REDIRECT = 307;\n/**\n * @deprecated Please use StatusCodes.TOO_MANY_REQUESTS\n *\n * */\nexports.TOO_MANY_REQUESTS = 429;\n/**\n * @deprecated Please use StatusCodes.UNAUTHORIZED\n *\n * */\nexports.UNAUTHORIZED = 401;\n/**\n * @deprecated Please use StatusCodes.UNPROCESSABLE_ENTITY\n *\n * */\nexports.UNPROCESSABLE_ENTITY = 422;\n/**\n * @deprecated Please use StatusCodes.UNSUPPORTED_MEDIA_TYPE\n *\n * */\nexports.UNSUPPORTED_MEDIA_TYPE = 415;\n/**\n * @deprecated Please use StatusCodes.USE_PROXY\n *\n * */\nexports.USE_PROXY = 305;\nexports.default = {\n    ACCEPTED: exports.ACCEPTED,\n    BAD_GATEWAY: exports.BAD_GATEWAY,\n    BAD_REQUEST: exports.BAD_REQUEST,\n    CONFLICT: exports.CONFLICT,\n    CONTINUE: exports.CONTINUE,\n    CREATED: exports.CREATED,\n    EXPECTATION_FAILED: exports.EXPECTATION_FAILED,\n    FORBIDDEN: exports.FORBIDDEN,\n    GATEWAY_TIMEOUT: exports.GATEWAY_TIMEOUT,\n    GONE: exports.GONE,\n    HTTP_VERSION_NOT_SUPPORTED: exports.HTTP_VERSION_NOT_SUPPORTED,\n    IM_A_TEAPOT: exports.IM_A_TEAPOT,\n    INSUFFICIENT_SPACE_ON_RESOURCE: exports.INSUFFICIENT_SPACE_ON_RESOURCE,\n    INSUFFICIENT_STORAGE: exports.INSUFFICIENT_STORAGE,\n    INTERNAL_SERVER_ERROR: exports.INTERNAL_SERVER_ERROR,\n    LENGTH_REQUIRED: exports.LENGTH_REQUIRED,\n    LOCKED: exports.LOCKED,\n    METHOD_FAILURE: exports.METHOD_FAILURE,\n    METHOD_NOT_ALLOWED: exports.METHOD_NOT_ALLOWED,\n    MOVED_PERMANENTLY: exports.MOVED_PERMANENTLY,\n    MOVED_TEMPORARILY: exports.MOVED_TEMPORARILY,\n    MULTI_STATUS: exports.MULTI_STATUS,\n    MULTIPLE_CHOICES: exports.MULTIPLE_CHOICES,\n    NETWORK_AUTHENTICATION_REQUIRED: exports.NETWORK_AUTHENTICATION_REQUIRED,\n    NO_CONTENT: exports.NO_CONTENT,\n    NON_AUTHORITATIVE_INFORMATION: exports.NON_AUTHORITATIVE_INFORMATION,\n    NOT_ACCEPTABLE: exports.NOT_ACCEPTABLE,\n    NOT_FOUND: exports.NOT_FOUND,\n    NOT_IMPLEMENTED: exports.NOT_IMPLEMENTED,\n    NOT_MODIFIED: exports.NOT_MODIFIED,\n    OK: exports.OK,\n    PARTIAL_CONTENT: exports.PARTIAL_CONTENT,\n    PAYMENT_REQUIRED: exports.PAYMENT_REQUIRED,\n    PERMANENT_REDIRECT: exports.PERMANENT_REDIRECT,\n    PRECONDITION_FAILED: exports.PRECONDITION_FAILED,\n    PRECONDITION_REQUIRED: exports.PRECONDITION_REQUIRED,\n    PROCESSING: exports.PROCESSING,\n    PROXY_AUTHENTICATION_REQUIRED: exports.PROXY_AUTHENTICATION_REQUIRED,\n    REQUEST_HEADER_FIELDS_TOO_LARGE: exports.REQUEST_HEADER_FIELDS_TOO_LARGE,\n    REQUEST_TIMEOUT: exports.REQUEST_TIMEOUT,\n    REQUEST_TOO_LONG: exports.REQUEST_TOO_LONG,\n    REQUEST_URI_TOO_LONG: exports.REQUEST_URI_TOO_LONG,\n    REQUESTED_RANGE_NOT_SATISFIABLE: exports.REQUESTED_RANGE_NOT_SATISFIABLE,\n    RESET_CONTENT: exports.RESET_CONTENT,\n    SEE_OTHER: exports.SEE_OTHER,\n    SERVICE_UNAVAILABLE: exports.SERVICE_UNAVAILABLE,\n    SWITCHING_PROTOCOLS: exports.SWITCHING_PROTOCOLS,\n    TEMPORARY_REDIRECT: exports.TEMPORARY_REDIRECT,\n    TOO_MANY_REQUESTS: exports.TOO_MANY_REQUESTS,\n    UNAUTHORIZED: exports.UNAUTHORIZED,\n    UNPROCESSABLE_ENTITY: exports.UNPROCESSABLE_ENTITY,\n    UNSUPPORTED_MEDIA_TYPE: exports.UNSUPPORTED_MEDIA_TYPE,\n    USE_PROXY: exports.USE_PROXY,\n};\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.reasonPhraseToStatusCode = exports.statusCodeToReasonPhrase = void 0;\n// Generated file. Do not edit\nexports.statusCodeToReasonPhrase = {\n    \"202\": \"Accepted\",\n    \"502\": \"Bad Gateway\",\n    \"400\": \"Bad Request\",\n    \"409\": \"Conflict\",\n    \"100\": \"Continue\",\n    \"201\": \"Created\",\n    \"417\": \"Expectation Failed\",\n    \"424\": \"Failed Dependency\",\n    \"403\": \"Forbidden\",\n    \"504\": \"Gateway Timeout\",\n    \"410\": \"Gone\",\n    \"505\": \"HTTP Version Not Supported\",\n    \"418\": \"I'm a teapot\",\n    \"419\": \"Insufficient Space on Resource\",\n    \"507\": \"Insufficient Storage\",\n    \"500\": \"Internal Server Error\",\n    \"411\": \"Length Required\",\n    \"423\": \"Locked\",\n    \"420\": \"Method Failure\",\n    \"405\": \"Method Not Allowed\",\n    \"301\": \"Moved Permanently\",\n    \"302\": \"Moved Temporarily\",\n    \"207\": \"Multi-Status\",\n    \"300\": \"Multiple Choices\",\n    \"511\": \"Network Authentication Required\",\n    \"204\": \"No Content\",\n    \"203\": \"Non Authoritative Information\",\n    \"406\": \"Not Acceptable\",\n    \"404\": \"Not Found\",\n    \"501\": \"Not Implemented\",\n    \"304\": \"Not Modified\",\n    \"200\": \"OK\",\n    \"206\": \"Partial Content\",\n    \"402\": \"Payment Required\",\n    \"308\": \"Permanent Redirect\",\n    \"412\": \"Precondition Failed\",\n    \"428\": \"Precondition Required\",\n    \"102\": \"Processing\",\n    \"103\": \"Early Hints\",\n    \"426\": \"Upgrade Required\",\n    \"407\": \"Proxy Authentication Required\",\n    \"431\": \"Request Header Fields Too Large\",\n    \"408\": \"Request Timeout\",\n    \"413\": \"Request Entity Too Large\",\n    \"414\": \"Request-URI Too Long\",\n    \"416\": \"Requested Range Not Satisfiable\",\n    \"205\": \"Reset Content\",\n    \"303\": \"See Other\",\n    \"503\": \"Service Unavailable\",\n    \"101\": \"Switching Protocols\",\n    \"307\": \"Temporary Redirect\",\n    \"429\": \"Too Many Requests\",\n    \"401\": \"Unauthorized\",\n    \"451\": \"Unavailable For Legal Reasons\",\n    \"422\": \"Unprocessable Entity\",\n    \"415\": \"Unsupported Media Type\",\n    \"305\": \"Use Proxy\",\n    \"421\": \"Misdirected Request\"\n};\nexports.reasonPhraseToStatusCode = {\n    \"Accepted\": 202,\n    \"Bad Gateway\": 502,\n    \"Bad Request\": 400,\n    \"Conflict\": 409,\n    \"Continue\": 100,\n    \"Created\": 201,\n    \"Expectation Failed\": 417,\n    \"Failed Dependency\": 424,\n    \"Forbidden\": 403,\n    \"Gateway Timeout\": 504,\n    \"Gone\": 410,\n    \"HTTP Version Not Supported\": 505,\n    \"I'm a teapot\": 418,\n    \"Insufficient Space on Resource\": 419,\n    \"Insufficient Storage\": 507,\n    \"Internal Server Error\": 500,\n    \"Length Required\": 411,\n    \"Locked\": 423,\n    \"Method Failure\": 420,\n    \"Method Not Allowed\": 405,\n    \"Moved Permanently\": 301,\n    \"Moved Temporarily\": 302,\n    \"Multi-Status\": 207,\n    \"Multiple Choices\": 300,\n    \"Network Authentication Required\": 511,\n    \"No Content\": 204,\n    \"Non Authoritative Information\": 203,\n    \"Not Acceptable\": 406,\n    \"Not Found\": 404,\n    \"Not Implemented\": 501,\n    \"Not Modified\": 304,\n    \"OK\": 200,\n    \"Partial Content\": 206,\n    \"Payment Required\": 402,\n    \"Permanent Redirect\": 308,\n    \"Precondition Failed\": 412,\n    \"Precondition Required\": 428,\n    \"Processing\": 102,\n    \"Early Hints\": 103,\n    \"Upgrade Required\": 426,\n    \"Proxy Authentication Required\": 407,\n    \"Request Header Fields Too Large\": 431,\n    \"Request Timeout\": 408,\n    \"Request Entity Too Large\": 413,\n    \"Request-URI Too Long\": 414,\n    \"Requested Range Not Satisfiable\": 416,\n    \"Reset Content\": 205,\n    \"See Other\": 303,\n    \"Service Unavailable\": 503,\n    \"Switching Protocols\": 101,\n    \"Temporary Redirect\": 307,\n    \"Too Many Requests\": 429,\n    \"Unauthorized\": 401,\n    \"Unavailable For Legal Reasons\": 451,\n    \"Unprocessable Entity\": 422,\n    \"Unsupported Media Type\": 415,\n    \"Use Proxy\": 305,\n    \"Misdirected Request\": 421\n};\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getStatusText = exports.getStatusCode = exports.getReasonPhrase = void 0;\nvar utils_1 = require(\"./utils\");\n/**\n * Returns the reason phrase for the given status code.\n * If the given status code does not exist, an error is thrown.\n *\n * @param {number|string} statusCode The HTTP status code\n * @returns {string} The associated reason phrase (e.g. \"Bad Request\", \"OK\")\n * */\nfunction getReasonPhrase(statusCode) {\n    var result = utils_1.statusCodeToReasonPhrase[statusCode.toString()];\n    if (!result) {\n        throw new Error(\"Status code does not exist: \" + statusCode);\n    }\n    return result;\n}\nexports.getReasonPhrase = getReasonPhrase;\n/**\n * Returns the status code for the given reason phrase.\n * If the given reason phrase does not exist, undefined is returned.\n *\n * @param {string} reasonPhrase The HTTP reason phrase (e.g. \"Bad Request\", \"OK\")\n * @returns {string} The associated status code\n * */\nfunction getStatusCode(reasonPhrase) {\n    var result = utils_1.reasonPhraseToStatusCode[reasonPhrase];\n    if (!result) {\n        throw new Error(\"Reason phrase does not exist: \" + reasonPhrase);\n    }\n    return result;\n}\nexports.getStatusCode = getStatusCode;\n/**\n * @deprecated\n *\n * Returns the reason phrase for the given status code.\n * If the given status code does not exist, undefined is returned.\n *\n * Deprecated in favor of getReasonPhrase\n *\n * @param {number|string} statusCode The HTTP status code\n * @returns {string|undefined} The associated reason phrase (e.g. \"Bad Request\", \"OK\")\n * */\nexports.getStatusText = getReasonPhrase;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.StatusCodes = void 0;\n// Generated file. Do not edit\nvar StatusCodes;\n(function (StatusCodes) {\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.2.1\n     *\n     * This interim response indicates that everything so far is OK and that the client should continue with the request or ignore it if it is already finished.\n     */\n    StatusCodes[StatusCodes[\"CONTINUE\"] = 100] = \"CONTINUE\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.2.2\n     *\n     * This code is sent in response to an Upgrade request header by the client, and indicates the protocol the server is switching too.\n     */\n    StatusCodes[StatusCodes[\"SWITCHING_PROTOCOLS\"] = 101] = \"SWITCHING_PROTOCOLS\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.1\n     *\n     * This code indicates that the server has received and is processing the request, but no response is available yet.\n     */\n    StatusCodes[StatusCodes[\"PROCESSING\"] = 102] = \"PROCESSING\";\n    /**\n     * Official Documentation @ https://www.rfc-editor.org/rfc/rfc8297#page-3\n     *\n     * This code indicates to the client that the server is likely to send a final response with the header fields included in the informational response.\n     */\n    StatusCodes[StatusCodes[\"EARLY_HINTS\"] = 103] = \"EARLY_HINTS\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.1\n     *\n     * The request has succeeded. The meaning of a success varies depending on the HTTP method:\n     * GET: The resource has been fetched and is transmitted in the message body.\n     * HEAD: The entity headers are in the message body.\n     * POST: The resource describing the result of the action is transmitted in the message body.\n     * TRACE: The message body contains the request message as received by the server\n     */\n    StatusCodes[StatusCodes[\"OK\"] = 200] = \"OK\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.2\n     *\n     * The request has succeeded and a new resource has been created as a result of it. This is typically the response sent after a PUT request.\n     */\n    StatusCodes[StatusCodes[\"CREATED\"] = 201] = \"CREATED\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.3\n     *\n     * The request has been received but not yet acted upon. It is non-committal, meaning that there is no way in HTTP to later send an asynchronous response indicating the outcome of processing the request. It is intended for cases where another process or server handles the request, or for batch processing.\n     */\n    StatusCodes[StatusCodes[\"ACCEPTED\"] = 202] = \"ACCEPTED\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.4\n     *\n     * This response code means returned meta-information set is not exact set as available from the origin server, but collected from a local or a third party copy. Except this condition, 200 OK response should be preferred instead of this response.\n     */\n    StatusCodes[StatusCodes[\"NON_AUTHORITATIVE_INFORMATION\"] = 203] = \"NON_AUTHORITATIVE_INFORMATION\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.5\n     *\n     * There is no content to send for this request, but the headers may be useful. The user-agent may update its cached headers for this resource with the new ones.\n     */\n    StatusCodes[StatusCodes[\"NO_CONTENT\"] = 204] = \"NO_CONTENT\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.6\n     *\n     * This response code is sent after accomplishing request to tell user agent reset document view which sent this request.\n     */\n    StatusCodes[StatusCodes[\"RESET_CONTENT\"] = 205] = \"RESET_CONTENT\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7233#section-4.1\n     *\n     * This response code is used because of range header sent by the client to separate download into multiple streams.\n     */\n    StatusCodes[StatusCodes[\"PARTIAL_CONTENT\"] = 206] = \"PARTIAL_CONTENT\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.2\n     *\n     * A Multi-Status response conveys information about multiple resources in situations where multiple status codes might be appropriate.\n     */\n    StatusCodes[StatusCodes[\"MULTI_STATUS\"] = 207] = \"MULTI_STATUS\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.1\n     *\n     * The request has more than one possible responses. User-agent or user should choose one of them. There is no standardized way to choose one of the responses.\n     */\n    StatusCodes[StatusCodes[\"MULTIPLE_CHOICES\"] = 300] = \"MULTIPLE_CHOICES\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.2\n     *\n     * This response code means that URI of requested resource has been changed. Probably, new URI would be given in the response.\n     */\n    StatusCodes[StatusCodes[\"MOVED_PERMANENTLY\"] = 301] = \"MOVED_PERMANENTLY\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.3\n     *\n     * This response code means that URI of requested resource has been changed temporarily. New changes in the URI might be made in the future. Therefore, this same URI should be used by the client in future requests.\n     */\n    StatusCodes[StatusCodes[\"MOVED_TEMPORARILY\"] = 302] = \"MOVED_TEMPORARILY\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.4\n     *\n     * Server sent this response to directing client to get requested resource to another URI with an GET request.\n     */\n    StatusCodes[StatusCodes[\"SEE_OTHER\"] = 303] = \"SEE_OTHER\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7232#section-4.1\n     *\n     * This is used for caching purposes. It is telling to client that response has not been modified. So, client can continue to use same cached version of response.\n     */\n    StatusCodes[StatusCodes[\"NOT_MODIFIED\"] = 304] = \"NOT_MODIFIED\";\n    /**\n     * @deprecated\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.6\n     *\n     * Was defined in a previous version of the HTTP specification to indicate that a requested response must be accessed by a proxy. It has been deprecated due to security concerns regarding in-band configuration of a proxy.\n     */\n    StatusCodes[StatusCodes[\"USE_PROXY\"] = 305] = \"USE_PROXY\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.7\n     *\n     * Server sent this response to directing client to get requested resource to another URI with same method that used prior request. This has the same semantic than the 302 Found HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request.\n     */\n    StatusCodes[StatusCodes[\"TEMPORARY_REDIRECT\"] = 307] = \"TEMPORARY_REDIRECT\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7538#section-3\n     *\n     * This means that the resource is now permanently located at another URI, specified by the Location: HTTP Response header. This has the same semantics as the 301 Moved Permanently HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request.\n     */\n    StatusCodes[StatusCodes[\"PERMANENT_REDIRECT\"] = 308] = \"PERMANENT_REDIRECT\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.1\n     *\n     * This response means that server could not understand the request due to invalid syntax.\n     */\n    StatusCodes[StatusCodes[\"BAD_REQUEST\"] = 400] = \"BAD_REQUEST\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7235#section-3.1\n     *\n     * Although the HTTP standard specifies \"unauthorized\", semantically this response means \"unauthenticated\". That is, the client must authenticate itself to get the requested response.\n     */\n    StatusCodes[StatusCodes[\"UNAUTHORIZED\"] = 401] = \"UNAUTHORIZED\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.2\n     *\n     * This response code is reserved for future use. Initial aim for creating this code was using it for digital payment systems however this is not used currently.\n     */\n    StatusCodes[StatusCodes[\"PAYMENT_REQUIRED\"] = 402] = \"PAYMENT_REQUIRED\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.3\n     *\n     * The client does not have access rights to the content, i.e. they are unauthorized, so server is rejecting to give proper response. Unlike 401, the client's identity is known to the server.\n     */\n    StatusCodes[StatusCodes[\"FORBIDDEN\"] = 403] = \"FORBIDDEN\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.4\n     *\n     * The server can not find requested resource. In the browser, this means the URL is not recognized. In an API, this can also mean that the endpoint is valid but the resource itself does not exist. Servers may also send this response instead of 403 to hide the existence of a resource from an unauthorized client. This response code is probably the most famous one due to its frequent occurence on the web.\n     */\n    StatusCodes[StatusCodes[\"NOT_FOUND\"] = 404] = \"NOT_FOUND\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.5\n     *\n     * The request method is known by the server but has been disabled and cannot be used. For example, an API may forbid DELETE-ing a resource. The two mandatory methods, GET and HEAD, must never be disabled and should not return this error code.\n     */\n    StatusCodes[StatusCodes[\"METHOD_NOT_ALLOWED\"] = 405] = \"METHOD_NOT_ALLOWED\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.6\n     *\n     * This response is sent when the web server, after performing server-driven content negotiation, doesn't find any content following the criteria given by the user agent.\n     */\n    StatusCodes[StatusCodes[\"NOT_ACCEPTABLE\"] = 406] = \"NOT_ACCEPTABLE\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7235#section-3.2\n     *\n     * This is similar to 401 but authentication is needed to be done by a proxy.\n     */\n    StatusCodes[StatusCodes[\"PROXY_AUTHENTICATION_REQUIRED\"] = 407] = \"PROXY_AUTHENTICATION_REQUIRED\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.7\n     *\n     * This response is sent on an idle connection by some servers, even without any previous request by the client. It means that the server would like to shut down this unused connection. This response is used much more since some browsers, like Chrome, Firefox 27+, or IE9, use HTTP pre-connection mechanisms to speed up surfing. Also note that some servers merely shut down the connection without sending this message.\n     */\n    StatusCodes[StatusCodes[\"REQUEST_TIMEOUT\"] = 408] = \"REQUEST_TIMEOUT\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.8\n     *\n     * This response is sent when a request conflicts with the current state of the server.\n     */\n    StatusCodes[StatusCodes[\"CONFLICT\"] = 409] = \"CONFLICT\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.9\n     *\n     * This response would be sent when the requested content has been permenantly deleted from server, with no forwarding address. Clients are expected to remove their caches and links to the resource. The HTTP specification intends this status code to be used for \"limited-time, promotional services\". APIs should not feel compelled to indicate resources that have been deleted with this status code.\n     */\n    StatusCodes[StatusCodes[\"GONE\"] = 410] = \"GONE\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.10\n     *\n     * The server rejected the request because the Content-Length header field is not defined and the server requires it.\n     */\n    StatusCodes[StatusCodes[\"LENGTH_REQUIRED\"] = 411] = \"LENGTH_REQUIRED\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7232#section-4.2\n     *\n     * The client has indicated preconditions in its headers which the server does not meet.\n     */\n    StatusCodes[StatusCodes[\"PRECONDITION_FAILED\"] = 412] = \"PRECONDITION_FAILED\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.11\n     *\n     * Request entity is larger than limits defined by server; the server might close the connection or return an Retry-After header field.\n     */\n    StatusCodes[StatusCodes[\"REQUEST_TOO_LONG\"] = 413] = \"REQUEST_TOO_LONG\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.12\n     *\n     * The URI requested by the client is longer than the server is willing to interpret.\n     */\n    StatusCodes[StatusCodes[\"REQUEST_URI_TOO_LONG\"] = 414] = \"REQUEST_URI_TOO_LONG\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.13\n     *\n     * The media format of the requested data is not supported by the server, so the server is rejecting the request.\n     */\n    StatusCodes[StatusCodes[\"UNSUPPORTED_MEDIA_TYPE\"] = 415] = \"UNSUPPORTED_MEDIA_TYPE\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7233#section-4.4\n     *\n     * The range specified by the Range header field in the request can't be fulfilled; it's possible that the range is outside the size of the target URI's data.\n     */\n    StatusCodes[StatusCodes[\"REQUESTED_RANGE_NOT_SATISFIABLE\"] = 416] = \"REQUESTED_RANGE_NOT_SATISFIABLE\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.14\n     *\n     * This response code means the expectation indicated by the Expect request header field can't be met by the server.\n     */\n    StatusCodes[StatusCodes[\"EXPECTATION_FAILED\"] = 417] = \"EXPECTATION_FAILED\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc2324#section-2.3.2\n     *\n     * Any attempt to brew coffee with a teapot should result in the error code \"418 I'm a teapot\". The resulting entity body MAY be short and stout.\n     */\n    StatusCodes[StatusCodes[\"IM_A_TEAPOT\"] = 418] = \"IM_A_TEAPOT\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.6\n     *\n     * The 507 (Insufficient Storage) status code means the method could not be performed on the resource because the server is unable to store the representation needed to successfully complete the request. This condition is considered to be temporary. If the request which received this status code was the result of a user action, the request MUST NOT be repeated until it is requested by a separate user action.\n     */\n    StatusCodes[StatusCodes[\"INSUFFICIENT_SPACE_ON_RESOURCE\"] = 419] = \"INSUFFICIENT_SPACE_ON_RESOURCE\";\n    /**\n     * @deprecated\n     * Official Documentation @ https://tools.ietf.org/rfcdiff?difftype=--hwdiff&url2=draft-ietf-webdav-protocol-06.txt\n     *\n     * A deprecated response used by the Spring Framework when a method has failed.\n     */\n    StatusCodes[StatusCodes[\"METHOD_FAILURE\"] = 420] = \"METHOD_FAILURE\";\n    /**\n     * Official Documentation @ https://datatracker.ietf.org/doc/html/rfc7540#section-9.1.2\n     *\n     * Defined in the specification of HTTP/2 to indicate that a server is not able to produce a response for the combination of scheme and authority that are included in the request URI.\n     */\n    StatusCodes[StatusCodes[\"MISDIRECTED_REQUEST\"] = 421] = \"MISDIRECTED_REQUEST\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.3\n     *\n     * The request was well-formed but was unable to be followed due to semantic errors.\n     */\n    StatusCodes[StatusCodes[\"UNPROCESSABLE_ENTITY\"] = 422] = \"UNPROCESSABLE_ENTITY\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.4\n     *\n     * The resource that is being accessed is locked.\n     */\n    StatusCodes[StatusCodes[\"LOCKED\"] = 423] = \"LOCKED\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.5\n     *\n     * The request failed due to failure of a previous request.\n     */\n    StatusCodes[StatusCodes[\"FAILED_DEPENDENCY\"] = 424] = \"FAILED_DEPENDENCY\";\n    /**\n     * Official Documentation @ https://datatracker.ietf.org/doc/html/rfc7231#section-6.5.15\n     *\n     * The server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol.\n     */\n    StatusCodes[StatusCodes[\"UPGRADE_REQUIRED\"] = 426] = \"UPGRADE_REQUIRED\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-3\n     *\n     * The origin server requires the request to be conditional. Intended to prevent the 'lost update' problem, where a client GETs a resource's state, modifies it, and PUTs it back to the server, when meanwhile a third party has modified the state on the server, leading to a conflict.\n     */\n    StatusCodes[StatusCodes[\"PRECONDITION_REQUIRED\"] = 428] = \"PRECONDITION_REQUIRED\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-4\n     *\n     * The user has sent too many requests in a given amount of time (\"rate limiting\").\n     */\n    StatusCodes[StatusCodes[\"TOO_MANY_REQUESTS\"] = 429] = \"TOO_MANY_REQUESTS\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-5\n     *\n     * The server is unwilling to process the request because its header fields are too large. The request MAY be resubmitted after reducing the size of the request header fields.\n     */\n    StatusCodes[StatusCodes[\"REQUEST_HEADER_FIELDS_TOO_LARGE\"] = 431] = \"REQUEST_HEADER_FIELDS_TOO_LARGE\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7725\n     *\n     * The user-agent requested a resource that cannot legally be provided, such as a web page censored by a government.\n     */\n    StatusCodes[StatusCodes[\"UNAVAILABLE_FOR_LEGAL_REASONS\"] = 451] = \"UNAVAILABLE_FOR_LEGAL_REASONS\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.1\n     *\n     * The server encountered an unexpected condition that prevented it from fulfilling the request.\n     */\n    StatusCodes[StatusCodes[\"INTERNAL_SERVER_ERROR\"] = 500] = \"INTERNAL_SERVER_ERROR\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.2\n     *\n     * The request method is not supported by the server and cannot be handled. The only methods that servers are required to support (and therefore that must not return this code) are GET and HEAD.\n     */\n    StatusCodes[StatusCodes[\"NOT_IMPLEMENTED\"] = 501] = \"NOT_IMPLEMENTED\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.3\n     *\n     * This error response means that the server, while working as a gateway to get a response needed to handle the request, got an invalid response.\n     */\n    StatusCodes[StatusCodes[\"BAD_GATEWAY\"] = 502] = \"BAD_GATEWAY\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.4\n     *\n     * The server is not ready to handle the request. Common causes are a server that is down for maintenance or that is overloaded. Note that together with this response, a user-friendly page explaining the problem should be sent. This responses should be used for temporary conditions and the Retry-After: HTTP header should, if possible, contain the estimated time before the recovery of the service. The webmaster must also take care about the caching-related headers that are sent along with this response, as these temporary condition responses should usually not be cached.\n     */\n    StatusCodes[StatusCodes[\"SERVICE_UNAVAILABLE\"] = 503] = \"SERVICE_UNAVAILABLE\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.5\n     *\n     * This error response is given when the server is acting as a gateway and cannot get a response in time.\n     */\n    StatusCodes[StatusCodes[\"GATEWAY_TIMEOUT\"] = 504] = \"GATEWAY_TIMEOUT\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.6\n     *\n     * The HTTP version used in the request is not supported by the server.\n     */\n    StatusCodes[StatusCodes[\"HTTP_VERSION_NOT_SUPPORTED\"] = 505] = \"HTTP_VERSION_NOT_SUPPORTED\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.6\n     *\n     * The server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper end point in the negotiation process.\n     */\n    StatusCodes[StatusCodes[\"INSUFFICIENT_STORAGE\"] = 507] = \"INSUFFICIENT_STORAGE\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-6\n     *\n     * The 511 status code indicates that the client needs to authenticate to gain network access.\n     */\n    StatusCodes[StatusCodes[\"NETWORK_AUTHENTICATION_REQUIRED\"] = 511] = \"NETWORK_AUTHENTICATION_REQUIRED\";\n})(StatusCodes = exports.StatusCodes || (exports.StatusCodes = {}));\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ReasonPhrases = void 0;\n// Generated file. Do not edit\nvar ReasonPhrases;\n(function (ReasonPhrases) {\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.3\n     *\n     * The request has been received but not yet acted upon. It is non-committal, meaning that there is no way in HTTP to later send an asynchronous response indicating the outcome of processing the request. It is intended for cases where another process or server handles the request, or for batch processing.\n     */\n    ReasonPhrases[\"ACCEPTED\"] = \"Accepted\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.3\n     *\n     * This error response means that the server, while working as a gateway to get a response needed to handle the request, got an invalid response.\n     */\n    ReasonPhrases[\"BAD_GATEWAY\"] = \"Bad Gateway\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.1\n     *\n     * This response means that server could not understand the request due to invalid syntax.\n     */\n    ReasonPhrases[\"BAD_REQUEST\"] = \"Bad Request\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.8\n     *\n     * This response is sent when a request conflicts with the current state of the server.\n     */\n    ReasonPhrases[\"CONFLICT\"] = \"Conflict\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.2.1\n     *\n     * This interim response indicates that everything so far is OK and that the client should continue with the request or ignore it if it is already finished.\n     */\n    ReasonPhrases[\"CONTINUE\"] = \"Continue\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.2\n     *\n     * The request has succeeded and a new resource has been created as a result of it. This is typically the response sent after a PUT request.\n     */\n    ReasonPhrases[\"CREATED\"] = \"Created\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.14\n     *\n     * This response code means the expectation indicated by the Expect request header field can't be met by the server.\n     */\n    ReasonPhrases[\"EXPECTATION_FAILED\"] = \"Expectation Failed\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.5\n     *\n     * The request failed due to failure of a previous request.\n     */\n    ReasonPhrases[\"FAILED_DEPENDENCY\"] = \"Failed Dependency\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.3\n     *\n     * The client does not have access rights to the content, i.e. they are unauthorized, so server is rejecting to give proper response. Unlike 401, the client's identity is known to the server.\n     */\n    ReasonPhrases[\"FORBIDDEN\"] = \"Forbidden\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.5\n     *\n     * This error response is given when the server is acting as a gateway and cannot get a response in time.\n     */\n    ReasonPhrases[\"GATEWAY_TIMEOUT\"] = \"Gateway Timeout\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.9\n     *\n     * This response would be sent when the requested content has been permenantly deleted from server, with no forwarding address. Clients are expected to remove their caches and links to the resource. The HTTP specification intends this status code to be used for \"limited-time, promotional services\". APIs should not feel compelled to indicate resources that have been deleted with this status code.\n     */\n    ReasonPhrases[\"GONE\"] = \"Gone\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.6\n     *\n     * The HTTP version used in the request is not supported by the server.\n     */\n    ReasonPhrases[\"HTTP_VERSION_NOT_SUPPORTED\"] = \"HTTP Version Not Supported\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc2324#section-2.3.2\n     *\n     * Any attempt to brew coffee with a teapot should result in the error code \"418 I'm a teapot\". The resulting entity body MAY be short and stout.\n     */\n    ReasonPhrases[\"IM_A_TEAPOT\"] = \"I'm a teapot\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.6\n     *\n     * The 507 (Insufficient Storage) status code means the method could not be performed on the resource because the server is unable to store the representation needed to successfully complete the request. This condition is considered to be temporary. If the request which received this status code was the result of a user action, the request MUST NOT be repeated until it is requested by a separate user action.\n     */\n    ReasonPhrases[\"INSUFFICIENT_SPACE_ON_RESOURCE\"] = \"Insufficient Space on Resource\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.6\n     *\n     * The server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper end point in the negotiation process.\n     */\n    ReasonPhrases[\"INSUFFICIENT_STORAGE\"] = \"Insufficient Storage\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.1\n     *\n     * The server encountered an unexpected condition that prevented it from fulfilling the request.\n     */\n    ReasonPhrases[\"INTERNAL_SERVER_ERROR\"] = \"Internal Server Error\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.10\n     *\n     * The server rejected the request because the Content-Length header field is not defined and the server requires it.\n     */\n    ReasonPhrases[\"LENGTH_REQUIRED\"] = \"Length Required\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.4\n     *\n     * The resource that is being accessed is locked.\n     */\n    ReasonPhrases[\"LOCKED\"] = \"Locked\";\n    /**\n     * @deprecated\n     * Official Documentation @ https://tools.ietf.org/rfcdiff?difftype=--hwdiff&url2=draft-ietf-webdav-protocol-06.txt\n     *\n     * A deprecated response used by the Spring Framework when a method has failed.\n     */\n    ReasonPhrases[\"METHOD_FAILURE\"] = \"Method Failure\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.5\n     *\n     * The request method is known by the server but has been disabled and cannot be used. For example, an API may forbid DELETE-ing a resource. The two mandatory methods, GET and HEAD, must never be disabled and should not return this error code.\n     */\n    ReasonPhrases[\"METHOD_NOT_ALLOWED\"] = \"Method Not Allowed\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.2\n     *\n     * This response code means that URI of requested resource has been changed. Probably, new URI would be given in the response.\n     */\n    ReasonPhrases[\"MOVED_PERMANENTLY\"] = \"Moved Permanently\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.3\n     *\n     * This response code means that URI of requested resource has been changed temporarily. New changes in the URI might be made in the future. Therefore, this same URI should be used by the client in future requests.\n     */\n    ReasonPhrases[\"MOVED_TEMPORARILY\"] = \"Moved Temporarily\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.2\n     *\n     * A Multi-Status response conveys information about multiple resources in situations where multiple status codes might be appropriate.\n     */\n    ReasonPhrases[\"MULTI_STATUS\"] = \"Multi-Status\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.1\n     *\n     * The request has more than one possible responses. User-agent or user should choose one of them. There is no standardized way to choose one of the responses.\n     */\n    ReasonPhrases[\"MULTIPLE_CHOICES\"] = \"Multiple Choices\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-6\n     *\n     * The 511 status code indicates that the client needs to authenticate to gain network access.\n     */\n    ReasonPhrases[\"NETWORK_AUTHENTICATION_REQUIRED\"] = \"Network Authentication Required\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.5\n     *\n     * There is no content to send for this request, but the headers may be useful. The user-agent may update its cached headers for this resource with the new ones.\n     */\n    ReasonPhrases[\"NO_CONTENT\"] = \"No Content\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.4\n     *\n     * This response code means returned meta-information set is not exact set as available from the origin server, but collected from a local or a third party copy. Except this condition, 200 OK response should be preferred instead of this response.\n     */\n    ReasonPhrases[\"NON_AUTHORITATIVE_INFORMATION\"] = \"Non Authoritative Information\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.6\n     *\n     * This response is sent when the web server, after performing server-driven content negotiation, doesn't find any content following the criteria given by the user agent.\n     */\n    ReasonPhrases[\"NOT_ACCEPTABLE\"] = \"Not Acceptable\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.4\n     *\n     * The server can not find requested resource. In the browser, this means the URL is not recognized. In an API, this can also mean that the endpoint is valid but the resource itself does not exist. Servers may also send this response instead of 403 to hide the existence of a resource from an unauthorized client. This response code is probably the most famous one due to its frequent occurence on the web.\n     */\n    ReasonPhrases[\"NOT_FOUND\"] = \"Not Found\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.2\n     *\n     * The request method is not supported by the server and cannot be handled. The only methods that servers are required to support (and therefore that must not return this code) are GET and HEAD.\n     */\n    ReasonPhrases[\"NOT_IMPLEMENTED\"] = \"Not Implemented\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7232#section-4.1\n     *\n     * This is used for caching purposes. It is telling to client that response has not been modified. So, client can continue to use same cached version of response.\n     */\n    ReasonPhrases[\"NOT_MODIFIED\"] = \"Not Modified\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.1\n     *\n     * The request has succeeded. The meaning of a success varies depending on the HTTP method:\n     * GET: The resource has been fetched and is transmitted in the message body.\n     * HEAD: The entity headers are in the message body.\n     * POST: The resource describing the result of the action is transmitted in the message body.\n     * TRACE: The message body contains the request message as received by the server\n     */\n    ReasonPhrases[\"OK\"] = \"OK\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7233#section-4.1\n     *\n     * This response code is used because of range header sent by the client to separate download into multiple streams.\n     */\n    ReasonPhrases[\"PARTIAL_CONTENT\"] = \"Partial Content\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.2\n     *\n     * This response code is reserved for future use. Initial aim for creating this code was using it for digital payment systems however this is not used currently.\n     */\n    ReasonPhrases[\"PAYMENT_REQUIRED\"] = \"Payment Required\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7538#section-3\n     *\n     * This means that the resource is now permanently located at another URI, specified by the Location: HTTP Response header. This has the same semantics as the 301 Moved Permanently HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request.\n     */\n    ReasonPhrases[\"PERMANENT_REDIRECT\"] = \"Permanent Redirect\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7232#section-4.2\n     *\n     * The client has indicated preconditions in its headers which the server does not meet.\n     */\n    ReasonPhrases[\"PRECONDITION_FAILED\"] = \"Precondition Failed\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-3\n     *\n     * The origin server requires the request to be conditional. Intended to prevent the 'lost update' problem, where a client GETs a resource's state, modifies it, and PUTs it back to the server, when meanwhile a third party has modified the state on the server, leading to a conflict.\n     */\n    ReasonPhrases[\"PRECONDITION_REQUIRED\"] = \"Precondition Required\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.1\n     *\n     * This code indicates that the server has received and is processing the request, but no response is available yet.\n     */\n    ReasonPhrases[\"PROCESSING\"] = \"Processing\";\n    /**\n     * Official Documentation @ https://www.rfc-editor.org/rfc/rfc8297#page-3\n     *\n     * This code indicates to the client that the server is likely to send a final response with the header fields included in the informational response.\n     */\n    ReasonPhrases[\"EARLY_HINTS\"] = \"Early Hints\";\n    /**\n     * Official Documentation @ https://datatracker.ietf.org/doc/html/rfc7231#section-6.5.15\n     *\n     * The server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol.\n     */\n    ReasonPhrases[\"UPGRADE_REQUIRED\"] = \"Upgrade Required\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7235#section-3.2\n     *\n     * This is similar to 401 but authentication is needed to be done by a proxy.\n     */\n    ReasonPhrases[\"PROXY_AUTHENTICATION_REQUIRED\"] = \"Proxy Authentication Required\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-5\n     *\n     * The server is unwilling to process the request because its header fields are too large. The request MAY be resubmitted after reducing the size of the request header fields.\n     */\n    ReasonPhrases[\"REQUEST_HEADER_FIELDS_TOO_LARGE\"] = \"Request Header Fields Too Large\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.7\n     *\n     * This response is sent on an idle connection by some servers, even without any previous request by the client. It means that the server would like to shut down this unused connection. This response is used much more since some browsers, like Chrome, Firefox 27+, or IE9, use HTTP pre-connection mechanisms to speed up surfing. Also note that some servers merely shut down the connection without sending this message.\n     */\n    ReasonPhrases[\"REQUEST_TIMEOUT\"] = \"Request Timeout\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.11\n     *\n     * Request entity is larger than limits defined by server; the server might close the connection or return an Retry-After header field.\n     */\n    ReasonPhrases[\"REQUEST_TOO_LONG\"] = \"Request Entity Too Large\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.12\n     *\n     * The URI requested by the client is longer than the server is willing to interpret.\n     */\n    ReasonPhrases[\"REQUEST_URI_TOO_LONG\"] = \"Request-URI Too Long\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7233#section-4.4\n     *\n     * The range specified by the Range header field in the request can't be fulfilled; it's possible that the range is outside the size of the target URI's data.\n     */\n    ReasonPhrases[\"REQUESTED_RANGE_NOT_SATISFIABLE\"] = \"Requested Range Not Satisfiable\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.6\n     *\n     * This response code is sent after accomplishing request to tell user agent reset document view which sent this request.\n     */\n    ReasonPhrases[\"RESET_CONTENT\"] = \"Reset Content\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.4\n     *\n     * Server sent this response to directing client to get requested resource to another URI with an GET request.\n     */\n    ReasonPhrases[\"SEE_OTHER\"] = \"See Other\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.4\n     *\n     * The server is not ready to handle the request. Common causes are a server that is down for maintenance or that is overloaded. Note that together with this response, a user-friendly page explaining the problem should be sent. This responses should be used for temporary conditions and the Retry-After: HTTP header should, if possible, contain the estimated time before the recovery of the service. The webmaster must also take care about the caching-related headers that are sent along with this response, as these temporary condition responses should usually not be cached.\n     */\n    ReasonPhrases[\"SERVICE_UNAVAILABLE\"] = \"Service Unavailable\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.2.2\n     *\n     * This code is sent in response to an Upgrade request header by the client, and indicates the protocol the server is switching too.\n     */\n    ReasonPhrases[\"SWITCHING_PROTOCOLS\"] = \"Switching Protocols\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.7\n     *\n     * Server sent this response to directing client to get requested resource to another URI with same method that used prior request. This has the same semantic than the 302 Found HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request.\n     */\n    ReasonPhrases[\"TEMPORARY_REDIRECT\"] = \"Temporary Redirect\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-4\n     *\n     * The user has sent too many requests in a given amount of time (\"rate limiting\").\n     */\n    ReasonPhrases[\"TOO_MANY_REQUESTS\"] = \"Too Many Requests\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7235#section-3.1\n     *\n     * Although the HTTP standard specifies \"unauthorized\", semantically this response means \"unauthenticated\". That is, the client must authenticate itself to get the requested response.\n     */\n    ReasonPhrases[\"UNAUTHORIZED\"] = \"Unauthorized\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7725\n     *\n     * The user-agent requested a resource that cannot legally be provided, such as a web page censored by a government.\n     */\n    ReasonPhrases[\"UNAVAILABLE_FOR_LEGAL_REASONS\"] = \"Unavailable For Legal Reasons\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.3\n     *\n     * The request was well-formed but was unable to be followed due to semantic errors.\n     */\n    ReasonPhrases[\"UNPROCESSABLE_ENTITY\"] = \"Unprocessable Entity\";\n    /**\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.13\n     *\n     * The media format of the requested data is not supported by the server, so the server is rejecting the request.\n     */\n    ReasonPhrases[\"UNSUPPORTED_MEDIA_TYPE\"] = \"Unsupported Media Type\";\n    /**\n     * @deprecated\n     * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.6\n     *\n     * Was defined in a previous version of the HTTP specification to indicate that a requested response must be accessed by a proxy. It has been deprecated due to security concerns regarding in-band configuration of a proxy.\n     */\n    ReasonPhrases[\"USE_PROXY\"] = \"Use Proxy\";\n    /**\n     * Official Documentation @ https://datatracker.ietf.org/doc/html/rfc7540#section-9.1.2\n     *\n     * Defined in the specification of HTTP/2 to indicate that a server is not able to produce a response for the combination of scheme and authority that are included in the request URI.\n     */\n    ReasonPhrases[\"MISDIRECTED_REQUEST\"] = \"Misdirected Request\";\n})(ReasonPhrases = exports.ReasonPhrases || (exports.ReasonPhrases = {}));\n","\"use strict\";\nvar __assign = (this && this.__assign) || function () {\n    __assign = Object.assign || function(t) {\n        for (var s, i = 1, n = arguments.length; i < n; i++) {\n            s = arguments[i];\n            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n                t[p] = s[p];\n        }\n        return t;\n    };\n    return __assign.apply(this, arguments);\n};\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n    if (k2 === undefined) k2 = k;\n    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n    if (k2 === undefined) k2 = k;\n    o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n    for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);\n};\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n    return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar legacy_1 = __importDefault(require(\"./legacy\"));\nvar utils_functions_1 = require(\"./utils-functions\");\nvar utils_functions_2 = require(\"./utils-functions\");\nObject.defineProperty(exports, \"getStatusCode\", { enumerable: true, get: function () { return utils_functions_2.getStatusCode; } });\nObject.defineProperty(exports, \"getReasonPhrase\", { enumerable: true, get: function () { return utils_functions_2.getReasonPhrase; } });\nObject.defineProperty(exports, \"getStatusText\", { enumerable: true, get: function () { return utils_functions_2.getStatusText; } });\nvar status_codes_1 = require(\"./status-codes\");\nObject.defineProperty(exports, \"StatusCodes\", { enumerable: true, get: function () { return status_codes_1.StatusCodes; } });\nvar reason_phrases_1 = require(\"./reason-phrases\");\nObject.defineProperty(exports, \"ReasonPhrases\", { enumerable: true, get: function () { return reason_phrases_1.ReasonPhrases; } });\n__exportStar(require(\"./legacy\"), exports);\nexports.default = __assign(__assign({}, legacy_1.default), { getStatusCode: utils_functions_1.getStatusCode,\n    getStatusText: utils_functions_1.getStatusText });\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\nfunction extractPathFromIssue(\n  issue: ReadonlyArray<PropertyKey | StandardSchemaV1.PathSegment>,\n): string {\n  let pathString = \"\";\n\n  for (const segment of issue) {\n    if (typeof segment === \"object\") {\n      if (segment.key != null) {\n        if (typeof segment.key === \"number\") {\n          pathString += `[${String(segment.key)}]`;\n        } else if (typeof segment.key === \"symbol\") {\n          pathString += `[SYMBOL:${String(segment.key)}]`;\n        } else {\n          pathString += `.${String(segment.key)}`;\n        }\n      }\n    } else {\n      pathString += `.${String(segment)}`;\n    }\n  }\n\n  return pathString.slice(1); // Remove the leading dot\n}\n\nexport const extractMessageFromStandardSchema = (\n  failureResult: StandardSchemaV1.FailureResult,\n): string => {\n  let message = \"Data validation failed:\\n\";\n  let issueCount = 0;\n\n  for (const issue of failureResult.issues) {\n    issueCount++;\n    if (issue.path == null || issue.path.length === 0) {\n      message += ` (issue ${issueCount}) ${issue.message}\\n`;\n    } else {\n      message += ` (issue ${issueCount}) [${extractPathFromIssue(issue.path)}]: ${issue.message}\\n`;\n    }\n  }\n\n  return message;\n};\n","import { err, err_nice } from \"@nice-code/error\";\nimport { StatusCodes } from \"http-status-codes\";\nimport type { IErrContext_HonoStandardSchema } from \"./err_validation.types\";\nimport { extractMessageFromStandardSchema } from \"./standard_schema/extractMessageFromStandardSchema\";\n\nexport enum EValidator {\n  standard_schema = \"standard_schema\",\n}\n\nexport const err_validation = err_nice.createChildDomain({\n  domain: \"err_validation\",\n  defaultHttpStatusCode: StatusCodes.BAD_REQUEST,\n  schema: {\n    [EValidator.standard_schema]: err<IErrContext_HonoStandardSchema>({\n      message: ({ issues }) => extractMessageFromStandardSchema({ issues }),\n    }),\n  },\n});\n","import { extractMessageFromStandardSchema } from \"@nice-code/common-errors\";\nimport {\n  type INiceErrorDomainProps,\n  type InferNiceError,\n  type NiceError,\n  type NiceErrorDomain,\n} from \"@nice-code/error\";\nimport type { err_cast_not_nice } from \"@nice-code/error/internal\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { EErrId_NiceAction, err_nice_action } from \"../../errors/err_nice_action\";\nimport type {\n  IActionErrorDeclaration,\n  TActionSchemaOptions,\n  TInferDeclaredErrors,\n  TTransportedValue,\n} from \"./ActionSchema.types\";\n\n/**\n * What a sender should expect back from an action — declared on its schema so both ends agree without\n * any wire flag (each derives the mode from the shared `domain:id`).\n *\n * - `payload` — a typed output (the action has `.output(...)`); the sender awaits it.\n * - `ack` — an empty success confirming receipt (no output); the sender may await it to know the\n *   receiver handled it (or to surface an error). This is the default for an action with no output.\n * - `none` — fire-and-forget: the receiver sends no reply and the sender doesn't wait. The sender's\n *   running action completes as soon as the frame is on the wire (no pending reply, no timeout).\n */\nexport enum EActionResponseMode {\n  payload = \"payload\",\n  ack = \"ack\",\n  none = \"none\",\n}\n\n/**\n * The delivery guarantee for an action, declared on its schema so both ends agree without a wire flag\n * (each derives the tier from the shared `domain:id`, exactly like {@link EActionResponseMode}). Opt-in;\n * the default is `none` (today's best-effort transport, unchanged).\n *\n * - `none` — best-effort (default). A dropped frame is lost; a reconnect does not replay it.\n * - `session` — ordered, at-least-once, dedup-by-seq **within a resumable session**; the client resends\n *   unacked frames on reconnect. Across a session reset (server eviction/restart) it degrades to\n *   at-least-once *with possible redelivery*, so a reliable handler **must be idempotent**.\n * - `persisted` — as `session`, but the server's dedup high-water is persisted (e.g. DO storage), so dedup\n *   and gap-free catch-up survive eviction too. Backed by the `ReliableLog` primitive.\n *\n * Orthogonal to {@link EActionResponseMode}: the reliability ack is a transport concern (it rides a\n * dedicated envelope slot), separate from the action's application-level reply. A reliable action with no\n * natural reply still gets a standalone transport ack.\n */\nexport enum EReliabilityTier {\n  none = \"none\",\n  session = \"session\",\n  persisted = \"persisted\",\n}\n\nexport class ActionSchema<\n  INPUT extends TTransportedValue<any, any> = never,\n  OUTPUT extends TTransportedValue<any, any> = never,\n  ERRORS extends readonly IActionErrorDeclaration<any, any>[] = readonly [],\n> {\n  private _errorDeclarations: IActionErrorDeclaration[] = [];\n  private inputOptions: TActionSchemaOptions<any, any> | undefined;\n  private outputOptions: TActionSchemaOptions<any, any> | undefined;\n  private _responseMode: EActionResponseMode | undefined;\n  private _reliabilityTier: EReliabilityTier = EReliabilityTier.none;\n\n  get inputSchema(): StandardSchemaV1 | undefined {\n    return this.inputOptions?.schema;\n  }\n\n  get outputSchema(): StandardSchemaV1 | undefined {\n    return this.outputOptions?.schema;\n  }\n\n  /**\n   * The response contract for this action. Defaults are inferred — `payload` when an output schema is\n   * declared, otherwise `ack` — and made explicit by {@link ack} / {@link fireAndForget}.\n   */\n  get responseMode(): EActionResponseMode {\n    if (this._responseMode != null) return this._responseMode;\n    return this.outputOptions != null ? EActionResponseMode.payload : EActionResponseMode.ack;\n  }\n\n  /**\n   * Mark this action as expecting only an acknowledgment (an empty success). Mostly for clarity — an\n   * output-less action already acks by default — but it documents intent and reads as the deliberate\n   * counterpart to {@link fireAndForget}.\n   */\n  ack(): this {\n    this._responseMode = EActionResponseMode.ack;\n    return this;\n  }\n\n  /**\n   * Mark this action as fire-and-forget: the receiver sends no reply, and the sender's running action\n   * completes the moment the frame is sent (no awaited reply, no timeout). Ideal for high-frequency\n   * server→client pushes (presence, ticks) where an ack would only add wire chatter.\n   */\n  fireAndForget(): this {\n    this._responseMode = EActionResponseMode.none;\n    return this;\n  }\n\n  /**\n   * The reliability tier for this action (see {@link EReliabilityTier}). Both ends read it from the\n   * shared schema, so no wire flag says \"this is reliable\" — the sender/receiver derive it from the\n   * `domain:id`. Defaults to {@link EReliabilityTier.none} (best-effort).\n   */\n  get reliabilityTier(): EReliabilityTier {\n    return this._reliabilityTier;\n  }\n\n  /**\n   * Opt this action into ordered, at-least-once delivery with resend-on-reconnect (see\n   * {@link EReliabilityTier}). Pass `{ persist: true }` for the persisted tier whose dedup survives\n   * server eviction. The `persist` flag is the *only* knob — reliability is deliberately un-parameterized\n   * (no priorities/TTL/exactly-once-effect); those stay in app land.\n   *\n   * At-least-once means a reliable handler can see a redelivered frame after a session reset, so it\n   * **must be idempotent**. The dedup-by-seq runtime makes that a non-issue within a live session.\n   */\n  reliable(options?: { persist?: boolean }): this {\n    this._reliabilityTier =\n      options?.persist === true ? EReliabilityTier.persisted : EReliabilityTier.session;\n    return this;\n  }\n\n  /**\n   * Declare the input schema (JSON-native or with explicit SERDE type param).\n   * For non-JSON-native inputs, prefer the 3-argument form below to avoid\n   * needing explicit type parameters.\n   *\n   * The schema runs at `request()` AND again on the receiving runtime before the handler executes,\n   * so it must accept its own validated output. Plain validators always do; a `transform` whose\n   * output fails its own input schema will reject valid requests on arrival — type conversion\n   * belongs in the SERDE pack/unpack arguments, not in schema transforms.\n   */\n  input<VS extends StandardSchemaV1 = StandardSchemaV1, SERDE_IN = any>(\n    options: TActionSchemaOptions<VS, SERDE_IN>,\n  ): ActionSchema<TTransportedValue<StandardSchemaV1.InferInput<VS>, SERDE_IN>, OUTPUT, ERRORS> {\n    this.inputOptions = options;\n    return this;\n  }\n\n  /**\n   * Declare the output schema (JSON-native or with explicit SERDE type param).\n   * For non-JSON-native outputs, prefer the 3-argument form below to avoid\n   * needing explicit type parameters.\n   */\n  output<VS extends StandardSchemaV1 = StandardSchemaV1, SERDE_OUT = any>(\n    options: TActionSchemaOptions<VS, SERDE_OUT>,\n  ): ActionSchema<INPUT, TTransportedValue<StandardSchemaV1.InferInput<VS>, SERDE_OUT>, ERRORS> {\n    this.outputOptions = options;\n    return this;\n  }\n\n  /**\n   * Declare that this action may throw any error from `domain`.\n   * `TInferActionError` will include `NiceError<DEF, keyof schema>` in its union.\n   */\n  throws<ERR_DEF extends INiceErrorDomainProps>(\n    domain: NiceErrorDomain<ERR_DEF>,\n  ): ActionSchema<\n    INPUT,\n    OUTPUT,\n    readonly [...ERRORS, IActionErrorDeclaration<ERR_DEF, keyof ERR_DEF[\"schema\"] & string>]\n  >;\n\n  /**\n   * Declare that this action may throw only the listed `ids` from `domain`.\n   * `TInferActionError` will include `NiceError<DEF, IDS[number]>` narrowed to those IDs.\n   */\n  throws<\n    ERR_DEF extends INiceErrorDomainProps,\n    IDS extends ReadonlyArray<keyof ERR_DEF[\"schema\"] & string>,\n  >(\n    domain: NiceErrorDomain<ERR_DEF>,\n    ids: IDS,\n  ): ActionSchema<\n    INPUT,\n    OUTPUT,\n    readonly [...ERRORS, IActionErrorDeclaration<ERR_DEF, IDS[number] & string>]\n  >;\n\n  throws(domain: NiceErrorDomain<any>, ids?: ReadonlyArray<string>): ActionSchema<any, any, any> {\n    this._errorDeclarations.push({ _domain: domain, _ids: ids });\n    return this;\n  }\n\n  /**\n   * Runtime counterpart of {@link TInferActionError}: `true` when `error` is one of\n   * the errors this action declared via `.throws()` (exact domain + id match). A\n   * wrapped foreign throw (`err_cast_not_nice`) is never declared, so it returns\n   * `false` automatically. Drives the `expected` flag on the action result.\n   */\n  isExpectedError(error: NiceError<any, any>): boolean {\n    return this._errorDeclarations.some(\n      (d) => d._domain.isExact(error) && (d._ids == null || d._ids.some((id) => error.hasId(id))),\n    );\n  }\n\n  /**\n   * Serialize raw input to a JSON-serializable form.\n   * Uses the schema's serialization.serialize if defined; otherwise the input\n   * is already JSON-native and is returned as-is.\n   */\n  serializeInput(rawInput: INPUT[0]): INPUT[1] {\n    if (this.inputOptions?.serialization) {\n      return this.inputOptions.serialization.serialize(rawInput);\n    }\n    return rawInput;\n  }\n\n  /**\n   * Deserialize a JSON value back into the raw input type.\n   * Uses serialization.deserialize if defined; otherwise the value is cast\n   * directly (it's already in the correct shape).\n   */\n  deserializeInput(serialized: INPUT[1]): INPUT[0] {\n    if (this.inputOptions?.serialization) {\n      return this.inputOptions.serialization.deserialize(serialized);\n    }\n    return serialized as INPUT[0];\n  }\n\n  /**\n   * Validate raw input against the schema defined via `.input({ schema })`.\n   * Throws `action_input_validation_failed` if validation fails.\n   * Returns the validated (and possibly coerced) value on success.\n   * If no input schema was declared, the value is passed through as-is.\n   */\n  validateInput(value: unknown, meta: { domain: string; actionId: string }): INPUT[0] {\n    if (this.inputOptions?.schema == null) {\n      return value as INPUT[0];\n    }\n    const result = this.inputOptions.schema[\"~standard\"].validate(value);\n\n    if (result instanceof Promise) {\n      throw err_nice_action.fromId(EErrId_NiceAction.action_input_validation_promise, {\n        domain: meta.domain,\n        actionId: meta.actionId,\n      });\n    }\n\n    if (result.issues != null) {\n      throw err_nice_action.fromId(EErrId_NiceAction.action_input_validation_failed, {\n        domain: meta.domain,\n        actionId: meta.actionId,\n        validationMessage: extractMessageFromStandardSchema(result),\n      });\n    }\n\n    return result.value as INPUT[0];\n  }\n\n  validateOutput(value: unknown, meta: { domain: string; actionId: string }): OUTPUT[0] {\n    if (this.outputOptions?.schema == null) {\n      return value as OUTPUT[0];\n    }\n    const result = this.outputOptions.schema[\"~standard\"].validate(value);\n\n    if (result instanceof Promise) {\n      throw err_nice_action.fromId(EErrId_NiceAction.action_output_validation_promise, {\n        domain: meta.domain,\n        actionId: meta.actionId,\n      });\n    }\n\n    if (result.issues != null) {\n      throw err_nice_action.fromId(EErrId_NiceAction.action_output_validation_failed, {\n        domain: meta.domain,\n        actionId: meta.actionId,\n        validationMessage: extractMessageFromStandardSchema(result),\n      });\n    }\n\n    return result.value as OUTPUT[0];\n  }\n\n  /**\n   * Serialize raw output to a JSON-serializable form.\n   */\n  serializeOutput(rawOutput: OUTPUT[0]): OUTPUT[1] {\n    if (this.outputOptions?.serialization) {\n      return this.outputOptions.serialization.serialize(rawOutput);\n    }\n    return rawOutput as OUTPUT[1];\n  }\n\n  /**\n   * Deserialize a JSON value back into the raw output type.\n   */\n  deserializeOutput(serialized: OUTPUT[1]): OUTPUT[0] {\n    if (this.outputOptions?.serialization) {\n      return this.outputOptions.serialization.deserialize(serialized);\n    }\n    return serialized as OUTPUT[0];\n  }\n}\n\n// ---------------------------------------------------------------------------\n// TInferActionError — lives here (not in .types) to avoid circular imports\n// ---------------------------------------------------------------------------\n\n/**\n * The union of `NiceError`s an action **declares** via `.throws()` — i.e. its\n * \"expected\" errors. An action with no `.throws()` declares none (`never`). The\n * generic / unhandled failures an action can also produce are intentionally *not*\n * here; they surface through the `expected: false` branch of the result outcome.\n */\nexport type TInferActionError<SCH> =\n  SCH extends ActionSchema<any, any, infer DECLS>\n    ? DECLS extends readonly IActionErrorDeclaration[]\n      ? TInferDeclaredErrors<DECLS>\n      : never\n    : never;\n\n/**\n * The error type for the **throw / catch** surface (`runToOutput`, react-query) —\n * the action's declared errors *plus* the generic `err_cast_not_nice` fallback,\n * since a thrown error may be one we never accounted for. (On the non-throwing\n * `runToResult` path you instead get the typed `expected` discriminant.)\n */\nexport type TActionThrownError<SCH> =\n  | TInferActionError<SCH>\n  | InferNiceError<typeof err_cast_not_nice>;\n\nexport const actionSchema = (): ActionSchema => {\n  return new ActionSchema();\n};\n","/** Capture a diagnostic caller stack. Callers must apply the opt-in policy before invoking this. */\nexport function captureDiagnosticCallSite(): string | undefined {\n  return new Error().stack;\n}\n","const e=globalThis.process?.env||Object.create(null),t=globalThis.process||{env:e},n=t!==void 0&&t.env&&t.env.NODE_ENV||void 0,r=[[`claude`,[`CLAUDECODE`,`CLAUDE_CODE`]],[`replit`,[`REPL_ID`]],[`gemini`,[`GEMINI_CLI`]],[`codex`,[`CODEX_SANDBOX`,`CODEX_THREAD_ID`]],[`opencode`,[`OPENCODE`]],[`pi`,[i(`PATH`,/\\.pi[\\\\/]agent/)]],[`auggie`,[`AUGMENT_AGENT`]],[`goose`,[`GOOSE_PROVIDER`]],[`devin`,[i(`EDITOR`,/devin/)]],[`cursor`,[`CURSOR_AGENT`]],[`kiro`,[i(`TERM_PROGRAM`,/kiro/)]]];function i(t,n){return()=>{let r=e[t];return r?n.test(r):!1}}function a(){let t=e.AI_AGENT;if(t)return{name:t.toLowerCase()};for(let[t,n]of r)for(let r of n)if(typeof r==`string`?e[r]:r())return{name:t};return{}}const o=a(),s=o.name,c=!!o.name,l=[[`APPVEYOR`],[`AWS_AMPLIFY`,`AWS_APP_ID`,{ci:!0}],[`AZURE_PIPELINES`,`SYSTEM_TEAMFOUNDATIONCOLLECTIONURI`],[`AZURE_STATIC`,`INPUT_AZURE_STATIC_WEB_APPS_API_TOKEN`],[`APPCIRCLE`,`AC_APPCIRCLE`],[`BAMBOO`,`bamboo_planKey`],[`BITBUCKET`,`BITBUCKET_COMMIT`],[`BITRISE`,`BITRISE_IO`],[`BUDDY`,`BUDDY_WORKSPACE_ID`],[`BUILDKITE`],[`CIRCLE`,`CIRCLECI`],[`CIRRUS`,`CIRRUS_CI`],[`CLOUDFLARE_PAGES`,`CF_PAGES`,{ci:!0}],[`CLOUDFLARE_WORKERS`,`WORKERS_CI`,{ci:!0}],[`GOOGLE_CLOUDRUN`,`K_SERVICE`],[`GOOGLE_CLOUDRUN_JOB`,`CLOUD_RUN_JOB`],[`CODEBUILD`,`CODEBUILD_BUILD_ARN`],[`CODEFRESH`,`CF_BUILD_ID`],[`DRONE`],[`DRONE`,`DRONE_BUILD_EVENT`],[`DSARI`],[`GITHUB_ACTIONS`],[`GITLAB`,`GITLAB_CI`],[`GITLAB`,`CI_MERGE_REQUEST_ID`],[`GOCD`,`GO_PIPELINE_LABEL`],[`LAYERCI`],[`JENKINS`,`JENKINS_URL`],[`HUDSON`,`HUDSON_URL`],[`MAGNUM`],[`NETLIFY`],[`NETLIFY`,`NETLIFY_LOCAL`,{ci:!1}],[`NEVERCODE`],[`RENDER`],[`SAIL`,`SAILCI`],[`SEMAPHORE`],[`SCREWDRIVER`],[`SHIPPABLE`],[`SOLANO`,`TDDIUM`],[`STRIDER`],[`TEAMCITY`,`TEAMCITY_VERSION`],[`TRAVIS`],[`VERCEL`,`NOW_BUILDER`],[`VERCEL`,`VERCEL`,{ci:!1}],[`VERCEL`,`VERCEL_ENV`,{ci:!1}],[`APPCENTER`,`APPCENTER_BUILD_ID`],[`CODESANDBOX`,`CODESANDBOX_SSE`,{ci:!1}],[`CODESANDBOX`,`CODESANDBOX_HOST`,{ci:!1}],[`STACKBLITZ`],[`STORMKIT`],[`CLEAVR`],[`ZEABUR`],[`CODESPHERE`,`CODESPHERE_APP_ID`,{ci:!0}],[`RAILWAY`,`RAILWAY_PROJECT_ID`],[`RAILWAY`,`RAILWAY_SERVICE_ID`],[`DENO-DEPLOY`,`DENO_DEPLOY`],[`DENO-DEPLOY`,`DENO_DEPLOYMENT_ID`],[`FIREBASE_APP_HOSTING`,`FIREBASE_APP_HOSTING`,{ci:!0}],[`EDGEONE_PAGES`,`EO_PAGES_CI`,{ci:!0}]];function u(){for(let t of l)if(e[t[1]||t[0]])return{name:t[0].toLowerCase(),...t[2]};return e.SHELL===`/bin/jsh`&&t.versions?.webcontainer?{name:`stackblitz`,ci:!1}:{name:``,ci:!1}}const d=u(),f=d.name,p=t.platform||``,m=!!e.CI||d.ci!==!1,h=!!t.stdout?.isTTY,g=typeof window<`u`,_=!!e.DEBUG,v=n===`test`||!!e.TEST,y=n===`production`||e.MODE===`production`,b=n===`dev`||n===`development`||e.MODE===`development`,x=!!e.MINIMAL||m||v||!h,S=/^win/i.test(p),C=/^linux/i.test(p),w=/^darwin/i.test(p),T=!e.NO_COLOR&&(!!e.FORCE_COLOR||(h||S)&&e.TERM!==`dumb`||m),E=(t.versions?.node||``).replace(/^v/,``)||null,D=Number(E?.split(`.`)[0])||null,O=!!t?.versions?.node,k=`Bun`in globalThis,A=`Deno`in globalThis,j=`fastly`in globalThis,M=`Netlify`in globalThis,N=`EdgeRuntime`in globalThis,P=globalThis.navigator?.userAgent===`Cloudflare-Workers`,F=[[M,`netlify`],[N,`edge-light`],[P,`workerd`],[j,`fastly`],[A,`deno`],[k,`bun`],[O,`node`]];function I(){let e=F.find(e=>e[0]);if(e)return{name:e[1]}}const L=I(),R=L?.name||``;export{s as agent,o as agentInfo,a as detectAgent,u as detectProvider,e as env,h as hasTTY,g as hasWindow,c as isAgent,k as isBun,m as isCI,T as isColorSupported,_ as isDebug,A as isDeno,b as isDevelopment,N as isEdgeLight,j as isFastly,C as isLinux,w as isMacOS,x as isMinimal,M as isNetlify,O as isNode,y as isProduction,v as isTest,S as isWindows,P as isWorkerd,n as nodeENV,D as nodeMajorVersion,E as nodeVersion,p as platform,t as process,f as provider,d as providerInfo,R as runtime,L as runtimeInfo};","import { runtime } from \"std-env\";\nimport type { IRuntimeMeta } from \"../ActionRuntime/ActionRuntime.types\";\n\nexport const getAssumedRuntimeInfo = (): IRuntimeMeta => {\n  return {\n    assumed: true,\n    runtimeName: runtime,\n  };\n};\n","import { EActionForm } from \"../ActionDefinition/Action/ActionBase.types\";\nimport type { IActionPayload_Progress_JsonObject } from \"../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport { EActionPayloadType } from \"../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport { isAction_Base_JsonObject } from \"./isAction_Base_JsonObject\";\n\nexport const isActionPayload_Progress_JsonObject = (\n  obj: unknown,\n): obj is IActionPayload_Progress_JsonObject => {\n  return (\n    isAction_Base_JsonObject(obj) &&\n    \"progress\" in (obj as any) &&\n    (obj as any).form === EActionForm.data &&\n    (obj as any).type === EActionPayloadType.progress\n  );\n};\n","import { EActionForm } from \"../ActionDefinition/Action/ActionBase.types\";\nimport type { IActionPayload_Request_JsonObject } from \"../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport { EActionPayloadType } from \"../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport { isAction_Base_JsonObject } from \"./isAction_Base_JsonObject\";\n\nexport const isActionPayload_Request_JsonObject = (\n  obj: unknown,\n): obj is IActionPayload_Request_JsonObject => {\n  // `input` is deliberately NOT required: a no-input action's bare `request()`\n  // serializes with no input field (JSON drops `undefined`), and requiring the key made the\n  // plain-JSON path silently ignore the whole request. The `type`/`form` discriminants identify\n  // a request on their own; a genuinely missing-but-required input now reaches the schema\n  // validation downstream and rejects loudly as a typed error instead of vanishing.\n  return (\n    isAction_Base_JsonObject(obj) &&\n    (obj as any).form === EActionForm.data &&\n    (obj as any).type === EActionPayloadType.request\n  );\n};\n","import type { TActionPayload_Any_JsonObject } from \"../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport { isActionPayload_Progress_JsonObject } from \"./isActionPayload_Progress_JsonObject\";\nimport { isActionPayload_Request_JsonObject } from \"./isActionPayload_Request_JsonObject\";\nimport { isActionPayload_Result_JsonObject } from \"./isActionPayload_Result_JsonObject\";\n\nexport function isActionPayload_Any_JsonObject(obj: unknown): obj is TActionPayload_Any_JsonObject {\n  return (\n    isActionPayload_Request_JsonObject(obj) ||\n    isActionPayload_Result_JsonObject(obj) ||\n    isActionPayload_Progress_JsonObject(obj)\n  );\n}\n","// Module-level stack tracking which local handler is currently in its synchronous execution phase.\n// Child actions dispatched synchronously from inside a handler capture the top of this stack\n// as their parentCuid. The stack is push/popped around each handler's synchronous phase only.\nconst _stack: string[] = [];\n\nexport function pushHandlerCuid(cuid: string): void {\n  _stack.push(cuid);\n}\n\nexport function popHandlerCuid(): void {\n  _stack.pop();\n}\n\nexport function peekHandlerCuid(): string | undefined {\n  return _stack[_stack.length - 1];\n}\n","import { err_nice_action } from \"../../../../errors/err_nice_action\";\n\nexport const err_nice_external_client = err_nice_action.createChildDomain({\n  domain: \"err_nice_external_client\",\n  schema: {},\n});\n","import { err } from \"@nice-code/error\";\nimport type { EWireConnectFailureKind } from \"@nice-code/wire\";\nimport { err_nice_external_client } from \"../Handler/PeerLink/Connector/err_nice_external_client\";\nimport type { ETransportShape } from \"./Transport.types\";\n\nexport enum EErrId_NiceTransport {\n  timeout = \"timeout\",\n  not_found = \"not_found\",\n  unsupported = \"unsupported\",\n  initialization_failed = \"initialization_failed\",\n  send_failed = \"send_failed\",\n  invalid_action_response = \"invalid_action_response\",\n  reliable_outbox_overflow = \"reliable_outbox_overflow\",\n  reliable_delivery_abandoned = \"reliable_delivery_abandoned\",\n  reliable_stream_closed = \"reliable_stream_closed\",\n}\n\nexport const err_nice_transport = err_nice_external_client.createChildDomain({\n  domain: \"err_nice_transport\",\n  schema: {\n    [EErrId_NiceTransport.timeout]: err<{ timeout: number }>({\n      message: ({ timeout }) => `ActionConnect transport timed out after ${timeout}ms.`,\n    }),\n    [EErrId_NiceTransport.not_found]: err<{\n      actionId: string;\n    }>({\n      message: ({ actionId }) => `No connected transport found for action \"${actionId}\".`,\n    }),\n    [EErrId_NiceTransport.unsupported]: err<{ transportShapes: ETransportShape[] }>({\n      message: ({ transportShapes }) =>\n        `${transportShapes.length} Transport(s) [${transportShapes.join(\", \")}] found but returned \"unsupported\" status.`,\n    }),\n    [EErrId_NiceTransport.initialization_failed]: err<{\n      actionId: string;\n      /** The most relevant underlying failure (e.g. a rejected handshake) — surfaced in the message. */\n      cause?: string;\n      /**\n       * The endpoint the failing transport actually dialed (meteor-connect-bridge feedback W2).\n       * One line that makes the error self-locating instead of \"some transport, somewhere\".\n       */\n      endpoint?: string;\n      /**\n       * Answered-wrongly vs unreachable vs rejected, typed (feedback W3) — branch on this rather\n       * than matching the message, which is exactly the brittleness consumers had to write:\n       *\n       * ```ts\n       * if (\n       *   err_nice_transport.isExact(e) &&\n       *   e.hasId(\"initialization_failed\") &&\n       *   e.getContext(\"initialization_failed\").kind ===\n       *     EWireConnectFailureKind.endpoint_unreachable\n       * ) { ... }\n       * ```\n       */\n      kind?: EWireConnectFailureKind;\n    }>({\n      message: ({ actionId, cause, endpoint }) => {\n        const head = `Could not connect any transport for action \"${actionId}\"${\n          endpoint != null ? ` against ${endpoint}` : \"\"\n        }`;\n        if (cause == null) return `${head} (all transports failed to initialize).`;\n        // A typed cause already ends in a full stop; appending ours would read as \"…\"..\"\n        return `${head}: ${cause}${cause.endsWith(\".\") ? \"\" : \".\"}`;\n      },\n    }),\n    [EErrId_NiceTransport.send_failed]: err<{\n      actionState: string;\n      actionId: string;\n      httpStatusCode?: number;\n      message?: string;\n    }>({\n      message: ({ actionId, httpStatusCode, message }) =>\n        `Failed to send action \"${actionId}\" [${httpStatusCode ?? \"Unknown status\"}]: ${message ?? \"Unknown error\"}.`,\n      httpStatusCode: ({ httpStatusCode }) => httpStatusCode ?? 500,\n    }),\n    [EErrId_NiceTransport.invalid_action_response]: err<{\n      actionId: string;\n    }>({\n      message: ({ actionId }) => `Invalid action response JSON structure for action \"${actionId}\"`,\n    }),\n    [EErrId_NiceTransport.reliable_outbox_overflow]: err<{\n      actionId: string;\n      streamId: string;\n      maxUnacked: number;\n    }>({\n      message: ({ actionId, maxUnacked }) =>\n        `Reliable outbox for action \"${actionId}\" exceeded its unacked window (${maxUnacked}) — the peer is not acknowledging. Send rejected to bound memory.`,\n    }),\n    [EErrId_NiceTransport.reliable_delivery_abandoned]: err<{\n      actionId: string;\n      streamId: string;\n      timeout: number;\n    }>({\n      message: ({ actionId, timeout }) =>\n        `Reliable action \"${actionId}\" was abandoned: not acknowledged within its ${timeout}ms delivery deadline (or swept with an aborted earlier frame on its stream). The stream skips past it and continues.`,\n    }),\n    [EErrId_NiceTransport.reliable_stream_closed]: err<{\n      actionId: string;\n      streamId: string;\n    }>({\n      message: ({ actionId, streamId }) =>\n        `Reliable action \"${actionId}\" was abandoned because its stream (\"${streamId}\") was closed (closeReliableStream) while the send was still unacknowledged.`,\n    }),\n  },\n});\n","import { ConnectionTransportManager as WireConnectionTransportManager } from \"@nice-code/wire\";\nimport { EErrId_NiceTransport, err_nice_transport } from \"./err_nice_transport\";\nimport type {\n  IActionTransportReadyData_Methods,\n  TTransportCache,\n  TTransportRouteParams,\n} from \"./Transport.types\";\nimport type { TransportConnection } from \"./TransportConnection\";\n\n/**\n * Preference-ordered transport selection for action dispatch — wire's generic\n * `ConnectionTransportManager` pinned to the action routing\n * params + methods, with the selection failures expressed in action's own `err_nice_transport`\n * vocabulary (the exact errors thrown before the move). An actionless dial\n * (`ChannelConnector.connect()`, the connection contract) reports as `\"connect()\"` in the failure messages.\n */\nexport class ConnectionTransportManager extends WireConnectionTransportManager<\n  TTransportRouteParams,\n  IActionTransportReadyData_Methods,\n  TransportConnection\n> {\n  constructor(cache: TTransportCache) {\n    super(cache, {\n      unsupported: (transportShapes) =>\n        err_nice_transport.fromId(EErrId_NiceTransport.unsupported, { transportShapes }),\n      notFound: (input) =>\n        err_nice_transport.fromId(EErrId_NiceTransport.not_found, {\n          actionId: input.action == null ? \"connect()\" : input.action.id,\n        }),\n      initializationFailed: (input, failure) =>\n        err_nice_transport\n          .fromId(EErrId_NiceTransport.initialization_failed, {\n            actionId: input.action == null ? \"connect()\" : input.action.id,\n            cause: failure.cause,\n            endpoint: failure.endpoint,\n            kind: failure.kind,\n          })\n          .withOriginError(failure.origin),\n    });\n  }\n}\n","import type {\n  TAction_Any_JsonObject,\n  TNarrowActionJsonTypeToActionInstanceType,\n} from \"../ActionDefinition/Action/Action.combined.types\";\nimport type { INiceActionIdAndDomain } from \"../ActionDefinition/Action/ActionBase.types\";\nimport type { ActionDomain } from \"../ActionDefinition/Domain/ActionDomain\";\nimport type { IActionDomain } from \"../ActionDefinition/Domain/ActionDomain.types\";\nimport { EErrId_NiceAction, err_nice_action } from \"../errors/err_nice_action\";\n\nexport class ActionDomainManager {\n  private _domains: Map<string, ActionDomain<any>> = new Map();\n\n  assertCanAddDomain(domain: ActionDomain<any>): void {\n    const existing = this._domains.get(domain.domain);\n    // Re-registering the SAME instance is routine (router overloads, merges) and stays silent.\n    // A different instance under the same wire name would silently shadow the earlier one —\n    // routing keys are name-only — so it fails here, at setup, instead of misrouting in production.\n    if (existing === domain || existing == null) return;\n    if (existing != null) {\n      throw err_nice_action.fromId(EErrId_NiceAction.domain_name_collision, {\n        domain: domain.domain,\n        existingParentDomains: existing.allDomains,\n        incomingParentDomains: domain.allDomains,\n      });\n    }\n  }\n\n  addDomain(domain: ActionDomain<any>): void {\n    this.assertCanAddDomain(domain);\n    this._domains.set(domain.domain, domain);\n  }\n\n  removeDomain(domain: ActionDomain<any>): void {\n    if (this._domains.get(domain.domain) === domain) this._domains.delete(domain.domain);\n  }\n\n  getDomains(): ActionDomain<any>[] {\n    return [...this._domains.values()];\n  }\n\n  verifyIsActionJson(action: INiceActionIdAndDomain<any>): void {\n    if (typeof action.domain !== \"string\" || typeof action.id !== \"string\") {\n      throw err_nice_action.fromId(EErrId_NiceAction.wire_not_action_data);\n    }\n  }\n\n  getActionDomain<DOM extends IActionDomain, ACT extends INiceActionIdAndDomain<DOM>>(\n    action: ACT,\n  ): ActionDomain<DOM> | undefined {\n    this.verifyIsActionJson(action);\n    const domain = this._domains.get(action.domain) as ActionDomain<DOM>;\n\n    if (!domain) {\n      return undefined;\n    }\n\n    return domain;\n  }\n\n  getActionDomainOrThrow<DOM extends IActionDomain, ACT extends INiceActionIdAndDomain<DOM>>(\n    action: ACT,\n  ): ActionDomain<DOM> {\n    this.verifyIsActionJson(action);\n    const domain = this._domains.get(action.domain) as ActionDomain<DOM>;\n\n    if (!domain) {\n      throw err_nice_action.fromId(EErrId_NiceAction.domain_no_handler, {\n        domain: action.domain,\n      });\n    }\n\n    return domain;\n  }\n\n  hydrateActionPayload<\n    D extends IActionDomain,\n    ID extends keyof D[\"actionSchema\"] & string,\n    A extends TAction_Any_JsonObject<D, ID>,\n  >(actionJson: A): TNarrowActionJsonTypeToActionInstanceType<D, A, ID> {\n    const domain = this.getActionDomainOrThrow(actionJson) as ActionDomain<D>;\n    return domain.hydrateAnyAction(actionJson);\n  }\n}\n","import type { INiceActionIdAndDomain } from \"../../ActionDefinition/Action/ActionBase.types\";\nimport type { ActionCore } from \"../../ActionDefinition/Action/Core/ActionCore\";\nimport type { ActionDomain } from \"../../ActionDefinition/Domain/ActionDomain\";\nimport type { IActionDomain } from \"../../ActionDefinition/Domain/ActionDomain.types\";\nimport { EErrId_NiceAction, err_nice_action } from \"../../errors/err_nice_action\";\nimport { ActionDomainManager } from \"../ActionDomainManager\";\nimport type { IHandleActionOptions } from \"../Handler/ActionHandler.types\";\nimport {\n  EActionRouterContextType,\n  type IActionRouterContext,\n  type TMatchHandlerKey,\n} from \"./ActionRouter.types\";\n\nexport class ActionRouter<DATA> {\n  readonly domainManager = new ActionDomainManager();\n  private actionRouteData = new Map<TMatchHandlerKey, DATA[]>();\n  private _context: IActionRouterContext;\n\n  constructor(context: IActionRouterContext) {\n    this._context = context;\n  }\n\n  // ---------------------------------------------------------------------------\n  // Merge / copy\n  // ---------------------------------------------------------------------------\n\n  /** Copy all routes from another router into this one, replacing any overlapping keys. */\n  mergeRouter(actionRouter: ActionRouter<DATA>): void {\n    for (const domain of actionRouter.getDomains()) {\n      this.domainManager.addDomain(domain);\n    }\n    for (const [matchKey, routeDataEntries] of actionRouter.actionRouteData.entries()) {\n      this.actionRouteData.set(matchKey, [...routeDataEntries]);\n    }\n  }\n\n  addDomainsFromOther(actionRouter: ActionRouter<DATA>): void {\n    for (const domain of actionRouter.getDomains()) {\n      this.domainManager.assertCanAddDomain(domain);\n    }\n    for (const domain of actionRouter.getDomains()) {\n      this.domainManager.addDomain(domain);\n    }\n  }\n\n  // ---------------------------------------------------------------------------\n  // Lookup\n  // ---------------------------------------------------------------------------\n\n  /** All FNs registered for an action, ID-specific entries first then domain wildcard. */\n  getRouteDataEntriesForAction(action: { domain: string; id: string }): DATA[] {\n    const idKey: TMatchHandlerKey = `dom[${action.domain}]id[${action.id}]`;\n    const domKey: TMatchHandlerKey = `dom[${action.domain}]id[_]`;\n    return [\n      ...(this.actionRouteData.get(idKey) ?? []),\n      ...(this.actionRouteData.get(domKey) ?? []),\n    ];\n  }\n\n  /** First FN registered for an action (ID-specific beats domain wildcard). */\n  getRouteDataForAction(action: INiceActionIdAndDomain): DATA | undefined {\n    return this.getRouteDataEntriesForAction(action)[0];\n  }\n\n  private throwNoHandlerForAction(\n    action: INiceActionIdAndDomain,\n    context: IHandleActionOptions,\n  ): never {\n    if (this._context.contextType === EActionRouterContextType.handler_route) {\n      throw err_nice_action.fromId(EErrId_NiceAction.no_action_execution_handler, {\n        domain: action.domain,\n        actionId: action.id,\n        specifiedClient: context.targetLocalRuntime?.coordinate,\n      });\n    }\n\n    if (this._context.contextType === EActionRouterContextType.runtime_to_handler) {\n      throw err_nice_action.fromId(EErrId_NiceAction.no_action_execution_handler, {\n        domain: action.domain,\n        actionId: action.id,\n        specifiedClient: this._context.runtime.coordinate,\n      });\n    }\n    throw err_nice_action.fromId(EErrId_NiceAction.no_action_execution_handler, {\n      domain: action.domain,\n      actionId: action.id,\n    });\n  }\n\n  getRouteDataEntriesForActionOrThrow(\n    action: INiceActionIdAndDomain,\n    context: IHandleActionOptions,\n  ): DATA[] {\n    const entries = this.getRouteDataEntriesForAction(action);\n\n    if (entries.length === 0) {\n      this.throwNoHandlerForAction(action, context);\n    }\n\n    return entries;\n  }\n\n  getRouteDataForActionOrThrow(\n    action: INiceActionIdAndDomain,\n    context: IHandleActionOptions,\n  ): DATA {\n    const routeData = this.getRouteDataForAction(action);\n\n    if (!routeData) {\n      this.throwNoHandlerForAction(action, context);\n    }\n\n    return routeData;\n  }\n\n  /** All FNs stored under an exact match key. */\n  getForKey(key: TMatchHandlerKey): readonly DATA[] {\n    return this.actionRouteData.get(key) ?? [];\n  }\n\n  /** Every match key that has at least one registered FN. */\n  getRegisteredKeys(): TMatchHandlerKey[] {\n    return [...this.actionRouteData.keys()];\n  }\n\n  getDomains(): ActionDomain[] {\n    return this.domainManager.getDomains();\n  }\n\n  // ---------------------------------------------------------------------------\n  // Registration — for* (replace) and add* (accumulate)\n  // ---------------------------------------------------------------------------\n\n  /** Register a handler for all actions in a domain, replacing any existing one. */\n  forDomain<FOR_DOM extends IActionDomain>(domain: ActionDomain<FOR_DOM>, routeData: DATA): this {\n    this.domainManager.addDomain(domain);\n    this.actionRouteData.set(`dom[${domain.domain}]id[_]`, [routeData]);\n    return this;\n  }\n\n  forAction<ACT_DOM extends IActionDomain, ID extends keyof ACT_DOM[\"actionSchema\"] & string>(\n    action: ActionCore<ACT_DOM, ID>,\n    routeData: DATA,\n  ): this {\n    return this.forActionId(action._domain, action.id, routeData);\n  }\n\n  /** Register a handler for a specific action, replacing any existing one. */\n  forActionId<ACT_DOM extends IActionDomain, ID extends keyof ACT_DOM[\"actionSchema\"] & string>(\n    domain: ActionDomain<ACT_DOM>,\n    id: ID,\n    routeData: DATA,\n  ): this {\n    this.domainManager.addDomain(domain);\n    this.actionRouteData.set(`dom[${domain.domain}]id[${id}]`, [routeData]);\n    return this;\n  }\n\n  /** Register one handler for several action IDs, replacing any existing ones. */\n  forActionIds<\n    ACT_DOM extends IActionDomain,\n    IDS extends ReadonlyArray<keyof ACT_DOM[\"actionSchema\"] & string>,\n  >(domain: ActionDomain<ACT_DOM>, ids: IDS, routeData: DATA): this {\n    this.domainManager.addDomain(domain);\n    for (const id of ids) {\n      this.forActionId(domain, id, routeData);\n    }\n    return this;\n  }\n\n  /** Register per-action handlers from a cases map, replacing any existing ones. */\n  forDomainActionCases<FOR_DOM extends IActionDomain>(\n    domain: ActionDomain<FOR_DOM>,\n    cases: { [ID in keyof FOR_DOM[\"actionSchema\"] & string]?: DATA },\n  ): this {\n    this.domainManager.addDomain(domain);\n    for (const id of Object.keys(cases) as Array<keyof FOR_DOM[\"actionSchema\"] & string>) {\n      const routeData = cases[id];\n      if (routeData != null) {\n        this.actionRouteData.set(`dom[${domain.domain}]id[${id}]`, [routeData]);\n      }\n    }\n    return this;\n  }\n\n  /** Append a handler for all actions in a domain (accumulates alongside existing). */\n  addForDomain<FOR_DOM extends IActionDomain>(\n    domain: ActionDomain<FOR_DOM>,\n    routeData: DATA,\n  ): this {\n    this.domainManager.addDomain(domain);\n    this._push(`dom[${domain.domain}]id[_]`, routeData);\n    return this;\n  }\n\n  /** Append a handler for a specific action (accumulates alongside existing). */\n  addForAction<ACT_DOM extends IActionDomain, ID extends keyof ACT_DOM[\"actionSchema\"] & string>(\n    domain: ActionDomain<ACT_DOM>,\n    id: ID,\n    routeData: DATA,\n  ): this {\n    this.domainManager.addDomain(domain);\n    this._push(`dom[${domain.domain}]id[${id}]`, routeData);\n    return this;\n  }\n\n  /** Append one handler for several action IDs (accumulates alongside existing). */\n  addForActionIds<\n    ACT_DOM extends IActionDomain,\n    IDS extends ReadonlyArray<keyof ACT_DOM[\"actionSchema\"] & string>,\n  >(domain: ActionDomain<ACT_DOM>, ids: IDS, routeData: DATA): this {\n    this.domainManager.addDomain(domain);\n    for (const id of ids) {\n      this.addForAction(domain, id, routeData);\n    }\n    return this;\n  }\n\n  /** Append per-action handlers from a cases map (accumulates alongside existing). */\n  addForDomainActionCases<FOR_DOM extends IActionDomain>(\n    domain: ActionDomain<FOR_DOM>,\n    cases: { [ID in keyof FOR_DOM[\"actionSchema\"] & string]?: DATA },\n  ): this {\n    this.domainManager.addDomain(domain);\n    for (const id of Object.keys(cases) as Array<keyof FOR_DOM[\"actionSchema\"] & string>) {\n      const routeData = cases[id];\n      if (routeData != null) {\n        this._push(`dom[${domain.domain}]id[${id}]`, routeData);\n      }\n    }\n    return this;\n  }\n\n  /** Append a handler directly by its raw match key (used when the key is known ahead of time). */\n  addForKey(key: TMatchHandlerKey, routeData: DATA): this {\n    this._push(key, routeData);\n    return this;\n  }\n\n  /** Remove one route-data object from every key; used by scoped installation teardown. */\n  removeRouteData(routeData: DATA): void {\n    for (const [key, entries] of this.actionRouteData) {\n      const remaining = entries.filter((entry) => entry !== routeData);\n      if (remaining.length === 0) this.actionRouteData.delete(key);\n      else if (remaining.length !== entries.length) this.actionRouteData.set(key, remaining);\n    }\n    const registeredKeys = [...this.actionRouteData.keys()];\n    for (const domain of this.domainManager.getDomains()) {\n      const prefix = `dom[${domain.domain}]id[`;\n      if (!registeredKeys.some((key) => key.startsWith(prefix))) {\n        this.domainManager.removeDomain(domain);\n      }\n    }\n  }\n\n  private _push(key: TMatchHandlerKey, routeData: DATA): void {\n    const existing = this.actionRouteData.get(key);\n    if (existing != null) {\n      existing.push(routeData);\n    } else {\n      this.actionRouteData.set(key, [routeData]);\n    }\n  }\n}\n","import { nanoid } from \"nanoid\";\nimport type { IActionRouteItemHandler } from \"../../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport type { ActionPayload_Request } from \"../../ActionDefinition/Action/Payload/ActionPayload_Request\";\nimport type { RunningAction } from \"../../ActionDefinition/Action/RunningAction\";\nimport type { IActionDomain } from \"../../ActionDefinition/Domain/ActionDomain.types\";\nimport { ActionRouter } from \"../Routing/ActionRouter\";\nimport type {\n  EActionHandlerType,\n  IActionHandler_Base,\n  IHandleActionOptions,\n  TActionHandler_Json,\n} from \"./ActionHandler.types\";\n\nexport abstract class ActionHandler<T extends EActionHandlerType>\n  implements IActionHandler_Base<T>\n{\n  abstract readonly handlerType: T;\n  private _cuid?: string;\n  abstract readonly actionRouter: ActionRouter<any>;\n\n  get cuid(): string {\n    this._cuid ??= nanoid();\n    return this._cuid;\n  }\n\n  getActionRouter() {\n    return this.actionRouter;\n  }\n\n  abstract handleActionRequest<\n    DOM extends IActionDomain,\n    ID extends keyof DOM[\"actionSchema\"] & string,\n  >(\n    action: ActionPayload_Request<DOM, ID>,\n    config?: IHandleActionOptions,\n  ): Promise<RunningAction<DOM, ID>>;\n\n  abstract toJsonObject(): TActionHandler_Json;\n\n  abstract toHandlerRouteItem(...args: any[]): IActionRouteItemHandler;\n}\n","import type { RuntimeCoordinate } from \"@nice-code/wire\";\nimport type { IActionReceiverMetadata } from \"../../../ActionDefinition/Action/Context/ActionContext.types\";\nimport type { ActionCore } from \"../../../ActionDefinition/Action/Core/ActionCore\";\nimport type {\n  TActionPayload_Any_Instance,\n  TActionPayload_Any_JsonObject,\n} from \"../../../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport type { ActionDomain } from \"../../../ActionDefinition/Domain/ActionDomain\";\nimport type { IActionDomain } from \"../../../ActionDefinition/Domain/ActionDomain.types\";\nimport { EErrId_NiceAction, err_nice_action } from \"../../../errors/err_nice_action\";\nimport type { ActionRuntime } from \"../../ActionRuntime\";\nimport { ActionRouter } from \"../../Routing/ActionRouter\";\nimport { EActionRouterContextType } from \"../../Routing/ActionRouter.types\";\nimport { ActionHandler } from \"../ActionHandler\";\nimport { EActionHandlerType, type IActionHandler_Peer } from \"../ActionHandler.types\";\n\n/**\n * Shared base for every handler that routes a domain set to/from *another runtime* (a \"peer\") — the\n * unified peer-link concept. Both specializations extend this as siblings, differing only in *who\n * establishes the connection*, which is a transport trait, not a routing one:\n *\n * - {@link ChannelConnector} — **dial-out**: this runtime opens connection(s) to one peer\n *   over a transport stack (with caching + fallback). The classic \"client → backend\" link.\n * - {@link ChannelAcceptor} — **accept-in**: connections are accepted from many peers and fed in\n *   via `receive()`; it keeps a per-connection registry and can push to any of them.\n *\n * To the runtime there is no \"client\" vs \"server\" — both are peer-link handlers (`handlerType =\n * external`) keyed to a peer coordinate, chosen by the return-path dispatch via {@link sendReturnPayload}.\n */\nexport abstract class PeerLink\n  extends ActionHandler<EActionHandlerType.peer>\n  implements IActionHandler_Peer\n{\n  /** The peer runtime this handler links to (an env-only coordinate for an accept-in handler). */\n  readonly peer: RuntimeCoordinate;\n  readonly handlerType = EActionHandlerType.peer;\n\n  /**\n   * Whether this link can deliver an *unsolicited* frame to the peer (a result/progress pushed back on\n   * the return path, or a `broadcast`). A duplex carrier (WebSocket/WebRTC/…) can; an exchange-only\n   * carrier (HTTP) cannot — its reply must ride the response to its own request. The runtime's\n   * return-path dispatch ({@link ActionRuntime.getReturnHandlerForOrigin}) skips handlers that can't\n   * push, so an exchange-only handler is never asked to deliver one.\n   */\n  abstract readonly canPush: boolean;\n\n  readonly actionRouter: ActionRouter<true> = new ActionRouter({\n    contextType: EActionRouterContextType.handler_route,\n    handler: this,\n  });\n\n  /** Listeners installed by the runtime (`resolveIncomingActionPayload`) for inbound peer frames. */\n  private _incomingRuntime: ActionRuntime | undefined;\n  private _incomingActionDataListener:\n    | ((json: TActionPayload_Any_JsonObject<any, any>, metadata?: IActionReceiverMetadata) => void)\n    | undefined;\n\n  constructor(peerCoordinate: RuntimeCoordinate) {\n    super();\n    this.peer = peerCoordinate;\n  }\n\n  /** @deprecated Use {@link peer}. */\n  get peerClient(): RuntimeCoordinate {\n    return this.peer;\n  }\n\n  // ---------------------------------------------------------------------------\n  // Routing — which domains/actions travel to this peer (shared by both specializations)\n  // ---------------------------------------------------------------------------\n\n  forDomain<FOR_DOM extends IActionDomain>(domain: ActionDomain<FOR_DOM>): this {\n    this.actionRouter.forDomain(domain, true);\n    return this;\n  }\n\n  forAction<ACT_DOM extends IActionDomain, ID extends keyof ACT_DOM[\"actionSchema\"] & string>(\n    action: ActionCore<ACT_DOM, ID>,\n  ): this {\n    this.actionRouter.forAction(action, true);\n    return this;\n  }\n\n  forActionIds<\n    ACT_DOM extends IActionDomain,\n    IDS extends ReadonlyArray<keyof ACT_DOM[\"actionSchema\"] & string>,\n  >(domain: ActionDomain<ACT_DOM>, ids: IDS): this {\n    this.actionRouter.forActionIds(domain, ids, true);\n    return this;\n  }\n\n  // ---------------------------------------------------------------------------\n  // Runtime binding — inbound peer frames\n  // ---------------------------------------------------------------------------\n\n  _setIncomingActionDataListener(\n    runtime: ActionRuntime,\n    listener: (\n      json: TActionPayload_Any_JsonObject<any, any>,\n      metadata?: IActionReceiverMetadata,\n    ) => void,\n  ): () => void {\n    if (this._incomingRuntime != null && this._incomingRuntime !== runtime) {\n      throw err_nice_action.fromId(EErrId_NiceAction.peer_handler_already_bound);\n    }\n    this._incomingRuntime = runtime;\n    this._incomingActionDataListener = listener;\n    return () => {\n      if (this._incomingRuntime !== runtime || this._incomingActionDataListener !== listener)\n        return;\n      this._incomingRuntime = undefined;\n      this._incomingActionDataListener = undefined;\n    };\n  }\n\n  /** Hand a decoded inbound frame to the runtime (called by each specialization's receive path). */\n  protected _emitIncoming(\n    json: TActionPayload_Any_JsonObject<any, any>,\n    metadata?: IActionReceiverMetadata,\n  ): void {\n    this._incomingActionDataListener?.(json, metadata);\n  }\n\n  /**\n   * Dispatch a result/progress payload back to the action's origin peer over this link. The runtime's\n   * return-path dispatch calls it on the link the request arrived on, or (with no arrival facts) on\n   * whichever peer-link handler best reaches `originClient`. `arrival` is the answered request's\n   * receiver metadata. Returns `true` if it was sent, `false` if no channel was available.\n   */\n  abstract sendReturnPayload(\n    payload: TActionPayload_Any_Instance<any, any>,\n    config: { targetLocalRuntime: ActionRuntime; arrival?: IActionReceiverMetadata },\n  ): Promise<boolean>;\n\n  /**\n   * Whether this handler currently holds a *live* connection bound to `origin`. The runtime's return-path\n   * dispatch ({@link ActionRuntime.getReturnHandlerForOrigin}) prefers a handler that owns the origin's\n   * connection over a mere coordinate match, so with several duplex acceptors a result/push routes back\n   * over the carrier the client connected on. Defaults to `false`; an acceptor overrides it from its\n   * connection registry.\n   */\n  ownsLiveConnectionFor(_origin: RuntimeCoordinate): boolean {\n    return false;\n  }\n\n  /** Release any long-lived connections this handler owns (a teardown). No-op by default. */\n  clearTransportCache(): void {}\n}\n","import { reliableStreamId } from \"@nice-code/wire\";\nimport type { IFrameReliability } from \"../../../Transport/Transport.types\";\n\nexport { reliableStreamId };\n\n/**\n * Client-side send bookkeeping for the `.reliable()` tier — the ordered, at-least-once outbox that lets a\n * reliable stream survive a dropped frame or a reconnect. It is **pure**: it assigns per-stream sequence\n * numbers, remembers unacked sends, prunes them on a cumulative ack, and hands back what to resend. The\n * actual dispatch (acquiring a transport, packing the frame) is the {@link ChannelConnector}'s job — this\n * component never touches the network, which keeps it exhaustively unit-testable.\n *\n * ## Stream identity (locked decision #1)\n * A reliable stream is keyed `(peerCoordinate + actionRoute)`. That id is *local* — it's reconstructed on\n * each side from the connection (peer) and the frame's route, so it never travels on the wire. Only the\n * per-frame `seq` (and the reply's cumulative `ack`) ride the envelope.\n *\n * ## Guarantee & contract\n * Ordered + dedup within a resumable session; at-least-once across a session reset (so handlers must be\n * idempotent). `seq` is 0-based and monotonic per stream. `ack` is the highest **contiguous** seq the\n * server has stored; the client prunes every unacked send `<= ack` and resends everything `> ack`.\n */\n\n/** One unacked send held until its `seq` is acknowledged (or dropped as undeliverable). */\nexport interface IOutboxEntry {\n  seq: number;\n  /** When the send was prepared (ms epoch) — drives the `oldestUnackedAgeMs` pressure stat. */\n  preparedAt: number;\n  reliability: IFrameReliability;\n  /** Re-dispatch this exact frame (same `seq`) over a freshly-ready transport. Idempotent server-side. */\n  dispatch: () => void;\n  /**\n   * Called when the entry is **dropped without delivery** by {@link ReliableOutbox.dropThrough} (its\n   * action aborted / its delivery deadline expired / an earlier frame's drop swept it). The connector\n   * uses it to abort the entry's still-pending action, so abandoning a stream's head fails the swept\n   * frames loudly instead of leaving them to time out one by one.\n   */\n  onDrop?: (reason: unknown) => void;\n  /** Called when the entry is pruned by an **ack** — the sender-side proof this frame was delivered. */\n  onAck?: () => void;\n}\n\n/** The per-send lifecycle hooks a caller may attach at {@link ReliableOutbox.prepare}. */\nexport interface IReliablePrepareHooks {\n  onDrop?: (reason: unknown) => void;\n  onAck?: () => void;\n}\n\ninterface IReliableStreamState {\n  /** Next seq to hand out. */\n  nextSeq: number;\n  /** Highest contiguous seq the peer has acknowledged; `-1` = nothing acked yet. */\n  ackedSeq: number;\n  /** seq → unacked entry, insertion-ordered (so resend is naturally in seq order). */\n  unacked: Map<number, IOutboxEntry>;\n}\n\nexport interface IReliableOutboxOptions {\n  /**\n   * Max unacked sends held per stream before the outbox refuses new ones. Guards against a permanently\n   * dead peer growing memory unbounded. Default 1024.\n   */\n  maxUnackedPerStream?: number;\n  /** Called once when a stream first overflows `maxUnackedPerStream`, with the offending stream id. */\n  onOverflow?: (streamId: string) => void;\n}\n\nconst DEFAULT_MAX_UNACKED = 1024;\n\n/** The seq/reliability a {@link ChannelConnector} stamps on a reliable frame, plus whether to proceed. */\nexport interface IReliablePrepared {\n  reliability: IFrameReliability;\n}\n\nexport class ReliableOutbox {\n  private readonly _streams = new Map<string, IReliableStreamState>();\n  private readonly _overflowed = new Set<string>();\n  private readonly _maxUnacked: number;\n  private readonly _onOverflow?: (streamId: string) => void;\n\n  constructor(options?: IReliableOutboxOptions) {\n    this._maxUnacked = options?.maxUnackedPerStream ?? DEFAULT_MAX_UNACKED;\n    this._onOverflow = options?.onOverflow;\n  }\n\n  /** The per-stream unacked cap (for surfacing in an overflow error). */\n  get maxUnackedPerStream(): number {\n    return this._maxUnacked;\n  }\n\n  private _stream(streamId: string): IReliableStreamState {\n    let state = this._streams.get(streamId);\n    if (state == null) {\n      state = { nextSeq: 0, ackedSeq: -1, unacked: new Map() };\n      this._streams.set(streamId, state);\n    }\n    return state;\n  }\n\n  /**\n   * Assign the next `seq` for a stream and remember the send until it's acked. Returns `null` when the\n   * stream is over its unacked window — the caller should fail the action with an overflow error rather\n   * than grow memory. `dispatch` is stored so the outbox can resend the exact frame on reconnect.\n   */\n  prepare(\n    streamId: string,\n    dispatch: () => void,\n    streamKey?: string,\n    hooks?: IReliablePrepareHooks,\n  ): IReliablePrepared | null {\n    const state = this._stream(streamId);\n    if (state.unacked.size >= this._maxUnacked) {\n      if (!this._overflowed.has(streamId)) {\n        this._overflowed.add(streamId);\n        this._onOverflow?.(streamId);\n      }\n      return null;\n    }\n\n    const seq = state.nextSeq++;\n    // `streamKey` (E3) rides the reliability object so the wire carries it and a re-sync (which mutates\n    // `seq` in place) preserves the key. Omitted when absent, keeping the default single-stream shape.\n    const reliability: IFrameReliability =\n      streamKey == null ? { streamId, seq } : { streamId, seq, streamKey };\n    state.unacked.set(seq, {\n      seq,\n      preparedAt: Date.now(),\n      reliability,\n      dispatch,\n      onDrop: hooks?.onDrop,\n      onAck: hooks?.onAck,\n    });\n    return { reliability };\n  }\n\n  /**\n   * Apply a cumulative ack for a stream: advance the high-water and drop every unacked send `<= ackSeq`.\n   * Returns the pruned entries (so the caller can settle per-send bookkeeping, e.g. clear delivery\n   * deadlines keyed by `entry.reliability`). A stale/duplicate ack (`<= ackedSeq`) is a no-op. Clears the\n   * overflow latch once the window drains.\n   */\n  ack(streamId: string, ackSeq: number): IOutboxEntry[] {\n    const state = this._streams.get(streamId);\n    if (state == null || ackSeq <= state.ackedSeq) return [];\n\n    state.ackedSeq = ackSeq;\n    const pruned: IOutboxEntry[] = [];\n    for (const entry of state.unacked.values()) {\n      if (entry.seq <= ackSeq) pruned.push(entry);\n    }\n    for (const entry of pruned) state.unacked.delete(entry.seq);\n\n    if (state.unacked.size < this._maxUnacked) this._overflowed.delete(streamId);\n    for (const entry of pruned) entry.onAck?.();\n    return pruned;\n  }\n\n  /**\n   * Abandon delivery of every still-unacked send `<= seq` on a stream — the undeliverable-frame escape\n   * hatch. Called when a reliable action **aborts** (deadline / explicit) while its frame is still\n   * unacked: the frame will never legitimately resend (the dispatch guard skips aborted actions), so\n   * leaving it would wedge the stream on a permanent seq gap. Dropping is **cumulative** (like an ack):\n   * every older unacked frame goes with it — they could no longer be delivered in order anyway — and each\n   * dropped entry's `onDrop` runs so its action fails loudly *now* rather than timing out serially.\n   *\n   * The caller then tells the receiver via an `rskip` control frame to advance past the abandoned seqs,\n   * so the stream **continues** (later frames deliver in order) instead of stalling. Advances `ackedSeq`\n   * (abandoned = settled) so a stale in-flight ack can't resurrect confusion, and clears the overflow\n   * latch as the window drains. Returns the dropped entries; empty when nothing `<= seq` was pending.\n   */\n  dropThrough(streamId: string, seq: number, reason: unknown): IOutboxEntry[] {\n    const state = this._streams.get(streamId);\n    if (state == null) return [];\n\n    const dropped: IOutboxEntry[] = [];\n    for (const entry of state.unacked.values()) {\n      if (entry.seq <= seq) dropped.push(entry);\n    }\n    for (const entry of dropped) state.unacked.delete(entry.seq);\n    if (seq > state.ackedSeq) state.ackedSeq = seq;\n    if (state.unacked.size < this._maxUnacked) this._overflowed.delete(streamId);\n\n    for (const entry of dropped) entry.onDrop?.(reason);\n    return dropped;\n  }\n\n  /** The unacked entries for one stream, in ascending seq order (Map preserves insertion = seq order). */\n  pending(streamId: string): IOutboxEntry[] {\n    return [...(this._streams.get(streamId)?.unacked.values() ?? [])];\n  }\n\n  /** Unacked count for one stream — the cheap read `pending().length` would allocate for. */\n  pendingCount(streamId: string): number {\n    return this._streams.get(streamId)?.unacked.size ?? 0;\n  }\n\n  /**\n   * `preparedAt` of the oldest unacked send on a stream (`undefined` when drained/unknown). Entries are\n   * insertion-ordered ascending by seq, so the first is the oldest — no scan.\n   */\n  oldestPreparedAt(streamId: string): number | undefined {\n    const state = this._streams.get(streamId);\n    if (state == null) return undefined;\n    for (const entry of state.unacked.values()) return entry.preparedAt;\n    return undefined;\n  }\n\n  /**\n   * The highest seq ever assigned on a stream (`nextSeq - 1`), or `undefined` for a stream this outbox\n   * has never prepared a send on. `closeReliableStream` abandons *through* this seq — covering every\n   * unacked send — without the caller holding any handle.\n   */\n  highestSeq(streamId: string): number | undefined {\n    const state = this._streams.get(streamId);\n    if (state == null || state.nextSeq === 0) return undefined;\n    return state.nextSeq - 1;\n  }\n\n  /** Every unacked entry across all streams, grouped per stream in seq order — the reconnect flush set. */\n  allPending(): IOutboxEntry[] {\n    const out: IOutboxEntry[] = [];\n    for (const state of this._streams.values()) out.push(...state.unacked.values());\n    return out;\n  }\n\n  /** Re-dispatch all unacked sends (call after a transport (re)connects). */\n  resendAll(): void {\n    for (const entry of this.allPending()) entry.dispatch();\n  }\n\n  /**\n   * Re-sync a stream after the receiver reset (an `rsync` control frame from an evicted/restarted server that\n   * lost its in-memory high-water): renumber the still-unacked entries from seq 0 — **mutating each entry's\n   * `reliability.seq` in place** so its stored dispatch closure resends the frame with the new seq — reset the\n   * ack high-water, then resend them in order. The fresh receiver then delivers the in-flight tail from 0\n   * instead of stalling on an unfillable gap. No-op when nothing is unacked or the stream is unknown;\n   * renumbering an already-0-based stream is harmless (idempotent), so a duplicate `rsync` is safe.\n   */\n  resync(streamId: string): void {\n    const state = this._streams.get(streamId);\n    if (state == null || state.unacked.size === 0) return;\n\n    const entries = [...state.unacked.values()]; // Map preserves insertion = ascending seq order\n    const renumbered = new Map<number, IOutboxEntry>();\n    entries.forEach((entry, index) => {\n      entry.seq = index;\n      entry.reliability.seq = index;\n      renumbered.set(index, entry);\n    });\n    state.unacked = renumbered;\n    state.ackedSeq = -1;\n    state.nextSeq = entries.length;\n\n    for (const entry of renumbered.values()) entry.dispatch();\n  }\n\n  /** Total unacked sends held (across streams) — for tests / diagnostics. */\n  get size(): number {\n    let n = 0;\n    for (const state of this._streams.values()) n += state.unacked.size;\n    return n;\n  }\n}\n","import type {\n  IControlMessage_ReliableClose,\n  IControlMessage_ReliableSkip,\n  RuntimeCoordinate,\n} from \"@nice-code/wire\";\nimport {\n  DEFAULT_TRANSPORT_TIMEOUT,\n  WireClient,\n  warnReliableDeliveryAbandonedOnce,\n} from \"@nice-code/wire\";\nimport type { IActionRouteItem } from \"../../../../ActionDefinition/Action/Context/ActionContext.types\";\nimport type {\n  IActionRouteItemHandler,\n  TActionPayload_Any_Instance,\n} from \"../../../../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport { EActionPayloadType } from \"../../../../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport type { ActionPayload_Request } from \"../../../../ActionDefinition/Action/Payload/ActionPayload_Request\";\nimport { RunningAction } from \"../../../../ActionDefinition/Action/RunningAction\";\nimport { ERunningActionUpdateType } from \"../../../../ActionDefinition/Action/RunningAction.types\";\nimport type { IActionDomain } from \"../../../../ActionDefinition/Domain/ActionDomain.types\";\nimport {\n  EActionResponseMode,\n  EReliabilityTier,\n} from \"../../../../ActionDefinition/Schema/ActionSchema\";\nimport { ActionRuntime } from \"../../../ActionRuntime\";\nimport { peekHandlerCuid } from \"../../../HandlerCallStack\";\nimport { ConnectionTransportManager } from \"../../../Transport/ConnectionTransportManager\";\nimport { EErrId_NiceTransport, err_nice_transport } from \"../../../Transport/err_nice_transport\";\nimport {\n  ETransportShape,\n  type IActionTransportReadyData_Methods,\n  type IFrameReliability,\n  type ITransportMethod_SendActionData_Input,\n  type ITransportRouteActionParams,\n  type TTransportRouteParams,\n} from \"../../../Transport/Transport.types\";\nimport type { TransportConnection } from \"../../../Transport/TransportConnection\";\nimport type { IActionHandler_Peer_Json, IHandleActionOptions } from \"../../ActionHandler.types\";\nimport { PeerLink } from \"../../PeerLink/PeerLink\";\nimport type {\n  IChannelConnectorConfig,\n  IReliableStreamPressure,\n  TLinkEvent,\n  TReliableStreamEvent,\n} from \"./ChannelConnector.types\";\nimport { ReliableOutbox, reliableStreamId } from \"./ReliableOutbox\";\n\n/**\n * Overall deadline for a reliable action, after which it aborts if still unacked. Reliability retries\n * across reconnects, but it must not retry *forever* — an unreachable peer has to surface as a failure\n * rather than a silent hang. Generous by default (tolerates a long reconnect) and overridable per\n * connector. (At-least-once + a deadline means a timed-out reliable action *may* still have been\n * delivered — the ack was simply lost; documented in the reliability contract.)\n */\nconst DEFAULT_RELIABLE_ACTION_TIMEOUT = 60_000;\n/** Backoff between retries when a reliable action can't acquire a transport at all (initial connect fails). */\nconst RELIABLE_CONNECT_RETRY_MS = 1_000;\n\n/**\n * Dial-out peer link: this runtime opens connection(s) to one peer over a transport stack (cached, with\n * preference-ordered fallback). The classic \"client → backend\" handler — but to the runtime it's just a\n * {@link PeerLink} like the accept-in server one.\n *\n * The connection **lifecycle** — dial, keep-alive redial ladder, link events, park, teardown — lives on\n * the {@link WireClient} this handler holds ({@link _wire}); the handler keeps only the action *lane*:\n * routing, the reliable outbox, return-path dispatch, and delegates every lifecycle verb to the client\n * (so `connectChannel` and a realm-only `createWireClient` are one connection implementation).\n */\nexport class ChannelConnector extends PeerLink {\n  /**\n   * This connection's own identity when it was given one (`connectChannel`'s `connectionId`), used\n   * in place of the local runtime's coordinate as the origin stamped on outgoing frames — matching\n   * the identity the handshake bound, so the peer's return path finds *this* socket. `undefined` ⇒\n   * the connection speaks as the runtime, which is the single-link default.\n   */\n  private readonly _connectionIdentity?: RuntimeCoordinate;\n  private _defaultTimeout: number;\n  private _reliableTimeout: number;\n  /**\n   * The wire connection this handler binds the action lane onto — it owns the transport cache,\n   * preference-ordered selection, the mux, and the whole connection **lifecycle** (dial, keep-alive\n   * redial, link events, park, teardown). The handler delegates every connection-level verb +\n   * property to it; `createWireClient` wraps the same class for a realm-only app.\n   */\n  private readonly _wire: WireClient<\n    TTransportRouteParams,\n    IActionTransportReadyData_Methods,\n    TransportConnection\n  >;\n\n  // ── Connection surface (delegated to `_wire`) — the `IRealmWireLink` seam + the chaos verb ──\n  /** Whether any transport can push (duplex) — a realm reads it. */\n  get canPush() {\n    return this._wire.canPush;\n  }\n  /** The local coordinate this connection dials out from — a realm defaults its identity from it. */\n  get localCoordinate() {\n    return this._wire.localCoordinate;\n  }\n  /**\n   * The negotiated wire security level this connection's frame protocols (a realm) ride at — a realm\n   * client reads it via `realmConnection(connector)` and refuses to send below its required minimum.\n   */\n  get securityLevel() {\n    return this._wire.securityLevel;\n  }\n  /**\n   * The frame-protocol mux riding this connection's link — protocol modules (a realm client)\n   * register here. Register protocols *before* {@link connect} / the first dispatch so the handshake\n   * advertises them.\n   */\n  get wireMux() {\n    return this._wire.wireMux;\n  }\n  /**\n   * The re-dial hook a realm client rides:\n   * `realmConnection(connector)` hands it to the engine as `requestReconnect`, invoked on an\n   * unanswered staleness probe.\n   */\n  get requestReconnect() {\n    return this._wire.requestReconnect;\n  }\n  /**\n   * Chaos/QA surface — `connector.debug.dropLink(...)` forces the outages\n   * page-level interception can't (never for production control flow). Delegated to the connection.\n   */\n  get debug() {\n    return this._wire.debug;\n  }\n\n  /** Client-side send bookkeeping for `.reliable()` actions (seq/ack/resend). Inert until one is used. */\n  private readonly _outbox = new ReliableOutbox();\n  /** Transports we've already attached a resend-on-disconnect listener to (attach once per connection). */\n  private readonly _resendHooked = new WeakSet<IActionTransportReadyData_Methods>();\n  /**\n   * Per-send **delivery deadline** timers, keyed by each unacked send's reliability object (stable across\n   * a re-sync, which renumbers `seq` by mutating that same object in place). Armed at `prepare`, cleared\n   * when the send is **acked** (not when its action settles — a reply-less action settles on send while\n   * its delivery is still pending). On expiry the frame is abandoned: its action aborts if still pending,\n   * and the stream skips past it (see {@link _abandonReliableThrough}), so delivery is *bounded* for\n   * reply-carrying and reply-less sends alike.\n   */\n  private readonly _deliveryDeadlines = new WeakMap<\n    IFrameReliability,\n    ReturnType<typeof setTimeout>\n  >();\n  /**\n   * The highest-abandoned-seq `rskip` per stream, kept (and re-flushed on every fresh connection) until\n   * the peer's ack passes it — so a skip lost to a drop mid-send still lands, and the receiver never\n   * waits forever on a seq the outbox abandoned. Cleared on an `rsync` (a fresh receiver has no gap to\n   * skip; stale pre-reset seqs must not be replayed against the renumbered stream).\n   */\n  private readonly _streamSkips = new Map<string, IControlMessage_ReliableSkip>();\n  /**\n   * Pending `rclose` per closed stream, kept until sent once on a live control channel (then dropped —\n   * `rclose` is a loss-tolerant memory reclaim, unlike an `rskip` it needs no ack retirement: delivery\n   * was already settled by the close's retained `rskip`, and a receiver that misses it self-heals).\n   */\n  private readonly _streamCloses = new Map<string, IControlMessage_ReliableClose>();\n  /** Most recent live methods able to carry control frames — the immediate path for an `rskip`. */\n  private _controlMethods?: IActionTransportReadyData_Methods;\n  /** Stream-level reliable-delivery observers (see {@link TReliableStreamEvent}). */\n  private readonly _reliableEventListeners = new Set<(event: TReliableStreamEvent) => void>();\n\n  constructor({\n    peer,\n    runtimeCoordinate,\n    transports,\n    defaultTimeout,\n    reliableActionTimeout,\n    wireMux,\n    localCoordinate,\n    connectionIdentity,\n    securityLevel,\n    reconnect,\n    keepLinkAlive,\n  }: IChannelConnectorConfig) {\n    const peerSpecifier = peer ?? runtimeCoordinate;\n    super(peerSpecifier);\n\n    this._connectionIdentity = connectionIdentity;\n    this._defaultTimeout = defaultTimeout ?? DEFAULT_TRANSPORT_TIMEOUT;\n    this._reliableTimeout = reliableActionTimeout ?? DEFAULT_RELIABLE_ACTION_TIMEOUT;\n    this._wire = new WireClient({\n      createManager: (cache) => new ConnectionTransportManager(cache),\n      mux: wireMux,\n      peer: this.peer,\n      localCoordinate: connectionIdentity ?? localCoordinate,\n      securityLevel,\n      canPush: transports.some((transport) => transport.type === ETransportShape.duplex),\n      reconnect: reconnect ?? keepLinkAlive,\n      // The action lane's route params ARE a valid actionless dial input (action/reliability optional).\n      buildConnectInput: (pair) => pair,\n      // Preserve the dispatch-driven default: fall back to the ambient runtime's coordinate.\n      defaultLocalCoordinate: () => ActionRuntime.getDefault().coordinate,\n    });\n\n    for (const transport of transports) {\n      // A request arriving here is answered over this connector; its origin stays the peer's own claim.\n      const securityLevel = transport._inboundSecurityLevel();\n      const connection = transport._createConnection({\n        resolvers: {\n          onIncomingActionDataJson: (json, reliability) => {\n            // A reliable reply carries the peer's cumulative high-water — prune the outbox for that stream\n            // so acked sends stop being resent. Keyed by (peer + route [+ streamKey]), matching how the\n            // request stamped it. No-op for a best-effort frame.\n            if (reliability?.ack != null) {\n              this._applyAck(\n                reliableStreamId(this.peer, json.domain, json.id, reliability.streamKey),\n                reliability.ack,\n              );\n            }\n            this._emitIncoming(json, { receiver: this, securityLevel });\n          },\n          onControlMessage: (message) => {\n            // Rebuild the (possibly keyed) stream id from the route + optional streamKey the frame carries.\n            const streamId = reliableStreamId(this.peer, message.domain, message.id, message.k);\n            if (message.$c === \"rack\") {\n              // A standalone reliability ack (no action reply to piggyback on — a reply-less stream, a keyed\n              // stream, or a duplicate the server suppressed). Prune the outbox, settling each acked send.\n              this._applyAck(streamId, message.ack);\n            } else if (message.$c === \"rsync\") {\n              // The server lost its state mid-stream (session-tier eviction/restart) and asked us to re-sync:\n              // renumber our still-unacked frames from 0 and resend, so the in-flight tail continues in order\n              // on the fresh receiver instead of stalling. Any pending skip is stale against the fresh\n              // receiver (its seqs predate the renumber — replaying it would swallow live renumbered\n              // frames), and there is no gap to skip on a state-less stream: drop it first.\n              this._streamSkips.delete(streamId);\n              this._outbox.resync(streamId);\n            }\n          },\n        },\n      });\n      connection.definition = transport;\n      this._wire.addTransport(connection);\n    }\n  }\n\n  // ── Connection lifecycle (delegated to `_wire`) ─────────────────────────────\n  /**\n   * Establish the connection without dispatching an action — so a realm-only\n   * (actionless) client can exist. Idempotent; resolves when the handshake completes, rejects (and\n   * arms/parks the keep-alive ladder) when the transport chain is exhausted. `targetLocalRuntime`\n   * overrides the dial identity; otherwise the connection's configured coordinate, else the ambient\n   * runtime's default — preserving the pre-descent behaviour.\n   *\n   * **Do not fire-and-forget the returned promise** — it is where handshake failures surface,\n   * including `identity_pin_mismatch` (branch on it with `err.hasId(\"identity_pin_mismatch\")`; see\n   * `err_wire_connect`).\n   */\n  async connect(config?: { targetLocalRuntime?: ActionRuntime }): Promise<void> {\n    await this._wire.connect({\n      localCoordinate: this._connectionIdentity ?? config?.targetLocalRuntime?.coordinate,\n    });\n  }\n\n  /**\n   * Tear down the (possibly half-open) duplex link and immediately re-dial it (the reconnect contract / Phase\n   * 8b) — surfaced to a realm client as `requestReconnect`, called by the staleness-probe\n   * escalation. **Awaitable** — resolves when the fresh link's handshake completes.\n   */\n  reconnectLink(): Promise<void> {\n    return this._wire.reconnectLink();\n  }\n\n  /**\n   * Permanently stop this connector: cancel any pending auto-redial and drop the connection cache\n   * (keep-alive never re-dials again — an explicit, final teardown, distinct from\n   * {@link clearTransportCache}).\n   */\n  dispose(): void {\n    this._wire.dispose();\n  }\n\n  // ---------------------------------------------------------------------------\n  // Action handling\n  // ---------------------------------------------------------------------------\n\n  async handleActionRequest<\n    DOM extends IActionDomain,\n    ID extends keyof DOM[\"actionSchema\"] & string,\n  >(\n    action: ActionPayload_Request<DOM, ID>,\n    config?: IHandleActionOptions,\n  ): Promise<RunningAction<DOM, ID>> {\n    const localRuntime = config?.targetLocalRuntime ?? ActionRuntime.getDefault();\n    const localClient = this._connectionIdentity ?? localRuntime.coordinate;\n\n    // A named connection speaks as itself, not as the runtime: the dispatching domain stamped the\n    // runtime's coordinate as the origin, but the peer bound *this socket* to the connection identity\n    // its handshake presented — the two must be the same string or the return path can't tell this\n    // connection from the runtime's other links to the same peer.\n    if (this._connectionIdentity != null) {\n      action.context._setOriginClient(this._connectionIdentity);\n    }\n\n    const incomingTimeout = config?.timeout ?? this._defaultTimeout;\n\n    // Capture parent + call site synchronously — once we await the transport the call stack is gone.\n    const parentCuid = peekHandlerCuid();\n    const callSite = localRuntime._captureActionCallSite(action, config?.captureCallSites);\n\n    const routeParams: ITransportRouteActionParams = {\n      action,\n      localClient,\n      externalClient: this.peer,\n    };\n\n    // Record the route hop up-front, labelled with the highest-priority transport, so the action shows\n    // its (expected) destination — the runtime + e.g. \"ws → backend\" — the moment it appears, instead\n    // of an \"unknown\" hop while the transport is still connecting. `_dispatchWhenTransportReady`\n    // corrects it once `getReadyTransport` picks the real winner (which can differ if the preferred\n    // transport is unavailable and a fallback serves the action).\n    const preferredTransport = this._wire.getPreferredTransport();\n    const routeItem: IActionRouteItem | undefined =\n      preferredTransport != null\n        ? {\n            runtime: localClient,\n            handler: this.toHandlerRouteItem(preferredTransport, routeParams),\n            time: Date.now(),\n          }\n        : undefined;\n    if (routeItem != null) action.context.addRouteItem(routeItem);\n\n    // Create + register the RunningAction up-front, before acquiring the transport. Acquiring it can\n    // take real time (opening a WebSocket + running its handshake on the first action), and that wait\n    // is part of the action's running lifecycle — not a precondition for the action to exist. Creating\n    // it now means observers (devtools, the dispatching domain's listeners) see the action the moment\n    // it's initiated and watch it move through \"connecting → sent → finished\", instead of it only\n    // popping into existence — already mid-flight or done — once the socket is ready.\n    const runningAction = new RunningAction<DOM, ID>({\n      context: action.context,\n      request: action,\n      parentCuid,\n      callSite,\n    });\n    localRuntime.registerRunningAction(runningAction);\n\n    // Reliable tier: assign the stream's next seq and remember this send in the outbox before dispatch,\n    // so a drop/reconnect can resend it. `routeParams.reliability` is then stamped onto every (re)send of\n    // this exact frame. Overflow (peer not acking) aborts the action rather than growing memory.\n    if (action.schema.reliabilityTier !== EReliabilityTier.none) {\n      // An optional per-request `streamKey` (E3) scopes an independent ordered stream of this action\n      // (e.g. one per room id); absent → the single default stream, byte-identical to today.\n      const streamKey = config?.streamKey;\n      const streamId = reliableStreamId(this.peer, action.domain, action.id, streamKey);\n      const prepared = this._outbox.prepare(\n        streamId,\n        () => {\n          // Stop resending only once the action is **aborted** (deadline / overflow / explicit abort) — not\n          // merely settled. A reply-less reliable action completes *on send* (isSettled), but the outbox must\n          // keep delivering it in the background until the peer acks (which prunes it here); gating on\n          // isSettled would silently skip resending a lost fire-and-forget frame.\n          if (runningAction.isAborted) return;\n          void this._dispatchWhenTransportReady(\n            runningAction,\n            routeParams,\n            routeItem,\n            incomingTimeout,\n          );\n        },\n        streamKey,\n        {\n          // Swept by an older frame's abandonment (or a stream close): settle the delivery promise, then\n          // fail the action loudly *now* (its frame was dropped with the head it was ordered behind)\n          // instead of riding out its own deadline undeliverable.\n          onDrop: (reason) => {\n            runningAction._notifyAckAbandoned(reason);\n            void runningAction._abort(reason);\n          },\n          // Acked = the sender-side proof of delivery — stamps the devtools chip (E7), emits the\n          // `reliability` update, and resolves `waitForAck()`.\n          onAck: () => runningAction._notifyAcked(),\n        },\n      );\n      if (prepared == null) {\n        this._emitReliableEvent(\n          streamKey == null\n            ? { type: \"overflow\", domain: action.domain, actionId: action.id }\n            : { type: \"overflow\", domain: action.domain, actionId: action.id, streamKey },\n        );\n        runningAction._abort(\n          err_nice_transport.fromId(EErrId_NiceTransport.reliable_outbox_overflow, {\n            actionId: action.id,\n            streamId,\n            maxUnacked: this._outbox.maxUnackedPerStream,\n          }),\n        );\n        return runningAction;\n      }\n      routeParams.reliability = prepared.reliability;\n      // Surface the tier + this frame's seq/streamKey on the RunningAction so observers (devtools) can\n      // show a reliable chip. The cumulative ack/redelivered are receiver-side facts (the server\n      // serve-logger + the handler's `context.reliability`), not ours.\n      runningAction._setReliability({\n        tier: action.schema.reliabilityTier,\n        seq: prepared.reliability.seq,\n        streamKey,\n      });\n      // Per-send delivery deadline: reliability retries across reconnects, but delivery must stay\n      // *bounded* — for a reply-carrying send (abort the pending action) and a reply-less one (already\n      // settled on send) alike. Cleared when the peer acks the frame, not when the action settles.\n      this._armDeliveryDeadline(streamId, prepared.reliability, runningAction);\n      // Any abort while the frame is unacked — the deadline above, an explicit `.abort()`, a transport\n      // failure — means the frame will never legitimately resend (the dispatch guard skips aborted\n      // actions). Left in place it would wedge the stream on a permanent seq gap; instead **abandon** it\n      // (and anything older still unacked) and tell the receiver to skip past, so the stream continues.\n      const abandonOnAbort = runningAction.addUpdateListeners([\n        (update) => {\n          if (update.type !== ERunningActionUpdateType.finished) return;\n          abandonOnAbort();\n          if (runningAction.isAborted) {\n            this._abandonReliableThrough(\n              streamId,\n              prepared.reliability,\n              action.domain,\n              action.id,\n              streamKey,\n            );\n          }\n        },\n      ]);\n    }\n\n    // Resolve the transport and dispatch in the background so the RunningAction can be returned (and\n    // observed) immediately. Any failure along the way aborts the action, surfacing through its result\n    // and in the devtools just as a synchronous send failure would.\n    void this._dispatchWhenTransportReady(runningAction, routeParams, routeItem, incomingTimeout);\n\n    return runningAction;\n  }\n\n  private async _dispatchWhenTransportReady<\n    DOM extends IActionDomain,\n    ID extends keyof DOM[\"actionSchema\"] & string,\n  >(\n    runningAction: RunningAction<DOM, ID>,\n    routeParams: ITransportRouteActionParams,\n    routeItem: IActionRouteItem | undefined,\n    incomingTimeout: number,\n  ): Promise<void> {\n    const action = routeParams.action;\n    try {\n      const { methods, transport } = await this._wire.getReadyTransport(routeParams);\n\n      // Establishment bookkeeping (keep-alive re-enable, backoff reset, `link_up`) already ran\n      // inside `_wire.getReadyTransport` above — a dispatch that brings a link up counts exactly\n      // like an explicit `connect()`. The lane only adds its own resend-on-disconnect hook below.\n\n      // First dispatch over a *fresh* connection: arm a resend of all still-unacked reliable frames if it\n      // drops (deferred a tick so the dropped connection's cache slot is evicted first, letting the resend\n      // acquire a fresh connection rather than the dead one) — and flush the other direction too: resend\n      // whatever is still unacked *now* (frames orphaned while no connection existed) plus any pending\n      // stream skips, so recovery is an invariant of acquiring a new transport, not only a side effect of\n      // losing the old one.\n      if (methods.addOnDisconnectListener != null && !this._resendHooked.has(methods)) {\n        this._resendHooked.add(methods);\n        methods.addOnDisconnectListener(() => {\n          if (this._outbox.size > 0) setTimeout(() => this._outbox.resendAll(), 0);\n        });\n        if (methods.sendControlData != null) this._controlMethods = methods;\n        if (this._outbox.size > 0) setTimeout(() => this._outbox.resendAll(), 0);\n      }\n\n      // Correct the hop to the transport that actually serves the action (the preferred one may have\n      // been unavailable). Mutated in place so the action wire and the devtools \"finished\" view reflect\n      // the real route.\n      const handlerRouteItem = this.toHandlerRouteItem(transport, routeParams);\n      if (routeItem != null) {\n        routeItem.handler = handlerRouteItem;\n        routeItem.time = Date.now();\n      } else {\n        action.context.addRouteItem({\n          runtime: routeParams.localClient,\n          handler: handlerRouteItem,\n          time: Date.now(),\n        });\n      }\n\n      const sendInput: ITransportMethod_SendActionData_Input = {\n        ...routeParams,\n        runningAction,\n        timeout: incomingTimeout,\n      };\n\n      if (action.type === EActionPayloadType.request && methods.updateRunConfig != null) {\n        const runConfig = methods.updateRunConfig(sendInput);\n        sendInput.timeout = runConfig?.timeout ?? incomingTimeout;\n      }\n\n      methods.sendActionData(sendInput);\n\n      // Flush any pending stream skips *after* the action frame: on a fresh connection the first request\n      // is what binds the client identity server-side, and a control frame arriving before any request\n      // couldn't be resolved to its client (it would be dropped). Frames are processed in order, and\n      // `skipTo` drains anything the request buffered behind the abandoned gap — so after-works, before\n      // doesn't.\n      if (this._streamSkips.size > 0) this._flushStreamSkips();\n\n      // Fire-and-forget: no reply correlates back, so resolve the running action on send instead of\n      // leaving it pending until it times out. This holds for a *reliable* fire-and-forget too — its\n      // delivery is guaranteed transparently by the outbox (resend on reconnect, prune on the standalone\n      // ack) in the background, so the caller still sees fire-and-forget completion on send.\n      if (\n        action.type === EActionPayloadType.request &&\n        action.schema.responseMode === EActionResponseMode.none\n      ) {\n        runningAction._completeWithResult(\n          (action as ActionPayload_Request<any, any>).successResult(undefined),\n        );\n      }\n    } catch (err) {\n      // A best-effort action aborts on any dispatch failure. A reliable action instead **retries**: a\n      // live connection would resend on disconnect, but a connect failure (initial *or* at resend time)\n      // has no live connection to hook — so schedule a backoff retry. Gated on `isAborted`, not\n      // `isSettled`: a reply-less reliable action is settled the moment it completes-on-send, yet its\n      // delivery must keep retrying until the peer acks (same rationale as the outbox resend guard).\n      // The per-entry delivery deadline is the upper bound that eventually drops it if the peer stays\n      // unreachable.\n      if (action.type === EActionPayloadType.request && routeParams.reliability != null) {\n        if (!runningAction.isAborted) {\n          setTimeout(() => {\n            if (runningAction.isAborted) return;\n            void this._dispatchWhenTransportReady(\n              runningAction,\n              routeParams,\n              routeItem,\n              incomingTimeout,\n            );\n          }, RELIABLE_CONNECT_RETRY_MS);\n        }\n        return;\n      }\n      runningAction._abort(err);\n    }\n  }\n\n  /**\n   * Apply a cumulative ack for a stream: prune the outbox, clear each acked send's delivery deadline, and\n   * retire a pending `rskip` once the ack passes it (proof the skip — or the frames it covered — landed).\n   * The single funnel for both ack paths (reply piggyback + standalone `rack` control frame).\n   */\n  private _applyAck(streamId: string, ack: number): void {\n    for (const entry of this._outbox.ack(streamId, ack)) {\n      const deadline = this._deliveryDeadlines.get(entry.reliability);\n      if (deadline != null) {\n        clearTimeout(deadline);\n        this._deliveryDeadlines.delete(entry.reliability);\n      }\n    }\n    const skip = this._streamSkips.get(streamId);\n    if (skip != null && ack >= skip.seq) this._streamSkips.delete(streamId);\n  }\n\n  /**\n   * Arm one reliable send's **delivery deadline**: if the peer hasn't acked the frame within\n   * {@link _reliableTimeout}, the frame is abandoned — the action aborts if still pending (its abort\n   * listener then runs the abandonment), while an already-settled reply-less action abandons directly\n   * (with a one-time route warning, since its caller was already told \"success on send\"). This is what\n   * turns \"retry across reconnects\" from a potential infinite hang into a bounded, eventually-failing\n   * operation for an unreachable peer — for *every* reliable send, reply-less included. Cleared by\n   * {@link _applyAck} when the frame is acked.\n   */\n  private _armDeliveryDeadline(\n    streamId: string,\n    reliability: IFrameReliability,\n    runningAction: RunningAction<any, any>,\n  ): void {\n    const timer = setTimeout(() => {\n      const aborted = runningAction._abort(\n        err_nice_transport.fromId(EErrId_NiceTransport.reliable_delivery_abandoned, {\n          actionId: runningAction.state.request.id,\n          streamId,\n          timeout: this._reliableTimeout,\n        }),\n      );\n      if (!aborted) {\n        // Reply-less (settled-on-send) — the abort listener won't fire, abandon here and warn once.\n        const request = runningAction.state.request;\n        warnReliableDeliveryAbandonedOnce(request.domain, request.id);\n        this._abandonReliableThrough(\n          streamId,\n          reliability,\n          request.domain,\n          request.id,\n          reliability.streamKey,\n        );\n      }\n    }, this._reliableTimeout);\n    this._deliveryDeadlines.set(reliability, timer);\n  }\n\n  /**\n   * Abandon a reliable send that will never deliver (its action aborted / its delivery deadline expired):\n   * drop it — and, cumulatively, every older still-unacked send on its stream (they could no longer be\n   * delivered in order; each fails loudly via its `onDrop`) — then record + send an `rskip` so the\n   * receiver advances past the abandoned seqs and the stream **continues** instead of wedging on a\n   * permanent gap. The skip is kept (and re-flushed on each fresh connection) until an ack passes it, so\n   * a drop can't lose it. Idempotent: a second call for the same (or an older) seq drops nothing.\n   */\n  private _abandonReliableThrough(\n    streamId: string,\n    reliability: IFrameReliability,\n    domain: string,\n    actionId: string,\n    streamKey?: string,\n    /** Overrides the default deadline-abandon reason (e.g. a `closeReliableStream`'s close reason). */\n    reasonOverride?: unknown,\n  ): void {\n    const seq = reliability.seq;\n    if (seq == null) return;\n\n    const reason =\n      reasonOverride ??\n      err_nice_transport.fromId(EErrId_NiceTransport.reliable_delivery_abandoned, {\n        actionId,\n        streamId,\n        timeout: this._reliableTimeout,\n      });\n    const dropped = this._outbox.dropThrough(streamId, seq, reason);\n    for (const entry of dropped) {\n      const deadline = this._deliveryDeadlines.get(entry.reliability);\n      if (deadline != null) {\n        clearTimeout(deadline);\n        this._deliveryDeadlines.delete(entry.reliability);\n      }\n    }\n    // Surface the abandoned range to stream-level observers: entries are in ascending seq order, so the\n    // range is `[first dropped, seq]` (the sweep is cumulative — it may cover several sends).\n    if (dropped.length > 0) {\n      this._emitReliableEvent({\n        type: \"abandoned\",\n        domain,\n        actionId,\n        ...(streamKey == null ? {} : { streamKey }),\n        fromSeq: dropped[0].seq,\n        toSeq: seq,\n        reason,\n      });\n    }\n    if (dropped.length === 0 && (this._streamSkips.get(streamId)?.seq ?? -1) >= seq) return;\n\n    const previous = this._streamSkips.get(streamId);\n    if (previous == null || seq > previous.seq) {\n      this._streamSkips.set(\n        streamId,\n        streamKey == null\n          ? { $c: \"rskip\", domain, id: actionId, seq }\n          : { $c: \"rskip\", domain, id: actionId, seq, k: streamKey },\n      );\n    }\n    this._flushStreamSkips();\n  }\n\n  /**\n   * Send every pending `rskip` over the last live control-capable connection (kept until acked past),\n   * then every pending `rclose` (dropped after one successful send — loss-tolerant reclaim).\n   */\n  private _flushStreamSkips(): void {\n    const methods = this._controlMethods;\n    if (methods?.sendControlData == null) return;\n    for (const skip of this._streamSkips.values()) {\n      methods.sendControlData(skip);\n    }\n    for (const [streamId, close] of this._streamCloses) {\n      methods.sendControlData(close);\n      this._streamCloses.delete(streamId);\n    }\n  }\n\n  /**\n   * Observe stream-level reliable-delivery events — the handle-less settlement surface: `abandoned`\n   * (frames `fromSeq..toSeq` dropped undelivered; the stream skipped past them) and `overflow` (a send\n   * rejected at the unacked-window cap). Complements the per-send `RunningAction.waitForAck()`, which\n   * requires holding the handle. Returns an unsubscribe. Wired by `connectChannel({ onReliableEvent })`.\n   */\n  addReliableEventListener(listener: (event: TReliableStreamEvent) => void): () => void {\n    this._reliableEventListeners.add(listener);\n    return () => {\n      this._reliableEventListeners.delete(listener);\n    };\n  }\n\n  private _emitReliableEvent(event: TReliableStreamEvent): void {\n    for (const listener of this._reliableEventListeners) {\n      try {\n        listener(event);\n      } catch (err) {\n        console.error(\"[reliable] onReliableEvent listener threw\", err);\n      }\n    }\n  }\n\n  /**\n   * Observe transport link-state: `link_down`, `redial_scheduled`\n   * (attempt + delay — truthful \"retrying in N s\" UX), `link_up` (with `downForMs`). Returns an\n   * unsubscribe. Wired by `connectChannel({ onLinkEvent })`; see {@link TLinkEvent} for the\n   * contract (a healthy heal is silent at the realm's sync layer — this is where it's visible).\n   */\n  addLinkEventListener(listener: (event: TLinkEvent) => void): () => void {\n    return this._wire.addLinkEventListener(listener);\n  }\n\n  /**\n   * Close one logical reliable stream **for good** — the teardown verb for a stream whose real-world\n   * subject is over (a finished game run, a departed room): abandon every still-unacked send on it\n   * (each pending action aborts loudly with `reliable_stream_closed`; already-settled fire-and-forget\n   * sends stop resending), tell the receiver to skip past them (retained `rskip` — survives drops), and\n   * release both sides' stream state (an `rclose` reclaim frame; on a keyed stream it also frees the\n   * key's `maxKeyedStreamsPerClient` slot).\n   *\n   * **Synchronous on the sender's state**: after it returns, nothing from this stream can resend — so\n   * calling it at teardown *before* changing dial state (e.g. switching the active run whose URL a\n   * multiplexed-peer transport derives) closes the cross-instance redelivery window entirely.\n   *\n   * The local seq counter is deliberately **kept** (a tiny tombstone): a reused key continues the seq\n   * space, so a receiver that missed the `rclose` (dead-socket race) can never mistake new sends for\n   * duplicates — and against a receiver that *did* forget, the first new send self-heals through the\n   * normal mid-stream re-sync. Closing a stream this connection never sent on is a no-op.\n   */\n  closeReliableStream(action: { domain: string; id: string }, streamKey?: string): void {\n    const streamId = reliableStreamId(this.peer, action.domain, action.id, streamKey);\n    const highest = this._outbox.highestSeq(streamId);\n    if (highest == null) return;\n\n    const reason = err_nice_transport.fromId(EErrId_NiceTransport.reliable_stream_closed, {\n      actionId: action.id,\n      streamId,\n    });\n    // Abandon the whole unacked tail (fails swept actions with the close reason, clears deadlines,\n    // emits the `abandoned` event, queues + flushes the retained rskip).\n    this._abandonReliableThrough(\n      streamId,\n      { streamId, seq: highest, streamKey },\n      action.domain,\n      action.id,\n      streamKey,\n      reason,\n    );\n    // Queue the receiver-side reclaim; sent with the skip flush (dropped after one successful send).\n    this._streamCloses.set(\n      streamId,\n      streamKey == null\n        ? { $c: \"rclose\", domain: action.domain, id: action.id }\n        : { $c: \"rclose\", domain: action.domain, id: action.id, k: streamKey },\n    );\n    this._flushStreamSkips();\n  }\n\n  /** Total unacked reliable sends held across every stream of this connection. */\n  reliablePending(): number;\n  /** One stream's pressure stats — see {@link IReliableStreamPressure}. */\n  reliablePending(\n    action: { domain: string; id: string },\n    streamKey?: string,\n  ): IReliableStreamPressure;\n  reliablePending(\n    action?: { domain: string; id: string },\n    streamKey?: string,\n  ): number | IReliableStreamPressure {\n    if (action == null) return this._outbox.size;\n    const streamId = reliableStreamId(this.peer, action.domain, action.id, streamKey);\n    const oldest = this._outbox.oldestPreparedAt(streamId);\n    return {\n      unackedCount: this._outbox.pendingCount(streamId),\n      oldestUnackedAgeMs: oldest == null ? undefined : Date.now() - oldest,\n      maxUnackedPerStream: this._outbox.maxUnackedPerStream,\n    };\n  }\n\n  /**\n   * Dispatch a result or progress payload directly back to the external client via the best\n   * available bidirectional transport (WebSocket / Custom). Used for return-path routing when the\n   * local runtime recognises that it has a direct channel to the action's originClient.\n   *\n   * Returns `true` if the payload was sent, `false` if no suitable transport was available.\n   */\n  async sendReturnPayload(\n    payload: TActionPayload_Any_Instance<any, any>,\n    config: { targetLocalRuntime: ActionRuntime },\n  ): Promise<boolean> {\n    const localClient = this._connectionIdentity ?? config.targetLocalRuntime.coordinate;\n    try {\n      const { methods } = await this._wire.getReadyTransport({\n        action: payload,\n        localClient,\n        externalClient: this.peer,\n      });\n      if (methods.sendReturnData == null) return false;\n      methods.sendReturnData(payload, { localClient, externalClient: this.peer });\n      return true;\n    } catch {\n      return false;\n    }\n  }\n\n  toJsonObject(): IActionHandler_Peer_Json {\n    return {\n      type: this.handlerType,\n      client: this.peer,\n    };\n  }\n\n  toHandlerRouteItem(\n    transport: TransportConnection,\n    input: ITransportRouteActionParams,\n  ): IActionRouteItemHandler {\n    return {\n      type: this.handlerType,\n      client: this.peer,\n      transOrd: transport.transOrd,\n      transShape: transport.type,\n      transInfo: transport.getRouteInfo(input),\n    };\n  }\n\n  /**\n   * Stop the keep-alive auto-redial and release the current link — the intention-revealing\n   * teardown counterpart of `reconnect`. Call this when a session is\n   * over (leaving a match, logging out): the link closes and stays closed until the next explicit\n   * `connect()`/dispatch. Not terminal (unlike {@link dispose}) — the connector is reusable.\n   *\n   * For dynamic-endpoint carriers, pair with a `createRequest` that returns `null` once its dial\n   * context is torn down — then even a mis-ordered teardown can't dial a garbage endpoint (the\n   * redial loop parks on `dial_unavailable`).\n   */\n  releaseLink(): void {\n    this._wire.releaseLink();\n  }\n\n  clearTransportCache(): void {\n    this._wire.clearTransportCache();\n  }\n}\n\nexport const createChannelConnector = (config: IChannelConnectorConfig) => {\n  return new ChannelConnector(config);\n};\n","import { castNiceError } from \"@nice-code/error\";\nimport {\n  type IRuntimeCoordinateSpecifics,\n  RuntimeCoordinate,\n  UNSET_RUNTIME_ENV_ID,\n} from \"@nice-code/wire\";\nimport { nanoid } from \"nanoid\";\nimport type { IActionReceiverMetadata } from \"../ActionDefinition/Action/Context/ActionContext.types\";\nimport type { ActionCore } from \"../ActionDefinition/Action/Core/ActionCore\";\nimport type { TActionPayload_Any_Instance } from \"../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport {\n  EActionPayloadType,\n  type TActionPayload_Any_JsonObject,\n} from \"../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport { ActionPayload_Request } from \"../ActionDefinition/Action/Payload/ActionPayload_Request\";\nimport { RunningAction } from \"../ActionDefinition/Action/RunningAction\";\nimport {\n  ERunningActionFinishedType,\n  ERunningActionUpdateType,\n} from \"../ActionDefinition/Action/RunningAction.types\";\nimport type { ActionDomain } from \"../ActionDefinition/Domain/ActionDomain\";\nimport type { IActionDomain } from \"../ActionDefinition/Domain/ActionDomain.types\";\nimport type { ActionRootDomain } from \"../ActionDefinition/Domain/ActionRootDomain\";\nimport { EActionResponseMode, EReliabilityTier } from \"../ActionDefinition/Schema/ActionSchema\";\nimport { captureDiagnosticCallSite } from \"../diagnostics/callSite\";\nimport { EErrId_NiceAction, err_nice_action } from \"../errors/err_nice_action\";\nimport { getAssumedRuntimeInfo } from \"../utils/getAssumedRuntimeEnvironment\";\nimport { isActionPayload_Any_JsonObject } from \"../utils/isActionPayload_Any_JsonObject\";\nimport type {\n  IActionRuntimeOptions,\n  IRuntimeMeta,\n  TActionRuntimeHandler,\n  TActionRuntimeScope,\n} from \"./ActionRuntime.types\";\nimport {\n  EActionHandlerType,\n  type IExecuteActionOptions,\n  type IHandleActionOptions,\n  type TActionHandler,\n} from \"./Handler/ActionHandler.types\";\nimport { ChannelConnector } from \"./Handler/PeerLink/Connector/ChannelConnector\";\nimport { PeerLink } from \"./Handler/PeerLink/PeerLink\";\nimport { ActionRouter } from \"./Routing/ActionRouter\";\nimport { EActionRouterContextType } from \"./Routing/ActionRouter.types\";\nimport type { Transport } from \"./Transport/Transport\";\n\ninterface IHandlerOwnership {\n  persistent: boolean;\n  leases: Set<symbol>;\n  unbind?: () => void;\n}\n\nexport class ActionRuntime {\n  private _coordinate: RuntimeCoordinate;\n  readonly timeCreated: number;\n  readonly runtimeInfo: IRuntimeMeta = getAssumedRuntimeInfo();\n  private readonly actionRouter: ActionRouter<TActionRuntimeHandler>;\n  private readonly _pendingRunningActions: Map<string, RunningAction<any, any>> = new Map();\n  private readonly _registeredPeerHandlers: PeerLink[] = [];\n  private readonly _registeredRoots = new Set<ActionRootDomain<any>>();\n  private readonly _handlerOwnership = new Map<TActionRuntimeHandler, IHandlerOwnership>();\n  private _disposed = false;\n  readonly captureCallSites: boolean;\n  readonly scope: TActionRuntimeScope;\n\n  static getDefault(): ActionRuntime {\n    return getDefaultActionRuntime();\n  }\n\n  constructor(coordinate: RuntimeCoordinate, options: IActionRuntimeOptions = {}) {\n    // A fresh-per-boot `insId` when first observed — load-bearing for reliable delivery, not just labelling:\n    // reliable streams are keyed by the full coordinate, so a rebooted runtime must present a *new*\n    // stream identity (its outbox restarts at seq 0; against a receiver's retained high-water for the\n    // old identity those frames would be silently swallowed as duplicates). See the epoch contract on\n    // `IRuntimeCoordinateSpecifics.insId`.\n    // Keep construction randomness-free so definitions and Worker configuration are safe at module scope.\n    this._coordinate = coordinate;\n    this.captureCallSites = options.captureCallSites ?? false;\n    this.scope = options.scope ?? \"global\";\n    this.timeCreated = Date.now();\n\n    this.actionRouter = new ActionRouter({\n      contextType: EActionRouterContextType.runtime_to_handler,\n      runtime: this,\n    });\n  }\n\n  get coordinate(): RuntimeCoordinate {\n    if (this._coordinate.insId == null) {\n      this._coordinate = this._coordinate.specify({ insId: nanoid(14) });\n    }\n    return this._coordinate;\n  }\n\n  get disposed(): boolean {\n    return this._disposed;\n  }\n\n  /** @internal */\n  _assertActive(): void {\n    if (this._disposed) {\n      throw err_nice_action.fromId(EErrId_NiceAction.runtime_disposed, {\n        runtime: this.coordinate.stringId,\n      });\n    }\n  }\n\n  /** @internal Apply the runtime/request diagnostic policy without replacing a supplied stack. */\n  _captureActionCallSite(\n    action: ActionPayload_Request<any, any>,\n    override?: boolean,\n  ): string | undefined {\n    if (action._callSite == null && (override ?? this.captureCallSites)) {\n      action._callSite = captureDiagnosticCallSite();\n    }\n    return action._callSite;\n  }\n\n  specifyRuntimeCoordinate(specifics: IRuntimeCoordinateSpecifics & { envId?: string }): void {\n    this._assertActive();\n    if (specifics.envId != null && this._coordinate.envId !== specifics.envId) {\n      throw err_nice_action.fromId(EErrId_NiceAction.not_implemented, {\n        label: `updating RuntimeCoordinate with a different \"envId\" (\"${this._coordinate.envId}\" → \"${specifics.envId}\")`,\n      });\n    }\n\n    this._coordinate = this._coordinate.specify(specifics);\n  }\n\n  registerRunningAction(ra: RunningAction<any, any>): void {\n    this._assertActive();\n    this._pendingRunningActions.set(ra.cuid, ra);\n    ra.addUpdateListeners([\n      (update) => {\n        if (update.type === ERunningActionUpdateType.finished) {\n          this._pendingRunningActions.delete(ra.cuid);\n        }\n      },\n    ]);\n  }\n\n  resolveIncomingActionPayload(\n    json: TActionPayload_Any_JsonObject<any, any>,\n    metadata?: IActionReceiverMetadata,\n  ): void {\n    if (this._disposed) return;\n    if (json.type === EActionPayloadType.request) {\n      this._handleActionPayloadWireFromReceiver(json, metadata).catch((err) => {\n        console.error(\n          `[ActionRuntime] Incoming action [${json.domain}:${json.id}:${json.form}:${json.type}] unhandled:`,\n          err,\n        );\n      });\n      return;\n    }\n    this._pendingRunningActions.get(json.context.cuid)?._resolveFromJson(json as any);\n  }\n\n  /** @internal Hydrate a wire request and attach receiver-owned metadata before application dispatch. */\n  async _handleActionPayloadWireFromReceiver(\n    wire: TActionPayload_Any_JsonObject<any, any>,\n    metadata?: IActionReceiverMetadata,\n  ): Promise<RunningAction<any, any>> {\n    const action = this._hydrateActionPayloadWire(wire);\n    if (metadata != null) action.context._setReceiverMetadata(metadata);\n    return this.handleActionPayload(action);\n  }\n\n  private _hydrateActionPayloadWire(wire: unknown): TActionPayload_Any_Instance<any, any> {\n    if (isActionPayload_Any_JsonObject(wire)) {\n      const domain = this.actionRouter.domainManager.getActionDomainOrThrow(wire);\n      return domain.hydrateAnyAction(wire) as TActionPayload_Any_Instance<any, any>;\n    }\n    throw err_nice_action.fromId(EErrId_NiceAction.wire_not_action_data);\n  }\n\n  /**\n   * Handle an incoming action wire (e.g. from a transport layer), route it to\n   * the correct handler, and return the response. The most specific handler\n   * match is chosen (action-ID-specific beats domain-wildcard).\n   */\n  async handleActionPayloadWire<\n    D extends IActionDomain,\n    ID extends keyof D[\"actionSchema\"] & string,\n  >(wire: TActionPayload_Any_JsonObject<D, ID>): Promise<RunningAction<D, ID>>;\n  async handleActionPayloadWire(wire: unknown): Promise<RunningAction<any, any>>;\n  async handleActionPayloadWire(wire: unknown): Promise<RunningAction<any, any>> {\n    this._assertActive();\n    return this.handleActionPayload(this._hydrateActionPayloadWire(wire));\n  }\n\n  /**\n   * The declared {@link EActionResponseMode} for a wire frame's action, looked up from its registered\n   * domain — `undefined` if the route isn't registered. Lets a transport decide, without executing the\n   * action, whether a reply will come back (so e.g. the reliable acceptor knows whether an ack must ride a\n   * standalone control frame vs. piggyback a reply).\n   */\n  responseModeForWire(wire: TActionPayload_Any_JsonObject<any>): EActionResponseMode | undefined {\n    try {\n      const domain = this.actionRouter.domainManager.getActionDomainOrThrow(wire);\n      return domain.actionSchema[wire.id]?.responseMode;\n    } catch {\n      return undefined;\n    }\n  }\n\n  /**\n   * The declared {@link EReliabilityTier} for a wire frame's action, looked up from its registered domain —\n   * `undefined` if the route isn't registered. Lets the reliable acceptor route a `persisted` stream through\n   * its persisted store (vs. the in-memory inbox for the `session` tier) without any wire flag: the tier is\n   * derived from the shared `domain:id`, exactly as the connector derives it to opt a send into the outbox.\n   */\n  reliabilityTierForWire(wire: TActionPayload_Any_JsonObject<any>): EReliabilityTier | undefined {\n    return this.reliabilityTierForRoute(wire.domain, wire.id);\n  }\n\n  /**\n   * {@link reliabilityTierForWire} by bare `domain:id` route — for callers holding only a route, e.g. the\n   * reliable acceptor resolving which receive store an `rskip` control message (no action payload) applies to.\n   */\n  reliabilityTierForRoute(domain: string, id: string): EReliabilityTier | undefined {\n    try {\n      const actionDomain = this.actionRouter.domainManager.getActionDomainOrThrow({ domain, id });\n      return actionDomain.actionSchema[id]?.reliabilityTier;\n    } catch {\n      return undefined;\n    }\n  }\n\n  async handleActionPayload<\n    DOM extends IActionDomain,\n    ID extends keyof DOM[\"actionSchema\"] & string,\n  >(\n    action: TActionPayload_Any_Instance<DOM, ID>,\n    options?: Omit<IHandleActionOptions, \"targetLocalRuntime\">,\n  ): Promise<RunningAction<DOM, ID>> {\n    this._assertActive();\n    if (action.type === EActionPayloadType.request) {\n      // This is the inbound entrypoint (server receiving a wire, or a bidirectional\n      // transport pushing an action to this client). Unlike the local-dispatch path\n      // (`runAction`), the handler doesn't attach the domain's action observers, so\n      // wire them on here — otherwise inbound actions never surface in devtools.\n      const observers = action.context._domain._collectActionObservers();\n\n      let handlerForAction: TActionHandler;\n      try {\n        handlerForAction = this.getHandlerForActionOrThrow(action, options);\n      } catch (err) {\n        const runningAction = new RunningAction<DOM, ID>({\n          context: action.context,\n          request: action,\n        });\n        runningAction.addUpdateListeners(observers);\n        runningAction._completeWithResult(action.errorResult(castNiceError(err)));\n        return runningAction;\n      }\n\n      // A request created locally has already passed ActionCore.request() validation, but a request\n      // hydrated from JSON/msgpack came from an untrusted peer and hydration intentionally only restores\n      // its wire shape. Validate again at the universal execution boundary before application code can\n      // observe `input`. Besides rejecting hostile frames, this makes adjacent-version schema drift a\n      // deterministic action result instead of allowing a handler to throw a foreign/native error while\n      // dereferencing a newly required field.\n      let validatedAction: ActionPayload_Request<DOM, ID>;\n      try {\n        validatedAction = new ActionPayload_Request(\n          { context: action.context },\n          action.context.validateInput(action.input),\n          { time: action.time },\n        );\n        validatedAction._callSite = action._callSite;\n      } catch (err) {\n        const runningAction = new RunningAction<DOM, ID>({\n          context: action.context,\n          request: action,\n        });\n        runningAction.addUpdateListeners(observers);\n        runningAction._completeWithResult(action.errorResult(castNiceError(err)));\n        this._trySetupReturnDispatch(runningAction);\n        return runningAction;\n      }\n\n      const runningAction = await handlerForAction.handleActionRequest(validatedAction, {\n        ...options,\n        targetLocalRuntime: this,\n      });\n      runningAction.addUpdateListeners(observers);\n      this._trySetupReturnDispatch(runningAction);\n      return runningAction;\n    }\n\n    throw err_nice_action.fromId(EErrId_NiceAction.not_implemented, {\n      label: `Handling incoming action payloads of type \"${action.type}\"`,\n    });\n  }\n\n  /**\n   * @internal\n   *\n   * Return the first handler registered for the given action, or `undefined`\n   * if none has been registered (action-ID-specific beats domain-wildcard).\n   */\n  _getHandlerForAction<ACT extends TActionPayload_Any_Instance<any, any>>(\n    action: ACT,\n    _options?: Omit<IHandleActionOptions, \"targetLocalRuntime\">,\n  ): TActionHandler | undefined {\n    const handlers = this.actionRouter.getRouteDataEntriesForAction(action);\n    const possibleHandlers = handlers.filter((handler) => {\n      return (\n        handler.handlerType === EActionHandlerType.peer ||\n        (handler.handlerType === EActionHandlerType.local &&\n          action.type === EActionPayloadType.request)\n      );\n    });\n\n    if (possibleHandlers.length === 0) {\n      return undefined;\n    }\n\n    let handlerScore = -1;\n    let handler: TActionHandler | undefined;\n\n    for (const possibleHandler of possibleHandlers) {\n      // A local handler always wins over any external one: registering a local handler for an action\n      // means \"execute it here\" (the \"handle locally if you can, else forward\" pattern, and the path\n      // by which an inbound push on a bidirectional domain is handled rather than re-forwarded). This\n      // is independent of registration order — otherwise an external `forDomain` registered first could\n      // shadow a local handler for the same action.\n      if (possibleHandler.handlerType === EActionHandlerType.local) {\n        return possibleHandler;\n      }\n\n      if (possibleHandler.handlerType === EActionHandlerType.peer) {\n        const score = RuntimeCoordinate.unknown.similarityLevel(possibleHandler.peer);\n        if (score > handlerScore) {\n          handlerScore = score;\n          handler = possibleHandler;\n        }\n      }\n    }\n\n    return handler;\n  }\n\n  getHandlerForActionOrThrow<ACT extends TActionPayload_Any_Instance<any, any>>(\n    action: ACT,\n    options?: Omit<IHandleActionOptions, \"localRuntime\">,\n  ): TActionHandler {\n    const handler = this._getHandlerForAction(action, options);\n\n    if (handler == null) {\n      throw err_nice_action.fromId(EErrId_NiceAction.no_action_execution_handler, {\n        actionId: action.id,\n        domain: action.domain,\n      });\n    }\n\n    return handler;\n  }\n\n  /**\n   * Register one or more handlers. Each handler's own `actionRouter` defines\n   * which domains/actions it handles — those routing keys are mirrored into\n   * this runtime's router so the same action can be served by multiple handlers.\n   * Re-adding the same handler object is idempotent. Global runtimes register with the affected root\n   * domains automatically; instance runtimes remain private and require explicit dispatch.\n   */\n  addHandlers(handlers: TActionRuntimeHandler[]): this {\n    this._addHandlers(handlers, { persistent: true, register: true });\n    return this;\n  }\n\n  /** @internal Install handlers for a host and return an idempotent ownership release. */\n  _installHandlers(\n    handlers: TActionRuntimeHandler[],\n    options: { register?: boolean } = {},\n  ): () => void {\n    this._assertActive();\n    const lease = Symbol(\"action-runtime-handler-installation\");\n    try {\n      this._addHandlers(handlers, {\n        persistent: false,\n        register: options.register ?? false,\n        lease,\n      });\n    } catch (error) {\n      this._releaseHandlerLease(lease);\n      throw error;\n    }\n    let released = false;\n    return () => {\n      if (released) return;\n      released = true;\n      this._releaseHandlerLease(lease);\n    };\n  }\n\n  private _addHandlers(\n    handlers: TActionRuntimeHandler[],\n    options: { persistent: boolean; register: boolean; lease?: symbol },\n  ): void {\n    this._assertActive();\n    this._assertNoDuplicateLocalExecutors(handlers);\n    // All-or-nothing: a later handler's failure undoes what this call installed or promoted.\n    const installed: TActionRuntimeHandler[] = [];\n    const promoted: IHandlerOwnership[] = [];\n    try {\n      for (const handler of handlers) {\n        let ownership = this._handlerOwnership.get(handler);\n        if (ownership == null) {\n          ownership = this._installHandler(handler);\n          installed.push(handler);\n        }\n        if (options.persistent && !ownership.persistent) {\n          ownership.persistent = true;\n          promoted.push(ownership);\n        }\n        if (options.lease != null) ownership.leases.add(options.lease);\n      }\n    } catch (error) {\n      for (const ownership of promoted) ownership.persistent = false;\n      for (const handler of installed) {\n        const ownership = this._handlerOwnership.get(handler);\n        if (ownership != null) this._uninstallHandler(handler, ownership);\n      }\n      throw error;\n    }\n    if (options.register) this._registerWithRoutedRoots();\n  }\n\n  private _installHandler(handler: TActionRuntimeHandler): IHandlerOwnership {\n    const handlerRouter = handler.getActionRouter();\n    const ownership: IHandlerOwnership = { persistent: false, leases: new Set() };\n    try {\n      this.actionRouter.addDomainsFromOther(handlerRouter);\n      if (handler.handlerType === EActionHandlerType.peer) {\n        ownership.unbind = handler._setIncomingActionDataListener(this, (json, metadata) =>\n          this.resolveIncomingActionPayload(json, metadata),\n        );\n        this._registeredPeerHandlers.push(handler);\n      }\n      for (const key of handlerRouter.getRegisteredKeys()) {\n        this.actionRouter.addForKey(key, handler);\n      }\n    } catch (error) {\n      this._uninstallHandler(handler, ownership);\n      throw error;\n    }\n    this._handlerOwnership.set(handler, ownership);\n    return ownership;\n  }\n\n  private _uninstallHandler(handler: TActionRuntimeHandler, ownership: IHandlerOwnership): void {\n    ownership.unbind?.();\n    this.actionRouter.removeRouteData(handler);\n    if (handler.handlerType === EActionHandlerType.peer) {\n      const peerIndex = this._registeredPeerHandlers.indexOf(handler);\n      if (peerIndex >= 0) this._registeredPeerHandlers.splice(peerIndex, 1);\n    }\n    this._handlerOwnership.delete(handler);\n  }\n\n  private _assertNoDuplicateLocalExecutors(handlers: TActionRuntimeHandler[]): void {\n    // Preserve the more fundamental wire-name collision diagnostic when definitions differ.\n    for (const handler of handlers) {\n      for (const domain of handler.getActionRouter().getDomains()) {\n        this.actionRouter.domainManager.assertCanAddDomain(domain);\n      }\n    }\n    const staged = new Map<string, TActionRuntimeHandler>();\n    for (const handler of handlers) {\n      if (handler.handlerType !== EActionHandlerType.local || this._handlerOwnership.has(handler)) {\n        continue;\n      }\n      for (const key of handler.getActionRouter().getRegisteredKeys()) {\n        const existing = this.actionRouter\n          .getForKey(key)\n          .find((candidate) => candidate.handlerType === EActionHandlerType.local);\n        const duplicate = existing ?? staged.get(key);\n        if (duplicate != null && duplicate !== handler) {\n          throw err_nice_action.fromId(EErrId_NiceAction.duplicate_action_executor, {\n            route: key,\n          });\n        }\n        staged.set(key, handler);\n      }\n    }\n  }\n\n  private _releaseHandlerLease(lease: symbol): void {\n    for (const [handler, ownership] of this._handlerOwnership) {\n      ownership.leases.delete(lease);\n      if (ownership.persistent || ownership.leases.size > 0) continue;\n      this._uninstallHandler(handler, ownership);\n    }\n  }\n\n  /**\n   * @internal Low-level primitive — the public way to open a connection is `connectChannel`, which\n   * derives routing from a channel and binds the crypto identity for you. This stays as the raw building\n   * block it sits on (it restates domain lists by hand) and is not part of the supported surface.\n   *\n   * Declare an external \"backend client\" in one call: build an\n   * {@link ChannelConnector} for `peer` carrying the given\n   * `transports`, route the listed `domains`/`actions` to it, register it (plus any\n   * `localHandlers` — e.g. server→client push handlers that share the same channel)\n   * on this runtime. Returns the external handler so the caller can\n   * later `clearTransportCache()` it.\n   */\n  connectTo(\n    peer: RuntimeCoordinate,\n    options: {\n      transports: Transport[];\n      domains?: ActionDomain<any>[];\n      actions?: ActionCore<any, any>[];\n      localHandlers?: TActionRuntimeHandler[];\n      defaultTimeout?: number;\n      reliableActionTimeout?: number;\n      wireMux?: import(\"@nice-code/wire\").WireProtocolMux;\n      /** The negotiated security level frame protocols ride at. */\n      securityLevel?: import(\"@nice-code/wire\").ESecurityLevel;\n      /** Auto-redial a protocol-carrying (realm) duplex link on drop. */\n      reconnect?: boolean;\n      /** @deprecated Use `reconnect`. */\n      keepLinkAlive?: boolean;\n      /**\n       * A per-connection identity for this link, replacing the runtime's coordinate as what it\n       * authenticates and stamps frames as — needed when this runtime holds *several* duplex links\n       * to the same peer. Derive it with `RuntimeCoordinate.withConnectionId`; `connectChannel`\n       * does that from its `connectionId` option.\n       */\n      connectionIdentity?: RuntimeCoordinate;\n    },\n  ): ChannelConnector {\n    const handler = new ChannelConnector({\n      peer,\n      transports: options.transports,\n      defaultTimeout: options.defaultTimeout,\n      reliableActionTimeout: options.reliableActionTimeout,\n      wireMux: options.wireMux,\n      localCoordinate: this.coordinate,\n      connectionIdentity: options.connectionIdentity,\n      securityLevel: options.securityLevel,\n      reconnect: options.reconnect ?? options.keepLinkAlive,\n    });\n\n    for (const domain of options.domains ?? []) {\n      handler.forDomain(domain);\n    }\n    for (const action of options.actions ?? []) {\n      handler.forAction(action);\n    }\n\n    this.addHandlers([handler, ...(options.localHandlers ?? [])]);\n\n    return handler;\n  }\n\n  private applyRuntimeForDomain(domain: ActionDomain<any>): void {\n    const rootDomain = domain.rootDomain;\n    if (!rootDomain._hasRuntime(this)) {\n      rootDomain._registerRuntime(this);\n      this._registeredRoots.add(rootDomain);\n    }\n  }\n\n  private _registerWithRoutedRoots(): void {\n    if (this.scope === \"instance\") return;\n    for (const domain of this.actionRouter.getDomains()) {\n      this.applyRuntimeForDomain(domain);\n    }\n  }\n\n  /**\n   * @deprecated Handler installation registers global runtimes automatically. Retained as an\n   * idempotent migration shim; it never registers an instance-scoped runtime.\n   */\n  apply(): this {\n    this._assertActive();\n    this._registerWithRoutedRoots();\n    return this;\n  }\n\n  async run<DOM extends IActionDomain, ID extends keyof DOM[\"actionSchema\"] & string>(\n    request: ActionPayload_Request<DOM, ID>,\n    options?: Omit<IExecuteActionOptions<DOM, ID>, \"targetLocalRuntime\">,\n  ): Promise<RunningAction<DOM, ID>> {\n    this._assertActive();\n    return request.run({ ...options, targetLocalRuntime: this });\n  }\n\n  /**\n   * Find the best registered external handler that can reach `originClient` directly.\n   * Used to locate the return-path channel for dispatching results back to the action origin.\n   * Returns `undefined` if no handler matches (score > 0 required, i.e. at least id must match).\n   *\n   * A handler that currently holds the origin's *live* connection always wins, regardless of its\n   * coordinate score — owning the live socket bound to the origin's exact coordinate (set from the\n   * handshake) is a strictly more precise match than a connector's declared `peer` score. This lets\n   * one server accept clients of several environments over a single acceptor. Only when no handler owns a\n   * live connection do we fall back to connector coordinate scoring.\n   */\n  getReturnHandlerForOrigin(originClient: RuntimeCoordinate): PeerLink | undefined {\n    if (originClient.envId === UNSET_RUNTIME_ENV_ID) return undefined;\n\n    let bestScore = -1;\n    let bestHandler: PeerLink | undefined;\n    let bestOwnedScore = -1;\n    let bestOwnedHandler: PeerLink | undefined;\n\n    for (const handler of this._registeredPeerHandlers) {\n      // Only a push-capable (duplex) link can deliver an unsolicited result back; an exchange-only\n      // (HTTP) handler returns its reply inline on the request, so skip it as a return-path candidate.\n      if (!handler.canPush) continue;\n      const score = originClient.similarityLevel(handler.peer);\n      if (score > bestScore) {\n        bestScore = score;\n        bestHandler = handler;\n      }\n      // Track the owning handler regardless of score; among several owners the higher score breaks the\n      // tie (first-registered on an all-equal tie, since `>` keeps the earlier one).\n      if (handler.ownsLiveConnectionFor(originClient) && score > bestOwnedScore) {\n        bestOwnedScore = score;\n        bestOwnedHandler = handler;\n      }\n    }\n\n    if (bestOwnedHandler != null) return bestOwnedHandler;\n    return bestScore > 0 ? bestHandler : undefined;\n  }\n\n  resetRuntime(): void {\n    this._assertActive();\n    for (const ra of this._pendingRunningActions.values()) {\n      ra._abort(err_nice_action.fromId(EErrId_NiceAction.runtime_reset));\n    }\n\n    for (const handler of this._registeredPeerHandlers) {\n      handler.clearTransportCache();\n    }\n  }\n\n  dispose(): void {\n    if (this._disposed) return;\n    this._disposed = true;\n\n    for (const root of this._registeredRoots) root._unregisterRuntime(this);\n    this._registeredRoots.clear();\n\n    if (this._pendingRunningActions.size > 0) {\n      const error = err_nice_action.fromId(EErrId_NiceAction.runtime_disposed, {\n        runtime: this.coordinate.stringId,\n      });\n      for (const running of this._pendingRunningActions.values()) running._abort(error);\n    }\n    this._pendingRunningActions.clear();\n\n    for (const handler of this._registeredPeerHandlers) {\n      const disposable = handler as PeerLink & { dispose?: () => void };\n      if (typeof disposable.dispose === \"function\") disposable.dispose();\n      else handler.clearTransportCache();\n    }\n    for (const [handler, ownership] of this._handlerOwnership) {\n      ownership.unbind?.();\n      this.actionRouter.removeRouteData(handler);\n    }\n    this._handlerOwnership.clear();\n    this._registeredPeerHandlers.length = 0;\n  }\n\n  private _trySetupReturnDispatch(runningAction: RunningAction<any, any>): void {\n    // Fire-and-forget actions get no reply — the sender never waits for one. Skip the return path\n    // entirely (the inbound push was handled locally; that's the whole contract).\n    if (runningAction.context.schema.responseMode === EActionResponseMode.none) {\n      return;\n    }\n\n    const originClient = runningAction.context.originClient;\n\n    if (\n      originClient.envId === UNSET_RUNTIME_ENV_ID ||\n      originClient.isSameFor(this._coordinate).id\n    ) {\n      return;\n    }\n\n    // Replies follow the arrival. An exchange (HTTP) arrival is answered inline on its own response,\n    // so it never selects a socket, even when the origin it names is authenticated and connected.\n    const arrival = runningAction.context._getReceiverMetadata();\n    if (arrival != null && !(arrival.receiver instanceof PeerLink)) return;\n    const arrivalLink = arrival?.receiver instanceof PeerLink ? arrival.receiver : undefined;\n\n    runningAction.addUpdateListeners([\n      (update) => {\n        if (\n          update.type === ERunningActionUpdateType.finished &&\n          update.finishType === ERunningActionFinishedType.success\n        ) {\n          if (this._disposed) return;\n          const returnHandler =\n            arrivalLink != null\n              ? this._registeredPeerHandlers.includes(arrivalLink) && arrivalLink.canPush\n                ? arrivalLink\n                : undefined\n              : this.getReturnHandlerForOrigin(originClient);\n          if (returnHandler == null) return;\n          // The response may carry a fresh context (a handler-returned or forwarded result JSON),\n          // so the request's arrival travels explicitly.\n          returnHandler\n            .sendReturnPayload(update.response, { targetLocalRuntime: this, arrival })\n            .catch(() => {});\n        }\n      },\n    ]);\n  }\n}\n\nconst runtimeState: {\n  defaultLocalRuntime?: ActionRuntime;\n  assumedRuntimeInfo?: IRuntimeMeta;\n} = {\n  defaultLocalRuntime: undefined,\n  assumedRuntimeInfo: undefined,\n};\n\nfunction getDefaultActionRuntime(): ActionRuntime {\n  if (runtimeState.assumedRuntimeInfo == null) {\n    runtimeState.assumedRuntimeInfo = getAssumedRuntimeInfo();\n  }\n\n  if (runtimeState.defaultLocalRuntime == null) {\n    runtimeState.defaultLocalRuntime = new ActionRuntime(\n      RuntimeCoordinate.unknown.specify({\n        perId: `${runtimeState.assumedRuntimeInfo?.runtimeName ?? \"unknown\"}-runtime`,\n      }),\n    );\n  }\n\n  return runtimeState.defaultLocalRuntime;\n}\n","import { castNiceError, type NiceError, niceTryAsync } from \"@nice-code/error\";\nimport type { ActionCore } from \"../../../ActionDefinition/Action/Core/ActionCore\";\nimport type { IActionRouteItemHandler } from \"../../../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport { ActionPayload_Request } from \"../../../ActionDefinition/Action/Payload/ActionPayload_Request\";\nimport { ActionPayload_Result } from \"../../../ActionDefinition/Action/Payload/ActionPayload_Result\";\nimport { RunningAction } from \"../../../ActionDefinition/Action/RunningAction\";\nimport type { ActionDomain } from \"../../../ActionDefinition/Domain/ActionDomain\";\nimport type { IActionDomain } from \"../../../ActionDefinition/Domain/ActionDomain.types\";\nimport { EErrId_NiceAction, err_nice_action } from \"../../../errors/err_nice_action\";\nimport { isActionPayload_Result_JsonObject } from \"../../../utils/isActionPayload_Result_JsonObject\";\nimport { ActionRuntime } from \"../../ActionRuntime\";\nimport { peekHandlerCuid, popHandlerCuid, pushHandlerCuid } from \"../../HandlerCallStack\";\nimport { ActionRouter } from \"../../Routing/ActionRouter\";\nimport { EActionRouterContextType } from \"../../Routing/ActionRouter.types\";\nimport { ActionHandler } from \"../ActionHandler\";\nimport {\n  EActionHandlerType,\n  type IActionHandler_Local,\n  type IActionHandler_Local_Json,\n  type IActionHandlerContext,\n  type IHandleActionOptions,\n} from \"../ActionHandler.types\";\nimport type { THandleActionExecutionFn } from \"./ActionLocalHandler.types\";\n\nexport class ActionLocalHandler\n  extends ActionHandler<EActionHandlerType.local>\n  implements IActionHandler_Local\n{\n  readonly handlerType = EActionHandlerType.local;\n  readonly actionRouter: ActionRouter<THandleActionExecutionFn<any, any>> = new ActionRouter({\n    contextType: EActionRouterContextType.handler_route,\n    handler: this,\n  });\n\n  constructor() {\n    super();\n  }\n\n  /**\n   * Register a handler for all actions in a domain.\n   * Receives the full primed action — use `matchAction()` to narrow to a specific action id.\n   * Useful for forwarding all domain actions to a remote endpoint.\n   * Lower priority than `forAction`.\n   */\n  forDomain<FOR_DOM extends IActionDomain>(\n    domain: ActionDomain<FOR_DOM>,\n    handler: THandleActionExecutionFn<FOR_DOM>,\n  ): this {\n    this.actionRouter.forDomain(domain, handler);\n    return this;\n  }\n\n  /**\n   * Register a handler for a base action instance. Takes priority over domain-wide handlers.\n   * Receives the full primed action with narrowed input type.\n   * Useful for handling specific actions locally while forwarding the rest of the domain. For example, a local \"ping\" action that checks connectivity without needing a round trip.\n   */\n  forAction<ACT_DOM extends IActionDomain, ID extends keyof ACT_DOM[\"actionSchema\"] & string>(\n    action: ActionCore<ACT_DOM, ID>,\n    handler: THandleActionExecutionFn<ACT_DOM, ID>,\n  ): this {\n    this.actionRouter.forAction(action, handler);\n    return this;\n  }\n\n  /**\n   * @deprecated Prefer `forAction`, `forDomainActionCases`, or an exhaustive\n   * `domain.wrapAsLocalHandler` map. Retained for this migration release.\n   *\n   * Register a handler for multiple action IDs (first-match-wins among cases).\n   * Receives the full primed action narrowed to the union of those IDs.\n   * Use `act.coreAction.id` to branch on which action was dispatched.\n   */\n  forActionIds<\n    ACT_DOM extends IActionDomain,\n    IDS extends ReadonlyArray<keyof ACT_DOM[\"actionSchema\"] & string>,\n  >(\n    domain: ActionDomain<ACT_DOM>,\n    ids: IDS,\n    handler: THandleActionExecutionFn<ACT_DOM, IDS[number]>,\n  ): this {\n    this.actionRouter.forActionIds(domain, ids, handler);\n    return this;\n  }\n\n  /**\n   * Register per-action handlers for a domain using a single map, without needing\n   * separate `forAction` calls. Unregistered action IDs are unaffected.\n   *\n   * @example\n   * ```ts\n   * handler.forDomainActionCases(userDomain, {\n   *   getUser:    (primed) => db.getUser(primed.input.userId),\n   *   deleteUser: (primed) => db.deleteUser(primed.input.userId),\n   * });\n   * ```\n   */\n  forDomainActionCases<FOR_DOM extends IActionDomain>(\n    domain: ActionDomain<FOR_DOM>,\n    cases: {\n      [ID in keyof FOR_DOM[\"actionSchema\"] & string]?: THandleActionExecutionFn<FOR_DOM, ID>;\n    },\n  ): this {\n    this.actionRouter.forDomainActionCases(domain, cases);\n    return this;\n  }\n\n  async handleActionRequest<\n    DOM extends IActionDomain,\n    ID extends keyof DOM[\"actionSchema\"] & string,\n  >(\n    action: ActionPayload_Request<DOM, ID>,\n    config?: IHandleActionOptions,\n  ): Promise<RunningAction<DOM, ID>> {\n    const targetLocalRuntime = config?.targetLocalRuntime ?? ActionRuntime.getDefault();\n\n    const handler = this.actionRouter.getRouteDataForActionOrThrow(action, {\n      targetLocalRuntime,\n    });\n\n    action.context.addRouteItem({\n      runtime: targetLocalRuntime.coordinate,\n      handler: this.toHandlerRouteItem(),\n      time: Date.now(),\n    });\n\n    const runningAction = new RunningAction<DOM, ID>({\n      context: action.context,\n      request: action,\n      parentCuid: peekHandlerCuid(),\n      callSite: targetLocalRuntime._captureActionCallSite(action, config?.captureCallSites),\n    });\n    // `_handleRunningAction` funnels every outcome (handler throw, output-validation\n    // throw, foreign throw) into a deterministic result via `niceTryAsync`, and settles\n    // the running action itself when even that result cannot be built.\n    void this._handleRunningAction(handler, runningAction, targetLocalRuntime);\n    return runningAction;\n  }\n\n  private async _handleRunningAction(\n    handler: THandleActionExecutionFn<any, any>,\n    runningAction: RunningAction<any, any>,\n    runtime: ActionRuntime,\n  ) {\n    const state = runningAction.state;\n\n    if (state.result != null) {\n      return;\n    }\n\n    // Yield before pushing so that sibling actions dispatched in the same synchronous\n    // frame have already read their parentCuid (which they do synchronously in\n    // handleActionRequest) before we mutate the stack. Without this, a concurrent\n    // sibling's peek would see our cuid and incorrectly treat us as its parent.\n    // Truly nested child actions (dispatched from inside the handler body below) still\n    // see our cuid correctly because the push happens before we call handler().\n    await Promise.resolve();\n\n    pushHandlerCuid(runningAction.cuid);\n    try {\n      // Everything that can fail — the handler itself and result normalization\n      // (output validation, payload hydration) — runs inside the funnel so any\n      // throw becomes a `{ ok: false }` result rather than an unhandled rejection.\n      const ran = await niceTryAsync(async (): Promise<ActionPayload_Result<any, any>> => {\n        const metadata = state.request.context._getReceiverMetadata();\n        const context: IActionHandlerContext = {\n          runtime,\n          origin: state.request.context.originClient,\n          authenticatedOrigin:\n            metadata?.originAuthenticated === true ? state.request.context.originClient : undefined,\n          securityLevel: metadata?.securityLevel,\n          reliability: state.request.context.reliability,\n          run: (request, options) => runtime.run(request, options),\n        };\n        const rawResult = await handler(state.request, context);\n\n        if (rawResult instanceof ActionPayload_Result) {\n          return rawResult;\n        }\n        if (rawResult != null && isActionPayload_Result_JsonObject(rawResult)) {\n          const domain = this.actionRouter.domainManager.getActionDomainOrThrow(state.request);\n          return domain.hydrateResultPayload(rawResult);\n        }\n        return state.request.successResult(rawResult);\n      });\n\n      let result: ActionPayload_Result<any, any>;\n      try {\n        result = ran.ok ? ran.output : this._errorResult(state.request, ran.error);\n      } catch (error) {\n        // No result could be built at all: reject the waiter instead of leaving it pending.\n        runningAction._failWithError(error);\n        return;\n      }\n      runningAction._completeWithResult(result);\n    } finally {\n      popHandlerCuid();\n    }\n  }\n\n  /**\n   * Building an error result classifies the error, which reads it (`isExact`, `hasId`). An error\n   * that cannot be read still has to answer, so the result becomes the cast of what reading threw.\n   */\n  private _errorResult(\n    request: ActionPayload_Request<any, any>,\n    error: NiceError<any, any>,\n  ): ActionPayload_Result<any, any> {\n    try {\n      return request.errorResult(error);\n    } catch (unreadable) {\n      return request.errorResult(castNiceError(unreadable));\n    }\n  }\n\n  async handlePayloadWireOrThrow(\n    wire: unknown,\n    config?: IHandleActionOptions,\n  ): Promise<RunningAction<any, any>> {\n    const hydratedAction = this.actionRouter.domainManager.hydrateActionPayload(wire as any);\n\n    if (!(hydratedAction instanceof ActionPayload_Request)) {\n      throw err_nice_action.fromId(EErrId_NiceAction.wire_action_not_payload, {\n        domain: hydratedAction.domain,\n        actionId: hydratedAction.id,\n        actionState: (hydratedAction as any).type ?? (hydratedAction as any).form,\n      });\n    }\n\n    return await this.handleActionRequest(hydratedAction, config);\n  }\n\n  toJsonObject(): IActionHandler_Local_Json {\n    return {\n      type: this.handlerType,\n    };\n  }\n\n  toHandlerRouteItem(): IActionRouteItemHandler {\n    return {\n      type: this.handlerType,\n    };\n  }\n}\n\nexport const createLocalHandler = () => {\n  return new ActionLocalHandler();\n};\n","import { EActionForm } from \"../ActionDefinition/Action/ActionBase.types\";\nimport type { IActionContext_JsonObject } from \"../ActionDefinition/Action/Context/ActionContext.types\";\nimport { isAction_Base_JsonObject } from \"./isAction_Base_JsonObject\";\n\nexport const isAction_Context_JsonObject = (obj: unknown): obj is IActionContext_JsonObject => {\n  return isAction_Base_JsonObject(obj) && obj.form === EActionForm.context;\n};\n","import { EActionForm } from \"../ActionDefinition/Action/ActionBase.types\";\nimport type { IActionCore_JsonObject } from \"../ActionDefinition/Action/Core/ActionCore.types\";\nimport { isAction_Base_JsonObject } from \"./isAction_Base_JsonObject\";\n\nexport const isAction_Core_JsonObject = (obj: unknown): obj is IActionCore_JsonObject => {\n  return isAction_Base_JsonObject(obj) && obj.form === EActionForm.core;\n};\n","import type { TAction_Any_JsonObject } from \"../ActionDefinition/Action/Action.combined.types\";\nimport { isAction_Context_JsonObject } from \"./isAction_Context_JsonObject\";\nimport { isAction_Core_JsonObject } from \"./isAction_Core_JsonObject\";\nimport { isActionPayload_Any_JsonObject } from \"./isActionPayload_Any_JsonObject\";\n\nexport function isAction_Any_JsonObject(obj: unknown): obj is TAction_Any_JsonObject {\n  return (\n    isActionPayload_Any_JsonObject(obj) ||\n    isAction_Context_JsonObject(obj) ||\n    isAction_Core_JsonObject(obj)\n  );\n}\n","import type { IActionBase_JsonObject } from \"../ActionDefinition/Action/ActionBase.types\";\nimport { EErrId_NiceAction, err_nice_action } from \"../errors/err_nice_action\";\nimport { isAction_Any_JsonObject } from \"./isAction_Any_JsonObject\";\n\nexport function assertIsActionJson(obj: unknown): asserts obj is IActionBase_JsonObject {\n  if (!isAction_Any_JsonObject(obj)) {\n    throw err_nice_action.fromId(EErrId_NiceAction.wire_not_action_data);\n  }\n}\n","import type { TAction_Any_Instance } from \"../ActionDefinition/Action/Action.combined.types\";\nimport type { IActionBase } from \"../ActionDefinition/Action/ActionBase.types\";\nimport { ActionContext } from \"../ActionDefinition/Action/Context/ActionContext\";\nimport { ActionCore } from \"../ActionDefinition/Action/Core/ActionCore\";\nimport { ActionPayload } from \"../ActionDefinition/Action/Payload/ActionPayload\";\n\nexport function isAction_Any_Instance<ACT extends IActionBase<any, any>>(\n  value: unknown | ACT,\n): value is TAction_Any_Instance<any, any> {\n  return (\n    value instanceof ActionCore || value instanceof ActionPayload || value instanceof ActionContext\n  );\n}\n","import type {\n  TDistributeRunningActionUpdateListener,\n  TRunningActionUpdateListener,\n} from \"../Action/RunningAction.types\";\nimport type { IActionDomain } from \"./ActionDomain.types\";\n\nexport abstract class ActionDomainBase<ACT_DOM extends IActionDomain = IActionDomain>\n  implements IActionDomain<ACT_DOM[\"allDomains\"], ACT_DOM[\"actionSchema\"]>\n{\n  readonly domain: ACT_DOM[\"domain\"];\n  readonly allDomains: ACT_DOM[\"allDomains\"];\n  readonly actionSchema: ACT_DOM[\"actionSchema\"];\n\n  protected _listeners: TRunningActionUpdateListener<any, any>[] = [];\n\n  constructor(definition: ACT_DOM) {\n    this.domain = definition.domain;\n    this.allDomains = definition.allDomains;\n    this.actionSchema = definition.actionSchema;\n  }\n\n  /**\n   * Add an observer that is called after every action dispatched through this domain.\n   * Returns an unsubscribe function — call it to remove the listener.\n   */\n  addActionListener(\n    listener: TDistributeRunningActionUpdateListener<\n      ACT_DOM,\n      keyof ACT_DOM[\"actionSchema\"] & string\n    >,\n  ): () => void {\n    this._listeners.push(listener as TRunningActionUpdateListener<any, any>);\n    return () => {\n      this._listeners = this._listeners.filter((l) => l !== listener);\n    };\n  }\n\n  /**\n   * @internal\n   * Observers registered directly on this domain via {@link addActionListener}.\n   * Used to wire observers (e.g. devtools) onto RunningActions that aren't created\n   * through the local-dispatch path — notably inbound actions pushed from a backend\n   * or another client over a bidirectional transport.\n   */\n  _getActionObservers(): TRunningActionUpdateListener<any, any>[] {\n    return this._listeners;\n  }\n}\n","import type { TActionPayload_Any_Instance } from \"../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport { EErrId_NiceAction, err_nice_action } from \"../errors/err_nice_action\";\nimport type { ActionRuntime } from \"./ActionRuntime\";\nimport type { IActionHandlerAndRuntime, IActionRuntimeManagerContext } from \"./ActionRuntime.types\";\nimport type { IHandleActionOptions } from \"./Handler/ActionHandler.types\";\n\n/** Root-domain registry. Object identity is the key; coordinates may legitimately match. */\nexport class ActionRuntimeManager {\n  private readonly _runtimes = new Set<ActionRuntime>();\n  private readonly _context: IActionRuntimeManagerContext;\n\n  constructor(context?: IActionRuntimeManagerContext) {\n    this._context = context ?? {};\n  }\n\n  registerRuntime(runtime: ActionRuntime): void {\n    runtime._assertActive();\n    this._runtimes.add(runtime);\n  }\n\n  unregisterRuntime(runtime: ActionRuntime): void {\n    this._runtimes.delete(runtime);\n  }\n\n  getRuntimeAndHandlerForAction(\n    action: TActionPayload_Any_Instance<any, any>,\n    options?: IHandleActionOptions,\n    throwOnIssue?: boolean,\n  ): IActionHandlerAndRuntime | undefined {\n    const localRuntime = options?.targetLocalRuntime;\n    if (localRuntime != null) {\n      localRuntime._assertActive();\n      const handler = localRuntime._getHandlerForAction(action, options);\n      if (handler != null) return { handler, runtime: localRuntime };\n      if (throwOnIssue) {\n        throw err_nice_action.fromId(EErrId_NiceAction.no_action_execution_handler, {\n          domain: action.domain,\n          actionId: action.id,\n          specifiedClient: localRuntime.coordinate,\n        });\n      }\n      return undefined;\n    }\n\n    // Keep the common one-runtime path allocation-free. A second eligible runtime changes the\n    // answer into a stable error in every build, so construction order never selects production code.\n    let selected: IActionHandlerAndRuntime | undefined;\n    let ambiguousRuntimeIds: string[] | undefined;\n    for (const runtime of this._runtimes) {\n      if (runtime.disposed) continue;\n      const handler = runtime._getHandlerForAction(action);\n      if (handler == null) continue;\n      if (selected == null) {\n        selected = { handler, runtime };\n      } else {\n        ambiguousRuntimeIds ??= [selected.runtime.coordinate.stringId];\n        ambiguousRuntimeIds.push(runtime.coordinate.stringId);\n      }\n    }\n\n    if (ambiguousRuntimeIds != null) {\n      throw err_nice_action.fromId(EErrId_NiceAction.ambiguous_action_runtime, {\n        domain: action.domain,\n        actionId: action.id,\n        runtimes: ambiguousRuntimeIds,\n      });\n    }\n    if (selected != null) return selected;\n\n    if (throwOnIssue && this._runtimes.size === 0) {\n      throw err_nice_action.fromId(EErrId_NiceAction.no_client_runtimes_registered, {\n        context: this._context,\n      });\n    }\n    if (throwOnIssue) {\n      throw err_nice_action.fromId(EErrId_NiceAction.no_action_execution_handler, {\n        domain: action.domain,\n        actionId: action.id,\n      });\n    }\n    return undefined;\n  }\n\n  getRuntimeAndHandlerForActionOrThrow(\n    action: TActionPayload_Any_Instance<any, any>,\n    options?: IHandleActionOptions,\n  ): IActionHandlerAndRuntime {\n    return this.getRuntimeAndHandlerForAction(action, options, true)!;\n  }\n\n  hasRuntime(runtime: ActionRuntime): boolean {\n    return this._runtimes.has(runtime);\n  }\n}\n","import type { ActionRuntime } from \"../../ActionRuntime/ActionRuntime\";\nimport type { IActionHandlerAndRuntime } from \"../../ActionRuntime/ActionRuntime.types\";\nimport { ActionRuntimeManager } from \"../../ActionRuntime/ActionRuntimeManager\";\nimport type { IExecuteActionOptions } from \"../../ActionRuntime/Handler/ActionHandler.types\";\nimport { EErrId_NiceAction, err_nice_action } from \"../../errors/err_nice_action\";\nimport type { ActionPayload_Request } from \"../Action/Payload/ActionPayload_Request\";\nimport { RunningAction } from \"../Action/RunningAction\";\nimport { ActionDomain } from \"./ActionDomain\";\nimport type {\n  IActionDomain,\n  IActionDomainChildOptions,\n  IActionRootDomain,\n  TActionDomainChildDef,\n} from \"./ActionDomain.types\";\nimport { ActionDomainBase } from \"./ActionDomainBase\";\n\nexport class ActionRootDomain<\n  ROOT_DOM extends IActionRootDomain = IActionRootDomain,\n> extends ActionDomainBase<ROOT_DOM> {\n  private _actionRuntimeManager: ActionRuntimeManager;\n\n  constructor(\n    readonly domainDefinition: {\n      domain: ROOT_DOM[\"domain\"];\n    },\n  ) {\n    const domainId = domainDefinition.domain;\n\n    super({\n      domain: domainId,\n      allDomains: [domainId],\n      actionSchema: {},\n    } as ROOT_DOM);\n\n    this._actionRuntimeManager = new ActionRuntimeManager({ domain: domainId });\n  }\n\n  createChildDomain<SUB_DOM extends IActionDomainChildOptions>(\n    subDomainDef: SUB_DOM & {\n      [K in Exclude<keyof SUB_DOM, keyof IActionDomainChildOptions>]: never;\n    },\n  ): ActionDomain<TActionDomainChildDef<ROOT_DOM, SUB_DOM>> {\n    if (this.allDomains.includes(subDomainDef.domain)) {\n      throw err_nice_action.fromId(EErrId_NiceAction.domain_already_exists_in_hierarchy, {\n        domain: subDomainDef.domain,\n        allParentDomains: this.allDomains,\n        parentDomain: this.domain,\n      });\n    }\n\n    return new ActionDomain<TActionDomainChildDef<ROOT_DOM, SUB_DOM>>(\n      {\n        allDomains: [...this.allDomains, subDomainDef.domain],\n        domain: subDomainDef.domain,\n        actionSchema: subDomainDef.actions,\n      },\n      { rootDomain: this },\n    );\n  }\n\n  _registerRuntime(runtime: ActionRuntime): void {\n    this._actionRuntimeManager.registerRuntime(runtime);\n  }\n\n  _unregisterRuntime(runtime: ActionRuntime): void {\n    this._actionRuntimeManager.unregisterRuntime(runtime);\n  }\n\n  _hasRuntime(runtime: ActionRuntime): boolean {\n    return this._actionRuntimeManager.hasRuntime(runtime);\n  }\n\n  async _runAction<\n    DOM extends IActionDomain,\n    ID extends keyof DOM[\"actionSchema\"] & string = keyof DOM[\"actionSchema\"] & string,\n    ACT extends ActionPayload_Request<DOM, ID> = ActionPayload_Request<DOM, ID>,\n  >(actionPayload: ACT, options?: IExecuteActionOptions<DOM, ID>): Promise<RunningAction<DOM, ID>> {\n    const allListeners = [...this._listeners, ...(options?.listeners ?? [])];\n\n    let handlerAndRuntime: IActionHandlerAndRuntime;\n    try {\n      handlerAndRuntime = this._actionRuntimeManager.getRuntimeAndHandlerForActionOrThrow(\n        actionPayload,\n        options,\n      );\n    } catch (err) {\n      const runningAction = new RunningAction<DOM, ID>({\n        context: actionPayload.context,\n        request: actionPayload,\n        callSite: actionPayload._callSite,\n      });\n      runningAction.addUpdateListeners(allListeners);\n      runningAction._failWithError(err);\n      throw err;\n    }\n\n    const { handler, runtime } = handlerAndRuntime;\n\n    runtime._captureActionCallSite(actionPayload, options?.captureCallSites);\n\n    actionPayload.context._setOriginClient(runtime.coordinate);\n\n    const runningAction = await handler.handleActionRequest(actionPayload, {\n      targetLocalRuntime: runtime,\n      timeout: options?.timeout,\n      // Forward the reliable-delivery streamKey (E3) so the connector can scope an independent stream.\n      streamKey: options?.streamKey,\n      captureCallSites: options?.captureCallSites,\n    });\n\n    runningAction.addUpdateListeners(allListeners);\n\n    return runningAction;\n  }\n}\n","import { castNiceError } from \"@nice-code/error\";\nimport { RuntimeCoordinate } from \"@nice-code/wire\";\nimport type { ActionRuntime } from \"../../ActionRuntime/ActionRuntime\";\nimport type { IExecuteActionOptions } from \"../../ActionRuntime/Handler/ActionHandler.types\";\nimport { ActionLocalHandler } from \"../../ActionRuntime/Handler/Local/ActionLocalHandler\";\nimport { EErrId_NiceAction, err_nice_action } from \"../../errors/err_nice_action\";\nimport { assertIsActionJson } from \"../../utils/assertIsActionJson\";\nimport { isAction_Any_Instance } from \"../../utils/isAction_Any_Instance\";\nimport type {\n  TAction_Any_JsonObject,\n  TDistributeActionPayload_Request,\n  TDistributeActionPayload_Result,\n  TDistributedDomainActions,\n  TNarrowActionJsonTypeToActionInstanceType,\n} from \"../Action/Action.combined.types\";\nimport { EActionForm, type IActionBase } from \"../Action/ActionBase.types\";\nimport { ActionContext } from \"../Action/Context/ActionContext\";\nimport type { IActionContext_Data_JsonObject } from \"../Action/Context/ActionContext.types\";\nimport { ActionCore } from \"../Action/Core/ActionCore\";\nimport {\n  EActionPayloadType,\n  type IActionPayload_Request_JsonObject,\n  type IActionPayload_Result_JsonObject,\n} from \"../Action/Payload/ActionPayload.types\";\nimport { ActionPayload_Request } from \"../Action/Payload/ActionPayload_Request\";\nimport { ActionPayload_Result } from \"../Action/Payload/ActionPayload_Result\";\nimport type { RunningAction } from \"../Action/RunningAction\";\nimport type { TRunningActionUpdateListener } from \"../Action/RunningAction.types\";\nimport type {\n  IActionDomain,\n  IActionDomainChildOptions,\n  TActionDomainChildDef,\n  TWrappableDomainActionHandler,\n} from \"./ActionDomain.types\";\nimport { ActionDomainBase } from \"./ActionDomainBase\";\nimport { type ActionRootDomain } from \"./ActionRootDomain\";\n\ntype TActionMap<ACT_DOM extends IActionDomain> = {\n  [K in keyof ACT_DOM[\"actionSchema\"] & string]: ActionCore<ACT_DOM, K>;\n};\n\nexport class ActionDomain<\n  ACT_DOM extends IActionDomain = IActionDomain,\n> extends ActionDomainBase<ACT_DOM> {\n  private _rootDomain: ActionRootDomain<any>;\n  private readonly _actionMap: TActionMap<ACT_DOM>;\n\n  constructor(\n    definition: ACT_DOM,\n    {\n      rootDomain,\n    }: {\n      rootDomain: ActionRootDomain<any>;\n    },\n  ) {\n    super(definition);\n    this._rootDomain = rootDomain;\n    this._actionMap = this.createActionMap();\n  }\n\n  get rootDomain() {\n    return this._rootDomain;\n  }\n\n  /**\n   * @internal\n   * All action observers that should see actions on this domain: the root domain's\n   * observers plus this subdomain's own. Mirrors the listener set the local-dispatch\n   * path assembles in `runAction`/`_runAction`, so inbound actions (pushed from a\n   * backend or another client) can be wired up identically and surface in devtools.\n   */\n  _collectActionObservers(): TRunningActionUpdateListener<any, any>[] {\n    return [...this._rootDomain._getActionObservers(), ...this._getActionObservers()];\n  }\n\n  _registerRuntime(runtime: ActionRuntime): void {\n    this._rootDomain._registerRuntime(runtime);\n  }\n\n  createChildDomain<SUB_DOM extends IActionDomainChildOptions>(\n    subDomainDef: SUB_DOM & {\n      [K in Exclude<keyof SUB_DOM, keyof IActionDomainChildOptions>]: never;\n    },\n  ): ActionDomain<TActionDomainChildDef<ACT_DOM, SUB_DOM>> {\n    if (this.allDomains.includes(subDomainDef.domain)) {\n      throw err_nice_action.fromId(EErrId_NiceAction.domain_already_exists_in_hierarchy, {\n        domain: subDomainDef.domain,\n        allParentDomains: this.allDomains,\n        parentDomain: this.domain,\n      });\n    }\n\n    return new ActionDomain<TActionDomainChildDef<ACT_DOM, SUB_DOM>>(\n      {\n        allDomains: [...this.allDomains, subDomainDef.domain],\n        domain: subDomainDef.domain,\n        actionSchema: subDomainDef.actions,\n      },\n      { rootDomain: this._rootDomain },\n    );\n  }\n\n  get action(): TActionMap<ACT_DOM> {\n    return this._actionMap;\n  }\n\n  actionsMap(): TActionMap<ACT_DOM> {\n    return this._actionMap;\n  }\n\n  actionForId<ID extends keyof ACT_DOM[\"actionSchema\"] & string>(id: ID): ActionCore<ACT_DOM, ID> {\n    const actionSchema = this.actionSchema[id];\n    if (!actionSchema) {\n      throw err_nice_action.fromId(EErrId_NiceAction.action_id_not_in_domain, {\n        domain: this.domain,\n        actionId: id as string,\n      });\n    }\n\n    return new ActionCore<ACT_DOM, ID>(this, id);\n  }\n\n  wrapAsPartialLocalHandler(\n    wrappedActionExecutor: Partial<TWrappableDomainActionHandler<ACT_DOM>>,\n  ): ActionLocalHandler {\n    const _handler = new ActionLocalHandler();\n    const executor = wrappedActionExecutor as unknown as Record<\n      string,\n      (input: any, ctx: any) => any\n    >;\n\n    for (const actionKey in wrappedActionExecutor) {\n      if (!this.actionSchema[actionKey]) {\n        continue;\n      }\n\n      _handler.forAction(this.actionForId(actionKey), (request, context) =>\n        executor[request.id](request.input, context),\n      );\n    }\n\n    return _handler;\n  }\n\n  wrapAsLocalHandler(\n    wrappedActionExecutor: TWrappableDomainActionHandler<ACT_DOM>,\n  ): ActionLocalHandler {\n    const _handler = new ActionLocalHandler();\n    const executor = wrappedActionExecutor as unknown as Record<\n      string,\n      (input: any, ctx: any) => any\n    >;\n    return _handler.forDomain(this, (request, context) =>\n      executor[request.id](request.input, context),\n    );\n  }\n\n  hydrateContext<ID extends keyof ACT_DOM[\"actionSchema\"] & string>(\n    id: ID,\n    contextData: IActionContext_Data_JsonObject,\n  ): ActionContext<ACT_DOM, ID> {\n    return new ActionContext(this, id, {\n      timeCreated: contextData.timeCreated,\n      cuid: contextData.cuid,\n      routing: contextData.routing.map((item) => {\n        return {\n          runtime: new RuntimeCoordinate(item.runtime),\n          handler: item.handler,\n          time: item.time,\n        };\n      }),\n      originClient: contextData.originClient\n        ? new RuntimeCoordinate(contextData.originClient)\n        : RuntimeCoordinate.unknown,\n    });\n  }\n\n  isDomainAction<ACT extends IActionBase<any, ACT_DOM, any>>(\n    action: ACT | unknown | null | undefined,\n  ): action is TDistributedDomainActions<ACT_DOM, ACT> {\n    return isAction_Any_Instance(action) && action.domain === this.domain;\n  }\n\n  hydrateRequestPayload<\n    ID extends keyof ACT_DOM[\"actionSchema\"] & string,\n    P extends IActionPayload_Request_JsonObject<ACT_DOM, ID>,\n  >(serialized: P): TDistributeActionPayload_Request<ACT_DOM, ID> {\n    if (serialized.type !== EActionPayloadType.request) {\n      throw err_nice_action.fromId(EErrId_NiceAction.hydration_action_state_mismatch, {\n        expected: EActionPayloadType.request,\n        received: serialized.type,\n      });\n    }\n\n    if (serialized.domain !== this.domain) {\n      throw err_nice_action.fromId(EErrId_NiceAction.hydration_domain_mismatch, {\n        expected: this.domain,\n        received: serialized.domain,\n      });\n    }\n\n    const id = serialized.id;\n    if (!this.actionSchema[id]) {\n      throw err_nice_action.fromId(EErrId_NiceAction.hydration_action_id_not_found, {\n        domain: this.domain,\n        actionId: serialized.id,\n      });\n    }\n\n    const contextAction = this.hydrateContext(id, serialized.context);\n\n    return new ActionPayload_Request(\n      { context: contextAction },\n      contextAction.deserializeInput(serialized.input),\n      {\n        time: serialized.time,\n      },\n    ) as TDistributeActionPayload_Request<ACT_DOM, ID>;\n  }\n\n  hydrateResultPayload<\n    ID extends keyof ACT_DOM[\"actionSchema\"] & string,\n    R extends IActionPayload_Result_JsonObject<ACT_DOM, ID>,\n  >(serialized: R): TDistributeActionPayload_Result<ACT_DOM, ID> {\n    if (serialized.type !== EActionPayloadType.result) {\n      throw err_nice_action.fromId(EErrId_NiceAction.hydration_action_state_mismatch, {\n        expected: EActionPayloadType.result,\n        received: serialized.type,\n      });\n    }\n\n    if (serialized.domain !== this.domain) {\n      throw err_nice_action.fromId(EErrId_NiceAction.hydration_domain_mismatch, {\n        expected: this.domain,\n        received: serialized.domain,\n      });\n    }\n\n    const id = serialized.id;\n\n    if (!this.actionSchema[id]) {\n      throw err_nice_action.fromId(EErrId_NiceAction.hydration_action_id_not_found, {\n        domain: this.domain,\n        actionId: serialized.id,\n      });\n    }\n\n    const contextAction = this.hydrateContext(id, serialized.context);\n\n    const result = serialized.result.ok\n      ? {\n          ok: true as const,\n          output: contextAction.schema.deserializeOutput(serialized.result.output),\n        }\n      : // Reconstruct the wire error into a real NiceError so `expected` can be\n        // re-derived against this side's schema and `error` carries its methods.\n        { ok: false as const, error: castNiceError(serialized.result.error) };\n\n    return new ActionPayload_Result({ context: contextAction }, result, {\n      time: serialized.time,\n    }) as TDistributeActionPayload_Result<ACT_DOM, ID>;\n  }\n\n  hydrateAnyAction<\n    ID extends keyof ACT_DOM[\"actionSchema\"] & string,\n    AJ extends TAction_Any_JsonObject<ACT_DOM, ID>,\n  >(actionJson: AJ): TNarrowActionJsonTypeToActionInstanceType<ACT_DOM, AJ, ID> {\n    assertIsActionJson(actionJson);\n\n    if (actionJson.form === EActionForm.data) {\n      if (actionJson.type === EActionPayloadType.request) {\n        return this.hydrateRequestPayload(\n          actionJson,\n        ) as unknown as TNarrowActionJsonTypeToActionInstanceType<ACT_DOM, AJ, ID>;\n      }\n\n      if (actionJson.type === EActionPayloadType.result) {\n        return this.hydrateResultPayload(\n          actionJson,\n        ) as unknown as TNarrowActionJsonTypeToActionInstanceType<ACT_DOM, AJ, ID>;\n      }\n    }\n\n    return this.actionForId(actionJson.id) as TNarrowActionJsonTypeToActionInstanceType<\n      ACT_DOM,\n      AJ,\n      ID\n    >;\n  }\n\n  async runAction<\n    ID extends keyof ACT_DOM[\"actionSchema\"] & string,\n    ACT extends ActionPayload_Request<ACT_DOM, ID>,\n  >(\n    request: ACT,\n    options?: IExecuteActionOptions<ACT_DOM, ID>,\n  ): Promise<RunningAction<ACT_DOM, ID>> {\n    const allListeners: TRunningActionUpdateListener<any, any>[] = [\n      ...(options?.listeners ?? []),\n      ...this._listeners,\n    ];\n\n    return this._rootDomain._runAction(request, {\n      ...options,\n      listeners: allListeners,\n    });\n  }\n\n  private createActionMap(): {\n    [K in keyof ACT_DOM[\"actionSchema\"] & string]: ActionCore<ACT_DOM, K>;\n  } {\n    const map = {} as {\n      [K in keyof ACT_DOM[\"actionSchema\"] & string]: ActionCore<ACT_DOM, K>;\n    };\n\n    for (const id in this.actionSchema) {\n      map[id] = new ActionCore(this, id);\n    }\n\n    return map;\n  }\n}\n","import type { IActionRootDomain } from \"../ActionDomain.types\";\nimport { ActionRootDomain } from \"../ActionRootDomain\";\n\nexport const createActionRootDomain = <ID extends string>(definition: {\n  domain: ID;\n}): ActionRootDomain<IActionRootDomain<ID>> => {\n  return new ActionRootDomain<IActionRootDomain<ID>>(definition);\n};\n","import type { TActionPayload_Any_JsonObject } from \"../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport { isActionPayload_Any_JsonObject } from \"./isActionPayload_Any_JsonObject\";\n\n/**\n * Minimal codec shape needed to turn an incoming channel frame back into action wire JSON. Matches\n * the `formatMessage` object the WebSocket transport (and `createBinaryWireAdapter`) provide.\n */\nexport interface IActionFrameDecoder {\n  incoming?: (\n    frame: string | ArrayBuffer | Uint8Array | Blob,\n  ) => TActionPayload_Any_JsonObject<any, any> | undefined;\n}\n\n/**\n * Decode a single inbound channel frame (text or binary) into validated action wire JSON, or\n * `undefined` if it isn't a recognisable action payload.\n *\n * Shared by the WebSocket transport's message listener and the server-side `ChannelAcceptor` so\n * both decode identically: a binary `decoder.incoming` (e.g. msgpackr) takes precedence, and plain\n * text frames fall back to JSON — keeping binary and JSON clients interoperable on one channel.\n */\nexport function decodeActionFrame(\n  frame: string | ArrayBuffer | Uint8Array,\n  decoder?: IActionFrameDecoder,\n): TActionPayload_Any_JsonObject<any, any> | undefined {\n  const decoded =\n    decoder?.incoming?.(frame) ??\n    (typeof frame === \"string\" ? parseJsonActionFrame(frame) : undefined);\n\n  return decoded != null && isActionPayload_Any_JsonObject(decoded) ? decoded : undefined;\n}\n\nfunction parseJsonActionFrame(\n  message: string,\n): TActionPayload_Any_JsonObject<any, any> | undefined {\n  try {\n    const json = JSON.parse(message);\n    return isActionPayload_Any_JsonObject(json) ? json : undefined;\n  } catch {\n    return undefined;\n  }\n}\n","import type { ESecurityLevel } from \"@nice-code/wire\";\nimport { RuntimeCoordinate } from \"@nice-code/wire\";\nimport type { IActionPayload_Request_JsonObject } from \"../../ActionDefinition/Action/Payload/ActionPayload.types\";\n\n/**\n * What the server knows about an inbound action request when it accepts it — handed to a logger *before*\n * the action executes. Deliberately carries only routing-level facts (which action, over which transport,\n * from whom) plus the raw {@link input}; a logger decides for itself whether to surface the input (the\n * default logger hides it unless told otherwise, since inputs can hold sensitive data).\n */\nexport interface IActionServeRequestInfo {\n  /** The carrier that received the request — its short kind label, e.g. `\"http\"`, `\"ws\"`, `\"webrtc\"`. */\n  transport: string;\n  /** Domain-qualified action id, e.g. `\"demo_basic/greet\"` (the {@link domain} + {@link action}). */\n  actionId: string;\n  /** The action's own (unqualified) id, e.g. `\"greet\"`. */\n  action: string;\n  /** The domain the action belongs to, e.g. `\"demo_basic\"`. */\n  domain: string;\n  /** The originating client runtime coordinate (its `stringId`) — who sent the request. */\n  origin: string;\n  /** The security level the request arrived under (`none` for a plain endpoint), when known. */\n  securityLevel?: ESecurityLevel;\n  /** The action's input — always provided; a logger shows it only if configured to (default: hidden). */\n  input: unknown;\n  /**\n   * The encoded request frame's size in bytes, as the serving path decoded it — **pre-decryption**, so\n   * this is the action payload's own cost, not the billed carrier frame. (For true wire bytes across\n   * every lane, use `serveChannel({ wireTap })`.) Absent where the path never sees an encoded frame.\n   */\n  bytes?: number;\n  /**\n   * Reliable-delivery metadata, present only when the request arrived on a `.reliable()` stream: the frame's\n   * per-stream sequence number, the cumulative high-water acked back to the client, and whether it was a\n   * **redelivered** duplicate (a resend the server already had). Absent for best-effort requests.\n   */\n  reliability?: IActionServeReliabilityInfo;\n}\n\n/** The reliable-stream facts a logger can surface for a `.reliable()` request. See {@link IActionServeRequestInfo.reliability}. */\nexport interface IActionServeReliabilityInfo {\n  seq?: number;\n  ack?: number;\n  redelivered?: boolean;\n}\n\n/**\n * How an action request was served — handed to the reporter that {@link IActionServeLogger.onRequest}\n * returns, once the action has finished and its result has been handed back to the client.\n */\nexport interface IActionServeResultInfo {\n  /** Whether the action succeeded. */\n  ok: boolean;\n  /** How the result went back to the client — typically the receiving transport (`\"http\"`, `\"ws\"`, …). */\n  returnedVia: string;\n  /** Wall-clock milliseconds from the request being received to its result being returned. */\n  durationMs: number;\n  /**\n   * The encoded result frame's size in bytes, pre-encryption — the mirror of\n   * {@link IActionServeRequestInfo.bytes}. Absent where the path never encodes a frame.\n   */\n  bytes?: number;\n  /** When {@link ok} is `false`: the failure's error id (when present) and message. */\n  error?: { id?: string; message: string };\n}\n\n/** Called once with the outcome by the reporter {@link IActionServeLogger.onRequest} returns. */\nexport type TActionServeResultReporter = (result: IActionServeResultInfo) => void;\n\n/**\n * A pluggable server-side logger for {@link serveChannel}. {@link onRequest} is called when the server\n * accepts an inbound action request (before it executes) and returns a reporter the server then calls with\n * the outcome — so one logger call spans the whole request→response, letting an implementation pair the two\n * lines (and time the gap) however it likes.\n *\n * Pass an instance as `serveChannel(..., { logger })`. Use {@link createDefaultServeLogger} for a ready-made\n * console logger, or implement this interface to forward to your own logging stack (pino, a metrics sink, …).\n */\nexport interface IActionServeLogger {\n  /**\n   * Observe an accepted inbound request. Return a reporter the server invokes once the action has been\n   * served with its outcome + how it was returned. Returning `undefined` skips the result line for this one\n   * request (e.g. to sample, or to ignore a noisy action).\n   */\n  onRequest(info: IActionServeRequestInfo): TActionServeResultReporter | undefined;\n}\n\n/** Build the {@link IActionServeRequestInfo} for an inbound request wire, shared by every serving path. */\nexport function actionServeRequestInfo(\n  wire: IActionPayload_Request_JsonObject,\n  meta: {\n    transport: string;\n    securityLevel?: ESecurityLevel;\n    origin?: string;\n    reliability?: IActionServeReliabilityInfo;\n    bytes?: number;\n  },\n): IActionServeRequestInfo {\n  // The bound (authenticated) origin is passed when the path knows it; otherwise fall back to the wire's\n  // self-asserted coordinate so a plain endpoint still names its caller.\n  const origin =\n    meta.origin ??\n    (wire.context.originClient != null\n      ? new RuntimeCoordinate(wire.context.originClient).stringId\n      : \"unknown\");\n  return {\n    transport: meta.transport,\n    domain: wire.domain,\n    action: wire.id,\n    actionId: `${wire.domain}/${wire.id}`,\n    origin,\n    securityLevel: meta.securityLevel,\n    input: wire.input,\n    bytes: meta.bytes,\n    reliability: meta.reliability,\n  };\n}\n\n/**\n * Reduce a result's failure error to the flat `{ id?, message }` a logger shows. Typed against the minimal\n * structural shape of a `NiceError` so {@link serveLogger} stays free of an `@nice-code/error` import.\n */\nexport function serveResultErrorInfo(error: {\n  def?: { domain?: string };\n  ids?: readonly string[];\n  cleanMessage?: string;\n  message: string;\n}): { id?: string; message: string } {\n  const domain = error.def?.domain;\n  const ids = error.ids != null && error.ids.length > 0 ? error.ids.join(\",\") : undefined;\n  const id = domain != null && ids != null ? `${domain}/${ids}` : (ids ?? domain);\n  return { id, message: error.cleanMessage ?? error.message };\n}\n\n/** Options for {@link createDefaultServeLogger}. */\nexport interface IDefaultServeLoggerOptions {\n  /** Where each line is written. Defaults to the global `console`. */\n  sink?: Pick<Console, \"log\" | \"error\">;\n  /** Tag prefixed to every line so server logs are greppable. Defaults to `\"[nice-action]\"`. */\n  tag?: string;\n  /**\n   * Include the action input on the request line. Off by default — inputs can carry sensitive data, so\n   * opt in only when you want it (this is the \"unless configured that way\" switch).\n   */\n  logInputs?: boolean;\n  /** Show the negotiated security level (`[encrypted]`, …) on the request line. Defaults to `true`. */\n  showSecurityLevel?: boolean;\n}\n\n/**\n * A ready-made {@link IActionServeLogger} that prints one line when a request arrives and one when it has\n * been served, to `console` (or any `sink` you pass). Drop it straight into `serveChannel` so a \"host and\n * forget\" backend gets request/response feedback with no extra wiring:\n * ```ts\n * serveChannel(channel, { identity, storage, carriers, logger: createDefaultServeLogger() });\n * // → [nice-action] ▶ demo_basic/greet  via http  from envId[web_app]…  [encrypted]\n * // ← [nice-action] ✓ demo_basic/greet  ok  via http  12ms\n * ```\n * Inputs are hidden by default (`logInputs: true` to include them).\n */\nexport function createDefaultServeLogger(\n  options: IDefaultServeLoggerOptions = {},\n): IActionServeLogger {\n  const sink = options.sink ?? console;\n  const tag = options.tag ?? \"[nice-action]\";\n  const showSecurity = options.showSecurityLevel ?? true;\n\n  return {\n    onRequest(info) {\n      const request = [tag, \"▶\", info.actionId, `via ${info.transport}`, `from ${info.origin}`];\n      if (info.bytes != null) request.push(`${info.bytes}B`);\n      if (showSecurity && info.securityLevel != null) request.push(`[${info.securityLevel}]`);\n      if (info.reliability != null) {\n        const { seq, ack, redelivered } = info.reliability;\n        request.push(\n          `reliable seq=${seq ?? \"-\"} ack=${ack ?? \"-\"}${redelivered ? \" (redelivered)\" : \"\"}`,\n        );\n      }\n      if (options.logInputs) request.push(`input=${safeJson(info.input)}`);\n      sink.log(request.join(\"  \"));\n\n      return (result) => {\n        const line = [\n          tag,\n          result.ok ? \"✓\" : \"✗\",\n          info.actionId,\n          result.ok ? \"ok\" : \"FAIL\",\n          `via ${result.returnedVia}`,\n          `${result.durationMs}ms`,\n        ];\n        if (result.bytes != null) line.push(`${result.bytes}B`);\n        if (!result.ok && result.error != null) {\n          const prefix = result.error.id != null ? `${result.error.id}: ` : \"\";\n          line.push(`— ${prefix}${result.error.message}`);\n        }\n        (result.ok ? sink.log : sink.error)(line.join(\"  \"));\n      };\n    },\n  };\n}\n\nfunction safeJson(value: unknown): string {\n  try {\n    return JSON.stringify(value);\n  } catch {\n    return String(value);\n  }\n}\n","import type { ClientCryptoKeyLink } from \"@nice-code/util\";\nimport {\n  DEFAULT_TRANSPORT_TIMEOUT,\n  decodeControlFrame,\n  ESecurityLevel,\n  encodeControlFrame,\n  type IClientVerifyKeyResolver,\n  type IReliableReceiver,\n  type IRuntimeCoordinate,\n  type IWireAcceptorProtocol,\n  type IWireConnectionBinding,\n  ReliableInbox,\n  RuntimeCoordinate,\n  reliableStreamId,\n  type TControlMessage,\n  type TFrame,\n  type TServerDictionaryVersionResolver,\n  UNSET_RUNTIME_ENV_ID,\n  WireAcceptor,\n  warnReliablePushUnsupportedOnce,\n  wireFrameByteSize,\n} from \"@nice-code/wire\";\nimport type { TDistributeActionPayload_Request } from \"../../../../ActionDefinition/Action/Action.combined.types\";\nimport type {\n  IActionReceiverMetadata,\n  IHandledReliability,\n} from \"../../../../ActionDefinition/Action/Context/ActionContext.types\";\nimport type { IActionRouteItemHandler } from \"../../../../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport {\n  EActionPayloadType,\n  type TActionPayload_Any_Instance,\n  type TActionPayload_Any_JsonObject,\n} from \"../../../../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport type { ActionPayload_Request } from \"../../../../ActionDefinition/Action/Payload/ActionPayload_Request\";\nimport { RunningAction } from \"../../../../ActionDefinition/Action/RunningAction\";\nimport { ERunningActionUpdateType } from \"../../../../ActionDefinition/Action/RunningAction.types\";\nimport type { ActionDomain } from \"../../../../ActionDefinition/Domain/ActionDomain\";\nimport type { IActionDomain } from \"../../../../ActionDefinition/Domain/ActionDomain.types\";\nimport {\n  EActionResponseMode,\n  EReliabilityTier,\n} from \"../../../../ActionDefinition/Schema/ActionSchema\";\nimport { EErrId_NiceAction, err_nice_action } from \"../../../../errors/err_nice_action\";\nimport { decodeActionFrame } from \"../../../../utils/decodeActionFrame\";\nimport { ActionRuntime } from \"../../../ActionRuntime\";\nimport {\n  actionServeRequestInfo,\n  type IActionServeLogger,\n  type IActionServeReliabilityInfo,\n  serveResultErrorInfo,\n  type TActionServeResultReporter,\n} from \"../../../Channel/serveLogger\";\nimport { peekHandlerCuid } from \"../../../HandlerCallStack\";\nimport type { IActionWireFormat } from \"../../../Transport/codec/actionWireCodec\";\nimport { EErrId_NiceTransport, err_nice_transport } from \"../../../Transport/err_nice_transport\";\nimport { ETransportShape, type IFrameReliability } from \"../../../Transport/Transport.types\";\nimport type {\n  IActionHandler_Peer_Json,\n  IActionHandlerContext,\n  IHandleActionOptions,\n} from \"../../ActionHandler.types\";\nimport { ActionLocalHandler } from \"../../Local/ActionLocalHandler\";\nimport type { THandleActionExecutionFn } from \"../../Local/ActionLocalHandler.types\";\nimport { PeerLink } from \"../../PeerLink/PeerLink\";\n\n/** The codec shape `ChannelAcceptor` uses to pack/unpack frames — same as the Link transport's. */\nexport type TActionChannelFormatMessage = IActionWireFormat;\n\n/** How a connection encodes its frames, remembered so we answer each client in its own dialect. */\nexport type TActionConnectionEncoding = \"json\" | \"binary\";\n\n/**\n * A connection's restorable identity — since the connection design this is wire's versioned\n * {@link IWireConnectionBinding} (`v: 1`; client coordinate + secure-session state + advertised\n * protocol ids owned by wire, with the lane's own facts in the opaque `lane` slot — see\n * {@link IAcceptorLaneBindingState}). Persisted attachments from before the versioned schema are\n * ignored on rehydrate (the socket is treated as fresh).\n */\nexport type IAcceptorConnectionBinding = IWireConnectionBinding;\n\n/**\n * The action lane's slot on the wire binding (E4): what this handler persists per connection\n * beyond the wire-owned identity — the frame encoding and the negotiated channel tags, so a\n * hibernation-woken acceptor answers each client in its dialect and rebuilds its codec.\n */\nexport interface IAcceptorLaneBindingState {\n  encoding: TActionConnectionEncoding;\n  /**\n   * The channel tags the connection negotiated (`hello.channels`), persisted so a multi-channel\n   * acceptor rebuilds the right per-connection codec on wake. Absent for a single-channel acceptor.\n   */\n  channelTags?: readonly string[];\n}\n\n/** Validate + read a rehydrated binding's opaque lane slot back into the lane's shape. */\nfunction readLaneBindingState(lane: unknown): IAcceptorLaneBindingState | undefined {\n  if (typeof lane !== \"object\" || lane == null || !(\"encoding\" in lane)) return undefined;\n  const channelTags =\n    \"channelTags\" in lane && Array.isArray(lane.channelTags) ? lane.channelTags : undefined;\n  return { encoding: lane.encoding === \"json\" ? \"json\" : \"binary\", channelTags };\n}\n\n/**\n * An acceptor-side frame protocol (M1 multiplex seam, realm protocol design §3) — since the connection design this is\n * wire's {@link IWireAcceptorProtocol}: the server half of a protocol riding the same connections\n * as action frames. Register via {@link ChannelAcceptor.registerFrameProtocol} (or the underlying\n * `WireAcceptor` directly); the wire acceptor dispatches reserved-prefix frames (`0x01`–`0x0F`)\n * per connection, advertises `proto:<id>` in its handshake welcome, gates traffic on the\n * connection's security level,\n * and fires attach/detach around the connection lifecycle (including hibernation resume).\n */\nexport type IAcceptorFrameProtocol<TConn> = IWireAcceptorProtocol<TConn>;\n\n/**\n * Server-side secure-channel config. When set, each connection negotiates a level from\n * {@link securityLevel}: an `authenticated`/`encrypted` client must complete the handshake (and is then\n * bound to its *authenticated* coordinate) before any action frame is accepted. A `none` client (only\n * when `none` is in the allowed set) is accepted as-is with a self-asserted identity. For the\n * `encrypted` level the codec source should be a session factory (`createFormatMessage`).\n */\nexport interface IAcceptorSecurity {\n  /**\n   * Accepted level(s). A single level is strict; an array is a negotiable allowed set — the server\n   * adopts whichever level each client requests (e.g. `[none, authenticated, encrypted]` serves all\n   * three over one endpoint).\n   */\n  securityLevel: ESecurityLevel | readonly ESecurityLevel[];\n  /** This server's crypto identity (verify + exchange key pairs, optionally persisted). */\n  link: ClientCryptoKeyLink;\n  /** This server's coordinate — its identity to clients during the handshake. */\n  localCoordinate: IRuntimeCoordinate;\n  /** Wire dictionary version — a fixed string (single channel), or a resolver composing it from the\n   * `hello.channels` tags (multi-channel). The handshake rejects on a mismatch / unknown channel. */\n  dictionaryVersion: string | TServerDictionaryVersionResolver;\n  /** Trust decision for a client's verify key (defaults to in-memory TOFU inside the handshake). */\n  verifyKeyResolver?: IClientVerifyKeyResolver;\n}\n\ninterface IChannelAcceptorBaseOptions<TConn> {\n  /**\n   * Coordinate of the *connecting clients* (typically env-only, e.g. `RuntimeCoordinate.env(\"web_app\")`),\n   * scored against an action's `originClient` to pick this handler when *no* handler holds the client's\n   * live connection (the offline-return fallback). A handler that currently owns the live socket always\n   * wins regardless, so this is optional: omit it for a multi-role server that accepts several client envs\n   * over one acceptor — it then defaults to `RuntimeCoordinate.unknown` (scores 0 against every client).\n   */\n  /** Write an encoded frame to a specific live connection (e.g. `(ws, frame) => ws.send(frame)`). */\n  send: (connection: TConn, frame: string | Uint8Array | ArrayBuffer) => void;\n  /** Close a live connection (e.g. `(ws) => ws.close(1008)`); used to end a refused handshake. */\n  close?: (connection: TConn) => void;\n  /**\n   * The runtime this handler belongs to. When set, {@link ChannelAcceptor.broadcast} can be called\n   * without threading a runtime through each call. Optional — `pushToClient` still takes one explicitly.\n   */\n  runtime?: ActionRuntime;\n  /** Timeout (ms) applied to server-initiated actions awaiting a client response. */\n  defaultTimeout?: number;\n  /**\n   * Called once when a connection is first bound to a client identity. Use it to persist the binding\n   * for transports that can resume after eviction — e.g. a Durable Object's hibernatable WebSocket:\n   * `(ws, binding) => ws.serializeAttachment(binding)` — then replay it via {@link ChannelAcceptor.rehydrate}\n   * when the channel comes back.\n   */\n  onConnectionBound?: (connection: TConn, binding: IAcceptorConnectionBinding) => void;\n  /**\n   * Enable the authenticated (optionally encrypted) handshake. When omitted, connections are trusted\n   * as-is (identity self-asserted) — fine for dev / trusted networks.\n   */\n  security?: IAcceptorSecurity;\n  /** Optional server-side logger — called per inbound action request with its served outcome. */\n  logger?: IActionServeLogger;\n  /**\n   * The server's wire-observation seam — the mirror of `connectChannel({ wireTap })`. Every frame\n   * crossing a carrier is reported with its true wire byte size (post-encryption) and its lane\n   * (`handshake` / `keepalive` / `action` / a protocol id such as `realm`), tagged with the bound\n   * client as `linkId`. Sizes only, never payload contents.\n   */\n  wireTap?: import(\"@nice-code/wire\").TWireTapFn;\n  /** Short carrier-kind label surfaced to the logger as the request's transport (e.g. `\"ws\"`). */\n  transportLabel?: string;\n  /**\n   * Persisted receive store for the **persisted** reliability tier (`.reliable({ persist: true })`). When set,\n   * a frame whose action declares the `persisted` tier is deduped through this store (e.g. a `ReliableLog` over\n   * a Durable Object's SQL) instead of the in-memory inbox — so its high-water survives eviction and a\n   * replayed stream dedups rather than redelivering. Omit it and persisted-tier streams degrade gracefully to\n   * the in-memory (session) behavior. `session`-tier streams always use the in-memory inbox.\n   *\n   * On the high-level serve surface this is the `reliableStore` option (`serveChannel` /\n   * `serveDurableObject`) — one store, two entry points; both names describe the same\n   * `IReliableReceiver`.\n   */\n  persistedReceiver?: IReliableReceiver<TActionPayload_Any_JsonObject<any>>;\n  /**\n   * Max distinct **keyed** (`streamKey`, E3) reliable streams tracked per bound client (default 256).\n   * Every keyed frame mints receiver state named by a client-chosen string, so without a cap one client\n   * could allocate unbounded server-side stream state; past the cap a new key's frames are served\n   * best-effort (delivered, but no ordering/dedup state is created) with a one-time warning.\n   */\n  maxKeyedStreamsPerClient?: number;\n}\n\n/**\n * Multi-channel codec selection: resolve a connection's advertised channel tags (`hello.channels`) into the\n * codec factory it should use, so one acceptor can serve several channels and pick each connection's codec\n * from the subset it connected. Returns `undefined` only for an unknown/unserved set (the handshake already\n * rejects those); given no tags it returns the default (single/combined) channel's factory.\n */\nexport type TAcceptorResolveCodec = (\n  tags: readonly string[] | undefined,\n) => (() => TActionChannelFormatMessage) | undefined;\n\n/**\n * Provide exactly one codec source:\n * - `formatMessage` — a single shared codec for every connection (stateless, e.g. `createBinaryWireAdapter`).\n * - `createFormatMessage` — a per-connection factory for stateful codecs (e.g.\n *   `createBinaryWireSessionFactory`, whose sessions hold correlation + identity state). Required for the\n *   leanest binary wire; the handler creates and caches one codec per connection.\n */\nexport type IChannelAcceptorOptions<TConn> = IChannelAcceptorBaseOptions<TConn> &\n  (\n    | {\n        formatMessage: TActionChannelFormatMessage;\n        createFormatMessage?: never;\n        resolveCodec?: never;\n      }\n    | {\n        createFormatMessage: () => TActionChannelFormatMessage;\n        formatMessage?: never;\n        resolveCodec?: never;\n      }\n    | { resolveCodec: TAcceptorResolveCodec; formatMessage?: never; createFormatMessage?: never }\n  );\n\n/**\n * A connection-aware execution case (see {@link ChannelAcceptor.forConnectionDomainCases}). It receives\n * the primed request plus a per-invocation `context` — whatever the wiring's context mapper produces from\n * the originating connection. The low-level handler passes the raw connection (`TConn | undefined`); the\n * higher-level `serveChannel` enriches it into an `IConnectionContext` (state + broadcast + pushBack). A\n * case may return the action's raw output, a result payload, or nothing (auto-wrapped as an empty\n * success) — exactly like a local handler case.\n */\nexport type TAcceptorCaseFn<\n  DOM extends IActionDomain,\n  ID extends keyof DOM[\"actionSchema\"] & string,\n  TCtx,\n> = (\n  action: TDistributeActionPayload_Request<DOM, ID>,\n  context: TCtx,\n) => ReturnType<THandleActionExecutionFn<DOM, ID>> | void;\n\n/**\n * The connection-aware case the bare {@link ChannelAcceptor} serves: its `context` is the originating\n * client's live connection (resolved from the request's `originClient`, `undefined` if the socket is\n * gone). It's {@link TAcceptorCaseFn} fixed to `TConn | undefined` — the un-enriched shape used by\n * {@link ChannelAcceptor.forConnectionDomainCases} and `acceptChannelConnections`.\n */\nexport type TAcceptorConnectionCaseFn<\n  DOM extends IActionDomain,\n  ID extends keyof DOM[\"actionSchema\"] & string,\n  TConn,\n> = TAcceptorCaseFn<DOM, ID, TConn | undefined>;\n\n/**\n * Server-side handler for backends that accept many client connections over a single open channel\n * (WebSockets, Durable Objects, …). It is transport-agnostic: you feed it inbound frames with\n * {@link receive} and tell it how to write outbound frames via the `send` option.\n *\n * Since the connection design this class is the **action lane** over a wire-owned {@link WireAcceptor}\n * (reachable as {@link wireAcceptor}): the backbone — handshake accept + secure sessions, security\n * levels, the client-identity registry, frame-protocol registration/dispatch/lifecycle, versioned\n * binding persistence + rehydrate, and keepalive — lives in wire; this handler keeps the action\n * half — codec negotiation, reliable receive (inbox/dedup/acks), request execution routing, and\n * the results/pushes going back out.\n *\n * Add it alongside your local execution handler:\n * ```ts\n * const serverHandler = createChannelAcceptor({ formatMessage, send: (ws, f) => ws.send(f) });\n * runtime.addHandlers([localHandler, serverHandler]);\n * // per inbound message (e.g. a Durable Object's webSocketMessage):\n * serverHandler.receive(ws, message);\n * ```\n *\n * Inbound requests route to your local handler; the runtime's return dispatch then calls this\n * handler back (it owns the originating live connection) to send the result to the originating\n * connection. It registers an empty action router, so it is never chosen to *execute* an inbound\n * request — only to ferry results/pushes back out.\n */\nexport class ChannelAcceptor<TConn = unknown> extends PeerLink {\n  /** Accept-in over a live (duplex) connection registry — it pushes results/broadcasts to bound sockets. */\n  readonly canPush = true;\n\n  /** The wire-owned acceptor backbone this lane composes on. */\n  readonly wireAcceptor: WireAcceptor<TConn>;\n\n  private readonly _formatMessage?: TActionChannelFormatMessage;\n  private readonly _createFormatMessage?: () => TActionChannelFormatMessage;\n  private readonly _resolveCodec?: TAcceptorResolveCodec;\n  private readonly _runtime?: ActionRuntime;\n  private readonly _serverTimeout: number;\n\n  // Per-connection lane registries: encoding + codec + negotiated channel tags (census §6).\n  private readonly _connEncoding = new Map<TConn, TActionConnectionEncoding>();\n  private readonly _codecByConn = new Map<TConn, TActionChannelFormatMessage>();\n  /** The channel tags each connection negotiated — drives its `resolveCodec` selection. */\n  private readonly _connTags = new Map<TConn, readonly string[] | undefined>();\n\n  // Server-side receive bookkeeping for `.reliable()` streams (dedup + ordered dispatch + high-water for\n  // acks). Keyed by (bound client + route). Inert until a frame carries a reliability seq.\n  private readonly _inbox = new ReliableInbox<TActionPayload_Any_JsonObject<any>>();\n\n  // Persisted receive store for the `persisted` tier (set when `persistedReceiver` is provided). Persisted-tier\n  // streams dedup through this instead of `_inbox`, so their high-water survives eviction.\n  private readonly _persistedReceiver?: IReliableReceiver<TActionPayload_Any_JsonObject<any>>;\n  /** Trusted arrival facts live beside decoded objects, never in attacker-controlled wire JSON. */\n  private readonly _receiverMetadataByWire = new WeakMap<object, IActionReceiverMetadata>();\n  /**\n   * Reliable stores may reconstruct buffered JSON as a new object. Retain the matching trusted\n   * arrival beside the receiver-owned stream/sequence address while this acceptor remains alive.\n   * A wake deliberately loses this non-serializable socket fact, so restored frames execute with\n   * no live connection context rather than borrowing whichever socket happened to fill the gap.\n   */\n  private readonly _receiverMetadataByReliableStream = new Map<\n    string,\n    Map<number, IActionReceiverMetadata>\n  >();\n  /** A token per live binding prevents an in-flight handler from borrowing a dropped/rebound socket. */\n  private readonly _bindingGenerationByConnection = new Map<TConn, object>();\n\n  // Distinct keyed (E3) stream ids admitted per bound client + the clients already warned for exceeding\n  // the cap. Keys are client-chosen strings, so this is the allocation bound on receiver stream state.\n  private readonly _keyedStreamsByClient = new Map<string, Set<string>>();\n  private readonly _keyedCapWarned = new Set<string>();\n  private readonly _maxKeyedStreams: number;\n\n  // Streams for which a session-reset re-sync has been requested (and warned). Latches the `rsync` *send*\n  // — one request per reset, not one per frame — so a burst of stale-numbered frames (a reconnect's\n  // resendAll) doesn't trigger a client re-sync (a full-window renumber + resend) per frame. Cleared when\n  // the stream recovers (a fresh in-order frame arrives) so a future reset re-syncs afresh, and on\n  // connection drop (the rsync may have died with the socket; the reconnect's stale frames must be able\n  // to request it again).\n  private readonly _resyncRequested = new Set<string>();\n\n  // Optional request/response logging. `_pendingReports` correlates an inbound request to its returned\n  // result by the action's `cuid`, so one log line can span the whole serve (and time the gap).\n  private readonly _logger?: IActionServeLogger;\n  private readonly _transportLabel: string;\n  private readonly _pendingReports = new Map<\n    string,\n    { report: TActionServeResultReporter; startedAt: number }\n  >();\n\n  constructor(options: IChannelAcceptorOptions<TConn>) {\n    super(RuntimeCoordinate.unknown);\n    this._formatMessage = options.formatMessage;\n    this._createFormatMessage = options.createFormatMessage;\n    this._resolveCodec = options.resolveCodec;\n    this._runtime = options.runtime;\n    this._serverTimeout = options.defaultTimeout ?? DEFAULT_TRANSPORT_TIMEOUT;\n    this._logger = options.logger;\n    this._transportLabel = options.transportLabel ?? \"ws\";\n    this._persistedReceiver = options.persistedReceiver;\n    this._maxKeyedStreams = options.maxKeyedStreamsPerClient ?? 256;\n\n    // The wire backbone, with this handler wired in as its lane (E5): every unprefixed frame — the\n    // lane's namespace — routes to `_onLaneFrame`, the lane supplies the handshake's version\n    // payload (`dictionaryVersion`, the connection design — wire's security config keeps only the neutral\n    // core), and the lane's per-connection facts (encoding + channel tags) ride the binding's\n    // opaque `lane` slot.\n    const security = options.security;\n    this.wireAcceptor = new WireAcceptor<TConn>({\n      send: options.send,\n      close: options.close,\n      tap: options.wireTap,\n      security:\n        security == null\n          ? undefined\n          : {\n              securityLevel: security.securityLevel,\n              link: security.link,\n              localCoordinate: security.localCoordinate,\n              verifyKeyResolver: security.verifyKeyResolver,\n            },\n      onConnectionBound: options.onConnectionBound,\n      lane: {\n        dictionaryVersion: security?.dictionaryVersion,\n        onFrame: (connection, frame, level) => this._onLaneFrame(connection, frame, level),\n        onAuthenticated: (connection, auth) => {\n          // Binary is the secure channel's encoding; remember the negotiated channel subset so\n          // `_codecFor` composes the matching codec.\n          this._connEncoding.set(connection, \"binary\");\n          this._connTags.set(connection, auth.channelTags);\n        },\n        bindingState: (connection) => this._laneBindingState(connection),\n        restoreBindingState: (connection, lane) => {\n          const state = readLaneBindingState(lane);\n          if (state == null) return;\n          this._connEncoding.set(connection, state.encoding);\n          this._connTags.set(connection, state.channelTags);\n        },\n        onDrop: (connection, client) => this._onConnectionDropped(connection, client),\n      },\n    });\n  }\n\n  /** The lane's opaque binding slot for a connection — persisted by the wire acceptor. */\n  private _laneBindingState(connection: TConn): IAcceptorLaneBindingState {\n    return {\n      encoding: this._connEncoding.get(connection) ?? \"binary\",\n      channelTags: this._connTags.get(connection),\n    };\n  }\n\n  /**\n   * Admit (or refuse) a **keyed** reliable stream for a client — the allocation bound on receiver stream\n   * state, since keys are client-chosen strings. Past the cap the caller serves the frame best-effort\n   * (delivered, no state) and this warns once per client.\n   */\n  private _admitKeyedStream(client: RuntimeCoordinate, streamId: string): boolean {\n    let admitted = this._keyedStreamsByClient.get(client.stringId);\n    if (admitted == null) {\n      admitted = new Set();\n      this._keyedStreamsByClient.set(client.stringId, admitted);\n    }\n    if (admitted.has(streamId)) return true;\n    if (admitted.size >= this._maxKeyedStreams) {\n      if (!this._keyedCapWarned.has(client.stringId)) {\n        this._keyedCapWarned.add(client.stringId);\n        console.warn(\n          `[reliable] client \"${client.stringId}\" exceeded maxKeyedStreamsPerClient ` +\n            `(${this._maxKeyedStreams}) — further keyed reliable streams from it are served best-effort ` +\n            \"(no ordering/dedup state). Raise the option if this is legitimate fan-out.\",\n        );\n      }\n      return false;\n    }\n    admitted.add(streamId);\n    return true;\n  }\n\n  override _setIncomingActionDataListener(\n    runtime: ActionRuntime,\n    listener: Parameters<PeerLink[\"_setIncomingActionDataListener\"]>[1],\n  ): () => void {\n    runtime._assertActive();\n    if (runtime.scope !== \"instance\") {\n      throw err_nice_action.fromId(EErrId_NiceAction.invalid_server_runtime_scope, {\n        runtime: runtime.coordinate.stringId,\n        actualScope: runtime.scope,\n      });\n    }\n    return super._setIncomingActionDataListener(runtime, listener);\n  }\n\n  /**\n   * Log an inbound request (basic action/transport/origin facts) before it executes, stashing the returned\n   * reporter by `cuid` so {@link _reportServed} can pair it with the result. Only requests are logged;\n   * result/progress frames replying to *our* pushes are not.\n   */\n  private _logRequestIn(\n    connection: TConn,\n    wire: TActionPayload_Any_JsonObject<any>,\n    securityLevel: ESecurityLevel,\n    reliability?: IActionServeReliabilityInfo,\n    bytes?: number,\n  ): void {\n    if (this._logger == null || wire.type !== EActionPayloadType.request) return;\n    const report = this._logger.onRequest(\n      actionServeRequestInfo(wire, {\n        transport: this._transportLabel,\n        securityLevel,\n        origin: this.wireAcceptor.clientForConnection(connection)?.stringId,\n        reliability,\n        bytes,\n      }),\n    );\n    // Only stash the reporter when a result will actually come back to pair with it — a reply-less\n    // (fire-and-forget) request never produces one, so its entry would sit in the map forever (and\n    // reply-less reliable streams are the highest-volume path).\n    if (report != null && this._runtime?.responseModeForWire(wire) !== EActionResponseMode.none) {\n      this._pendingReports.set(wire.context.cuid, { report, startedAt: Date.now() });\n    }\n  }\n\n  /** Report a served result back to the reporter stashed by {@link _logRequestIn} (no-op if none/not a result). */\n  private _reportServed(payload: TActionPayload_Any_Instance<any, any>, bytes?: number): void {\n    if (payload.type !== EActionPayloadType.result) return;\n    const entry = this._pendingReports.get(payload.context.cuid);\n    if (entry == null) return;\n    this._pendingReports.delete(payload.context.cuid);\n    const durationMs = Date.now() - entry.startedAt;\n    const outcome = payload.result;\n    entry.report(\n      outcome.ok\n        ? { ok: true, returnedVia: this._transportLabel, durationMs, bytes }\n        : {\n            ok: false,\n            returnedVia: this._transportLabel,\n            durationMs,\n            bytes,\n            error: serveResultErrorInfo(outcome.error),\n          },\n    );\n  }\n\n  /**\n   * The codec for a connection: a per-connection session (cached) when a factory was provided, else\n   * the single shared `formatMessage`.\n   */\n  private _codecFor(connection: TConn): TActionChannelFormatMessage {\n    // Multi-channel: the per-connection codec is composed from the tags the connection negotiated. Cached\n    // once resolved (a session codec holds correlation state, so it must be the same instance per socket).\n    if (this._resolveCodec != null) {\n      let codec = this._codecByConn.get(connection);\n      if (codec == null) {\n        const factory = this._resolveCodec(this._connTags.get(connection));\n        if (factory != null) {\n          codec = factory();\n          this._codecByConn.set(connection, codec);\n          return codec;\n        }\n      } else {\n        return codec;\n      }\n    }\n    if (this._createFormatMessage != null) {\n      let codec = this._codecByConn.get(connection);\n      if (codec == null) {\n        codec = this._createFormatMessage();\n        this._codecByConn.set(connection, codec);\n      }\n      return codec;\n    }\n    if (this._formatMessage != null) return this._formatMessage;\n    throw err_nice_transport.fromId(EErrId_NiceTransport.not_found, {\n      actionId:\n        \"server-handler-codec (provide formatMessage, createFormatMessage, or resolveCodec)\",\n    });\n  }\n\n  /**\n   * Register (or replace) the connection-bound persistence callback after construction. Used by\n   * lifecycle helpers like {@link createHibernatableWsServerAdapter} so persistence and replay are\n   * owned by one place instead of being split across the constructor options.\n   */\n  setOnConnectionBound(\n    onConnectionBound: (connection: TConn, binding: IAcceptorConnectionBinding) => void,\n  ): void {\n    this.wireAcceptor.setOnConnectionBound(onConnectionBound);\n  }\n\n  /**\n   * Register a frame protocol (M1 multiplex seam) on the wire acceptor: every connection can then\n   * exchange the protocol's prefixed frames beside action frames (subject to the wire security\n   * gate, the connection contract). Register before serving; protocols are advertised in the handshake welcome.\n   */\n  registerFrameProtocol(protocol: IAcceptorFrameProtocol<TConn>): void {\n    this.wireAcceptor.registerProtocol(protocol);\n  }\n\n  /**\n   * Feed one inbound frame from a connection into the wire acceptor. Prefixed protocol frames and\n   * the handshake/keepalive are handled there; everything else — the lane's namespace — comes back\n   * through {@link _onLaneFrame} to be decoded, identity-bound, and routed (requests execute\n   * locally; results/progress resolve pending server-initiated actions).\n   */\n  receive(connection: TConn, frame: string | ArrayBuffer | Uint8Array): void {\n    this.wireAcceptor.receive(connection, frame);\n  }\n\n  /** One inbound lane frame (already decrypted), with the connection's negotiated level. */\n  private _onLaneFrame(connection: TConn, frame: TFrame, level: ESecurityLevel): void {\n    // Sender-originated control frames (`rskip`, …) ride beside action frames — a cheap first-byte\n    // peek short-circuits action frames, mirroring the connector's receive path.\n    const control = decodeControlFrame(frame);\n    if (control != null) {\n      this._onControlMessage(connection, control);\n      return;\n    }\n\n    const codec = this._codecFor(connection);\n    const wire = decodeActionFrame(frame, codec);\n    if (wire == null) return;\n\n    if (level === ESecurityLevel.none) {\n      // Plain path: identity is self-asserted; remember the dialect the client speaks.\n      const encoding: TActionConnectionEncoding = typeof frame === \"string\" ? \"json\" : \"binary\";\n      this._connEncoding.set(connection, encoding);\n      if (wire.type === EActionPayloadType.request) {\n        this._resolveRequestIdentity(connection, wire);\n      }\n    } else if (wire.type === EActionPayloadType.request) {\n      // The connection is bound to an *authenticated* coordinate — always use it, never the wire's\n      // self-asserted originClient.\n      const bound = this.wireAcceptor.clientForConnection(connection);\n      if (bound != null) wire.context.originClient = bound.toJsonObject();\n    }\n\n    this._dispatchInbound(connection, wire, codec, frame, level);\n  }\n\n  /**\n   * Route a decoded inbound frame to the runtime. A best-effort frame is logged + emitted as before. A\n   * **reliable** request (its frame carries a `seq`) goes through the {@link ReliableInbox}: it's\n   * dispatched only in contiguous order (out-of-order frames buffer), duplicates are suppressed, and a\n   * duplicate/gap sends a standalone ack so the client's outbox drains. `frame` is the raw (decrypted)\n   * encoded bytes the codec re-reads for the reliability slot.\n   */\n  private _dispatchInbound(\n    connection: TConn,\n    wire: TActionPayload_Any_JsonObject<any>,\n    codec: TActionChannelFormatMessage,\n    frame: string | ArrayBuffer | Uint8Array,\n    level: ESecurityLevel,\n  ): void {\n    if (wire.type === EActionPayloadType.request) {\n      let bindingGeneration = this._bindingGenerationByConnection.get(connection);\n      if (bindingGeneration == null) {\n        bindingGeneration = {};\n        this._bindingGenerationByConnection.set(connection, bindingGeneration);\n      }\n      this._receiverMetadataByWire.set(wire, {\n        receiver: this,\n        connection,\n        bindingGeneration,\n        securityLevel: level,\n      });\n    }\n    const reliability =\n      wire.type === EActionPayloadType.request ? codec.incomingReliability?.(frame) : undefined;\n    // The decoded frame's own size (the action payload's cost), for `IActionServeRequestInfo.bytes`.\n    // True billed carrier bytes are a different measurement — see `serveChannel({ wireTap })`.\n    const bytes = this._logger != null ? wireFrameByteSize(frame) : undefined;\n\n    if (reliability?.seq != null) {\n      this._dispatchReliableRequest(\n        connection,\n        wire,\n        reliability.seq,\n        level,\n        reliability.streamKey,\n        bytes,\n      );\n      return;\n    }\n\n    this._logRequestIn(connection, wire, level, undefined, bytes);\n    this._emitIncomingFromReceiver(wire);\n  }\n\n  /** Ordered/dedup dispatch of one reliable request via the inbox (see {@link _dispatchInbound}). */\n  private _dispatchReliableRequest(\n    connection: TConn,\n    wire: TActionPayload_Any_JsonObject<any>,\n    seq: number,\n    level: ESecurityLevel,\n    streamKey?: string,\n    bytes?: number,\n  ): void {\n    const client = this.wireAcceptor.clientForConnection(connection);\n    // No bound identity → can't key the stream; fall back to a plain dispatch (best-effort).\n    if (client == null) {\n      this._logRequestIn(connection, wire, level, undefined, bytes);\n      this._emitIncomingFromReceiver(wire);\n      return;\n    }\n\n    const streamId = reliableStreamId(client, wire.domain, wire.id, streamKey);\n    // Keyed streams are capped per client (keys are client-chosen strings — an allocation lever): past\n    // the cap the frame is served best-effort rather than minting more receiver state.\n    if (streamKey != null && !this._admitKeyedStream(client, streamId)) {\n      this._logRequestIn(connection, wire, level, undefined, bytes);\n      this._emitIncomingFromReceiver(wire);\n      return;\n    }\n    // Persisted-tier streams dedup through the persisted store (high-water survives eviction); every other\n    // reliable stream uses the in-memory inbox. The tier is derived from the shared `domain:id`, no wire flag.\n    const receiver = this._receiverForWire(wire);\n    const { deliver, duplicate, needsResync } = receiver.receive(streamId, seq, wire);\n\n    // Session-tier reset (a mid-stream frame on a receiver with no state): ask the client to re-sync rather\n    // than buffer an unfillable gap. Nothing is delivered/buffered; the client renumbers its unacked frames\n    // from 0 and resends, which then arrives on a clean stream. The request (and its warn) is latched per\n    // reset: a burst of stale frames — a reconnect's whole resendAll — triggers exactly one `rsync`, not a\n    // client-side full-window renumber + resend per frame.\n    if (needsResync) {\n      this._forgetReliableReceiverMetadata(streamId, seq);\n      if (!this._resyncRequested.has(streamId)) {\n        this._resyncRequested.add(streamId);\n        this._sendControl(\n          connection,\n          streamKey == null\n            ? { $c: \"rsync\", domain: wire.domain, id: wire.id }\n            : { $c: \"rsync\", domain: wire.domain, id: wire.id, k: streamKey },\n        );\n        console.warn(\n          `[reliable] stream reset detected for \"${wire.domain}:${wire.id}\" (received seq ${seq} with no ` +\n            \"prior state) — requesting client re-sync of its in-flight frames. Use the persisted tier \" +\n            \"(.reliable({ persist: true })) to also survive eviction without a re-sync.\",\n        );\n      }\n      return;\n    }\n    // Stream is progressing normally again — clear the reset latch so a future reset re-syncs afresh.\n    this._resyncRequested.delete(streamId);\n\n    const ack = receiver.contiguousSeq(streamId);\n    // Reliability facts for the logger, tagged onto the frame that was actually received this call (`seq`);\n    // any buffered frames it drains are logged without a seq, since they were received on an earlier call.\n    const receivedReliability: IActionServeReliabilityInfo = { seq, ack, redelivered: duplicate };\n    // A gap keeps the payload inside the reliable receiver. Preserve its transport-owned facts at\n    // the same trusted address, bounded to the receiver's standard gap window. Repeated copies of\n    // the same sequence never replace the first arrival's binding.\n    if (!duplicate && deliver.length === 0 && ack != null && seq > ack && seq - ack <= 1_024) {\n      const arrival = this._receiverMetadataByWire.get(wire);\n      if (arrival != null) this._rememberReliableReceiverMetadata(streamId, seq, arrival);\n    }\n\n    // A reply-less (fire-and-forget) reliable stream sends no handler reply, so its ack has nothing to\n    // piggyback on — it rides a standalone control frame instead. That lets us **truly dedup**: a\n    // duplicate yields an empty `deliver` and is simply not re-dispatched (the handler never sees a\n    // resent frame), and we still re-ack the high-water so the client's outbox drains on reconnect.\n    if (this._runtime?.responseModeForWire(wire) === EActionResponseMode.none) {\n      this._emitReliableDelivered(\n        connection,\n        deliver,\n        level,\n        receivedReliability,\n        streamKey,\n        bytes,\n        this._receiverMetadataByWire.get(wire),\n        streamId,\n      );\n      this._sendControl(\n        connection,\n        streamKey == null\n          ? { $c: \"rack\", domain: wire.domain, id: wire.id, ack }\n          : { $c: \"rack\", domain: wire.domain, id: wire.id, ack, k: streamKey },\n      );\n      return;\n    }\n\n    // Reply-carrying acks use the receiver-owned reliability stamp on each action context.\n    // A sender-chosen cuid is never used to correlate the stream for an asynchronous reply.\n\n    // A duplicate (a reconnect resend) is re-dispatched to the idempotent handler so its reply — carrying\n    // the output the client may still be waiting for — regenerates with a fresh ack. Ordering is still\n    // guaranteed (out-of-order frames buffer; the handler never sees frames out of order). The handler\n    // can see it *is* a re-run (`redelivered: true`) via the local context stamp — e.g. to return a\n    // memoized reply instead of re-running an expensive body.\n    if (duplicate) {\n      this._logRequestIn(connection, wire, level, receivedReliability, bytes);\n      this._emitIncomingFromReceiver(\n        wire,\n        streamKey == null ? { seq, redelivered: true } : { seq, streamKey, redelivered: true },\n      );\n      this._forgetReliableReceiverMetadata(streamId, seq);\n      return;\n    }\n\n    // In-order (possibly draining a buffered contiguous run); a gap yields an empty `deliver` — the frame\n    // is buffered and the client's ordered resend delivers the filler that releases it.\n    this._emitReliableDelivered(\n      connection,\n      deliver,\n      level,\n      receivedReliability,\n      streamKey,\n      bytes,\n      this._receiverMetadataByWire.get(wire),\n      streamId,\n    );\n  }\n\n  /**\n   * Stamp the receiver-side reliability facts onto a delivered frame's **local** context (the\n   * `originClient`-overwrite pattern) so the executing handler reads them as `action.context.reliability`\n   * — the free idempotency key. Local-only: `toJsonObject()` never writes the field, so a reply built off\n   * this context is byte-identical with and without the stamp.\n   */\n  private _emitIncomingFromReceiver(\n    wire: TActionPayload_Any_JsonObject<any>,\n    reliability?: IHandledReliability,\n    arrivalOverride?: IActionReceiverMetadata,\n  ): void {\n    const arrival = arrivalOverride ?? this._receiverMetadataByWire.get(wire);\n    this._receiverMetadataByWire.delete(wire);\n    const securityLevel = arrival?.securityLevel;\n    this._emitIncoming(wire, {\n      receiver: this,\n      connection: arrival?.connection,\n      bindingGeneration: arrival?.bindingGeneration,\n      securityLevel,\n      originAuthenticated: securityLevel != null && securityLevel !== ESecurityLevel.none,\n      reliability,\n    });\n  }\n\n  /**\n   * Log + emit each frame the receiver decided to deliver in this receive. Only the **first** (the frame\n   * actually received this call) carries the reliability facts for the *logger*; drained buffered frames\n   * were logged/seq'd on their own earlier arrivals, so they log without a (stale) seq. Every delivered\n   * frame is stamped with its **own** seq for the executing handler, though — delivered frames are a\n   * contiguous run ending at the new high-water (`ack`), so frame `i` carries `ack - (length - 1 - i)`.\n   */\n  private _emitReliableDelivered(\n    connection: TConn,\n    deliver: TActionPayload_Any_JsonObject<any>[],\n    level: ESecurityLevel,\n    receivedReliability: IActionServeReliabilityInfo,\n    streamKey?: string,\n    bytes?: number,\n    receivedArrival?: IActionReceiverMetadata,\n    streamId?: string,\n  ): void {\n    const ack = receivedReliability.ack;\n    deliver.forEach((delivered, index) => {\n      const deliveredSeq = ack != null ? ack - (deliver.length - 1 - index) : undefined;\n      // `ReliableLog` reconstructs stored JSON, so the just-received frame may be a clone. Match it\n      // by its receiver-owned sequence position, never by attacker-controlled cuid.\n      const arrivalOverride =\n        deliveredSeq != null && deliveredSeq === receivedReliability.seq\n          ? receivedArrival\n          : deliveredSeq != null && streamId != null\n            ? this._takeReliableReceiverMetadata(streamId, deliveredSeq)\n            : undefined;\n      // `deliver` may drain frames buffered by an earlier gap, whose encoded sizes are long gone.\n      // Only the frame that just arrived carries `bytes` (the same one that carries the reliability\n      // facts) — the rest report none rather than a borrowed, wrong number.\n      this._logRequestIn(\n        connection,\n        delivered,\n        level,\n        index === 0 ? receivedReliability : undefined,\n        index === 0 ? bytes : undefined,\n      );\n      if (ack != null) {\n        const reliability: IHandledReliability =\n          streamKey == null\n            ? {\n                seq: ack - (deliver.length - 1 - index),\n                redelivered: false,\n              }\n            : {\n                seq: ack - (deliver.length - 1 - index),\n                streamKey,\n                redelivered: false,\n              };\n        this._emitIncomingFromReceiver(delivered, reliability, arrivalOverride);\n      } else this._emitIncomingFromReceiver(delivered, undefined, arrivalOverride);\n    });\n  }\n\n  /**\n   * The receive store a reliable frame's stream is served by: the persisted {@link _persistedReceiver} for a\n   * `persisted`-tier action (when one is configured), else the in-memory {@link _inbox}. A persisted action with\n   * no configured store degrades to the inbox (session-tier behavior) rather than failing.\n   */\n  private _receiverForWire(\n    wire: TActionPayload_Any_JsonObject<any>,\n  ): IReliableReceiver<TActionPayload_Any_JsonObject<any>> {\n    return this._receiverForRoute(wire.domain, wire.id);\n  }\n\n  /** {@link _receiverForWire} by bare route — for control messages, which carry no action payload. */\n  private _receiverForRoute(\n    domain: string,\n    id: string,\n  ): IReliableReceiver<TActionPayload_Any_JsonObject<any>> {\n    if (\n      this._persistedReceiver != null &&\n      this._runtime?.reliabilityTierForRoute(domain, id) === EReliabilityTier.persisted\n    ) {\n      return this._persistedReceiver;\n    }\n    return this._inbox;\n  }\n\n  /**\n   * A sender-originated transport control message arrived on a connection. `rskip` and `rclose` are the\n   * meaningful ones server-side (`rack`/`rsync` flow the other way — a decoded one here is simply\n   * ignored). `rskip`: the client's outbox **abandoned** every undelivered frame `<= seq` of the stream\n   * (their actions aborted / delivery deadlines expired), so advance the stream past the abandoned seqs\n   * and deliver whatever was buffered behind the gap — the stream continues instead of wedging on frames\n   * that will never arrive; the new high-water is re-acked so the client can retire the skip. `rclose`:\n   * the client closed the stream for good — release its receiver state (a pure reclaim).\n   */\n  private _onControlMessage(connection: TConn, message: TControlMessage): void {\n    // A sender closed a stream for good (`closeReliableStream`) — release every bit of receiver state\n    // named by it: the tracking store's high-water + frames, the re-sync latch, and (for a keyed stream)\n    // its slot in the keyed-stream quota, so closed keys stop counting against `maxKeyedStreamsPerClient`.\n    // Loss-tolerant by design (see the `rclose` doc): delivery was already settled by the sender's\n    // retained `rskip`, so this is purely a reclaim.\n    if (message.$c === \"rclose\") {\n      const client = this.wireAcceptor.clientForConnection(connection);\n      if (client == null) return;\n      const streamId = reliableStreamId(client, message.domain, message.id, message.k);\n      this._receiverForRoute(message.domain, message.id).forgetStream?.(streamId);\n      // A persisted-tier stream may have degraded to the inbox (no store configured) — clear both.\n      this._inbox.forget(streamId);\n      this._resyncRequested.delete(streamId);\n      if (message.k != null) {\n        this._keyedStreamsByClient.get(client.stringId)?.delete(streamId);\n      }\n      this._receiverMetadataByReliableStream.delete(streamId);\n      return;\n    }\n\n    if (message.$c !== \"rskip\") return;\n    const client = this.wireAcceptor.clientForConnection(connection);\n    if (client == null) return;\n\n    const streamId = reliableStreamId(client, message.domain, message.id, message.k);\n    // The keyed-stream cap applies here too — a skip for an inadmissible key must not mint state.\n    if (message.k != null && !this._admitKeyedStream(client, streamId)) return;\n    const receiver = this._receiverForRoute(message.domain, message.id);\n    const { deliver, ack } = receiver.skipTo(streamId, message.seq);\n    this._forgetReliableReceiverMetadataThrough(streamId, message.seq);\n    // The stream is live again from the skip point — a future genuine reset should warn/re-sync afresh.\n    this._resyncRequested.delete(streamId);\n\n    this._emitReliableDelivered(\n      connection,\n      deliver,\n      this.wireAcceptor.levelFor(connection),\n      { ack },\n      message.k,\n      undefined,\n      undefined,\n      streamId,\n    );\n    this._sendControl(\n      connection,\n      message.k == null\n        ? { $c: \"rack\", domain: message.domain, id: message.id, ack }\n        : { $c: \"rack\", domain: message.domain, id: message.id, ack, k: message.k },\n    );\n  }\n\n  private _rememberReliableReceiverMetadata(\n    streamId: string,\n    seq: number,\n    metadata: IActionReceiverMetadata,\n  ): void {\n    let bySeq = this._receiverMetadataByReliableStream.get(streamId);\n    if (bySeq == null) {\n      bySeq = new Map();\n      this._receiverMetadataByReliableStream.set(streamId, bySeq);\n    }\n    if (!bySeq.has(seq)) bySeq.set(seq, metadata);\n  }\n\n  private _takeReliableReceiverMetadata(\n    streamId: string,\n    seq: number,\n  ): IActionReceiverMetadata | undefined {\n    const bySeq = this._receiverMetadataByReliableStream.get(streamId);\n    const metadata = bySeq?.get(seq);\n    bySeq?.delete(seq);\n    if (bySeq?.size === 0) this._receiverMetadataByReliableStream.delete(streamId);\n    return metadata;\n  }\n\n  private _forgetReliableReceiverMetadata(streamId: string, seq: number): void {\n    this._takeReliableReceiverMetadata(streamId, seq);\n  }\n\n  private _forgetReliableReceiverMetadataThrough(streamId: string, through: number): void {\n    const bySeq = this._receiverMetadataByReliableStream.get(streamId);\n    if (bySeq == null) return;\n    for (const seq of bySeq.keys()) if (seq <= through) bySeq.delete(seq);\n    if (bySeq.size === 0) this._receiverMetadataByReliableStream.delete(streamId);\n  }\n\n  /** Encode + send a transport {@link TControlMessage} to a connection (through its secure session if any). */\n  private _sendControl(connection: TConn, message: TControlMessage): void {\n    this.wireAcceptor.sendTo(connection, encodeControlFrame(message));\n  }\n\n  /**\n   * Ensure an inbound request carries the client's identity and that this connection is bound to it,\n   * so its result can be routed back. A session codec omits `originClient` after the first request, so\n   * when it's missing we restore it from the (possibly rehydrated) binding instead. (Plain mode only;\n   * secure mode binds the authenticated coordinate at handshake time.)\n   */\n  private _resolveRequestIdentity(\n    connection: TConn,\n    wire: TActionPayload_Any_JsonObject<any>,\n  ): void {\n    const wireOrigin = wire.context.originClient;\n\n    if (wireOrigin != null && wireOrigin.envId !== UNSET_RUNTIME_ENV_ID) {\n      // Bind (and, when the identity is new, persist) through the wire acceptor — the encoding set\n      // just before this call rides the binding's lane slot.\n      const client = new RuntimeCoordinate(wireOrigin);\n      const previous = this.wireAcceptor.clientForConnection(connection);\n      if (previous != null && previous.stringId !== client.stringId) {\n        this._bindingGenerationByConnection.delete(connection);\n      }\n      this.wireAcceptor.bindPlainConnection(connection, client);\n      return;\n    }\n\n    // Identity dropped by the session — restore it from the binding so return routing still works.\n    const bound = this.wireAcceptor.clientForConnection(connection);\n    if (bound != null) wire.context.originClient = bound.toJsonObject();\n  }\n\n  /**\n   * Restore a connection→client binding without an inbound frame — for transports that resume after\n   * eviction. Pair it with the {@link IChannelAcceptorOptions.onConnectionBound} hook: persist\n   * the binding there, then replay each live connection here when the channel comes back (e.g. a\n   * Durable Object iterating `ctx.getWebSockets()` as it wakes from hibernation). A binding persisted\n   * before the versioned (`v: 1`) schema is ignored — the socket is treated as fresh.\n   */\n  rehydrate(connection: TConn, binding: IAcceptorConnectionBinding): void {\n    this.wireAcceptor.rehydrate(connection, binding);\n  }\n\n  toJsonObject(): IActionHandler_Peer_Json {\n    return {\n      type: this.handlerType,\n      client: this.peer,\n    };\n  }\n\n  override toHandlerRouteItem(): IActionRouteItemHandler {\n    return {\n      type: this.handlerType,\n      client: this.peer,\n      transShape: ETransportShape.duplex,\n      transOrd: 0,\n    };\n  }\n\n  /** Forget a connection (call on socket close) so stale entries don't misroute later results. */\n  drop(connection: TConn): void {\n    this.wireAcceptor.drop(connection);\n  }\n\n  /** Permanently quiesce this acceptor and detach every live/rehydrated connection. */\n  dispose(): void {\n    this.wireAcceptor.dispose();\n  }\n\n  /** Lane cleanup when the wire acceptor drops a connection (fired with the bound client, if any). */\n  private _onConnectionDropped(connection: TConn, client: RuntimeCoordinate | undefined): void {\n    // Un-latch any pending re-sync requests for this client's streams: the `rsync` may have died with the\n    // socket, and the reconnect's stale frames must be able to trigger a fresh one (the latch alone would\n    // otherwise deadlock recovery). The inbox state itself is deliberately kept — reconnect dedup needs it.\n    if (client != null) {\n      const prefix = `${client.stringId}::`;\n      for (const streamId of this._resyncRequested) {\n        if (streamId.startsWith(prefix)) this._resyncRequested.delete(streamId);\n      }\n    }\n    this._connEncoding.delete(connection);\n    this._codecByConn.delete(connection);\n    this._connTags.delete(connection);\n    this._bindingGenerationByConnection.delete(connection);\n    // Buffered reliable arrivals hold a STRONG reference to the socket; without this a closed\n    // connection is retained until its gap fills or an ack sweeps the stream.\n    for (const bySeq of this._receiverMetadataByReliableStream.values()) {\n      for (const metadata of bySeq.values()) {\n        if (metadata.connection !== connection) continue;\n        // Keep historical security facts for durable stores that reconstruct the buffered JSON,\n        // while releasing the socket and preventing any later binding from becoming its arrival.\n        metadata.connection = undefined;\n        metadata.bindingGeneration = undefined;\n      }\n    }\n  }\n\n  private _liveArrivalConnection(metadata: IActionReceiverMetadata): TConn | undefined {\n    const connection = metadata.connection as TConn | undefined;\n    return metadata.receiver === this &&\n      connection != null &&\n      metadata.bindingGeneration != null &&\n      this._bindingGenerationByConnection.get(connection) === metadata.bindingGeneration &&\n      this.wireAcceptor.hasConnection(connection)\n      ? connection\n      : undefined;\n  }\n\n  /** Live connection for a client coordinate, if currently registered. */\n  getConnectionForClient(client: RuntimeCoordinate): TConn | undefined {\n    return this.wireAcceptor.connectionForClient(client.stringId);\n  }\n\n  /** This acceptor owns the origin's return path when it currently holds a live connection bound to it. */\n  override ownsLiveConnectionFor(origin: RuntimeCoordinate): boolean {\n    return this.wireAcceptor.ownsLiveConnectionFor(origin.stringId);\n  }\n\n  /** Whether this acceptor currently tracks `connection` — used to pick the owning handler among several. */\n  hasConnection(connection: TConn): boolean {\n    return this.wireAcceptor.hasConnection(connection);\n  }\n\n  /**\n   * Send (and optionally await) a server-initiated action to a specific connected client. Pass the\n   * connection token directly (e.g. the `ws`) or a client `RuntimeCoordinate` to look one up.\n   */\n  pushToClient<DOM extends IActionDomain, ID extends keyof DOM[\"actionSchema\"] & string>(\n    runtime: ActionRuntime,\n    target: TConn | RuntimeCoordinate,\n    request: ActionPayload_Request<DOM, ID>,\n    options?: { timeout?: number },\n  ): RunningAction<DOM, ID> {\n    const connection = this._resolveConnection(target);\n    return this._dispatch(runtime, connection, request, options?.timeout);\n  }\n\n  /**\n   * Build a local handler whose cases are connection-aware: each case receives the primed request and\n   * the originating client's live connection (resolved from `originClient`), so handlers don't repeat\n   * the `getConnectionForClient(action.context.originClient)` lookup. Cases may return raw output or\n   * nothing, just like {@link ActionLocalHandler.forDomainActionCases}. Add the returned handler to the\n   * runtime alongside this server handler:\n   * ```ts\n   * runtime.addHandlers([serverHandler.forConnectionDomainCases(domain, { … }), serverHandler]);\n   * ```\n   */\n  forConnectionDomainCases<FOR_DOM extends IActionDomain>(\n    domain: ActionDomain<FOR_DOM>,\n    cases: {\n      [ID in keyof FOR_DOM[\"actionSchema\"] & string]?: TAcceptorConnectionCaseFn<\n        FOR_DOM,\n        ID,\n        TConn\n      >;\n    },\n  ): ActionLocalHandler {\n    // Default context = the raw connection (or undefined when the socket is gone). The cast bridges the\n    // per-id mapped case map to the merged `any`-keyed map the multi form iterates (a known TS variance\n    // limitation on the contravariant action param — same bridge `acceptChannelConnections` uses).\n    return this.forConnectionDomainCasesMulti(\n      [domain],\n      cases as Record<string, TAcceptorConnectionCaseFn<any, any, TConn> | undefined>,\n      (connection) => connection,\n    );\n  }\n\n  /**\n   * Like {@link forConnectionDomainCases} but spanning several domains with one merged case map — used\n   * by channel-derived wiring (`acceptChannelConnections` / `serveChannel`) where the channel's\n   * `toAcceptor` domains are served together. Each domain takes only the cases whose ids it owns, so a\n   * single map can cover several domains and unrelated ids are ignored.\n   *\n   * `mapContext` turns the resolved connection into whatever the case's second argument should be: the\n   * raw connection for the low-level helper, or an enriched `IConnectionContext` for `serveChannel`. It's\n   * called once per inbound action, after the originating connection is resolved.\n   */\n  forConnectionDomainCasesMulti<TCtx>(\n    domains: readonly ActionDomain<any>[],\n    cases: Record<string, TAcceptorCaseFn<any, any, TCtx> | undefined>,\n    mapContext: (\n      connection: TConn | undefined,\n      request: ActionPayload_Request<any, any>,\n      isConnectionLive: () => boolean,\n      execution: IActionHandlerContext,\n    ) => TCtx,\n  ): ActionLocalHandler {\n    const handler = new ActionLocalHandler();\n\n    for (const domain of domains) {\n      const ownedIds = new Set(Object.keys(domain.actionsMap()));\n      const wrapped: Record<string, THandleActionExecutionFn<any, any>> = {};\n\n      for (const id in cases) {\n        if (!ownedIds.has(id)) continue;\n        const caseFn = cases[id];\n        if (caseFn == null) continue;\n        wrapped[id] = (request, execution) => {\n          const metadata = request.context._getReceiverMetadata();\n          const connection = metadata == null ? undefined : this._liveArrivalConnection(metadata);\n          const isConnectionLive = () =>\n            connection != null &&\n            this._bindingGenerationByConnection.get(connection) === metadata?.bindingGeneration &&\n            this.wireAcceptor.hasConnection(connection);\n          return caseFn(request, mapContext(connection, request, isConnectionLive, execution));\n        };\n      }\n\n      handler.forDomainActionCases(domain, wrapped);\n    }\n\n    return handler;\n  }\n\n  /**\n   * Fan a server-initiated request out to every currently-bound connection. A fresh request is built\n   * per connection (each push mutates its own action context) and dispatched fire-and-forget. Pass\n   * `except` to skip the originating socket and `where` to filter by connection (e.g. read its\n   * attachment for a role). Iterating bound connections (rather than every accepted socket) skips\n   * sockets that are still mid-handshake and so can't yet receive a frame.\n   */\n  broadcast<DOM extends IActionDomain, ID extends keyof DOM[\"actionSchema\"] & string>(\n    makeRequest: () => ActionPayload_Request<DOM, ID>,\n    options?: {\n      runtime?: ActionRuntime;\n      except?: TConn | null;\n      where?: (connection: TConn) => boolean;\n      timeout?: number;\n      onError?: (error: unknown, connection: TConn) => void;\n    },\n  ): void {\n    const runtime = options?.runtime ?? this._runtime;\n    if (runtime == null) {\n      throw err_nice_transport.fromId(EErrId_NiceTransport.not_found, {\n        actionId: \"server-handler-runtime (construct with `runtime` or pass `options.runtime`)\",\n      });\n    }\n\n    for (const connection of this.wireAcceptor.connections()) {\n      if (options?.except != null && connection === options.except) continue;\n      if (options?.where != null && !options.where(connection)) continue;\n      try {\n        this.pushToClient(runtime, connection, makeRequest(), { timeout: options?.timeout });\n      } catch (error) {\n        if (options?.onError != null) options.onError(error, connection);\n        else console.error(\"[ws-server] broadcast push failed\", error);\n      }\n    }\n  }\n\n  override async sendReturnPayload(\n    payload: TActionPayload_Any_Instance<any, any>,\n    config: { targetLocalRuntime: ActionRuntime; arrival?: IActionReceiverMetadata },\n  ): Promise<boolean> {\n    const arrival = config.arrival ?? payload.context._getReceiverMetadata();\n    // With arrival facts, only that exact live binding may carry the reply — never a coordinate match.\n    const connection =\n      arrival == null\n        ? this.wireAcceptor.connectionForClient(payload.context.originClient.stringId)\n        : arrival.receiver === this\n          ? this._liveArrivalConnection(arrival)\n          : undefined;\n    if (connection == null) return false;\n    const bytes = this._sendPayload(\n      connection,\n      payload,\n      config.targetLocalRuntime.coordinate,\n      arrival?.reliability,\n    );\n    this._reportServed(payload, bytes);\n    return true;\n  }\n\n  override async handleActionRequest<\n    DOM extends IActionDomain,\n    ID extends keyof DOM[\"actionSchema\"] & string,\n  >(\n    action: ActionPayload_Request<DOM, ID>,\n    config?: IHandleActionOptions,\n  ): Promise<RunningAction<DOM, ID>> {\n    const runtime = config?.targetLocalRuntime ?? ActionRuntime.getDefault();\n    const connection = this._resolveSingleConnection();\n    return this._dispatch(runtime, connection, action, config?.timeout);\n  }\n\n  private _dispatch<DOM extends IActionDomain, ID extends keyof DOM[\"actionSchema\"] & string>(\n    runtime: ActionRuntime,\n    connection: TConn,\n    action: ActionPayload_Request<DOM, ID>,\n    timeout?: number,\n  ): RunningAction<DOM, ID> {\n    const timeoutMs = timeout ?? this._serverTimeout;\n\n    // Reliability is connector→acceptor only: a server-initiated push of a reliable-declared action is\n    // best-effort (no outbox/seq/resend). Warn once per route so the direction downgrade is visible.\n    if (action.schema.reliabilityTier !== EReliabilityTier.none) {\n      warnReliablePushUnsupportedOnce(action.domain, action.id);\n    }\n\n    // The client must be able to route its result back to *us*, so the origin is this backend.\n    action.context._setOriginClient(runtime.coordinate);\n    action.context.addRouteItem({\n      runtime: runtime.coordinate,\n      handler: this.toHandlerRouteItem(),\n      time: Date.now(),\n    });\n\n    const runningAction = new RunningAction<DOM, ID>({\n      context: action.context,\n      request: action,\n      parentCuid: peekHandlerCuid(),\n      callSite: action._callSite,\n    });\n    runtime.registerRunningAction(runningAction);\n\n    // Fire-and-forget: no reply will come, so don't park a pending action behind a timeout. Send the\n    // frame and complete immediately as success — the running action still surfaces in devtools, it just\n    // resolves on send rather than on a (never-arriving) reply.\n    if (action.schema.responseMode === EActionResponseMode.none) {\n      try {\n        this._sendPayload(connection, action, runtime.coordinate);\n        runningAction._completeWithResult(\n          (action as ActionPayload_Request<any, any>).successResult(undefined),\n        );\n      } catch (err) {\n        runningAction._abort(this._pushSendError(action.id, err));\n      }\n      return runningAction;\n    }\n\n    const timeoutId = setTimeout(() => {\n      runningAction._abort(\n        err_nice_transport.fromId(EErrId_NiceTransport.timeout, { timeout: timeoutMs }),\n      );\n    }, timeoutMs);\n    runningAction.addUpdateListeners([\n      (update) => {\n        if (update.type === ERunningActionUpdateType.finished) clearTimeout(timeoutId);\n      },\n    ]);\n\n    try {\n      this._sendPayload(connection, action, runtime.coordinate);\n    } catch (err) {\n      runningAction._abort(this._pushSendError(action.id, err));\n    }\n\n    return runningAction;\n  }\n\n  /** A failed push send as a typed `send_failed`, keeping the carrier's error as the origin. */\n  private _pushSendError(actionId: string, cause: unknown): unknown {\n    if (err_nice_transport.isExact(cause)) return cause;\n    return err_nice_transport\n      .fromId(EErrId_NiceTransport.send_failed, {\n        actionId,\n        actionState: \"request\",\n        message: cause instanceof Error ? cause.message : String(cause),\n      })\n      .withOriginError(cause);\n  }\n\n  /** Encode + send one payload; returns the encoded frame's size so a logger can report it. */\n  private _sendPayload(\n    connection: TConn,\n    payload: TActionPayload_Any_Instance<any, any>,\n    localClient: RuntimeCoordinate,\n    answered?: IHandledReliability,\n  ): number {\n    const encoding = this._connEncoding.get(connection) ?? \"binary\";\n\n    // Piggyback the cumulative ack onto the receiver-owned stream of the request being answered.\n    // The JSON encoding can't carry the reliability slot, so reliable delivery rides the binary codec only.\n    let rel: IFrameReliability | undefined;\n    if (payload.type === EActionPayloadType.result) {\n      const streamKey = (answered ?? payload.context.reliability)?.streamKey;\n      const streamId = reliableStreamId(\n        payload.context.originClient,\n        payload.domain,\n        payload.id,\n        streamKey,\n      );\n      // Whichever store tracks the stream owns its high-water (persisted store checked first).\n      const receiver = this._persistedReceiver?.hasStream(streamId)\n        ? this._persistedReceiver\n        : this._inbox.hasStream(streamId)\n          ? this._inbox\n          : undefined;\n      if (receiver != null) {\n        const ack = receiver.contiguousSeq(streamId);\n        rel = streamKey == null ? { streamId, ack } : { streamId, ack, streamKey };\n      }\n    }\n\n    const frame =\n      encoding === \"json\"\n        ? JSON.stringify(payload.toJsonObject())\n        : this._codecFor(connection).outgoing({\n            action: payload,\n            localClient,\n            externalClient: this.peer,\n            reliability: rel,\n          });\n\n    // A secure connection's session encrypts (and orders) the frame; plain/authenticated connections (and\n    // connections with no secure session at all) send as-is — the wire acceptor owns that branch.\n    this.wireAcceptor.sendTo(connection, frame);\n    return wireFrameByteSize(frame);\n  }\n\n  private _resolveConnection(target: TConn | RuntimeCoordinate): TConn {\n    if (target instanceof RuntimeCoordinate) {\n      const connection = this.wireAcceptor.connectionForClient(target.stringId);\n      if (connection == null) {\n        throw err_nice_transport.fromId(EErrId_NiceTransport.not_found, {\n          actionId: target.stringId,\n        });\n      }\n      return connection;\n    }\n    return target;\n  }\n\n  private _resolveSingleConnection(): TConn {\n    if (this.wireAcceptor.connectionCount !== 1) {\n      throw err_nice_transport.fromId(EErrId_NiceTransport.not_found, {\n        actionId:\n          \"server-handler-target (use pushToClient with an explicit connection or client coordinate)\",\n      });\n    }\n    const first = this.wireAcceptor.connections().next();\n    if (first.done === true) {\n      throw err_nice_transport.fromId(EErrId_NiceTransport.not_found, {\n        actionId: \"server-handler-target\",\n      });\n    }\n    return first.value;\n  }\n}\n\nexport const createChannelAcceptor = <TConn = unknown>(\n  options: IChannelAcceptorOptions<TConn>,\n): ChannelAcceptor<TConn> => {\n  return new ChannelAcceptor<TConn>(options);\n};\n","import { ClientCryptoKeyLink, type StorageAdapter } from \"@nice-code/util\";\nimport type { IReliableReceiver } from \"@nice-code/wire\";\nimport {\n  createStorageTofuVerifyKeyResolver,\n  ESecurityLevel,\n  type IClientVerifyKeyResolver,\n} from \"@nice-code/wire\";\nimport type { TActionPayload_Any_JsonObject } from \"../../../../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport { EErrId_NiceAction, err_nice_action } from \"../../../../errors/err_nice_action\";\nimport type { ActionRuntime } from \"../../../ActionRuntime\";\nimport type { IActionChannel } from \"../../../Channel/ActionChannel\";\nimport type { IActionServeLogger } from \"../../../Channel/serveLogger\";\nimport { ChannelAcceptor } from \"./ChannelAcceptor\";\n\n/** Default accepted set: negotiate per connection to whatever the client picks. */\nconst DEFAULT_SERVER_SECURITY_LEVELS = [\n  ESecurityLevel.none,\n  ESecurityLevel.authenticated,\n  ESecurityLevel.encrypted,\n] as const;\n\nexport interface ISecureChannelAcceptorOptions<TConn> {\n  /**\n   * The default channel identity (codec + dictionary version) — same one single-channel clients use, and\n   * the fallback a multi-channel acceptor composes against when a client advertises no tags.\n   */\n  channel: IActionChannel;\n  /**\n   * Multi-channel: resolve a connection's advertised channel tags (`hello.channels`) into the channel it\n   * should use (its codec + dictionary version), or `null` for an unknown/unserved set (the handshake then\n   * rejects). When set, this acceptor serves several channels and selects/composes per connection; when\n   * omitted it serves the single {@link channel}. Built by `serveChannel` from its channel registry.\n   */\n  resolveChannel?: (tags: readonly string[] | undefined) => IActionChannel | null;\n  /** This server's runtime — its coordinate is the server identity presented in the handshake. */\n  runtime: ActionRuntime;\n  /**\n   * One backing store for the server's crypto identity *and* its trust-on-first-use verify-key pins.\n   * Their keys don't collide, so a single adapter is enough; back it with persistent storage (e.g. a\n   * Durable Object's storage) so identity and pins survive eviction.\n   */\n  storage: StorageAdapter;\n  /** Write an encoded frame to a specific live connection (e.g. `(ws, frame) => ws.send(frame)`). */\n  send: (connection: TConn, frame: string | Uint8Array | ArrayBuffer) => void;\n  /** Close a live connection (e.g. `(ws) => ws.close(1008)`); used to end a refused handshake. */\n  close?: (connection: TConn) => void;\n  /**\n   * The server's crypto identity. Defaults to a fresh {@link ClientCryptoKeyLink} over `storage`.\n   * Pass an existing link to share one identity across several acceptors on the same server (e.g. a\n   * WebSocket acceptor and a secure-HTTP {@link createActionFetchHandler}), so they present the same\n   * verify/exchange keys — avoiding a divergent-key race when two fresh links initialize concurrently.\n   */\n  link?: ClientCryptoKeyLink;\n  /** Accepted level(s); defaults to negotiating any of none/authenticated/encrypted. */\n  securityLevel?: ESecurityLevel | readonly ESecurityLevel[];\n  /** Trust decision for a client's verify key; defaults to storage-backed TOFU over `storage`. */\n  verifyKeyResolver?: IClientVerifyKeyResolver;\n  /** Timeout (ms) applied to server-initiated actions awaiting a client response. */\n  defaultTimeout?: number;\n  /** Optional server-side logger — called per inbound action request with its served outcome. */\n  logger?: IActionServeLogger;\n  /** Server-side wire tap (see {@link IChannelAcceptorBaseOptions.wireTap}). */\n  wireTap?: import(\"@nice-code/wire\").TWireTapFn;\n  /** Short carrier-kind label surfaced to the logger as the request's transport (e.g. `\"ws\"`). */\n  transportLabel?: string;\n  /** Persisted receive store for the persisted reliability tier (see {@link IChannelAcceptorBaseOptions.persistedReceiver}). */\n  persistedReceiver?: IReliableReceiver<TActionPayload_Any_JsonObject<any>>;\n  /** Cap on distinct keyed (`streamKey`) reliable streams per client (see {@link IChannelAcceptorBaseOptions.maxKeyedStreamsPerClient}). */\n  maxKeyedStreamsPerClient?: number;\n}\n\n/**\n * Build an {@link ChannelAcceptor} for the secure binary channel with the boilerplate folded in:\n * it creates the {@link ClientCryptoKeyLink} and the storage-backed TOFU resolver from a single\n * `storage`, installs the channel's per-connection codec, and assembles the `security` block\n * from the runtime coordinate + channel version (accepting all three levels by default).\n *\n * For a hibernatable transport (e.g. a Durable Object), pair it with\n * {@link createHibernatableWsServerAdapter} to wire persistence + replay.\n */\nexport function createSecureChannelAcceptor<TConn = unknown>(\n  options: ISecureChannelAcceptorOptions<TConn>,\n): ChannelAcceptor<TConn> {\n  // A serving runtime must never be a global dispatch target: sibling instances sharing an isolate\n  // would otherwise answer each other's untargeted calls. `serveChannel` asserts this for the\n  // high-level path; this is the same gate for the advanced `acceptChannel` one.\n  options.runtime._assertActive();\n  if (options.runtime.scope !== \"instance\") {\n    throw err_nice_action.fromId(EErrId_NiceAction.invalid_server_runtime_scope, {\n      runtime: options.runtime.coordinate.stringId,\n      actualScope: options.runtime.scope,\n    });\n  }\n\n  const link = options.link ?? new ClientCryptoKeyLink({ storageAdapter: options.storage });\n  const resolveChannel = options.resolveChannel;\n\n  const baseSecurity = {\n    securityLevel: options.securityLevel ?? DEFAULT_SERVER_SECURITY_LEVELS,\n    link,\n    localCoordinate: options.runtime.coordinate.toJsonObject(),\n    verifyKeyResolver:\n      options.verifyKeyResolver ?? createStorageTofuVerifyKeyResolver(options.storage),\n  };\n  const baseOptions = {\n    send: options.send,\n    close: options.close,\n    runtime: options.runtime,\n    defaultTimeout: options.defaultTimeout,\n    logger: options.logger,\n    wireTap: options.wireTap,\n    transportLabel: options.transportLabel,\n    persistedReceiver: options.persistedReceiver,\n    maxKeyedStreamsPerClient: options.maxKeyedStreamsPerClient,\n  };\n\n  // Multi-channel: codec + dictionary version are composed per connection from the advertised tags.\n  if (resolveChannel != null) {\n    return new ChannelAcceptor<TConn>({\n      ...baseOptions,\n      resolveCodec: (tags) => resolveChannel(tags)?.createCodec,\n      security: {\n        ...baseSecurity,\n        dictionaryVersion: (hello) => resolveChannel(hello.channels)?.dictionaryVersion ?? null,\n      },\n    });\n  }\n\n  // Single channel: one fixed codec + dictionary version (unchanged behaviour).\n  return new ChannelAcceptor<TConn>({\n    ...baseOptions,\n    createFormatMessage: options.channel.createCodec,\n    security: { ...baseSecurity, dictionaryVersion: options.channel.dictionaryVersion },\n  });\n}\n","import type {\n  ESecurityLevel,\n  IDuplexCarrier,\n  IExchangeCarrier,\n  IWireDialParams,\n  IWireDuplexCarrierSource,\n  IWireExchangeCarrierSource,\n} from \"@nice-code/wire\";\nimport type { TTransportRouteParams } from \"../Transport.types\";\n\n/**\n * The carrier *shapes* ({@link TFrame}, {@link IDuplexCarrier}, {@link IExchangeCarrier},\n * {@link TCarrier}) now live in `@nice-code/wire` — they are protocol-agnostic byte-moving\n * contracts shared with `@nice-code/realm`. Re-exported here so existing imports keep working.\n *\n * What stays action-side are the carrier **sources**: the per-action openers + routing metadata that\n * bind a wire carrier to the action transport (`TTransportRouteParams` is action routing).\n */\nexport type { IDuplexCarrier, IExchangeCarrier, TCarrier, TFrame } from \"@nice-code/wire\";\n\n/**\n * A reusable opener for a {@link IDuplexCarrier} plus the per-action metadata a duplex transport needs.\n * Built by the small carrier factories (`wsCarrier`, `rtcCarrier`, `inMemoryCarrier`) and passed as a\n * `carrier` to `connectChannel`'s transports (the internal `transport()` factory drives it) — so adding a\n * new carrier is \"write one of these\", nothing else.\n */\nexport type IDuplexCarrierSource = IWireDuplexCarrierSource<TTransportRouteParams> &\n  IActionCarrierOptions;\n\n/**\n * The exchange-shape counterpart to {@link IDuplexCarrierSource}: a reusable opener for an\n * {@link IExchangeCarrier} plus the per-action metadata an exchange transport needs. Built by\n * `httpCarrier` and passed as a `carrier` to `connectChannel`'s transports — adding a new request/reply\n * protocol is \"write one of these\". The `shape` tag lets the internal `transport()` factory pick the\n * duplex vs exchange transport.\n */\nexport type IExchangeCarrierSource = IWireExchangeCarrierSource<TTransportRouteParams> &\n  IActionCarrierOptions;\n\n/** Action-only policy carried beside wire's protocol-neutral carrier source. */\nexport interface IActionCarrierOptions {\n  /** Security level override for this carrier. */\n  securityLevel?: ESecurityLevel;\n  /** Per-dispatch availability gate. */\n  available?: (input: TTransportRouteParams) => boolean;\n  /** Optional devtools label override. */\n  label?: string;\n}\n\n/**\n * Convert action routing data into wire's generic carrier dial shape. The routing fields also stay at\n * the top level, so a carrier source written for the older `open(input: TTransportRouteParams)` shape\n * still reads `input.action`.\n */\nexport function toActionDialParams(\n  input: TTransportRouteParams,\n): IWireDialParams<TTransportRouteParams> & TTransportRouteParams {\n  return { ...input, dialContext: input };\n}\n\n/**\n * Narrow a carrier source to the exchange shape via its `shape` discriminant — the one branch the\n * internal `transport()` factory uses to pick the duplex vs exchange transport. A duplex source carries\n * no `shape`, so the `else` branch is the duplex one.\n */\nexport function isExchangeCarrierSource(\n  carrier: IDuplexCarrierSource | IExchangeCarrierSource,\n): carrier is IExchangeCarrierSource {\n  return \"shape\" in carrier && carrier.shape === \"exchange\";\n}\n","import { EActionForm } from \"../../../ActionDefinition/Action/ActionBase.types\";\nimport type { IActionContext_Data_JsonObject } from \"../../../ActionDefinition/Action/Context/ActionContext.types\";\nimport {\n  EActionPayloadType,\n  type IActionPayload_Base_JsonObject,\n  type TActionPayload_Any_JsonObject,\n} from \"../../../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport type { ActionDomain } from \"../../../ActionDefinition/Domain/ActionDomain\";\nimport type { TPossibleDomainIdList } from \"../../../ActionDefinition/Domain/ActionDomain.types\";\nimport type { IFrameReliabilityWire, ITransportRouteActionParams } from \"../Transport.types\";\n\nexport type { IFrameReliabilityWire } from \"../Transport.types\";\n\n/**\n * Shared building blocks for the binary action codecs (the stateless {@link createBinaryWireAdapter} and\n * the per-connection `createBinaryWireSessionFactory`). Both map a `domain:id` route to a tiny integer\n * and reduce the verbose JSON wire to a positional tuple — they only differ in how much context they\n * carry per frame, so the dictionary + payload (de)assembly live here.\n */\n\n/**\n * The carrier-neutral codec a Link connection uses to (de)serialize action payloads on the wire — the\n * same shape every duplex carrier (WS/WebRTC/in-memory) shares.\n */\nexport interface IActionWireFormat {\n  /**\n   * Pack an outgoing action payload. Return a `string` for text frames (JSON) or a binary\n   * `Uint8Array`/`ArrayBuffer` for optimized binary frames (e.g. msgpackr).\n   */\n  outgoing: (input: ITransportRouteActionParams) => string | Uint8Array | ArrayBuffer;\n  /**\n   * Unpack an incoming frame back into the wire JSON object the runtime hydrates + validates. Return\n   * `undefined` to defer to the connection's built-in JSON parser — this is how binary adapters stay\n   * backward compatible with plain-JSON clients on the same socket.\n   */\n  incoming?: (\n    input: string | ArrayBuffer | Uint8Array | Blob,\n  ) => TActionPayload_Any_JsonObject<any, any> | undefined;\n  /**\n   * Unpack just the reliability integers off a frame (the optional trailing envelope slot), or\n   * `undefined` when the frame carries none (a best-effort frame). Separate from {@link incoming} so the\n   * best-effort decode path stays untouched; the receive-side reliability layer reads this alongside.\n   */\n  incomingReliability?: (\n    input: string | ArrayBuffer | Uint8Array | Blob,\n  ) => IFrameReliabilityWire | undefined;\n}\n\n/**\n * The single integer a reliable frame carries in its trailing envelope slot, chosen by direction:\n * a request carries its `seq`, any reply/progress carries the cumulative `ack`. Returns `undefined`\n * when there's nothing to stamp, so the codec keeps the frame at its best-effort length.\n */\nexport function encodeReliabilitySlot(\n  reliability: { seq?: number; ack?: number } | undefined,\n  payloadType: (typeof ReversePayloadType)[number],\n): number | undefined {\n  if (reliability == null) return undefined;\n  const value = payloadType === EActionPayloadType.request ? reliability.seq : reliability.ack;\n  return value == null ? undefined : value;\n}\n\n/**\n * Reconstruct the {@link IFrameReliabilityWire} from a decoded slot value, by payload direction — or\n * `undefined` when the slot isn't a well-formed reliability integer (a request's `seq` must be an integer\n * `>= 0`; a reply's cumulative `ack` an integer `>= -1`). The slot comes straight off the peer's wire, so\n * a malformed value from a buggy/hostile peer must degrade the frame to best-effort dispatch rather than\n * pollute stream state with a garbage seq.\n */\nexport function decodeReliabilitySlot(\n  value: unknown,\n  payloadType: (typeof ReversePayloadType)[number],\n): IFrameReliabilityWire | undefined {\n  const min = payloadType === EActionPayloadType.request ? 0 : -1;\n  if (typeof value !== \"number\" || !Number.isInteger(value) || value < min) return undefined;\n  return payloadType === EActionPayloadType.request ? { seq: value } : { ack: value };\n}\n\n/**\n * Tiny integer codes for the payload type, so the verbose `\"request\"`/`\"result\"`/`\"progress\"`\n * strings never hit the wire. The index in {@link ReversePayloadType} must line up with the value.\n */\nexport const PayloadTypeToInt: Record<\n  EActionPayloadType.request | EActionPayloadType.result | EActionPayloadType.progress,\n  number\n> = {\n  [EActionPayloadType.request]: 0,\n  [EActionPayloadType.result]: 1,\n  [EActionPayloadType.progress]: 2,\n};\nexport const ReversePayloadType = [\n  EActionPayloadType.request,\n  EActionPayloadType.result,\n  EActionPayloadType.progress,\n] as const;\n\nexport interface IActionRouteMeta {\n  domain: string;\n  id: string;\n  allDomains: TPossibleDomainIdList;\n}\n\nexport interface IActionRouteDictionary {\n  /** `domain:id` → wire integer. */\n  routeToInt: Map<string, number>;\n  /** wire integer → route metadata for reconstruction. */\n  intToRoute: IActionRouteMeta[];\n}\n\n/**\n * Build the positional `domain:id` ↔ integer dictionary. Both ends of a channel MUST build it from\n * the same domains in the same order — the mapping is positional, so a mismatch routes to the wrong\n * action. Add new transported domains to the end of the list.\n */\nexport function buildActionRouteDictionary(domains: ActionDomain<any>[]): IActionRouteDictionary {\n  const routeToInt = new Map<string, number>();\n  const intToRoute: IActionRouteMeta[] = [];\n\n  for (const dom of domains) {\n    for (const actionId of Object.keys(dom.actionSchema)) {\n      const routeKey = `${dom.domain}:${actionId}`;\n      if (routeToInt.has(routeKey)) continue;\n      routeToInt.set(routeKey, intToRoute.length);\n      intToRoute.push({ domain: dom.domain, id: actionId, allDomains: dom.allDomains });\n    }\n  }\n\n  return { routeToInt, intToRoute };\n}\n\n/** Pull the type-specific payload (`input` / `result` / `progress`) out of a wire JSON object. */\nexport function extractWirePayload(json: TActionPayload_Any_JsonObject<any, any>): unknown {\n  if (json.type === EActionPayloadType.request) return json.input;\n  if (json.type === EActionPayloadType.result) return json.result;\n  if (json.type === EActionPayloadType.progress) return json.progress;\n  return undefined;\n}\n\n/**\n * Reassemble a full wire JSON object from its decoded parts. `inputHash`/`outputHash` are emitted\n * empty — the hydration constructors recompute them — and the result still satisfies\n * `isActionPayload_Any_JsonObject` so it flows through validation like a JSON frame.\n */\nexport function assembleWireJson(\n  routeMeta: IActionRouteMeta,\n  payloadType: (typeof ReversePayloadType)[number],\n  time: number,\n  context: IActionContext_Data_JsonObject,\n  // Runtime-dynamic payload straight off the wire (msgpack/JSON) — Valibot validates it on hydrate.\n  payloadData: any,\n): TActionPayload_Any_JsonObject<any, any> {\n  const base: Omit<IActionPayload_Base_JsonObject<EActionPayloadType>, \"type\"> = {\n    form: EActionForm.data,\n    domain: routeMeta.domain,\n    id: routeMeta.id,\n    allDomains: routeMeta.allDomains,\n    time,\n    context,\n  };\n\n  if (payloadType === EActionPayloadType.request) {\n    return { ...base, type: EActionPayloadType.request, input: payloadData, inputHash: \"\" };\n  }\n  if (payloadType === EActionPayloadType.result) {\n    return { ...base, type: EActionPayloadType.result, result: payloadData, outputHash: \"\" };\n  }\n  return { ...base, type: EActionPayloadType.progress, progress: payloadData };\n}\n","import { type IRuntimeCoordinate, RuntimeCoordinate, UNSET_RUNTIME_ENV_ID } from \"@nice-code/wire\";\nimport { pack, unpack } from \"msgpackr\";\nimport { nanoid } from \"nanoid\";\nimport { EActionPayloadType } from \"../../../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport type { ActionDomain } from \"../../../ActionDefinition/Domain/ActionDomain\";\nimport type { ITransportRouteActionParams } from \"../Transport.types\";\nimport {\n  assembleWireJson,\n  buildActionRouteDictionary,\n  decodeReliabilitySlot,\n  encodeReliabilitySlot,\n  extractWirePayload,\n  type IActionWireFormat,\n  type IFrameReliabilityWire,\n  PayloadTypeToInt,\n  ReversePayloadType,\n} from \"./actionWireCodec\";\n\n/**\n * Positional layout of the *session* binary envelope — the leanest frame. Compared to the stateless\n * adapter it replaces the 21-char `cuid` with a small per-connection integer and only carries\n * `originClient` on the very first request of each direction (the peer remembers it afterwards).\n *\n *   [ routeInt, typeInt, corrId, time, originClient?, payloadData ]\n */\nconst ENVELOPE = {\n  route: 0,\n  type: 1,\n  corr: 2,\n  time: 3,\n  originClient: 4,\n  payload: 5,\n  /** Optional trailing slot — present only on a reliable frame (see {@link encodeReliabilitySlot}). */\n  reliability: 6,\n  /** Optional streamKey slot (E3) — present only on a *keyed* reliable frame; makes the frame length 8. */\n  streamKey: 7,\n} as const;\n/**\n * Best-effort frame length. A reliable frame appends the seq/ack slot → {@link ENVELOPE_LENGTH_RELIABLE};\n * a *keyed* reliable frame appends one more (the streamKey) → {@link ENVELOPE_LENGTH_RELIABLE_KEYED}. The\n * distinct lengths are self-discriminating: a peer that predates a length rejects the frame wholesale\n * (never mis-decodes it), so keyless reliable frames stay byte-identical and an old peer drops a keyed one.\n */\nconst ENVELOPE_LENGTH = 6;\nconst ENVELOPE_LENGTH_RELIABLE = 7;\nconst ENVELOPE_LENGTH_RELIABLE_KEYED = 8;\n\n/**\n * How long a pending correlation entry is kept before it's swept. A correlation only matters until its\n * action resolves or times out, so anything older than the longest realistic action timeout can be\n * dropped — this bounds memory when requests time out or a connection dies mid-flight (their replies\n * would never arrive, leaving the entry orphaned). Generous default so live correlations are never\n * pruned (the default transport timeout is 10s).\n */\nconst DEFAULT_CORRELATION_TTL_MS = 5 * 60_000;\n\ntype TFormatMessage = IActionWireFormat;\n\ninterface IPendingCorrelation<V> {\n  value: V;\n  /** Insertion time (ms), used to expire orphaned entries. */\n  time: number;\n}\n\nexport interface IBinaryWireSessionOptions {\n  /** Override how long an unresolved correlation is retained before being swept (ms). */\n  correlationTtlMs?: number;\n}\n\nfunction isKnownIdentity(\n  coordinate: IRuntimeCoordinate | null | undefined,\n): coordinate is IRuntimeCoordinate {\n  return coordinate != null && coordinate.envId !== UNSET_RUNTIME_ENV_ID;\n}\n\n/**\n * Drop entries older than `ttlMs`. Maps keep insertion order and entries are inserted in time order,\n * so the oldest are first — stop sweeping at the first live entry.\n */\nfunction pruneExpired<K, V>(map: Map<K, IPendingCorrelation<V>>, now: number, ttlMs: number): void {\n  for (const [key, entry] of map) {\n    if (now - entry.time <= ttlMs) break;\n    map.delete(key);\n  }\n}\n\n/**\n * Builds a factory of *stateful, per-connection* codecs for {@link LinkTransport} /\n * `ChannelAcceptor` — the maximally compact binary wire. Call the returned factory once per live\n * connection (each socket on the client, each accepted connection on the server) so every channel\n * gets its own correlation + identity state.\n *\n * On top of everything {@link createBinaryWireAdapter} drops, a session also drops:\n * - **`cuid`** — replaced by a per-connection integer correlation id. The initiator maps it to its\n *   real cuid; the responder echoes it; each side reconstructs the cuid from its own map. Correlation\n *   only needs to be unique per socket, so a counter suffices.\n * - **`originClient` after the first request** — the first request each side sends carries its\n *   identity; the peer remembers it and injects it into later frames. Replies omit it entirely (a\n *   reply carries the initiator's own origin, which the initiator already knows).\n *\n * Both ends MUST build the factory from the same domains in the same order (positional dictionary).\n * Text frames still return `undefined` from `incoming`, so JSON clients remain interoperable.\n *\n * Hibernation note: after a server connection is evicted its session resets, so a still-connected\n * client (whose session persists) will keep omitting `originClient`. The server must therefore restore\n * the connection→client binding from its own store (see `ChannelAcceptor.rehydrate`) and\n * inject `originClient` from there — the session alone can't recover it.\n */\nexport function createBinaryWireSessionFactory(\n  domains: ActionDomain<any>[],\n  options?: IBinaryWireSessionOptions,\n): () => TFormatMessage {\n  const { routeToInt, intToRoute } = buildActionRouteDictionary(domains);\n  const unknownIdentity = RuntimeCoordinate.unknown.toJsonObject();\n  const ttlMs = options?.correlationTtlMs ?? DEFAULT_CORRELATION_TTL_MS;\n\n  return (): TFormatMessage => {\n    let outCounter = 0;\n    // Requests this side initiated: correlation id → our cuid (to resolve the eventual reply).\n    const corrToCuid = new Map<number, IPendingCorrelation<string>>();\n    // Requests this side is responding to: our (synthesized) cuid → the correlation id to echo back.\n    const cuidToCorr = new Map<string, IPendingCorrelation<number>>();\n    let selfIdentity: IRuntimeCoordinate | undefined;\n    let peerIdentity: IRuntimeCoordinate | undefined;\n\n    return {\n      outgoing: (input: ITransportRouteActionParams): Uint8Array => {\n        const json = input.action.toJsonObject();\n        const routeKey = `${json.domain}:${json.id}`;\n        const routeInt = routeToInt.get(routeKey);\n        if (routeInt == null) {\n          throw new Error(`[binary-wire] Cannot pack unregistered action route: ${routeKey}`);\n        }\n\n        const now = Date.now();\n        pruneExpired(corrToCuid, now, ttlMs);\n        pruneExpired(cuidToCorr, now, ttlMs);\n\n        let corr: number;\n        let wireIdentity: IRuntimeCoordinate | undefined;\n\n        if (json.type === EActionPayloadType.request) {\n          // Initiator: assign a fresh per-connection correlation id, remember our cuid for the reply.\n          corr = outCounter++;\n          corrToCuid.set(corr, { value: json.context.cuid, time: now });\n\n          // Send our identity only on the first request — the peer remembers it from then on.\n          if (selfIdentity == null && isKnownIdentity(json.context.originClient)) {\n            selfIdentity = json.context.originClient;\n            wireIdentity = json.context.originClient;\n          }\n        } else {\n          // Responder: echo the correlation id the request arrived with.\n          corr = cuidToCorr.get(json.context.cuid)?.value ?? -1;\n          if (json.type === EActionPayloadType.result) cuidToCorr.delete(json.context.cuid);\n        }\n\n        // A reliable frame appends the seq/ack slot; a keyed reliable frame appends the streamKey too; a\n        // best-effort frame stays at ENVELOPE_LENGTH, so its packed bytes are unchanged.\n        const reliabilitySlot = encodeReliabilitySlot(input.reliability, json.type);\n        const streamKey = input.reliability?.streamKey;\n        const length =\n          streamKey != null\n            ? ENVELOPE_LENGTH_RELIABLE_KEYED\n            : reliabilitySlot == null\n              ? ENVELOPE_LENGTH\n              : ENVELOPE_LENGTH_RELIABLE;\n        const envelope = new Array(length);\n        envelope[ENVELOPE.route] = routeInt;\n        envelope[ENVELOPE.type] = PayloadTypeToInt[json.type];\n        envelope[ENVELOPE.corr] = corr;\n        envelope[ENVELOPE.time] = json.time;\n        envelope[ENVELOPE.originClient] = wireIdentity; // undefined except the first request\n        envelope[ENVELOPE.payload] = extractWirePayload(json);\n        if (reliabilitySlot != null) envelope[ENVELOPE.reliability] = reliabilitySlot;\n        if (streamKey != null) envelope[ENVELOPE.streamKey] = streamKey;\n\n        return pack(envelope);\n      },\n\n      incoming: (frame: string | ArrayBuffer | Uint8Array | Blob) => {\n        let buffer: Uint8Array;\n        if (frame instanceof ArrayBuffer) {\n          buffer = new Uint8Array(frame);\n        } else if (frame instanceof Uint8Array) {\n          buffer = frame;\n        } else {\n          return undefined;\n        }\n\n        try {\n          const envelope = unpack(buffer);\n          if (!isSessionEnvelope(envelope)) return undefined;\n\n          const routeMeta = intToRoute[envelope[ENVELOPE.route]];\n          const payloadType = ReversePayloadType[envelope[ENVELOPE.type]];\n          if (routeMeta == null || payloadType == null) return undefined;\n\n          const now = Date.now();\n          pruneExpired(corrToCuid, now, ttlMs);\n          pruneExpired(cuidToCorr, now, ttlMs);\n\n          const corr: number = envelope[ENVELOPE.corr];\n          const time: number = envelope[ENVELOPE.time];\n          const wireIdentity: IRuntimeCoordinate | undefined = envelope[ENVELOPE.originClient];\n\n          let cuid: string;\n          let originClient: IRuntimeCoordinate;\n\n          if (payloadType === EActionPayloadType.request) {\n            // Incoming request: synthesize a local cuid, remember the correlation for our reply.\n            cuid = nanoid();\n            cuidToCorr.set(cuid, { value: corr, time: now });\n\n            if (isKnownIdentity(wireIdentity)) peerIdentity = wireIdentity;\n            originClient = peerIdentity ?? unknownIdentity;\n          } else {\n            // Incoming reply: map the correlation id back to the cuid of the request we initiated.\n            cuid = corrToCuid.get(corr)?.value ?? nanoid();\n            if (payloadType === EActionPayloadType.result) corrToCuid.delete(corr);\n            // A reply carries our own origin (the request originated on this side).\n            originClient = selfIdentity ?? unknownIdentity;\n          }\n\n          const context = { cuid, timeCreated: time, routing: [], originClient };\n          return assembleWireJson(\n            routeMeta,\n            payloadType,\n            time,\n            context,\n            envelope[ENVELOPE.payload],\n          );\n        } catch (e) {\n          console.error(\"[binary-wire] Failed to unpack binary action session frame\", e);\n          return undefined;\n        }\n      },\n\n      // A pure peek at the reliability slot — must NOT touch the correlation/identity state `incoming`\n      // maintains, so it unpacks independently and only reads the trailing integer.\n      incomingReliability: (frame): IFrameReliabilityWire | undefined => {\n        let buffer: Uint8Array;\n        if (frame instanceof ArrayBuffer) buffer = new Uint8Array(frame);\n        else if (frame instanceof Uint8Array) buffer = frame;\n        else return undefined;\n\n        try {\n          const envelope = unpack(buffer);\n          if (\n            !isSessionEnvelope(envelope) ||\n            (envelope.length !== ENVELOPE_LENGTH_RELIABLE &&\n              envelope.length !== ENVELOPE_LENGTH_RELIABLE_KEYED)\n          ) {\n            return undefined;\n          }\n          const payloadType = ReversePayloadType[envelope[ENVELOPE.type]];\n          if (payloadType == null) return undefined;\n          const wire = decodeReliabilitySlot(envelope[ENVELOPE.reliability], payloadType);\n          if (wire == null) return undefined;\n          if (envelope.length === ENVELOPE_LENGTH_RELIABLE_KEYED) {\n            // The streamKey slot comes off the peer's wire — a non-string (buggy/hostile peer) must not\n            // flow into stream ids / control frames, so the whole slot degrades to best-effort.\n            const streamKey = envelope[ENVELOPE.streamKey];\n            if (typeof streamKey !== \"string\") return undefined;\n            wire.streamKey = streamKey;\n          }\n          return wire;\n        } catch {\n          return undefined;\n        }\n      },\n    };\n  };\n}\n\n/** A decoded session frame is one of ours iff it's an array of best-effort or reliable length. */\n// msgpackr yields `any`; this matches the pre-existing `Array.isArray` narrowing the raw envelope indexing relied on.\nfunction isSessionEnvelope(envelope: unknown): envelope is any[] {\n  return (\n    Array.isArray(envelope) &&\n    (envelope.length === ENVELOPE_LENGTH ||\n      envelope.length === ENVELOPE_LENGTH_RELIABLE ||\n      envelope.length === ENVELOPE_LENGTH_RELIABLE_KEYED)\n  );\n}\n","import { ESecurityLevel } from \"@nice-code/wire\";\nimport type { IActionTransportResolvers } from \"./Transport.types\";\nimport {\n  type ETransportShape,\n  type ITransportRouteInfo,\n  type TTransportRouteParams,\n} from \"./Transport.types\";\nimport type { TransportConnection } from \"./TransportConnection\";\n\n/**\n * Context handed to a {@link Transport} definition when a handler builds a live connection from it.\n * Only bidirectional transports (WebSocket / Custom) make use of `resolvers`.\n */\nexport interface ITransportConnectionContext {\n  resolvers?: IActionTransportResolvers;\n}\n\n/**\n * Reusable transport definition. Built by the internal `transport({ carrier, secure })` factory (which\n * `connectChannel` / `serveChannel` drive) and passed to a `ChannelConnector`. A single\n * definition can be shared across multiple handlers — each handler builds its own live\n * {@link TransportConnection} via {@link TransportConnection._createConnection}.\n */\nexport abstract class Transport<T extends ETransportShape = ETransportShape> {\n  abstract readonly type: T;\n\n  /** Internal: build a fresh, per-handler live connection from this definition. */\n  abstract _createConnection(ctx: ITransportConnectionContext): TransportConnection<T>;\n\n  /**\n   * Resolve human-readable info about how a specific action would be routed through this transport\n   * (e.g. the request URL/method, or the WebSocket endpoint). Surfaced in the action devtools.\n   */\n  abstract getRouteInfo(input: TTransportRouteParams): ITransportRouteInfo;\n\n  /** @internal The security level frames received over this transport were protected at. */\n  _inboundSecurityLevel(): ESecurityLevel {\n    return ESecurityLevel.none;\n  }\n}\n","import {\n  establishPlainExchangeSession,\n  establishSecureExchangeSession,\n  type IWireExchangeSession,\n} from \"@nice-code/wire\";\nimport { EActionPayloadType } from \"../../../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport { ERunningActionUpdateType } from \"../../../ActionDefinition/Action/RunningAction.types\";\nimport { isActionPayload_Result_JsonObject } from \"../../../utils/isActionPayload_Result_JsonObject\";\nimport type { IExchangeCarrier } from \"../Carrier/Carrier.types\";\nimport { EErrId_NiceTransport, err_nice_transport } from \"../err_nice_transport\";\nimport type {\n  IActionTransportReadyData_Methods,\n  ISecureClientConfig,\n  TSendActionDataMethod,\n  TUpdateActionRunConfig,\n} from \"../Transport.types\";\n\n/**\n * The action lane over wire's exchange session: wire's\n * `establishPlain/SecureExchangeSession` owns the envelope, the one-time handshake, and the\n * per-request token + crypto; what stays here is the lane — each action's wire rides one\n * exchange, and (for a request) the correlated reply completes the {@link RunningAction} inline\n * (there is no return path — the duplex counterpart is `establishLinkSession`). The lane\n * contributes its handshake payload (`dictionaryVersion`/`channelTags`) exactly as the duplex\n * lane's `handshakeConfig()` does; the exchange path is lane-only (no mux — the protocol contract).\n */\nexport interface IExchangeSessionContext {\n  carrier: IExchangeCarrier;\n  updateRunConfig?: TUpdateActionRunConfig;\n  /** When present (and not `none`) the handshake runs at bring-up; absent ⇒ plain exchange. */\n  secure?: ISecureClientConfig;\n}\n\n/** Plain path (no handshake/token): every action rides a bare `act` envelope, plaintext both ways. */\nexport function finalizePlainExchangeMethods(\n  ctx: IExchangeSessionContext,\n): IActionTransportReadyData_Methods {\n  return buildExchangeMethods(ctx, establishPlainExchangeSession(ctx.carrier));\n}\n\n/** Secure path: run the handshake (two exchanges) once at bring-up, then reuse the token + crypto. */\nexport async function finalizeSecureExchangeMethods(\n  ctx: IExchangeSessionContext & { secure: ISecureClientConfig },\n): Promise<IActionTransportReadyData_Methods> {\n  const session = await establishSecureExchangeSession({\n    carrier: ctx.carrier,\n    secure: ctx.secure,\n    // The lane's handshake payload (E5) — the same fields the duplex lane supplies.\n    lane: { dictionaryVersion: ctx.secure.dictionaryVersion, channels: ctx.secure.channelTags },\n  });\n  return buildExchangeMethods(ctx, session);\n}\n\nfunction buildExchangeMethods(\n  ctx: IExchangeSessionContext,\n  session: IWireExchangeSession,\n): IActionTransportReadyData_Methods {\n  const sendActionData: TSendActionDataMethod = (inputs) => {\n    void runExchange(session, inputs).catch((err) => inputs.runningAction._abort(err));\n  };\n\n  return { sendActionData, updateRunConfig: ctx.updateRunConfig };\n}\n\nasync function runExchange(\n  session: IWireExchangeSession,\n  inputs: Parameters<TSendActionDataMethod>[0],\n): Promise<void> {\n  const { action, runningAction, timeout } = inputs;\n\n  const ac = new AbortController();\n  let timedOut = false;\n  const timeoutId = setTimeout(() => {\n    timedOut = true;\n    ac.abort();\n  }, timeout);\n  const unsubscribe = runningAction.addUpdateListeners([\n    (update) => {\n      if (update.type === ERunningActionUpdateType.finished) {\n        clearTimeout(timeoutId);\n        ac.abort();\n      }\n    },\n  ]);\n\n  try {\n    // Only a request awaits a reply (progress/result payloads aren't sent by a connector over exchange).\n    if (action.type !== EActionPayloadType.request) {\n      await session.send(action.toJsonObject(), { signal: ac.signal });\n      return;\n    }\n\n    const outcome = await session.exchange(action.toJsonObject(), { signal: ac.signal });\n    if (!outcome.ok && outcome.reason === \"peer_error\") {\n      throw err_nice_transport.fromId(EErrId_NiceTransport.send_failed, {\n        actionState: action.type,\n        actionId: action.id,\n        message: outcome.message,\n      });\n    }\n    if (!outcome.ok || !isActionPayload_Result_JsonObject(outcome.wire)) {\n      throw err_nice_transport.fromId(EErrId_NiceTransport.invalid_action_response, {\n        actionId: action.id,\n      });\n    }\n\n    runningAction._completeWithResult(action._domain.hydrateResultPayload(outcome.wire));\n  } catch (err) {\n    if (timedOut) {\n      throw err_nice_transport.fromId(EErrId_NiceTransport.timeout, { timeout });\n    }\n    throw err;\n  } finally {\n    clearTimeout(timeoutId);\n    unsubscribe();\n  }\n}\n","import { TransportConnection as WireTransportConnection } from \"@nice-code/wire\";\nimport type {\n  ETransportShape,\n  IActionTransportDef,\n  IActionTransportInitialized,\n  IActionTransportReadyData_Base,\n  IActionTransportReadyData_Methods,\n  TTransportRouteParams,\n} from \"./Transport.types\";\n\n/**\n * Live, per-handler transport runtime built from a reusable {@link Transport} definition — the\n * action instantiation of wire's generic `TransportConnection` (shared connection design,\n * Phase 2): routing params pinned to {@link ITransportRouteActionParams} and the finalized\n * methods to {@link IActionTransportReadyData_Methods}. The machinery (status processing, cache\n * keys, async bring-up hooks) lives in wire; subclasses (`LinkConnection`, `ExchangeConnection`)\n * are unchanged. Construct these via `definition._createConnection(...)`, never directly.\n */\nexport abstract class TransportConnection<\n  T extends ETransportShape = ETransportShape,\n  RP extends TTransportRouteParams = TTransportRouteParams,\n  RD extends IActionTransportReadyData_Base = IActionTransportReadyData_Base,\n  I extends IActionTransportInitialized<RP, RD> = IActionTransportInitialized<RP, RD>,\n  DEF extends IActionTransportDef<T, I> = IActionTransportDef<T, I>,\n> extends WireTransportConnection<T, RP, RD, IActionTransportReadyData_Methods, I, DEF> {}\n","import { ESecurityLevel } from \"@nice-code/wire\";\nimport {\n  finalizePlainExchangeMethods,\n  finalizeSecureExchangeMethods,\n  type IExchangeSessionContext,\n} from \"../SecureSession/establishExchangeSession\";\nimport {\n  ETransportShape,\n  type IActionTransportReadyData_Methods,\n  type TTransportRouteParams,\n} from \"../Transport.types\";\nimport { TransportConnection } from \"../TransportConnection\";\nimport type {\n  IActionTransportDef_Exchange,\n  IActionTransportInitialized_Exchange,\n  IActionTransportReadyData_Exchange,\n} from \"./TransportExchange.types\";\n\n/**\n * Carrier-agnostic live connection for the exchange (request → single reply) shape — the HTTP\n * counterpart to {@link LinkConnection}. It owns only the bring-up (run the secure handshake on first\n * use); the request/reply lifecycle + crypto live in the shared `establishExchangeSession`.\n */\nexport class ExchangeConnection extends TransportConnection<\n  ETransportShape.exchange,\n  TTransportRouteParams,\n  IActionTransportReadyData_Exchange,\n  IActionTransportInitialized_Exchange,\n  IActionTransportDef_Exchange\n> {\n  constructor(def: Omit<IActionTransportDef_Exchange, \"type\">) {\n    super({ ...def, type: ETransportShape.exchange });\n  }\n\n  protected override _getCacheKey(input: TTransportRouteParams): string {\n    return this.initialized.getCacheKey?.(input).join(\"\\x00\") ?? \"\";\n  }\n\n  // Only a secure exchange needs async bring-up (the handshake). A plain (`none`) exchange is usable the\n  // instant the carrier opens — finalized synchronously like HTTP today.\n  protected override _needsAsyncBringUp(data: IActionTransportReadyData_Exchange): boolean {\n    return data.secureChannel != null && data.secureChannel.securityLevel !== ESecurityLevel.none;\n  }\n\n  protected override _finalizeReady(\n    data: IActionTransportReadyData_Exchange,\n  ): IActionTransportReadyData_Methods | Promise<IActionTransportReadyData_Methods> {\n    const secure = data.secureChannel;\n    if (secure != null && secure.securityLevel !== ESecurityLevel.none) {\n      return finalizeSecureExchangeMethods({ ...this._sessionContext(data), secure });\n    }\n    return this._finalizeTransportMethods(data);\n  }\n\n  _finalizeTransportMethods(\n    data: IActionTransportReadyData_Exchange,\n  ): IActionTransportReadyData_Methods {\n    return finalizePlainExchangeMethods(this._sessionContext(data));\n  }\n\n  private _sessionContext(data: IActionTransportReadyData_Exchange): IExchangeSessionContext {\n    return {\n      carrier: data.carrier,\n      updateRunConfig: data.updateRunConfig,\n      secure: data.secureChannel,\n    };\n  }\n}\n","import {\n  ESecurityLevel,\n  err_wire_connect,\n  protocolsFromCaps,\n  type TWireTapFn,\n  type WireProtocolMux,\n  withExchangeTap,\n} from \"@nice-code/wire\";\nimport { EErrId_NiceAction, err_nice_action } from \"../../../errors/err_nice_action\";\nimport type { IExchangeCarrier } from \"../Carrier/Carrier.types\";\nimport { type ITransportConnectionContext, Transport } from \"../Transport\";\nimport {\n  ETransportShape,\n  ETransportStatus,\n  type ISecureClientConfig,\n  type ITransportRouteInfo,\n  type TTransportRouteParams,\n  type TUpdateActionRunConfig,\n} from \"../Transport.types\";\nimport { ExchangeConnection } from \"./ExchangeConnection\";\n\nexport interface IExchangeTransportOptions {\n  /** Open (or reuse) the exchange carrier for an action — e.g. `httpCarrier(...).open`. */\n  openCarrier: (input: TTransportRouteParams) => IExchangeCarrier;\n  /** Secure config; when set (and `securityLevel !== none`) the handshake runs once at bring-up. */\n  security?: ISecureClientConfig;\n  updateRunConfig?: TUpdateActionRunConfig;\n  /** Keys identifying a reusable session, so one carrier is shared across actions to the same peer. */\n  getCacheKey?: (input: TTransportRouteParams) => string[];\n  /** @deprecated Use `getCacheKey`. */\n  getTransportCacheKey?: (input: TTransportRouteParams) => string[];\n  /**\n   * Optional availability gate. When it returns `false`, the manager skips this transport for that action\n   * (reporting `unsupported`) and falls through to the next — without opening the carrier or computing its\n   * cache key. Re-evaluated per dispatch, so the transport can become available later with no reconnect.\n   */\n  available?: (input: TTransportRouteParams) => boolean;\n  /** Short label for the devtools chip (defaults to \"exchange\"). */\n  label?: string;\n  getRouteInfo?: (input: TTransportRouteParams) => ITransportRouteInfo;\n  /** The connection's frame-protocol mux, when one exists — consulted only by the D-11 guard. */\n  mux?: WireProtocolMux;\n  /**\n   * Whether *every* transport on this connection is exchange-shaped (computed by `connectChannel`).\n   * Prefixed protocols need a duplex transport — on an exchange-only connection they\n   * could never speak, so bringing this transport up with protocols registered on {@link mux}\n   * throws `err_nice_wire_connect.protocol_on_exchange_only` instead of leaving them silently mute.\n   * A mixed chain (duplex preferred, exchange fallback) never sets this: there the protocols\n   * legitimately ride the duplex transport when it is up.\n   */\n  exchangeOnlyConnection?: boolean;\n  /** Wire-traffic observation (devtools) — request/reply envelope bytes under the `\"http\"` lane. */\n  wireTap?: TWireTapFn;\n}\n\n/**\n * A carrier-agnostic exchange (request → single reply) transport: it drives nice-action's secure session\n * over any {@link IExchangeCarrier} (HTTP being the one built-in). The duplex counterpart is\n * {@link LinkTransport}; this is the no-push half — its reply rides the response to its own request, so it\n * can't deliver an unsolicited frame (the runtime never picks it for the return path).\n */\nexport class ExchangeTransport extends Transport<ETransportShape.exchange> {\n  readonly type = ETransportShape.exchange;\n\n  private readonly options: IExchangeTransportOptions;\n\n  constructor(options: IExchangeTransportOptions) {\n    super();\n    if (options.getCacheKey != null && options.getTransportCacheKey != null) {\n      throw err_nice_action.fromId(EErrId_NiceAction.conflicting_connect_options, {\n        detail: \"ExchangeTransport: pass only `getCacheKey`; `getTransportCacheKey` is deprecated\",\n      });\n    }\n    this.options = { ...options, getCacheKey: options.getCacheKey ?? options.getTransportCacheKey };\n  }\n\n  static create(options: IExchangeTransportOptions): ExchangeTransport {\n    return new ExchangeTransport(options);\n  }\n\n  _createConnection(_ctx: ITransportConnectionContext): ExchangeConnection {\n    const options = this.options;\n\n    return new ExchangeConnection({\n      initialize: () => ({\n        getCacheKey: options.getCacheKey,\n        isAvailable: options.available,\n        requiresWebCrypto:\n          options.security != null && options.security.securityLevel !== ESecurityLevel.none,\n        getTransport: (input) => {\n          assertProtocolsRideDuplex(options);\n          const carrier = options.openCarrier(input);\n          return {\n            status: ETransportStatus.ready,\n            readyData: {\n              carrier:\n                options.wireTap != null ? withExchangeTap(carrier, options.wireTap) : carrier,\n              secureChannel: options.security,\n              updateRunConfig: options.updateRunConfig,\n            },\n          };\n        },\n      }),\n    });\n  }\n\n  getRouteInfo(input: TTransportRouteParams): ITransportRouteInfo {\n    if (this.options.getRouteInfo != null) return this.options.getRouteInfo(input);\n    return {\n      carrierLabel: this.options.label ?? \"exchange\",\n      summary: this.options.label ?? \"exchange\",\n    };\n  }\n}\n\n/**\n * The D-11 guard: an exchange-only connection carries only the lane, so a registered prefixed\n * protocol is a configuration error surfaced clearly at bring-up (the first dispatch through this\n * transport) — after registration, which may legitimately happen later than `connectChannel`\n * (e.g. `realmConnection(connector)`), hence not at construction.\n */\nfunction assertProtocolsRideDuplex(options: IExchangeTransportOptions): void {\n  if (options.exchangeOnlyConnection !== true || options.mux == null) return;\n  for (const protocolId of protocolsFromCaps(options.mux.localCaps())) {\n    throw err_wire_connect.fromId(\"protocol_on_exchange_only\", { protocolId });\n  }\n}\n","import type { IActionTransportResolvers } from \"../Transport.types\";\n\nexport const createUnsetTransportResolvers = (\n  transportLabel: string,\n): IActionTransportResolvers => ({\n  onIncomingActionDataJson: (json) => {\n    console.warn(\n      `Received incoming action JSON [${json.domain}:${json.id}] on Transport [${transportLabel}] but no incoming data listener has been set.`,\n    );\n  },\n});\n","import type { NiceError } from \"@nice-code/error\";\nimport {\n  CAP_RELIABLE,\n  CAP_RELIABLE_STREAMKEY,\n  decodeControlFrame,\n  encodeControlFrame,\n  establishPlainDuplexSession,\n  establishSecureDuplexSession,\n  type IWireDuplexSession,\n  type IWireHeartbeat,\n  type IWireLaneEndpoint,\n  type IWireLaneProtocol,\n  type TFrame,\n  type TWireTapFn,\n  warnReliablePeerUnsupportedOnce,\n  warnReliableStreamKeyUnsupportedOnce,\n  warnReliableWireUnavailableOnce,\n} from \"@nice-code/wire\";\nimport { EActionPayloadType } from \"../../../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport type { RunningAction } from \"../../../ActionDefinition/Action/RunningAction\";\nimport { ERunningActionUpdateType } from \"../../../ActionDefinition/Action/RunningAction.types\";\nimport { EReliabilityTier } from \"../../../ActionDefinition/Schema/ActionSchema\";\nimport { decodeActionFrame } from \"../../../utils/decodeActionFrame\";\nimport type { IDuplexCarrier } from \"../Carrier/Carrier.types\";\nimport { EErrId_NiceTransport, err_nice_transport } from \"../err_nice_transport\";\nimport type { TLinkFormatMessage } from \"../Link/TransportLink.types\";\nimport type {\n  IActionTransportReadyData_Methods,\n  IActionTransportResolvers,\n  ISecureClientConfig,\n  TSendActionDataMethod,\n  TUpdateActionRunConfig,\n} from \"../Transport.types\";\n\n/**\n * The action **lane tail** of a connector link session (shared connection design, Phase 2;\n * formalized as the wire lane protocol at Phase 5). The wire half — carrier attach, client\n * handshake, frame-crypto pipe, pre-ready buffering, mux bind, disconnect fan-out — lives in\n * `@nice-code/wire`'s `establish(Plain|Secure)DuplexSession`; what stays here is everything that\n * speaks *actions*: the codec (binary wire / JSON fallback), control-frame decode, reliability\n * warnings/stripping, per-send timeouts + the abort set, and the\n * {@link IActionTransportReadyData_Methods} surface `LinkConnection` exposes upward — packaged as\n * the {@link IWireLaneProtocol} implementation the session drives (E5: action owns the\n * unprefixed-frame namespace and supplies the handshake's `dictionaryVersion`/`channels`).\n */\nexport interface ILinkSessionContext {\n  channel: IDuplexCarrier;\n  resolvers: IActionTransportResolvers;\n  formatMessage?: TLinkFormatMessage;\n  updateRunConfig?: TUpdateActionRunConfig;\n  /** The error used to abort in-flight actions when the channel is closed/gone (carrier-specific). */\n  makeDisconnectError: (actionId: string) => NiceError;\n  /** Wire keepalive (8b.3) — half-open detection for this link's session; `undefined` = off. */\n  heartbeat?: IWireHeartbeat;\n  /** Wire-traffic observation (devtools) — reports every carrier frame's true bytes. */\n  wireTap?: TWireTapFn;\n}\n\n/**\n * The action lane as a wire lane endpoint: every unprefixed frame decodes here (control frame →\n * action frame), and a lost connection aborts the in-flight best-effort sends.\n */\nfunction connectorLaneEndpoint(\n  ctx: ILinkSessionContext,\n  abortSet: Set<RunningAction<any, any>>,\n): IWireLaneEndpoint {\n  return {\n    id: \"action\",\n    onLaneFrame: (frame) => handleLaneFrame(ctx, frame),\n    onDetach: () => abortInFlight(ctx, abortSet),\n  };\n}\n\n/** Plain path (no handshake): route every inbound frame to the runtime; send without crypto. */\nexport function finalizePlainLinkMethods(\n  ctx: ILinkSessionContext,\n): IActionTransportReadyData_Methods {\n  const abortSet = new Set<RunningAction<any, any>>();\n  const session = establishPlainDuplexSession({\n    channel: ctx.channel,\n    lane: connectorLaneEndpoint(ctx, abortSet),\n    heartbeat: ctx.heartbeat,\n    tap: ctx.wireTap,\n  });\n  return buildSendMethods(ctx, session, abortSet);\n}\n\n/**\n * Secure path: the wire session runs the handshake (buffering frames that race ahead), then lane\n * frames flow here. The lane protocol supplies the handshake payload (E5 — `dictionaryVersion`/\n * `channelTags` come off the action channel via {@link ISecureClientConfig}, which is the lane's\n * own config surface; wire consumes only the neutral core). `remoteReliable`/`remoteStreamKey`\n * come off the negotiated caps.\n */\nexport async function finalizeSecureLinkMethods(\n  ctx: ILinkSessionContext & { secure: ISecureClientConfig },\n): Promise<IActionTransportReadyData_Methods> {\n  const abortSet = new Set<RunningAction<any, any>>();\n  const lane: IWireLaneProtocol = {\n    ...connectorLaneEndpoint(ctx, abortSet),\n    handshakeConfig: () => ({\n      dictionaryVersion: ctx.secure.dictionaryVersion,\n      channels: ctx.secure.channelTags,\n    }),\n  };\n  const session = await establishSecureDuplexSession({\n    channel: ctx.channel,\n    secure: ctx.secure,\n    lane,\n    mux: ctx.secure.mux,\n    heartbeat: ctx.heartbeat,\n    tap: ctx.wireTap,\n  });\n\n  // `remoteReliable`/`remoteStreamKey` are known (true/false) for a secure connection: an old peer omits the\n  // cap, so a `.reliable()` (or keyed) send warns + degrades. The plain path can't negotiate caps → both\n  // `undefined` (no warn).\n  return buildSendMethods(\n    ctx,\n    session,\n    abortSet,\n    session.remoteCaps?.includes(CAP_RELIABLE) ?? false,\n    session.remoteCaps?.includes(CAP_RELIABLE_STREAMKEY) ?? false,\n  );\n}\n\nfunction buildSendMethods(\n  ctx: ILinkSessionContext,\n  session: IWireDuplexSession,\n  abortSet: Set<RunningAction<any, any>>,\n  /** Secure path only: whether the peer advertised reliable support. `undefined` = unknown (plain path). */\n  remoteReliable?: boolean,\n  /** Secure path only: whether the peer advertised streamkey (E3) support. `undefined` = unknown (plain). */\n  remoteStreamKey?: boolean,\n): IActionTransportReadyData_Methods {\n  const sendActionData: TSendActionDataMethod = (inputs) => {\n    const { action, runningAction, timeout } = inputs;\n\n    // A reliable request owns its own lifecycle in the connector's outbox: it must NOT be aborted when\n    // this connection drops (the outbox resends it on reconnect) and it does NOT use the normal\n    // per-send timeout (delivery is guaranteed by resend, bounded by the outbox window). Best-effort\n    // requests keep their existing abort-on-close + timeout behaviour, byte-for-byte unchanged.\n    const isReliableRequest =\n      action.type === EActionPayloadType.request &&\n      action.schema?.reliabilityTier != null &&\n      action.schema.reliabilityTier !== EReliabilityTier.none;\n\n    if (!session.isOpen()) {\n      if (action.type === EActionPayloadType.request && !isReliableRequest) {\n        runningAction._abort(ctx.makeDisconnectError(action.id));\n      }\n      return;\n    }\n\n    if (action.type === EActionPayloadType.request && !isReliableRequest) {\n      abortSet.add(runningAction);\n      const timeoutId = setTimeout(() => {\n        runningAction._abort(err_nice_transport.fromId(EErrId_NiceTransport.timeout, { timeout }));\n      }, timeout);\n      runningAction.addUpdateListeners([\n        (update) => {\n          if (update.type === ERunningActionUpdateType.finished) {\n            clearTimeout(timeoutId);\n            abortSet.delete(runningAction);\n          }\n        },\n      ]);\n    }\n\n    // A reliable frame carries a `reliability` slot the binary codec writes; with no codec the JSON fallback\n    // below drops it, silently degrading the frame to best-effort. Surface that once per route.\n    let sendInputs = inputs;\n    if (inputs.reliability != null) {\n      if (ctx.formatMessage == null) {\n        warnReliableWireUnavailableOnce(action.domain, action.id);\n      } else if (remoteReliable === false) {\n        // Secure peer that predates reliable support (no `reliable` cap in its welcome): its decoder only\n        // accepts the best-effort envelope length, so a frame carrying the slot would be rejected\n        // *wholesale* — not delivered at all. Strip the slot instead: the frame goes out genuinely\n        // best-effort (byte-identical to a non-reliable send) and is delivered; ordering/dedup/resend\n        // don't apply. Warn once so the version skew is visible. (The outbox still tracks the send — its\n        // delivery deadline eventually abandons it, since a slot-less frame is never acked.)\n        warnReliablePeerUnsupportedOnce(action.domain, action.id);\n        sendInputs = { ...inputs, reliability: undefined };\n      } else if (inputs.reliability.streamKey != null && remoteStreamKey === false) {\n        // Secure peer that supports reliability but not *keyed* streams (E3): a keyed frame is a distinct\n        // length it drops wholesale, so it won't be delivered. The key can NOT be safely stripped (that\n        // would merge independent seq spaces into the single default stream and corrupt its dedup), so\n        // this stays a clean non-delivery. Warn once so the version skew is visible.\n        warnReliableStreamKeyUnsupportedOnce(action.domain, action.id);\n      }\n    }\n\n    session.send(\n      ctx.formatMessage?.outgoing(sendInputs) ?? JSON.stringify(sendInputs.action.toJsonObject()),\n    );\n  };\n\n  return {\n    sendActionData,\n    // Sender-originated control frames (`rskip`, …) ride the same pipe as action frames, so on a secure\n    // connection they're encrypted + ordered with the stream they control.\n    sendControlData: (message) => {\n      if (!session.isOpen()) return;\n      session.send(encodeControlFrame(message));\n    },\n    updateRunConfig: ctx.updateRunConfig,\n    addOnDisconnectListener: (cb) => session.addOnDisconnectListener(cb),\n    disconnect: () => session.close(),\n    sendReturnData: (payload, clients) => {\n      const formatted =\n        clients != null ? ctx.formatMessage?.outgoing({ action: payload, ...clients }) : undefined;\n      session.send(formatted ?? JSON.stringify(payload.toJsonObject()));\n    },\n  };\n}\n\n/**\n * One inbound lane frame (already decrypted; the mux never saw it or didn't claim it): a control\n * frame or an action frame — the lane's whole receive vocabulary.\n */\nfunction handleLaneFrame(ctx: ILinkSessionContext, frame: TFrame): void {\n  // Peek for a transport control frame (reliability ack, …) before the action path — a cheap first-byte\n  // check short-circuits action frames, so best-effort decoding is unchanged.\n  const control = decodeControlFrame(frame);\n  if (control != null) {\n    ctx.resolvers.onControlMessage?.(control);\n    return;\n  }\n\n  const rawJson = decodeActionFrame(frame, ctx.formatMessage);\n  if (rawJson != null) {\n    // Surface the reliability integers (seq/ack) alongside the frame so the connector can prune its\n    // outbox and the acceptor can dedup. Only pass the second arg for an actual reliable frame — the\n    // best-effort receive call stays exactly one arg (unchanged contract).\n    const reliability = ctx.formatMessage?.incomingReliability?.(frame);\n    if (reliability != null) ctx.resolvers.onIncomingActionDataJson(rawJson, reliability);\n    else ctx.resolvers.onIncomingActionDataJson(rawJson);\n  }\n}\n\nfunction abortInFlight(ctx: ILinkSessionContext, abortSet: Set<RunningAction<any, any>>): void {\n  const error = ctx.makeDisconnectError(\"—\");\n  for (const ra of [...abortSet]) ra._abort(error);\n}\n","import type { NiceError } from \"@nice-code/error\";\nimport { ESecurityLevel } from \"@nice-code/wire\";\nimport { EErrId_NiceTransport, err_nice_transport } from \"../err_nice_transport\";\nimport { createUnsetTransportResolvers } from \"../helpers/createUnsetTransportResolvers\";\nimport {\n  finalizePlainLinkMethods,\n  finalizeSecureLinkMethods,\n  type ILinkSessionContext,\n} from \"../SecureSession/establishLinkSession\";\nimport {\n  ETransportShape,\n  type IActionTransportReadyData_Methods,\n  type IActionTransportResolvers,\n  type TTransportRouteParams,\n} from \"../Transport.types\";\nimport { TransportConnection } from \"../TransportConnection\";\nimport type {\n  IActionTransportDef_Link,\n  IActionTransportInitialized_Link,\n  IActionTransportReadyData_Link,\n} from \"./TransportLink.types\";\n\n/** Abort error for a closed link channel (carrier-neutral — the carrier itself isn't named). */\nfunction linkDisconnectError(actionId: string): NiceError {\n  return err_nice_transport.fromId(EErrId_NiceTransport.send_failed, {\n    actionId,\n    actionState: \"request\",\n    message: \"link channel disconnected\",\n  });\n}\n\n/**\n * Carrier-agnostic live connection. It owns only the *bring-up* (open the carrier, then run the secure\n * session); the session itself — handshake, frame crypto, codec, send/receive — lives in the shared\n * {@link finalizeSecureLinkMethods}/{@link finalizePlainLinkMethods}, so a WebSocket, a WebRTC data\n * channel, a Bluetooth characteristic, and an in-memory pipe all run the identical secure layer.\n */\nexport class LinkConnection extends TransportConnection<\n  ETransportShape.duplex,\n  TTransportRouteParams,\n  IActionTransportReadyData_Link,\n  IActionTransportInitialized_Link,\n  IActionTransportDef_Link\n> {\n  private resolvers: IActionTransportResolvers;\n\n  constructor(def: Omit<IActionTransportDef_Link, \"type\">, resolvers?: IActionTransportResolvers) {\n    super({ ...def, type: ETransportShape.duplex });\n    this.resolvers = resolvers ?? createUnsetTransportResolvers(\"link\");\n  }\n\n  protected override _getCacheKey(input: TTransportRouteParams): string {\n    return this.initialized.getCacheKey?.(input).join(\"\\x00\") ?? \"\";\n  }\n\n  // A link is always brought up asynchronously: open the carrier (`channel.ready`), then run the\n  // handshake when secure. The base reports `initializing` and drives these hooks.\n  protected override _needsAsyncBringUp(): boolean {\n    return true;\n  }\n\n  protected override _awaitCarrierReady(data: IActionTransportReadyData_Link): Promise<void> {\n    return data.channel.ready;\n  }\n\n  protected override _finalizeReady(\n    data: IActionTransportReadyData_Link,\n  ): IActionTransportReadyData_Methods | Promise<IActionTransportReadyData_Methods> {\n    const secure = data.secureChannel;\n    if (secure != null && secure.securityLevel !== ESecurityLevel.none) {\n      return finalizeSecureLinkMethods({ ...this._sessionContext(data), secure });\n    }\n    return this._finalizeTransportMethods(data);\n  }\n\n  private _sessionContext(data: IActionTransportReadyData_Link): ILinkSessionContext {\n    return {\n      channel: data.channel,\n      resolvers: this.resolvers,\n      formatMessage: data.formatMessage,\n      updateRunConfig: data.updateRunConfig,\n      makeDisconnectError: linkDisconnectError,\n      heartbeat: data.heartbeat,\n      wireTap: data.wireTap,\n    };\n  }\n\n  // Public (not `protected`) so the binary-frame test can finalize a connection's methods directly.\n  _finalizeTransportMethods(\n    data: IActionTransportReadyData_Link,\n  ): IActionTransportReadyData_Methods {\n    return finalizePlainLinkMethods(this._sessionContext(data));\n  }\n}\n","import { ESecurityLevel } from \"@nice-code/wire\";\nimport { EErrId_NiceAction, err_nice_action } from \"../../../errors/err_nice_action\";\nimport type { IDuplexCarrier } from \"../Carrier/Carrier.types\";\nimport { type ITransportConnectionContext, Transport } from \"../Transport\";\nimport {\n  ETransportShape,\n  ETransportStatus,\n  type ISecureClientConfig,\n  type ITransportRouteInfo,\n  type TTransportRouteParams,\n  type TUpdateActionRunConfig,\n} from \"../Transport.types\";\nimport { LinkConnection } from \"./LinkConnection\";\nimport type { TLinkFormatMessage } from \"./TransportLink.types\";\n\nexport interface ILinkTransportOptions {\n  /**\n   * Open (or reuse) the carrier for an action — a WebSocket adapter, a WebRTC data channel, a Bluetooth\n   * characteristic, an in-memory pipe, anything that satisfies {@link IDuplexCarrier}.\n   */\n  openChannel: (input: TTransportRouteParams) => IDuplexCarrier;\n  /** Shared codec for every channel (stateless). */\n  formatMessage?: TLinkFormatMessage;\n  /**\n   * Per-channel codec factory — called once per opened channel so stateful codecs (e.g. the binary\n   * session) get their own instance. Takes precedence over `formatMessage`.\n   */\n  createFormatMessage?: () => TLinkFormatMessage;\n  /** Secure-channel config; when set (and `securityLevel !== none`) the handshake runs on init. */\n  security?: ISecureClientConfig;\n  updateRunConfig?: TUpdateActionRunConfig;\n  /** Keys identifying a reusable channel, so one carrier is shared across actions to the same peer. */\n  getCacheKey?: (input: TTransportRouteParams) => string[];\n  /** @deprecated Use `getCacheKey`. */\n  getTransportCacheKey?: (input: TTransportRouteParams) => string[];\n  /**\n   * Optional availability gate. When it returns `false`, the manager skips this transport for that action\n   * (reporting `unsupported`) and falls through to the next — without opening the carrier or computing its\n   * cache key. Re-evaluated per dispatch, so the transport can become available later with no reconnect.\n   */\n  available?: (input: TTransportRouteParams) => boolean;\n  /** Short label for the devtools chip (defaults to \"link\"). */\n  label?: string;\n  getRouteInfo?: (input: TTransportRouteParams) => ITransportRouteInfo;\n  /**\n   * Wire keepalive (8b.3) resolver — a thunk so `connectChannel` can decide **at dial time**\n   * (protocols register on the mux after the connector is built; the auto-on default depends on\n   * them). Returns the concrete config, or `undefined` for off.\n   */\n  heartbeat?: () => import(\"@nice-code/wire\").IWireHeartbeat | undefined;\n  /** @deprecated Use `heartbeat`. */\n  linkKeepalive?: () => import(\"@nice-code/wire\").IWireHeartbeat | undefined;\n  /** Wire-traffic observation (devtools) — threaded into every dial's session (survives redials). */\n  wireTap?: import(\"@nice-code/wire\").TWireTapFn;\n}\n\n/**\n * A carrier-agnostic transport: it drives nice-action's secure session + action routing over any\n * {@link IDuplexCarrier}. The WebSocket transport is the special case that opens a `WebSocket`;\n * this opens whatever `openChannel` returns, so the identical secure layer works over WebRTC, Bluetooth,\n * or an in-memory pipe. Reported with an overridable carrier label in the devtools (defaults to \"link\").\n */\nexport class LinkTransport extends Transport<ETransportShape.duplex> {\n  readonly type = ETransportShape.duplex;\n\n  private readonly options: ILinkTransportOptions;\n\n  constructor(options: ILinkTransportOptions) {\n    super();\n    if (options.getCacheKey != null && options.getTransportCacheKey != null) {\n      throw err_nice_action.fromId(EErrId_NiceAction.conflicting_connect_options, {\n        detail: \"LinkTransport: pass only `getCacheKey`; `getTransportCacheKey` is deprecated\",\n      });\n    }\n    if (options.heartbeat != null && options.linkKeepalive != null) {\n      throw err_nice_action.fromId(EErrId_NiceAction.conflicting_connect_options, {\n        detail: \"LinkTransport: pass only `heartbeat`; `linkKeepalive` is deprecated\",\n      });\n    }\n    this.options = {\n      ...options,\n      getCacheKey: options.getCacheKey ?? options.getTransportCacheKey,\n      heartbeat: options.heartbeat ?? options.linkKeepalive,\n    };\n  }\n\n  static create(options: ILinkTransportOptions): LinkTransport {\n    return new LinkTransport(options);\n  }\n\n  _createConnection(ctx: ITransportConnectionContext): LinkConnection {\n    const options = this.options;\n\n    return new LinkConnection(\n      {\n        initialize: () => ({\n          getCacheKey: options.getCacheKey,\n          isAvailable: options.available,\n          requiresWebCrypto:\n            options.security != null && options.security.securityLevel !== ESecurityLevel.none,\n          getTransport: (input) => ({\n            status: ETransportStatus.ready,\n            readyData: {\n              channel: options.openChannel(input),\n              formatMessage: options.createFormatMessage?.() ?? options.formatMessage,\n              updateRunConfig: options.updateRunConfig,\n              secureChannel: options.security,\n              heartbeat: options.heartbeat?.(),\n              wireTap: options.wireTap,\n            },\n          }),\n        }),\n      },\n      ctx.resolvers,\n    );\n  }\n\n  // A secure client handshake only completes at exactly the level it requested.\n  override _inboundSecurityLevel(): ESecurityLevel {\n    return this.options.security?.securityLevel ?? ESecurityLevel.none;\n  }\n\n  getRouteInfo(input: TTransportRouteParams): ITransportRouteInfo {\n    if (this.options.getRouteInfo != null) return this.options.getRouteInfo(input);\n    return {\n      carrierLabel: this.options.label ?? \"link\",\n      summary: this.options.label ?? \"link\",\n    };\n  }\n}\n","import { ClientCryptoKeyLink, type StorageAdapter } from \"@nice-code/util\";\nimport { ESecurityLevel } from \"@nice-code/wire\";\nimport type { ActionRuntime } from \"../ActionRuntime\";\nimport type { IActionChannel } from \"../Channel/ActionChannel\";\nimport {\n  type IDuplexCarrierSource,\n  type IExchangeCarrierSource,\n  isExchangeCarrierSource,\n  toActionDialParams,\n} from \"./Carrier/Carrier.types\";\nimport { ExchangeTransport } from \"./Exchange/ExchangeTransport\";\nimport { LinkTransport } from \"./Link/LinkTransport\";\nimport type { TTransportRouteParams } from \"./Transport.types\";\n\nexport interface ITransportOptions {\n  /**\n   * How to reach the peer. A duplex carrier (`wsCarrier(() => ({ url }))`, `rtcCarrier(dc)`,\n   * `inMemoryCarrier().carrier`) builds a push-capable {@link LinkTransport}; an exchange carrier\n   * (`httpCarrier(...)`) builds a request/reply {@link ExchangeTransport}.\n   */\n  carrier: IDuplexCarrierSource | IExchangeCarrierSource;\n  /** The shared channel identity (per-connection codec + dictionary version) — same one both ends use. */\n  channel: IActionChannel;\n  /** This peer's runtime — its coordinate is the authenticated identity sent in the handshake. */\n  runtime: ActionRuntime;\n  /**\n   * Override the identity this transport authenticates as, when the connection carries its own\n   * (`connectChannel`'s `connectionId`). Defaults to the runtime's coordinate.\n   */\n  identity?: import(\"@nice-code/wire\").RuntimeCoordinate;\n  /** Expected peer identity verified by secure handshakes. Omit only for low-level transport use. */\n  expectedPeer?: import(\"@nice-code/wire\").RuntimeCoordinate;\n  /**\n   * Run the authenticated/encrypted handshake over this carrier (`true`), or carry the bare action wire\n   * with no crypto (`false`). A secure transport needs a crypto identity (`link` or `storage`); a plain\n   * one needs neither.\n   */\n  secure: boolean;\n  /**\n   * The crypto identity for a secure transport. Defaults to a fresh {@link ClientCryptoKeyLink} over\n   * `storage`. Pass an existing link to share one identity across several secure transports to the same\n   * peer (e.g. a secure WS preferred + secure HTTP fallback), so they present the same verify/exchange keys.\n   */\n  link?: ClientCryptoKeyLink;\n  /** Backing store for the crypto identity when no `link` is given (secure transports only). */\n  storage?: StorageAdapter;\n  /** The level a secure transport requests; the peer must allow it. Defaults to `authenticated`. */\n  securityLevel?: ESecurityLevel;\n  /** See `connectChannel`'s `reuseExchangeSessions` (exchange carriers only). */\n  reuseExchangeSessions?: boolean;\n  /**\n   * Optional availability gate. When it returns `false`, this transport reports as `unsupported` for that\n   * action and the manager falls through to the next transport in preference order — without opening the\n   * carrier or computing its cache key. Re-evaluated per dispatch. Omit = always available.\n   */\n  available?: (input: TTransportRouteParams) => boolean;\n  /** Override the devtools chip label (defaults to the carrier's `carrierLabel`). */\n  label?: string;\n  /** Optional frame-protocol mux threaded into the secure config (see `ISecureClientConfig.mux`). */\n  mux?: import(\"@nice-code/wire\").WireProtocolMux;\n  /**\n   * Whether *every* transport on this connection is exchange-shaped (computed by `connectChannel`).\n   * Protocols need a duplex transport — an exchange transport built with this set\n   * throws `protocol_on_exchange_only` at bring-up when {@link mux} has registered protocols.\n   */\n  exchangeOnlyConnection?: boolean;\n  /**\n   * Wire keepalive (8b.3) resolver, threaded by `connectChannel` — resolved per dial (see\n   * `ILinkTransportOptions.heartbeat`). Duplex transports only; an exchange transport has no\n   * long-lived link to keep alive.\n   */\n  heartbeat?: () => import(\"@nice-code/wire\").IWireHeartbeat | undefined;\n  /**\n   * Wire-traffic observation (devtools): every frame this transport actually puts on / takes off\n   * the carrier is reported with its true wire byte size and lane (`action`, `realm`, `handshake`,\n   * `keepalive`, `http`). Threaded by `connectChannel({ wireTap })`.\n   */\n  wireTap?: import(\"@nice-code/wire\").TWireTapFn;\n}\n\n/**\n * The one transport factory — swap the carrier to change protocol, flip `secure` to add or drop the\n * crypto layer. A {@link IDuplexCarrierSource} builds a push-capable {@link LinkTransport} (WS is just\n * `carrier: wsCarrier(() => ({ url }))`), an {@link IExchangeCarrierSource} builds a request/reply\n * {@link ExchangeTransport} (HTTP). When `secure`, it folds in the handshake `security` block (the\n * {@link ClientCryptoKeyLink} from `storage`, the runtime coordinate, the channel's dictionary version);\n * when not, it carries the bare wire. The internal building block both `connectChannel` and `serveChannel`\n * drive — consumers connect via those single entry points, not this directly.\n */\nexport function transport(\n  options: ITransportOptions & { carrier: IDuplexCarrierSource },\n): LinkTransport;\nexport function transport(\n  options: ITransportOptions & { carrier: IExchangeCarrierSource },\n): ExchangeTransport;\nexport function transport(options: ITransportOptions): LinkTransport | ExchangeTransport;\nexport function transport(options: ITransportOptions): LinkTransport | ExchangeTransport {\n  const { carrier, channel, available, label } = options;\n  const labelFor = label ?? carrier.carrierLabel;\n  const carrierGetCacheKey = carrier.getCacheKey;\n  const carrierGetRouteInfo = carrier.getRouteInfo;\n\n  // The handshake `security` block, assembled once for a secure transport (omitted for a plain one).\n  let security: Parameters<typeof LinkTransport.create>[0][\"security\"];\n  if (options.secure) {\n    const link =\n      options.link ??\n      (options.storage != null\n        ? new ClientCryptoKeyLink({ storageAdapter: options.storage })\n        : undefined);\n    if (link == null) {\n      throw new Error(\n        \"transport: a secure transport requires `link` or `storage` for the crypto identity.\",\n      );\n    }\n    security = {\n      securityLevel: options.securityLevel ?? ESecurityLevel.authenticated,\n      link,\n      localCoordinate: (options.identity ?? options.runtime.coordinate).toJsonObject(),\n      expectedPeer: options.expectedPeer?.toJsonObject(),\n      reuseExchangeSessions: options.reuseExchangeSessions,\n      dictionaryVersion: channel.dictionaryVersion,\n      channelTags: channel.tags,\n      mux: options.mux,\n    };\n  }\n\n  if (isExchangeCarrierSource(carrier)) {\n    // An exchange carrier JSON-encodes the action wire in its envelope, so it needs no channel codec.\n    return ExchangeTransport.create({\n      openCarrier: (input) => carrier.open(toActionDialParams(input)),\n      getCacheKey:\n        carrierGetCacheKey == null\n          ? undefined\n          : (input) => carrierGetCacheKey(toActionDialParams(input)),\n      available: available ?? carrier.available,\n      getRouteInfo:\n        carrierGetRouteInfo == null\n          ? undefined\n          : (input) => carrierGetRouteInfo(toActionDialParams(input)),\n      label: labelFor,\n      security,\n      mux: options.mux,\n      exchangeOnlyConnection: options.exchangeOnlyConnection,\n      wireTap: options.wireTap,\n    });\n  }\n\n  // A duplex link frames the action wire itself, so it always needs the channel's codec.\n  return LinkTransport.create({\n    openChannel: (input) => carrier.open(toActionDialParams(input)),\n    createFormatMessage: channel.createCodec,\n    getCacheKey:\n      carrierGetCacheKey == null\n        ? undefined\n        : (input) => carrierGetCacheKey(toActionDialParams(input)),\n    available: available ?? carrier.available,\n    getRouteInfo:\n      carrierGetRouteInfo == null\n        ? undefined\n        : (input) => carrierGetRouteInfo(toActionDialParams(input)),\n    label: labelFor,\n    security,\n    heartbeat: options.heartbeat,\n    wireTap: options.wireTap,\n  });\n}\n","import type { ClientCryptoKeyLink, StorageAdapter } from \"@nice-code/util\";\nimport type { RuntimeCoordinate } from \"@nice-code/wire\";\nimport { assembleWireConnectionParts, ESecurityLevel, securityLevelMeets } from \"@nice-code/wire\";\nimport type { ActionDomain } from \"../../ActionDefinition/Domain/ActionDomain\";\nimport type { TWrappableDomainActionHandler } from \"../../ActionDefinition/Domain/ActionDomain.types\";\nimport { EErrId_NiceAction, err_nice_action } from \"../../errors/err_nice_action\";\nimport type { ActionRuntime } from \"../ActionRuntime\";\nimport type { ActionLocalHandler } from \"../Handler/Local/ActionLocalHandler\";\nimport type {\n  ChannelAcceptor,\n  TAcceptorCaseFn,\n} from \"../Handler/PeerLink/Acceptor/ChannelAcceptor\";\nimport {\n  createSecureChannelAcceptor,\n  type ISecureChannelAcceptorOptions,\n} from \"../Handler/PeerLink/Acceptor/createSecureChannelAcceptor\";\nimport type { ChannelConnector } from \"../Handler/PeerLink/Connector/ChannelConnector\";\nimport type {\n  TLinkEvent,\n  TReliableStreamEvent,\n} from \"../Handler/PeerLink/Connector/ChannelConnector.types\";\nimport {\n  type IDuplexCarrierSource,\n  type IExchangeCarrierSource,\n  isExchangeCarrierSource,\n} from \"../Transport/Carrier/Carrier.types\";\nimport {\n  buildActionRouteDictionary,\n  type IActionWireFormat,\n} from \"../Transport/codec/actionWireCodec\";\nimport {\n  createBinaryWireSessionFactory,\n  type IBinaryWireSessionOptions,\n} from \"../Transport/codec/createBinaryWireSessionFactory\";\nimport { transport } from \"../Transport/createTransport\";\nimport type { Transport } from \"../Transport/Transport\";\nimport type { TTransportRouteParams } from \"../Transport/Transport.types\";\n\n/**\n * A transport-agnostic routing contract between two runtimes, declared *by role* rather than by\n * \"client\"/\"server\". The two ends are named for the only asymmetry that survives every carrier (WS,\n * WebRTC, BLE, raw TCP): which side dials and which side accepts.\n *\n * - The **connector** dials out and opens the link ({@link connectChannel}).\n * - The **acceptor** accepts incoming links and can push back ({@link acceptChannelConnections}).\n *\n * `toAcceptor` domains flow connector→acceptor (the classic \"request\"); `toConnector` domains flow\n * acceptor→connector (the classic \"push\"). Both ends derive their routing from the same channel instead\n * of restating domain lists — and because the contract is independent of how bytes move, the very same\n * channel can be carried over HTTP, secure WebSockets, or a mix (WS preferred, HTTP fallback).\n *\n * Beyond the routing, a channel also carries its *wire identity* — the per-connection binary codec both\n * ends build from the same domain list, plus the `dictionaryVersion` the handshake checks for drift.\n * Whether a given transport runs encrypted is a per-transport choice (see {@link IConnectTransport.secure}\n * and the acceptor's `securityLevel`), not a property of the channel — so one `defineChannel` definition\n * serves both plain and secure transports.\n */\nexport interface IActionChannel<\n  TO_ACCEPTOR extends readonly ActionDomain<any>[] = readonly ActionDomain<any>[],\n  TO_CONNECTOR extends readonly ActionDomain<any>[] = readonly ActionDomain<any>[],\n> {\n  /**\n   * Domains the connector *sends to the acceptor* (connector→acceptor requests). The connector forwards\n   * them over its transport(s); the acceptor executes them.\n   */\n  toAcceptorDomains: TO_ACCEPTOR;\n  /**\n   * Domains the acceptor *pushes to the connector* (acceptor→connector). The connector registers local\n   * handlers for them ({@link connectChannel}'s `onPush`); the acceptor broadcasts them. Pushes need a\n   * bidirectional transport (e.g. a WebSocket) — over a request-only transport like HTTP they simply\n   * never flow.\n   */\n  toConnectorDomains: TO_CONNECTOR;\n  /** Wire dictionary version — derived from the domains by default; the handshake rejects a mismatch. */\n  dictionaryVersion: string;\n  /** Per-connection session codec factory (call once per live connection). */\n  createCodec: () => IActionWireFormat;\n  /**\n   * Stable channel id, auto-derived from the channel's domain *names* (so it survives action-level\n   * evolution — adding an action changes `dictionaryVersion`, not `tag`). A connecting client advertises\n   * it in the handshake so a multi-channel acceptor can select/compose the right codec per connection.\n   */\n  tag: string;\n  /**\n   * The constituent channel tags this channel carries: `[tag]` for a plain channel, the parts in order for\n   * a {@link combineChannels} result. This is what the connector advertises to the acceptor (`hello.channels`).\n   */\n  tags: readonly string[];\n}\n\n/**\n * Derive a stable channel tag from the domain *names* (not the action list), so the tag identifies the\n * channel across action-level changes — those move `dictionaryVersion` (the drift check), never the tag.\n */\nfunction deriveChannelTag(domains: readonly ActionDomain<any>[]): string {\n  return domains.map((domain) => domain.domain).join(\"+\");\n}\n\n/**\n * Derive a stable wire-dictionary version from the ordered route list (FNV-1a over `domain:id,…`), so\n * the version moves automatically whenever the transported domains change — a stale peer is then\n * rejected by the handshake instead of silently misrouting a positionally-packed frame.\n */\nfunction deriveDictionaryVersion(domains: ActionDomain<any>[]): string {\n  const { intToRoute } = buildActionRouteDictionary(domains);\n  const signature = intToRoute.map((route) => `${route.domain}:${route.id}`).join(\",\");\n\n  let hash = 0x811c9dc5;\n  for (let i = 0; i < signature.length; i++) {\n    hash ^= signature.charCodeAt(i);\n    hash = Math.imul(hash, 0x01000193);\n  }\n  return `auto:${(hash >>> 0).toString(16).padStart(8, \"0\")}`;\n}\n\n/**\n * Declare a transport-agnostic channel by role — the single source of truth both peers share. Each end\n * MUST call this with the same domains in the same order (the binary wire dictionary is positional); the\n * `dictionaryVersion` is derived from those domains unless you pin an explicit one. The wire dictionary\n * spans `[...toAcceptor, ...toConnector]` in that order. Any change to the domains or their actions moves\n * the derived version, and the handshake rejects a peer whose version differs, so deploy both ends\n * together. Appending stays compatible with older peers only under a hand-pinned `dictionaryVersion`\n * you leave unchanged, and only when the additions come last in the whole dictionary.\n *\n * Declare the domains *by role* — `toAcceptor` (connector→acceptor requests) and `toConnector`\n * (acceptor→connector pushes) — so the routing for both ends is derived from the channel (see\n * {@link connectChannel} and {@link serveChannel}) instead of being restated at each end. Security is a\n * per-transport concern, not a channel one, so this same definition is used whether a transport runs\n * plain or encrypted.\n */\nexport function defineChannel<\n  const TO_ACCEPTOR extends readonly ActionDomain<any>[] = [],\n  const TO_CONNECTOR extends readonly ActionDomain<any>[] = [],\n>(\n  options: {\n    /** Domains the connector sends to the acceptor (connector→acceptor requests), in a stable order. Omit for a connection-only channel (e.g. a realm-only app). */\n    toAcceptor?: TO_ACCEPTOR;\n    /** Domains the acceptor pushes to the connector (acceptor→connector), in a stable order. Omit for a connection-only channel. */\n    toConnector?: TO_CONNECTOR;\n    /** Pin a human-readable version instead of the derived hash (must match on both ends). */\n    dictionaryVersion?: string;\n    /** Pin the channel's selection tag instead of the domain-name-derived default (must match on both ends). */\n    tag?: string;\n    /** Tuning for the per-connection binary session (e.g. correlation TTL). */\n    sessionOptions?: IBinaryWireSessionOptions;\n  } = {},\n): IActionChannel<TO_ACCEPTOR, TO_CONNECTOR> {\n  // Omitted lists mean a connection-only channel: it still negotiates its (empty) codec + dictionary\n  // version, establishes identity + security, and can carry frame protocols (e.g. a realm) — there are\n  // simply no actions routed over it.\n  const toAcceptor = (options.toAcceptor ?? []) as TO_ACCEPTOR;\n  const toConnector = (options.toConnector ?? []) as TO_CONNECTOR;\n  // Dictionary order is positional and must match on both ends: connector→acceptor routes first, then\n  // acceptor→connector pushes.\n  const allDomains: ActionDomain<any>[] = [...toAcceptor, ...toConnector];\n  const tag = options.tag ?? deriveChannelTag(allDomains);\n\n  return {\n    toAcceptorDomains: toAcceptor,\n    toConnectorDomains: toConnector,\n    dictionaryVersion: options.dictionaryVersion ?? deriveDictionaryVersion(allDomains),\n    createCodec: createBinaryWireSessionFactory(allDomains, options.sessionOptions),\n    tag,\n    tags: [tag],\n  };\n}\n\n// ---------------------------------------------------------------------------\n// Channel-derived wiring (connector + acceptor)\n// ---------------------------------------------------------------------------\n\ntype TUnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void\n  ? I\n  : never;\n\ntype TDomainPushHandlers<D> =\n  D extends ActionDomain<infer DEF> ? Partial<TWrappableDomainActionHandler<DEF>> : never;\n\n/**\n * The `onPush` map for a channel: the merged set of every acceptor→connector (`toConnector`) action\n * handler, each receiving the pushed action's input. Derived from the channel's `toConnectorDomains`, so\n * the keys and input types follow the channel definition.\n */\nexport type TChannelPushHandlers<TO_CONNECTOR extends readonly ActionDomain<any>[]> =\n  TUnionToIntersection<TDomainPushHandlers<TO_CONNECTOR[number]>>;\n\n/**\n * Deprecated descriptor form retained for migration. New code passes carrier sources directly through\n * `carriers`; security, availability, and labels live on the source.\n *\n * A duplex carrier (`wsCarrier(() => ({ url }))`, `rtcCarrier(dc)`) builds a push-capable link; an exchange carrier\n * (`httpCarrier(...)`) builds a request/reply transport. List them in preference order — the connection\n * prefers the first that's ready and falls through on failure (e.g. secure WS preferred, HTTP fallback).\n */\n/** @deprecated Pass carrier sources directly through `carriers`. */\nexport interface IConnectTransport {\n  /** How to reach the peer — a duplex carrier (push-capable) or an exchange carrier (request/reply). */\n  carrier: IDuplexCarrierSource | IExchangeCarrierSource;\n  /**\n   * Run the authenticated/encrypted handshake over this carrier. Defaults to `true`. A secure transport\n   * draws its identity from the connection's shared `link`/`storage`; set `false` for a plain transport\n   * (e.g. a bare HTTP fallback beside a secure WS), which then needs no `storage`.\n   */\n  secure?: boolean;\n  /** Security level for this secure transport; defaults to the connection-level `securityLevel`. */\n  securityLevel?: ESecurityLevel;\n  /**\n   * Optional availability gate — when it returns `false` this transport is skipped and the connection\n   * falls through to the next in preference order, re-evaluated per dispatch. Omit = always available.\n   */\n  available?: (input: TTransportRouteParams) => boolean;\n  /** Override the devtools chip label (defaults to the carrier's own label). */\n  label?: string;\n}\n\nexport interface IConnectChannelBaseOptions<TO_CONNECTOR extends readonly ActionDomain<any>[]> {\n  /** The peer's runtime coordinate — the acceptor this connection dials. */\n  peer: RuntimeCoordinate;\n  /**\n   * One backing store for this connection's crypto identity, fanned across every *secure* transport so\n   * they present the same verify/exchange keys. Required when any transport is secure (the default); a\n   * fully-plain connection (every transport `secure: false`) may omit it. Pass `link` instead to share an\n   * existing identity. May be omitted for a secure connection only when `ephemeralIdentity: true`.\n   *\n   * **Must be durable, not just present**: the peer pins this identity's verify key on first contact\n   * (trust-on-first-use, keyed by the runtime coordinate's `envId::perId`). A store that forgets across\n   * reloads (a memory adapter) regenerates the key, and every load after the first is rejected with\n   * `identity_pin_mismatch`. In a browser use `createWebLocalStorageAdapter`; memory adapters are for\n   * tests. Pairing a non-durable store with `withPersistentId` logs a warning for exactly this reason.\n   */\n  storage?: StorageAdapter;\n  /**\n   * The connection's crypto identity. Defaults to the one {@link ClientCryptoKeyLink} over\n   * `storage`: every connection built from the same storage adapter shares it.\n   */\n  link?: ClientCryptoKeyLink;\n  /**\n   * Declare this connection's identity **ephemeral by construction**: the coordinate's persistent id\n   * is minted fresh every session (e.g. `perId: crypto.randomUUID()` at startup), so the peer's\n   * trust-on-first-use pin intentionally lives and dies with the session, so `storage` may be omitted\n   * or non-durable. Supplied `link`/`storage` still takes precedence. Do NOT set it\n   * for an id that survives reloads (a stored visitor/user id): that pairing genuinely breaks on the\n   * second load (`identity_pin_mismatch`), which is what the warning exists to catch.\n   */\n  ephemeralIdentity?: boolean;\n  /** Default security level for secure transports; defaults to `authenticated`. */\n  securityLevel?: ESecurityLevel;\n  /**\n   * Keep each secure HTTP (exchange) session per peer identity and reuse it — across this\n   * connection's transports, every other connection sharing the same `link`, and page loads — so a\n   * reload or a second transport to the same peer makes no handshake. The session is stored in the\n   * identity's own `storage`, sealed with its key (useless to another device, gone with the\n   * identity), and dropped for a fresh handshake when the peer refuses it or it expires.\n   *\n   * Three setups get a one-time warning, because reuse cannot do this there: every HTTP carrier\n   * `secure: false` (the option is ignored), an identity with no `storage` (kept in memory only,\n   * gone on reload), and `ephemeralIdentity: true` (no later load has the id it was filed under).\n   */\n  reuseExchangeSessions?: boolean;\n  /**\n   * This connection's own name within the runtime — required when one runtime holds **several duplex\n   * links to the same peer** (a store socket and a jobs socket on one backend), and meaningless\n   * otherwise. The peer binds each connection by the identity it presents, so two links that present\n   * the runtime's bare coordinate are indistinguishable to it: replies and pushes for *both* go back\n   * over whichever bound first, and the other socket's traffic silently hangs until it times out.\n   *\n   * Give each such connection a stable label (`\"store\"`, `\"jobs\"`) and they become separately\n   * addressable. A stable label is safe here — it is folded into the runtime's per-boot `insId`\n   * (`RuntimeCoordinate.withConnectionId`), not substituted for it, so reliable delivery keeps the\n   * fresh-per-boot stream epoch it depends on. This is *not* a way to run several identities from one\n   * runtime: `envId` and the persistent id are unchanged, so the peer still sees one client, one\n   * trust-on-first-use pin, one set of permissions.\n   *\n   * One link to a peer needs nothing here. Two links to *different* peers need nothing either — they\n   * already differ by `peer`.\n   */\n  connectionId?: string;\n  /** Handlers for the channel's acceptor→connector pushes. Optional — omit for a send-only connection. */\n  onPush?: TChannelPushHandlers<TO_CONNECTOR>;\n  /**\n   * Frame protocols riding this connection beside the action lane (shared connection design,\n   * Phase 3): registered on the connection's mux **at construction**, before any dispatch or\n   * `connect()` can run — so the handshake always advertises them and the caps ordering trap\n   * is unrepresentable on this path. Protocol modules that manage their own\n   * registration (a realm client via `realmConnection(connector)`) don't need this — register them\n   * before calling `connect()` instead.\n   */\n  protocols?: readonly import(\"@nice-code/wire\").IWireFrameProtocol[];\n  /**\n   * Bring your own frame-protocol mux — effectively a pre-populated alias of {@link protocols}\n   *: `connectChannel` creates one per connection by default (reachable as\n   * `connector.wireMux`) and registers `protocols` onto it. Pass one only to share it across\n   * connections or drive it from tests; prefer `protocols` everywhere else.\n   */\n  wireMux?: import(\"@nice-code/wire\").WireProtocolMux;\n  /** Default per-action timeout for this connection. */\n  defaultTimeout?: number;\n  /**\n   * Delivery deadline (ms) for `.reliable()` sends — how long an unacked frame retries across reconnects\n   * before it's abandoned (a pending action aborts with `reliable_delivery_abandoned`; the stream skips\n   * past it and continues). Default 60s.\n   *\n   * Not the same dial as `@nice-code/realm`'s `pendingExpiryMs` (default 10s): this is a\n   * *redelivery* deadline for at-least-once actions; that is an *optimistic-settle* expiry for\n   * realm writes. They differ on purpose — a realm write past its window rolls back UI, while a\n   * reliable action keeps retrying toward delivery.\n   */\n  reliableActionTimeout?: number;\n  /**\n   * Observe stream-level reliable-delivery events without holding per-send handles: `abandoned` (frames\n   * `fromSeq..toSeq` of a stream dropped undelivered — deadline, abort sweep, or stream close; the\n   * stream skipped past them and continues) and `overflow` (a send rejected at the unacked-window cap).\n   * The handle-less complement of `RunningAction.waitForAck()` — use it to re-push lost ranges from your\n   * own records, surface \"receiver may be behind\", or shed load ahead of the overflow cliff.\n   */\n  onReliableEvent?: (event: TReliableStreamEvent) => void;\n  /**\n   * Observe transport link-state: `link_down`, `redial_scheduled`\n   * (attempt + delay — truthful \"reconnecting, retrying in N s\" UX and flaky-link telemetry), and\n   * `link_up` (with `downForMs`). A drop that {@link reconnect} heals cleanly is *silent* at\n   * the realm's sync layer (`onDiagnostic`) — this hook is where transport churn is visible.\n   * Post-hoc subscription: `connector.addLinkEventListener`.\n   */\n  onLinkEvent?: (event: TLinkEvent) => void;\n  /**\n   * Keep a realm-carrying duplex link alive by auto-redialing it on an unexpected drop, with\n   * exponential backoff + jitter. Default: on when this connection carries a\n   * frame protocol (a realm rides the mux), off for a pure-action connection. Set `false` to opt\n   * out (e.g. an app that manages its own connection lifecycle). Independent of a realm's own\n   * probe-escalation `requestReconnect`, which also routes here.\n   *\n   * Teardown: `connector.releaseLink()` stops the auto-redial and releases the link (the\n   * intention-revealing counterpart of this option); `clearTransportCache()` also suppresses the\n   * redial until the next explicit `connect()`/dispatch. Observe drops/redials via\n   * {@link onLinkEvent}.\n   */\n  /** Keep a duplex link connected by redialing after unexpected drops. */\n  reconnect?: boolean;\n  /** @deprecated Use `reconnect`. */\n  keepLinkAlive?: boolean;\n  /**\n   * Wire-level half-open detection (8b.3 / the resilience contract): after `idleMs` with no inbound\n   * frame the link sends a raw `\"ping\"`; nothing back within `pongTimeoutMs` ⇒ the socket is\n   * closed locally, converting a *half-open* link (browser offline, NAT death — `isOpen()` true,\n   * sends into the void) into the ordinary close → {@link reconnect} redial, for **every**\n   * protocol on the link at once. Worst-case detection ≈ `idleMs + pongTimeoutMs` (default\n   * 15 s + 5 s ≈ 20 s — vs ~35 s for the realm staleness probe alone, which stays as\n   * belt-and-braces and can now be relaxed rather than carrying the whole burden).\n   *\n   * Default: on whenever {@link reconnect} is active (protocol-carrying links); pass a config\n   * object to force it on for a pure-action connection too; `false` disables. A busy link never\n   * pings. Requires a peer that answers the wire `\"ping\"` — every `@nice-code` acceptor (and the\n   * Cloudflare DO auto-response) does; disable against older third-party peers.\n   */\n  /** Wire-level half-open detection. */\n  heartbeat?: false | { idleMs?: number; pongTimeoutMs?: number };\n  /** @deprecated Use `heartbeat`. */\n  linkKeepalive?: false | { idleMs?: number; pongTimeoutMs?: number };\n  /**\n   * Observe this connection's wire traffic: called once per\n   * frame that actually crosses a carrier, with its **true wire byte size** — measured\n   * post-encryption, exactly what a platform's per-message billing / egress metering sees — and\n   * its lane (`action`, `realm`/protocol id, `handshake`, `keepalive`, `http`). Feed it a\n   * `TrafficMetricsCore` (`wireTap: traffic.wireTap`) and render the devtools Traffic tab, or\n   * point it at your own telemetry. Applies to every transport in {@link transports} and\n   * survives redials; sizes only — payload contents are never captured. Omit = zero overhead.\n   *\n   * Every event is stamped with `linkId` = {@link peer}'s `stringId`, so several connectors feeding\n   * ONE core still split per backend (\"which backend costs what\") — the mirror of `serveChannel`'s\n   * tap, which stamps the bound *client* per frame.\n   */\n  wireTap?: import(\"@nice-code/wire\").TWireTapFn;\n}\n\nexport type TActionCarrierSource = IDuplexCarrierSource | IExchangeCarrierSource;\n\nexport type IConnectChannelOptions<TO_CONNECTOR extends readonly ActionDomain<any>[]> =\n  IConnectChannelBaseOptions<TO_CONNECTOR> &\n    (\n      | {\n          /** Carrier sources in preference order. Security and carrier policy live on each value. */\n          carriers: readonly TActionCarrierSource[];\n          transports?: never;\n        }\n      | {\n          /** @deprecated Pass carrier values directly through `carriers`. */\n          transports: readonly IConnectTransport[];\n          carriers?: never;\n        }\n    );\n\n/**\n * Identities already dialled per (runtime, peer) — the check behind the several-links-one-identity\n * warning below. Keyed off the runtime weakly so a torn-down runtime takes its entry with it.\n */\nconst dialledIdentities = new WeakMap<ActionRuntime, Map<string, Set<string>>>();\n\n/**\n * The several-duplex-links trap (Vibenode feedback §1): a second `connectChannel` from one runtime to\n * one peer presenting the *same* identity is invisible to the acceptor — it binds connections by the\n * full coordinate string — so replies and pushes for both links go back over whichever bound first and\n * the other socket's traffic hangs until it times out. Silent, and it looks like a backend stall.\n *\n * Warn at dial time rather than at the misroute: this fires deterministically at setup, before any\n * traffic, and names the fix. Duplex connections only — the caller gates on that.\n */\nfunction warnOnSharedConnectionIdentity(\n  runtime: ActionRuntime,\n  peer: RuntimeCoordinate,\n  identity: RuntimeCoordinate,\n): void {\n  let byPeer = dialledIdentities.get(runtime);\n  if (byPeer == null) {\n    byPeer = new Map();\n    dialledIdentities.set(runtime, byPeer);\n  }\n  const identities = byPeer.get(peer.stringId) ?? new Set<string>();\n  byPeer.set(peer.stringId, identities);\n  if (identities.has(identity.stringId)) {\n    console.warn(\n      `connectChannel: this runtime already has a connection to [${peer.stringId}] dialling as ` +\n        `[${identity.stringId}]. The peer binds each connection by that identity, so it cannot tell ` +\n        \"the two apart: every reply and push for both goes back over whichever connected first, and \" +\n        \"the other link's traffic hangs until it times out. Give each connection its own \" +\n        '`connectionId` (e.g. `connectChannel(runtime, jobsChannel, { connectionId: \"jobs\", … })`) — ' +\n        \"or, if they carry the same routes over one link, use `connectChannels`.\",\n    );\n    return;\n  }\n  identities.add(identity.stringId);\n}\n\n/**\n * Open a connection to a peer from a single call — the dial-out dual of `serveChannel`. The channel is\n * the single source of truth for *what* is routed (`toAcceptor` domains forwarded to the peer,\n * `toConnector` pushes handled locally from `onPush`); the call binds the shared facts — the channel's\n * codec/dictionary version, the runtime, and one crypto identity (a {@link ClientCryptoKeyLink} over\n * `storage`) — into every carrier. List carriers in preference order (secure WS preferred, plain HTTP\n * fallback):\n * ```ts\n * const connector = connectChannel(runtime, lobbyChannel, {\n *   peer: runtime_coordinate_lobby_do,\n *   storage,\n *   carriers: [wsCarrier(url), httpCarrier(httpUrl, { secure: false })],\n *   onPush: { player_joined: (p) => { … } },\n * });\n * ```\n * Returns the {@link ChannelConnector} so the caller can later `clearTransportCache()` it.\n */\nexport function connectChannel<\n  TO_ACCEPTOR extends readonly ActionDomain<any>[],\n  TO_CONNECTOR extends readonly ActionDomain<any>[],\n>(\n  runtime: ActionRuntime,\n  channel: IActionChannel<TO_ACCEPTOR, TO_CONNECTOR>,\n  options: IConnectChannelOptions<TO_CONNECTOR>,\n): ChannelConnector {\n  if ((options.carriers == null) === (options.transports == null)) {\n    throw err_nice_action.fromId(EErrId_NiceAction.conflicting_connect_options, {\n      detail: \"connectChannel requires exactly one of `carriers` or deprecated `transports`\",\n    });\n  }\n  if (options.reconnect != null && options.keepLinkAlive != null) {\n    throw err_nice_action.fromId(EErrId_NiceAction.conflicting_connect_options, {\n      detail: \"connectChannel: pass only `reconnect`; `keepLinkAlive` is deprecated\",\n    });\n  }\n  if (options.heartbeat != null && options.linkKeepalive != null) {\n    throw err_nice_action.fromId(EErrId_NiceAction.conflicting_connect_options, {\n      detail: \"connectChannel: pass only `heartbeat`; `linkKeepalive` is deprecated\",\n    });\n  }\n  const transports: readonly IConnectTransport[] =\n    options.carriers?.map((carrier) => ({\n      carrier,\n      secure: carrier.secure,\n      securityLevel: carrier.securityLevel,\n      available: carrier.available,\n      label: carrier.label,\n    })) ?? options.transports!;\n  const securityLevel = options.securityLevel ?? ESecurityLevel.authenticated;\n  const anySecure = transports.some((transport) => transport.secure ?? true);\n\n  // What this connection calls itself: the runtime, or a named connection within it. Everything\n  // downstream that names the local side reads this one value — the handshake identity the peer binds\n  // the socket to, and the origin stamped on each frame it routes returns by — so the two can't drift.\n  const connectionIdentity =\n    options.connectionId != null\n      ? runtime.coordinate.withConnectionId(options.connectionId)\n      : undefined;\n  // Only a push-capable link can be misrouted to: an exchange transport answers on its own request and\n  // is skipped by the return-path dispatch, so an HTTP-only connection is never part of the ambiguity.\n  if (transports.some((descriptor) => !isExchangeCarrierSource(descriptor.carrier))) {\n    warnOnSharedConnectionIdentity(runtime, options.peer, connectionIdentity ?? runtime.coordinate);\n  }\n\n  // The connection facts shared with `createWireClient` — the mux (created up-front so protocol\n  // registration precedes the handshake), one crypto identity fanned across every secure transport,\n  // the keepalive resolver, and the per-link traffic tap (stamped with the peer this connector dials,\n  // so several connectors into ONE `TrafficMetricsCore` still split per backend). One implementation\n  // for both dial-out entry points; `connectChannel` then builds action `Transport`s\n  // (with the codec lane) around the result, a realm-only `createWireClient` builds mux-only\n  // `WireLinkConnection`s.\n  const {\n    mux: wireMux,\n    link,\n    resolveHeartbeat,\n    wireTap,\n  } = assembleWireConnectionParts({\n    callerName: \"connectChannel\",\n    peer: options.peer,\n    identity: connectionIdentity ?? runtime.coordinate,\n    mux: options.wireMux,\n    protocols: options.protocols,\n    anySecure,\n    storage: options.storage,\n    link: options.link,\n    ephemeralIdentity: options.ephemeralIdentity,\n    reuseExchangeSessions: options.reuseExchangeSessions,\n    exchangeCarrierSecurity: transports\n      .filter((descriptor) => isExchangeCarrierSource(descriptor.carrier))\n      .map(\n        (descriptor) =>\n          (descriptor.secure ?? true) &&\n          (descriptor.securityLevel ?? securityLevel) !== ESecurityLevel.none,\n      ),\n    reconnect: options.reconnect,\n    heartbeat: options.heartbeat,\n    keepLinkAlive: options.keepLinkAlive,\n    linkKeepalive: options.linkKeepalive,\n    wireTap: options.wireTap,\n  });\n\n  // Protocols need a duplex transport: when the whole chain is exchange-shaped, an\n  // exchange transport built with this flag surfaces `protocol_on_exchange_only` at bring-up if\n  // protocols were registered on the mux (a mixed chain rides them on its duplex transport).\n  const exchangeOnlyConnection = transports.every((descriptor) =>\n    isExchangeCarrierSource(descriptor.carrier),\n  );\n\n  const builtTransports: Transport[] = transports.map((descriptor) =>\n    transport({\n      carrier: descriptor.carrier,\n      channel,\n      runtime,\n      identity: connectionIdentity,\n      expectedPeer: options.peer,\n      secure: descriptor.secure ?? true,\n      link,\n      securityLevel: descriptor.securityLevel ?? securityLevel,\n      reuseExchangeSessions: options.reuseExchangeSessions,\n      available: descriptor.available,\n      label: descriptor.label,\n      mux: wireMux,\n      exchangeOnlyConnection,\n      heartbeat: resolveHeartbeat,\n      wireTap,\n    }),\n  );\n\n  // Each push domain self-filters `onPush` to its own action ids, so a channel with several push\n  // domains splits one merged map across the right handlers.\n  const pushHandlers =\n    options.onPush != null\n      ? channel.toConnectorDomains.map((domain) =>\n          domain.wrapAsPartialLocalHandler(\n            options.onPush as Parameters<typeof domain.wrapAsPartialLocalHandler>[0],\n          ),\n        )\n      : [];\n\n  // The level the mux's frame protocols (a realm) actually ride at. Protocols ride the mux over a\n  // *duplex* transport (an exchange transport can't push them), so the connector reports the **floor**\n  // across the duplex transports — a plain duplex fallback drags it to `none`, and a per-transport\n  // override below the connection default can't hide behind that default. A realm client asserts this\n  // before its first `hello`: it must never over-report, or avatar data could\n  // leave as app-layer plaintext. No duplex transport ⇒ `none` (a realm can't ride an exchange-only\n  // connection anyway — it needs push).\n  const duplexSecurityLevels = transports\n    .filter((descriptor) => !isExchangeCarrierSource(descriptor.carrier))\n    .map((descriptor) =>\n      (descriptor.secure ?? true)\n        ? (descriptor.securityLevel ?? securityLevel)\n        : ESecurityLevel.none,\n    );\n  const connectionSecurityLevel =\n    duplexSecurityLevels.length === 0\n      ? ESecurityLevel.none\n      : duplexSecurityLevels.reduce((floor, level) =>\n          securityLevelMeets(level, floor) ? floor : level,\n        );\n\n  const handler = runtime.connectTo(options.peer, {\n    transports: builtTransports,\n    domains: [...channel.toAcceptorDomains],\n    localHandlers: pushHandlers,\n    defaultTimeout: options.defaultTimeout,\n    reliableActionTimeout: options.reliableActionTimeout,\n    wireMux,\n    securityLevel: connectionSecurityLevel,\n    reconnect: options.reconnect ?? options.keepLinkAlive,\n    connectionIdentity,\n  });\n  if (options.onReliableEvent != null) {\n    handler.addReliableEventListener(options.onReliableEvent);\n  }\n  if (options.onLinkEvent != null) {\n    handler.addLinkEventListener(options.onLinkEvent);\n  }\n  return handler;\n}\n\n// ---------------------------------------------------------------------------\n// Multi-channel: combine several channels into one, to share a single connection / endpoint\n// ---------------------------------------------------------------------------\n\n/** The acceptor domains of one channel (`toAcceptor`). */\ntype TChannelAcceptorDomains<C> = C extends IActionChannel<infer A, any> ? A : never;\n/** The connector (push) domains of one channel (`toConnector`). */\ntype TChannelConnectorDomains<C> = C extends IActionChannel<any, infer B> ? B : never;\n/** The union of every channel's acceptor domains (distributes over the channel tuple). */\nexport type TCombinedAcceptorDomains<CHANNELS extends readonly IActionChannel<any, any>[]> =\n  TChannelAcceptorDomains<CHANNELS[number]>;\n/** The union of every channel's connector (push) domains. */\nexport type TCombinedConnectorDomains<CHANNELS extends readonly IActionChannel<any, any>[]> =\n  TChannelConnectorDomains<CHANNELS[number]>;\n\n/**\n * Combine several channels into one whose domains are the **union** of theirs, in list order — so a set of\n * channels can ride a *single* connection / endpoint (one handshake, one crypto identity) yet stay\n * independent contracts (the runtime still routes each action by its domain). The positional wire\n * dictionary spans `[...each toAcceptor, ...each toConnector]`, and the derived `dictionaryVersion` covers\n * the whole union, so the handshake's drift check validates the exact combination with no new wire fields.\n *\n * Both ends MUST combine the **same channels in the same order** (exactly the per-channel `defineChannel`\n * contract, lifted to the set) — which is why {@link connectChannels} and {@link serveChannels} are exact\n * duals. A single-element list returns that channel unchanged.\n */\nexport function combineChannels<const CHANNELS extends readonly IActionChannel<any, any>[]>(\n  channels: CHANNELS,\n): IActionChannel<TCombinedAcceptorDomains<CHANNELS>, TCombinedConnectorDomains<CHANNELS>> {\n  if (channels.length === 1) {\n    return channels[0] as IActionChannel<\n      TCombinedAcceptorDomains<CHANNELS>,\n      TCombinedConnectorDomains<CHANNELS>\n    >;\n  }\n  const toAcceptor = channels.flatMap((channel) => [...channel.toAcceptorDomains]);\n  const toConnector = channels.flatMap((channel) => [...channel.toConnectorDomains]);\n  // The union flatten can't be expressed as a single value-level tuple; defineChannel derives the right\n  // codec + version from the concrete domain arrays, and we re-assert the precise union element types.\n  // Carry the constituent tags (in order) so the connector can advertise the exact subset it uses and a\n  // multi-channel acceptor composes the matching codec; `tag` is the combined, human-readable id.\n  const tags = channels.flatMap((channel) => [...channel.tags]);\n  const combined: IActionChannel = {\n    ...defineChannel({ toAcceptor, toConnector }),\n    tag: tags.join(\"+\"),\n    tags,\n  };\n  return combined as IActionChannel<\n    TCombinedAcceptorDomains<CHANNELS>,\n    TCombinedConnectorDomains<CHANNELS>\n  >;\n}\n\n/**\n * Connect several channels to a single backend over **one shared connection** — the connect-side dual of\n * {@link serveChannels} and the multi-channel form of {@link connectChannel}. One handshake, one crypto\n * identity, and one transport stack carry the union of the channels' domains; the runtime still dispatches\n * each action by its domain, so the channels stay independent. `onPush` is the merged set of every\n * channel's `toConnector` handlers.\n * ```ts\n * connectChannels(runtime, [mainChannel, notificationsChannel], {\n *   peer: backendCoord, storage,\n *   carriers: [httpCarrier(url)],\n *   onPush: { notified: (p) => { … } },\n * });\n * ```\n * For per-channel identities/transports (e.g. an ephemeral per-resource connection), keep using separate\n * {@link connectChannel} calls — `connectChannels` is purely additive for the \"several channels, one\n * backend\" case.\n */\nexport function connectChannels<const CHANNELS extends readonly IActionChannel<any, any>[]>(\n  runtime: ActionRuntime,\n  channels: CHANNELS,\n  options: IConnectChannelOptions<TCombinedConnectorDomains<CHANNELS>>,\n): ChannelConnector {\n  return connectChannel(runtime, combineChannels(channels), options);\n}\n\ntype TDomainAcceptorCases<D, TCtx> =\n  D extends ActionDomain<infer DEF>\n    ? { [ID in keyof DEF[\"actionSchema\"] & string]?: TAcceptorCaseFn<DEF, ID, TCtx> }\n    : never;\n\n/**\n * The connection-aware case map for a channel's acceptor side: the merged set of every\n * connector→acceptor (`toAcceptor`) action handler, each receiving the primed request plus a per-action\n * `context`. `TCtx` is whatever the wiring supplies as that second argument — the raw connection\n * (`TConn | undefined`) for the low-level `acceptChannelConnections`, or an enriched `IConnectionContext`\n * for `serveChannel`'s `channelCases`. Derived from the channel's `toAcceptorDomains`, so the keys and\n * input/output types follow the channel.\n */\nexport type TChannelAcceptorCases<\n  TO_ACCEPTOR extends readonly ActionDomain<any>[],\n  TCtx,\n> = TUnionToIntersection<TDomainAcceptorCases<TO_ACCEPTOR[number], TCtx>>;\n\n/**\n * Register an acceptor handler's execution for a channel straight from its definition: the channel's\n * `toAcceptor` domains are served together with one merged, connection-aware case map (each case gets\n * the primed request + the originating connection, as with\n * {@link ChannelAcceptor.forConnectionDomainCases}). The domain list is taken from the channel,\n * never restated. Add the returned handler to the runtime alongside the acceptor handler:\n * ```ts\n * runtime.addHandlers([acceptChannelConnections(serverHandler, channel, { … }), serverHandler]);\n * ```\n *\n * The case's second argument is the raw connection (`TConn | undefined`). For the richer state +\n * broadcast + pushBack context, serve the channel through `serveChannel`'s `channelCases` instead.\n */\nexport function acceptChannelConnections<TO_ACCEPTOR extends readonly ActionDomain<any>[], TConn>(\n  serverHandler: ChannelAcceptor<TConn>,\n  channel: IActionChannel<TO_ACCEPTOR, any>,\n  cases: TChannelAcceptorCases<TO_ACCEPTOR, TConn | undefined>,\n): ActionLocalHandler {\n  return serverHandler.forConnectionDomainCasesMulti(\n    channel.toAcceptorDomains,\n    cases as Record<string, TAcceptorCaseFn<any, any, TConn | undefined> | undefined>,\n    (connection) => connection,\n  );\n}\n\n/**\n * {@link acceptChannel}'s options — the secure-acceptor builder options minus the `channel` and `runtime`\n * it already takes positionally. One option bag, shared with the underlying {@link createSecureChannelAcceptor}.\n */\nexport type IAcceptChannelOptions<TConn> = Omit<\n  ISecureChannelAcceptorOptions<TConn>,\n  \"channel\" | \"runtime\"\n>;\n\n/**\n * Build the secure {@link ChannelAcceptor} for a channel — the accept-in counterpart to\n * {@link connectChannel}. It folds in the boilerplate of {@link createSecureChannelAcceptor} (the\n * `ClientCryptoKeyLink` + storage-backed TOFU resolver from one `storage`, the channel's codec +\n * dictionary version, the `security` block from the runtime coordinate) but takes the `(runtime, channel,\n * options)` shape of the channel family. Pair it with {@link acceptChannelConnections} for execution:\n * ```ts\n * const runtime = new ActionRuntime(serverCoordinate, { scope: \"instance\" });\n * const acceptor = acceptChannel(runtime, gameChannel, { storage, send });\n * runtime.addHandlers([acceptChannelConnections(acceptor, gameChannel, { … }), acceptor]);\n * ```\n */\nexport function acceptChannel<\n  TO_ACCEPTOR extends readonly ActionDomain<any>[],\n  TO_CONNECTOR extends readonly ActionDomain<any>[],\n  TConn = unknown,\n>(\n  runtime: ActionRuntime,\n  channel: IActionChannel<TO_ACCEPTOR, TO_CONNECTOR>,\n  options: IAcceptChannelOptions<TConn>,\n): ChannelAcceptor<TConn> {\n  return createSecureChannelAcceptor<TConn>({ ...options, channel, runtime });\n}\n","import type { ClientCryptoKeyLink } from \"@nice-code/util\";\nimport type {\n  IClientVerifyKeyResolver,\n  IRuntimeCoordinate,\n  TServerDictionaryVersionResolver,\n} from \"@nice-code/wire\";\nimport {\n  ESecurityLevel,\n  type IWireExchangeLaneRequest,\n  type TWireExchangeLaneReply,\n  WireExchangeAcceptor,\n} from \"@nice-code/wire\";\nimport { EActionPayloadType } from \"../../../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport { isActionPayload_Any_JsonObject } from \"../../../utils/isActionPayload_Any_JsonObject\";\nimport type { ActionRuntime } from \"../../ActionRuntime\";\nimport {\n  actionServeRequestInfo,\n  type IActionServeLogger,\n  serveResultErrorInfo,\n} from \"../../Channel/serveLogger\";\n\n/** Acceptor secure config for the exchange (HTTP) endpoint — same identity an `ChannelAcceptor` uses. */\nexport interface IExchangeAcceptorSecurity {\n  /** This acceptor's crypto identity (verify + exchange key pairs, optionally persisted). */\n  link: ClientCryptoKeyLink;\n  /** This acceptor's coordinate — its identity to clients during the handshake. */\n  localCoordinate: IRuntimeCoordinate;\n  /** Wire dictionary version — a fixed string (single channel), or a resolver composing it from the\n   * `hello.channels` tags (multi-channel). The handshake rejects on a mismatch / unknown channel. */\n  dictionaryVersion: string | TServerDictionaryVersionResolver;\n  /** Accepted level(s) — a single level is strict, an array is a negotiable allowed set. */\n  securityLevel: ESecurityLevel | readonly ESecurityLevel[];\n  /** Trust decision for a client's verify key (defaults to in-memory TOFU inside the handshake). */\n  verifyKeyResolver?: IClientVerifyKeyResolver;\n}\n\nexport interface IExchangeAcceptorConfig {\n  security: IExchangeAcceptorSecurity;\n  /** The runtime that executes an inbound action wire and produces its result. */\n  runtime: ActionRuntime;\n  /** Optional server-side logger — called per inbound action request with its outcome. */\n  logger?: IActionServeLogger;\n  /** Short carrier-kind label surfaced to the logger as the request's transport (default `\"http\"`). */\n  transportLabel?: string;\n  /**\n   * How long a minted session ticket stays valid (ms), told to the client on accept. After it\n   * expires the acceptor refuses it and the client handshakes again. Defaults to 12h — long enough for an ordinary session's life,\n   * since a sealed ticket carries no server state to revoke before then. Keep it shorter for a more\n   * tightly time-boxed session.\n   */\n  sessionTtlMs?: number;\n}\n\n/**\n * The action lane over wire's {@link WireExchangeAcceptor} —\n * the HTTP counterpart to `ChannelAcceptor` composing on `WireAcceptor`. Wire owns the exchange\n * mechanics: the envelope, the server handshake over the two `hs` POSTs, the sealed `hsc`/`t`\n * tokens that make the whole endpoint **stateless** across isolates, and the per-session frame\n * crypto. What stays here is the lane: validating the opened wire as an action payload, binding\n * the handshake-authenticated identity onto it (never the wire's self-asserted one), routing it\n * through the runtime, logging, and returning the result wire for the same response.\n *\n * The public config is unchanged by the split — `dictionaryVersion` remains on\n * {@link IExchangeAcceptorSecurity} (it is the lane's own handshake payload, E5); internally it\n * feeds wire's exchange lane while the neutral core feeds wire's security block, mirroring how\n * `ChannelAcceptor` splits its `IAcceptorSecurity`.\n */\nexport class ExchangeAcceptor {\n  private readonly _core: WireExchangeAcceptor;\n  private readonly _runtime: ActionRuntime;\n  private readonly _logger?: IActionServeLogger;\n  private readonly _transportLabel: string;\n\n  constructor(config: IExchangeAcceptorConfig) {\n    this._runtime = config.runtime;\n    this._logger = config.logger;\n    this._transportLabel = config.transportLabel ?? \"http\";\n    this._core = new WireExchangeAcceptor({\n      security: {\n        securityLevel: config.security.securityLevel,\n        link: config.security.link,\n        localCoordinate: config.security.localCoordinate,\n        verifyKeyResolver: config.security.verifyKeyResolver,\n      },\n      lane: {\n        dictionaryVersion: config.security.dictionaryVersion,\n        onExchange: (request) => this._onExchange(request),\n      },\n      sessionTtlMs: config.sessionTtlMs,\n    });\n  }\n\n  /** Process one POST body (an exchange envelope), returning the reply body to send back. */\n  handlePost(body: string): Promise<string> {\n    return this._core.handlePost(body);\n  }\n\n  /** Serve one opened `act` wire: validate → bind identity → log → run → return the result wire. */\n  private async _onExchange(request: IWireExchangeLaneRequest): Promise<TWireExchangeLaneReply> {\n    if (!isActionPayload_Any_JsonObject(request.wire)) {\n      return { ok: false, message: \"malformed action wire\" };\n    }\n    const wire = request.wire;\n    const client = request.client;\n\n    // Bind the *authenticated* identity (never the wire's self-asserted one) so the action runs as the\n    // handshake-verified client.\n    if (client != null && wire.type === EActionPayloadType.request) {\n      wire.context.originClient = client.toJsonObject();\n    }\n\n    // Log the request (basic action/transport/origin facts) before executing, and report the outcome once\n    // the result is back — the reply rides this same response, so it returned over the same transport.\n    const report =\n      this._logger != null && wire.type === EActionPayloadType.request\n        ? this._logger.onRequest(\n            actionServeRequestInfo(wire, {\n              transport: this._transportLabel,\n              securityLevel: request.securityLevel,\n              origin: client?.stringId,\n            }),\n          )\n        : undefined;\n    const startedAt = Date.now();\n\n    const running = await this._runtime._handleActionPayloadWireFromReceiver(wire, {\n      receiver: this,\n      securityLevel: request.securityLevel,\n      originAuthenticated: client != null && request.securityLevel !== ESecurityLevel.none,\n    });\n    const result = await running.waitForResultPayload();\n    const resultWire = result.toJsonObject();\n\n    if (report != null) {\n      const returnedVia = request.encrypted\n        ? `${this._transportLabel} (encrypted)`\n        : this._transportLabel;\n      report(\n        result.result.ok\n          ? { ok: true, returnedVia, durationMs: Date.now() - startedAt }\n          : {\n              ok: false,\n              returnedVia,\n              durationMs: Date.now() - startedAt,\n              error: serveResultErrorInfo(result.result.error),\n            },\n      );\n    }\n\n    return { ok: true, wire: resultWire };\n  }\n}\n","import { isNiceError } from \"@nice-code/error\";\nimport {\n  decodeExchangeRequest,\n  ESecurityLevel,\n  encodeExchange,\n  type TWireExchangeReply,\n} from \"@nice-code/wire\";\nimport { EActionPayloadType } from \"../../../../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport { EErrId_NiceAction } from \"../../../../errors/err_nice_action\";\nimport { isActionPayload_Any_JsonObject } from \"../../../../utils/isActionPayload_Any_JsonObject\";\nimport type { ActionRuntime } from \"../../../ActionRuntime\";\nimport {\n  actionServeRequestInfo,\n  type IActionServeLogger,\n  serveResultErrorInfo,\n} from \"../../../Channel/serveLogger\";\nimport {\n  ExchangeAcceptor,\n  type IExchangeAcceptorSecurity,\n} from \"../../../Transport/SecureSession/exchangeAcceptor\";\n\n/** Permissive defaults — fine for a public action endpoint; override (or disable) via `cors`. */\nconst DEFAULT_CORS_HEADERS: Record<string, string> = {\n  \"Access-Control-Allow-Origin\": \"*\",\n  \"Access-Control-Allow-Methods\": \"GET, POST, OPTIONS\",\n  \"Access-Control-Allow-Headers\": \"Content-Type\",\n  \"Access-Control-Max-Age\": \"86400\",\n};\n\nexport interface IActionFetchHandlerOptions {\n  /**\n   * CORS headers merged onto every response (a preflight `OPTIONS` is answered `204` with them).\n   * Defaults to permissive `*`; pass `false` to attach no CORS headers at all.\n   */\n  cors?: Record<string, string> | false;\n  /** Which requests carry an action wire on `POST`. Default: pathname ends with `/action`. */\n  isActionPath?: (url: URL) => boolean;\n  /** Which requests are WebSocket upgrades. Default: pathname ends with `/ws`. */\n  isWebSocketPath?: (url: URL) => boolean;\n  /**\n   * Whether a request is a WebSocket upgrade for this endpoint, given the whole request (not just the\n   * URL). When set it *replaces* the default gate (an `Upgrade: websocket` header on an\n   * {@link isWebSocketPath} match) — use it when the discriminant needs a header or method, not only the\n   * path. Only consulted when {@link onWebSocketUpgrade} is present.\n   */\n  isWebSocketUpgrade?: (request: Request, url: URL) => boolean;\n  /**\n   * Perform the transport-specific WebSocket upgrade (e.g. a Durable Object's\n   * `new WebSocketPair()` + `ctx.acceptWebSocket()` returning a `101`). Omit for HTTP-only endpoints.\n   * Its response is returned as-is — a `101` upgrade carries no CORS headers.\n   */\n  onWebSocketUpgrade?: (request: Request, url: URL) => Response | Promise<Response>;\n  /** Forwarded to `ActionPayload_Result.toHttpResponse` — use the error's HTTP status (default true). */\n  useErrorStatus?: boolean;\n  /**\n   * Enable the secure exchange protocol (handshake + token sessions + body encryption) on the `/action`\n   * endpoint, mirroring an `ChannelAcceptor`'s `security`. The matching connector is a secure HTTP\n   * carrier (`connectChannel(..., { carriers: [httpCarrier(url)] })`). When omitted, the\n   * endpoint is plain: it accepts the connector's plain `{ k: \"act\", w }` envelope (answered in kind) or a\n   * raw action wire (answered with the raw result).\n   */\n  security?: IExchangeAcceptorSecurity;\n  /**\n   * Optional server-side logger — called per inbound action request with its outcome. Threaded into the\n   * secure {@link ExchangeAcceptor} and used directly on the plain action POST, so both endpoint styles log.\n   */\n  logger?: IActionServeLogger;\n  /** Short carrier-kind label surfaced to the logger as the request's transport (default `\"http\"`). */\n  transportLabel?: string;\n}\n\n/**\n * Build the `fetch` handler a server/Durable-Object exposes for action traffic, folding in the\n * boilerplate every endpoint repeats: CORS (incl. the `OPTIONS` preflight), routing the `/action`\n * `POST` body through the runtime (`handleActionPayloadWire` → `waitForResultPayload` →\n * `toHttpResponse`), an optional WebSocket-upgrade hook, and a `404` fallback.\n *\n * It only touches web-standard `Request`/`Response`, so it stays transport-agnostic — the one\n * environment-specific bit (the WS upgrade) is injected via {@link IActionFetchHandlerOptions.onWebSocketUpgrade}:\n * ```ts\n * this.fetchHandler = createActionFetchHandler(this.runtime, {\n *   onWebSocketUpgrade: () => {\n *     const pair = new WebSocketPair();\n *     this.ctx.acceptWebSocket(pair[1]);\n *     return new Response(null, { status: 101, webSocket: pair[0] });\n *   },\n * });\n * // async fetch(request) { return this.fetchHandler(request); }\n * ```\n */\nexport function createActionFetchHandler(\n  runtime: ActionRuntime,\n  options: IActionFetchHandlerOptions = {},\n): (request: Request) => Promise<Response> {\n  const corsHeaders = options.cors === false ? {} : (options.cors ?? DEFAULT_CORS_HEADERS);\n  const isActionPath = options.isActionPath ?? ((url) => url.pathname.endsWith(\"/action\"));\n  const isWebSocketPath = options.isWebSocketPath ?? ((url) => url.pathname.endsWith(\"/ws\"));\n  const transportLabel = options.transportLabel ?? \"http\";\n  const exchangeAcceptor =\n    options.security != null\n      ? new ExchangeAcceptor({\n          runtime,\n          security: options.security,\n          logger: options.logger,\n          transportLabel,\n        })\n      : undefined;\n\n  const withCors = (response: Response): Response => {\n    if (options.cors === false) return response;\n    const headers = new Headers(response.headers);\n    for (const [key, value] of Object.entries(corsHeaders)) headers.set(key, value);\n    return new Response(response.body, { status: response.status, headers });\n  };\n\n  const badRequest = (message: string): Response =>\n    new Response(JSON.stringify({ error: message }), {\n      status: 400,\n      headers: { \"Content-Type\": \"application/json\" },\n    });\n\n  // Always 200: the connector's `httpCarrier` reads any non-2xx as \"not speaking the protocol\", so\n  // even a refusal must ride an `err` envelope.\n  const envelopeReply = (reply: TWireExchangeReply): Response =>\n    new Response(encodeExchange(reply), {\n      status: 200,\n      headers: { \"Content-Type\": \"application/json\" },\n    });\n  const envelopeError = (message: string): Response => envelopeReply({ k: \"err\", message });\n\n  return async (request: Request): Promise<Response> => {\n    if (request.method === \"OPTIONS\") {\n      return withCors(new Response(null, { status: 204 }));\n    }\n\n    const url = new URL(request.url);\n\n    const isWebSocketUpgrade =\n      options.isWebSocketUpgrade ??\n      ((req: Request, u: URL) => req.headers.get(\"Upgrade\") === \"websocket\" && isWebSocketPath(u));\n\n    if (options.onWebSocketUpgrade != null && isWebSocketUpgrade(request, url)) {\n      return options.onWebSocketUpgrade(request, url);\n    }\n\n    if (request.method === \"POST\" && isActionPath(url)) {\n      // Secure exchange: the body is a protocol envelope (handshake or tokened/encrypted action); the\n      // acceptor drives the handshake + token session and returns the reply envelope inline.\n      if (exchangeAcceptor != null) {\n        const reply = await exchangeAcceptor.handlePost(await request.text());\n        return withCors(\n          new Response(reply, { status: 200, headers: { \"Content-Type\": \"application/json\" } }),\n        );\n      }\n\n      // Plain endpoint. The connector's plain session still speaks the exchange envelope — a\n      // tokenless `{ k: \"act\", w: <wire> }` — so it is unwrapped here and answered in kind. A raw\n      // action wire (hand-posted, curl, an older peer) is accepted too, and answered raw.\n      const text = await request.text();\n      const envelope = decodeExchangeRequest(text);\n      if (envelope?.k === \"hs\") {\n        return withCors(\n          envelopeError(\n            \"plain endpoint: no handshake here — connect with `{ carrier: httpCarrier(...), secure: false }`\",\n          ),\n        );\n      }\n      if (envelope != null && \"c\" in envelope) {\n        return withCors(envelopeError(\"plain endpoint: cannot open an encrypted frame\"));\n      }\n      let body: unknown;\n      if (envelope != null) {\n        body = envelope.w;\n      } else {\n        try {\n          body = JSON.parse(text);\n        } catch {\n          // Not JSON at all (scanners, stale tabs, corrupt clients) — a client problem, not a crash.\n          return withCors(badRequest(\"request body is not valid JSON\"));\n        }\n      }\n      const answerError = (message: string): Response =>\n        envelope != null ? envelopeError(message) : badRequest(message);\n      const report =\n        options.logger != null &&\n        isActionPayload_Any_JsonObject(body) &&\n        body.type === EActionPayloadType.request\n          ? options.logger.onRequest(actionServeRequestInfo(body, { transport: transportLabel }))\n          : undefined;\n      const startedAt = Date.now();\n\n      let running: Awaited<ReturnType<ActionRuntime[\"handleActionPayloadWire\"]>>;\n      try {\n        running = await runtime._handleActionPayloadWireFromReceiver(body as any, {\n          receiver: runtime,\n          securityLevel: ESecurityLevel.none,\n        });\n      } catch (error) {\n        // Garbage that parsed as JSON but is not an action wire: answer a clean refusal instead of\n        // letting the NiceError escape as an uncaught exception + raw 500. Anything else is a\n        // genuine server-side failure and still propagates.\n        if (\n          isNiceError(error) &&\n          error\n            .getIds()\n            .some(\n              (id) =>\n                id === EErrId_NiceAction.wire_not_action_data ||\n                id === EErrId_NiceAction.wire_action_not_payload,\n            )\n        ) {\n          report?.({\n            ok: false,\n            returnedVia: transportLabel,\n            durationMs: Date.now() - startedAt,\n            error: serveResultErrorInfo(error),\n          });\n          return withCors(answerError(error.message));\n        }\n        throw error;\n      }\n      const result = await running.waitForResultPayload();\n\n      report?.(\n        result.result.ok\n          ? { ok: true, returnedVia: transportLabel, durationMs: Date.now() - startedAt }\n          : {\n              ok: false,\n              returnedVia: transportLabel,\n              durationMs: Date.now() - startedAt,\n              error: serveResultErrorInfo(result.result.error),\n            },\n      );\n      if (envelope != null) {\n        return withCors(envelopeReply({ k: \"act\", w: result.toJsonObject() }));\n      }\n      return withCors(result.toHttpResponse({ useErrorStatus: options.useErrorStatus }));\n    }\n\n    return withCors(new Response(\"Not found\", { status: 404 }));\n  };\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { ChannelAcceptor, IAcceptorConnectionBinding } from \"../ChannelAcceptor\";\n\n/**\n * The composite value persisted to a connection's attachment: the consumer's own app state plus the\n * {@link ChannelAcceptor} routing binding. Co-storing them in one slot means a transport whose\n * sockets outlive process eviction (e.g. a Durable Object's hibernatable WebSocket) recovers both the\n * application identity *and* the action routing from a single attachment after a wake — no storage reads.\n */\nexport interface IConnectionAttachment<TApp> {\n  app?: TApp;\n  binding?: IAcceptorConnectionBinding;\n}\n\nexport interface IConnectionStateStoreOptions<TConn, TApp> {\n  /** Read a connection's raw attachment (e.g. `(ws) => ws.deserializeAttachment()`). */\n  read: (connection: TConn) => unknown;\n  /** Persist a connection's attachment (e.g. `(ws, value) => ws.serializeAttachment(value)`). */\n  write: (connection: TConn, value: IConnectionAttachment<TApp>) => void;\n  /**\n   * All currently-live connections (e.g. `() => ctx.getWebSockets()`). Used to replay routing bindings\n   * after a wake (via {@link createConnectionStateStore}) and to enumerate app state in\n   * {@link ConnectionStateStore.entries}.\n   */\n  getConnections: () => TConn[];\n  /**\n   * Optional Standard Schema (valibot, zod, …) validating the *app* portion on read. A value that\n   * fails validation reads back as `null` — the same lenient behavior as a hand-written safeParse\n   * helper. The binding is the library's own shape and is never validated.\n   */\n  schema?: StandardSchemaV1<unknown, TApp>;\n}\n\n/**\n * A typed per-connection state store that co-owns the app state and the acceptor handler's routing\n * binding in one attachment, so neither the consumer nor the handler has to hand-merge the two. Create\n * it through {@link createConnectionStateStore} (which also wires binding persistence and replays\n * surviving connections after a wake), then `get`/`set`/`clearApp` the app state directly.\n *\n * The mechanism is carrier-neutral — it only needs read/write/enumerate callbacks for the connection's\n * attachment — but it pays off on transports whose connections outlive process eviction (e.g. a\n * Durable Object's hibernatable WebSockets), which is why it lives beside the hibernation adapter.\n *\n * ```ts\n * const players = createConnectionStateStore(serverHandler, {\n *   schema: vs_player,\n *   read: (ws) => ws.deserializeAttachment(),\n *   write: (ws, v) => ws.serializeAttachment(v),\n *   getConnections: () => ctx.getWebSockets(),\n * });\n * players.set(ws, player); // binding is preserved automatically\n * const player = players.get(ws);\n * ```\n */\nexport class ConnectionStateStore<TConn, TApp> {\n  constructor(private readonly options: IConnectionStateStoreOptions<TConn, TApp>) {}\n\n  /** The validated app state for a connection, or `null` if unset / invalid. */\n  get(connection: TConn): TApp | null {\n    return this._readAttachment(connection).app ?? null;\n  }\n\n  /** Set the app state, preserving the runtime binding already pinned to the connection. */\n  set(connection: TConn, app: TApp): void {\n    const existing = this._readAttachment(connection);\n    this.options.write(connection, { app, binding: existing.binding });\n  }\n\n  /** Clear the app state but keep the binding (e.g. a spectator that stopped watching). */\n  clearApp(connection: TConn): void {\n    const existing = this._readAttachment(connection);\n    this.options.write(connection, { binding: existing.binding });\n  }\n\n  /** Every live connection paired with its (validated) app state — for rebuilding in-memory state after a wake. */\n  entries(): [TConn, TApp | null][] {\n    return this.options\n      .getConnections()\n      .map((connection) => [connection, this._readAttachment(connection).app ?? null]);\n  }\n\n  /** @internal Persist a freshly-bound connection's binding, preserving any app state already stored. */\n  _persistBinding(connection: TConn, binding: IAcceptorConnectionBinding): void {\n    const existing = this._readAttachment(connection);\n    this.options.write(connection, { app: existing.app, binding });\n  }\n\n  /** @internal The persisted binding for a connection, if any (used to replay routing after a wake). */\n  _readBinding(connection: TConn): IAcceptorConnectionBinding | undefined {\n    return this._readAttachment(connection).binding;\n  }\n\n  private _readAttachment(connection: TConn): IConnectionAttachment<TApp> {\n    try {\n      const raw = this.options.read(connection);\n      if (typeof raw !== \"object\" || raw === null) return {};\n\n      const attachment = raw as IConnectionAttachment<TApp>;\n      const result: IConnectionAttachment<TApp> = {};\n      // The binding is our own serialized shape — trust it as written.\n      if (attachment.binding != null) result.binding = attachment.binding;\n      if (attachment.app !== undefined) {\n        const app = this._validateApp(attachment.app);\n        if (app !== undefined) result.app = app;\n      }\n      return result;\n    } catch {\n      return {};\n    }\n  }\n\n  private _validateApp(value: unknown): TApp | undefined {\n    const schema = this.options.schema;\n    if (schema == null) return value as TApp;\n    const result = schema[\"~standard\"].validate(value);\n    // App state is validated on a synchronous read path; an async schema can't be honored here.\n    if (result instanceof Promise) return undefined;\n    if (result.issues != null) return undefined;\n    return result.value;\n  }\n}\n\n/**\n * Build a per-connection {@link ConnectionStateStore} bound to an {@link ChannelAcceptor}: it registers\n * itself as the handler's connection-bound persistence callback (so bindings are written without\n * overwriting app state) and immediately replays every live connection's stored binding via\n * {@link ChannelAcceptor.rehydrate} — so on a transport that resumes after eviction (e.g. a\n * Durable Object waking from hibernation) both the app identity and the action routing come back from a\n * single attachment, with no storage reads and no hand-rolled merge.\n *\n * Lives outside the handler so the generic {@link ChannelAcceptor} stays free of any attachment/\n * hibernation concern — it exposes only the neutral `setOnConnectionBound` + `rehydrate`\n * hooks this builder drives.\n */\nexport function createConnectionStateStore<TConn, TApp>(\n  handler: ChannelAcceptor<TConn>,\n  options: IConnectionStateStoreOptions<TConn, TApp>,\n): ConnectionStateStore<TConn, TApp> {\n  const store = new ConnectionStateStore<TConn, TApp>(options);\n  handler.setOnConnectionBound((connection, binding) => store._persistBinding(connection, binding));\n\n  // Rebuild routing for sockets that survived an eviction.\n  for (const connection of options.getConnections()) {\n    const binding = store._readBinding(connection);\n    if (binding != null) handler.rehydrate(connection, binding);\n  }\n\n  return store;\n}\n","import type { ChannelAcceptor, IAcceptorConnectionBinding } from \"../ChannelAcceptor\";\n\nexport interface IHibernatableWsServerAdapterOptions<TConn> {\n  /** The handler to drive (from `createSecureChannelAcceptor` or `createChannelAcceptor`). */\n  handler: ChannelAcceptor<TConn>;\n  /** All currently-live connections — replayed on construction to rebuild bindings after a wake. */\n  getConnections: () => TConn[];\n  /** Read a connection's persisted binding (e.g. `(ws) => ws.deserializeAttachment()`). */\n  getAttachment: (connection: TConn) => IAcceptorConnectionBinding | undefined;\n  /** Persist a connection's binding when it is bound (e.g. `(ws, b) => ws.serializeAttachment(b)`). */\n  setAttachment: (connection: TConn, binding: IAcceptorConnectionBinding) => void;\n}\n\n/**\n * The neutral lifecycle surface for a duplex (push-capable) acceptor: feed it each inbound frame and tell\n * it when a connection goes away. Carrier-agnostic — a WebSocket, a WebRTC data channel, or any other\n * duplex connection drives the same two methods.\n */\nexport interface IDuplexConnectionRouter<TConn> {\n  /** Feed one inbound frame from a connection into the handler. */\n  receive: (connection: TConn, frame: string | ArrayBuffer | Uint8Array) => void;\n  /** Forget a connection (call on socket close/error). */\n  drop: (connection: TConn) => void;\n}\n\n/**\n * Wire the hibernation lifecycle for an acceptor handler on a transport whose connections outlive process\n * eviction (e.g. a Durable Object's hibernatable WebSockets). It owns persistence end to end:\n * registers `setAttachment` as the handler's connection-bound callback and immediately replays every\n * live connection's stored binding via `getAttachment`, so results/pushes still route after a wake.\n *\n * Layered on top of the generic {@link ChannelAcceptor} — it touches only the handler's neutral\n * `setOnConnectionBound` / `rehydrate` / `receive` / `drop` surface, so no\n * hibernation concern leaks into the handler itself.\n *\n * Construct it once when the handler is built, then forward connection events:\n * ```ts\n * const duplex = createHibernatableWsServerAdapter({ handler, getConnections, getAttachment, setAttachment });\n * // webSocketMessage(ws, msg) => duplex.receive(ws, msg);\n * // webSocketClose/Error(ws)  => duplex.drop(ws);\n * ```\n */\nexport function createHibernatableWsServerAdapter<TConn>(\n  options: IHibernatableWsServerAdapterOptions<TConn>,\n): IDuplexConnectionRouter<TConn> {\n  const { handler, getConnections, getAttachment, setAttachment } = options;\n\n  handler.setOnConnectionBound(setAttachment);\n\n  // Rebuild bindings for connections that survived an eviction.\n  for (const connection of getConnections()) {\n    const binding = getAttachment(connection);\n    if (binding != null) handler.rehydrate(connection, binding);\n  }\n\n  return {\n    receive: (connection, frame) => handler.receive(connection, frame),\n    drop: (connection) => handler.drop(connection),\n  };\n}\n","import type { IDuplexAcceptorCarrier } from \"@nice-code/wire\";\nimport { ETransportShape } from \"../Transport.types\";\n\nexport {\n  createDuplexCarrierLifecycle,\n  type IAcceptorAttachmentStore,\n  type IDuplexAcceptorCarrier,\n  type IDuplexCarrierLifecycle,\n  type IDuplexConnectionRouter,\n  type IInboundFrameLimits,\n  type IWsAcceptorCarrierOptions,\n  type TInboundFrameLimitReason,\n} from \"@nice-code/wire\";\n\n/**\n * Exchange acceptor carriers remain action-owned because they decode and answer the action lane.\n * Duplex acceptor carriers are wire-owned and re-exported above for source compatibility.\n */\nexport interface IExchangeAcceptorCarrier {\n  /** Discriminant so `serveChannel` can tell an exchange carrier from a duplex one. */\n  readonly shape: ETransportShape.exchange;\n  /**\n   * Whether this endpoint runs the secure exchange protocol (default `true`). `false` makes it a plain\n   * endpoint — no handshake, token, or encryption: the connector's plain `{ k: \"act\", w }` envelope is\n   * answered in kind, and a raw action wire is answered with the raw result. A plain endpoint ignores the\n   * central crypto identity entirely.\n   */\n  secure?: boolean;\n  /** Which requests carry an action exchange envelope on `POST`. Defaults to `serveChannel`'s path match. */\n  isActionPath?: (url: URL) => boolean;\n  /**\n   * CORS headers merged onto every response (a preflight `OPTIONS` is answered `204`). Defaults to the\n   * permissive `*` set; pass `false` to attach no CORS headers at all.\n   */\n  cors?: Record<string, string> | false;\n  /** Plain mode only: use the error's HTTP status for failures (default `true`). Ignored when secure. */\n  useErrorStatus?: boolean;\n  /** Short carrier-kind label for the devtools chip (e.g. `\"http\"`). */\n  readonly carrierLabel: string;\n}\n\nexport type TAcceptorCarrier<TConn = unknown> =\n  | IDuplexAcceptorCarrier<TConn>\n  | IExchangeAcceptorCarrier;\n\n/**\n * Narrow an acceptor carrier to the exchange shape via its `shape` discriminant — the one branch\n * `serveChannel` uses to pick the duplex (push-capable) vs exchange (request/reply) wiring. A duplex\n * carrier carries `shape: ETransportShape.duplex`, so the `else` branch is the duplex one.\n */\nexport function isExchangeAcceptorCarrier<TConn>(\n  carrier: TAcceptorCarrier<TConn>,\n): carrier is IExchangeAcceptorCarrier {\n  return carrier.shape === ETransportShape.exchange;\n}\n","import { ClientCryptoKeyLink, type StorageAdapter } from \"@nice-code/util\";\nimport type { IReliableReceiver } from \"@nice-code/wire\";\nimport {\n  createStorageTofuVerifyKeyResolver,\n  ESecurityLevel,\n  type IClientVerifyKeyResolver,\n  RuntimeCoordinate,\n} from \"@nice-code/wire\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { TActionPayload_Any_JsonObject } from \"../../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport type { ActionPayload_Request } from \"../../ActionDefinition/Action/Payload/ActionPayload_Request\";\nimport type { RunningAction } from \"../../ActionDefinition/Action/RunningAction\";\nimport type { ActionDomain } from \"../../ActionDefinition/Domain/ActionDomain\";\nimport type { IActionDomain } from \"../../ActionDefinition/Domain/ActionDomain.types\";\nimport { EErrId_NiceAction, err_nice_action } from \"../../errors/err_nice_action\";\nimport { ActionRuntime } from \"../ActionRuntime\";\nimport type { TActionRuntimeHandler } from \"../ActionRuntime.types\";\nimport type { IActionHandlerContext } from \"../Handler/ActionHandler.types\";\nimport {\n  type ChannelAcceptor,\n  createChannelAcceptor,\n  type IAcceptorFrameProtocol,\n  type TAcceptorCaseFn,\n} from \"../Handler/PeerLink/Acceptor/ChannelAcceptor\";\nimport { createActionFetchHandler } from \"../Handler/PeerLink/Acceptor/createActionFetchHandler\";\nimport {\n  type ConnectionStateStore,\n  createConnectionStateStore,\n  type IConnectionAttachment,\n} from \"../Handler/PeerLink/Acceptor/Hibernation/ConnectionStateStore\";\nimport {\n  createHibernatableWsServerAdapter,\n  type IDuplexConnectionRouter,\n} from \"../Handler/PeerLink/Acceptor/Hibernation/createHibernatableWsServerAdapter\";\nimport {\n  type IDuplexAcceptorCarrier,\n  type IExchangeAcceptorCarrier,\n  isExchangeAcceptorCarrier,\n  type TAcceptorCarrier,\n} from \"../Transport/Carrier/AcceptorCarrier.types\";\nimport { EErrId_NiceTransport, err_nice_transport } from \"../Transport/err_nice_transport\";\nimport type { IExchangeAcceptorSecurity } from \"../Transport/SecureSession/exchangeAcceptor\";\nimport {\n  acceptChannel,\n  combineChannels,\n  type IActionChannel,\n  type TChannelAcceptorCases,\n  type TCombinedAcceptorDomains,\n} from \"./ActionChannel\";\nimport type { IActionServeLogger } from \"./serveLogger\";\n\n/**\n * Build the per-connection subset resolver a multi-channel acceptor uses: advertised `hello.channels`\n * tags → the channel that connection speaks (its own codec + dictionary version for a single tag, the\n * composed union for several, the combined `channel` for none). Returns `null` — the handshake then\n * rejects — for an unknown tag, and for a repeated tag: a repeat would compose the same channel twice\n * into the positional wire dictionary and desync every later route index.\n *\n * Throws immediately (setup time, not per connection) when two served channels share a tag — a\n * last-write-wins registry could never route that deterministically.\n */\nexport function buildChannelSubsetResolver(\n  combined: IActionChannel<any, any>,\n  registry: readonly IActionChannel<any, any>[],\n): (tags: readonly string[] | undefined) => IActionChannel | null {\n  const byTag = new Map<string, IActionChannel<any, any>>();\n  for (const entry of registry) {\n    if (byTag.has(entry.tag)) {\n      throw new Error(\n        `serveChannel: duplicate channel tag \"${entry.tag}\" in \\`channels\\` — every served channel needs a distinct tag, or subset selection cannot route deterministically.`,\n      );\n    }\n    byTag.set(entry.tag, entry);\n  }\n  return (tags) => {\n    if (tags == null || tags.length === 0) return combined;\n    const selected: IActionChannel<any, any>[] = [];\n    const seen = new Set<string>();\n    for (const tag of tags) {\n      const found = byTag.get(tag);\n      if (found == null || seen.has(tag)) return null;\n      seen.add(tag);\n      selected.push(found);\n    }\n    return selected.length === 1 ? selected[0] : combineChannels(selected);\n  };\n}\n\n/** Default accepted set, shared by every carrier: negotiate per connection to whatever the client picks. */\nconst DEFAULT_SERVER_SECURITY_LEVELS = [\n  ESecurityLevel.none,\n  ESecurityLevel.authenticated,\n  ESecurityLevel.encrypted,\n] as const;\n\n/** Per-connection app-state config for {@link serveChannel}'s `connectionState`. */\nexport interface IServeConnectionStateOptions<TApp> {\n  /**\n   * Optional Standard Schema (valibot, zod, …) validating the app state on read — a value that fails\n   * validation reads back as `null`. Omit to store the app state untyped.\n   */\n  schema?: StandardSchemaV1<unknown, TApp>;\n}\n\n/**\n * The per-action handle a `serveChannel` `channelCases` case receives as its second argument — the\n * originating connection enriched with everything a case typically reaches for, so it never threads\n * `ws` through `this.connections` / `this.server` by hand:\n *\n * - {@link state} / {@link setState} / {@link clearState} — the connection's typed app state (when\n *   `connectionState` is configured), co-stored with the routing binding so it survives hibernation.\n * - {@link broadcast} — fan a server push to every other connection (skip self with `exceptSelf`).\n * - {@link pushBack} — push a server-initiated action down *this* same connection.\n *\n * Over the HTTP-exchange path there is no live socket: {@link connection} is `null`, {@link state} reads\n * `null`, and {@link setState}/{@link clearState}/{@link pushBack} throw `connection_required` (an exchange reply\n * rides its own request — it can't carry an unsolicited push).\n */\nexport interface IConnectionContext<TConn, TApp = unknown> extends IActionHandlerContext {\n  /** The originating live connection, or `null` on the HTTP-exchange path (escape hatch). */\n  connection: TConn | null;\n  /** This connection's app state, or `null` if unset / no live socket. */\n  state: TApp | null;\n  /** Set this connection's app state. Throws `connection_required` without a live socket. */\n  setState: (value: TApp) => void;\n  /** Clear this connection's app state but keep the routing binding. Throws without a live socket. */\n  clearState: () => void;\n  /** Fan a server-initiated action out to every connection; `exceptSelf` skips this one. */\n  broadcast: <DOM extends IActionDomain, ID extends keyof DOM[\"actionSchema\"] & string>(\n    makeRequest: () => ActionPayload_Request<DOM, ID>,\n    options?: {\n      exceptSelf?: boolean;\n      where?: (connection: TConn) => boolean;\n      timeout?: number;\n      onError?: (error: unknown, connection: TConn) => void;\n    },\n  ) => void;\n  /** Push a server-initiated action down this same connection. Throws if there is no live socket. */\n  pushBack: <DOM extends IActionDomain, ID extends keyof DOM[\"actionSchema\"] & string>(\n    request: ActionPayload_Request<DOM, ID>,\n    options?: { timeout?: number },\n  ) => RunningAction<DOM, ID>;\n}\n\nexport interface IServeChannelOptions<\n  TO_ACCEPTOR extends readonly ActionDomain<any>[],\n  TConn,\n  TApp = unknown,\n> {\n  /**\n   * One backing store for the server's crypto identity *and* its trust-on-first-use verify-key pins\n   * (their keys don't collide). It is built once and shared across every carrier, so the WebSocket and the\n   * secure-HTTP endpoint present the exact same verify/exchange keys and trust the same pinned clients.\n   * Back it with persistent storage (e.g. a Durable Object's storage) so identity + pins survive eviction.\n   *\n   * Required only when at least one carrier is secure (the default). A fully-plain server (every carrier\n   * `secure: false`) needs no storage and may omit it.\n   *\n   * The secure HTTP exchange is stateless — its handshake + session ride sealed tokens, so it touches\n   * this store only for the (read-mostly) identity, never per session. That lets a single secure-exchange\n   * server (`carriers: [httpAcceptorCarrier()]`) run on a stateless Worker/Node backend with no Durable\n   * Object. On a *strongly-consistent* store (DO storage, D1, Node memory) the default lazy identity is\n   * fork-safe. On an *eventually-consistent* store (Cloudflare KV) pass an explicit {@link link} built\n   * with `identityMode: \"required\"` and `provisionIdentity()` it once out-of-band, so a transient read\n   * miss can never fork a second identity (which pinned clients would then permanently reject).\n   */\n  storage?: StorageAdapter;\n  /**\n   * The carriers this channel is served over — the accept-in dual of `connectChannel`'s `transports`.\n   * Build them with `wsAcceptorCarrier` / `httpAcceptorCarrier`. Any number of duplex (push-capable)\n   * carriers are supported (e.g. WebSocket + WebRTC), plus at most one exchange (request/reply) carrier;\n   * all share one crypto identity and one runtime, and each result/push routes back over the carrier its\n   * client connected on.\n   */\n  carriers: readonly TAcceptorCarrier<TConn>[];\n  /** Your execution handlers (e.g. the local handler holding the action cases). Registered for you. */\n  handlers?: TActionRuntimeHandler[];\n  /**\n   * The individual channels this acceptor serves, for **subset selection** — set by `serveChannels` so a\n   * client connecting any subset (advertised as `hello.channels` tags) gets the matching composed codec +\n   * dictionary version. Omit for a single channel (then `channel` is used as-is). When two or more are\n   * given, a connection with no advertised tags falls back to the combined `channel`.\n   */\n  channels?: readonly IActionChannel<any, any>[];\n  /**\n   * The server's crypto identity. Defaults to a fresh {@link ClientCryptoKeyLink} over `storage`. Pass an\n   * existing link only to share identity with acceptors built outside this call.\n   */\n  link?: ClientCryptoKeyLink;\n  /** Accepted level(s) for every carrier; defaults to negotiating any of none/authenticated/encrypted. */\n  securityLevel?: ESecurityLevel | readonly ESecurityLevel[];\n  /** Trust decision for a client's verify key; defaults to storage-backed TOFU over `storage`. */\n  verifyKeyResolver?: IClientVerifyKeyResolver;\n  /** Timeout (ms) applied to server-initiated actions awaiting a client response. */\n  defaultTimeout?: number;\n  /**\n   * Co-store per-connection app state alongside the routing binding in the sole duplex carrier's connection\n   * attachment, so both survive a wake from eviction. Reach the typed store back on `server.connections`.\n   * Requires the carrier to expose an attachment store (the Cloudflare `durableObjectWsCarrier` does) and\n   * exactly one duplex carrier.\n   */\n  connectionState?: IServeConnectionStateOptions<TApp>;\n  /**\n   * Connection-aware action cases for the channel's acceptor (`toAcceptor`) domains — each case receives the\n   * primed request *and* an {@link IConnectionContext} (the connection plus its typed `state` and\n   * `broadcast`/`pushBack`). The connection-aware dual of `handlers`, registered on the runtime for you.\n   * Requires exactly one duplex carrier.\n   */\n  channelCases?: TChannelAcceptorCases<TO_ACCEPTOR, IConnectionContext<TConn, TApp>>;\n  /**\n   * Optional pluggable logger for served requests — `onRequest` fires when an inbound action is accepted\n   * (before it executes) and returns a reporter called with the outcome, so each request produces a\n   * request line and a result line. Fanned across every carrier (each request is tagged with its carrier's\n   * transport label, e.g. `\"http\"` / `\"ws\"`). Use {@link createDefaultServeLogger} for a ready-made console\n   * logger, or implement {@link IActionServeLogger} to forward to your own logging stack:\n   * ```ts\n   * serveChannel(channel, { identity, storage, carriers, logger: createDefaultServeLogger() });\n   * ```\n   */\n  logger?: IActionServeLogger;\n  /**\n   * The server's wire-observation seam — the exact mirror of `connectChannel({ wireTap })`. Every frame\n   * that crosses a carrier is reported with its **true wire byte size** (post-encryption on the way out,\n   * pre-decryption on the way in: what the platform actually transmits and bills) and its lane\n   * (`\"handshake\"` / `\"keepalive\"` / `\"action\"` / a frame-protocol id such as `\"realm\"`), tagged with the\n   * bound client's coordinate as `linkId` so a multi-client server attributes traffic per connection.\n   * Sizes only — payload contents are never captured.\n   *\n   * Feed it a `TrafficMetricsCore` to give a backend the same traffic panel a frontend has:\n   * ```ts\n   * const traffic = new TrafficMetricsCore();\n   * serveChannel(channel, { identity, storage, carriers, wireTap: traffic.wireTap });\n   * createServerDevtoolsHost({ name: \"api\" }).contributeSample(trafficSampleScope(\"traffic\", traffic));\n   * ```\n   * Fanned across every duplex carrier. With no tap the cost is one null check per frame.\n   */\n  wireTap?: import(\"@nice-code/wire\").TWireTapFn;\n  /**\n   * Persisted receive store for the **persisted** reliability tier (`.reliable({ persist: true })`). When set,\n   * a persisted-tier stream dedups through this store (shared across all duplex carriers) instead of the\n   * in-memory inbox, so its high-water survives eviction and a replayed stream dedups rather than\n   * redelivering. Build it with the platform helper (Cloudflare: `cloudflareReliableLog(ctx)`). Omit it and\n   * persisted-tier streams degrade gracefully to the session-tier (in-memory) behavior.\n   *\n   * Same store as the lower-level acceptor's\n   * {@link IChannelAcceptorBaseOptions.persistedReceiver | `persistedReceiver`} — this serve-level\n   * option simply feeds that field, so type-surface searches for either name land on the same thing.\n   */\n  reliableStore?: IReliableReceiver<TActionPayload_Any_JsonObject<any>>;\n  /**\n   * Cap on distinct **keyed** (`streamKey`) reliable streams tracked per client (default 256). Keys are\n   * client-chosen strings, so this bounds the receiver state one client can allocate; past the cap a new\n   * key's frames are served best-effort with a one-time warning.\n   */\n  maxKeyedStreamsPerClient?: number;\n  /**\n   * Protocol modules to register on every duplex acceptor handler — e.g. a realm server's acceptor\n   * protocol (`createRealmHost(...).protocol`). The accept-in mirror of\n   * `connectChannel({ protocols })`. Registered **before** the hibernation adapter replays surviving\n   * bindings, so each protocol's `onAttach` fires for rehydrated connections on a Durable Object wake.\n   */\n  protocols?: readonly IAcceptorFrameProtocol<TConn>[];\n}\n\n/**\n * One server serving a secure channel over several carriers — the accept-in dual of `connectChannel`,\n * returned by {@link serveChannel}. Wire its surface straight to the host's request/socket events.\n */\nexport interface IChannelServer<TConn, TApp = unknown> {\n  /** The instance-scoped runtime executing this server's actions. */\n  readonly runtime: ActionRuntime;\n  /**\n   * The duplex channel acceptors — one per duplex carrier, in carrier order (empty if none). For pushing,\n   * prefer {@link pushToClient} (it resolves the owning acceptor); reach for these for cross-carrier work\n   * like a per-acceptor `broadcast`.\n   */\n  acceptors: ChannelAcceptor<TConn>[];\n  /**\n   * Unified request handler: answers the CORS preflight, performs the duplex upgrade for an upgrade\n   * request, serves a secure-exchange action `POST`, else `404`. Forward the host's `fetch` straight to it.\n   */\n  fetch: (request: Request) => Promise<Response>;\n  /**\n   * Feed one inbound frame from a live connection into the server — forward your host's \"message\" event\n   * here (a Durable Object's `webSocketMessage`, a Bun `websocket.message`, a Node `ws.on(\"message\")`).\n   * Routes to the sole duplex carrier; throws with a clear message when there are zero or several duplex\n   * carriers (for the multi-carrier case feed each `acceptors[i]` / carrier handle directly).\n   */\n  receive: (connection: TConn, frame: string | Uint8Array | ArrayBuffer) => void;\n  /**\n   * Forget a connection on close/error — forward your host's \"close\"/\"error\" event here. Routes to the\n   * sole duplex carrier; a no-op when there are none (an HTTP-only server has no sockets to drop).\n   */\n  drop: (connection: TConn) => void;\n  /** Permanently quiesce the host: detach connections and reject/ignore all late entry points. */\n  dispose: () => void;\n  /**\n   * Push a server-initiated action to a connected client (the runtime is bound in, so unlike\n   * {@link ChannelAcceptor.pushToClient} you pass only the target + request). It routes through the duplex\n   * carrier the target connected on. Every failure is an `err_nice_transport`: `not_found` is thrown\n   * at the call when no duplex carrier holds the target; `send_failed` and `timeout` reject the action.\n   */\n  pushToClient: <DOM extends IActionDomain, ID extends keyof DOM[\"actionSchema\"] & string>(\n    target: TConn | RuntimeCoordinate,\n    request: ActionPayload_Request<DOM, ID>,\n    options?: { timeout?: number },\n  ) => RunningAction<DOM, ID>;\n  /**\n   * Fan a server-initiated action out to every connection on the sole duplex carrier (skip the origin with\n   * `except`, filter with `where`). The push-to-many counterpart of {@link pushToClient}. Throws if there\n   * isn't exactly one duplex carrier (with several, broadcast over a specific `acceptors[i]`).\n   */\n  broadcast: <DOM extends IActionDomain, ID extends keyof DOM[\"actionSchema\"] & string>(\n    makeRequest: () => ActionPayload_Request<DOM, ID>,\n    options?: {\n      except?: TConn | null;\n      where?: (connection: TConn) => boolean;\n      timeout?: number;\n      onError?: (error: unknown, connection: TConn) => void;\n    },\n  ) => void;\n  /**\n   * The per-connection app-state store co-stored with the routing binding in the connection attachment —\n   * present only when `connectionState` was passed. `get`/`set`/`clearApp`/`entries` it directly; it\n   * survives hibernation alongside the binding.\n   */\n  connections?: ConnectionStateStore<TConn, TApp>;\n}\n\nexport type TServeRuntimeOptions =\n  | { identity: RuntimeCoordinate; runtime?: never }\n  | { runtime: ActionRuntime; identity?: never };\n\nexport type TServeChannelOptions<\n  TO_ACCEPTOR extends readonly ActionDomain<any>[],\n  TConn,\n  TApp = unknown,\n> = IServeChannelOptions<TO_ACCEPTOR, TConn, TApp> & TServeRuntimeOptions;\n\nexport function serveChannel<\n  TO_ACCEPTOR extends readonly ActionDomain<any>[],\n  TO_CONNECTOR extends readonly ActionDomain<any>[],\n  TConn,\n  TApp,\n>(\n  channel: IActionChannel<TO_ACCEPTOR, TO_CONNECTOR>,\n  options: TServeChannelOptions<TO_ACCEPTOR, TConn, TApp> & {\n    connectionState: IServeConnectionStateOptions<TApp>;\n  },\n): IChannelServer<TConn, TApp> & { connections: ConnectionStateStore<TConn, TApp> };\nexport function serveChannel<\n  TO_ACCEPTOR extends readonly ActionDomain<any>[] = readonly ActionDomain<any>[],\n  TO_CONNECTOR extends readonly ActionDomain<any>[] = readonly ActionDomain<any>[],\n  TConn = unknown,\n  TApp = unknown,\n>(\n  channel: IActionChannel<TO_ACCEPTOR, TO_CONNECTOR>,\n  options: TServeChannelOptions<TO_ACCEPTOR, TConn, TApp>,\n): IChannelServer<TConn, TApp>;\n\n/**\n * Serve a secure channel over one or more carriers from a single call — the accept-in dual of\n * `connectChannel`. It builds the crypto identity (a {@link ClientCryptoKeyLink} + a storage-backed TOFU\n * resolver) and the security block (coordinate, dictionary version, accepted levels) *once* from\n * `(runtime, channel)` and fans them across every carrier, so the WebSocket and the secure-HTTP endpoint\n * can never drift apart. It registers your handlers (plus the duplex acceptor it builds) on the runtime,\n * wires hibernation when the duplex carrier exposes an attachment store, and returns a single\n * {@link IChannelServer} whose `fetch` / `receive` / `drop` / `pushToClient` / `broadcast` you forward\n * straight to the host:\n * ```ts\n * const server = serveChannel(channel, {\n *   identity: serverCoordinate, storage,\n *   carriers: [wsAcceptorCarrier({ send, upgrade, attachmentStore }), httpAcceptorCarrier()],\n *   connectionState: { schema: vs_player }, // optional: co-store per-connection app state (survives hibernation)\n *   channelCases: { join: (action, conn) => { conn.setState(action.input); … } }, // connection-aware cases\n * });\n * // fetch(req) => server.fetch(req)\n * // webSocketMessage(conn, m) => server.receive(conn, m)\n * // webSocketClose/Error(conn) => server.drop(conn)\n * // server.connections.get(conn) / server.broadcast(() => push.request(…), { except: conn })\n * ```\n *\n * On Cloudflare, `serveDurableObject` folds the whole DO transport stack (carriers + storage + keepalive)\n * into this — reach for it instead of assembling the carriers by hand.\n *\n * `TConn` (the live-connection token a duplex carrier hands back through `send`/`receive`/`drop`) is\n * inferred from the carriers — `WebSocket` for `wsAcceptorCarrier`, the data-channel type for a WebRTC\n * carrier, and so on — so it stays carrier-agnostic. Passing `connectionState` narrows the return so\n * `server.connections` is non-optional.\n */\nexport function serveChannel<\n  TO_ACCEPTOR extends readonly ActionDomain<any>[],\n  TO_CONNECTOR extends readonly ActionDomain<any>[],\n  TConn,\n  TApp,\n>(\n  runtime: ActionRuntime,\n  channel: IActionChannel<TO_ACCEPTOR, TO_CONNECTOR>,\n  options: IServeChannelOptions<TO_ACCEPTOR, TConn, TApp> & {\n    connectionState: IServeConnectionStateOptions<TApp>;\n  },\n): IChannelServer<TConn, TApp> & { connections: ConnectionStateStore<TConn, TApp> };\nexport function serveChannel<\n  TO_ACCEPTOR extends readonly ActionDomain<any>[] = readonly ActionDomain<any>[],\n  TO_CONNECTOR extends readonly ActionDomain<any>[] = readonly ActionDomain<any>[],\n  TConn = unknown,\n  TApp = unknown,\n>(\n  runtime: ActionRuntime,\n  channel: IActionChannel<TO_ACCEPTOR, TO_CONNECTOR>,\n  options: IServeChannelOptions<TO_ACCEPTOR, TConn, TApp>,\n): IChannelServer<TConn, TApp>;\nexport function serveChannel(\n  runtimeOrChannel:\n    | ActionRuntime\n    | IActionChannel<readonly ActionDomain<any>[], readonly ActionDomain<any>[]>,\n  channelOrOptions:\n    | IActionChannel<readonly ActionDomain<any>[], readonly ActionDomain<any>[]>\n    | TServeChannelOptions<readonly ActionDomain<any>[], any, any>,\n  legacyOptions?: IServeChannelOptions<readonly ActionDomain<any>[], any, any>,\n): IChannelServer<any, any> {\n  type TConn = any;\n  const modern = !(runtimeOrChannel instanceof ActionRuntime);\n  const channel = (modern ? runtimeOrChannel : channelOrOptions) as IActionChannel<\n    readonly ActionDomain<any>[],\n    readonly ActionDomain<any>[]\n  >;\n  const rawOptions = (modern ? channelOrOptions : legacyOptions) as\n    | TServeChannelOptions<readonly ActionDomain<any>[], any, any>\n    | undefined;\n  if (rawOptions == null) {\n    throw err_nice_action.fromId(EErrId_NiceAction.conflicting_server_options, {\n      detail: \"serveChannel requires server options\",\n    });\n  }\n  const suppliedRuntime = modern ? rawOptions.runtime : (runtimeOrChannel as ActionRuntime);\n  const identity = modern ? rawOptions.identity : undefined;\n  if (modern && (suppliedRuntime == null) === (identity == null)) {\n    throw err_nice_action.fromId(EErrId_NiceAction.conflicting_server_options, {\n      detail: \"pass exactly one of `identity` or `runtime`\",\n    });\n  }\n  // The deprecated positional form takes its runtime positionally; an `identity` in the options bag\n  // would be silently dropped, so say so instead of ignoring it.\n  if (!modern && rawOptions.identity != null) {\n    throw err_nice_action.fromId(EErrId_NiceAction.conflicting_server_options, {\n      detail:\n        \"the deprecated `serveChannel(runtime, channel, options)` form cannot take `identity` — \" +\n        \"use `serveChannel(channel, { identity, … })`\",\n    });\n  }\n  const ownsRuntime = suppliedRuntime == null;\n  const runtime = suppliedRuntime ?? new ActionRuntime(identity!, { scope: \"instance\" });\n  const { identity: _identity, runtime: _runtime, ...options } = rawOptions as any;\n  runtime._assertActive();\n  if (runtime.scope !== \"instance\") {\n    throw err_nice_action.fromId(EErrId_NiceAction.invalid_server_runtime_scope, {\n      runtime: runtime.coordinate.stringId,\n      actualScope: runtime.scope,\n    });\n  }\n  try {\n    const duplexCarriers = options.carriers.filter(\n      (carrier: TAcceptorCarrier<TConn>): carrier is IDuplexAcceptorCarrier<TConn> =>\n        !isExchangeAcceptorCarrier(carrier),\n    );\n    const exchangeCarriers = options.carriers.filter(\n      (carrier: TAcceptorCarrier<TConn>): carrier is IExchangeAcceptorCarrier =>\n        isExchangeAcceptorCarrier(carrier),\n    );\n\n    if (exchangeCarriers.length > 1) {\n      throw new Error(\"serveChannel: at most one exchange carrier is supported\");\n    }\n    const exchangeCarrier: IExchangeAcceptorCarrier | undefined = exchangeCarriers[0];\n\n    const singleDuplex = duplexCarriers.length === 1;\n    if (options.connectionState != null && !singleDuplex) {\n      throw new Error(\"serveChannel: `connectionState` requires exactly one duplex carrier\");\n    }\n    if (options.channelCases != null && !singleDuplex) {\n      throw new Error(\"serveChannel: `channelCases` requires exactly one duplex carrier\");\n    }\n\n    const exchangeSecure = exchangeCarrier != null && (exchangeCarrier.secure ?? true);\n    const anyDuplexSecure = duplexCarriers.some(\n      (carrier: IDuplexAcceptorCarrier<TConn>) => carrier.secure ?? true,\n    );\n    const securityLevel = options.securityLevel ?? DEFAULT_SERVER_SECURITY_LEVELS;\n\n    // Multi-channel subset selection: when serving several channels, resolve a connection's advertised tags\n    // (`hello.channels`) into the channel it should use. Omitted for a single channel (unchanged path).\n    const registry = options.channels;\n    const resolveChannel =\n      registry != null && registry.length > 1\n        ? buildChannelSubsetResolver(channel, registry)\n        : undefined;\n\n    // The shared crypto identity (link + TOFU resolver) — built once and fanned across every *secure*\n    // carrier. Only constructed when something needs it; a fully-plain server uses no storage.\n    let secure:\n      | {\n          storage: StorageAdapter;\n          link: ClientCryptoKeyLink;\n          verifyKeyResolver: IClientVerifyKeyResolver;\n        }\n      | undefined;\n    if (anyDuplexSecure || exchangeSecure) {\n      const storage = options.storage;\n      if (storage == null) {\n        throw new Error(\n          \"serveChannel: a secure carrier requires `storage`. Pass it, or set `secure: false` on the carrier for a plain endpoint.\",\n        );\n      }\n      secure = {\n        storage,\n        link: options.link ?? new ClientCryptoKeyLink({ storageAdapter: storage }),\n        verifyKeyResolver: options.verifyKeyResolver ?? createStorageTofuVerifyKeyResolver(storage),\n      };\n    }\n\n    // One acceptor handler per duplex carrier, each activated as its own lifecycle handle. Secure carriers →\n    // `acceptChannel` (handshake + the shared identity, so they present the same keys as the exchange\n    // endpoint); plain carriers → the base `createChannelAcceptor` over the channel's wire codec, no crypto.\n    // Phase-A connection-aware return routing then sends each result/push back over the carrier its client\n    // connected on.\n    // The plain (in-memory only) router for a connection — no persistence across eviction.\n    const plainRouter = (handler: ChannelAcceptor<TConn>): IDuplexConnectionRouter<TConn> => ({\n      receive: (connection, frame) => handler.receive(connection, frame),\n      drop: (connection) => handler.drop(connection),\n    });\n    const asObject = (value: unknown): object =>\n      typeof value === \"object\" && value != null ? value : {};\n\n    const acceptors: ChannelAcceptor<TConn>[] = [];\n    // The per-connection app-state store, built once over the sole duplex carrier when `connectionState` is set.\n    let connections: ConnectionStateStore<TConn, any> | undefined;\n    for (const carrier of duplexCarriers) {\n      const handler =\n        (carrier.secure ?? true) && secure != null\n          ? acceptChannel<any, any, TConn>(runtime, channel, {\n              storage: secure.storage,\n              link: secure.link,\n              verifyKeyResolver: secure.verifyKeyResolver,\n              securityLevel,\n              send: carrier.send,\n              close: carrier.close,\n              defaultTimeout: options.defaultTimeout,\n              resolveChannel,\n              logger: options.logger,\n              wireTap: options.wireTap,\n              transportLabel: carrier.carrierLabel,\n              persistedReceiver: options.reliableStore,\n              maxKeyedStreamsPerClient: options.maxKeyedStreamsPerClient,\n            })\n          : createChannelAcceptor<TConn>({\n              createFormatMessage: channel.createCodec,\n              send: carrier.send,\n              close: carrier.close,\n              runtime,\n              defaultTimeout: options.defaultTimeout,\n              logger: options.logger,\n              wireTap: options.wireTap,\n              transportLabel: carrier.carrierLabel,\n              persistedReceiver: options.reliableStore,\n              maxKeyedStreamsPerClient: options.maxKeyedStreamsPerClient,\n            });\n\n      // Frame protocols first (M1 seam): they must exist before the hibernation adapter below replays\n      // surviving bindings, so protocol `onAttach` hooks fire for rehydrated connections.\n      for (const protocol of options.protocols ?? []) {\n        handler.registerFrameProtocol(protocol);\n      }\n\n      // The attachment is one composite slot `{ app?, binding? }` per connection: serveChannel owns its\n      // layout so binding *and* app state survive a wake from a single slot.\n      // - no attachment store → in-memory only (no replay).\n      // - `connectionState` requested → the connection store owns binding + app persistence and wake-replay.\n      // - otherwise → the bare hibernation adapter persists/replays just the `.binding` sub-field.\n      const attach = carrier.attachmentStore;\n      let router: IDuplexConnectionRouter<TConn>;\n      if (attach == null) {\n        router = plainRouter(handler);\n      } else if (options.connectionState != null) {\n        connections = createConnectionStateStore<TConn, any>(handler, {\n          schema: options.connectionState.schema,\n          getConnections: attach.getConnections,\n          read: attach.read,\n          write: attach.write,\n        });\n        router = plainRouter(handler); // the store already replayed surviving bindings\n      } else {\n        router = createHibernatableWsServerAdapter<TConn>({\n          handler,\n          getConnections: attach.getConnections,\n          getAttachment: (connection) =>\n            (attach.read(connection) as IConnectionAttachment<unknown> | null | undefined)?.binding,\n          setAttachment: (connection, binding) =>\n            attach.write(connection, { ...asObject(attach.read(connection)), binding }),\n        });\n      }\n      carrier._activate(router);\n      acceptors.push(handler);\n    }\n\n    const installedHandlers: TActionRuntimeHandler[] = [...(options.handlers ?? []), ...acceptors];\n\n    // --- Connection lifecycle + server-push surface ---\n    // `receive`/`drop` are the universal forwarding seam every host environment feeds (a Durable Object's\n    // `webSocketMessage`, a Bun `websocket.message`, …). They route to the sole duplex carrier (the common\n    // case); with several, each carrier is its own handle, so callers feed those directly.\n    const soleDuplex: IDuplexConnectionRouter<TConn> | undefined = singleDuplex\n      ? duplexCarriers[0]\n      : undefined;\n    let disposed = false;\n    const receive = (connection: TConn, frame: string | Uint8Array | ArrayBuffer): void => {\n      if (disposed) return;\n      if (soleDuplex == null) {\n        throw new Error(\n          duplexCarriers.length === 0\n            ? \"serveChannel: no duplex carrier to receive on (this server has no socket transport)\"\n            : \"serveChannel: several duplex carriers — feed each carrier handle's receive() directly\",\n        );\n      }\n      soleDuplex.receive(connection, frame);\n    };\n    const drop = (connection: TConn): void => {\n      if (disposed) return;\n      soleDuplex?.drop(connection);\n    };\n\n    const pushToClient = <DOM extends IActionDomain, ID extends keyof DOM[\"actionSchema\"] & string>(\n      target: TConn | RuntimeCoordinate,\n      request: ActionPayload_Request<DOM, ID>,\n      pushOptions?: { timeout?: number },\n    ): RunningAction<DOM, ID> => {\n      if (disposed) throw new Error(\"serveChannel: server disposed\");\n      // Route the push through the acceptor that actually holds the target's live connection.\n      const owner =\n        target instanceof RuntimeCoordinate\n          ? acceptors.find((acceptor) => acceptor.ownsLiveConnectionFor(target))\n          : acceptors.find((acceptor) => acceptor.hasConnection(target));\n      if (owner == null) {\n        throw err_nice_transport.fromId(EErrId_NiceTransport.not_found, {\n          actionId:\n            target instanceof RuntimeCoordinate ? target.stringId : \"push-target-connection\",\n        });\n      }\n      return owner.pushToClient(runtime, target, request, pushOptions);\n    };\n\n    const broadcast = <DOM extends IActionDomain, ID extends keyof DOM[\"actionSchema\"] & string>(\n      makeRequest: () => ActionPayload_Request<DOM, ID>,\n      broadcastOptions?: {\n        except?: TConn | null;\n        where?: (connection: TConn) => boolean;\n        timeout?: number;\n        onError?: (error: unknown, connection: TConn) => void;\n      },\n    ): void => {\n      if (disposed) throw new Error(\"serveChannel: server disposed\");\n      if (!singleDuplex) {\n        throw new Error(\n          \"serveChannel: broadcast requires exactly one duplex carrier — broadcast over a specific acceptors[i] instead\",\n        );\n      }\n      acceptors[0].broadcast(makeRequest, { runtime, ...broadcastOptions });\n    };\n\n    // The per-action context handed to `channelCases`: the resolved connection enriched with typed `state`\n    // plus `broadcast`/`pushBack`, so a case never reaches back into `connections`/the server by hand.\n    const makeConnectionContext = (\n      connection: TConn | undefined,\n      _request: ActionPayload_Request<any, any>,\n      isConnectionLive: () => boolean,\n      execution: IActionHandlerContext,\n    ): IConnectionContext<TConn, any> => ({\n      ...execution,\n      get connection() {\n        return connection != null && isConnectionLive() ? connection : null;\n      },\n      get state() {\n        return connection != null && isConnectionLive() && connections != null\n          ? connections.get(connection)\n          : null;\n      },\n      setState(value) {\n        if (connection == null || !isConnectionLive()) {\n          throw err_nice_action.fromId(EErrId_NiceAction.connection_required, {\n            operation: \"set connection state\",\n          });\n        }\n        if (connections != null) connections.set(connection, value);\n      },\n      clearState() {\n        if (connection == null || !isConnectionLive()) {\n          throw err_nice_action.fromId(EErrId_NiceAction.connection_required, {\n            operation: \"clear connection state\",\n          });\n        }\n        if (connections != null) connections.clearApp(connection);\n      },\n      broadcast(makeRequest, contextOptions) {\n        broadcast(makeRequest, {\n          except: contextOptions?.exceptSelf && isConnectionLive() ? (connection ?? null) : null,\n          where: contextOptions?.where,\n          timeout: contextOptions?.timeout,\n          onError: contextOptions?.onError,\n        });\n      },\n      pushBack(pushRequest, pushOptions) {\n        if (connection == null || !isConnectionLive()) {\n          throw err_nice_action.fromId(EErrId_NiceAction.connection_required, {\n            operation: \"push back to the client\",\n          });\n        }\n        return pushToClient(connection, pushRequest, pushOptions);\n      },\n    });\n\n    // Connection-aware action cases for the channel's acceptor domains, registered on the runtime alongside\n    // the (sole) duplex acceptor — the connection-aware dual of `handlers`. Each case gets the enriched\n    // `IConnectionContext`, built per inbound action.\n    if (options.channelCases != null) {\n      installedHandlers.push(\n        acceptors[0].forConnectionDomainCasesMulti(\n          channel.toAcceptorDomains,\n          options.channelCases as Record<\n            string,\n            TAcceptorCaseFn<any, any, IConnectionContext<TConn, any>> | undefined\n          >,\n          makeConnectionContext,\n        ),\n      );\n    }\n\n    // A served runtime is instance-scoped and stays out of root-domain global dispatch. The lease\n    // lets one borrowed runtime back several hosts without one host removing another's handlers.\n    let releaseRuntimeHandlers: () => void;\n    try {\n      releaseRuntimeHandlers = runtime._installHandlers(installedHandlers);\n    } catch (error) {\n      for (const carrier of duplexCarriers) carrier._dispose?.();\n      for (const acceptor of acceptors) acceptor.dispose();\n      throw error;\n    }\n\n    // The exchange (request/reply) security block — derived from the same identity + the channel/runtime\n    // facts, so it never restates what the duplex side already knows. Omitted for a plain exchange carrier\n    // (`secure: false`), which then answers the plain envelope (or a raw wire) with no handshake — letting a\n    // plain HTTP fallback sit beside a secure WS.\n    const exchangeSecurity: IExchangeAcceptorSecurity | undefined =\n      exchangeSecure && secure != null\n        ? {\n            link: secure.link,\n            verifyKeyResolver: secure.verifyKeyResolver,\n            localCoordinate: runtime.coordinate.toJsonObject(),\n            // The exchange carries the JSON wire (no positional codec), so it only needs the right dictionary\n            // version for the handshake — composed per connection from the advertised tags when multi-channel.\n            dictionaryVersion:\n              resolveChannel != null\n                ? (hello) => resolveChannel(hello.channels)?.dictionaryVersion ?? null\n                : channel.dictionaryVersion,\n            securityLevel,\n          }\n        : undefined;\n\n    // Compose the upgrade across the duplex carriers that can be reached via an HTTP upgrade (typically just\n    // one WebSocket carrier; a WebRTC carrier is signalled out of band and has no `upgrade`). The first\n    // carrier whose `isUpgrade` matches handles the request.\n    const defaultIsUpgrade = (request: Request) => request.headers.get(\"Upgrade\") === \"websocket\";\n    const upgraders: {\n      isUpgrade: (request: Request, url: URL) => boolean;\n      upgrade: (request: Request, url: URL) => Response | Promise<Response>;\n    }[] = [];\n    for (const carrier of duplexCarriers) {\n      if (carrier.upgrade == null) continue;\n      upgraders.push({\n        isUpgrade: carrier.isUpgrade ?? defaultIsUpgrade,\n        upgrade: carrier.upgrade,\n      });\n    }\n\n    const activeFetch = createActionFetchHandler(runtime, {\n      cors: exchangeCarrier?.cors,\n      onWebSocketUpgrade:\n        upgraders.length === 0\n          ? undefined\n          : (request, url) =>\n              (upgraders.find((u) => u.isUpgrade(request, url)) ?? upgraders[0]).upgrade(\n                request,\n                url,\n              ),\n      isWebSocketUpgrade:\n        upgraders.length === 0\n          ? undefined\n          : (request, url) => upgraders.some((u) => u.isUpgrade(request, url)),\n      // A single forwarding route means the path is already matched: any POST that isn't an upgrade is an\n      // action exchange. With no exchange carrier there is no HTTP action endpoint, so POSTs fall through.\n      isActionPath:\n        exchangeCarrier != null ? (exchangeCarrier.isActionPath ?? (() => true)) : () => false,\n      security: exchangeSecurity,\n      useErrorStatus: exchangeCarrier?.useErrorStatus,\n      logger: options.logger,\n      transportLabel: exchangeCarrier?.carrierLabel,\n    });\n\n    const fetch = (request: Request): Promise<Response> =>\n      disposed\n        ? Promise.resolve(\n            new Response(\"serveChannel: server disposed\", {\n              status: 503,\n              headers: { \"cache-control\": \"no-store\" },\n            }),\n          )\n        : activeFetch(request);\n\n    const dispose = (): void => {\n      if (disposed) return;\n      disposed = true;\n      // Close every public transport entry point before detach hooks run: a hook that synchronously\n      // touches its carrier must still observe a terminal server, and rate windows can be released now.\n      for (const carrier of duplexCarriers) carrier._dispose?.();\n      for (const acceptor of acceptors) acceptor.dispose();\n      releaseRuntimeHandlers();\n      if (ownsRuntime) runtime.dispose();\n    };\n\n    return {\n      runtime,\n      acceptors,\n      fetch,\n      receive,\n      drop,\n      dispose,\n      pushToClient,\n      broadcast,\n      connections,\n    };\n  } catch (error) {\n    for (const carrier of (options.carriers ?? []) as readonly TAcceptorCarrier<any>[]) {\n      if (!isExchangeAcceptorCarrier(carrier)) carrier._dispose?.();\n    }\n    if (ownsRuntime) runtime.dispose();\n    throw error;\n  }\n}\n\n/**\n * Serve a **set** of channels over one acceptor / endpoint — the accept-in dual of `connectChannels` and\n * the multi-channel form of {@link serveChannel}. The channels are combined into one (their domains\n * unioned in list order, see {@link combineChannels}) and served over a single set of carriers + one crypto\n * identity; the runtime routes each inbound action to the right handler by its domain, exactly as for a\n * single channel. `handlers` cover every channel's actions; `channelCases` is one merged, connection-aware\n * map typed against the union of all the channels' acceptor domains.\n * ```ts\n * const server = serveChannels([mainChannel, notificationsChannel], {\n *   identity: serverCoordinate, storage,\n *   carriers: [wsAcceptorCarrier(...), httpAcceptorCarrier()],\n *   handlers: [mainHandler, notificationsHandler],\n * });\n * ```\n * Both ends must list the **same channels in the same order** (the `combineChannels` contract), which is\n * what makes `serveChannels` ↔ `connectChannels` exact duals. Passing `connectionState` narrows the return\n * so `server.connections` is non-optional, exactly as with `serveChannel`.\n */\nexport function serveChannels<\n  const CHANNELS extends readonly IActionChannel<any, any>[],\n  TConn,\n  TApp,\n>(\n  channels: CHANNELS,\n  options: TServeChannelOptions<TCombinedAcceptorDomains<CHANNELS>, TConn, TApp> & {\n    connectionState: IServeConnectionStateOptions<TApp>;\n  },\n): IChannelServer<TConn, TApp> & { connections: ConnectionStateStore<TConn, TApp> };\nexport function serveChannels<\n  const CHANNELS extends readonly IActionChannel<any, any>[],\n  TConn = unknown,\n  TApp = unknown,\n>(\n  channels: CHANNELS,\n  options: TServeChannelOptions<TCombinedAcceptorDomains<CHANNELS>, TConn, TApp>,\n): IChannelServer<TConn, TApp>;\n/** @deprecated Pass the channel list first and select the server with `identity` or `runtime` in options. */\nexport function serveChannels<\n  const CHANNELS extends readonly IActionChannel<any, any>[],\n  TConn,\n  TApp,\n>(\n  runtime: ActionRuntime,\n  channels: CHANNELS,\n  options: IServeChannelOptions<TCombinedAcceptorDomains<CHANNELS>, TConn, TApp> & {\n    connectionState: IServeConnectionStateOptions<TApp>;\n  },\n): IChannelServer<TConn, TApp> & { connections: ConnectionStateStore<TConn, TApp> };\nexport function serveChannels<\n  const CHANNELS extends readonly IActionChannel<any, any>[],\n  TConn = unknown,\n  TApp = unknown,\n>(\n  runtime: ActionRuntime,\n  channels: CHANNELS,\n  options: IServeChannelOptions<TCombinedAcceptorDomains<CHANNELS>, TConn, TApp>,\n): IChannelServer<TConn, TApp>;\nexport function serveChannels(\n  runtimeOrChannels: ActionRuntime | readonly IActionChannel<any, any>[],\n  channelsOrOptions:\n    | readonly IActionChannel<any, any>[]\n    | TServeChannelOptions<readonly ActionDomain<any>[], any, any>,\n  legacyOptions?: IServeChannelOptions<readonly ActionDomain<any>[], any, any>,\n): IChannelServer<any, any> {\n  const legacy = runtimeOrChannels instanceof ActionRuntime;\n  const channels = (legacy ? channelsOrOptions : runtimeOrChannels) as readonly IActionChannel<\n    any,\n    any\n  >[];\n  const options = (legacy ? legacyOptions : channelsOrOptions) as any;\n  const combined: IActionChannel<readonly ActionDomain<any>[], readonly ActionDomain<any>[]> =\n    combineChannels(channels as readonly [IActionChannel<any, any>, ...IActionChannel<any, any>[]]);\n  // Pass the individual channels as the registry so a client connecting any *subset* (advertised as\n  // `hello.channels` tags) gets the matching composed codec + dictionary version.\n  return legacy\n    ? serveChannel(runtimeOrChannels, combined, { ...options, channels })\n    : serveChannel(combined, { ...options, channels });\n}\n","import { err } from \"@nice-code/error\";\nimport { err_nice_transport } from \"../../../err_nice_transport\";\n\nexport enum EErrId_NiceTransport_WebSocket {\n  ws_disconnected = \"ws_disconnected\",\n  ws_create_failed = \"ws_create_failed\",\n  ws_error = \"ws_error\",\n}\n\nexport const err_nice_transport_ws = err_nice_transport.createChildDomain({\n  domain: \"err_nice_transport_ws\",\n  schema: {\n    [EErrId_NiceTransport_WebSocket.ws_disconnected]: err<Record<string, never>>({\n      message: () => `WebSocket transport disconnected.`,\n    }),\n    [EErrId_NiceTransport_WebSocket.ws_create_failed]: err<{\n      originalError?: Error;\n    }>({\n      message: ({ originalError }) =>\n        `Failed to create WebSocket transport.${originalError ? ` Original error: ${originalError.message}` : \"\"}`,\n    }),\n    [EErrId_NiceTransport_WebSocket.ws_error]: err<{\n      originalError?: Error;\n    }>({\n      message: ({ originalError }) =>\n        `WebSocket transport error.${originalError ? ` Original error: ${originalError.message}` : \"\"}`,\n    }),\n  },\n});\n","import { type IWsCarrierRequest, wsCarrier as wireWsCarrier } from \"@nice-code/wire\";\nimport { EErrId_NiceAction, err_nice_action } from \"../../../../../errors/err_nice_action\";\nimport type { ITransportRouteInfo, TTransportRouteParams } from \"../../../Transport.types\";\nimport type { IDuplexCarrierSource } from \"../../Carrier.types\";\n\n/** The WebSocket an action's socket is opened against — wire's request shape, re-exported. */\nexport type { IWsCarrierRequest } from \"@nice-code/wire\";\n\nexport interface IWsCarrierOptions {\n  /** Run this carrier plainly. Defaults to secure. */\n  secure?: boolean;\n  /** Override the reuse key (defaults to `[url]`, so one socket is shared per endpoint). */\n  getCacheKey?: (input: TTransportRouteParams) => string[];\n  /** @deprecated Use `getCacheKey`. */\n  getTransportCacheKey?: (input: TTransportRouteParams) => string[];\n  /** Override the devtools route info for a specific action. */\n  getRouteInfo?: (input: TTransportRouteParams) => ITransportRouteInfo;\n  /** Skip this carrier for a dispatch when the predicate returns false. */\n  available?: (input: TTransportRouteParams) => boolean;\n  /** Override the carrier label shown in devtools. */\n  label?: string;\n  /**\n   * Construct the socket for a dial — the **testability seam**: inject a\n   * controllable socket to simulate outage/latency/drops without touching globals. Gates every\n   * dial, keep-alive redials included. Passed straight through to wire's `wsCarrier`.\n   */\n  createWebSocket?: (url: string) => WebSocket;\n}\n\n/**\n * A WebSocket {@link IDuplexCarrierSource}: the action instantiation of wire's `wsCarrier`\n * — the dial context is the per-action routing params,\n * so `createRequest` still derives the socket URL per action exactly as before. Pass it as a\n * `carrier` to `connectChannel`.\n *\n * `createRequest` may return `null` for \"no valid endpoint right now\" —\n * the keep-alive redial then PARKS instead of dialing garbage, so a dynamic-endpoint teardown\n * (`_activeMatchId = undefined`) needs no careful ordering against `releaseLink()`.\n */\nexport function wsCarrier(\n  request: string | ((input: TTransportRouteParams) => IWsCarrierRequest | string | null),\n  options: IWsCarrierOptions = {},\n): IDuplexCarrierSource {\n  if (options.getCacheKey != null && options.getTransportCacheKey != null) {\n    throw err_nice_action.fromId(EErrId_NiceAction.conflicting_connect_options, {\n      detail: \"wsCarrier: pass only `getCacheKey`; `getTransportCacheKey` is deprecated\",\n    });\n  }\n  const getCacheKey = options.getCacheKey ?? options.getTransportCacheKey;\n  const getRouteInfo = options.getRouteInfo;\n  const source = wireWsCarrier<TTransportRouteParams>(\n    typeof request === \"string\" ? request : (params) => request(params.dialContext),\n    {\n      secure: options.secure,\n      getCacheKey: getCacheKey == null ? undefined : (params) => getCacheKey(params.dialContext),\n      getRouteInfo: getRouteInfo == null ? undefined : (params) => getRouteInfo(params.dialContext),\n      createWebSocket: options.createWebSocket,\n    },\n  );\n  return { ...source, available: options.available, label: options.label };\n}\n","import { ETransportShape } from \"../../../Transport.types\";\nimport type { IExchangeAcceptorCarrier } from \"../../AcceptorCarrier.types\";\n\nexport interface IHttpAcceptorCarrierOptions {\n  /**\n   * Whether this endpoint runs the secure exchange protocol (default `true`). Pass `false` for a plain\n   * endpoint — no handshake, token, or encryption — the request/reply dual of a connector's plain HTTP\n   * transport (`{ carrier: httpCarrier(...), secure: false }`), whose plain `{ k: \"act\", w }` envelope it\n   * answers in kind; a raw action wire (hand-posted) is accepted too and answered with the raw result. A\n   * plain endpoint ignores the crypto identity, so it can sit alongside a secure WebSocket on the same\n   * server (e.g. a secure WS preferred, plain HTTP fallback).\n   */\n  secure?: boolean;\n  /** Which requests carry an action exchange envelope on `POST`. Defaults to `serveChannel`'s path match. */\n  isActionPath?: (url: URL) => boolean;\n  /**\n   * CORS headers merged onto every response (a preflight `OPTIONS` is answered `204`). Defaults to the\n   * permissive `*` set; pass `false` to attach no CORS headers at all.\n   */\n  cors?: Record<string, string> | false;\n  /** Plain mode only: use the error's HTTP status for failures (default `true`). Ignored when secure. */\n  useErrorStatus?: boolean;\n  /** Override the devtools carrier-kind label (defaults to `\"http\"`). */\n  carrierLabel?: string;\n}\n\n/**\n * An HTTP {@link IExchangeAcceptorCarrier}: the accept-in dual of {@link httpCarrier}. It serves the\n * secure exchange protocol (handshake → token session → encrypted frames) over web-standard\n * `Request`/`Response`. The crypto identity, runtime coordinate, dictionary version, and accepted security\n * levels are all supplied centrally by `serveChannel`, so this only needs to say which requests carry an\n * action envelope and how to answer CORS.\n */\nexport function httpAcceptorCarrier(\n  options: IHttpAcceptorCarrierOptions = {},\n): IExchangeAcceptorCarrier {\n  return {\n    shape: ETransportShape.exchange,\n    carrierLabel: options.carrierLabel ?? \"http\",\n    secure: options.secure,\n    isActionPath: options.isActionPath,\n    cors: options.cors,\n    useErrorStatus: options.useErrorStatus,\n  };\n}\n","const { getOwnPropertyNames, getOwnPropertySymbols } = Object;\n// eslint-disable-next-line @typescript-eslint/unbound-method\nconst { hasOwnProperty } = Object.prototype;\n/**\n * Combine two comparators into a single comparators.\n */\nfunction combineComparators(comparatorA, comparatorB) {\n    return function isEqual(a, b, state) {\n        return comparatorA(a, b, state) && comparatorB(a, b, state);\n    };\n}\n/**\n * Wrap the provided `areItemsEqual` method to manage the circular state, allowing\n * for circular references to be safely included in the comparison without creating\n * stack overflows.\n */\nfunction createIsCircular(areItemsEqual) {\n    return function isCircular(a, b, state) {\n        if (!a || !b || typeof a !== 'object' || typeof b !== 'object') {\n            return areItemsEqual(a, b, state);\n        }\n        const { cache } = state;\n        const cachedA = cache.get(a);\n        const cachedB = cache.get(b);\n        if (cachedA && cachedB) {\n            return cachedA === b && cachedB === a;\n        }\n        cache.set(a, b);\n        cache.set(b, a);\n        const result = areItemsEqual(a, b, state);\n        cache.delete(a);\n        cache.delete(b);\n        return result;\n    };\n}\n/**\n * Get the properties to strictly examine, which include both own properties that are\n * not enumerable and symbol properties.\n */\nfunction getStrictProperties(object) {\n    return getOwnPropertyNames(object).concat(getOwnPropertySymbols(object));\n}\n/**\n * Whether the object contains the property passed as an own property.\n */\nconst hasOwn = \n// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\nObject.hasOwn || ((object, property) => hasOwnProperty.call(object, property));\n\nconst PREACT_VNODE = '__v';\nconst PREACT_OWNER = '__o';\nconst REACT_OWNER = '_owner';\nconst { getOwnPropertyDescriptor, keys } = Object;\n/**\n * Whether the values passed are equal based on a [SameValue](https://262.ecma-international.org/7.0/#sec-samevalue) basis.\n * Simplified, this maps to if the two values are referentially equal to one another (`a === b`) or both are `NaN`.\n *\n * @note\n * When available in the environment, this is just a re-export of the global\n * [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) method.\n */\nconst sameValueEqual = \n// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\nObject.is\n    || function sameValueEqual(a, b) {\n        return a === b ? a !== 0 || 1 / a === 1 / b : a !== a && b !== b;\n    };\n/**\n * Whether the values passed are equal based on a [SameValue](https://262.ecma-international.org/7.0/#sec-samevaluezero) basis.\n * Simplified, this maps to if the two values are referentially equal to one another (`a === b`), both are `NaN`, or both\n * are either positive or negative zero.\n */\nfunction sameValueZeroEqual(a, b) {\n    return a === b || (a !== a && b !== b);\n}\n/**\n * Whether the values passed are equal based on a\n * [Strict Equality Comparison](https://262.ecma-international.org/7.0/#sec-strict-equality-comparison) basis.\n * Simplified, this maps to if the two values are referentially equal to one another (`a === b`).\n *\n * @note\n * This is mainly available as a convenience function, such as being a default when a function to determine equality between\n * two objects is used.\n */\nfunction strictEqual(a, b) {\n    return a === b;\n}\n/**\n * Whether the array buffers are equal in value.\n */\nfunction areArrayBuffersEqual(a, b) {\n    return a.byteLength === b.byteLength && areTypedArraysEqual(new Uint8Array(a), new Uint8Array(b));\n}\n/**\n * Whether the arrays are equal in value.\n */\nfunction areArraysEqual(a, b, state) {\n    let index = a.length;\n    if (b.length !== index) {\n        return false;\n    }\n    while (index-- > 0) {\n        if (!state.equals(a[index], b[index], index, index, a, b, state)) {\n            return false;\n        }\n    }\n    return true;\n}\n/**\n * Whether the dataviews are equal in value.\n */\nfunction areDataViewsEqual(a, b) {\n    return (a.byteLength === b.byteLength\n        && areTypedArraysEqual(new Uint8Array(a.buffer, a.byteOffset, a.byteLength), new Uint8Array(b.buffer, b.byteOffset, b.byteLength)));\n}\n/**\n * Whether the dates passed are equal in value.\n */\nfunction areDatesEqual(a, b) {\n    return sameValueEqual(a.getTime(), b.getTime());\n}\n/**\n * Whether the errors passed are equal in value.\n */\nfunction areErrorsEqual(a, b) {\n    return a.name === b.name && a.message === b.message && a.cause === b.cause && a.stack === b.stack;\n}\n/**\n * Whether the `Map`s are equal in value.\n */\nfunction areMapsEqual(a, b, state) {\n    const size = a.size;\n    if (size !== b.size) {\n        return false;\n    }\n    if (!size) {\n        return true;\n    }\n    const matchedIndices = new Array(size);\n    const aIterable = a.entries();\n    let aResult;\n    let bResult;\n    let index = 0;\n    // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n    while ((aResult = aIterable.next())) {\n        if (aResult.done) {\n            break;\n        }\n        const bIterable = b.entries();\n        let hasMatch = false;\n        let matchIndex = 0;\n        // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n        while ((bResult = bIterable.next())) {\n            if (bResult.done) {\n                break;\n            }\n            if (matchedIndices[matchIndex]) {\n                matchIndex++;\n                continue;\n            }\n            const aEntry = aResult.value;\n            const bEntry = bResult.value;\n            if (state.equals(aEntry[0], bEntry[0], index, matchIndex, a, b, state)\n                && state.equals(aEntry[1], bEntry[1], aEntry[0], bEntry[0], a, b, state)) {\n                hasMatch = matchedIndices[matchIndex] = true;\n                break;\n            }\n            matchIndex++;\n        }\n        if (!hasMatch) {\n            return false;\n        }\n        index++;\n    }\n    return true;\n}\n/**\n * Whether the objects are equal in value.\n */\nfunction areObjectsEqual(a, b, state) {\n    const properties = keys(a);\n    let index = properties.length;\n    if (keys(b).length !== index) {\n        return false;\n    }\n    // Decrementing `while` showed faster results than either incrementing or\n    // decrementing `for` loop and than an incrementing `while` loop. Declarative\n    // methods like `some` / `every` were not used to avoid incurring the garbage\n    // cost of anonymous callbacks.\n    while (index-- > 0) {\n        if (!isPropertyEqual(a, b, state, properties[index])) {\n            return false;\n        }\n    }\n    return true;\n}\n/**\n * Whether the objects are equal in value with strict property checking.\n */\nfunction areObjectsEqualStrict(a, b, state) {\n    const properties = getStrictProperties(a);\n    let index = properties.length;\n    if (getStrictProperties(b).length !== index) {\n        return false;\n    }\n    let property;\n    let descriptorA;\n    let descriptorB;\n    // Decrementing `while` showed faster results than either incrementing or\n    // decrementing `for` loop and than an incrementing `while` loop. Declarative\n    // methods like `some` / `every` were not used to avoid incurring the garbage\n    // cost of anonymous callbacks.\n    while (index-- > 0) {\n        property = properties[index];\n        if (!isPropertyEqual(a, b, state, property)) {\n            return false;\n        }\n        descriptorA = getOwnPropertyDescriptor(a, property);\n        descriptorB = getOwnPropertyDescriptor(b, property);\n        if ((descriptorA || descriptorB)\n            && (!descriptorA\n                || !descriptorB\n                || descriptorA.configurable !== descriptorB.configurable\n                || descriptorA.enumerable !== descriptorB.enumerable\n                || descriptorA.writable !== descriptorB.writable)) {\n            return false;\n        }\n    }\n    return true;\n}\n/**\n * Whether the primitive wrappers passed are equal in value.\n */\nfunction arePrimitiveWrappersEqual(a, b) {\n    return sameValueEqual(a.valueOf(), b.valueOf());\n}\n/**\n * Whether the regexps passed are equal in value.\n */\nfunction areRegExpsEqual(a, b) {\n    return a.source === b.source && a.flags === b.flags;\n}\n/**\n * Whether the `Set`s are equal in value.\n */\nfunction areSetsEqual(a, b, state) {\n    const size = a.size;\n    if (size !== b.size) {\n        return false;\n    }\n    if (!size) {\n        return true;\n    }\n    const matchedIndices = new Array(size);\n    const aIterable = a.values();\n    let aResult;\n    let bResult;\n    // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n    while ((aResult = aIterable.next())) {\n        if (aResult.done) {\n            break;\n        }\n        const bIterable = b.values();\n        let hasMatch = false;\n        let matchIndex = 0;\n        // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n        while ((bResult = bIterable.next())) {\n            if (bResult.done) {\n                break;\n            }\n            if (!matchedIndices[matchIndex]\n                && state.equals(aResult.value, bResult.value, aResult.value, bResult.value, a, b, state)) {\n                hasMatch = matchedIndices[matchIndex] = true;\n                break;\n            }\n            matchIndex++;\n        }\n        if (!hasMatch) {\n            return false;\n        }\n    }\n    return true;\n}\n/**\n * Whether the TypedArray instances are equal in value.\n */\nfunction areTypedArraysEqual(a, b) {\n    let index = a.byteLength;\n    if (b.byteLength !== index || a.byteOffset !== b.byteOffset) {\n        return false;\n    }\n    while (index-- > 0) {\n        if (a[index] !== b[index]) {\n            return false;\n        }\n    }\n    return true;\n}\n/**\n * Whether the URL instances are equal in value.\n */\nfunction areUrlsEqual(a, b) {\n    return (a.hostname === b.hostname\n        && a.pathname === b.pathname\n        && a.protocol === b.protocol\n        && a.port === b.port\n        && a.hash === b.hash\n        && a.username === b.username\n        && a.password === b.password);\n}\nfunction isPropertyEqual(a, b, state, property) {\n    if ((property === REACT_OWNER || property === PREACT_OWNER || property === PREACT_VNODE)\n        && (a.$$typeof || b.$$typeof)) {\n        return true;\n    }\n    return hasOwn(b, property) && state.equals(a[property], b[property], property, property, a, b, state);\n}\n\n// eslint-disable-next-line @typescript-eslint/unbound-method\nconst toString = Object.prototype.toString;\n/**\n * Create a comparator method based on the type-specific equality comparators passed.\n */\nfunction createEqualityComparator(config) {\n    const supportedComparatorMap = createSupportedComparatorMap(config);\n    const { areArraysEqual, areDatesEqual, areFunctionsEqual, areMapsEqual, areNumbersEqual, areObjectsEqual, areRegExpsEqual, areSetsEqual, getUnsupportedCustomComparator, } = config;\n    /**\n     * compare the value of the two objects and return true if they are equivalent in values\n     */\n    return function comparator(a, b, state) {\n        // If the items are strictly equal, no need to do a value comparison.\n        if (a === b) {\n            return true;\n        }\n        // If either of the items are nullish and fail the strictly equal check\n        // above, then they must be unequal.\n        if (a == null || b == null) {\n            return false;\n        }\n        const type = typeof a;\n        if (type !== typeof b) {\n            return false;\n        }\n        if (type !== 'object') {\n            if (type === 'number' || type === 'bigint') {\n                return areNumbersEqual(a, b, state);\n            }\n            if (type === 'function') {\n                return areFunctionsEqual(a, b, state);\n            }\n            // If a primitive value that is not strictly equal, it must be unequal.\n            return false;\n        }\n        const constructor = a.constructor;\n        // Checks are listed in order of commonality of use-case:\n        //   1. Common complex object types (plain object, array)\n        //   2. Common data values (date, regexp)\n        //   3. Less-common complex object types (map, set)\n        //   4. Less-common data values (promise, primitive wrappers)\n        // Inherently this is both subjective and assumptive, however\n        // when reviewing comparable libraries in the wild this order\n        // appears to be generally consistent.\n        // Constructors should match, otherwise there is potential for false positives\n        // between class and subclass or custom object and POJO.\n        if (constructor !== b.constructor) {\n            return false;\n        }\n        // Try to fast-path equality checks for other complex object types in the\n        // same realm to avoid capturing the string tag. Strict equality is used\n        // instead of `instanceof` because it is more performant for the common\n        // use-case. If someone is creating a subclass from a native class, it will be\n        // handled with the string tag comparison.\n        if (constructor === Object) {\n            return areObjectsEqual(a, b, state);\n        }\n        if (constructor === Array) {\n            return areArraysEqual(a, b, state);\n        }\n        if (constructor === Date) {\n            return areDatesEqual(a, b, state);\n        }\n        if (constructor === RegExp) {\n            return areRegExpsEqual(a, b, state);\n        }\n        if (constructor === Map) {\n            return areMapsEqual(a, b, state);\n        }\n        if (constructor === Set) {\n            return areSetsEqual(a, b, state);\n        }\n        if (constructor === Promise) {\n            // Avoid tag checks for promise values, since we know if they are not referentially equal\n            // then they are not equal.\n            return false;\n        }\n        // `isArray()` works on subclasses and is cross-realm, so we can avoid capturing\n        // the string tag or doing an `instanceof` in edge cases.\n        if (Array.isArray(a)) {\n            return areArraysEqual(a, b, state);\n        }\n        // Since this is a custom object, capture the string tag to determining its type.\n        // This is reasonably performant in modern environments like v8 and SpiderMonkey.\n        const tag = toString.call(a);\n        const supportedComparator = supportedComparatorMap[tag];\n        if (supportedComparator) {\n            return supportedComparator(a, b, state);\n        }\n        const unsupportedCustomComparator = getUnsupportedCustomComparator && getUnsupportedCustomComparator(a, b, state, tag);\n        if (unsupportedCustomComparator) {\n            return unsupportedCustomComparator(a, b, state);\n        }\n        // If not matching any tags that require a specific type of comparison, then we hard-code false because\n        // the only thing remaining is strict equality, which has already been compared. This is for a few reasons:\n        //   - Certain types that cannot be introspected (e.g., `WeakMap`). For these types, this is the only\n        //     comparison that can be made.\n        //   - For types that can be introspected but do not have an objective definition of what\n        //     equality is (`Error`, etc.), the subjective decision is to be conservative and strictly compare.\n        // In all cases, these decisions should be reevaluated based on changes to the language and\n        // common development practices.\n        return false;\n    };\n}\n/**\n * Create the configuration object used for building comparators.\n */\nfunction createEqualityComparatorConfig({ circular, createCustomConfig, strict, }) {\n    let config = {\n        areArrayBuffersEqual,\n        areArraysEqual: strict ? areObjectsEqualStrict : areArraysEqual,\n        areDataViewsEqual,\n        areDatesEqual: areDatesEqual,\n        areErrorsEqual: areErrorsEqual,\n        areFunctionsEqual: strictEqual,\n        areMapsEqual: strict ? combineComparators(areMapsEqual, areObjectsEqualStrict) : areMapsEqual,\n        areNumbersEqual: sameValueEqual,\n        areObjectsEqual: strict ? areObjectsEqualStrict : areObjectsEqual,\n        arePrimitiveWrappersEqual: arePrimitiveWrappersEqual,\n        areRegExpsEqual: areRegExpsEqual,\n        areSetsEqual: strict ? combineComparators(areSetsEqual, areObjectsEqualStrict) : areSetsEqual,\n        areTypedArraysEqual: strict\n            ? combineComparators(areTypedArraysEqual, areObjectsEqualStrict)\n            : areTypedArraysEqual,\n        areUrlsEqual: areUrlsEqual,\n        getUnsupportedCustomComparator: undefined,\n    };\n    if (createCustomConfig) {\n        config = Object.assign({}, config, createCustomConfig(config));\n    }\n    if (circular) {\n        const areArraysEqual = createIsCircular(config.areArraysEqual);\n        const areMapsEqual = createIsCircular(config.areMapsEqual);\n        const areObjectsEqual = createIsCircular(config.areObjectsEqual);\n        const areSetsEqual = createIsCircular(config.areSetsEqual);\n        config = Object.assign({}, config, {\n            areArraysEqual,\n            areMapsEqual,\n            areObjectsEqual,\n            areSetsEqual,\n        });\n    }\n    return config;\n}\n/**\n * Default equality comparator pass-through, used as the standard `isEqual` creator for\n * use inside the built comparator.\n */\nfunction createInternalEqualityComparator(compare) {\n    return function (a, b, _indexOrKeyA, _indexOrKeyB, _parentA, _parentB, state) {\n        return compare(a, b, state);\n    };\n}\n/**\n * Create the `isEqual` function used by the consuming application.\n */\nfunction createIsEqual({ circular, comparator, createState, equals, strict }) {\n    if (createState) {\n        return function isEqual(a, b) {\n            const { cache = circular ? new WeakMap() : undefined, meta } = createState();\n            return comparator(a, b, {\n                cache,\n                equals,\n                meta,\n                strict,\n            });\n        };\n    }\n    if (circular) {\n        return function isEqual(a, b) {\n            return comparator(a, b, {\n                cache: new WeakMap(),\n                equals,\n                meta: undefined,\n                strict,\n            });\n        };\n    }\n    const state = {\n        cache: undefined,\n        equals,\n        meta: undefined,\n        strict,\n    };\n    return function isEqual(a, b) {\n        return comparator(a, b, state);\n    };\n}\n/**\n * Create a map of `toString()` values to their respective handlers for `tag`-based lookups.\n */\nfunction createSupportedComparatorMap({ areArrayBuffersEqual, areArraysEqual, areDataViewsEqual, areDatesEqual, areErrorsEqual, areFunctionsEqual, areMapsEqual, areNumbersEqual, areObjectsEqual, arePrimitiveWrappersEqual, areRegExpsEqual, areSetsEqual, areTypedArraysEqual, areUrlsEqual, }) {\n    return {\n        '[object Arguments]': areObjectsEqual,\n        '[object Array]': areArraysEqual,\n        '[object ArrayBuffer]': areArrayBuffersEqual,\n        '[object AsyncGeneratorFunction]': areFunctionsEqual,\n        '[object BigInt]': areNumbersEqual,\n        '[object BigInt64Array]': areTypedArraysEqual,\n        '[object BigUint64Array]': areTypedArraysEqual,\n        '[object Boolean]': arePrimitiveWrappersEqual,\n        '[object DataView]': areDataViewsEqual,\n        '[object Date]': areDatesEqual,\n        // If an error tag, it should be tested explicitly. Like RegExp, the properties are not\n        // enumerable, and therefore will give false positives if tested like a standard object.\n        '[object Error]': areErrorsEqual,\n        '[object Float16Array]': areTypedArraysEqual,\n        '[object Float32Array]': areTypedArraysEqual,\n        '[object Float64Array]': areTypedArraysEqual,\n        '[object Function]': areFunctionsEqual,\n        '[object GeneratorFunction]': areFunctionsEqual,\n        '[object Int8Array]': areTypedArraysEqual,\n        '[object Int16Array]': areTypedArraysEqual,\n        '[object Int32Array]': areTypedArraysEqual,\n        '[object Map]': areMapsEqual,\n        '[object Number]': arePrimitiveWrappersEqual,\n        '[object Object]': (a, b, state) => \n        // The exception for value comparison is custom `Promise`-like class instances. These should\n        // be treated the same as standard `Promise` objects, which means strict equality, and if\n        // it reaches this point then that strict equality comparison has already failed.\n        typeof a.then !== 'function' && typeof b.then !== 'function' && areObjectsEqual(a, b, state),\n        // For RegExp, the properties are not enumerable, and therefore will give false positives if\n        // tested like a standard object.\n        '[object RegExp]': areRegExpsEqual,\n        '[object Set]': areSetsEqual,\n        '[object String]': arePrimitiveWrappersEqual,\n        '[object URL]': areUrlsEqual,\n        '[object Uint8Array]': areTypedArraysEqual,\n        '[object Uint8ClampedArray]': areTypedArraysEqual,\n        '[object Uint16Array]': areTypedArraysEqual,\n        '[object Uint32Array]': areTypedArraysEqual,\n    };\n}\n\n/**\n * Whether the items passed are deeply-equal in value.\n */\nconst deepEqual = createCustomEqual();\n/**\n * Whether the items passed are deeply-equal in value based on strict comparison.\n */\nconst strictDeepEqual = createCustomEqual({ strict: true });\n/**\n * Whether the items passed are deeply-equal in value, including circular references.\n */\nconst circularDeepEqual = createCustomEqual({ circular: true });\n/**\n * Whether the items passed are deeply-equal in value, including circular references,\n * based on strict comparison.\n */\nconst strictCircularDeepEqual = createCustomEqual({\n    circular: true,\n    strict: true,\n});\n/**\n * Whether the items passed are shallowly-equal in value.\n */\nconst shallowEqual = createCustomEqual({\n    createInternalComparator: () => sameValueEqual,\n});\n/**\n * Whether the items passed are shallowly-equal in value based on strict comparison\n */\nconst strictShallowEqual = createCustomEqual({\n    strict: true,\n    createInternalComparator: () => sameValueEqual,\n});\n/**\n * Whether the items passed are shallowly-equal in value, including circular references.\n */\nconst circularShallowEqual = createCustomEqual({\n    circular: true,\n    createInternalComparator: () => sameValueEqual,\n});\n/**\n * Whether the items passed are shallowly-equal in value, including circular references,\n * based on strict comparison.\n */\nconst strictCircularShallowEqual = createCustomEqual({\n    circular: true,\n    createInternalComparator: () => sameValueEqual,\n    strict: true,\n});\n/**\n * Create a custom equality comparison method.\n *\n * This can be done to create very targeted comparisons in extreme hot-path scenarios\n * where the standard methods are not performant enough, but can also be used to provide\n * support for legacy environments that do not support expected features like\n * `RegExp.prototype.flags` out of the box.\n */\nfunction createCustomEqual(options = {}) {\n    const { circular = false, createInternalComparator: createCustomInternalComparator, createState, strict = false, } = options;\n    const config = createEqualityComparatorConfig(options);\n    const comparator = createEqualityComparator(config);\n    const equals = createCustomInternalComparator\n        ? createCustomInternalComparator(comparator)\n        : createInternalEqualityComparator(comparator);\n    return createIsEqual({ circular, comparator, createState, equals, strict });\n}\n\nexport { circularDeepEqual, circularShallowEqual, createCustomEqual, deepEqual, sameValueEqual, sameValueZeroEqual, shallowEqual, strictCircularDeepEqual, strictCircularShallowEqual, strictDeepEqual, strictEqual, strictShallowEqual };\n","// src/utils/env.ts\nvar NOTHING = Symbol.for(\"immer-nothing\");\nvar DRAFTABLE = Symbol.for(\"immer-draftable\");\nvar DRAFT_STATE = Symbol.for(\"immer-state\");\n\n// src/utils/errors.ts\nvar errors = process.env.NODE_ENV !== \"production\" ? [\n  // All error codes, starting by 0:\n  function(plugin) {\n    return `The plugin for '${plugin}' has not been loaded into Immer. To enable the plugin, import and call \\`enable${plugin}()\\` when initializing your application.`;\n  },\n  function(thing) {\n    return `produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${thing}'`;\n  },\n  \"This object has been frozen and should not be mutated\",\n  function(data) {\n    return \"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? \" + data;\n  },\n  \"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.\",\n  \"Immer forbids circular references\",\n  \"The first or second argument to `produce` must be a function\",\n  \"The third argument to `produce` must be a function or undefined\",\n  \"First argument to `createDraft` must be a plain object, an array, or an immerable object\",\n  \"First argument to `finishDraft` must be a draft returned by `createDraft`\",\n  function(thing) {\n    return `'current' expects a draft, got: ${thing}`;\n  },\n  \"Object.defineProperty() cannot be used on an Immer draft\",\n  \"Object.setPrototypeOf() cannot be used on an Immer draft\",\n  \"Immer only supports deleting array indices\",\n  \"Immer only supports setting array indices and the 'length' property\",\n  function(thing) {\n    return `'original' expects a draft, got: ${thing}`;\n  }\n  // Note: if more errors are added, the errorOffset in Patches.ts should be increased\n  // See Patches.ts for additional errors\n] : [];\nfunction die(error, ...args) {\n  if (process.env.NODE_ENV !== \"production\") {\n    const e = errors[error];\n    const msg = isFunction(e) ? e.apply(null, args) : e;\n    throw new Error(`[Immer] ${msg}`);\n  }\n  throw new Error(\n    `[Immer] minified error nr: ${error}. Full error at: https://bit.ly/3cXEKWf`\n  );\n}\n\n// src/utils/common.ts\nvar O = Object;\nvar getPrototypeOf = O.getPrototypeOf;\nvar CONSTRUCTOR = \"constructor\";\nvar PROTOTYPE = \"prototype\";\nvar CONFIGURABLE = \"configurable\";\nvar ENUMERABLE = \"enumerable\";\nvar WRITABLE = \"writable\";\nvar VALUE = \"value\";\nvar isDraft = (value) => !!value && !!value[DRAFT_STATE];\nfunction isDraftable(value) {\n  if (!value)\n    return false;\n  return isPlainObject(value) || isArray(value) || !!value[DRAFTABLE] || !!value[CONSTRUCTOR]?.[DRAFTABLE] || isMap(value) || isSet(value);\n}\nvar objectCtorString = O[PROTOTYPE][CONSTRUCTOR].toString();\nvar cachedCtorStrings = /* @__PURE__ */ new WeakMap();\nfunction isPlainObject(value) {\n  if (!value || !isObjectish(value))\n    return false;\n  const proto = getPrototypeOf(value);\n  if (proto === null || proto === O[PROTOTYPE])\n    return true;\n  const Ctor = O.hasOwnProperty.call(proto, CONSTRUCTOR) && proto[CONSTRUCTOR];\n  if (Ctor === Object)\n    return true;\n  if (!isFunction(Ctor))\n    return false;\n  let ctorString = cachedCtorStrings.get(Ctor);\n  if (ctorString === void 0) {\n    ctorString = Function.toString.call(Ctor);\n    cachedCtorStrings.set(Ctor, ctorString);\n  }\n  return ctorString === objectCtorString;\n}\nfunction original(value) {\n  if (!isDraft(value))\n    die(15, value);\n  return value[DRAFT_STATE].base_;\n}\nfunction each(obj, iter, strict = true) {\n  if (getArchtype(obj) === 0 /* Object */) {\n    const keys = strict ? Reflect.ownKeys(obj) : O.keys(obj);\n    keys.forEach((key) => {\n      iter(key, obj[key], obj);\n    });\n  } else {\n    obj.forEach((entry, index) => iter(index, entry, obj));\n  }\n}\nfunction getArchtype(thing) {\n  const state = thing[DRAFT_STATE];\n  return state ? state.type_ : isArray(thing) ? 1 /* Array */ : isMap(thing) ? 2 /* Map */ : isSet(thing) ? 3 /* Set */ : 0 /* Object */;\n}\nvar has = (thing, prop, type = getArchtype(thing)) => type === 2 /* Map */ ? thing.has(prop) : O[PROTOTYPE].hasOwnProperty.call(thing, prop);\nvar get = (thing, prop, type = getArchtype(thing)) => (\n  // @ts-ignore\n  type === 2 /* Map */ ? thing.get(prop) : thing[prop]\n);\nvar set = (thing, propOrOldValue, value, type = getArchtype(thing)) => {\n  if (type === 2 /* Map */)\n    thing.set(propOrOldValue, value);\n  else if (type === 3 /* Set */) {\n    thing.add(value);\n  } else\n    thing[propOrOldValue] = value;\n};\nfunction is(x, y) {\n  if (x === y) {\n    return x !== 0 || 1 / x === 1 / y;\n  } else {\n    return x !== x && y !== y;\n  }\n}\nvar isArray = Array.isArray;\nvar isMap = (target) => target instanceof Map;\nvar isSet = (target) => target instanceof Set;\nvar isObjectish = (target) => typeof target === \"object\";\nvar isFunction = (target) => typeof target === \"function\";\nvar isBoolean = (target) => typeof target === \"boolean\";\nfunction isArrayIndex(value) {\n  const n = +value;\n  return Number.isInteger(n) && String(n) === value;\n}\nvar getProxyDraft = (value) => {\n  if (!isObjectish(value))\n    return null;\n  return value?.[DRAFT_STATE];\n};\nvar latest = (state) => state.copy_ || state.base_;\nvar getValue = (value) => {\n  const proxyDraft = getProxyDraft(value);\n  return proxyDraft ? proxyDraft.copy_ ?? proxyDraft.base_ : value;\n};\nvar getFinalValue = (state) => state.modified_ ? state.copy_ : state.base_;\nfunction shallowCopy(base, strict) {\n  if (isMap(base)) {\n    return new Map(base);\n  }\n  if (isSet(base)) {\n    return new Set(base);\n  }\n  if (isArray(base))\n    return Array[PROTOTYPE].slice.call(base);\n  const isPlain = isPlainObject(base);\n  if (strict === true || strict === \"class_only\" && !isPlain) {\n    const descriptors = O.getOwnPropertyDescriptors(base);\n    delete descriptors[DRAFT_STATE];\n    let keys = Reflect.ownKeys(descriptors);\n    for (let i = 0; i < keys.length; i++) {\n      const key = keys[i];\n      const desc = descriptors[key];\n      if (desc[WRITABLE] === false) {\n        desc[WRITABLE] = true;\n        desc[CONFIGURABLE] = true;\n      }\n      if (desc.get || desc.set)\n        descriptors[key] = {\n          [CONFIGURABLE]: true,\n          [WRITABLE]: true,\n          // could live with !!desc.set as well here...\n          [ENUMERABLE]: desc[ENUMERABLE],\n          [VALUE]: base[key]\n        };\n    }\n    return O.create(getPrototypeOf(base), descriptors);\n  } else {\n    const proto = getPrototypeOf(base);\n    if (proto !== null && isPlain) {\n      return { ...base };\n    }\n    const obj = O.create(proto);\n    return O.assign(obj, base);\n  }\n}\nfunction freeze(obj, deep = false) {\n  if (isFrozen(obj) || isDraft(obj) || !isDraftable(obj))\n    return obj;\n  if (getArchtype(obj) > 1) {\n    O.defineProperties(obj, {\n      set: dontMutateMethodOverride,\n      add: dontMutateMethodOverride,\n      clear: dontMutateMethodOverride,\n      delete: dontMutateMethodOverride\n    });\n  }\n  O.freeze(obj);\n  if (deep)\n    each(\n      obj,\n      (_key, value) => {\n        freeze(value, true);\n      },\n      false\n    );\n  return obj;\n}\nfunction dontMutateFrozenCollections() {\n  die(2);\n}\nvar dontMutateMethodOverride = {\n  [VALUE]: dontMutateFrozenCollections\n};\nfunction isFrozen(obj) {\n  if (obj === null || !isObjectish(obj))\n    return true;\n  return O.isFrozen(obj);\n}\n\n// src/utils/plugins.ts\nvar PluginMapSet = \"MapSet\";\nvar PluginPatches = \"Patches\";\nvar PluginArrayMethods = \"ArrayMethods\";\nvar plugins = {};\nfunction getPlugin(pluginKey) {\n  const plugin = plugins[pluginKey];\n  if (!plugin) {\n    die(0, pluginKey);\n  }\n  return plugin;\n}\nvar isPluginLoaded = (pluginKey) => !!plugins[pluginKey];\nfunction loadPlugin(pluginKey, implementation) {\n  if (!plugins[pluginKey])\n    plugins[pluginKey] = implementation;\n}\n\n// src/core/scope.ts\nvar currentScope;\nvar getCurrentScope = () => currentScope;\nvar createScope = (parent_, immer_) => ({\n  drafts_: [],\n  parent_,\n  immer_,\n  // Whenever the modified draft contains a draft from another scope, we\n  // need to prevent auto-freezing so the unowned draft can be finalized.\n  canAutoFreeze_: true,\n  unfinalizedDrafts_: 0,\n  handledSet_: /* @__PURE__ */ new Set(),\n  processedForPatches_: /* @__PURE__ */ new Set(),\n  mapSetPlugin_: isPluginLoaded(PluginMapSet) ? getPlugin(PluginMapSet) : void 0,\n  arrayMethodsPlugin_: isPluginLoaded(PluginArrayMethods) ? getPlugin(PluginArrayMethods) : void 0\n});\nfunction usePatchesInScope(scope, patchListener) {\n  if (patchListener) {\n    scope.patchPlugin_ = getPlugin(PluginPatches);\n    scope.patches_ = [];\n    scope.inversePatches_ = [];\n    scope.patchListener_ = patchListener;\n  }\n}\nfunction revokeScope(scope) {\n  leaveScope(scope);\n  scope.drafts_.forEach(revokeDraft);\n  scope.drafts_ = null;\n}\nfunction leaveScope(scope) {\n  if (scope === currentScope) {\n    currentScope = scope.parent_;\n  }\n}\nvar enterScope = (immer2) => currentScope = createScope(currentScope, immer2);\nfunction revokeDraft(draft) {\n  const state = draft[DRAFT_STATE];\n  if (state.type_ === 0 /* Object */ || state.type_ === 1 /* Array */)\n    state.revoke_();\n  else\n    state.revoked_ = true;\n}\n\n// src/core/finalize.ts\nfunction processResult(result, scope) {\n  scope.unfinalizedDrafts_ = scope.drafts_.length;\n  const baseDraft = scope.drafts_[0];\n  const isReplaced = result !== void 0 && result !== baseDraft;\n  if (isReplaced) {\n    if (baseDraft[DRAFT_STATE].modified_) {\n      revokeScope(scope);\n      die(4);\n    }\n    if (isDraftable(result)) {\n      result = finalize(scope, result);\n    }\n    const { patchPlugin_ } = scope;\n    if (patchPlugin_) {\n      patchPlugin_.generateReplacementPatches_(\n        baseDraft[DRAFT_STATE].base_,\n        result,\n        scope\n      );\n    }\n  } else {\n    result = finalize(scope, baseDraft);\n  }\n  maybeFreeze(scope, result, true);\n  revokeScope(scope);\n  if (scope.patches_) {\n    scope.patchListener_(scope.patches_, scope.inversePatches_);\n  }\n  return result !== NOTHING ? result : void 0;\n}\nfunction finalize(rootScope, value) {\n  if (isFrozen(value))\n    return value;\n  const state = value[DRAFT_STATE];\n  if (!state) {\n    const finalValue = handleValue(value, rootScope.handledSet_, rootScope);\n    return finalValue;\n  }\n  if (!isSameScope(state, rootScope)) {\n    return value;\n  }\n  if (!state.modified_) {\n    return state.base_;\n  }\n  if (!state.finalized_) {\n    const { callbacks_ } = state;\n    if (callbacks_) {\n      while (callbacks_.length > 0) {\n        const callback = callbacks_.pop();\n        callback(rootScope);\n      }\n    }\n    generatePatchesAndFinalize(state, rootScope);\n  }\n  return state.copy_;\n}\nfunction maybeFreeze(scope, value, deep = false) {\n  if (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {\n    freeze(value, deep);\n  }\n}\nfunction markStateFinalized(state) {\n  state.finalized_ = true;\n  state.scope_.unfinalizedDrafts_--;\n}\nvar isSameScope = (state, rootScope) => state.scope_ === rootScope;\nvar EMPTY_LOCATIONS_RESULT = [];\nfunction updateDraftInParent(parent, draftValue, finalizedValue, originalKey) {\n  const parentCopy = latest(parent);\n  const parentType = parent.type_;\n  if (originalKey !== void 0) {\n    const currentValue = get(parentCopy, originalKey, parentType);\n    if (currentValue === draftValue) {\n      set(parentCopy, originalKey, finalizedValue, parentType);\n      return;\n    }\n  }\n  if (!parent.draftLocations_) {\n    const draftLocations = parent.draftLocations_ = /* @__PURE__ */ new Map();\n    each(parentCopy, (key, value) => {\n      if (isDraft(value)) {\n        const keys = draftLocations.get(value) || [];\n        keys.push(key);\n        draftLocations.set(value, keys);\n      }\n    });\n  }\n  const locations = parent.draftLocations_.get(draftValue) ?? EMPTY_LOCATIONS_RESULT;\n  for (const location of locations) {\n    set(parentCopy, location, finalizedValue, parentType);\n  }\n}\nfunction registerChildFinalizationCallback(parent, child, key) {\n  parent.callbacks_.push(function childCleanup(rootScope) {\n    const state = child;\n    if (!state || !isSameScope(state, rootScope)) {\n      return;\n    }\n    rootScope.mapSetPlugin_?.fixSetContents(state);\n    const finalizedValue = getFinalValue(state);\n    updateDraftInParent(parent, state.draft_ ?? state, finalizedValue, key);\n    generatePatchesAndFinalize(state, rootScope);\n  });\n}\nfunction generatePatchesAndFinalize(state, rootScope) {\n  const shouldFinalize = state.modified_ && !state.finalized_ && (state.type_ === 3 /* Set */ || state.type_ === 1 /* Array */ && state.allIndicesReassigned_ || (state.assigned_?.size ?? 0) > 0);\n  if (shouldFinalize) {\n    const { patchPlugin_ } = rootScope;\n    if (patchPlugin_) {\n      const basePath = patchPlugin_.getPath(state);\n      if (basePath) {\n        patchPlugin_.generatePatches_(state, basePath, rootScope);\n      }\n    }\n    markStateFinalized(state);\n  }\n}\nfunction handleCrossReference(target, key, value) {\n  const { scope_ } = target;\n  if (isDraft(value)) {\n    const state = value[DRAFT_STATE];\n    if (isSameScope(state, scope_)) {\n      state.callbacks_.push(function crossReferenceCleanup() {\n        prepareCopy(target);\n        const finalizedValue = getFinalValue(state);\n        updateDraftInParent(target, value, finalizedValue, key);\n      });\n    }\n  } else if (isDraftable(value)) {\n    target.callbacks_.push(function nestedDraftCleanup() {\n      const targetCopy = latest(target);\n      if (target.type_ === 3 /* Set */) {\n        if (targetCopy.has(value)) {\n          handleValue(value, scope_.handledSet_, scope_);\n        }\n      } else {\n        if (get(targetCopy, key, target.type_) === value) {\n          if (scope_.drafts_.length > 1 && (target.assigned_.get(key) ?? false) === true && target.copy_) {\n            handleValue(\n              get(target.copy_, key, target.type_),\n              scope_.handledSet_,\n              scope_\n            );\n          }\n        }\n      }\n    });\n  }\n}\nfunction handleValue(target, handledSet, rootScope) {\n  if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {\n    return target;\n  }\n  if (isDraft(target) || handledSet.has(target) || !isDraftable(target) || isFrozen(target)) {\n    return target;\n  }\n  handledSet.add(target);\n  each(target, (key, value) => {\n    if (isDraft(value)) {\n      const state = value[DRAFT_STATE];\n      if (isSameScope(state, rootScope)) {\n        const updatedValue = getFinalValue(state);\n        set(target, key, updatedValue, target.type_);\n        markStateFinalized(state);\n      }\n    } else if (isDraftable(value)) {\n      handleValue(value, handledSet, rootScope);\n    }\n  });\n  return target;\n}\n\n// src/core/proxy.ts\nfunction createProxyProxy(base, parent) {\n  const baseIsArray = isArray(base);\n  const state = {\n    type_: baseIsArray ? 1 /* Array */ : 0 /* Object */,\n    // Track which produce call this is associated with.\n    scope_: parent ? parent.scope_ : getCurrentScope(),\n    // True for both shallow and deep changes.\n    modified_: false,\n    // Used during finalization.\n    finalized_: false,\n    // Track which properties have been assigned (true) or deleted (false).\n    // actually instantiated in `prepareCopy()`\n    assigned_: void 0,\n    // The parent draft state.\n    parent_: parent,\n    // The base state.\n    base_: base,\n    // The base proxy.\n    draft_: null,\n    // set below\n    // The base copy with any updated values.\n    copy_: null,\n    // Called by the `produce` function.\n    revoke_: null,\n    isManual_: false,\n    // `callbacks` actually gets assigned in `createProxy`\n    callbacks_: void 0\n  };\n  let target = state;\n  let traps = objectTraps;\n  if (baseIsArray) {\n    target = [state];\n    traps = arrayTraps;\n  }\n  const { revoke, proxy } = Proxy.revocable(target, traps);\n  state.draft_ = proxy;\n  state.revoke_ = revoke;\n  return [proxy, state];\n}\nvar objectTraps = {\n  get(state, prop) {\n    if (prop === DRAFT_STATE)\n      return state;\n    if (prop === \"constructor\" || prop === \"__proto__\") {\n      const source2 = latest(state);\n      const value2 = source2[prop];\n      return new Proxy(value2 || {}, {\n        get: (target, key) => {\n          if (key === \"__proto__\" || key === \"prototype\") {\n            return Object.freeze(/* @__PURE__ */ Object.create(null));\n          }\n          return Reflect.get(target, key);\n        },\n        set: () => {\n          return true;\n        },\n        apply: (target, thisArg, args) => {\n          return Reflect.apply(target, thisArg, args);\n        }\n      });\n    }\n    let arrayPlugin = state.scope_.arrayMethodsPlugin_;\n    const isArrayWithStringProp = state.type_ === 1 /* Array */ && typeof prop === \"string\";\n    if (isArrayWithStringProp) {\n      if (arrayPlugin?.isArrayOperationMethod(prop)) {\n        return arrayPlugin.createMethodInterceptor(state, prop);\n      }\n    }\n    const source = latest(state);\n    if (!has(source, prop, state.type_)) {\n      return readPropFromProto(state, source, prop);\n    }\n    const value = source[prop];\n    if (state.finalized_ || !isDraftable(value)) {\n      return value;\n    }\n    if (isArrayWithStringProp && state.operationMethod && arrayPlugin?.isMutatingArrayMethod(\n      state.operationMethod\n    ) && isArrayIndex(prop)) {\n      return value;\n    }\n    if (value === peek(state.base_, prop)) {\n      prepareCopy(state);\n      const childKey = state.type_ === 1 /* Array */ ? +prop : prop;\n      const childDraft = createProxy(state.scope_, value, state, childKey);\n      return state.copy_[childKey] = childDraft;\n    }\n    return value;\n  },\n  has(state, prop) {\n    if (prop === \"constructor\" || prop === \"__proto__\" || prop === \"prototype\") {\n      return false;\n    }\n    return prop in latest(state);\n  },\n  ownKeys(state) {\n    return Reflect.ownKeys(latest(state));\n  },\n  set(state, prop, value) {\n    if (prop === \"constructor\" || prop === \"__proto__\" || prop === \"prototype\") {\n      return true;\n    }\n    const desc = getDescriptorFromProto(latest(state), prop);\n    if (desc?.set) {\n      desc.set.call(state.draft_, value);\n      return true;\n    }\n    if (!state.modified_) {\n      const current2 = peek(latest(state), prop);\n      const currentState = current2?.[DRAFT_STATE];\n      if (currentState && currentState.base_ === value) {\n        state.copy_[prop] = value;\n        state.assigned_.set(prop, false);\n        return true;\n      }\n      if (is(value, current2) && (value !== void 0 || has(state.base_, prop, state.type_)))\n        return true;\n      prepareCopy(state);\n      markChanged(state);\n    }\n    if (state.copy_[prop] === value && // special case: handle new props with value 'undefined'\n    (value !== void 0 || has(state.copy_, prop, state.type_)) || // special case: NaN\n    Number.isNaN(value) && Number.isNaN(state.copy_[prop]))\n      return true;\n    state.copy_[prop] = value;\n    state.assigned_.set(prop, true);\n    handleCrossReference(state, prop, value);\n    return true;\n  },\n  deleteProperty(state, prop) {\n    prepareCopy(state);\n    if (peek(state.base_, prop) !== void 0 || prop in state.base_) {\n      state.assigned_.set(prop, false);\n      markChanged(state);\n    } else {\n      state.assigned_.delete(prop);\n    }\n    if (state.copy_) {\n      delete state.copy_[prop];\n    }\n    return true;\n  },\n  // Note: We never coerce `desc.value` into an Immer draft, because we can't make\n  // the same guarantee in ES5 mode.\n  getOwnPropertyDescriptor(state, prop) {\n    const owner = latest(state);\n    const desc = Reflect.getOwnPropertyDescriptor(owner, prop);\n    if (!desc)\n      return desc;\n    return {\n      [WRITABLE]: true,\n      [CONFIGURABLE]: state.type_ !== 1 /* Array */ || prop !== \"length\",\n      [ENUMERABLE]: desc[ENUMERABLE],\n      [VALUE]: owner[prop]\n    };\n  },\n  defineProperty() {\n    die(11);\n  },\n  getPrototypeOf(state) {\n    return getPrototypeOf(state.base_);\n  },\n  setPrototypeOf() {\n    die(12);\n  }\n};\nvar arrayTraps = {};\nfor (let key in objectTraps) {\n  let fn = objectTraps[key];\n  arrayTraps[key] = function() {\n    const args = arguments;\n    args[0] = args[0][0];\n    return fn.apply(this, args);\n  };\n}\narrayTraps.deleteProperty = function(state, prop) {\n  if (process.env.NODE_ENV !== \"production\" && isNaN(parseInt(prop)))\n    die(13);\n  return arrayTraps.set.call(this, state, prop, void 0);\n};\narrayTraps.set = function(state, prop, value) {\n  if (process.env.NODE_ENV !== \"production\" && prop !== \"length\" && isNaN(parseInt(prop)))\n    die(14);\n  return objectTraps.set.call(this, state[0], prop, value, state[0]);\n};\nfunction peek(draft, prop) {\n  const state = draft[DRAFT_STATE];\n  const source = state ? latest(state) : draft;\n  return source[prop];\n}\nfunction readPropFromProto(state, source, prop) {\n  const desc = getDescriptorFromProto(source, prop);\n  return desc ? VALUE in desc ? desc[VALUE] : (\n    // This is a very special case, if the prop is a getter defined by the\n    // prototype, we should invoke it with the draft as context!\n    desc.get?.call(state.draft_)\n  ) : void 0;\n}\nfunction getDescriptorFromProto(source, prop) {\n  if (!(prop in source))\n    return void 0;\n  let proto = getPrototypeOf(source);\n  while (proto) {\n    const desc = Object.getOwnPropertyDescriptor(proto, prop);\n    if (desc)\n      return desc;\n    proto = getPrototypeOf(proto);\n  }\n  return void 0;\n}\nfunction markChanged(state) {\n  if (!state.modified_) {\n    state.modified_ = true;\n    if (state.parent_) {\n      markChanged(state.parent_);\n    }\n  }\n}\nfunction prepareCopy(state) {\n  if (!state.copy_) {\n    state.assigned_ = /* @__PURE__ */ new Map();\n    state.copy_ = shallowCopy(\n      state.base_,\n      state.scope_.immer_.useStrictShallowCopy_\n    );\n  }\n}\n\n// src/core/immerClass.ts\nvar Immer2 = class {\n  constructor(config) {\n    this.autoFreeze_ = true;\n    this.useStrictShallowCopy_ = false;\n    this.useStrictIteration_ = false;\n    /**\n     * The `produce` function takes a value and a \"recipe function\" (whose\n     * return value often depends on the base state). The recipe function is\n     * free to mutate its first argument however it wants. All mutations are\n     * only ever applied to a __copy__ of the base state.\n     *\n     * Pass only a function to create a \"curried producer\" which relieves you\n     * from passing the recipe function every time.\n     *\n     * Only plain objects and arrays are made mutable. All other objects are\n     * considered uncopyable.\n     *\n     * Note: This function is __bound__ to its `Immer` instance.\n     *\n     * @param {any} base - the initial state\n     * @param {Function} recipe - function that receives a proxy of the base state as first argument and which can be freely modified\n     * @param {Function} patchListener - optional function that will be called with all the patches produced here\n     * @returns {any} a new state, or the initial state if nothing was modified\n     */\n    this.produce = (base, recipe, patchListener) => {\n      if (isFunction(base) && !isFunction(recipe)) {\n        const defaultBase = recipe;\n        recipe = base;\n        const self = this;\n        return function curriedProduce(base2 = defaultBase, ...args) {\n          return self.produce(base2, (draft) => recipe.call(this, draft, ...args));\n        };\n      }\n      if (!isFunction(recipe))\n        die(6);\n      if (patchListener !== void 0 && !isFunction(patchListener))\n        die(7);\n      let result;\n      if (isDraftable(base)) {\n        const scope = enterScope(this);\n        const proxy = createProxy(scope, base, void 0);\n        let hasError = true;\n        try {\n          result = recipe(proxy);\n          hasError = false;\n        } finally {\n          if (hasError)\n            revokeScope(scope);\n          else\n            leaveScope(scope);\n        }\n        usePatchesInScope(scope, patchListener);\n        return processResult(result, scope);\n      } else if (!base || !isObjectish(base)) {\n        result = recipe(base);\n        if (result === void 0)\n          result = base;\n        if (result === NOTHING)\n          result = void 0;\n        if (this.autoFreeze_)\n          freeze(result, true);\n        if (patchListener) {\n          const p = [];\n          const ip = [];\n          getPlugin(PluginPatches).generateReplacementPatches_(base, result, {\n            patches_: p,\n            inversePatches_: ip\n          });\n          patchListener(p, ip);\n        }\n        return result;\n      } else\n        die(1, base);\n    };\n    this.produceWithPatches = (base, recipe) => {\n      if (isFunction(base)) {\n        return (state, ...args) => this.produceWithPatches(state, (draft) => base(draft, ...args));\n      }\n      let patches, inversePatches;\n      const result = this.produce(base, recipe, (p, ip) => {\n        patches = p;\n        inversePatches = ip;\n      });\n      return [result, patches, inversePatches];\n    };\n    if (isBoolean(config?.autoFreeze))\n      this.setAutoFreeze(config.autoFreeze);\n    if (isBoolean(config?.useStrictShallowCopy))\n      this.setUseStrictShallowCopy(config.useStrictShallowCopy);\n    if (isBoolean(config?.useStrictIteration))\n      this.setUseStrictIteration(config.useStrictIteration);\n  }\n  createDraft(base) {\n    if (!isDraftable(base))\n      die(8);\n    if (isDraft(base))\n      base = current(base);\n    const scope = enterScope(this);\n    const proxy = createProxy(scope, base, void 0);\n    proxy[DRAFT_STATE].isManual_ = true;\n    leaveScope(scope);\n    return proxy;\n  }\n  finishDraft(draft, patchListener) {\n    const state = draft && draft[DRAFT_STATE];\n    if (!state || !state.isManual_)\n      die(9);\n    const { scope_: scope } = state;\n    usePatchesInScope(scope, patchListener);\n    return processResult(void 0, scope);\n  }\n  /**\n   * Pass true to automatically freeze all copies created by Immer.\n   *\n   * By default, auto-freezing is enabled.\n   */\n  setAutoFreeze(value) {\n    this.autoFreeze_ = value;\n  }\n  /**\n   * Pass true to enable strict shallow copy.\n   *\n   * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.\n   */\n  setUseStrictShallowCopy(value) {\n    this.useStrictShallowCopy_ = value;\n  }\n  /**\n   * Pass false to use faster iteration that skips non-enumerable properties\n   * but still handles symbols for compatibility.\n   *\n   * By default, strict iteration is enabled (includes all own properties).\n   */\n  setUseStrictIteration(value) {\n    this.useStrictIteration_ = value;\n  }\n  shouldUseStrictIteration() {\n    return this.useStrictIteration_;\n  }\n  applyPatches(base, patches) {\n    let i;\n    for (i = patches.length - 1; i >= 0; i--) {\n      const patch = patches[i];\n      if (patch.path.length === 0 && patch.op === \"replace\") {\n        base = patch.value;\n        break;\n      }\n    }\n    if (i > -1) {\n      patches = patches.slice(i + 1);\n    }\n    const applyPatchesImpl = getPlugin(PluginPatches).applyPatches_;\n    if (isDraft(base)) {\n      return applyPatchesImpl(base, patches);\n    }\n    return this.produce(\n      base,\n      (draft) => applyPatchesImpl(draft, patches)\n    );\n  }\n};\nfunction createProxy(rootScope, value, parent, key) {\n  const [draft, state] = isMap(value) ? getPlugin(PluginMapSet).proxyMap_(value, parent) : isSet(value) ? getPlugin(PluginMapSet).proxySet_(value, parent) : createProxyProxy(value, parent);\n  const scope = parent?.scope_ ?? getCurrentScope();\n  scope.drafts_.push(draft);\n  state.callbacks_ = parent?.callbacks_ ?? [];\n  state.key_ = key;\n  if (parent && key !== void 0) {\n    registerChildFinalizationCallback(parent, state, key);\n  } else {\n    state.callbacks_.push(function rootDraftCleanup(rootScope2) {\n      rootScope2.mapSetPlugin_?.fixSetContents(state);\n      const { patchPlugin_ } = rootScope2;\n      if (state.modified_ && patchPlugin_) {\n        patchPlugin_.generatePatches_(state, [], rootScope2);\n      }\n    });\n  }\n  return draft;\n}\n\n// src/core/current.ts\nfunction current(value) {\n  if (!isDraft(value))\n    die(10, value);\n  return currentImpl(value);\n}\nfunction currentImpl(value) {\n  if (!isDraftable(value) || isFrozen(value))\n    return value;\n  const state = value[DRAFT_STATE];\n  let copy;\n  let strict = true;\n  if (state) {\n    if (!state.modified_)\n      return state.base_;\n    state.finalized_ = true;\n    copy = shallowCopy(value, state.scope_.immer_.useStrictShallowCopy_);\n    strict = state.scope_.immer_.shouldUseStrictIteration();\n  } else {\n    copy = shallowCopy(value, true);\n  }\n  each(\n    copy,\n    (key, childValue) => {\n      set(copy, key, currentImpl(childValue));\n    },\n    strict\n  );\n  if (state) {\n    state.finalized_ = false;\n  }\n  return copy;\n}\n\n// src/plugins/patches.ts\nfunction enablePatches() {\n  const errorOffset = 16;\n  if (process.env.NODE_ENV !== \"production\") {\n    errors.push(\n      'Sets cannot have \"replace\" patches.',\n      function(op) {\n        return \"Unsupported patch operation: \" + op;\n      },\n      function(path) {\n        return \"Cannot apply patch, path doesn't resolve: \" + path;\n      },\n      \"Patching reserved attributes like __proto__, prototype and constructor is not allowed\"\n    );\n  }\n  function getPath(state, path = []) {\n    if (state.key_ !== void 0) {\n      const parentCopy = state.parent_.copy_ ?? state.parent_.base_;\n      const proxyDraft = getProxyDraft(get(parentCopy, state.key_));\n      const valueAtKey = get(parentCopy, state.key_);\n      if (valueAtKey === void 0) {\n        return null;\n      }\n      if (valueAtKey !== state.draft_ && valueAtKey !== state.base_ && valueAtKey !== state.copy_) {\n        return null;\n      }\n      if (proxyDraft != null && proxyDraft.base_ !== state.base_) {\n        return null;\n      }\n      const isSet2 = state.parent_.type_ === 3 /* Set */;\n      let key;\n      if (isSet2) {\n        const setParent = state.parent_;\n        key = Array.from(setParent.drafts_.keys()).indexOf(state.key_);\n      } else {\n        key = state.key_;\n      }\n      if (!(isSet2 && parentCopy.size > key || has(parentCopy, key))) {\n        return null;\n      }\n      path.push(key);\n    }\n    if (state.parent_) {\n      return getPath(state.parent_, path);\n    }\n    path.reverse();\n    try {\n      resolvePath(state.copy_, path);\n    } catch (e) {\n      return null;\n    }\n    return path;\n  }\n  function resolvePath(base, path) {\n    let current2 = base;\n    for (let i = 0; i < path.length - 1; i++) {\n      const key = path[i];\n      current2 = get(current2, key);\n      if (!isObjectish(current2) || current2 === null) {\n        throw new Error(`Cannot resolve path at '${path.join(\"/\")}'`);\n      }\n    }\n    return current2;\n  }\n  const REPLACE = \"replace\";\n  const ADD = \"add\";\n  const REMOVE = \"remove\";\n  function generatePatches_(state, basePath, scope) {\n    if (state.scope_.processedForPatches_.has(state)) {\n      return;\n    }\n    state.scope_.processedForPatches_.add(state);\n    const { patches_, inversePatches_ } = scope;\n    switch (state.type_) {\n      case 0 /* Object */:\n      case 2 /* Map */:\n        return generatePatchesFromAssigned(\n          state,\n          basePath,\n          patches_,\n          inversePatches_\n        );\n      case 1 /* Array */:\n        return generateArrayPatches(\n          state,\n          basePath,\n          patches_,\n          inversePatches_\n        );\n      case 3 /* Set */:\n        return generateSetPatches(\n          state,\n          basePath,\n          patches_,\n          inversePatches_\n        );\n    }\n  }\n  function generateArrayPatches(state, basePath, patches, inversePatches) {\n    let { base_, assigned_ } = state;\n    let copy_ = state.copy_;\n    if (copy_.length < base_.length) {\n      ;\n      [base_, copy_] = [copy_, base_];\n      [patches, inversePatches] = [inversePatches, patches];\n    }\n    const allReassigned = state.allIndicesReassigned_ === true;\n    for (let i = 0; i < base_.length; i++) {\n      const copiedItem = copy_[i];\n      const baseItem = base_[i];\n      const isAssigned = allReassigned || assigned_?.get(i.toString());\n      if (isAssigned && copiedItem !== baseItem) {\n        const childState = copiedItem?.[DRAFT_STATE];\n        if (childState && childState.modified_) {\n          continue;\n        }\n        const path = basePath.concat([i]);\n        patches.push({\n          op: REPLACE,\n          path,\n          // Need to maybe clone it, as it can in fact be the original value\n          // due to the base/copy inversion at the start of this function\n          value: clonePatchValueIfNeeded(copiedItem)\n        });\n        inversePatches.push({\n          op: REPLACE,\n          path,\n          value: clonePatchValueIfNeeded(baseItem)\n        });\n      }\n    }\n    for (let i = base_.length; i < copy_.length; i++) {\n      const path = basePath.concat([i]);\n      patches.push({\n        op: ADD,\n        path,\n        // Need to maybe clone it, as it can in fact be the original value\n        // due to the base/copy inversion at the start of this function\n        value: clonePatchValueIfNeeded(copy_[i])\n      });\n    }\n    for (let i = copy_.length - 1; base_.length <= i; --i) {\n      const path = basePath.concat([i]);\n      inversePatches.push({\n        op: REMOVE,\n        path\n      });\n    }\n  }\n  function generatePatchesFromAssigned(state, basePath, patches, inversePatches) {\n    const { base_, copy_, type_ } = state;\n    each(state.assigned_, (key, assignedValue) => {\n      const origValue = get(base_, key, type_);\n      const value = get(copy_, key, type_);\n      const op = !assignedValue ? REMOVE : has(base_, key) ? REPLACE : ADD;\n      if (origValue === value && op === REPLACE)\n        return;\n      const path = basePath.concat(key);\n      patches.push(\n        op === REMOVE ? { op, path } : { op, path, value: clonePatchValueIfNeeded(value) }\n      );\n      inversePatches.push(\n        op === ADD ? { op: REMOVE, path } : op === REMOVE ? { op: ADD, path, value: clonePatchValueIfNeeded(origValue) } : { op: REPLACE, path, value: clonePatchValueIfNeeded(origValue) }\n      );\n    });\n  }\n  function generateSetPatches(state, basePath, patches, inversePatches) {\n    let { base_, copy_ } = state;\n    let i = 0;\n    base_.forEach((value) => {\n      if (!copy_.has(value)) {\n        const path = basePath.concat([i]);\n        patches.push({\n          op: REMOVE,\n          path,\n          value\n        });\n        inversePatches.unshift({\n          op: ADD,\n          path,\n          value\n        });\n      }\n      i++;\n    });\n    i = 0;\n    copy_.forEach((value) => {\n      if (!base_.has(value)) {\n        const path = basePath.concat([i]);\n        patches.push({\n          op: ADD,\n          path,\n          value\n        });\n        inversePatches.unshift({\n          op: REMOVE,\n          path,\n          value\n        });\n      }\n      i++;\n    });\n  }\n  function generateReplacementPatches_(baseValue, replacement, scope) {\n    const { patches_, inversePatches_ } = scope;\n    patches_.push({\n      op: REPLACE,\n      path: [],\n      value: replacement === NOTHING ? void 0 : replacement\n    });\n    inversePatches_.push({\n      op: REPLACE,\n      path: [],\n      value: baseValue\n    });\n  }\n  function applyPatches_(draft, patches) {\n    patches.forEach((patch) => {\n      const { path, op } = patch;\n      let base = draft;\n      for (let i = 0; i < path.length - 1; i++) {\n        const parentType = getArchtype(base);\n        let p = path[i];\n        if (typeof p !== \"string\" && typeof p !== \"number\") {\n          p = \"\" + p;\n        }\n        if ((parentType === 0 /* Object */ || parentType === 1 /* Array */) && (p === \"__proto__\" || p === CONSTRUCTOR))\n          die(errorOffset + 3);\n        if (isFunction(base) && p === PROTOTYPE)\n          die(errorOffset + 3);\n        base = get(base, p);\n        if (!isObjectish(base))\n          die(errorOffset + 2, path.join(\"/\"));\n      }\n      const type = getArchtype(base);\n      const value = deepClonePatchValue(patch.value);\n      const key = path[path.length - 1];\n      switch (op) {\n        case REPLACE:\n          switch (type) {\n            case 2 /* Map */:\n              return base.set(key, value);\n            case 3 /* Set */:\n              die(errorOffset);\n            default:\n              return base[key] = value;\n          }\n        case ADD:\n          switch (type) {\n            case 1 /* Array */:\n              return key === \"-\" ? base.push(value) : base.splice(key, 0, value);\n            case 2 /* Map */:\n              return base.set(key, value);\n            case 3 /* Set */:\n              return base.add(value);\n            default:\n              return base[key] = value;\n          }\n        case REMOVE:\n          switch (type) {\n            case 1 /* Array */:\n              return base.splice(key, 1);\n            case 2 /* Map */:\n              return base.delete(key);\n            case 3 /* Set */:\n              return base.delete(patch.value);\n            default:\n              return delete base[key];\n          }\n        default:\n          die(errorOffset + 1, op);\n      }\n    });\n    return draft;\n  }\n  function deepClonePatchValue(obj) {\n    if (!isDraftable(obj))\n      return obj;\n    if (isArray(obj))\n      return obj.map(deepClonePatchValue);\n    if (isMap(obj))\n      return new Map(\n        Array.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)])\n      );\n    if (isSet(obj))\n      return new Set(Array.from(obj).map(deepClonePatchValue));\n    const cloned = Object.create(getPrototypeOf(obj));\n    for (const key in obj)\n      cloned[key] = deepClonePatchValue(obj[key]);\n    if (has(obj, DRAFTABLE))\n      cloned[DRAFTABLE] = obj[DRAFTABLE];\n    return cloned;\n  }\n  function clonePatchValueIfNeeded(obj) {\n    if (isDraft(obj)) {\n      return deepClonePatchValue(obj);\n    } else\n      return obj;\n  }\n  loadPlugin(PluginPatches, {\n    applyPatches_,\n    generatePatches_,\n    generateReplacementPatches_,\n    getPath\n  });\n}\n\n// src/plugins/mapset.ts\nfunction enableMapSet() {\n  class DraftMap extends Map {\n    constructor(target, parent) {\n      super();\n      this[DRAFT_STATE] = {\n        type_: 2 /* Map */,\n        parent_: parent,\n        scope_: parent ? parent.scope_ : getCurrentScope(),\n        modified_: false,\n        finalized_: false,\n        copy_: void 0,\n        assigned_: void 0,\n        base_: target,\n        draft_: this,\n        isManual_: false,\n        revoked_: false,\n        callbacks_: []\n      };\n    }\n    get size() {\n      return latest(this[DRAFT_STATE]).size;\n    }\n    has(key) {\n      return latest(this[DRAFT_STATE]).has(key);\n    }\n    set(key, value) {\n      const state = this[DRAFT_STATE];\n      assertUnrevoked(state);\n      if (!latest(state).has(key) || latest(state).get(key) !== value) {\n        prepareMapCopy(state);\n        markChanged(state);\n        state.assigned_.set(key, true);\n        state.copy_.set(key, value);\n        state.assigned_.set(key, true);\n        handleCrossReference(state, key, value);\n      }\n      return this;\n    }\n    delete(key) {\n      if (!this.has(key)) {\n        return false;\n      }\n      const state = this[DRAFT_STATE];\n      assertUnrevoked(state);\n      prepareMapCopy(state);\n      markChanged(state);\n      if (state.base_.has(key)) {\n        state.assigned_.set(key, false);\n      } else {\n        state.assigned_.delete(key);\n      }\n      state.copy_.delete(key);\n      return true;\n    }\n    clear() {\n      const state = this[DRAFT_STATE];\n      assertUnrevoked(state);\n      if (latest(state).size) {\n        prepareMapCopy(state);\n        markChanged(state);\n        state.assigned_ = /* @__PURE__ */ new Map();\n        each(state.base_, (key) => {\n          state.assigned_.set(key, false);\n        });\n        state.copy_.clear();\n      }\n    }\n    forEach(cb, thisArg) {\n      const state = this[DRAFT_STATE];\n      latest(state).forEach((_value, key, _map) => {\n        cb.call(thisArg, this.get(key), key, this);\n      });\n    }\n    get(key) {\n      const state = this[DRAFT_STATE];\n      assertUnrevoked(state);\n      const value = latest(state).get(key);\n      if (state.finalized_ || !isDraftable(value)) {\n        return value;\n      }\n      if (value !== state.base_.get(key)) {\n        return value;\n      }\n      const draft = createProxy(state.scope_, value, state, key);\n      prepareMapCopy(state);\n      state.copy_.set(key, draft);\n      return draft;\n    }\n    keys() {\n      return latest(this[DRAFT_STATE]).keys();\n    }\n    values() {\n      const iterator = this.keys();\n      return iteratorFrom({\n        next: () => {\n          const r = iterator.next();\n          if (r.done)\n            return r;\n          const value = this.get(r.value);\n          return {\n            done: false,\n            value\n          };\n        }\n      });\n    }\n    entries() {\n      const iterator = this.keys();\n      return iteratorFrom({\n        next: () => {\n          const r = iterator.next();\n          if (r.done)\n            return r;\n          const value = this.get(r.value);\n          return {\n            done: false,\n            value: [r.value, value]\n          };\n        }\n      });\n    }\n    [(DRAFT_STATE, Symbol.iterator)]() {\n      return this.entries();\n    }\n  }\n  function iteratorFrom(iterable) {\n    if (typeof Iterator !== \"undefined\") {\n      return Iterator.from(iterable);\n    }\n    const iterator = {\n      ...iterable,\n      [Symbol.iterator]: () => iterator\n    };\n    return iterator;\n  }\n  function proxyMap_(target, parent) {\n    const map = new DraftMap(target, parent);\n    return [map, map[DRAFT_STATE]];\n  }\n  function prepareMapCopy(state) {\n    if (!state.copy_) {\n      state.assigned_ = /* @__PURE__ */ new Map();\n      state.copy_ = new Map(state.base_);\n    }\n  }\n  class DraftSet extends Set {\n    constructor(target, parent) {\n      super();\n      this[DRAFT_STATE] = {\n        type_: 3 /* Set */,\n        parent_: parent,\n        scope_: parent ? parent.scope_ : getCurrentScope(),\n        modified_: false,\n        finalized_: false,\n        copy_: void 0,\n        base_: target,\n        draft_: this,\n        drafts_: /* @__PURE__ */ new Map(),\n        revoked_: false,\n        isManual_: false,\n        assigned_: void 0,\n        callbacks_: []\n      };\n    }\n    get size() {\n      return latest(this[DRAFT_STATE]).size;\n    }\n    has(value) {\n      const state = this[DRAFT_STATE];\n      assertUnrevoked(state);\n      if (!state.copy_) {\n        return state.base_.has(value);\n      }\n      if (state.copy_.has(value))\n        return true;\n      if (state.drafts_.has(value) && state.copy_.has(state.drafts_.get(value)))\n        return true;\n      return false;\n    }\n    add(value) {\n      const state = this[DRAFT_STATE];\n      assertUnrevoked(state);\n      if (!this.has(value)) {\n        prepareSetCopy(state);\n        markChanged(state);\n        state.copy_.add(value);\n        handleCrossReference(state, value, value);\n      }\n      return this;\n    }\n    delete(value) {\n      if (!this.has(value)) {\n        return false;\n      }\n      const state = this[DRAFT_STATE];\n      assertUnrevoked(state);\n      prepareSetCopy(state);\n      markChanged(state);\n      return state.copy_.delete(value) || (state.drafts_.has(value) ? state.copy_.delete(state.drafts_.get(value)) : (\n        /* istanbul ignore next */\n        false\n      ));\n    }\n    clear() {\n      const state = this[DRAFT_STATE];\n      assertUnrevoked(state);\n      if (latest(state).size) {\n        prepareSetCopy(state);\n        markChanged(state);\n        state.copy_.clear();\n      }\n    }\n    values() {\n      const state = this[DRAFT_STATE];\n      assertUnrevoked(state);\n      prepareSetCopy(state);\n      return state.copy_.values();\n    }\n    entries() {\n      const state = this[DRAFT_STATE];\n      assertUnrevoked(state);\n      prepareSetCopy(state);\n      return state.copy_.entries();\n    }\n    keys() {\n      return this.values();\n    }\n    [(DRAFT_STATE, Symbol.iterator)]() {\n      return this.values();\n    }\n    forEach(cb, thisArg) {\n      const iterator = this.values();\n      let result = iterator.next();\n      while (!result.done) {\n        cb.call(thisArg, result.value, result.value, this);\n        result = iterator.next();\n      }\n    }\n  }\n  function proxySet_(target, parent) {\n    const set2 = new DraftSet(target, parent);\n    return [set2, set2[DRAFT_STATE]];\n  }\n  function prepareSetCopy(state) {\n    if (!state.copy_) {\n      state.copy_ = /* @__PURE__ */ new Set();\n      state.base_.forEach((value) => {\n        if (isDraftable(value)) {\n          const draft = createProxy(state.scope_, value, state, value);\n          state.drafts_.set(value, draft);\n          state.copy_.add(draft);\n        } else {\n          state.copy_.add(value);\n        }\n      });\n    }\n  }\n  function assertUnrevoked(state) {\n    if (state.revoked_)\n      die(3, JSON.stringify(latest(state)));\n  }\n  function fixSetContents(target) {\n    if (target.type_ === 3 /* Set */ && target.copy_) {\n      const copy = new Set(target.copy_);\n      target.copy_.clear();\n      copy.forEach((value) => {\n        target.copy_.add(getValue(value));\n      });\n    }\n  }\n  loadPlugin(PluginMapSet, { proxyMap_, proxySet_, fixSetContents });\n}\n\n// src/plugins/arrayMethods.ts\nfunction enableArrayMethods() {\n  const SHIFTING_METHODS = /* @__PURE__ */ new Set([\"shift\", \"unshift\"]);\n  const QUEUE_METHODS = /* @__PURE__ */ new Set([\"push\", \"pop\"]);\n  const RESULT_RETURNING_METHODS = /* @__PURE__ */ new Set([\n    ...QUEUE_METHODS,\n    ...SHIFTING_METHODS\n  ]);\n  const REORDERING_METHODS = /* @__PURE__ */ new Set([\"reverse\", \"sort\"]);\n  const MUTATING_METHODS = /* @__PURE__ */ new Set([\n    ...RESULT_RETURNING_METHODS,\n    ...REORDERING_METHODS,\n    \"splice\"\n  ]);\n  const FIND_METHODS = /* @__PURE__ */ new Set([\"find\", \"findLast\"]);\n  const NON_MUTATING_METHODS = /* @__PURE__ */ new Set([\n    \"filter\",\n    \"slice\",\n    \"concat\",\n    \"flat\",\n    ...FIND_METHODS,\n    \"findIndex\",\n    \"findLastIndex\",\n    \"some\",\n    \"every\",\n    \"indexOf\",\n    \"lastIndexOf\",\n    \"includes\",\n    \"join\",\n    \"toString\",\n    \"toLocaleString\"\n  ]);\n  function isMutatingArrayMethod(method) {\n    return MUTATING_METHODS.has(method);\n  }\n  function isNonMutatingArrayMethod(method) {\n    return NON_MUTATING_METHODS.has(method);\n  }\n  function isArrayOperationMethod(method) {\n    return isMutatingArrayMethod(method) || isNonMutatingArrayMethod(method);\n  }\n  function enterOperation(state, method) {\n    state.operationMethod = method;\n  }\n  function exitOperation(state) {\n    state.operationMethod = void 0;\n  }\n  function executeArrayMethod(state, operation, markLength = true) {\n    prepareCopy(state);\n    const result = operation();\n    markChanged(state);\n    if (markLength)\n      state.assigned_.set(\"length\", true);\n    return result;\n  }\n  function markAllIndicesReassigned(state) {\n    state.allIndicesReassigned_ = true;\n  }\n  function normalizeSliceIndex(index, length) {\n    if (index < 0) {\n      return Math.max(length + index, 0);\n    }\n    return Math.min(index, length);\n  }\n  function handleInsertedValues(state, startIndex, values) {\n    for (let i = 0; i < values.length; i++) {\n      const index = startIndex + i;\n      state.assigned_.set(index, true);\n      handleCrossReference(state, index, values[i]);\n    }\n  }\n  function handleSimpleOperation(state, method, args) {\n    return executeArrayMethod(state, () => {\n      const lengthBefore = state.copy_.length;\n      const result = state.copy_[method](...args);\n      if (SHIFTING_METHODS.has(method)) {\n        markAllIndicesReassigned(state);\n      }\n      if (method === \"push\" && args.length > 0) {\n        handleInsertedValues(state, lengthBefore, args);\n      } else if (method === \"unshift\" && args.length > 0) {\n        handleInsertedValues(state, 0, args);\n      }\n      return RESULT_RETURNING_METHODS.has(method) ? result : state.draft_;\n    });\n  }\n  function handleReorderingOperation(state, method, args) {\n    return executeArrayMethod(\n      state,\n      () => {\n        ;\n        state.copy_[method](...args);\n        markAllIndicesReassigned(state);\n        return state.draft_;\n      },\n      false\n    );\n  }\n  function createMethodInterceptor(state, originalMethod) {\n    return function interceptedMethod(...args) {\n      const method = originalMethod;\n      enterOperation(state, method);\n      try {\n        if (isMutatingArrayMethod(method)) {\n          if (RESULT_RETURNING_METHODS.has(method)) {\n            return handleSimpleOperation(state, method, args);\n          }\n          if (REORDERING_METHODS.has(method)) {\n            return handleReorderingOperation(state, method, args);\n          }\n          if (method === \"splice\") {\n            const res = executeArrayMethod(\n              state,\n              () => state.copy_.splice(...args)\n            );\n            markAllIndicesReassigned(state);\n            if (args.length > 2) {\n              const startIndex = normalizeSliceIndex(\n                args[0] ?? 0,\n                state.copy_.length\n              );\n              handleInsertedValues(state, startIndex, args.slice(2));\n            }\n            return res;\n          }\n        } else {\n          return handleNonMutatingOperation(state, method, args);\n        }\n      } finally {\n        exitOperation(state);\n      }\n    };\n  }\n  function handleNonMutatingOperation(state, method, args) {\n    const source = latest(state);\n    if (method === \"filter\") {\n      const predicate = args[0];\n      const result = [];\n      for (let i = 0; i < source.length; i++) {\n        if (predicate(source[i], i, source)) {\n          result.push(state.draft_[i]);\n        }\n      }\n      return result;\n    }\n    if (FIND_METHODS.has(method)) {\n      const predicate = args[0];\n      const isForward = method === \"find\";\n      const step = isForward ? 1 : -1;\n      const start = isForward ? 0 : source.length - 1;\n      for (let i = start; i >= 0 && i < source.length; i += step) {\n        if (predicate(source[i], i, source)) {\n          return state.draft_[i];\n        }\n      }\n      return void 0;\n    }\n    if (method === \"slice\") {\n      const rawStart = args[0] ?? 0;\n      const rawEnd = args[1] ?? source.length;\n      const start = normalizeSliceIndex(rawStart, source.length);\n      const end = normalizeSliceIndex(rawEnd, source.length);\n      const result = [];\n      for (let i = start; i < end; i++) {\n        result.push(state.draft_[i]);\n      }\n      return result;\n    }\n    return source[method](...args);\n  }\n  loadPlugin(PluginArrayMethods, {\n    createMethodInterceptor,\n    isArrayOperationMethod,\n    isMutatingArrayMethod\n  });\n}\n\n// src/immer.ts\nvar immer = new Immer2();\nvar produce = immer.produce;\nvar produceWithPatches = /* @__PURE__ */ immer.produceWithPatches.bind(immer);\nvar setAutoFreeze = /* @__PURE__ */ immer.setAutoFreeze.bind(immer);\nvar setUseStrictShallowCopy = /* @__PURE__ */ immer.setUseStrictShallowCopy.bind(immer);\nvar setUseStrictIteration = /* @__PURE__ */ immer.setUseStrictIteration.bind(immer);\nvar applyPatches = /* @__PURE__ */ immer.applyPatches.bind(immer);\nvar createDraft = /* @__PURE__ */ immer.createDraft.bind(immer);\nvar finishDraft = /* @__PURE__ */ immer.finishDraft.bind(immer);\nvar castDraft = (value) => value;\nvar castImmutable = (value) => value;\nexport {\n  Immer2 as Immer,\n  applyPatches,\n  castDraft,\n  castImmutable,\n  createDraft,\n  current,\n  enableArrayMethods,\n  enableMapSet,\n  enablePatches,\n  finishDraft,\n  freeze,\n  DRAFTABLE as immerable,\n  isDraft,\n  isDraftable,\n  NOTHING as nothing,\n  original,\n  produce,\n  produceWithPatches,\n  setAutoFreeze,\n  setUseStrictIteration,\n  setUseStrictShallowCopy\n};\n//# sourceMappingURL=immer.mjs.map","import { deepEqual } from \"fast-equals\";\nimport {\n  applyPatches,\n  type Draft,\n  enablePatches,\n  type Patch,\n  type PatchListener,\n  produce,\n  produceWithPatches,\n} from \"immer\";\n\n// Immer emits JSON patches for `produceWithPatches`, which the store exposes via\n// `listenToPatches`. This must run once, before any patch-producing update.\nenablePatches();\n\n/**\n * A plain pub/sub listener. Fired (in the order added) every time the store's\n * root state reference changes. This is the vanilla integration point that any\n * ecosystem — including the React adapter's `useSyncExternalStore` — builds on.\n */\nexport type TUpdateListener = () => void;\n\n/**\n * **Mutate-only**: change the `draft` in place. Unlike immer's `produce`, a returned value is\n * NOT honored as a replacement state — to swap the state wholesale use {@link Store.replace}.\n * (An updater that returns an object without touching its draft throws, catching the\n * `store.update(() => initialState())` reset idiom that would otherwise silently no-op.)\n *\n * @typeParam S  The store's state\n * @param draft     The mutable draft to change during this update (Immer proxy).\n * @param original  A readonly snapshot of the state as it was before this update.\n */\nexport type TUpdateFunction<S> = (draft: Draft<S>, original: S) => void;\n\n/**\n * A selector that derives a watched slice `T` from the full store state `S`.\n */\nexport type TStoreWatch<S extends object, T> = (state: S) => T;\n\n/**\n * Fired by {@link Store.watch} whenever the watched slice changes structurally.\n */\nexport type TStoreSubscriptionListener<S extends object, T> = (\n  watched: T,\n  allState: S,\n  previousWatched: T,\n) => void;\n\n/**\n * Runs inside an Immer `produce` whenever a watched slice changes, letting the\n * store derive further state from its own mutations.\n */\nexport type TReactionFunction<S extends object, T> = (\n  watched: T,\n  draft: Draft<S>,\n  original: S,\n  previousWatched: T,\n) => void;\n\nexport type TStoreActionUpdate<S extends object> = (\n  updater: TUpdateFunction<S> | TUpdateFunction<S>[],\n  patchesCallback?: TPatchesCallback,\n) => void;\n\nexport type TStoreAction<S extends object> = (update: TStoreActionUpdate<S>) => void;\n\nexport type TPatchesCallback = (patches: Patch[], inversePatches: Patch[]) => void;\n\n/**\n * @internal\n * Drives a registered reaction. `forceRun` bypasses the change-detection\n * fast-path (used when a reaction is created with `runNow`).\n */\ntype TRunReactionFunction = (forceRun?: boolean) => void;\n\n/**\n * @internal\n * Drives a registered selector subscription on every store emission.\n */\ntype TRunSubscriptionFunction = () => void;\n\n/**\n * @internal\n * Binds a reaction definition to a concrete store instance.\n */\ntype TReactionCreator<S extends object> = (store: Store<S>) => TRunReactionFunction;\n\nexport interface IStoreInternalOptions<S extends object> {\n  ssr: boolean;\n  reactionCreators?: TReactionCreator<S>[];\n}\n\nexport interface ICreateReactionOptions {\n  runNow?: boolean;\n  runNowWithSideEffects?: boolean;\n}\n\n/**\n * @internal\n *\n * Builds the per-emission runner for a selector subscription.\n *\n * Change detection follows the \"Fast-Path\" rule: Immer's structural sharing\n * means an untouched branch keeps its exact reference, so a strict `===` check\n * resolves the overwhelmingly common \"nothing changed\" case in 0ms. Only when\n * the reference actually changes do we pay for a `deepEqual` traversal to\n * confirm the change is structural and not just a new-but-equal reference.\n */\nfunction makeSubscriptionFunction<S extends object, T>(\n  store: Store<S>,\n  watch: TStoreWatch<S, T>,\n  listener: TStoreSubscriptionListener<S, T>,\n): TRunSubscriptionFunction {\n  let lastWatchState: T = watch(store.state);\n\n  return () => {\n    const currentState = store.state;\n    const nextWatchState = watch(currentState);\n\n    // Fast-path: reference is identical → the watched branch was never touched.\n    if (nextWatchState === lastWatchState) {\n      return;\n    }\n\n    // Reference changed — fall back to deep equality to confirm real change.\n    if (deepEqual(nextWatchState, lastWatchState)) {\n      // Structurally equal: adopt the new reference so the fast-path stays hot,\n      // but do not notify — nothing the watcher cares about actually changed.\n      lastWatchState = nextWatchState;\n      return;\n    }\n\n    const previousWatched = lastWatchState;\n    lastWatchState = nextWatchState;\n    listener(nextWatchState, currentState, previousWatched);\n  };\n}\n\n/**\n * @internal\n *\n * Builds a reaction creator. Reactions follow the same Fast-Path rule as\n * subscriptions, then run their recipe inside Immer to derive further state.\n */\nfunction makeReactionFunctionCreator<S extends object, T>(\n  watch: TStoreWatch<S, T>,\n  reaction: TReactionFunction<S, T>,\n): TReactionCreator<S> {\n  return (store) => {\n    let lastWatchState: T = watch(store.state);\n\n    return (forceRun = false) => {\n      const currentState = store.state;\n      const nextWatchState = watch(currentState);\n\n      if (!forceRun) {\n        // Fast-path: identical reference → skip entirely.\n        if (nextWatchState === lastWatchState) {\n          return;\n        }\n\n        // New reference but structurally equal → adopt and skip the recipe.\n        if (deepEqual(nextWatchState, lastWatchState)) {\n          lastWatchState = nextWatchState;\n          return;\n        }\n      }\n\n      const previousWatched = lastWatchState;\n      lastWatchState = nextWatchState;\n\n      // Reactions mutate via Immer but must not re-enter the reaction loop, so\n      // they write back through the no-reaction update path.\n      if (store._hasPatchListeners()) {\n        const [nextState, patches, inversePatches] = produceWithPatches(\n          currentState,\n          (draft: Draft<S>) => {\n            reaction(nextWatchState, draft, currentState, previousWatched);\n          },\n        );\n\n        store._updateStateWithoutReaction(nextState);\n\n        if (patches.length > 0) {\n          store._emitPatches(patches, inversePatches);\n        }\n      } else {\n        const nextState = produce(currentState, (draft: Draft<S>) => {\n          reaction(nextWatchState, draft, currentState, previousWatched);\n        });\n        store._updateStateWithoutReaction(nextState);\n      }\n    };\n  };\n}\n\n/**\n * A framework-agnostic, Immer-backed state container.\n *\n * The store owns a single immutable state value and a `Set` of plain\n * listeners. Every mutation runs through Immer's `produce`, and listeners are\n * only notified when the resulting root reference actually changes — making\n * \"no-op\" updates genuinely free for subscribers.\n *\n * @typeParam S  Your store's state interface.\n */\nexport class Store<S extends object = object> {\n  private currentState: S;\n  private readonly createInitialState: () => S;\n  private ssr = false;\n\n  /** Plain pub/sub listeners — a Set both dedupes and dispatches fast. */\n  private readonly listeners = new Set<TUpdateListener>();\n\n  private reactionCreators: TReactionCreator<S>[] = [];\n  private reactions: TRunReactionFunction[] = [];\n  private clientSubscriptions: TRunSubscriptionFunction[] = [];\n\n  /**\n   * @internal\n   */\n  public _patchListeners: PatchListener[] = [];\n\n  constructor(initialState: S | (() => S)) {\n    if (initialState instanceof Function) {\n      this.createInitialState = initialState;\n      this.currentState = initialState();\n    } else {\n      this.createInitialState = () => initialState;\n      this.currentState = initialState;\n    }\n  }\n\n  /**\n   * The store's current state, frozen (shallow) for read safety — mutations must go through\n   * {@link update} / {@link replace}, never by writing to this object.\n   *\n   * Reach for it in plain logic (event handlers, engines, tests). In React components use\n   * `useStoreState` so the component re-renders on change; for side-effects use {@link watch}.\n   */\n  get state(): S {\n    return Object.freeze(this.currentState);\n  }\n\n  /**\n   * @internal\n   */\n  _setInternalOptions({ ssr, reactionCreators = [] }: IStoreInternalOptions<S>) {\n    this.ssr = ssr;\n    this.reactionCreators = reactionCreators;\n    this.reactions = reactionCreators.map((rc) => rc(this));\n  }\n\n  /**\n   * @internal\n   */\n  _getReactionCreators(): TReactionCreator<S>[] {\n    return this.reactionCreators;\n  }\n\n  /**\n   * @internal\n   */\n  _instantiateReactions() {\n    this.reactions = this.reactionCreators.map((rc) => rc(this));\n  }\n\n  /**\n   * @internal\n   */\n  _getInitialState(): S {\n    return this.createInitialState();\n  }\n\n  /**\n   * @internal\n   */\n  _hasPatchListeners(): boolean {\n    return this._patchListeners.length > 0;\n  }\n\n  /**\n   * @internal\n   */\n  _emitPatches(patches: Patch[], inversePatches: Patch[]) {\n    for (const listener of this._patchListeners) {\n      listener(patches, inversePatches);\n    }\n  }\n\n  /**\n   * @internal\n   *\n   * Writes a new state value without running reactions. Used by reactions\n   * themselves to avoid re-entrancy.\n   */\n  _updateStateWithoutReaction(nextState: S) {\n    this.currentState = nextState;\n  }\n\n  /**\n   * @internal\n   *\n   * Commits a new root state, runs reactions, then dispatches to all\n   * subscribers. Callers are responsible for the `nextState !== currentState`\n   * reference guard before invoking this.\n   */\n  _updateState(nextState: S) {\n    this.currentState = nextState;\n\n    // Reactions run first and may derive further state (without re-triggering).\n    for (const runReaction of this.reactions) {\n      runReaction();\n    }\n\n    if (this.ssr) {\n      return;\n    }\n\n    for (const runSubscription of this.clientSubscriptions) {\n      runSubscription();\n    }\n\n    for (const listener of this.listeners) {\n      listener();\n    }\n  }\n\n  /**\n   * Subscribe a plain listener to store mutations. The listener fires once per\n   * committed update (root reference change) and receives no arguments — read\n   * the latest value with {@link state}.\n   *\n   * This is the low-level primitive that vanilla code and framework adapters\n   * (e.g. React's `useSyncExternalStore`) build upon.\n   *\n   * @returns An unsubscribe function.\n   */\n  subscribe(listener: TUpdateListener): () => void {\n    this.listeners.add(listener);\n    return () => {\n      this.listeners.delete(listener);\n    };\n  }\n\n  /**\n   * Subscribe to a derived slice of state. The `listener` only fires when the\n   * watched value changes structurally (per the Fast-Path rule).\n   *\n   * @returns An unsubscribe function.\n   */\n  watch<T>(watch: TStoreWatch<S, T>, listener: TStoreSubscriptionListener<S, T>): () => void {\n    if (this.ssr) {\n      return () => {\n        console.warn(\n          `@nice-code/state: Subscriptions made on the server side are not registered, so this unsubscribe call does nothing.`,\n        );\n      };\n    }\n\n    const run = makeSubscriptionFunction(this, watch, listener);\n    this.clientSubscriptions.push(run);\n\n    return () => {\n      this.clientSubscriptions = this.clientSubscriptions.filter((f) => f !== run);\n    };\n  }\n\n  /**\n   * Register a reaction: when the watched slice changes, the `reaction` recipe\n   * runs inside Immer to derive further state on the same store.\n   *\n   * @returns A function that removes the reaction.\n   */\n  createReaction<T>(\n    watch: TStoreWatch<S, T>,\n    reaction: TReactionFunction<S, T>,\n    { runNow = false, runNowWithSideEffects = false }: ICreateReactionOptions = {},\n  ): () => void {\n    const creator = makeReactionFunctionCreator(watch, reaction);\n    this.reactionCreators.push(creator);\n\n    const run = creator(this);\n    this.reactions.push(run);\n\n    if (runNow || runNowWithSideEffects) {\n      run(true);\n\n      if (runNowWithSideEffects && !this.ssr) {\n        this._updateState(this.currentState);\n      }\n    }\n\n    return () => {\n      this.reactions = this.reactions.filter((f) => f !== run);\n      this.reactionCreators = this.reactionCreators.filter((f) => f !== creator);\n    };\n  }\n\n  /**\n   * Subscribe to the Immer patches produced by each update.\n   *\n   * @returns An unsubscribe function.\n   */\n  listenToPatches(patchListener: PatchListener): () => void {\n    this._patchListeners.push(patchListener);\n    return () => {\n      this._patchListeners = this._patchListeners.filter((f) => f !== patchListener);\n    };\n  }\n\n  /**\n   * Mutate the store via one or more Immer update functions.\n   *\n   * @param updater          A single update function, or an array applied in order.\n   * @param patchesCallback  Optional callback receiving the patches for this update.\n   */\n  update(updater: TUpdateFunction<S> | TUpdateFunction<S>[], patchesCallback?: TPatchesCallback) {\n    update(this, updater, patchesCallback);\n  }\n\n  /**\n   * Replace the store's state entirely with a new state value — the reset/swap counterpart to\n   * {@link update} (whose update functions are mutate-only). A replace is a first-class citizen\n   * of the patch stream: patch listeners receive one root `replace` patch (path `[]`) with its\n   * inverse, so persistence/undo/sync layers built on {@link listenToPatches} see resets too.\n   */\n  replace(newState: S) {\n    if (newState === this.currentState) return;\n    if (this._hasPatchListeners()) {\n      // Mirror update()'s ordering: patches are emitted before the commit/dispatch.\n      this._emitPatches(\n        [{ op: \"replace\", path: [], value: newState }],\n        [{ op: \"replace\", path: [], value: this.currentState }],\n      );\n    }\n    this._updateState(newState);\n  }\n\n  /**\n   * Replace the store's state by mapping from the current state.\n   */\n  replaceFromCurrent(replacer: (state: S) => S) {\n    this.replace(replacer(this.currentState));\n  }\n\n  /**\n   * Apply a set of Immer patches to the store.\n   */\n  applyPatches(patches: Patch[]) {\n    applyPatchesToStore(this, patches);\n  }\n}\n\n/**\n * Apply Immer patches to a store, committing only if the root reference changes.\n */\nexport function applyPatchesToStore<S extends object = object>(store: Store<S>, patches: Patch[]) {\n  const currentState = store.state;\n  const nextState = applyPatches(currentState, patches);\n  if (nextState !== currentState) {\n    store._updateState(nextState);\n  }\n}\n\n/**\n * @internal\n *\n * The \"returned a replacement state\" footgun guard: the update pipeline is mutate-only — unlike\n * immer's `produce`, a state returned from an update function is NOT honored. The natural\n * reset idiom `store.update(() => createInitialState())` therefore used to be a *silent no-op*.\n * An updater that returned an object while leaving its draft untouched almost certainly meant\n * exactly that, so it throws here instead. (Concise-arrow returns like `(d) => d.count++` or\n * `(d) => (d.x = value)` modify the draft and stay allowed.)\n *\n * **A returned *draft* is not the footgun** — `Object.assign(draft, next)` already applied the\n * mutation, and returning the draft is merely redundant. Judging it by whether the draft happened\n * to change made the throw data-dependent: the pattern passed every first run and blew up later\n * on the one reset where `next` was identical (meteor-connect-bridge feedback S1). Splitting on\n * draft identity instead is deterministic — a returned draft always passes, a returned\n * *replacement* with an untouched draft always throws.\n */\nfunction assertNoReturnedState(\n  returned: unknown,\n  draftWasModified: boolean,\n  returnedIsDraft: boolean,\n): void {\n  if (returnedIsDraft) return;\n  if (!draftWasModified && typeof returned === \"object\" && returned != null) {\n    throw new Error(\n      \"@nice-code/state: an update function returned a value without modifying its draft. \" +\n        \"Update functions are mutate-only — a returned state is ignored (unlike immer's produce). \" +\n        \"To reset or swap the state wholesale, use store.replace(next); to change part of it, \" +\n        \"mutate the draft.\",\n    );\n  }\n}\n\n/**\n * @internal\n *\n * Runs an updater (or array of updaters) through Immer, collecting patches.\n */\nfunction applyUpdaterWithPatches<S extends object>(\n  currentState: S,\n  updater: TUpdateFunction<S> | TUpdateFunction<S>[],\n): [S, Patch[], Patch[]] {\n  if (typeof updater === \"function\") {\n    let returned: unknown;\n    let returnedIsDraft = false;\n    const [next, patches, inversePatches] = produceWithPatches(currentState, (draft: Draft<S>) => {\n      returned = updater(draft, currentState);\n      returnedIsDraft = returned === draft;\n    });\n    assertNoReturnedState(returned, next !== currentState, returnedIsDraft);\n    return [next, patches, inversePatches];\n  }\n\n  let state = currentState;\n  const patches: Patch[] = [];\n  const inversePatches: Patch[] = [];\n\n  for (const single of updater) {\n    let returned: unknown;\n    let returnedIsDraft = false;\n    const [next, p, ip] = produceWithPatches(state, (draft: Draft<S>) => {\n      returned = single(draft, state);\n      returnedIsDraft = returned === draft;\n    });\n    assertNoReturnedState(returned, next !== state, returnedIsDraft);\n    state = next;\n    patches.push(...p);\n    inversePatches.push(...ip);\n  }\n\n  return [state, patches, inversePatches];\n}\n\n/**\n * @internal\n *\n * Runs an updater (or array of updaters) through Immer without tracking patches.\n */\nfunction applyUpdater<S extends object>(\n  currentState: S,\n  updater: TUpdateFunction<S> | TUpdateFunction<S>[],\n): S {\n  if (typeof updater === \"function\") {\n    let returned: unknown;\n    let returnedIsDraft = false;\n    const next = produce(currentState, (draft: Draft<S>) => {\n      returned = updater(draft, currentState);\n      returnedIsDraft = returned === draft;\n    });\n    assertNoReturnedState(returned, next !== currentState, returnedIsDraft);\n    return next;\n  }\n\n  return updater.reduce<S>((previousState, single) => {\n    let returned: unknown;\n    let returnedIsDraft = false;\n    const next = produce(previousState, (draft: Draft<S>) => {\n      returned = single(draft, previousState);\n      returnedIsDraft = returned === draft;\n    });\n    assertNoReturnedState(returned, next !== previousState, returnedIsDraft);\n    return next;\n  }, currentState);\n}\n\n/**\n * Mutate a store via one or more Immer update functions.\n *\n * Patches are only computed when there's a consumer for them (a registered\n * patch listener or a `patchesCallback`), keeping the common path allocation-free.\n * Listeners are notified only when the root reference actually changes.\n *\n * @param store            The store to update.\n * @param updater          A single update function, or an array applied in order.\n * @param patchesCallback  Optional callback receiving the patches for this update.\n */\nexport function update<S extends object = object>(\n  store: Store<S>,\n  updater: TUpdateFunction<S> | TUpdateFunction<S>[],\n  patchesCallback?: TPatchesCallback,\n) {\n  const currentState = store.state;\n\n  let nextState: S;\n\n  if (store._hasPatchListeners() || patchesCallback != null) {\n    const [next, patches, inversePatches] = applyUpdaterWithPatches(currentState, updater);\n\n    if (patches.length > 0) {\n      if (patchesCallback != null) {\n        patchesCallback(patches, inversePatches);\n      }\n      store._emitPatches(patches, inversePatches);\n    }\n\n    nextState = next;\n  } else {\n    nextState = applyUpdater(currentState, updater);\n  }\n\n  // Reference guard: an updater that mutated nothing yields the same reference,\n  // so we skip the dispatch entirely.\n  if (nextState !== currentState) {\n    store._updateState(nextState);\n  }\n}\n","import { err, err_nice } from \"@nice-code/error\";\n\n/**\n * The realm base error domain. Rejection frames carry `packError` output (a msgpack\n * map), never positional tuples — rejections are the rare path, so they stay fully descriptive\n * and hydratable. User realms define their own domains for rule/intent rejections; these are the\n * engine's own errors. (`protocol_unsupported` lives in `@nice-code/wire` — it is a link-level\n * concern, not a realm one.)\n */\nexport const err_realm = err_nice.createChildDomain({\n  domain: \"err_nice_realm\",\n  schema: {\n    schema_mismatch: err<{ clientHash: string; serverHash: string; realmId: string }>({\n      message: ({ realmId, clientHash, serverHash }) =>\n        `Realm \"${realmId}\" schema mismatch — avatar ${clientHash.slice(0, 12)}… vs server ${serverHash.slice(0, 12)}…. ` +\n        \"The client and server were built from different realm definitions; refusing to attach \" +\n        \"(silent token skew would corrupt state).\",\n      context: { required: true },\n    }),\n    realm_unknown: err<{ realmId: string }>({\n      message: ({ realmId }) => `This server hosts no realm with id \"${realmId}\".`,\n      context: { required: true },\n    }),\n    unauthorized_avatar_type: err<{ avatarType: string; expected: readonly string[] }>({\n      message: ({ avatarType, expected }) =>\n        `Client type \"${avatarType}\" is not permitted here (expected: ${expected.join(\", \")}).`,\n      context: { required: true },\n    }),\n    /** The connection's identity could not be resolved to a realm avatar: the\n     * server's `resolveAvatar`/`avatarType` mapping returned nothing for this connection. */\n    avatar_unresolved: err<{ realmId: string }>({\n      message: ({ realmId }) =>\n        `This connection's identity could not be resolved to an avatar of realm \"${realmId}\" — ` +\n        \"the server's resolveAvatar returned undefined (or the attachment carries no coordinate).\",\n      context: { required: true },\n    }),\n    /**\n     * The connection's negotiated wire security level is below the realm's declared minimum\n     *. Fail-closed at attach: the avatar never attaches, so no avatar data\n     * flows below the required level. Raise the connection's `securityLevel` (e.g. `encrypted`) to\n     * attach — the realm requires it.\n     */\n    insufficient_security: err<{ realmId: string; required: string; actual: string }>({\n      message: ({ realmId, required, actual }) =>\n        `Realm \"${realmId}\" requires a \"${required}\" connection but this one negotiated \"${actual}\". ` +\n        \"Connect with at least the required security level — the realm refuses to move avatar data below it.\",\n      context: { required: true },\n    }),\n    unauthorized_coordinate: err<{ path: string }>({\n      message: ({ path }) => `This avatar's coordinates may not write \"${path}\".`,\n      context: { required: true },\n    }),\n    value_invalid: err<{ path: string; expected: string }>({\n      message: ({ path, expected }) =>\n        `The value written to \"${path}\" does not match the schema (expected ${expected}).`,\n      context: { required: true },\n    }),\n    limits_exceeded: err<{ limit: string }>({\n      message: ({ limit }) => `Ingress limit exceeded: ${limit}.`,\n      context: { required: true },\n    }),\n    intent_unknown: err<{ intent: string }>({\n      message: ({ intent }) => `Unknown intent \"${intent}\".`,\n      context: { required: true },\n    }),\n    version_gap_unrecoverable: err<{ lastKnownVersion: number; oldestReplayable: number }>({\n      message: ({ lastKnownVersion, oldestReplayable }) =>\n        `Version ${lastKnownVersion} is behind the replayable window (oldest ${oldestReplayable}) — full rehydration required.`,\n      context: { required: true },\n    }),\n    /** A write or intent made before the first hydrate is queued for it; this is the queued\n     * handle's rejection when that hydrate never came (the realm detached, or `pendingExpiryMs`\n     * passed first). Definite: nothing was sent. A refused attach rejects with the attach error. */\n    write_before_hydrate: err<{ realmId: string }>({\n      message: ({ realmId }) =>\n        `A write on \"${realmId}\" was queued for the first hydrate, which never arrived (the realm ` +\n        \"detached, or the pending expiry passed first) — nothing was sent.\",\n      context: { required: true },\n    }),\n    /**\n     * The optimistic frame expired / was rolled back before an authoritative answer arrived — an\n     * **unknown outcome**, NOT proof the server rejected it. The\n     * write may have committed on the server while the ack was lost, or the link dropped mid-flight.\n     * Do not blindly re-issue a non-idempotent **intent** on this error — re-read state (it\n     * converges via the next replay/hydrate) and decide. A rules rejection, by contrast, is a\n     * definite \"no\" and carries the rule's own error, not this one.\n     */\n    frame_too_stale: err<{ basisVersion: number }>({\n      message: ({ basisVersion }) =>\n        `The optimistic frame (basis ${basisVersion}) expired before it could be confirmed — outcome unknown (it may have committed; re-read state rather than re-issuing a non-idempotent intent).`,\n      context: { required: true },\n    }),\n    /** The durable-write backlog cap: too many unconfirmed\n     * `durability: \"reassert\"` frames accumulated (a long outage). The app's cue to fall back to\n     * its own source-of-truth re-sync instead of queueing more. */\n    durable_backlog_overflow: err<{ pendingFrames: number }>({\n      message: ({ pendingFrames }) =>\n        `The durable-write backlog is full (${pendingFrames} unconfirmed reassert frames) — ` +\n        \"this write was rejected. Re-sync from your source of truth after reconnecting.\",\n      context: { required: true },\n    }),\n    frame_invalid: err<{ reason: string }>({\n      message: ({ reason }) => `Malformed realm frame: ${reason}.`,\n      context: { required: true },\n    }),\n    /**\n     * A structurally valid write (schema + rules passed) that does not APPLY to the current\n     * authoritative state — its target's parent no longer exists (a record entry deleted by a\n     * server-side prune, or a transient region reset by a hibernation wake between the write's\n     * basis and its arrival). Distinct from {@link frame_invalid} (a malformed/hostile frame): the\n     * frame was well-formed, the state simply moved out from under it. A predicted optimistic write\n     * on this path rolls back; the app should re-read state (an assert-on-resume re-creates a\n     * pruned own-entry) rather than re-issue blindly. Additive since 0.46 — pre-0.46 servers send\n     * `frame_invalid` for this case.\n     */\n    write_target_missing: err<{ path: string }>({\n      message: ({ path }) =>\n        `The write to \"${path}\" could not be applied — its parent no longer exists (a pruned entry ` +\n        \"or a transient region reset since the write's basis). Re-read state instead of re-issuing.\",\n      context: { required: true },\n    }),\n  },\n});\n","import type { TSchemaNode } from \"./schema.types\";\n\n/**\n * Server-side value validation: every value entering the state through the wire is\n * checked against its schema node **before any rule runs** — wire types are never trusted; a\n * string landing in a `t.number()` leaf dies here (`err_realm.value_invalid`), not in a rule or,\n * worse, in another client's decoded state. Also used for intent-input validation on both sides.\n */\n\nexport interface IValueInvalid {\n  /** Path suffix below the validated node where the mismatch sits (`[]` = the node itself). */\n  path: (string | number)[];\n  expected: string;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n  return (\n    typeof value === \"object\" &&\n    value != null &&\n    !Array.isArray(value) &&\n    !(value instanceof Uint8Array)\n  );\n}\n\n/** `undefined` = valid; otherwise where and what was expected. */\nexport function validateValue(node: TSchemaNode, value: unknown): IValueInvalid | undefined {\n  switch (node.kind) {\n    case \"string\":\n      if (typeof value !== \"string\") return { path: [], expected: \"string\" };\n      if (node.maxLength != null && value.length > node.maxLength) {\n        return { path: [], expected: `a string of at most ${node.maxLength} characters` };\n      }\n      return undefined;\n    case \"number\": {\n      if (typeof value !== \"number\") return { path: [], expected: \"number\" };\n      const bounded = node.min != null || node.max != null || node.integer === true;\n      // Unbounded t.number() keeps its historical acceptance of any JS number; a bounded one\n      // must be finite or NaN would sail through every comparison below.\n      if (bounded && !Number.isFinite(value)) return { path: [], expected: \"a finite number\" };\n      if (node.integer === true && !Number.isInteger(value)) {\n        return { path: [], expected: \"an integer\" };\n      }\n      if (node.min != null && value < node.min) {\n        return { path: [], expected: `a number >= ${node.min}` };\n      }\n      if (node.max != null && value > node.max) {\n        return { path: [], expected: `a number <= ${node.max}` };\n      }\n      return undefined;\n    }\n    case \"boolean\":\n      return typeof value === \"boolean\" ? undefined : { path: [], expected: \"boolean\" };\n    case \"literal\":\n      return value === node.value\n        ? undefined\n        : { path: [], expected: `literal ${JSON.stringify(node.value)}` };\n    case \"optional\":\n      return value === undefined ? undefined : validateValue(node.inner, value);\n    case \"union\": {\n      for (const option of node.options) {\n        if (validateValue(option, value) == null) return undefined;\n      }\n      return { path: [], expected: \"one of the union options\" };\n    }\n    case \"object\": {\n      if (!isPlainObject(value)) return { path: [], expected: \"object\" };\n      for (const key of Object.keys(value)) {\n        if (node.entries[key] == null) {\n          return { path: [key], expected: \"no such key in the schema\" };\n        }\n      }\n      for (const [key, child] of Object.entries(node.entries)) {\n        const childValue = value[key];\n        if (childValue === undefined) {\n          if (child.kind !== \"optional\") return { path: [key], expected: child.kind };\n          continue;\n        }\n        const invalid = validateValue(child, childValue);\n        if (invalid != null) {\n          return { path: [key, ...invalid.path], expected: invalid.expected };\n        }\n      }\n      return undefined;\n    }\n    case \"record\": {\n      if (!isPlainObject(value)) return { path: [], expected: \"record\" };\n      // Whole-value cardinality; an incremental `record.$id` add is covered by the state-aware\n      // bounded gate (validateBoundedState), which sees the candidate next state.\n      if (node.maxKeys != null && Object.keys(value).length > node.maxKeys) {\n        return { path: [], expected: `a record with at most ${node.maxKeys} entries` };\n      }\n      for (const [key, entry] of Object.entries(value)) {\n        const invalid = validateValue(node.value, entry);\n        if (invalid != null) {\n          return { path: [key, ...invalid.path], expected: invalid.expected };\n        }\n      }\n      return undefined;\n    }\n    case \"array\": {\n      if (!Array.isArray(value)) return { path: [], expected: \"array\" };\n      if (node.maxItems != null && value.length > node.maxItems) {\n        return { path: [], expected: `an array of at most ${node.maxItems} items` };\n      }\n      for (let i = 0; i < value.length; i++) {\n        const invalid = validateValue(node.item, value[i]);\n        if (invalid != null) {\n          return { path: [i, ...invalid.path], expected: invalid.expected };\n        }\n      }\n      return undefined;\n    }\n    case \"standard\": {\n      const result = node.schema[\"~standard\"].validate(value);\n      if (result instanceof Promise) {\n        // Realm writes are synchronous by design — an async validator can't gate them.\n        return { path: [], expected: \"a synchronous standard-schema validator\" };\n      }\n      return result.issues == null\n        ? undefined\n        : { path: [], expected: result.issues[0]?.message ?? \"standard-schema pass\" };\n    }\n  }\n}\n","/**\n * Dynamic record-key interning: record keys are arbitrary strings\n * (nanoids, user ids); after their first appearance they travel as small ints. The server owns id\n * assignment (eager, on first committed write touching the key) and sends each connection the\n * `keyDict` delta entries it hasn't seen before any frame that uses them; clients only ever\n * *resolve*. Ids are engine-global per realm instance — the per-signature shared encode can then\n * contain interned ids while the (tiny) dict deltas stay per-connection.\n */\nexport class RealmKeyDict {\n  private readonly _toId = new Map<string, number>();\n  private readonly _toKey: string[] = [];\n\n  /** Intern a key (assigning the next id on first sight) — server side. */\n  intern(key: string): number {\n    let id = this._toId.get(key);\n    if (id == null) {\n      id = this._toKey.length;\n      this._toId.set(key, id);\n      this._toKey.push(key);\n    }\n    return id;\n  }\n\n  /** The id for a key when already interned (encode-side lookup that must not assign). */\n  idOf(key: string): number | undefined {\n    return this._toId.get(key);\n  }\n\n  /** Resolve an interned id back to its key — client side (undefined = unknown id). */\n  keyOf(id: number): string | undefined {\n    return this._toKey[id];\n  }\n\n  /** Load delta entries from a `keyDict`/`hydrate` frame — client side. */\n  load(entries: readonly [key: string, id: number][]): void {\n    for (const [key, id] of entries) {\n      this._toId.set(key, id);\n      this._toKey[id] = key;\n    }\n  }\n\n  get size(): number {\n    return this._toId.size;\n  }\n\n  /** Drop all entries — a client clears on re-hello (a woken server session reassigns ids). */\n  clear(): void {\n    this._toId.clear();\n    this._toKey.length = 0;\n  }\n}\n","import type { TWirePathSegment } from \"../RealmDefinition/Schema/tokenMap\";\n\n/**\n * The realm wire protocol: every frame is a msgpack fixarray `[kind, slot, …]` riding\n * the wire frame-protocol port at prefix `0x01` (M1 seam). The **slot** is a client-assigned small\n * int established by `hello`, so several realms — or several instances — share one peer link with\n * a one-byte discriminator per frame.\n *\n * Identity note (deviation D-13): v1 protocols are secure-duplex-only (D-11), so the connection is\n * already authenticated when the first realm frame arrives — `hello` carries no credential of its\n * own; the server resolves coordinates from the connection identity via its `resolveAvatar` hook.\n */\n\nexport const REALM_FRAME_KIND = {\n  hello: 0,\n  hydrate: 1,\n  patches: 2,\n  write: 3,\n  intent: 4,\n  ack: 5,\n  reject: 6,\n  keyDict: 7,\n  detach: 8,\n  /**\n   * Client→server capability advertisement. Sent right after\n   * every `hello` (fresh attach, reconnect, probe) so a hibernation-woken server — which lost the\n   * per-session feature state — re-learns them for free. An old server decodes an unknown kind →\n   * drops it → never emits the features it names; a new server with a client that never sends this\n   * frame sees no features and stays on the legacy per-frame path. Both skew directions are safe by\n   * the drop-unknown rule the codec + acceptor already enforce.\n   */\n  clientCaps: 9,\n  /**\n   * Server→client egress envelope (Phase 1 wire; Phase 2 emits it). Carries several complete realm\n   * frames as one message — see {@link IRealmFrameBatch}. Emitted **only** to a connection that\n   * advertised {@link REALM_FEATURE.batch}; never sent client→server. Nesting is forbidden.\n   */\n  batch: 10,\n} as const;\n\n/** Reverse lookup: frame-kind int → its name (devtools frame attribution). */\nexport const REALM_FRAME_KIND_NAME: Record<number, string> = Object.fromEntries(\n  Object.entries(REALM_FRAME_KIND).map(([name, kind]) => [kind, name]),\n);\n\n/**\n * Negotiated egress features a client advertises via a `clientCaps` frame. Kept as short opaque\n * tokens (they travel per hello) — bump the token, never repurpose one, when the shape changes.\n */\nexport const REALM_FEATURE = {\n  /** The v1 batch envelope: the server may fold this connection's frames into a {@link IRealmFrameBatch}. */\n  batch: \"b1\",\n} as const;\n\nexport type TRealmFeature = (typeof REALM_FEATURE)[keyof typeof REALM_FEATURE];\n\n/** Patch op ints — 1:1 with immer's `replace`/`add`/`remove`. */\nexport const REALM_OP = { replace: 0, add: 1, remove: 2 } as const;\n\n/**\n * The reserved broadcast slot: a server frame carrying it addresses **every** realm attached to\n * the link (never assignable to a realm). Used by the M6 wake path — a rehydrated Durable Object\n * sends `detach[slot=0xff, reason=\"rehello\"]` so each attached realm client re-hellos with its\n * `lastKnownVersion` and resumes via patch replay.\n */\nexport const REALM_BROADCAST_SLOT = 0xff;\n\n/** The `detach.reason` asking the client to re-attach (hibernation wake / unknown slot heal). */\nexport const REALM_DETACH_REASON_REHELLO = \"rehello\";\n\nexport type TRealmOpKind = (typeof REALM_OP)[keyof typeof REALM_OP];\n\n/**\n * One wire patch op: `[op, path]` for `remove`, `[op, path, value]` otherwise. Path segments are\n * schema tokens (ints at object levels), interned key ids (ints at record levels), or raw strings\n * (record keys before interning) — the token map's level structure disambiguates int meanings.\n */\nexport type TWireOp =\n  | [typeof REALM_OP.remove, TWirePathSegment[]]\n  | [TRealmOpKind, TWirePathSegment[], unknown];\n\nexport interface IRealmFrameHello {\n  kind: typeof REALM_FRAME_KIND.hello;\n  slot: number;\n  realmId: string;\n  schemaHash: string;\n  /** The last authoritative version this client holds (`-1` = none — full hydrate needed). */\n  lastKnownVersion: number;\n  /**\n   * The log epoch the client's `lastKnownVersion` belongs to — echoed from the\n   * hydrate that delivered it; absent before the first hydrate. The server replays only when it\n   * matches its own epoch; any mismatch (wiped storage, re-created realm, migration) forces a\n   * full hydrate instead of a diff computed against a different history.\n   */\n  epoch: string | undefined;\n}\n\nexport interface IRealmFrameHydrate {\n  kind: typeof REALM_FRAME_KIND.hydrate;\n  slot: number;\n  version: number;\n  /** msgpack blob of the client's sliced state (name-keyed; chunked above the host's ceiling). */\n  stateBlob: Uint8Array;\n  /** Key-dictionary seed entries (reserved — v1 servers send `[]`, interning is patch-lazy). */\n  keyDictSeed: [key: string, id: number][];\n  /** `true` = a continuation chunk follows; apply atomically only when the final chunk lands. */\n  more: boolean;\n  /** The engine's log epoch — minted at genesis and at `migrate`; echo it in `hello`. */\n  epoch: string;\n  /**\n   * The client-relevant ingress limits: `[maxPatchesPerFrame, maxFrameBytes,\n   * writeRatePerSecond]` — the client coalescer splits over-limit flushes against these.\n   */\n  limits: [maxPatchesPerFrame: number, maxFrameBytes: number, writeRatePerSecond: number];\n  /**\n   * The server-resolved avatar identity echo: `[type, persistentId, instanceId]`\n   * — the coordinates verdicts and view slicing run against. The client warns loudly when it\n   * disagrees with its own ref (the \"prediction passes, server rejects every time\" bug class).\n   */\n  avatar: [type: string, persistentId: string, instanceId: string];\n}\n\nexport interface IRealmFramePatches {\n  kind: typeof REALM_FRAME_KIND.patches;\n  slot: number;\n  fromVersion: number;\n  toVersion: number;\n  ops: TWireOp[];\n}\n\nexport interface IRealmFrameWrite {\n  kind: typeof REALM_FRAME_KIND.write;\n  slot: number;\n  clientSeq: number;\n  basisVersion: number;\n  ops: TWireOp[];\n}\n\nexport interface IRealmFrameIntent {\n  kind: typeof REALM_FRAME_KIND.intent;\n  slot: number;\n  clientSeq: number;\n  /** Sorted-name intent token (part of the schema hash). */\n  intentToken: number;\n  input: unknown;\n}\n\n/** Settle-only (D6): no result payload — outcomes live in state. */\nexport interface IRealmFrameAck {\n  kind: typeof REALM_FRAME_KIND.ack;\n  slot: number;\n  clientSeq: number;\n  version: number;\n}\n\nexport interface IRealmFrameReject {\n  kind: typeof REALM_FRAME_KIND.reject;\n  slot: number;\n  clientSeq: number;\n  /** The rejecting NiceError's `toJsonObject()` — rehydrate with `castNiceError`. */\n  error: Record<string, unknown>;\n}\n\nexport interface IRealmFrameKeyDict {\n  kind: typeof REALM_FRAME_KIND.keyDict;\n  slot: number;\n  entries: [key: string, id: number][];\n}\n\nexport interface IRealmFrameDetach {\n  kind: typeof REALM_FRAME_KIND.detach;\n  slot: number;\n  reason: string | undefined;\n}\n\n/** Client→server capability advertisement — the `features` are opaque {@link REALM_FEATURE} tokens. */\nexport interface IRealmFrameClientCaps {\n  kind: typeof REALM_FRAME_KIND.clientCaps;\n  slot: number;\n  features: string[];\n}\n\n/**\n * Server→client egress envelope: `frames` are complete, already-decoded realm frames, each routed\n * to its OWN inner slot on receipt (a batch is a **connection**-level envelope). The codec rejects\n * a nested batch and any malformed child at decode time — so a decoded batch is always a flat list\n * of well-formed non-batch frames (the fuzz gate holds for the envelope's contents too).\n */\nexport interface IRealmFrameBatch {\n  kind: typeof REALM_FRAME_KIND.batch;\n  slot: number;\n  frames: TRealmFrame[];\n}\n\nexport type TRealmFrame =\n  | IRealmFrameHello\n  | IRealmFrameHydrate\n  | IRealmFramePatches\n  | IRealmFrameWrite\n  | IRealmFrameIntent\n  | IRealmFrameAck\n  | IRealmFrameReject\n  | IRealmFrameKeyDict\n  | IRealmFrameDetach\n  | IRealmFrameClientCaps\n  | IRealmFrameBatch;\n","import { pack, unpack } from \"msgpackr\";\nimport { err_realm } from \"../RealmDefinition/errors/err_realm\";\nimport type { TWirePathSegment } from \"../RealmDefinition/Schema/tokenMap\";\nimport type {\n  IRealmFrameAck,\n  IRealmFrameClientCaps,\n  IRealmFrameDetach,\n  IRealmFrameHello,\n  IRealmFrameHydrate,\n  IRealmFrameIntent,\n  IRealmFrameKeyDict,\n  IRealmFramePatches,\n  IRealmFrameReject,\n  IRealmFrameWrite,\n  TRealmFrame,\n  TWireOp,\n} from \"./realmFrame.types\";\nimport { REALM_FRAME_KIND, REALM_OP } from \"./realmFrame.types\";\n\n/**\n * The realm frame codec: encode side builds each frame's msgpack fixarray; decode\n * side strictly validates shape and rejects with a typed `err_realm.frame_invalid` — garbage bytes\n * never throw-through as raw msgpackr/TypeErrors into the engines (the fuzz gate).\n */\n\nfunction invalid(reason: string): never {\n  throw err_realm.fromId(\"frame_invalid\", { reason });\n}\n\nfunction expectInt(value: unknown, what: string): number {\n  if (typeof value !== \"number\" || !Number.isInteger(value)) invalid(`${what} must be an int`);\n  return value;\n}\n\nfunction expectString(value: unknown, what: string): string {\n  if (typeof value !== \"string\") invalid(`${what} must be a string`);\n  return value;\n}\n\nfunction expectSlot(value: unknown): number {\n  const slot = expectInt(value, \"slot\");\n  if (slot < 0 || slot > 0xff) invalid(`slot ${slot} out of range`);\n  return slot;\n}\n\nfunction expectPath(value: unknown): TWirePathSegment[] {\n  if (!Array.isArray(value) || value.length === 0) invalid(\"op path must be a non-empty array\");\n  for (const seg of value) {\n    if (typeof seg === \"number\") {\n      if (!Number.isInteger(seg) || seg < 0) invalid(`invalid path token ${seg}`);\n    } else if (typeof seg !== \"string\") {\n      invalid(\"path segments must be ints or strings\");\n    }\n  }\n  return value as TWirePathSegment[];\n}\n\nfunction expectOps(value: unknown): TWireOp[] {\n  if (!Array.isArray(value)) invalid(\"ops must be an array\");\n  for (const op of value) {\n    if (!Array.isArray(op) || op.length < 2 || op.length > 3) invalid(\"malformed op\");\n    const kind = expectInt(op[0], \"op kind\");\n    if (kind !== REALM_OP.replace && kind !== REALM_OP.add && kind !== REALM_OP.remove) {\n      invalid(`unknown op kind ${kind}`);\n    }\n    expectPath(op[1]);\n    if (kind === REALM_OP.remove && op.length !== 2) invalid(\"remove op carries no value\");\n    if (kind !== REALM_OP.remove && op.length !== 3) invalid(\"replace/add op requires a value\");\n  }\n  return value as TWireOp[];\n}\n\nfunction expectLimits(\n  value: unknown,\n): [maxPatchesPerFrame: number, maxFrameBytes: number, writeRatePerSecond: number] {\n  if (!Array.isArray(value) || value.length !== 3) invalid(\"hydrate limits must be 3 ints\");\n  expectInt(value[0], \"limits.maxPatchesPerFrame\");\n  expectInt(value[1], \"limits.maxFrameBytes\");\n  expectInt(value[2], \"limits.writeRatePerSecond\");\n  return value as [number, number, number];\n}\n\nfunction expectAvatarEcho(\n  value: unknown,\n): [type: string, persistentId: string, instanceId: string] {\n  if (!Array.isArray(value) || value.length !== 3) invalid(\"hydrate avatar must be 3 strings\");\n  expectString(value[0], \"avatar.type\");\n  expectString(value[1], \"avatar.persistentId\");\n  expectString(value[2], \"avatar.instanceId\");\n  return value as [string, string, string];\n}\n\n/** Hard caps on the capability advertisement — `clientCaps` is processed BEFORE the engine's\n * ingress limits (it is pre-rate-limit bookkeeping), so the codec itself must bound it. */\nconst MAX_CLIENT_CAPS_FEATURES = 16;\nconst MAX_CLIENT_CAPS_FEATURE_LENGTH = 32;\n\nfunction expectFeatures(value: unknown): string[] {\n  if (!Array.isArray(value)) invalid(\"clientCaps features must be an array\");\n  if (value.length > MAX_CLIENT_CAPS_FEATURES) invalid(\"clientCaps features list too long\");\n  for (const feature of value) {\n    if (expectString(feature, \"clientCaps feature\").length > MAX_CLIENT_CAPS_FEATURE_LENGTH) {\n      invalid(\"clientCaps feature too long\");\n    }\n  }\n  return value as string[];\n}\n\nfunction expectDictEntries(value: unknown): [string, number][] {\n  if (!Array.isArray(value)) invalid(\"keyDict entries must be an array\");\n  for (const entry of value) {\n    if (!Array.isArray(entry) || entry.length !== 2) invalid(\"malformed keyDict entry\");\n    expectString(entry[0], \"keyDict key\");\n    const id = expectInt(entry[1], \"keyDict id\");\n    if (id < 0) invalid(\"keyDict id must be >= 0\");\n  }\n  return value as [string, number][];\n}\n\n// ── Encoders ─────────────────────────────────────────────────────────────────\n\nexport function encodeHello(frame: Omit<IRealmFrameHello, \"kind\">): Uint8Array {\n  return pack([\n    REALM_FRAME_KIND.hello,\n    frame.slot,\n    frame.realmId,\n    frame.schemaHash,\n    frame.lastKnownVersion,\n    frame.epoch ?? null,\n  ]);\n}\n\nexport function encodeHydrate(frame: Omit<IRealmFrameHydrate, \"kind\">): Uint8Array {\n  return pack([\n    REALM_FRAME_KIND.hydrate,\n    frame.slot,\n    frame.version,\n    frame.stateBlob,\n    frame.keyDictSeed,\n    frame.more,\n    frame.epoch,\n    frame.limits,\n    frame.avatar,\n  ]);\n}\n\nexport function encodePatches(frame: Omit<IRealmFramePatches, \"kind\">): Uint8Array {\n  return pack([\n    REALM_FRAME_KIND.patches,\n    frame.slot,\n    frame.fromVersion,\n    frame.toVersion,\n    frame.ops,\n  ]);\n}\n\nexport function encodeWrite(frame: Omit<IRealmFrameWrite, \"kind\">): Uint8Array {\n  return pack([REALM_FRAME_KIND.write, frame.slot, frame.clientSeq, frame.basisVersion, frame.ops]);\n}\n\nexport function encodeIntent(frame: Omit<IRealmFrameIntent, \"kind\">): Uint8Array {\n  return pack([\n    REALM_FRAME_KIND.intent,\n    frame.slot,\n    frame.clientSeq,\n    frame.intentToken,\n    frame.input,\n  ]);\n}\n\nexport function encodeAck(frame: Omit<IRealmFrameAck, \"kind\">): Uint8Array {\n  return pack([REALM_FRAME_KIND.ack, frame.slot, frame.clientSeq, frame.version]);\n}\n\nexport function encodeReject(frame: Omit<IRealmFrameReject, \"kind\">): Uint8Array {\n  return pack([REALM_FRAME_KIND.reject, frame.slot, frame.clientSeq, frame.error]);\n}\n\nexport function encodeKeyDict(frame: Omit<IRealmFrameKeyDict, \"kind\">): Uint8Array {\n  return pack([REALM_FRAME_KIND.keyDict, frame.slot, frame.entries]);\n}\n\nexport function encodeDetach(frame: Omit<IRealmFrameDetach, \"kind\">): Uint8Array {\n  return pack([REALM_FRAME_KIND.detach, frame.slot, frame.reason ?? null]);\n}\n\nexport function encodeClientCaps(frame: Omit<IRealmFrameClientCaps, \"kind\">): Uint8Array {\n  return pack([REALM_FRAME_KIND.clientCaps, frame.slot, frame.features]);\n}\n\n/**\n * The egress envelope (Phase 1 wire). Takes **already-encoded** child frame bytes — the server\n * batches the exact frames it would otherwise send one at a time. The decoder re-inflates them into\n * `frames`, so encode/decode are deliberately asymmetric (bytes in, decoded frames out).\n */\nexport function encodeBatch(frame: { slot: number; payloads: Uint8Array[] }): Uint8Array {\n  return pack([REALM_FRAME_KIND.batch, frame.slot, frame.payloads]);\n}\n\n// ── Decoder ──────────────────────────────────────────────────────────────────\n\n/**\n * Decode one realm protocol payload (prefix already stripped by the mux). Throws\n * `err_realm.frame_invalid` on any malformed input — never a raw decode error.\n */\nexport function decodeRealmFrame(payload: Uint8Array): TRealmFrame {\n  let raw: unknown;\n  try {\n    raw = unpack(payload);\n  } catch {\n    invalid(\"not msgpack\");\n  }\n  if (!Array.isArray(raw) || raw.length < 2) invalid(\"frame must be a [kind, slot, …] array\");\n\n  const kind = expectInt(raw[0], \"kind\");\n  const slot = expectSlot(raw[1]);\n\n  switch (kind) {\n    case REALM_FRAME_KIND.hello: {\n      if (raw.length !== 6) invalid(\"hello must have 6 elements\");\n      if (raw[5] != null && typeof raw[5] !== \"string\") invalid(\"hello epoch must be a string\");\n      return {\n        kind,\n        slot,\n        realmId: expectString(raw[2], \"realmId\"),\n        schemaHash: expectString(raw[3], \"schemaHash\"),\n        lastKnownVersion: expectInt(raw[4], \"lastKnownVersion\"),\n        epoch: raw[5] ?? undefined,\n      };\n    }\n    case REALM_FRAME_KIND.hydrate: {\n      if (raw.length !== 9) invalid(\"hydrate must have 9 elements\");\n      if (!(raw[3] instanceof Uint8Array)) invalid(\"hydrate stateBlob must be bytes\");\n      if (typeof raw[5] !== \"boolean\") invalid(\"hydrate more must be a boolean\");\n      return {\n        kind,\n        slot,\n        version: expectInt(raw[2], \"version\"),\n        stateBlob: raw[3],\n        keyDictSeed: expectDictEntries(raw[4]),\n        more: raw[5],\n        epoch: expectString(raw[6], \"hydrate epoch\"),\n        limits: expectLimits(raw[7]),\n        avatar: expectAvatarEcho(raw[8]),\n      };\n    }\n    case REALM_FRAME_KIND.patches: {\n      if (raw.length !== 5) invalid(\"patches must have 5 elements\");\n      return {\n        kind,\n        slot,\n        fromVersion: expectInt(raw[2], \"fromVersion\"),\n        toVersion: expectInt(raw[3], \"toVersion\"),\n        ops: expectOps(raw[4]),\n      };\n    }\n    case REALM_FRAME_KIND.write: {\n      if (raw.length !== 5) invalid(\"write must have 5 elements\");\n      return {\n        kind,\n        slot,\n        clientSeq: expectInt(raw[2], \"clientSeq\"),\n        basisVersion: expectInt(raw[3], \"basisVersion\"),\n        ops: expectOps(raw[4]),\n      };\n    }\n    case REALM_FRAME_KIND.intent: {\n      if (raw.length !== 5) invalid(\"intent must have 5 elements\");\n      return {\n        kind,\n        slot,\n        clientSeq: expectInt(raw[2], \"clientSeq\"),\n        intentToken: expectInt(raw[3], \"intentToken\"),\n        input: raw[4],\n      };\n    }\n    case REALM_FRAME_KIND.ack: {\n      if (raw.length !== 4) invalid(\"ack must have 4 elements\");\n      return {\n        kind,\n        slot,\n        clientSeq: expectInt(raw[2], \"clientSeq\"),\n        version: expectInt(raw[3], \"version\"),\n      };\n    }\n    case REALM_FRAME_KIND.reject: {\n      if (raw.length !== 4) invalid(\"reject must have 4 elements\");\n      if (typeof raw[3] !== \"object\" || raw[3] == null || Array.isArray(raw[3])) {\n        invalid(\"reject error must be a map\");\n      }\n      return { kind, slot, clientSeq: expectInt(raw[2], \"clientSeq\"), error: raw[3] };\n    }\n    case REALM_FRAME_KIND.keyDict: {\n      if (raw.length !== 3) invalid(\"keyDict must have 3 elements\");\n      return { kind, slot, entries: expectDictEntries(raw[2]) };\n    }\n    case REALM_FRAME_KIND.detach: {\n      if (raw.length !== 3) invalid(\"detach must have 3 elements\");\n      if (raw[2] != null && typeof raw[2] !== \"string\") invalid(\"detach reason must be a string\");\n      return { kind, slot, reason: raw[2] ?? undefined };\n    }\n    case REALM_FRAME_KIND.clientCaps: {\n      if (raw.length !== 3) invalid(\"clientCaps must have 3 elements\");\n      return { kind, slot, features: expectFeatures(raw[2]) };\n    }\n    case REALM_FRAME_KIND.batch: {\n      if (raw.length !== 3) invalid(\"batch must have 3 elements\");\n      if (!Array.isArray(raw[2])) invalid(\"batch payloads must be an array\");\n      // The fuzz gate extends into the envelope: every child is decoded here (so a malformed child\n      // fails the whole batch, never throws-through downstream), and a nested batch is rejected —\n      // a batch is always a flat list of well-formed non-batch frames by the time it is returned.\n      const frames: TRealmFrame[] = [];\n      for (const payload of raw[2]) {\n        if (!(payload instanceof Uint8Array)) invalid(\"batch payload must be bytes\");\n        const child = decodeRealmFrame(payload);\n        if (child.kind === REALM_FRAME_KIND.batch) invalid(\"batch may not nest\");\n        frames.push(child);\n      }\n      return { kind, slot, frames };\n    }\n    default:\n      invalid(`unknown frame kind ${kind}`);\n  }\n}\n","/**\n * Prototype-pollution deny-list for dynamic record keys. Wire segments\n * become object keys in the state tree — on server apply and on client/replica projection. Three of\n * them are never legitimate `t.id()` record keys and are actively dangerous as object keys:\n *\n * - `__proto__` — assigning it can repoint an object's prototype (classic prototype pollution).\n * - `constructor` / `prototype` — shadow built-ins; a stepping stone to the same class of attack.\n *\n * A hostile client (server-side) or a hostile/replayed server frame (client-side) is the threat; a\n * well-behaved peer never produces these, so the deny-list is a pure no-op in practice (a golden\n * asserts the reference schema uses none of them as field names either). One predicate, every path —\n * the server rejects the frame, the client/replica drops the offending patch.\n */\n\nconst UNSAFE_KEYS: ReadonlySet<string> = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\n/** True when a decoded path segment is a prototype-pollution vector. */\nexport function isUnsafeKey(segment: unknown): boolean {\n  return typeof segment === \"string\" && UNSAFE_KEYS.has(segment);\n}\n\n/** True when any segment of a decoded (name) path is unsafe — the per-path screen for both sides. */\nexport function pathHasUnsafeKey(path: readonly unknown[]): boolean {\n  return path.some(isUnsafeKey);\n}\n\n/**\n * True when a patch **value** carries an unsafe own key anywhere in its object/array tree. A coarse\n * write/intent that creates a whole record entry emits the entry as one patch whose *value* holds\n * the dynamic keys (they never appear in the patch path), so the path screen alone would miss them.\n * Own keys only (`Object.entries`), so an inherited `constructor` is not falsely flagged; a decoded\n * own `__proto__` (e.g. from `JSON.parse`/msgpack) is. Values are schema-bounded, so the recursion\n * is bounded.\n */\nexport function valueHasUnsafeKey(value: unknown): boolean {\n  if (value == null || typeof value !== \"object\") return false;\n  if (Array.isArray(value)) return value.some(valueHasUnsafeKey);\n  for (const [key, child] of Object.entries(value)) {\n    if (isUnsafeKey(key) || valueHasUnsafeKey(child)) return true;\n  }\n  return false;\n}\n","import type { Patch } from \"immer\";\nimport type { TSchemaNode, TSchemaRoot } from \"../RealmDefinition/Schema/schema.types\";\nimport type { RealmTokenMap } from \"../RealmDefinition/Schema/tokenMap\";\nimport type { TRealmOpKind, TWireOp } from \"./realmFrame.types\";\nimport { REALM_OP } from \"./realmFrame.types\";\n\n/**\n * Immer patches ↔ realm wire ops. Wire ops always use **name-space string paths**\n * tokenized through the realm's token map; immer patches on realm state only ever contain string\n * segments *except* inside arrays — and arrays are leaf-replace-only on the wire (proposal §7.8),\n * so {@link canonicalizeStatePatches} lifts any array-interior patch to a whole-array `replace`\n * before encoding.\n */\n\nconst IMMER_OP_TO_WIRE: Record<Patch[\"op\"], TRealmOpKind> = {\n  replace: REALM_OP.replace,\n  add: REALM_OP.add,\n  remove: REALM_OP.remove,\n};\n\nconst WIRE_OP_TO_IMMER: Record<TRealmOpKind, Patch[\"op\"]> = {\n  [REALM_OP.replace]: \"replace\",\n  [REALM_OP.add]: \"add\",\n  [REALM_OP.remove]: \"remove\",\n};\n\nfunction unwrapOptional(node: TSchemaNode): TSchemaNode {\n  return node.kind === \"optional\" ? unwrapOptional(node.inner) : node;\n}\n\n/** The schema node a name path addresses (undefined when the path leaves the schema). */\nexport function schemaNodeAtPath(\n  root: TSchemaRoot,\n  path: readonly (string | number)[],\n): TSchemaNode | undefined {\n  let node: TSchemaNode | undefined;\n  let entries: Record<string, TSchemaNode> | undefined = root;\n  for (const seg of path) {\n    if (entries != null) {\n      node = typeof seg === \"string\" ? entries[seg] : undefined;\n      entries = undefined;\n    } else if (node != null) {\n      const inner = unwrapOptional(node);\n      if (inner.kind === \"object\") node = inner.entries[seg as string];\n      else if (inner.kind === \"record\") node = inner.value;\n      else return undefined;\n    }\n    if (node == null) return undefined;\n  }\n  return node;\n}\n\nfunction getAtPath(state: unknown, path: readonly (string | number)[]): unknown {\n  let current: unknown = state;\n  for (const seg of path) {\n    if (current == null || typeof current !== \"object\") return undefined;\n    current = (current as Record<string | number, unknown>)[seg];\n  }\n  return current;\n}\n\n/** The path-prefix length up to (and including) the first array node, or `undefined` if none. */\nfunction arrayCutIndex(root: TSchemaRoot, path: readonly (string | number)[]): number | undefined {\n  for (let i = 1; i < path.length; i++) {\n    const node = schemaNodeAtPath(root, path.slice(0, i));\n    if (node != null && unwrapOptional(node).kind === \"array\") return i;\n  }\n  return undefined;\n}\n\n/**\n * Normalize immer patches for the wire: any patch *inside* an array node is lifted to a single\n * whole-array `replace` (value read from the post-mutation state), and duplicate lifts of the\n * same array collapse. All surviving paths are pure string name paths.\n */\nexport function canonicalizeStatePatches(\n  patches: readonly Patch[],\n  stateAfter: unknown,\n  schemaRoot: TSchemaRoot,\n): Patch[] {\n  const out: Patch[] = [];\n  const liftedArrays = new Set<string>();\n  for (const patch of patches) {\n    const cut = arrayCutIndex(schemaRoot, patch.path);\n    if (cut == null || cut === patch.path.length) {\n      out.push(patch);\n      continue;\n    }\n    const arrayPath = patch.path.slice(0, cut) as string[];\n    const key = arrayPath.join(\"\\0\");\n    if (liftedArrays.has(key)) continue;\n    liftedArrays.add(key);\n    out.push({ op: \"replace\", path: arrayPath, value: getAtPath(stateAfter, arrayPath) });\n  }\n  return out;\n}\n\n/**\n * Conflate an ORDERED run of authoritative patch ops to the shortest final-state-equivalent run\n *. Used for replay: a reconnect inside the log window merges\n * every missed version's ops, which for a 60 Hz cursor is ~1000 dead intermediate positions in one\n * frame. Server→client ops are absolute-value ops (`add`/`replace` carry the whole subtree; `remove`\n * deletes it), so a later op at path `P` makes every earlier op AT `P` OR UNDER `P` redundant — the\n * later op overwrites/removes that whole subtree. One pass, evicting each new op's covered\n * predecessors and keeping everything else IN PLACE:\n *\n *   - a later op at `P` evicts earlier ops at `P` or a descendant of `P` (covered — dropped);\n *   - an earlier op at an ANCESTOR of `P` is kept, in place (it built the container `P` mutates —\n *     dropping it would orphan `P`);\n *   - unrelated ops are kept.\n *\n * Survivors keep their relative order, so the result is a **subsequence** of the input: on any base\n * where the raw run applies cleanly (i.e. every replay base — the server applied it), the conflated\n * run applies cleanly to the same final state.\n *\n * This is deliberately NOT the client's exact-path `dedupeByPath` (RealmClient) — that keeps only the\n * last write per *identical* path, which is right for a client's own single-leaf write stream but\n * would leave a stale `players.alice.x` beside a later whole-`players.alice` replace. Conflation is\n * subtree-aware; dedupe is not.\n */\nexport function conflateOps(ops: readonly Patch[]): Patch[] {\n  const result: Patch[] = [];\n  for (const op of ops) {\n    // Walk backwards so splices don't shift indices we have yet to test.\n    for (let i = result.length - 1; i >= 0; i--) {\n      if (isPathPrefix(op.path, result[i].path)) result.splice(i, 1);\n    }\n    result.push(op);\n  }\n  return result;\n}\n\n/** `prefix ⊑ path`: `path` equals `prefix` or is a descendant of it (segment-wise). */\nfunction isPathPrefix(\n  prefix: readonly (string | number)[],\n  path: readonly (string | number)[],\n): boolean {\n  if (prefix.length > path.length) return false;\n  for (let i = 0; i < prefix.length; i++) {\n    if (prefix[i] !== path[i]) return false;\n  }\n  return true;\n}\n\n/** Name-space immer patches → wire ops (encode side). */\nexport function namePatchesToWireOps(\n  patches: readonly Patch[],\n  tokens: RealmTokenMap,\n  internKey?: (key: string) => number | undefined,\n): TWireOp[] {\n  return patches.map((patch) => {\n    const path = tokens.tokenizePath(patch.path as string[], internKey);\n    if (patch.op === \"remove\") return [REALM_OP.remove, path];\n    return [IMMER_OP_TO_WIRE[patch.op], path, patch.value];\n  });\n}\n\n/** Wire ops → name-space immer patches (decode side). */\nexport function wireOpsToNamePatches(\n  ops: readonly TWireOp[],\n  tokens: RealmTokenMap,\n  resolveKey?: (id: number) => string | undefined,\n): Patch[] {\n  return ops.map((op) => {\n    const path = tokens.detokenizePath(op[1], resolveKey);\n    if (op[0] === REALM_OP.remove) return { op: \"remove\", path };\n    return { op: WIRE_OP_TO_IMMER[op[0]], path, value: op[2] };\n  });\n}\n","import type { NiceError } from \"@nice-code/error\";\nimport { ESecurityLevel, securityLevelMeets } from \"@nice-code/wire\";\nimport type { TRealmSecurityLevel } from \"../RealmDefinition/defineRealm\";\nimport { err_realm } from \"../RealmDefinition/errors/err_realm\";\n\n/**\n * The client-side security floor. The server's attach gate stops\n * *routing* an under-secured avatar — it does NOT stop this client from *sending*. So only this\n * local check keeps avatar identity/state from leaving the device as app-layer plaintext when a\n * realm marked `security: \"encrypted\"` is connected over an `authenticated` link (a misconfigured\n * client). It runs **before the first `hello`**, and a shortfall blocks every realm frame, `hello`\n * included.\n *\n * Shared by {@link connectRealm} and {@link connectRealmReplica} so the two connect paths can't\n * drift — the replica is the highest-value leak (an \"everything\" view of the realm) and a wholly\n * separate code path.\n */\n\n/** Map the realm-local policy level to the wire enum for ranking (no `as`, per the code guide). */\nfunction realmLevelToWire(level: TRealmSecurityLevel): ESecurityLevel {\n  return level === \"encrypted\" ? ESecurityLevel.encrypted : ESecurityLevel.authenticated;\n}\n\n/**\n * The effective client minimum = the higher of the realm's declared floor and an optional\n * per-connect override. The override can only *raise* the bar (checking against `realm.security`\n * alone would silently ignore a caller asking for more — Phase 4.2). The server enforces its own\n * floor independently.\n */\nfunction effectiveClientMinimum(\n  realmSecurity: TRealmSecurityLevel,\n  connectOverride?: TRealmSecurityLevel,\n): TRealmSecurityLevel {\n  if (connectOverride == null) return realmSecurity;\n  return realmSecurity === \"encrypted\" || connectOverride === \"encrypted\"\n    ? \"encrypted\"\n    : \"authenticated\";\n}\n\n/**\n * Returns the `insufficient_security` reject error when the connection's negotiated level is below\n * the effective client minimum (`max(realm.security, connectOverride)`), or `undefined` to proceed.\n *\n * A bare-mux adapter (a test loopback) reports **no** level → the check is skipped: the level is\n * unknown, and production always attaches through a `ChannelConnector`, which carries one (Phase\n * 4.2). Callers apply the detach themselves (set `attachError`, status `detached`, skip `hello`) —\n * the *check* lives here so it can't diverge between the two connect paths.\n */\nexport function computeRealmSecurityShortfall(\n  adapter: { securityLevel?: ESecurityLevel },\n  realm: { id: string; security: TRealmSecurityLevel },\n  connectOverride?: TRealmSecurityLevel,\n): NiceError<any, any> | undefined {\n  const actual = adapter.securityLevel;\n  if (actual == null) return undefined; // mux-only source — unknown level, skip (documented)\n  const required = realmLevelToWire(effectiveClientMinimum(realm.security, connectOverride));\n  if (securityLevelMeets(actual, required)) return undefined;\n  return err_realm.fromId(\"insufficient_security\", {\n    realmId: realm.id,\n    required,\n    actual,\n  });\n}\n","import type { Patch } from \"immer\";\n\n/**\n * Structural diff between two projections: the generic version of what imperative\n * renderers used to hand-roll per consumer (the pixel demo's 40-line identity-gated record\n * diff). Immer's structural sharing makes it cheap: an unchanged subtree keeps its reference\n * across `applyPatches`/rebase, so `prev === next` prunes it in O(1) — the walk only descends\n * where something actually changed.\n *\n * Semantics match the realm's canonical patch shape: plain objects/records diff per key\n * (`add`/`remove`/recurse); everything else — primitives, arrays (already canonicalized to\n * whole-array replaces on the wire), type changes — is a leaf `replace`.\n */\nexport function diffProjected(prev: unknown, next: unknown, path: string[] = []): Patch[] {\n  if (prev === next) return [];\n  if (!isPlainRecord(prev) || !isPlainRecord(next)) {\n    return [{ op: \"replace\", path: [...path], value: next }];\n  }\n\n  const patches: Patch[] = [];\n  for (const key of Object.keys(next)) {\n    if (key in prev) {\n      patches.push(...diffProjected(prev[key], next[key], [...path, key]));\n    } else {\n      patches.push({ op: \"add\", path: [...path, key], value: next[key] });\n    }\n  }\n  for (const key of Object.keys(prev)) {\n    if (!(key in next)) patches.push({ op: \"remove\", path: [...path, key] });\n  }\n  return patches;\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === \"object\" && value != null && !Array.isArray(value);\n}\n","import type {\n  IAlterRuleContext,\n  IViewAvatarRef,\n  IViewRuleContext,\n  TAlterCond,\n  TRuleVerdict,\n  TViewCond,\n} from \"./rules.types\";\n\n/**\n * Rule-condition evaluation — isomorphic by design: the server runs the full\n * pipeline; client-side prediction runs the same functions with `serverExtras` absent, which makes\n * every `r.serverChecked` part auto-pass (exactly the slice of optimism that can roll back).\n *\n * View conditions are coordinate-only in v1 and **must not depend on `avatar.instanceId`** — the\n * server groups per-view-signature encodes by `(type, persistentId)` (multi-tab clients share a\n * slice), so an instanceId-dependent view rule would silently mis-slice.\n */\n\nexport interface IServerRuleExtras<TCtx = unknown> {\n  ctx: TCtx;\n  /** Log-backed CAS helper for the leaf under evaluation. */\n  touchedSince(basisVersion: number): boolean;\n}\n\nexport function evalViewCond<TAvatarType extends string>(\n  cond: TViewCond<TAvatarType, any>,\n  context: IViewRuleContext<TAvatarType, Record<string, string>>,\n): boolean {\n  if (typeof cond === \"function\") return cond(context);\n  if (cond.kind === \"everyone\") return true;\n  return cond.types.includes(context.avatar.type);\n}\n\n/**\n * Evaluate an alter condition for an **avatar** write. Returns the rule verdict, or the sentinel\n * `\"serverOnly\"` when the path is not avatar-writable at all (callers map it to\n * `err_realm.unauthorized_coordinate`). Prediction passes `serverExtras: undefined`.\n */\nexport function evalAlterCond<TAvatarType extends string, TState, TCtx>(\n  cond: TAlterCond<TAvatarType, any, any, TState, TCtx>,\n  context: IAlterRuleContext<TAvatarType, Record<string, string>, unknown, TState>,\n  serverExtras: IServerRuleExtras<TCtx> | undefined,\n): TRuleVerdict | \"serverOnly\" {\n  if (typeof cond === \"function\") return cond(context);\n  switch (cond.kind) {\n    case \"serverOnly\":\n      return \"serverOnly\";\n    case \"serverChecked\":\n      if (serverExtras == null) return true; // prediction auto-passes\n      return cond.fn({ ...context, ...serverExtras });\n    case \"all\": {\n      for (const part of cond.conds) {\n        const verdict = evalAlterCond(part, context, serverExtras);\n        if (verdict !== true) return verdict;\n      }\n      return true;\n    }\n  }\n}\n\n/** The slicer's signature-group key — view rules may not read `instanceId` (see module doc). */\nexport function viewSignatureKey(avatar: IViewAvatarRef): string {\n  return `${avatar.type}\\0${avatar.persistentId}`;\n}\n","import type { TSchemaNode, TSchemaRoot } from \"../RealmDefinition/Schema/schema.types\";\nimport { schemaNodeAtPath } from \"../RealmWire/wirePatch\";\n\n/**\n * Subtree-write expansion: an object-valued patch — including a\n * whole record-entry `add`/`remove` — expands to **every leaf path it covers**, and the write\n * passes only if every covered leaf's own most-specific rule passes. Creation is just the first\n * write; deletion is a `remove` through the same gate; rules never need \"create\" clauses.\n *\n * For `add`/`replace`, dynamic record keys are enumerated from the written value **and** the\n * current state at that path (a whole-record replace also removes entries the value omits — those\n * leaves are covered too). For `remove`, from the current state alone. Expansion is bounded by\n * `maxLeaves` (an ingress limit — a hostile deep-subtree write must not become CPU).\n */\n\nfunction unwrapOptional(node: TSchemaNode): TSchemaNode {\n  return node.kind === \"optional\" ? unwrapOptional(node.inner) : node;\n}\n\nfunction getAtPath(state: unknown, path: readonly string[]): unknown {\n  let current: unknown = state;\n  for (const seg of path) {\n    if (current == null || typeof current !== \"object\") return undefined;\n    current = (current as Record<string, unknown>)[seg];\n  }\n  return current;\n}\n\nexport class ExpansionOverflowError extends Error {\n  constructor(max: number) {\n    super(`subtree write expands past the ${max}-leaf limit`);\n  }\n}\n\nexport function expandWriteToLeaves(options: {\n  schemaRoot: TSchemaRoot;\n  path: readonly string[];\n  op: \"add\" | \"replace\" | \"remove\";\n  /** The written value (`undefined` for `remove`). */\n  value: unknown;\n  /** Current authoritative (server) or projected (client-prediction) state. */\n  state: unknown;\n  maxLeaves: number;\n}): string[][] {\n  const node = schemaNodeAtPath(options.schemaRoot, options.path);\n  if (node == null) {\n    throw new Error(`expandWriteToLeaves: path leaves the schema (${options.path.join(\".\")})`);\n  }\n  const leaves: string[][] = [];\n  const push = (leaf: string[]): void => {\n    if (leaves.length >= options.maxLeaves) throw new ExpansionOverflowError(options.maxLeaves);\n    leaves.push(leaf);\n  };\n\n  const walk = (schemaNode: TSchemaNode, path: string[], value: unknown, prev: unknown): void => {\n    const inner = unwrapOptional(schemaNode);\n    if (inner.kind === \"object\") {\n      for (const [key, child] of Object.entries(inner.entries)) {\n        walk(\n          child,\n          [...path, key],\n          value == null ? undefined : (value as Record<string, unknown>)[key],\n          prev == null ? undefined : (prev as Record<string, unknown>)[key],\n        );\n      }\n      return;\n    }\n    if (inner.kind === \"record\") {\n      const keys = new Set<string>();\n      if (value != null && typeof value === \"object\") {\n        for (const key of Object.keys(value)) keys.add(key);\n      }\n      if (prev != null && typeof prev === \"object\") {\n        for (const key of Object.keys(prev)) keys.add(key);\n      }\n      for (const key of keys) {\n        walk(\n          inner.value,\n          [...path, key],\n          value == null ? undefined : (value as Record<string, unknown>)[key],\n          prev == null ? undefined : (prev as Record<string, unknown>)[key],\n        );\n      }\n      return;\n    }\n    // Leaf (string/number/boolean/literal/union/array/standard): one covered rule check.\n    push(path);\n  };\n\n  const prev = getAtPath(options.state, options.path);\n  walk(node, [...options.path], options.op === \"remove\" ? undefined : options.value, prev);\n  return leaves;\n}\n","import type { Patch } from \"immer\";\nimport type { IRealmDefinition } from \"../RealmDefinition/defineRealm\";\nimport { err_realm } from \"../RealmDefinition/errors/err_realm\";\nimport { evalAlterCond } from \"../RealmDefinition/Rules/evalRules\";\nimport type { IRealmAvatarRef, TRuleVerdict } from \"../RealmDefinition/Rules/rules.types\";\nimport { validateValue } from \"../RealmDefinition/Schema/validateValue\";\nimport { expandWriteToLeaves } from \"../RealmServer/expandWrite\";\nimport { schemaNodeAtPath } from \"../RealmWire/wirePatch\";\n\n/**\n * Client-side write prediction: the same expansion + rule pipeline the server\n * runs, minus everything server-only — `r.serverChecked` parts auto-pass (that is exactly the\n * slice of optimism that can later roll back), `prev`/`state` come from the writer's projected\n * view. A NiceError here rejects the write in the same tick, before anything renders.\n */\nfunction getProjectedAtPath(state: unknown, path: readonly string[]): unknown {\n  let current: unknown = state;\n  for (const seg of path) {\n    if (current == null || typeof current !== \"object\") return undefined;\n    current = (current as Record<string, unknown>)[seg];\n  }\n  return current;\n}\n\nexport function predictWrite(options: {\n  realm: IRealmDefinition<any, any, any, any, any>;\n  patches: readonly Patch[];\n  avatar: IRealmAvatarRef;\n  /** The projected view the write was composed against. */\n  state: object;\n  basisVersion: number;\n}): TRuleVerdict {\n  const { realm, avatar, state, basisVersion } = options;\n  for (const patch of options.patches) {\n    const path = patch.path as string[];\n    const node = schemaNodeAtPath(realm.stateDef, path);\n    if (node == null) {\n      return err_realm.fromId(\"value_invalid\", {\n        path: path.join(\".\"),\n        expected: \"a schema path\",\n      });\n    }\n    if (patch.op !== \"remove\") {\n      const invalid = validateValue(node, patch.value);\n      if (invalid != null) {\n        return err_realm.fromId(\"value_invalid\", {\n          path: [...path, ...invalid.path].join(\".\"),\n          expected: invalid.expected,\n        });\n      }\n      // Record-cardinality preview against the projected view (fast same-tick feedback). A sliced\n      // view can HIDE entries, so this is optimistic only — the server's candidate-state gate\n      // stays authoritative and may still reject, rolling the prediction back.\n      for (let i = 1; i < path.length; i++) {\n        let ancestor = schemaNodeAtPath(realm.stateDef, path.slice(0, i));\n        while (ancestor?.kind === \"optional\") ancestor = ancestor.inner;\n        if (ancestor?.kind !== \"record\" || ancestor.maxKeys == null) continue;\n        const container = getProjectedAtPath(state, path.slice(0, i));\n        if (container == null || typeof container !== \"object\" || Array.isArray(container)) {\n          continue;\n        }\n        const entryKey = path[i];\n        if (!(entryKey in container) && Object.keys(container).length >= ancestor.maxKeys) {\n          return err_realm.fromId(\"value_invalid\", {\n            path: path.slice(0, i).join(\".\"),\n            expected: `a record with at most ${ancestor.maxKeys} entries`,\n          });\n        }\n      }\n    }\n    const leaves = expandWriteToLeaves({\n      schemaRoot: realm.stateDef,\n      path,\n      op: patch.op,\n      value: patch.value,\n      state,\n      maxLeaves: Number.POSITIVE_INFINITY,\n    });\n    for (const leafPath of leaves) {\n      const match = realm.ruleTrie.match(leafPath);\n      if (match == null) {\n        return err_realm.fromId(\"unauthorized_coordinate\", { path: leafPath.join(\".\") });\n      }\n      const rel = leafPath.slice(path.length);\n      const verdict = evalAlterCond(\n        match.rule.alter,\n        {\n          avatar,\n          params: match.params,\n          prev: getAtPath(state, leafPath),\n          next: patch.op === \"remove\" ? undefined : getAtPath(patch.value, rel),\n          state,\n          basisVersion,\n        },\n        undefined, // prediction: serverChecked auto-passes\n      );\n      if (verdict === \"serverOnly\") {\n        return err_realm.fromId(\"unauthorized_coordinate\", { path: leafPath.join(\".\") });\n      }\n      if (verdict !== true) return verdict;\n    }\n  }\n  return true;\n}\n\nfunction getAtPath(state: unknown, path: readonly string[]): unknown {\n  let current: unknown = state;\n  for (const seg of path) {\n    if (current == null || typeof current !== \"object\") return undefined;\n    current = (current as Record<string, unknown>)[seg];\n  }\n  return current;\n}\n","import type { Patch } from \"immer\";\nimport type { TSchemaNode, TSchemaRoot } from \"../RealmDefinition/Schema/schema.types\";\nimport { schemaNodeAtPath } from \"../RealmWire/wirePatch\";\n\n/**\n * Defense-in-depth for the confirmed-apply path: interleave synthetic `add <prefix> = {}` patches\n * so every inbound `add`/`replace` finds its **structural** parents. A slice may legitimately lack\n * a fixed container the schema declares (an empty nested record omitted by an older server, or a\n * container whose position only deeper exact rules cover) — immer's `applyPatches` would then\n * throw `path doesn't resolve` on the child patch, far from the cause. Fixed containers are\n * structural (the schema ships to every client), so synthesizing an empty shell reveals nothing.\n *\n * It deliberately does NOT synthesize a missing **dynamic record entry**: a missing\n * entry means a missed `add <entry> = {…}`, and fabricating a `{}` shell would produce a silent\n * partial entry (missing the add's fields) that persists until the next reconnect. There, the\n * throw is the right outcome — the Phase-3 inbound wrap turns it into a resync that re-fetches the\n * whole entry from authority.\n */\nexport function withStructuralParents(\n  state: object,\n  patches: Patch[],\n  schemaRoot: TSchemaRoot,\n): Patch[] {\n  let out: Patch[] | undefined;\n  for (let index = 0; index < patches.length; index++) {\n    const patch = patches[index];\n    if (patch.op !== \"remove\" && patch.path.length > 1) {\n      for (let depth = 1; depth < patch.path.length; depth++) {\n        const prefix = patch.path.slice(0, depth);\n        if (prefixResolves(state, out ?? patches.slice(0, index), prefix)) continue;\n        // A missing DYNAMIC RECORD ENTRY (a prefix whose parent schema node is a record) is a\n        // missed `add <entry> = {…}`, not absent structure — fabricating a `{}` shell here would\n        // silently produce a PARTIAL entry (missing every field the add carried) with no error\n        //. Stop synthesizing: let `applyPatches` throw so the Phase-3 wrap resyncs and\n        // the server re-sends the whole entry. Fixed-key containers below are still synthesized.\n        const parentNode =\n          depth === 1 ? undefined : schemaNodeAtPath(schemaRoot, prefix.slice(0, -1));\n        if (parentNode != null && unwrapOptional(parentNode).kind === \"record\") break;\n        const node = schemaNodeAtPath(schemaRoot, prefix);\n        if (node == null) break; // off-schema — let applyPatches surface it\n        const kind = unwrapOptional(node).kind;\n        if (kind !== \"object\" && kind !== \"record\") break;\n        out ??= patches.slice(0, index);\n        out.push({ op: \"add\", path: prefix, value: {} });\n      }\n    }\n    out?.push(patch);\n  }\n  return out ?? patches;\n}\n\n/** Whether `prefix` resolves in `state` as already patched by the `earlier` batch entries. */\nfunction prefixResolves(\n  state: object,\n  earlier: readonly Patch[],\n  prefix: readonly (string | number)[],\n): boolean {\n  // The last earlier patch at (or above) the prefix decides — its value replaced that subtree.\n  for (let i = earlier.length - 1; i >= 0; i--) {\n    const patch = earlier[i];\n    if (patch.path.length > prefix.length) continue;\n    if (!patch.path.every((seg, j) => String(seg) === String(prefix[j]))) continue;\n    if (patch.op === \"remove\") return false;\n    return getAtPath(patch.value, prefix.slice(patch.path.length)) !== undefined;\n  }\n  return getAtPath(state, prefix) !== undefined;\n}\n\nfunction unwrapOptional(node: TSchemaNode): TSchemaNode {\n  return node.kind === \"optional\" ? unwrapOptional(node.inner) : node;\n}\n\nfunction getAtPath(value: unknown, path: readonly (string | number)[]): unknown {\n  let current: unknown = value;\n  for (const seg of path) {\n    if (current == null || typeof current !== \"object\") return undefined;\n    current = (current as Record<string | number, unknown>)[seg];\n  }\n  return current;\n}\n","import type { NiceError } from \"@nice-code/error\";\n\n/**\n * The settle handle every realm write API returns: status + a **lazy thenable**.\n * The real promise materializes only when `.then`/`await` is used, so fire-and-forget writes\n * (cursor moves) never produce unhandled-rejection noise — while rejections always still reach\n * `onMutationRejected`. Await resolves `{ version }` with the read-your-writes guarantee (the ack\n * is ordered after the authoritative patches ≤ its version).\n */\n\nexport type TRealmWriteStatus = \"pending\" | \"confirmed\" | \"rejected\";\n\nexport interface IRealmWriteSettled {\n  version: number;\n}\n\nexport interface IRealmWriteHandle extends PromiseLike<IRealmWriteSettled> {\n  readonly status: TRealmWriteStatus;\n  /** The hydratable rejection when `status === \"rejected\"`. */\n  readonly error: NiceError<any, any> | undefined;\n}\n\nexport interface IWriteHandleController {\n  handle: IRealmWriteHandle;\n  confirm(settled: IRealmWriteSettled): void;\n  reject(error: NiceError<any, any>): void;\n}\n\nexport function createWriteHandle(): IWriteHandleController {\n  let status: TRealmWriteStatus = \"pending\";\n  let settled: IRealmWriteSettled | undefined;\n  let error: NiceError<any, any> | undefined;\n  let promise: Promise<IRealmWriteSettled> | undefined;\n  let resolvePromise: ((value: IRealmWriteSettled) => void) | undefined;\n  let rejectPromise: ((reason: unknown) => void) | undefined;\n\n  const materialize = (): Promise<IRealmWriteSettled> => {\n    if (promise == null) {\n      if (status === \"confirmed\" && settled != null) {\n        promise = Promise.resolve(settled);\n      } else if (status === \"rejected\") {\n        promise = Promise.reject(error);\n      } else {\n        promise = new Promise((resolve, reject) => {\n          resolvePromise = resolve;\n          rejectPromise = reject;\n        });\n      }\n    }\n    return promise;\n  };\n\n  const handle: IRealmWriteHandle = {\n    get status() {\n      return status;\n    },\n    get error() {\n      return error;\n    },\n    // biome-ignore lint/suspicious/noThenProperty: the lazy thenable IS the design — awaitable settle without eager promise allocation for fire-and-forget writes\n    then: (onFulfilled, onRejected) => materialize().then(onFulfilled, onRejected),\n  };\n\n  return {\n    handle,\n    confirm(value) {\n      if (status !== \"pending\") return;\n      status = \"confirmed\";\n      settled = value;\n      resolvePromise?.(value);\n    },\n    reject(reason) {\n      if (status !== \"pending\") return;\n      status = \"rejected\";\n      error = reason;\n      rejectPromise?.(reason);\n    },\n  };\n}\n","import { castNiceError, type NiceError } from \"@nice-code/error\";\nimport { Store } from \"@nice-code/state\";\nimport { unrefTimer } from \"@nice-code/util\";\nimport type { ESecurityLevel, IRuntimeCoordinate } from \"@nice-code/wire\";\nimport { applyPatches, enablePatches, type Patch, produceWithPatches } from \"immer\";\nimport { unpack } from \"msgpackr\";\nimport type {\n  IRealmDefinition,\n  TInferAvatarView,\n  TRealmSecurityLevel,\n} from \"../RealmDefinition/defineRealm\";\nimport { err_realm } from \"../RealmDefinition/errors/err_realm\";\nimport type { IRealmIntentDef } from \"../RealmDefinition/Intents/intents.types\";\nimport type { IRealmAvatarRef } from \"../RealmDefinition/Rules/rules.types\";\nimport type { TInferNode } from \"../RealmDefinition/Schema/schema.types\";\nimport { validateValue } from \"../RealmDefinition/Schema/validateValue\";\nimport { RealmKeyDict } from \"../RealmWire/keyDict\";\nimport type { TRealmFrame } from \"../RealmWire/realmFrame.types\";\nimport {\n  REALM_DETACH_REASON_REHELLO,\n  REALM_FEATURE,\n  REALM_FRAME_KIND,\n  REALM_FRAME_KIND_NAME,\n} from \"../RealmWire/realmFrame.types\";\nimport {\n  encodeClientCaps,\n  encodeDetach,\n  encodeHello,\n  encodeIntent,\n  encodeWrite,\n} from \"../RealmWire/realmFrameCodec\";\nimport { pathHasUnsafeKey } from \"../RealmWire/unsafeKey\";\nimport {\n  canonicalizeStatePatches,\n  namePatchesToWireOps,\n  wireOpsToNamePatches,\n} from \"../RealmWire/wirePatch\";\nimport { computeRealmSecurityShortfall } from \"./assertRealmSecurity\";\nimport { diffProjected } from \"./diffProjected\";\nimport { predictWrite } from \"./predict\";\nimport { withStructuralParents } from \"./structuralParents\";\nimport {\n  createWriteHandle,\n  type IRealmWriteHandle,\n  type IWriteHandleController,\n} from \"./writeHandle\";\n\nenablePatches();\n\n/**\n * The realm client engine: `confirmed` state (authoritative frames only) + a `pending`\n * queue of optimistic frames, projected into one `@nice-code/state` Store — the rebase model.\n * One Store flush per incoming frame; acks are ordered after the patches ≤ their version, so\n * `await handle` ⇒ the store already reflects the outcome (read-your-writes, the protocol contract).\n */\n\n// ── The connection seam ────────────────────────────────────────────────────────\n\n/** What the client engine talks through — a realm slot on some link. */\nexport interface IRealmClientPort {\n  send(bytes: Uint8Array): void;\n  isOpen(): boolean;\n}\n\nexport interface IRealmPortHandlers {\n  /**\n   * One inbound decoded frame. `byteSize` is the decoded realm payload's size when the dispatcher\n   * knows it (`realmMuxClient` passes the protocol payload's length; a regrouped batch child\n   * carries none) — devtools attribution only, never behavior.\n   */\n  onFrame(frame: TRealmFrame, byteSize?: number): void;\n  /** Link (re)established — the engine sends its `hello`. */\n  onAttach(): void;\n  onDetach(): void;\n}\n\n/** A slot-scoped connection source: `realmConnection` in production, loopbacks in tests. */\nexport interface IRealmConnectionAdapter {\n  slot: number;\n  /**\n   * The link's authenticated local coordinate, when the adapter came from a connection-owning\n   * handle (`realmConnection(connector)`) — `connectRealm` defaults the client ref from it.\n   */\n  coordinate?: IRuntimeCoordinate;\n  /**\n   * The coordinate of the peer this link dials, when the adapter came from a connection-owning\n   * handle. Observational only — reported to `devtools.handleReady` so a topology can attribute this\n   * realm to the backend it is *actually* connected to (a realm id alone is ambiguous: two hosts may\n   * serve the same one).\n   */\n  peer?: IRuntimeCoordinate;\n  /** @deprecated Use {@link peer}. */\n  peerCoordinate?: IRuntimeCoordinate;\n  /**\n   * The connection's negotiated wire security level — carried from\n   * `realmConnection(connector)`. `connectRealm`/`connectRealmReplica` assert it against the realm's\n   * required minimum before the first `hello`. Absent on a bare-mux adapter (test loopback), where\n   * the assertion is skipped.\n   */\n  securityLevel?: ESecurityLevel;\n  register(handlers: IRealmPortHandlers): IRealmClientPort;\n  /** Release the slot (realm detached client-side). */\n  release(): void;\n  /**\n   * Ask the owning connection to tear down and re-dial the underlying link.\n   * Optional: a bare-mux / loopback adapter omits it (nothing to re-dial). The production\n   * `realmConnection(connector)` wires it to the connector's reconnect. Invoked when the\n   * staleness probe goes unanswered — a half-open socket (`isOpen()` still `true`, sends into the\n   * void) is otherwise undetectable at the realm layer.\n   */\n  requestReconnect?: () => void;\n  /**\n   * Observe the owning connection's link-state events — the structural\n   * shadow of the connector's `addLinkEventListener` (realm never imports action; only the fields\n   * the realm reads are typed). The engine forwards a re-establishment (`link_up` after a drop)\n   * into `onDiagnostic` as `link_redialed`. Optional: bare-mux / loopback adapters omit it.\n   */\n  subscribeLinkEvents?: (\n    listener: (event: { type: string; downForMs?: number }) => void,\n  ) => () => void;\n}\n\n// ── Options / handle types ─────────────────────────────────────────────────────\n\n/**\n * A rolled-back optimistic write/intent. **Wire `onMutationRejected` in production** — an unhandled\n * rejection silently un-does state the user already saw (\"my move vanished\"); a `rolledBackPaths`\n * rejection with no handler logs one `console.warn` per handle as a floor. Note the outcome is\n * only *definite* for a rules rejection (the `error` is the\n * rule's own \"no\"); a {@link err_realm} `frame_too_stale` here means the frame expired with an\n * **unknown** server outcome — re-read state, don't blindly re-issue a non-idempotent intent.\n */\nexport interface IRealmMutationRejection {\n  error: NiceError<any, any>;\n  kind: \"write\" | \"intent\";\n  intentName?: string;\n  /** Name-space paths whose optimistic effect was rolled back. */\n  rolledBackPaths: string[];\n}\n\n/**\n * Options for {@link connectRealm}.\n *\n * **Transport resilience (auto-redial) is configured on the connector, not the realm:**\n * `connectChannel(..., { reconnect })`. The realm rides whatever link the connector maintains —\n * these options only tune the realm's own sync-layer behavior (probes, expiry, diagnostics) on top\n * of that link.\n */\nexport interface IConnectRealmOptions<\n  TAvatarType extends string = string,\n  TView extends object = any,\n> {\n  /**\n   * Who this client is to the realm. `type` is always explicit (realm-specific); `persistentId`/\n   * `instanceId` default from the connection's authenticated coordinate when the adapter carries\n   * one (`realmConnection(connector)`) — explicit values override (tests/replicas).\n   */\n  avatar: { type: TAvatarType; persistentId?: string; instanceId?: string };\n  connection: IRealmConnectionAdapter;\n  /**\n   * Raise the client-side security floor above the realm's own `security` for this connection.\n   * The effective client minimum is `max(realm.security, this)`, asserted\n   * against the connection's negotiated level before the first `hello` — a shortfall fails the attach\n   * with `insufficient_security` and never emits a frame. Can only *raise* the bar; the server\n   * enforces its own floor independently. Omit to use the realm's declared minimum.\n   */\n  security?: TRealmSecurityLevel;\n  onMutationRejected?: (rejection: IRealmMutationRejection) => void;\n  /**\n   * A pending frame that outlives this window rejects with `frame_too_stale` (default 10s) —\n   * the *optimistic-settle* expiry: past it, the write's UI effect rolls back. Not the same dial\n   * as nice-action's `reliableActionTimeout` (default 60s), which is a *redelivery* deadline for\n   * at-least-once actions — they differ on purpose.\n   */\n  pendingExpiryMs?: number;\n  /**\n   * Extra coalescing window in ms for pointer-frequency paths (default: microtask only).\n   * Successive direct writes inside the window merge into one wire frame.\n   *\n   * The window is trailing-edge: the first write arms a timer and the merged frame ships when\n   * the window closes — a lone write therefore pays the full window as added latency before it\n   * is sent. Right for continuous streams (cursor, drag); wrong for event-shaped input lanes\n   * (keyboard transitions, button presses) — leave it unset there, the microtask-only default\n   * still merges same-tick writes at zero added latency. For a leading-edge window (lone writes\n   * send immediately, bursts still merge), use {@link coalesce} with `leading: true` instead.\n   * This option is the trailing-edge shorthand for `coalesce: { ms }`; when both are given,\n   * `coalesce` wins.\n   */\n  coalesceMs?: number;\n  /**\n   * The full coalescing dial ({@link coalesceMs} is the trailing-edge shorthand). With\n   * `leading: true` the window becomes a classic leading+trailing throttle: a write arriving\n   * with **no open window seals and sends immediately**, then opens a merge window behind it as\n   * a cooldown; writes landing inside the window coalesce and flush once at the window's end\n   * (which starts the next cooldown). Sends stay capped at ~`1000 / ms` per second, but an\n   * isolated write — a keyboard transition after quiet — no longer pays the window as latency.\n   * The right shape when one connection carries both duty cycles (a held-key stream AND\n   * transition events); a single hot path can use `update(fn, { flush: \"immediate\" })` instead.\n   */\n  coalesce?: { ms: number; leading?: boolean };\n  /**\n   * Write-through (experimental): raw `realm.store.update(...)` calls are captured\n   * and sent as realm writes. The engine's own projection flushes are excluded by the\n   * synchronous `projecting` guard around `store.replace` (whose root replace patch is also\n   * filtered — a wholesale swap is never a realm write).\n   */\n  experimental_writeThroughStore?: boolean;\n  /**\n   * The presence primitive: state this avatar must assert whenever it is (re-)attached — a lobby\n   * entry, a cursor row, \"my side of the record\". Runs\n   * as an ordinary optimistic write after EVERY full hydrate: the first attach, an\n   * out-of-log-window resume, and an epoch change (server wiped / ephemeral realm cold-started).\n   *\n   * On a **transient-bearing realm** it also runs after every incremental patch-replay resume\n   * (reconnect AND live probe/rehello — every hello is tracked, so even the periodic staleness probe\n   * heals): a transient region carries only its current value, so a same-epoch DO hibernation wake\n   * reloads it empty and the replay refresh confirms the loss — re-asserting here is the only thing\n   * that re-creates your entry. On a fully-durable realm\n   * it does NOT re-fire on a replay resume — the asserted state is still confirmed there. Idempotent\n   * either way: a no-op draft enqueues nothing.\n   *\n   * **Ordering guarantee (the reassert lane):** on a recovery, the re-own reaches the server BEFORE\n   * any resent write or intent, so an intent whose server logic reads your transient entry (a `fire`\n   * reading your `aim`) runs against the re-owned entry, never the wiped region. You do not sequence\n   * this yourself — the library rides the recovery hello with the re-own on an internal lane.\n   *\n   * **The guard pattern is blessed and recommended.** Writing `if (draft.mine != null) return; …`\n   * (re-own only if lost) is safe on EVERY recovery path: the draft the library evaluates on a\n   * resume reflects the AUTHORITATIVE post-recovery state (the transient-region refresh has already\n   * been applied), so a wake-wiped entry is observed as genuinely missing and re-created, while a\n   * healthy resume observes it present and enqueues nothing. Prefer the guard to an unconditional\n   * rewrite: it is cheaper (no idempotent write per healthy resume) and equally correct. To preserve\n   * your entry's exact pre-wake VALUE, read it from your own source-of-truth store inside the assert\n   * (`draft.mine = { …fromMyStore }`), not from the draft — after a wipe the draft's authoritative\n   * value is absent, so `draft.mine?.x ?? 0` re-owns at defaults (any still-pending pre-wake leaf\n   * writes then rebase on top).\n   *\n   * Rules apply as usual; a rejection surfaces once via `onMutationRejected` and is not\n   * auto-retried (a rules rejection is a program error, not a race). Ordered before `whenLive()`\n   * continuations resolve, so \"await whenLive, then read my entry\" observes the optimistic entry.\n   * If a recovery ever fails to re-create an entry you own (no assert, or a truly pruned parent),\n   * the `reown_missing` diagnostic fires (see {@link IConnectRealmOptions.onDiagnostic}).\n   */\n  assertOnAttach?: (draft: TView) => void;\n  /**\n   * The staleness probe: while `live` with an open link and **no inbound realm\n   * frame** for this window, re-send `hello(lastKnownVersion, epoch)` — idempotent by design\n   * (current ⇒ an ~10 B empty replay that doubles as the liveness signal; stale ⇒ exactly the\n   * missed patches; wiped server ⇒ full hydrate via the epoch). Kills the \"ghost\" class: a lost\n   * wake-rehello, missed caps, or a suspended runtime all converge on \"quiet too long → probe →\n   * resync\". Default 25 000 ms; `0` disables (tests / hosts with their own liveness).\n   */\n  staleProbeAfterMs?: number;\n  /**\n   * Probe-escalation window: after a staleness probe, if **no** inbound\n   * frame arrives within this window the link is presumed dead — status flips to `\"connecting\"`,\n   * a `probe_escalated` diagnostic fires, and the connection's `requestReconnect` (when the\n   * adapter provides one) is invoked. This is what closes the half-open-socket hole the probe\n   * alone only *detects*: `isOpen()` stays `true` while sends vanish, so the probe would otherwise\n   * re-send hellos into the void forever. Default 10 000 ms; `0` disables escalation (detect-only).\n   */\n  probeReplyTimeoutMs?: number;\n  /**\n   * Observe sync-health events: automatic resyncs (`resync`), non-continuous frames\n   * dropped during a recovery (`gap_dropped`), inbound frames that failed to decode/apply\n   * (`frame_error`), staleness-probe escalations (`probe_escalated`), and the re-own tripwire\n   * (`reown_missing` — a transient entry you own went missing and the recovery did not re-create\n   * it; the definite signal to wire if you silence `write_target_missing` in `onMutationRejected`).\n   * Wire this in production — resync frequency is the sync-health signal (a healthy realm emits\n   * none of the above; `link_redialed`, below, is the exception). When absent, the first\n   * occurrence of each event type logs one `console.warn` per handle (silent-failure guard).\n   *\n   * **Transport-level drops that heal by redial do not surface here** — a healthy heal is silent\n   * at the sync layer (no sync was lost). For link drop/redial/re-establish observation, use the\n   * connector's `onLinkEvent` (`connectChannel` options); the one transport event forwarded into\n   * this stream is `link_redialed` (the link re-established, with `downForMs`), so realm-level\n   * telemetry can count transport churn without a second wiring point.\n   */\n  onDiagnostic?: (event: TRealmDiagnosticEvent) => void;\n  /**\n   * The devtools observation seam: decoded frames in/out,\n   * mutation lifecycle (created → confirmed/rejected), every diagnostic, status flips. Wire it\n   * with `RealmDevtoolsCore.instrument(label)` from `@nice-code/realm/devtools/browser` — or any\n   * {@link IRealmDevtoolsTap} of your own. Omit = zero overhead (one null check per event).\n   */\n  devtools?: import(\"./realmDevtoolsTap.types\").IRealmDevtoolsTap;\n}\n\nexport type TRealmStatus = \"connecting\" | \"live\" | \"detached\";\n\n/**\n * Sync-health events surfaced by {@link IConnectRealmOptions.onDiagnostic}. Resync\n * frequency is the production sync-health signal — a healthy realm emits no sync events. The one\n * exception is `link_redialed`: it is transport churn, not lost sync, so expect it on ordinary\n * network drops and alert on the other types.\n */\nexport type TRealmDiagnosticEvent =\n  | {\n      /** A lost-sync condition was detected and a recovery hello was sent (or suppressed only by\n       * a very recent one — see the reply-grace window). `write_target_missing` is the structural\n       * divergence trigger (Phase 1.5 / the recovery contract): a server reject proved a predicted write could\n       * not apply, so the client re-reads instead of looping on doomed frames. */\n      type: \"resync\";\n      reason: \"version_gap\" | \"frame_error\" | \"write_target_missing\";\n      fromVersion?: number;\n      toVersion?: number;\n      confirmedVersion?: number;\n    }\n  | {\n      /** A `reject` frame arrived for a `clientSeq` no longer pending (Phase 1.5): the frame settled\n       * (locally rebased away, or expired) between send and reject, or a stale duplicate. Harmless,\n       * but its presence is the fingerprint of a divergence window — surfaced instead of dropped. */\n      type: \"late_reject\";\n      clientSeq: number;\n      errorIds: string[];\n    }\n  | {\n      /** A non-continuous `patches` frame arrived while a recovery hello was in flight — dropped\n       * without applying (it predates the recovery; the replay/hydrate answer supersedes it). */\n      type: \"gap_dropped\";\n      fromVersion: number;\n      toVersion: number;\n      confirmedVersion: number;\n    }\n  | {\n      /** An inbound frame failed to decode or apply. */\n      type: \"frame_error\";\n      error: unknown;\n    }\n  | {\n      /** The staleness probe went unanswered past its reply window. */\n      type: \"probe_escalated\";\n    }\n  | {\n      /**\n       * The underlying transport link re-established after a drop — the\n       * ONE transport event forwarded here, so realm-level telemetry can count link churn without\n       * a second wiring point. A drop healed this way loses no sync (no `resync` fires); for the\n       * full drop/redial/backoff picture, subscribe to the connector's `onLinkEvent`.\n       */\n      type: \"link_redialed\";\n      downForMs: number;\n    }\n  | {\n      /**\n       * A transient entry this avatar owns went missing (a `write_target_missing` reject flagged\n       * its parent) and the recovery re-own did NOT re-create it. This is the definite \"your\n       * `assertOnAttach` produced no write for path X\"\n       * signal — wire it if you silence `write_target_missing` in `onMutationRejected`, since that\n       * reject is then your only other tell and is easily mistaken for benign wake noise. The\n       * library escalates ONCE on the first occurrence (a forced full-hydrate — the in-place\n       * equivalent of a page reload); a second `reown_missing` for the same path means even that did\n       * not restore it, so the parent is legitimately gone (a pruned entry, a removed peer) and the\n       * app should stop retrying and reflect that in its UI. `path` is dotted for display only —\n       * do not parse it back into segments (a record key may itself contain a dot).\n       */\n      type: \"reown_missing\";\n      path: string;\n    };\n\n/** A write or intent made before the first hydrate, held until there is state to run it against. */\ninterface IQueuedWrite {\n  kind: \"write\" | \"intent\";\n  intentName?: string;\n  /** Runs the real write once hydrated; its handle settles the queued one. */\n  run: () => IRealmWriteHandle;\n  controller: IWriteHandleController;\n  expiryTimer: ReturnType<typeof setTimeout> | undefined;\n}\n\n/** Runs every step even when one throws; `rethrow()` then surfaces the first error. */\ninterface IStepGuard {\n  run(step: () => void): void;\n  rethrow(): void;\n}\n\nfunction createStepGuard(): IStepGuard {\n  let failure: { error: unknown } | undefined;\n  return {\n    run(step) {\n      try {\n        step();\n      } catch (error) {\n        failure ??= { error };\n      }\n    },\n    rethrow() {\n      if (failure != null) throw failure.error;\n    },\n  };\n}\n\ninterface IPendingFrame {\n  clientSeq: number;\n  kind: \"write\" | \"intent\";\n  intentName?: string;\n  /** Predicted name-space patches (empty for a non-optimistic intent). */\n  patches: Patch[];\n  basisVersion: number;\n  handles: IWriteHandleController[];\n  /** Rebuild the wire frame on resend (fresh basis after a reconnect). */\n  buildFrame: (clientSeq: number, basisVersion: number) => Uint8Array;\n  expiryTimer: ReturnType<typeof setTimeout> | undefined;\n  /** Still open for coalescing (unsent, this microtask/window). */\n  openForMerge: boolean;\n  /** `limits_exceeded` retry count — bounded; then the reject settles as usual. */\n  retries: number;\n  /** The durable tier: a reassert frame never expires — it resends\n   * across reconnects (and full rehydrates) until confirmed or rejected by authority. */\n  durability?: \"reassert\";\n  /**\n   * The Phase 2 reassert lane: a library-authored transient re-own (`assertOnAttach`) ridden on a\n   * recovery hello with the sentinel `clientSeq: -2`. It skips outbound parking (must travel during\n   * the hello window), never expires (re-sent on the next hello), and its patches are folded FIRST\n   * in `revalidateAndResendPending` so pre-wake leaf writes rebase onto the re-created parent (F4).\n   */\n  isSystemAssert?: boolean;\n  /**\n   * `Date.now()` of the LAST send of this frame (`realm.stats` sampling) — re-stamped on every\n   * resend, so a post-reconnect confirm samples the round trip from the resend that earned it,\n   * never the outage. Absent until the frame first reaches an open port.\n   */\n  sentAt?: number;\n}\n\n/** Options bag for {@link IRealmHandle.update}. */\nexport interface IRealmUpdateOptions {\n  /**\n   * `\"reassert\"` marks this write durable: it is exempt from `pendingExpiryMs` and is rebuilt +\n   * resent on every reattach — including across an epoch change — until the server confirms or\n   * rejects it. Link failures never roll it back; **authority still wins** (a rules rejection\n   * settles immediately, durable or not). For producer roles: a client that owns an append-only\n   * region (a host streaming an input log) writes it with this tier. Keep tiers per path region\n   * — reassert frames only coalesce with other reassert frames. Bounded: past the backlog cap\n   * further reassert writes reject with `durable_backlog_overflow` (fall back to re-syncing from\n   * your source of truth). Intents have no durable tier — a durable data-answering exchange is\n   * the action plane (reliable actions).\n   */\n  durability?: \"reassert\";\n  /**\n   * `\"immediate\"` skips the coalescing window for THIS write: any buffered coalescing writes\n   * flush first (compose order is preserved — same as an intent), then this write seals and\n   * sends on its own frame. The per-write escape hatch for a latency-critical lane (a game\n   * input transition) on a connection whose other paths want a merge window. Under a recovery\n   * hello the frame still parks like every sealed frame (resent rebased by the answer) — the\n   * recovery invariants hold; \"immediate\" never streams against a wiped transient region.\n   */\n  flush?: \"immediate\";\n}\n\n/** The durable-write backlog cap (§4): past this many unconfirmed reassert frames, new reassert\n * writes reject loudly instead of growing memory for the length of the outage. */\nconst MAX_REASSERT_PENDING_FRAMES = 256;\n\n/**\n * The sentinel `clientSeq` for a Phase 2 reassert-lane system-assert. Negative so it never collides\n * with a real client seq (0, 1, 2, …); the engine applies such a frame through the full rules\n * pipeline but skips the replay high-water, so it can be ordered on the wire before pending frames\n * without swallowing their seqs (the §0 constraint). An old server (≤ 0.47) dup-acks any `seq ≤ -1`,\n * degrading gracefully to the post-answer fallback re-own.\n */\nconst SYSTEM_ASSERT_SEQ = -2;\n\n/** How many `limits_exceeded` rejects one write frame may absorb before settling as a reject. */\nconst MAX_LIMIT_RETRIES = 3;\n/** Backoff before resending a frame the server rate-limited (`writeRatePerSecond` breach). */\nconst RATE_RETRY_MS = 1_000;\n\nexport interface IRealmPendingInfo {\n  readonly count: number;\n  has(pathPrefix: string): boolean;\n  subscribe(listener: () => void): () => void;\n}\n\n/**\n * Live link-quality estimate for this realm handle — see {@link IRealmHandle.stats}. Values are\n * EWMA-smoothed; `null` until the first sample lands.\n */\nexport interface IRealmStats {\n  /** Smoothed round-trip ms: frame send → server confirm (the coalesce window is NOT included). */\n  rttMs: number | null;\n  /** Smoothed mean absolute deviation of the RTT samples — the \"how steady\" companion number. */\n  jitterMs: number | null;\n  /** Total samples folded in — gate displays on `samples > 0` (or a few, for a settled EWMA). */\n  samples: number;\n}\n\n/**\n * Does this inbound frame prove we are **in sync** with the server — as opposed to merely proving\n * the socket is up?\n *\n * Everything the server sends carries sync information (`hydrate`/`patches` are state, `ack` says a\n * write landed, `keyDict` extends the intern dictionary those depend on) **except a `reject`**,\n * which says only \"that write of yours was refused\". A stream of nothing but rejects is a link that\n * is alive and a client that is learning nothing — precisely the state the staleness probe exists\n * to break out of.\n *\n * A `batch` is transparent: it is healthy if any child is, so an envelope of pure rejects counts as\n * what it is. (Nesting is forbidden by the codec; the recursion costs nothing and means this cannot\n * be wrong if that ever changes.)\n */\nfunction provesSyncHealth(frame: TRealmFrame): boolean {\n  if (frame.kind === REALM_FRAME_KIND.batch) return frame.frames.some(provesSyncHealth);\n  return frame.kind !== REALM_FRAME_KIND.reject;\n}\n\n/** Why a {@link IRealmHandle.listenToPatches} flush happened — see {@link IRealmPatchMeta.cause}. */\nexport type TRealmPatchCause = \"confirm\" | \"optimistic\" | \"rebase\" | \"hydrate\";\n\n/** The second argument to a {@link IRealmHandle.listenToPatches} listener. */\nexport interface IRealmPatchMeta {\n  /**\n   * **How** this flush was produced — a shape hint for the emitted patches, NOT an authority\n   * signal (that is {@link authoritative}):\n   * - `\"confirm\"` — fresh authoritative patches applied with **no optimistic overlay in play**, so\n   *   the emission is the server's own ops verbatim (the internal no-diff fast path).\n   * - `\"optimistic\"` — a local write/intent applied speculatively (includes the library's own\n   *   transient re-own). **The only cause that carries no new server information** — your own\n   *   un-acked write echoing back.\n   * - `\"rebase\"` — the projection was rebuilt and the emission is a structural diff. Covers two\n   *   very different situations, which is why it cannot be read as \"not authoritative\": fresh\n   *   server patches landing **while you have writes in flight** (`authoritative: true` — the\n   *   common case for any client that writes continuously), and pure local rebuilds like an\n   *   expiry or reject rollback (`authoritative: false`).\n   * - `\"hydrate\"` — a full rebuild: exactly `[{ op: \"replace\", path: [], value }]`.\n   *\n   * **Do not gate a reconciler on `cause === \"confirm\"`.** It means \"authoritative *and* your\n   * outbox happened to be empty\", so a client that writes continuously — any game client — sees\n   * most of its authoritative traffic as `\"rebase\"` and a confirm-gate silently discards it. The\n   * effect scales with latency and is invisible on localhost. Gate on {@link authoritative}, or\n   * simply skip `\"optimistic\"`.\n   */\n  cause: TRealmPatchCause;\n  /**\n   * **The authority predicate**: `true` when this flush applied fresh authoritative state (a\n   * server patches frame — with or without an optimistic overlay in play — or a hydrate), `false`\n   * when it was a purely local rebuild (your own optimistic write, an expiry/reject rollback, an\n   * ack dropping a settled overlay).\n   *\n   * This is the field a predictor/reconciler wants: `if (!meta.authoritative) return;`. Pair it\n   * with a domain freshness check (a tick or version on the authoritative region) to decide what\n   * is actually *new* — provenance says why the flush happened; your tick says what changed.\n   */\n  authoritative: boolean;\n  /** The confirmed authoritative version at emit time. */\n  confirmedVersion: number;\n}\n\nexport interface IRealmHandle<\n  TView extends object,\n  TIntents extends Record<string, IRealmIntentDef<any, any, any, any>>,\n  // `any`, not `string`: a `string` default makes a two-argument annotation widen connectRealm's\n  // inferred avatar type, and the realm argument then fails to match.\n  TAvatarType extends string = any,\n> {\n  store: Store<TView>;\n  /** Who this handle is to the realm — the same ref the rules judge. Key your own entries with `avatar.persistentId`. */\n  readonly avatar: Readonly<IRealmAvatarRef<TAvatarType>>;\n  /**\n   * Optimistic direct write (LWW absolute-set semantics — read-modify-write belongs in an\n   * intent). Writes coalesce per window into one wire frame; a flush exceeding the\n   * server-advertised `maxPatchesPerFrame` **splits** into consecutive frames —\n   * each part stays atomic on the server, all handles settle with the last part\n   * (read-your-writes holds), but a split flush is no longer atomic as a whole.\n   *\n   * Pass `{ durability: \"reassert\" }` for the durable tier: exempt\n   * from `pendingExpiryMs`, resent across reconnects until confirmed — see\n   * {@link IRealmUpdateOptions.durability}.\n   *\n   * Safe to call before the first hydrate: the call is queued, and `fn` runs against the hydrated\n   * state (after `assertOnAttach`, in call order). Its handle rejects if the realm never hydrates\n   * — with {@link IRealmHandle.attachError} on a refused attach, else `write_before_hydrate`.\n   * Intents queue the same way.\n   */\n  update(fn: (draft: TView) => void, options?: IRealmUpdateOptions): IRealmWriteHandle;\n  intents: {\n    [K in keyof TIntents]: (input: TInferNode<TIntents[K][\"input\"]>) => IRealmWriteHandle;\n  };\n  pending: IRealmPendingInfo;\n  readonly status: TRealmStatus;\n  /**\n   * `true` once this handle has EVER been `\"live\"` — never reset for the handle's lifetime (a\n   * fresh `connectRealm` starts `false`; teardown/re-create is the reset). Distinguishes the two\n   * very different `\"connecting\"` moments without a hand-rolled flag: `!hasBeenLive` ⇒ the initial\n   * join (\"joining…\" spinner), `hasBeenLive` ⇒ a recovery (\"reconnecting…\" warning). Skew-safe by\n   * design — the status enum stays three-valued.\n   */\n  readonly hasBeenLive: boolean;\n  /** The confirmed authoritative version. */\n  readonly version: number;\n  /** The attach failure (schema mismatch / unknown realm), when the server refused the hello. */\n  readonly attachError: NiceError<any, any> | undefined;\n  /**\n   * Resolves when the realm first hydrates (`status === \"live\"`); rejects on an attach failure,\n   * on detach, or after `timeoutMs` (default 10s). Replaces hand-rolled status polling —\n   * resolved immediately when already live.\n   */\n  whenLive(options?: { timeoutMs?: number }): Promise<void>;\n  /**\n   * Subscribe to status transitions: the listener fires on **every** change\n   * (`connecting ↔ live → detached`) with the new status. Returns the unsubscribe. Drives\n   * connection UI (`useRealmStatus` rides this) — the store/pending subscriptions deliberately\n   * do not fire on a pure status flip.\n   *\n   * The second argument carries {@link hasBeenLive}, so one listener renders both `\"connecting\"`\n   * moments truthfully: `status === \"connecting\" && meta.hasBeenLive` ⇒ \"reconnecting…\" (warning);\n   * `!meta.hasBeenLive` ⇒ \"joining…\" (spinner).\n   */\n  subscribeStatus(\n    listener: (status: TRealmStatus, meta: { hasBeenLive: boolean }) => void,\n  ): () => void;\n  /**\n   * Subscribe to sync-health diagnostics post-hoc — the multi-listener\n   * complement of `options.onDiagnostic` (which stays a single connect-time callback). Listeners\n   * are additive observers: they fire on every event regardless of `onDiagnostic`, and having at\n   * least one suppresses the unwired-app `console.warn` floor (the event is observed). Returns\n   * the unsubscribe.\n   */\n  subscribeDiagnostics(listener: (event: TRealmDiagnosticEvent) => void): () => void;\n  /**\n   * The patch feed for imperative renderers: the projected-store delta per flush,\n   * in name-space `immer` patch shape — apply it to a typed array / canvas / scene graph\n   * instead of re-diffing the whole state per flush. Fast path: a confirmed-frames-only flush\n   * with no optimistic overlay emits the authoritative patches directly; a rebase flush emits a\n   * structural diff (identity-pruned via immer's sharing, so it only walks what changed). A\n   * hydrate — or any full rebuild — emits exactly `[{ op: \"replace\", path: [], value }]`.\n   * Listeners fire after the store flush (the store already reflects `value`s). A flush that\n   * changes nothing (an empty diff, an unchanged projection) emits nothing — unlike\n   * `store.subscribe`, which fires on every projection.\n   *\n   * The listener's second argument ({@link IRealmPatchMeta}) carries the flush's provenance: gate\n   * a predictor/reconciler on **`meta.authoritative`** — reacting to a non-authoritative flush\n   * replays your own un-acked echo as if it were server truth (the classic input-lag bug), while\n   * gating on `cause === \"confirm\"` silently discards real server truth whenever you have writes\n   * in flight. See {@link IRealmPatchMeta.cause}.\n   */\n  listenToPatches(listener: (patches: readonly Patch[], meta: IRealmPatchMeta) => void): () => void;\n  /**\n   * Link-quality estimate, EWMA-smoothed (α=0.2), fed by traffic the realm already earns:\n   * write-confirm round trips (send → ack, the coalesce window excluded) and answered hellos\n   * (the staleness probe's ~10 B empty replay — so a read-mostly client samples at its probe\n   * cadence; lower `staleProbeAfterMs` deliberately for denser sampling). **No dedicated ping\n   * exists by design**: a realm-level ping would wake a hibernated server (a billed cost) just\n   * to measure it. Poll from a HUD/render tick — the getter is O(1).\n   */\n  readonly stats: IRealmStats;\n  /** Leave the realm: sends `detach`, releases the slot, expires pending writes. */\n  detach(): void;\n}\n\nconst DEFAULT_PENDING_EXPIRY_MS = 10_000;\nconst DEFAULT_STALE_PROBE_AFTER_MS = 25_000;\n/** How long a probe may go unanswered before the link is presumed dead. */\nconst DEFAULT_PROBE_REPLY_TIMEOUT_MS = 10_000;\n\n/**\n * Attach a realm client to a connection. The store starts empty and fills on hydrate;\n * `realm.update()` is the blessed write API (LWW absolute-set contract — read-modify-write\n * belongs in an intent, the protocol contract).\n */\nexport function connectRealm<\n  TState extends object,\n  TAvatarType extends string,\n  TCtx,\n  TIntents extends Record<string, IRealmIntentDef<any, any, any, any>>,\n>(\n  realm: IRealmDefinition<TState, TAvatarType, TCtx, TIntents, any> & { _state?: TState },\n  options: IConnectRealmOptions<TAvatarType, TState>,\n): IRealmHandle<\n  TInferAvatarView<{ _state?: TState }, TAvatarType> & object,\n  TIntents,\n  TAvatarType\n> {\n  type TView = TState; // v1: the view type equals the state type (deviation D-6)\n\n  // Identity defaults from the connection's authenticated coordinate: `realmConnection(connector)`\n  // carries the connection's local coordinate, so the ref the\n  // server independently derives via `resolveAvatar` and the one prediction runs against can no\n  // longer silently disagree. Explicit values stay as overrides (tests/replicas).\n  const coordinate = options.connection.coordinate;\n  const persistentId = options.avatar.persistentId ?? coordinate?.perId;\n  if (persistentId == null) {\n    throw new Error(\n      \"connectRealm: no avatar identity — the connection carries no persistent id. Give it one where you open the connection (identity: coord.withPersistentId(id)), or pass avatar.persistentId explicitly.\",\n    );\n  }\n  const avatar: IRealmAvatarRef<TAvatarType> = {\n    type: options.avatar.type,\n    persistentId,\n    instanceId: options.avatar.instanceId ?? coordinate?.insId ?? \"default\",\n  };\n  const expiryMs = options.pendingExpiryMs ?? DEFAULT_PENDING_EXPIRY_MS;\n  const slot = options.connection.slot;\n  const devtools = options.devtools;\n\n  // Coalescing config: `coalesce` is the full dial, `coalesceMs` the trailing-edge shorthand.\n  const coalesceCfg =\n    options.coalesce ?? (options.coalesceMs != null ? { ms: options.coalesceMs } : undefined);\n  const coalesceWindowMs = coalesceCfg != null && coalesceCfg.ms > 0 ? coalesceCfg.ms : 0;\n  const coalesceLeading = coalesceCfg?.leading === true && coalesceWindowMs > 0;\n\n  const store = new Store<TView>({} as TView);\n  const dict = new RealmKeyDict();\n  const pendingListeners = new Set<() => void>();\n\n  let confirmed: TView = {} as TView;\n  let confirmedVersion = -1;\n  /** The log epoch `confirmedVersion` belongs to — echoed in every hello. */\n  let serverEpoch: string | undefined;\n  /** Server-advertised ingress limits off the hydrate — drives flush splitting. */\n  let advertisedLimits:\n    | { maxPatchesPerFrame: number; maxFrameBytes: number; writeRatePerSecond: number }\n    | undefined;\n  let identityWarned = false;\n  let status: TRealmStatus = \"connecting\";\n  let attachError: NiceError<any, any> | undefined;\n\n  /**\n   * The prefix for this handle's `console.warn` floors. The realm id alone is ambiguous with\n   * several *instances* of the same realm on one page (two matches of one game realm), so once the\n   * hydrate names the server's history the epoch's first chars disambiguate — and correlate with\n   * the server's own logs. Pre-hydrate warns keep the plain prefix (never block a warn on identity).\n   */\n  const warnTag = (): string =>\n    serverEpoch == null ? `[realm:${realm.id}]` : `[realm:${realm.id}#${serverEpoch.slice(0, 8)}]`;\n  /** Status-transition listeners: `subscribeStatus` subscribers + the `whenLive` waiters (B.4). */\n  const statusListeners = new Set<(status: TRealmStatus, meta: { hasBeenLive: boolean }) => void>();\n  /** Latched on the first `live` and never reset — joining vs reconnecting. */\n  let hasBeenLive = false;\n  const setStatus = (next: TRealmStatus): void => {\n    if (status === next) return;\n    status = next;\n    if (next === \"live\") hasBeenLive = true;\n    // A throwing listener must not starve the others (the `whenLive` waiters among them).\n    const guard = createStepGuard();\n    // Detached before the first hydrate: the queued writes can never run. Settled before the\n    // listeners run, so they already read the final pending count.\n    if (next === \"detached\") guard.run(rejectHydrateQueue);\n    for (const listener of [...statusListeners]) guard.run(() => listener(next, { hasBeenLive }));\n    guard.run(() => devtools?.onStatus?.(next, { hasBeenLive }));\n    guard.rethrow();\n  };\n  let pending: IPendingFrame[] = [];\n  const hydrateQueue: IQueuedWrite[] = [];\n  /** Set from the hydrate's `confirmedVersion` until its queue drains: new writes queue behind. */\n  let hydrating = false;\n  let nextSeq = 0;\n  let flushScheduled = false;\n  let projecting = false;\n  let port: IRealmClientPort | undefined;\n  /**\n   * Staleness-probe clocks.\n   *\n   * `lastSyncInboundAt` is deliberately a **sync-health** clock, not a liveness one: only a frame\n   * carrying real server sync information stamps it (see {@link provesSyncHealth}). A `reject`\n   * proves the link is *up*, and proves nothing about whether we are in sync — so it must not\n   * suppress the probe. That distinction matters because the two used to be one clock, and the\n   * failure it allowed was self-sealing: a pathological reject loop is exactly the situation the\n   * staleness probe exists to heal, and every reject in it pushed the probe further away\n   *.\n   *\n   * There is no separate *liveness* clock here because nothing at this layer needs one — liveness is\n   * the wire's job (`connectChannel({ heartbeat })`, which counts any inbound frame and drops a\n   * silent link). The realm's probe is purely \"am I still in sync?\". If server-initiated liveness\n   * ever lands and wants a pure inbound clock, it adds one then rather than re-merging these.\n   */\n  let lastSyncInboundAt = Date.now();\n  let lastProbeAt = 0;\n  /** One-shot probe-reply deadline — armed after a probe, cleared by any inbound. */\n  let probeDeadline: ReturnType<typeof setTimeout> | undefined;\n\n  // ── Lost-sync recovery ──────────────────────────────────────────\n  /** An attach/recovery hello is out and unanswered — non-continuous frames drop, never apply. */\n  let helloInFlight = false;\n  let helloSentAt = 0;\n  /** Suppress duplicate recovery hellos only while one is plausibly still being answered. */\n  const HELLO_REPLY_GRACE_MS = 10_000;\n\n  const warnedDiagnostics = new Set<string>();\n  /** `subscribeDiagnostics` listeners — additive observers, multi-listener. */\n  const diagnosticListeners = new Set<(event: TRealmDiagnosticEvent) => void>();\n  const onDiagnostic = (event: TRealmDiagnosticEvent): void => {\n    devtools?.onDiagnostic?.(event);\n    for (const listener of [...diagnosticListeners]) listener(event);\n    if (options.onDiagnostic != null) {\n      options.onDiagnostic(event);\n      return;\n    }\n    // Silent-failure guard: an unwired, unobserved app still leaves one trace per event type per\n    // handle. A `subscribeDiagnostics` listener counts as wiring — it can see and report the event.\n    if (diagnosticListeners.size > 0) return;\n    if (!warnedDiagnostics.has(event.type)) {\n      warnedDiagnostics.add(event.type);\n      console.warn(`${warnTag()} sync-health event \"${event.type}\"`, event);\n    }\n  };\n\n  /**\n   * Deliver a rejection to `onMutationRejected`, or — when unwired — log a one-time floor for a\n   * **silent rollback** (app-contract §2): a rejection that reverted already-shown optimistic state\n   * (`rolledBackPaths` non-empty) would otherwise vanish with no trace (\"my move disappeared\"). A\n   * rejection that never rendered (immediate predict/validation failures, `rolledBackPaths: []`) is\n   * not warned — nothing was shown to roll back.\n   */\n  let warnedSilentRollback = false;\n  const emitRejection = (rejection: IRealmMutationRejection): void => {\n    if (options.onMutationRejected != null) {\n      options.onMutationRejected(rejection);\n      return;\n    }\n    if (rejection.rolledBackPaths.length > 0 && !warnedSilentRollback) {\n      warnedSilentRollback = true;\n      console.warn(\n        `${warnTag()} an optimistic ${rejection.kind} rolled back on ` +\n          `[${rejection.rolledBackPaths.join(\", \")}] (${rejection.error.getIds().join(\", \")}) with no ` +\n          \"onMutationRejected handler — the change silently reverted. Wire onMutationRejected on connectRealm. \" +\n          \"Note: frame_too_stale is an UNKNOWN outcome (may have committed), not a definite reject.\",\n      );\n    }\n  };\n\n  // ── Probe config + escalation ──────────────────\n  const staleProbeAfterMs = options.staleProbeAfterMs ?? DEFAULT_STALE_PROBE_AFTER_MS;\n  const probeReplyTimeoutMs = options.probeReplyTimeoutMs ?? DEFAULT_PROBE_REPLY_TIMEOUT_MS;\n\n  /**\n   * Arm the escalation deadline after a probe-flavored hello (Phase 1.2 backstop): a probe/rehello\n   * keeps `live` status for a one-round-trip heal on a link we still believe is up — but if NO\n   * inbound frame lands within the window the link is genuinely dead/half-open, so flip to\n   * `connecting` truthfully and ask the connection to re-dial. Status thus flips only on *evidence*\n   * of an outage, never on a protocol chore (the Issue-1 contract). Cleared by any inbound frame.\n   */\n  const armProbeEscalation = (): void => {\n    if (probeReplyTimeoutMs <= 0) return;\n    if (probeDeadline != null) clearTimeout(probeDeadline);\n    probeDeadline = setTimeout(() => {\n      probeDeadline = undefined;\n      if (status !== \"live\") return; // already flipped (a detach raced us) — nothing to do\n      // A reply arrived — and specifically a *syncing* one. A reject landing after our probe is not\n      // an answer to it, so it must not call off the escalation the unanswered probe armed.\n      if (lastSyncInboundAt >= lastProbeAt) return;\n      onDiagnostic({ type: \"probe_escalated\" });\n      setStatus(\"connecting\"); // truthful UI: we cannot currently sync\n      options.connection.requestReconnect?.();\n    }, probeReplyTimeoutMs);\n    unrefTimer(probeDeadline);\n  };\n\n  /** A Phase 2 reassert-lane frame is awaiting its ack — the post-answer fallback re-own defers to it. */\n  const hasPendingSystemAssert = (): boolean => pending.some((frame) => frame.isSystemAssert);\n\n  // ── realm.stats (Dirt Derby item 2): EWMA RTT/jitter off traffic the realm already earns ──────\n  /** EWMA weight — ~last 5 samples dominate; steady under the occasional outlier. */\n  const STATS_ALPHA = 0.2;\n  let statsRttMs: number | null = null;\n  let statsJitterMs: number | null = null;\n  let statsSamples = 0;\n  const recordRttSample = (sampleMs: number): void => {\n    if (sampleMs < 0) return; // clock skew guard — never fold a negative sample\n    statsSamples += 1;\n    if (statsRttMs == null || statsJitterMs == null) {\n      statsRttMs = sampleMs;\n      statsJitterMs = 0;\n    } else {\n      // Jitter first, against the pre-update mean (mean absolute deviation, EWMA-smoothed).\n      statsJitterMs += STATS_ALPHA * (Math.abs(sampleMs - statsRttMs) - statsJitterMs);\n      statsRttMs += STATS_ALPHA * (sampleMs - statsRttMs);\n    }\n    devtools?.onStats?.({ rttMs: statsRttMs, jitterMs: statsJitterMs, samples: statsSamples });\n  };\n\n  /**\n   * Declare lost-sync and heal via re-hello: the recovery hello is **probe-flavored**\n   * — no status flap, since on a live link the heal is one round-trip (the server replays exactly\n   * the missed span from `confirmedVersion`, or full-hydrates when out of window / epoch\n   * mismatch). Safe in every trigger scenario because `applyConfirmed` is immutable — a detected\n   * gap was never applied and a failed apply left `confirmed` untouched, so `confirmedVersion` is\n   * always an honest basis. Suppressed while a hello is already in flight (time-bounded by the\n   * reply grace, so a lost recovery hello cannot suppress forever). `sendHello` itself sets the\n   * in-flight flag and arms escalation, so this just decides whether to fire (Phase 1.1).\n   */\n  const requestResync = (\n    reason: \"version_gap\" | \"frame_error\" | \"write_target_missing\",\n    detail?: { fromVersion?: number; toVersion?: number; confirmedVersion?: number },\n  ): void => {\n    if (status === \"detached\") return; // never re-hello a released slot\n    onDiagnostic({ type: \"resync\", reason, ...detail });\n    if (helloInFlight && Date.now() - helloSentAt < HELLO_REPLY_GRACE_MS) return;\n    if (port?.isOpen() !== true) return; // the next onAttach hellos anyway\n    sendHello({ probe: true });\n  };\n\n  // ── The re-own tripwire (Phase 2 / Overshot ask #2) ─────────────────────────\n  /**\n   * Parent paths a `write_target_missing` reject flagged, awaiting proof the recovery re-created\n   * them. Keyed by `JSON.stringify(segments)` (a record key may contain a dot, so a string join is\n   * not a safe key). Checked once the recovery has settled with no re-own in flight\n   * ({@link checkReownWatch}); a still-missing parent emits `reown_missing` and escalates once.\n   */\n  const reownWatch = new Map<string, string[]>();\n  /** Paths already escalated once (a forced full-hydrate) — the bound: at most one extra hydrate. */\n  const reownEscalated = new Set<string>();\n\n  /** Walk `confirmed` to a path; `true` when every segment resolves to a non-null value. */\n  const confirmedHasPath = (segments: readonly string[]): boolean => {\n    let cursor: unknown = confirmed;\n    for (const seg of segments) {\n      if (cursor == null || typeof cursor !== \"object\") return false;\n      cursor = (cursor as Record<string, unknown>)[seg];\n    }\n    return cursor != null;\n  };\n\n  /**\n   * Verify the recovery re-created every watched parent (Phase 2). Runs only when no re-own is in\n   * flight (a pending system-assert means \"wait — it may still land\"), so the sync loopback (assert\n   * acked re-entrantly, `confirmed` already carries it) and the async wire (assert acks in a later\n   * frame) both reach this with the outcome settled. A parent that is now present healed → cleared.\n   * A parent still absent means the re-own produced no write for it (no `assertOnAttach`, a guard\n   * that never observed the loss, or a rejected re-own): emit `reown_missing`, and on the FIRST such\n   * event escalate with one forced full-hydrate (the in-place page-reload equivalent — the Phase 1\n   * hydrate re-own gets a genuinely fresh basis). A second event for the same path (the forced\n   * hydrate also failed) means the parent is legitimately gone — emit once more and stop (no loop).\n   */\n  const checkReownWatch = (): void => {\n    if (reownWatch.size === 0) return;\n    if (hasPendingSystemAssert()) return; // a re-own is still in flight — re-check when it settles\n    for (const [key, segments] of [...reownWatch]) {\n      if (confirmedHasPath(segments)) {\n        reownWatch.delete(key);\n        reownEscalated.delete(key);\n        continue;\n      }\n      onDiagnostic({ type: \"reown_missing\", path: segments.join(\".\") });\n      if (reownEscalated.has(key)) {\n        // Already escalated once and still gone → legitimately absent (pruned entry / removed peer).\n        reownWatch.delete(key);\n        reownEscalated.delete(key);\n      } else if (port?.isOpen() === true && status !== \"detached\") {\n        reownEscalated.add(key);\n        sendHello({ probe: true, forceFullHydrate: true }); // one in-place reload equivalent\n      }\n    }\n  };\n\n  /** Backoff retry for a recovery whose ANSWER failed to apply: never a tight loop,\n   * never a silent give-up — each retry re-emits the `resync` diagnostic via `requestResync`. */\n  let resyncAttempts = 0;\n  let resyncTimer: ReturnType<typeof setTimeout> | undefined;\n  const clearResyncRetry = (): void => {\n    if (resyncTimer != null) {\n      clearTimeout(resyncTimer);\n      resyncTimer = undefined;\n    }\n  };\n  const scheduleResyncWithBackoff = (): void => {\n    // The failed frame may have BEEN the recovery answer — clear the in-flight flag so the retry\n    // hello is not suppressed by it.\n    helloInFlight = false;\n    if (resyncTimer != null) return; // one armed retry at a time\n    const delay = Math.min(250 * 2 ** resyncAttempts, 5_000);\n    resyncAttempts += 1;\n    const timer = setTimeout(() => {\n      resyncTimer = undefined;\n      requestResync(\"frame_error\");\n    }, delay);\n    unrefTimer(timer);\n    resyncTimer = timer;\n  };\n\n  const notifyPending = (): void => {\n    for (const listener of pendingListeners) listener();\n  };\n\n  // ── Projection: one Store flush per change to confirmed or pending ──\n\n  /** Patch-feed listeners + the last projection they were told about. */\n  const patchListeners = new Set<(patches: readonly Patch[], meta: IRealmPatchMeta) => void>();\n  let lastProjected: TView = {} as TView;\n  /**\n   * Batch coalescing (Phase 2): while applying one `batch` envelope's children, per-child `project()`\n   * calls are suppressed and collapsed into a single projection after the last child — N store\n   * flushes / re-renders / patch-feed emissions become one.\n   */\n  let projectSuppressed = false;\n  let suppressedProjectPending = false;\n  /**\n   * Provenance through the suppression window (Dirt Derby item 7): the collapsed post-batch flush\n   * reports `\"confirm\"` only when EVERY suppressed child projection was itself a confirm apply\n   * (fresh authority, no optimistic overlay) — one non-confirm child (an ack settle, a rebase)\n   * downgrades the whole collapse to `\"rebase\"`.\n   */\n  let batchAllConfirm = true;\n  /** {@link IRealmPatchMeta.authoritative} through the suppression window: OR of the children. */\n  let batchAnyAuthoritative = false;\n\n  /** Derive a flush's provenance from its delta (see {@link IRealmPatchMeta.cause}). */\n  const causeOfDelta = (delta?: {\n    confirmed?: Patch[];\n    fullReplace?: boolean;\n    cause?: TRealmPatchCause;\n    authoritative?: boolean;\n  }): TRealmPatchCause => {\n    if (delta?.fullReplace === true) return \"hydrate\";\n    if (delta?.confirmed != null) return \"confirm\";\n    return delta?.cause ?? \"rebase\";\n  };\n\n  /**\n   * Did this flush apply fresh authoritative state? (see {@link IRealmPatchMeta.authoritative}).\n   * Deliberately independent of `cause`: a hydrate and the C.2 fast path are authoritative by\n   * construction, and a patches frame landing under an optimistic overlay is authoritative too —\n   * it just cannot use the fast path, so it emits as `\"rebase\"`. That gap is the whole reason this\n   * field exists (Dirt Derby's Phase B census: at +200 ms a writing client received 60% of fresh\n   * authoritative ticks as `\"rebase\"`, because its outbox is non-empty for ~RTT after every input).\n   */\n  const isAuthoritative = (delta?: {\n    confirmed?: Patch[];\n    fullReplace?: boolean;\n    cause?: TRealmPatchCause;\n    authoritative?: boolean;\n  }): boolean => {\n    if (delta == null) return false; // a bare rebuild (ack settle, rollback, teardown)\n    if (delta.fullReplace === true || delta.confirmed != null) return true;\n    return delta.authoritative === true;\n  };\n\n  /**\n   * `delta.confirmed` = the authoritative patches that triggered this flush, when the caller\n   * verified the store carried no optimistic overlay (the C.2 fast path — emitted verbatim);\n   * `delta.fullReplace` = a rebuild (hydrate) — emit the root replace instead of a diff;\n   * `delta.cause` = an explicit provenance for flushes that emit a structural diff (an optimistic\n   * apply, the collapsed batch projection). No delta ⇒ a `\"rebase\"`-class rebuild.\n   */\n  const project = (delta?: {\n    confirmed?: Patch[];\n    fullReplace?: boolean;\n    cause?: TRealmPatchCause;\n    authoritative?: boolean;\n  }): void => {\n    if (projectSuppressed) {\n      // Inside a batch: defer to the single post-batch projection (the delta is dropped — a batch\n      // rebuilds via a structural diff, never the C.2 confirmed-only fast path). Provenance is\n      // folded into two booleans: any non-confirm child downgrades the collapse's cause (item 7\n      // note a), and any authoritative child makes the collapse authoritative (it applied server\n      // state, whatever else rode along).\n      suppressedProjectPending = true;\n      if (causeOfDelta(delta) !== \"confirm\") batchAllConfirm = false;\n      if (isAuthoritative(delta)) batchAnyAuthoritative = true;\n      return;\n    }\n    let projected: TView = confirmed;\n    const dropped: IPendingFrame[] = [];\n    for (const frame of pending) {\n      try {\n        projected = applyPatches(projected, frame.patches);\n      } catch {\n        // The rebase can no longer apply this frame (its parent vanished) ⇒ local reject.\n        dropped.push(frame);\n      }\n    }\n    if (dropped.length > 0) {\n      pending = pending.filter((frame) => !dropped.includes(frame));\n      for (const frame of dropped) {\n        settleReject(\n          frame,\n          err_realm.fromId(\"frame_too_stale\", { basisVersion: frame.basisVersion }),\n        );\n      }\n    }\n    projecting = true;\n    try {\n      store.replace(projected);\n    } finally {\n      projecting = false;\n    }\n\n    // The patch feed, after the store flush so listeners read consistent state.\n    if (projected !== lastProjected) {\n      const cause = causeOfDelta(delta);\n      const authoritative = isAuthoritative(delta);\n      // Devtools sees every flush's provenance, NOT only the flushes some unrelated\n      // `listenToPatches` consumer asked for. The three reads above are cheap; the expensive part\n      // (`diffProjected`) stays behind the listener check below, so an uninstrumented realm pays\n      // exactly what it did before and an instrumented one pays three field reads per flush.\n      devtools?.onFlush?.({ cause, authoritative, confirmedVersion });\n      if (patchListeners.size > 0) {\n        const emit: readonly Patch[] =\n          delta?.fullReplace === true\n            ? [{ op: \"replace\", path: [], value: projected }]\n            : (delta?.confirmed ?? diffProjected(lastProjected, projected));\n        if (emit.length > 0) {\n          const meta: IRealmPatchMeta = { cause, authoritative, confirmedVersion };\n          for (const listener of [...patchListeners]) listener(emit, meta);\n        }\n      }\n    }\n    lastProjected = projected;\n\n    notifyPending();\n  };\n\n  /** Apply authoritative patches to `confirmed`, tolerant of slice no-ops (replayed removes). */\n  const applyConfirmed = (patches: Patch[]): Patch[] => {\n    const applicable = patches.filter((patch) => {\n      if (patch.op !== \"remove\") return true;\n      let cursor: unknown = confirmed;\n      for (const seg of patch.path.slice(0, -1)) {\n        if (cursor == null || typeof cursor !== \"object\") return false;\n        cursor = (cursor as Record<string, unknown>)[seg];\n      }\n      return (\n        cursor != null &&\n        typeof cursor === \"object\" &&\n        String(patch.path[patch.path.length - 1]) in (cursor as object)\n      );\n    });\n    // A patch into a container this slice never received must not blow up the pipeline —\n    // synthesize the structural parents the schema declares (see structuralParents.ts).\n    const prepared = withStructuralParents(confirmed, applicable, realm.stateDef);\n    confirmed = applyPatches(confirmed, prepared);\n    return prepared;\n  };\n\n  // ── Settlement ───────────────────────────────────────────────────────────────\n\n  const settleReject = (frame: IPendingFrame, error: NiceError<any, any>): void => {\n    if (frame.expiryTimer != null) clearTimeout(frame.expiryTimer);\n    for (const handle of frame.handles) handle.reject(error);\n    devtools?.onMutation?.({\n      type: \"rejected\",\n      clientSeq: frame.clientSeq,\n      kind: frame.kind,\n      intentName: frame.intentName,\n      durability: frame.durability,\n      systemAssert: frame.isSystemAssert,\n      errorIds: error.getIds() as string[],\n      rolledBackPaths: frame.patches.map((patch) => patch.path.join(\".\")),\n    });\n    // A reassert-lane re-own (Phase 2) is a library-authored write, not a user mutation. Its\n    // link-loss rollback (`frame_too_stale`) is expected — it re-sends on the next hello — so it is\n    // NOT surfaced as a mutation rejection. A genuine authority (rules) rejection still surfaces:\n    // an `assertOnAttach` writing state it doesn't own is an app bug that must stay loud.\n    if (frame.isSystemAssert && (error.getIds() as string[]).includes(\"frame_too_stale\")) return;\n    emitRejection({\n      error,\n      kind: frame.kind,\n      intentName: frame.intentName,\n      rolledBackPaths: frame.patches.map((patch) => patch.path.join(\".\")),\n    });\n  };\n\n  const settleConfirm = (frame: IPendingFrame, version: number): void => {\n    if (frame.expiryTimer != null) clearTimeout(frame.expiryTimer);\n    // A confirmed round trip is a `realm.stats` sample: last send → this ack. Measured from\n    // `sendFrame`'s stamp — never from enqueue, so the coalesce window is not baked into the RTT.\n    if (frame.sentAt != null) recordRttSample(Date.now() - frame.sentAt);\n    for (const handle of frame.handles) handle.confirm({ version });\n    devtools?.onMutation?.({\n      type: \"confirmed\",\n      clientSeq: frame.clientSeq,\n      kind: frame.kind,\n      intentName: frame.intentName,\n      durability: frame.durability,\n      systemAssert: frame.isSystemAssert,\n      version,\n    });\n  };\n\n  const armExpiry = (frame: IPendingFrame): void => {\n    // The durable tier (§4): a reassert frame has no optimistic-settle deadline — it lives until\n    // the server answers (or the handle detaches). Link loss is survived by the reattach resend.\n    if (frame.durability === \"reassert\") return;\n    frame.expiryTimer = setTimeout(() => {\n      if (!pending.includes(frame)) return;\n      pending = pending.filter((candidate) => candidate !== frame);\n      settleReject(\n        frame,\n        err_realm.fromId(\"frame_too_stale\", { basisVersion: frame.basisVersion }),\n      );\n      project();\n    }, expiryMs);\n    // Never keep the process alive for a pending optimistic write.\n    unrefTimer(frame.expiryTimer);\n  };\n\n  // ── Outbound: coalescing flush + limit splitting ────\n\n  const sendFrame = (frame: IPendingFrame): void => {\n    if (port == null || !port.isOpen()) return; // resent on the next attach\n    // (Re-)stamp for `realm.stats`: a resend measures from ITSELF, so a post-outage confirm\n    // samples the network round trip that actually earned it, never the outage duration.\n    frame.sentAt = Date.now();\n    const encoded = frame.buildFrame(frame.clientSeq, frame.basisVersion);\n    devtools?.onFrame?.(\"out\", frame.kind, encoded.byteLength);\n    port.send(encoded);\n  };\n\n  /** One write frame per this many ops — the advertised limit, or a retry-halved local ceiling. */\n  let localMaxPatchesCeiling: number | undefined;\n  const effectiveMaxPatches = (): number =>\n    localMaxPatchesCeiling ?? advertisedLimits?.maxPatchesPerFrame ?? Number.POSITIVE_INFINITY;\n\n  const makeWritePart = (\n    clientSeq: number,\n    patches: Patch[],\n    basisVersion: number,\n    handles: IWriteHandleController[],\n    retries: number,\n    durability: \"reassert\" | undefined,\n  ): IPendingFrame => {\n    const part: IPendingFrame = {\n      clientSeq,\n      kind: \"write\",\n      patches,\n      basisVersion,\n      handles,\n      buildFrame: (seq, basis) =>\n        encodeWrite({\n          slot,\n          clientSeq: seq,\n          basisVersion: basis,\n          ops: namePatchesToWireOps(dedupeByPath(part.patches), realm.tokens),\n        }),\n      expiryTimer: undefined,\n      openForMerge: false,\n      retries,\n      durability,\n    };\n    return part;\n  };\n\n  /**\n   * Split one over-limit write frame into consecutive ≤`limit` parts: each part is\n   * atomic on the server; every settle handle rides the LAST part, so read-your-writes holds\n   * (acks are ordered). The trade — a split flush loses whole-flush atomicity — is documented on\n   * `update()`. Replaces `frame` in the pending queue in place, preserving projection order.\n   */\n  const splitFrame = (frame: IPendingFrame, deduped: Patch[], limit: number): IPendingFrame[] => {\n    if (frame.expiryTimer != null) clearTimeout(frame.expiryTimer);\n    const parts: IPendingFrame[] = [];\n    for (let offset = 0; offset < deduped.length; offset += limit) {\n      const chunk = deduped.slice(offset, offset + limit);\n      const isLast = offset + limit >= deduped.length;\n      parts.push(\n        makeWritePart(\n          parts.length === 0 ? frame.clientSeq : nextSeq++,\n          chunk,\n          frame.basisVersion,\n          isLast ? frame.handles : [],\n          frame.retries,\n          frame.durability, // split parts inherit the tier (a durable write stays durable)\n        ),\n      );\n    }\n    const index = pending.indexOf(frame);\n    if (index >= 0) pending.splice(index, 1, ...parts);\n    for (const part of parts) armExpiry(part);\n    return parts;\n  };\n\n  /** Seal one flushed frame: send it whole, or split first when it exceeds the advertised limit. */\n  const sealAndSend = (frame: IPendingFrame): void => {\n    if (frame.kind !== \"write\") {\n      sendFrame(frame);\n      return;\n    }\n    const deduped = dedupeByPath(frame.patches);\n    const limit = effectiveMaxPatches();\n    if (deduped.length <= limit) {\n      sendFrame(frame);\n      return;\n    }\n    for (const part of splitFrame(frame, deduped, limit)) sendFrame(part);\n  };\n\n  const flushOutbox = (): void => {\n    flushScheduled = false;\n    for (const frame of [...pending]) {\n      if (!frame.openForMerge) continue;\n      frame.openForMerge = false;\n      // Park while a recovery hello is in flight (Phase 1.4 / Issue 3 / the recovery contract): seal the frame\n      // (so it stops coalescing) but hold the send — the answer's `revalidateAndResendPending`\n      // resends survivors rebased and settles doomed ones locally, so nothing is streamed against a\n      // wiped transient region (the `write_target_missing` burst). The system-assert re-own still\n      // travels, riding the hello directly.\n      if (helloInFlight) continue;\n      sealAndSend(frame);\n    }\n  };\n\n  /**\n   * The leading-edge cooldown (Dirt Derby item 1): armed right after a leading send. While it\n   * runs, new writes open an ordinary merge frame; the window-END timer flushes them (the\n   * trailing half) and — having sent — re-arms, so sends stay capped at one per window. An idle\n   * window (nothing merged) simply expires: the next write is a fresh leading edge.\n   */\n  let leadingCooldownTimer: ReturnType<typeof setTimeout> | undefined;\n  const armLeadingCooldown = (): void => {\n    const timer = setTimeout(() => {\n      leadingCooldownTimer = undefined;\n      if (pending.some((frame) => frame.openForMerge)) {\n        flushOutbox();\n        armLeadingCooldown();\n      }\n    }, coalesceWindowMs);\n    unrefTimer(timer);\n    leadingCooldownTimer = timer;\n  };\n\n  const scheduleFlush = (): void => {\n    if (flushScheduled) return;\n    flushScheduled = true;\n    // Inside a leading cooldown the window-end timer IS the flush — arming another would double-send.\n    if (coalesceLeading && leadingCooldownTimer != null) return;\n    if (coalesceWindowMs > 0) {\n      const timer = setTimeout(flushOutbox, coalesceWindowMs);\n      unrefTimer(timer);\n    } else {\n      queueMicrotask(flushOutbox);\n    }\n  };\n\n  // ── Writes ───────────────────────────────────────────────────────\n\n  const rejectUnsent = (\n    controller: IWriteHandleController,\n    kind: \"write\" | \"intent\",\n    error: NiceError<any, any>,\n    intentName?: string,\n  ): IRealmWriteHandle => {\n    controller.reject(error);\n    emitRejection({ error, kind, intentName, rolledBackPaths: [] });\n    // Never enqueued (no clientSeq) — the timeline still shows the failed attempt.\n    devtools?.onMutation?.({\n      type: \"rejected\",\n      clientSeq: -1,\n      kind,\n      intentName,\n      errorIds: error.getIds() as string[],\n      rolledBackPaths: [],\n    });\n    return controller.handle;\n  };\n\n  const rejectImmediately = (\n    kind: \"write\" | \"intent\",\n    error: NiceError<any, any>,\n    intentName?: string,\n  ): IRealmWriteHandle => rejectUnsent(createWriteHandle(), kind, error, intentName);\n\n  // ── The pre-hydrate queue ────────────────────────────────────────────────────\n  // A write or intent made before the first hydrate has no state to run against (the projection\n  // is `{}`), so it waits here and runs against the hydrated view, in call order.\n\n  const neverHydratedError = (): NiceError<any, any> =>\n    attachError ?? err_realm.fromId(\"write_before_hydrate\", { realmId: realm.id });\n\n  const rejectQueued = (queued: IQueuedWrite, error: NiceError<any, any>): void => {\n    if (queued.expiryTimer != null) clearTimeout(queued.expiryTimer);\n    rejectUnsent(queued.controller, queued.kind, error, queued.intentName);\n  };\n\n  // A write made by an app callback during the hydrate (a `live` listener) lands behind the queue.\n  const mustQueueUntilHydrate = (): boolean => confirmedVersion === -1 || hydrating;\n\n  const queueUntilHydrate = (\n    queuedWrite: Pick<IQueuedWrite, \"kind\" | \"intentName\" | \"run\">,\n    durability?: \"reassert\",\n  ): IRealmWriteHandle => {\n    const controller = createWriteHandle();\n    if (status === \"detached\") {\n      return rejectUnsent(\n        controller,\n        queuedWrite.kind,\n        neverHydratedError(),\n        queuedWrite.intentName,\n      );\n    }\n    const queued: IQueuedWrite = { ...queuedWrite, controller, expiryTimer: undefined };\n    // Same deadline as a sent frame, and the same durable-tier exemption (see `armExpiry`).\n    if (durability !== \"reassert\") {\n      queued.expiryTimer = setTimeout(() => {\n        const index = hydrateQueue.indexOf(queued);\n        if (index < 0) return;\n        hydrateQueue.splice(index, 1);\n        const guard = createStepGuard();\n        guard.run(() => rejectQueued(queued, neverHydratedError()));\n        guard.run(notifyPending);\n        guard.rethrow();\n      }, expiryMs);\n      unrefTimer(queued.expiryTimer);\n    }\n    hydrateQueue.push(queued);\n    notifyPending();\n    return controller.handle;\n  };\n\n  const runQueued = (queued: IQueuedWrite): void => {\n    if (queued.expiryTimer != null) clearTimeout(queued.expiryTimer);\n    const { controller } = queued;\n    let sent: IRealmWriteHandle;\n    try {\n      sent = queued.run();\n    } catch (cause) {\n      // The caller's stack is gone, so a throwing updater cannot re-throw to it.\n      console.error(`${warnTag()} a write queued before the first hydrate threw`, cause);\n      rejectQueued(queued, castNiceError(cause));\n      return;\n    }\n    const settled = sent;\n    settled.then(controller.confirm, () => {\n      if (settled.error != null) controller.reject(settled.error);\n    });\n  };\n\n  /** Runs every queued write; a throwing app callback is held by `guard` and strands nothing. */\n  const drainHydrateQueue = (guard: IStepGuard): void => {\n    for (let queued = hydrateQueue.shift(); queued != null; queued = hydrateQueue.shift()) {\n      const next = queued;\n      guard.run(() => runQueued(next));\n    }\n    // A queued write that settled without sending (a no-op, a predicted reject) changed the count.\n    guard.run(notifyPending);\n  };\n\n  const rejectHydrateQueue = (): void => {\n    if (hydrateQueue.length === 0) return;\n    const guard = createStepGuard();\n    for (const queued of hydrateQueue.splice(0)) {\n      guard.run(() => rejectQueued(queued, neverHydratedError()));\n    }\n    guard.run(notifyPending);\n    guard.rethrow();\n  };\n\n  const enqueueWrite = (\n    patches: Patch[],\n    writeOptions?: IRealmUpdateOptions,\n  ): IRealmWriteHandle => {\n    const durability = writeOptions?.durability;\n    const immediate = writeOptions?.flush === \"immediate\";\n    // The durable backlog cap (§4): a long outage must not grow memory unboundedly — past the\n    // cap, new reassert writes reject loudly (the app falls back to its source-of-truth resync).\n    if (durability === \"reassert\") {\n      const backlog = pending.filter((frame) => frame.durability === \"reassert\").length;\n      if (backlog >= MAX_REASSERT_PENDING_FRAMES) {\n        return rejectImmediately(\n          \"write\",\n          err_realm.fromId(\"durable_backlog_overflow\", { pendingFrames: backlog }),\n        );\n      }\n    }\n    const controller = createWriteHandle();\n\n    // `flush: \"immediate\"` (Dirt Derby item 1): flush any buffered coalescing writes FIRST — the\n    // same compose-order rule intents follow — then this write rides its own sealed frame below.\n    // (flushOutbox seals every open frame even while parked, so no open frame survives to merge into.)\n    if (immediate) flushOutbox();\n\n    // Coalesce into the still-open write frame of this window when possible (same basis) —\n    // within the same durability tier only (§4): a durable write never merges into an expiring\n    // frame or vice versa.\n    const open = immediate\n      ? undefined\n      : pending.find(\n          (frame) =>\n            frame.kind === \"write\" && frame.openForMerge && frame.durability === durability,\n        );\n    if (open != null) {\n      open.patches.push(...patches);\n      open.handles.push(controller);\n      project({ cause: \"optimistic\" });\n      scheduleFlush();\n      return controller.handle;\n    }\n\n    const frame: IPendingFrame = {\n      clientSeq: nextSeq++,\n      kind: \"write\",\n      patches,\n      basisVersion: confirmedVersion,\n      handles: [controller],\n      // Client→server paths always use raw string record keys: interned ids are a *session*\n      // assignment, and a woken server session reassigns them — a stale id here would write the\n      // wrong path. The §12.1 byte win is the server→client fan-out; this direction stays safe.\n      buildFrame: (clientSeq, basisVersion) =>\n        encodeWrite({\n          slot,\n          clientSeq,\n          basisVersion,\n          ops: namePatchesToWireOps(dedupeByPath(frame.patches), realm.tokens),\n        }),\n      expiryTimer: undefined,\n      openForMerge: true,\n      retries: 0,\n      durability,\n    };\n    pending.push(frame);\n    devtools?.onMutation?.({\n      type: \"created\",\n      clientSeq: frame.clientSeq,\n      kind: \"write\",\n      durability,\n    });\n    armExpiry(frame);\n    project({ cause: \"optimistic\" });\n    if (immediate) {\n      // Own sealed frame, sent now. Under a recovery hello it seals but HOLDS (the parking\n      // invariant) — the answer's revalidate resends it rebased, like every sealed frame.\n      frame.openForMerge = false;\n      if (!helloInFlight) sealAndSend(frame);\n    } else if (coalesceLeading && leadingCooldownTimer == null) {\n      // The leading edge: no window is open, so this write sends NOW (flushOutbox seals + sends\n      // it, or parks it under a recovery hello) and the window opens as a cooldown behind it.\n      flushOutbox();\n      armLeadingCooldown();\n    } else {\n      scheduleFlush();\n    }\n    return controller.handle;\n  };\n\n  const applyUpdate = (\n    fn: (draft: TView) => void,\n    updateOptions?: IRealmUpdateOptions,\n  ): IRealmWriteHandle => {\n    const projected = store.state;\n    let returned: unknown;\n    const [next, patches] = produceWithPatches(projected, (draft) => {\n      returned = fn(draft as TView);\n    });\n    if (patches.length === 0) {\n      // Same footgun guard as @nice-code/state: `realm.update(() => nextState)` is mutate-only —\n      // a returned state would silently confirm as a no-op write, so throw a located error.\n      if (typeof returned === \"object\" && returned != null) {\n        throw new Error(\n          `[realm:${realm.id}] realm.update(fn): the update function returned a value without ` +\n            \"modifying its draft. Updates are mutate-only — a returned state is ignored \" +\n            \"(unlike immer's produce). Mutate the draft instead.\",\n        );\n      }\n      const controller = createWriteHandle();\n      controller.confirm({ version: confirmedVersion });\n      return controller.handle;\n    }\n    const canonical = canonicalizeStatePatches(patches, next, realm.stateDef);\n    const verdict = predictWrite({\n      realm,\n      patches: canonical,\n      avatar,\n      state: projected,\n      basisVersion: confirmedVersion,\n    });\n    if (verdict !== true) return rejectImmediately(\"write\", verdict);\n    return enqueueWrite(canonical, updateOptions);\n  };\n\n  const update = (\n    fn: (draft: TView) => void,\n    updateOptions?: IRealmUpdateOptions,\n  ): IRealmWriteHandle =>\n    mustQueueUntilHydrate()\n      ? queueUntilHydrate(\n          { kind: \"write\", run: () => applyUpdate(fn, updateOptions) },\n          updateOptions?.durability,\n        )\n      : applyUpdate(fn, updateOptions);\n\n  // ── Intents ──────────────────────────────────────────────────────\n\n  const runIntent = (name: string, input: unknown): IRealmWriteHandle =>\n    mustQueueUntilHydrate()\n      ? queueUntilHydrate({ kind: \"intent\", intentName: name, run: () => sendIntent(name, input) })\n      : sendIntent(name, input);\n\n  const sendIntent = (name: string, input: unknown): IRealmWriteHandle => {\n    const def = realm.intents[name] as IRealmIntentDef<TView, TAvatarType, TCtx> | undefined;\n    if (def == null) {\n      return rejectImmediately(\n        \"intent\",\n        err_realm.fromId(\"intent_unknown\", { intent: name }),\n        name,\n      );\n    }\n    const invalid = validateValue(def.input, input);\n    if (invalid != null) {\n      return rejectImmediately(\n        \"intent\",\n        err_realm.fromId(\"value_invalid\", {\n          path: [name, ...invalid.path].join(\".\"),\n          expected: invalid.expected,\n        }),\n        name,\n      );\n    }\n\n    // Preserve compose order: any coalescing writes buffered before this intent flush first.\n    flushOutbox();\n\n    // Optimistic prediction on a draft of the caller's view; a throwing predictor is absent.\n    let predicted: Patch[] = [];\n    if (def.optimistic != null) {\n      try {\n        const projected = store.state;\n        const [next, patches] = produceWithPatches(projected, (draft) => {\n          def.optimistic?.({ view: draft as TView, avatar, input: input as never });\n        });\n        predicted = canonicalizeStatePatches(patches, next, realm.stateDef);\n      } catch {\n        predicted = [];\n      }\n    }\n\n    const controller = createWriteHandle();\n    const intentToken = realm.intentNames.indexOf(name);\n    const frame: IPendingFrame = {\n      clientSeq: nextSeq++,\n      kind: \"intent\",\n      intentName: name,\n      patches: predicted,\n      basisVersion: confirmedVersion,\n      handles: [controller],\n      buildFrame: (clientSeq) => encodeIntent({ slot, clientSeq, intentToken, input }),\n      expiryTimer: undefined,\n      openForMerge: false, // intents never coalesce\n      retries: 0,\n    };\n    pending.push(frame);\n    devtools?.onMutation?.({\n      type: \"created\",\n      clientSeq: frame.clientSeq,\n      kind: \"intent\",\n      intentName: name,\n    });\n    armExpiry(frame);\n    if (predicted.length > 0) project({ cause: \"optimistic\" });\n    else notifyPending();\n    // Park during a recovery hello (Phase 1.4): the answer's `revalidateAndResendPending` resends\n    // it (intents are always kept) once the re-own is on the server, so a transient-reading intent\n    // never executes against a wiped region (Overshot Issue 2).\n    if (!helloInFlight) sendFrame(frame);\n    return controller.handle;\n  };\n\n  // ── Inbound frames ───────────────────────────────────────────────────────────\n\n  /**\n   * `limits_exceeded` recovery: a well-behaved client must survive a breach — even\n   * a mis-advertised limit — instead of settling the write as a fatal reject (and, ×10, being\n   * forcibly detached). Frame-size breaches re-split against a halved local ceiling; a rate\n   * breach resends after a backoff. Bounded by {@link MAX_LIMIT_RETRIES} and the frame's own\n   * expiry; unsplittable limits (record key length, expansion overflow) settle as before.\n   * Returns `true` when the reject was absorbed as a retry.\n   */\n  const retryLimitReject = (frame: IPendingFrame, error: NiceError<any, any>): boolean => {\n    if (frame.kind !== \"write\") return false;\n    if (!(error.getIds() as string[]).includes(\"limits_exceeded\")) return false;\n    if (frame.retries >= MAX_LIMIT_RETRIES) return false;\n    const breached: unknown = error.getContext(\"limits_exceeded\");\n    const limitName =\n      typeof breached === \"object\" && breached != null && \"limit\" in breached\n        ? String(breached.limit)\n        : \"\";\n\n    if (limitName === \"writeRatePerSecond\") {\n      frame.retries += 1;\n      const timer = setTimeout(() => {\n        // Hold if a recovery hello is in flight (Phase 1.4) — the answer's revalidate resends it.\n        if (pending.includes(frame) && !helloInFlight) sendFrame(frame);\n      }, RATE_RETRY_MS);\n      unrefTimer(timer);\n      return true;\n    }\n\n    if (limitName === \"maxPatchesPerFrame\" || limitName === \"maxFrameBytes\") {\n      frame.retries += 1;\n      const deduped = dedupeByPath(frame.patches);\n      if (deduped.length <= 1) return false; // cannot split further — settle the reject\n      // Halve the local ceiling below whatever we just sent (a mis-advertised limit converges).\n      localMaxPatchesCeiling = Math.max(\n        1,\n        Math.floor(Math.min(effectiveMaxPatches(), deduped.length) / 2),\n      );\n      for (const part of splitFrame(frame, deduped, localMaxPatchesCeiling)) sendFrame(part);\n      return true;\n    }\n\n    return false;\n  };\n\n  const revalidateAndResendPending = (): void => {\n    const kept: IPendingFrame[] = [];\n    // Structural fold basis: `confirmed` (already carrying the resume answer, incl. any\n    // transient reset/prune) layered with the frames we keep — so a write whose parent an earlier\n    // kept frame re-creates still applies.\n    let foldState: TView = confirmed;\n    // Fold any pending system-assert FIRST (Phase 2 / F4): the reassert-lane re-own re-creates a\n    // transient parent a wake reset, so pre-wake leaf writes rebase onto it here instead of\n    // false-dropping as `frame_too_stale`. It stays first in `kept`, so the resend loop below sends\n    // it ahead of every rebased frame — the ordering guarantee for a transient-reading intent.\n    for (const frame of pending) {\n      if (frame.isSystemAssert) {\n        try {\n          foldState = applyPatches(foldState, frame.patches);\n        } catch {\n          // A malformed re-own can't apply — leave the fold basis at confirmed; the entry heals on\n          // the assert's own broadcast/ack, and pre-wake leaves drop as before.\n        }\n      }\n    }\n    for (const frame of pending) {\n      if (frame.isSystemAssert) {\n        kept.push(frame); // stays at the front — sent first below, ahead of the rebased frames\n        continue;\n      }\n      const verdict =\n        frame.kind === \"intent\"\n          ? true // the server re-decides; client-supplied ids make retries idempotent (D6)\n          : predictWrite({\n              realm,\n              patches: frame.patches,\n              avatar,\n              state: confirmed,\n              basisVersion: confirmedVersion,\n            });\n      if (verdict !== true) {\n        settleReject(frame, verdict);\n        continue;\n      }\n      if (frame.kind === \"write\") {\n        // Doomed-resend guard: a write can pass schema+rules yet fail to APPLY when a\n        // resume refresh deleted its parent (a transient region reset by a wake, a pruned entry) —\n        // the server would reject it too (the parent is gone there as well). Settle it locally\n        // instead of round-tripping a guaranteed reject. `applyPatches` is the same tolerance\n        // `project()`'s rebase uses.\n        let nextFold: TView;\n        try {\n          nextFold = applyPatches(foldState, frame.patches);\n        } catch {\n          settleReject(\n            frame,\n            err_realm.fromId(\"frame_too_stale\", { basisVersion: frame.basisVersion }),\n          );\n          continue;\n        }\n        foldState = nextFold;\n      }\n      frame.basisVersion = confirmedVersion;\n      kept.push(frame);\n    }\n    // Commit the surviving queue BEFORE resending: on an in-memory link the ack can arrive\n    // synchronously inside `sendFrame` and must splice from the live queue, not a stale one.\n    pending = kept;\n    for (const frame of [...kept]) {\n      // Send every sealed survivor, the system-assert included and FIRST (it heads `kept`): the\n      // re-own reaches the server before the rebased writes/intents that read the re-created entry.\n      if (!frame.openForMerge) sendFrame(frame);\n    }\n  };\n\n  let hydrateChunks: Uint8Array[] = [];\n\n  const handleFrame = (frame: TRealmFrame): void => {\n    switch (frame.kind) {\n      case REALM_FRAME_KIND.batch: {\n        // Phase 2 egress envelope: apply every child through this same switch, but collapse their\n        // projections into one (the store flushes / patch-feed emits once for the whole envelope).\n        // Children are flat and non-batch (codec fuzz gate). Settlements (ack/reject confirm/reject\n        // the pending handles) are NOT suppressed — only the projection is — so read-your-writes\n        // still holds: the store is rebuilt before any `await handle` continuation runs.\n        const wasSuppressed = projectSuppressed;\n        projectSuppressed = true;\n        if (!wasSuppressed) {\n          // Fresh suppression window (item 7 note a).\n          batchAllConfirm = true;\n          batchAnyAuthoritative = false;\n        }\n        let childFailed = false;\n        let childError: unknown;\n        try {\n          for (const child of frame.frames) {\n            // Per-child isolation: one poisoned child must not abort its siblings —\n            // their settlements (ack/reject) still run. Safe because the continuity guard (F2)\n            // drops any later patches child that would now land on the wrong base. The first\n            // error is rethrown AFTER the batch projection, so the outer wrap resyncs once.\n            try {\n              handleFrame(child);\n            } catch (error) {\n              if (!childFailed) {\n                childFailed = true;\n                childError = error;\n              }\n            }\n          }\n        } finally {\n          projectSuppressed = wasSuppressed;\n        }\n        if (!projectSuppressed && suppressedProjectPending) {\n          suppressedProjectPending = false;\n          // The collapsed flush re-diffs (per-child deltas were dropped) — provenance survives as\n          // the two folded booleans: all-confirm children ⇒ \"confirm\", anything else ⇒ \"rebase\";\n          // any authoritative child ⇒ the collapse carries fresh server state.\n          project({\n            cause: batchAllConfirm ? \"confirm\" : \"rebase\",\n            authoritative: batchAnyAuthoritative,\n          });\n        }\n        if (childFailed) throw childError;\n        return;\n      }\n      case REALM_FRAME_KIND.hydrate: {\n        dict.load(frame.keyDictSeed);\n        // Chunked hydrate: buffer continuation chunks; apply atomically on the last.\n        hydrateChunks.push(frame.stateBlob);\n        if (frame.more) return;\n        const blob = concatChunks(hydrateChunks);\n        hydrateChunks = [];\n        // A first hydrate (no prior confirmed version) SEEDS the entry via the trailing `update`\n        // below; a resume hydrate (out-of-log-window / epoch change) may have reloaded the transient\n        // region empty and must re-own through the lane BEFORE revalidate, so a resent transient-\n        // reading intent is ordered after the re-own (D4). Captured before `confirmedVersion` moves.\n        const isFirstHydrate = confirmedVersion < 0;\n        confirmed = unpack(blob) as TView;\n        confirmedVersion = frame.version;\n        // The attach facts ride the hydrate: the epoch names the\n        // history this version belongs to, the limits drive flush splitting, and the identity\n        // echo catches the \"prediction and verdicts run against different clients\" bug class.\n        serverEpoch = frame.epoch;\n        advertisedLimits = {\n          maxPatchesPerFrame: frame.limits[0],\n          maxFrameBytes: frame.limits[1],\n          writeRatePerSecond: frame.limits[2],\n        };\n        localMaxPatchesCeiling = undefined; // fresh advertisement supersedes any retry-halved ceiling\n        warnOnIdentityMismatch(frame.avatar);\n        // App callbacks below (status/patch listeners, `assertOnAttach`) may throw. Each step still\n        // runs and the pre-hydrate queue still drains; the first error is rethrown at the end.\n        hydrating = true;\n        const guard = createStepGuard();\n        try {\n          guard.run(() => setStatus(\"live\"));\n          if (helloInFlight) recordRttSample(Date.now() - helloSentAt); // hello → hydrate answer\n          helloInFlight = false; // the hello is answered\n          // A RESUME hydrate re-owns through the reassert lane, sampled from the just-hydrated\n          // `confirmed` (a wiped transient entry is genuinely absent there) — so a guarded\n          // assert observes the loss, and the re-own is folded + sent AHEAD of any resent\n          // transient-reading intent (D4: without this, revalidate below would resend a pre-wake\n          // `fire` before the post-project `update` re-own, deterministically rejecting\n          // `not_joined`). Skipped on the first hydrate (seeded below) and when the pre-answer\n          // lane already queued the re-own.\n          if (\n            !isFirstHydrate &&\n            realm.transient.length > 0 &&\n            options.assertOnAttach != null &&\n            !hasPendingSystemAssert()\n          ) {\n            guard.run(() => enqueueSystemAssert(confirmed));\n          }\n          // Revalidate first: it folds the pending reassert-lane re-own (Phase 2) and (re)sends\n          // the queue with the re-own ordered ahead of every rebased frame. Then rebuild the store.\n          guard.run(revalidateAndResendPending);\n          // A hydrate is a rebuild for the patch feed (C.2).\n          guard.run(() => project({ fullReplace: true }));\n          // The presence primitive (G1): SEED this avatar's own state on a first hydrate (a\n          // transient region is genesis-empty here), and cover the healthy-resume idempotent\n          // rewrite — an ordinary optimistic write enqueued AFTER the store rebuild so its draft\n          // reads the fresh hydrated view, and before the microtask-deferred `whenLive()`\n          // continuations observe the store. Skipped when the reassert lane already carries the\n          // re-own for this hello (Phase 2).\n          const assertOnAttach = options.assertOnAttach;\n          if (assertOnAttach != null && !hasPendingSystemAssert()) {\n            guard.run(() => applyUpdate(assertOnAttach));\n          }\n        } finally {\n          drainHydrateQueue(guard);\n          hydrating = false;\n        }\n        // Tripwire settle point (Phase 2), incl. the forced-hydrate escalation answer: verify the\n        // watched parent was re-created (skipped while a lane re-own is still pending).\n        checkReownWatch();\n        // A throwing callback still surfaces as `frame_error` and a resync.\n        guard.rethrow();\n        return;\n      }\n      case REALM_FRAME_KIND.keyDict: {\n        dict.load(frame.entries);\n        return;\n      }\n      case REALM_FRAME_KIND.patches: {\n        // Version-continuity guard: a frame must either advance FROM our confirmed\n        // version (normal flow; transient-only frames have from === to === confirmed), or be a\n        // continuation chunk of a split flush (chunks share from/to — the first advanced\n        // `confirmedVersion` to `toVersion`, chunks 2..n re-arrive with to === confirmed and\n        // their absolute ops apply safely at the unchanged version). Anything else is a gap\n        // (a lost/misapplied frame) or a foreign history — applying it would silently diverge.\n        const isContinuous = frame.fromVersion === confirmedVersion;\n        const isContinuation = frame.toVersion === confirmedVersion;\n        if (!isContinuous && !isContinuation) {\n          if (helloInFlight) {\n            // Crossed our in-flight hello on the wire — the replay/hydrate answer supersedes it.\n            onDiagnostic({\n              type: \"gap_dropped\",\n              fromVersion: frame.fromVersion,\n              toVersion: frame.toVersion,\n              confirmedVersion,\n            });\n          } else {\n            requestResync(\"version_gap\", {\n              fromVersion: frame.fromVersion,\n              toVersion: frame.toVersion,\n              confirmedVersion,\n            });\n          }\n          return;\n        }\n        // An acceptance-passing frame IS the recovery answer (cleared before the apply so a\n        // Phase-3 apply failure can immediately re-hello without tripping the in-flight guard).\n        const answeredHello = helloInFlight;\n        helloInFlight = false;\n        // A hello answer is a `realm.stats` sample — this is how a read-mostly client samples at\n        // its staleness-probe cadence for free (the ~10 B empty replay). A broadcast racing the\n        // in-flight hello can under-report (it \"answers\" sooner than the true reply); rare by\n        // construction — a probe only fires after a quiet window — and the EWMA absorbs it.\n        if (answeredHello) recordRttSample(Date.now() - helloSentAt);\n        // Prototype-pollution deny-list (Phase 5): drop any patch whose path carries an unsafe\n        // record key before it touches confirmed/projected state — defense against a hostile or\n        // replayed server frame (the server never emits one; a well-behaved link is a no-op).\n        const patches = wireOpsToNamePatches(frame.ops, realm.tokens, (id) =>\n          dict.keyOf(id),\n        ).filter((patch) => !pathHasUnsafeKey(patch.path));\n        // C.2 fast path: no optimistic overlay in the store ⇒ the projected delta IS the\n        // authoritative patches — no diff needed.\n        const clean = pending.length === 0 && lastProjected === confirmed;\n        const applied = applyConfirmed(patches);\n        confirmedVersion = frame.toVersion;\n        // The recovery tail in the required order (§2.2 / F4), on EVERY answered hello — both\n        // resume shapes answer a tracked hello: a `connecting` reconnect AND a `live` probe/rehello\n        // (Phase 1.1 makes even the periodic probe tracked, so it heals here too, closing the\n        // silent-loss hole the recovery contract found). A resume answer refreshes transient regions to their\n        // CURRENT server value — which a same-epoch DO wake reset to genesis (or a prune emptied) —\n        // so re-own this avatar's own entry BEFORE revalidating, so pending leaf writes rebase onto\n        // the re-created parent instead of false-dropping (`write_target_missing`/`frame_too_stale`).\n        if (answeredHello) {\n          // Re-own through the reassert lane, sampled from the POST-answer `confirmed` (the transient\n          // replace at `applyConfirmed` above already landed, so a wiped entry is genuinely absent\n          // here) — this is what lets a GUARDED assert observe the loss and re-create the entry, the\n          // stall the old `update(store.state)` fallback could never break (it read the projection one\n          // `project()` before it was rebuilt, so the guard always saw a stale-present entry). Routing\n          // through the lane — not `update()` — also puts the re-own at the FRONT of `pending`, so\n          // `revalidateAndResendPending` folds AND sends it ahead of every resent frame (a pre-wake\n          // `fire` runs against the re-owned entry, never the wiped region). Skipped when the\n          // pre-answer lane already queued a re-own (unconditional assert) — clobbering it would drop\n          // that frame's preserved pre-wake value.\n          if (!hasPendingSystemAssert()) enqueueSystemAssert(confirmed);\n          revalidateAndResendPending();\n        }\n        if (status === \"connecting\") setStatus(\"live\"); // a replay answered our hello — live now\n        // BOTH branches applied fresh authoritative patches — `clean` only decides whether the\n        // emission can be the server's ops verbatim (C.2) or must be a structural diff under the\n        // overlay. The `authoritative: true` on the slow branch is what a reconciler actually\n        // needs: gating on `cause === \"confirm\"` here discards it (Dirt Derby's census: 60% of\n        // fresh ticks at +200 ms, because a writing client's outbox is non-empty for ~RTT).\n        project(clean && pending.length === 0 ? { confirmed: applied } : { authoritative: true });\n        // Tripwire settle point (Phase 2): a resync answer that produced NO re-own (no assert, or a\n        // guard that saw the parent already present) leaves the watched parent unhealed — emit\n        // `reown_missing` + escalate once. Skipped while a re-own is still pending (checked on its ack).\n        checkReownWatch();\n        return;\n      }\n      case REALM_FRAME_KIND.ack: {\n        const index = pending.findIndex((candidate) => candidate.clientSeq === frame.clientSeq);\n        if (index < 0) return;\n        const [settledFrame] = pending.splice(index, 1);\n        settleConfirm(settledFrame, frame.version);\n        project();\n        // A re-own (system-assert) just landed — the tripwire's settle point: verify it re-created\n        // the watched parent (Phase 2). `confirmed` already carries the re-own's broadcast echo.\n        if (settledFrame.isSystemAssert) checkReownWatch();\n        return;\n      }\n      case REALM_FRAME_KIND.reject: {\n        const error = castNiceError(frame.error);\n        if (frame.clientSeq === -1) {\n          // Attach failure sentinel (schema mismatch / unknown realm).\n          attachError = error;\n          helloInFlight = false; // answered, terminally\n          setStatus(\"detached\");\n          return;\n        }\n        const index = pending.findIndex((candidate) => candidate.clientSeq === frame.clientSeq);\n        if (index < 0) {\n          // A reject for a frame no longer pending (Phase 1.5 / the recovery contract): it settled between send\n          // and reject (rebased away by a resume, or expired), or is a stale duplicate. Silent today;\n          // surfaced now — it is the fingerprint of a divergence window and would have pinned the\n          // demo-board trigger in one console read.\n          onDiagnostic({\n            type: \"late_reject\",\n            clientSeq: frame.clientSeq,\n            errorIds: error.getIds() as string[],\n          });\n          return;\n        }\n        if (retryLimitReject(pending[index], error)) return; // recoverable breach\n        const [rejectedFrame] = pending.splice(index, 1);\n        settleReject(rejectedFrame, error);\n        project(); // atomic single-flush rollback\n        // Structural divergence self-heal (Phase 1.5 / the recovery contract): a `write_target_missing` reject\n        // proves the client predicted a write the server could not apply — its confirmed state is\n        // stale (a transient region reset / entry pruned that never reached us). Re-read via a\n        // probe-flavored, tracked resync whose answer re-owns the entry — converting the the recovery contract\n        // sustained reject loop into ONE round-trip, regardless of what deleted the entry.\n        if ((error.getIds() as string[]).includes(\"write_target_missing\")) {\n          // Flag the rejected write's parent(s) for the reown tripwire (Phase 2): if the recovery\n          // re-own does not re-create them, `checkReownWatch` emits `reown_missing` (Overshot ask #2).\n          for (const patch of rejectedFrame.patches) {\n            if (patch.path.length > 1) {\n              const parent = patch.path.slice(0, -1) as string[];\n              reownWatch.set(JSON.stringify(parent), parent);\n            }\n          }\n          requestResync(\"write_target_missing\");\n        }\n        // A settled re-own (system-assert) is a tripwire checkpoint — did the parent actually land?\n        if (rejectedFrame.isSystemAssert) checkReownWatch();\n        return;\n      }\n      case REALM_FRAME_KIND.detach: {\n        if (frame.reason === REALM_DETACH_REASON_REHELLO) {\n          // A woken server (or one that lost this slot) asks us to re-attach. Probe-flavored\n          // (Phase 1.2): the link never dropped and the heal is one round-trip, so keep `live` —\n          // no HUD flap on every DO wake (Overshot Issue 1). Tracked (1.1), so its answer re-owns\n          // transient state; the escalation deadline (armed by the probe) flips to `connecting`\n          // only if the re-hello goes unanswered — status moves on evidence of an outage, not a\n          // protocol chore. Skip when a hello is already in flight.\n          if (status === \"live\") sendHello({ probe: true });\n          return;\n        }\n        helloInFlight = false;\n        setStatus(\"detached\");\n        return;\n      }\n      default:\n        return;\n    }\n  };\n\n  /**\n   * The defensive inbound boundary: every inbound frame runs through `handleFrame`\n   * inside this wrap. A decode/apply throw — an unknown interned key id (`detokenizePath`), a\n   * patch that can't resolve its parent (`applyConfirmed`) — must NOT escape into the wire mux,\n   * silently drop the frame, or (inside a batch) abort its siblings. On any failure we heal the\n   * same way a version gap does: re-hello with backoff. `lastSyncInboundAt` is stamped only AFTER a\n   * clean handling, so a throwing frame no longer fools the staleness probe into thinking the\n   * link is healthy — and only for a frame that actually carries sync information\n   * ({@link provesSyncHealth}), so a reject cannot either.\n   */\n  const onFrame = (frame: TRealmFrame, byteSize?: number): void => {\n    devtools?.onFrame?.(\n      \"in\",\n      REALM_FRAME_KIND_NAME[frame.kind] ?? String(frame.kind),\n      byteSize ?? 0,\n    );\n    try {\n      handleFrame(frame);\n    } catch (error) {\n      onDiagnostic({ type: \"frame_error\", error });\n      hydrateChunks = []; // a mid-hydrate failure must not poison the next hydrate's reassembly\n      scheduleResyncWithBackoff();\n      return;\n    }\n    // Everything below asks the same question — \"did the server just tell us something that proves\n    // we are in sync?\" — and a `reject` is the one clean frame whose answer is no. All\n    // three of these used to accept any clean frame, which made a reject a *recovery suppressant*:\n    // it pushed the probe's clock forward, called off an armed escalation, and cancelled a\n    // scheduled resync retry, each while leaving the client exactly as desynced as it was.\n    if (!provesSyncHealth(frame)) return;\n    lastSyncInboundAt = Date.now(); // clean handling only\n    resyncAttempts = 0; // a syncing frame proves recovery worked — reset the backoff ladder\n    clearResyncRetry();\n    if (probeDeadline != null) {\n      // Our probe was answered — cancel the pending escalation.\n      clearTimeout(probeDeadline);\n      probeDeadline = undefined;\n    }\n  };\n\n  // ── Attach lifecycle ─────────────────────────────────────────────────────────\n\n  /**\n   * The identity echo check: the hydrate names the avatar the server resolved —\n   * the one verdicts and view slicing run against. A disagreement with our own ref is the\n   * silent-flicker bug class (prediction passes locally, the server rejects every time), so it\n   * warns loudly, once per handle.\n   */\n  const warnOnIdentityMismatch = (echo: [string, string, string]): void => {\n    const [type, persistentId, instanceId] = echo;\n    if (\n      type === avatar.type &&\n      persistentId === avatar.persistentId &&\n      instanceId === avatar.instanceId\n    ) {\n      return;\n    }\n    if (identityWarned) return;\n    identityWarned = true;\n    console.warn(\n      `${warnTag()} identity mismatch — this client predicts as ` +\n        `${avatar.type}/${avatar.persistentId}/${avatar.instanceId} but the server resolved it as ` +\n        `${type}/${persistentId}/${instanceId}. Prediction and view slicing run ` +\n        \"against DIFFERENT identities: owner-gated writes will pass locally and reject on the \" +\n        \"server. Fix the server's resolveAvatar/avatarType, or the avatar passed to connectRealm.\",\n    );\n  };\n\n  /**\n   * The reassert lane (Phase 2 / Overshot Issue 2): ride a recovery hello with a re-own WRITE so a\n   * transient entry a wake reset is re-created server-side BEFORE any resent frame executes — so an\n   * intent that reads transient state (a `fire` reading `aim[me]`) runs against the re-owned entry,\n   * not the wiped region. It uses the sentinel `clientSeq: -2`, which the engine applies through the\n   * full rules pipeline but skips the replay high-water — so it can be ordered on the wire ahead of\n   * pending frames without swallowing their seqs (the §0 constraint that makes a naive \"assert as a\n   * normal write, sent first\" unsafe: its higher seq would advance the high-water and the resent\n   * intents would be dup-acked as already-processed, falsely confirmed but never run).\n   *\n   * Skipped when there is nothing to re-own (no `assertOnAttach`, no transient region, or a no-op\n   * draft) and before the first hydrate (the hydrate's own assert seeds the entry). Only one is\n   * pending at a time; a second hello supersedes it (idempotent — no user handle).\n   *\n   * **Sampling basis (`sampleState`) is the whole fix for the guarded-assert stall (Overshot 0.48).**\n   * A guarded re-own (`if (draft.mine != null) return`) can only fire against state that reflects a\n   * wake wipe. Two call sites, deliberately different bases:\n   * - `sendHello` samples `store.state` — the OPPORTUNISTIC pre-answer lane. The client has not yet\n   *   learned a same-epoch wake wiped the region (no version advance, no broadcast), so a guarded\n   *   assert sees its entry present and produces nothing here; an UNCONDITIONAL rewrite still fires\n   *   and rides the recovery for a flicker-free re-own that preserves the pre-wake value.\n   * - the resume answer (patches/hydrate) samples `confirmed` AFTER the answer's transient-region\n   *   replace has been applied — the AUTHORITATIVE basis where a wiped entry is genuinely absent, so\n   *   a guarded assert finally observes the loss and re-creates it. Skipped when the pre-answer lane\n   *   already produced a frame (unconditional case) so that frame's pre-wake value is not clobbered.\n   */\n  const enqueueSystemAssert = (sampleState: TView): void => {\n    if (options.assertOnAttach == null || realm.transient.length === 0) return;\n    if (confirmedVersion < 0) return; // first attach: the hydrate's own assert seeds the entry\n    if (port == null || !port.isOpen()) return;\n    const [next, patches] = produceWithPatches(sampleState, (draft) => {\n      options.assertOnAttach?.(draft as TView);\n    });\n    if (patches.length === 0) return; // nothing to re-own\n    const canonical = canonicalizeStatePatches(patches, next, realm.stateDef);\n    if (canonical.length === 0) return;\n    // Supersede any prior pending re-own (a rapid second hello) — it has no user handle to settle.\n    if (pending.some((frame) => frame.isSystemAssert)) {\n      pending = pending.filter((frame) => !frame.isSystemAssert);\n    }\n    const frame: IPendingFrame = {\n      clientSeq: SYSTEM_ASSERT_SEQ,\n      kind: \"write\",\n      patches: canonical,\n      basisVersion: confirmedVersion,\n      handles: [],\n      buildFrame: (clientSeq, basisVersion) =>\n        encodeWrite({\n          slot,\n          clientSeq,\n          basisVersion,\n          ops: namePatchesToWireOps(dedupeByPath(canonical), realm.tokens),\n        }),\n      expiryTimer: undefined, // never expires: re-sent on the next hello, superseded, or torn down\n      openForMerge: false,\n      retries: 0,\n      isSystemAssert: true,\n    };\n    // Front of the queue so `revalidateAndResendPending` folds AND sends it first — the re-own\n    // reaches the server ahead of every rebased frame (writes and intents). It is enqueued (not sent\n    // here): the answer's revalidate is the single send point, which keeps the ordering correct under\n    // both the async wire (hello → answer → assert+resends) and the synchronous test loopback (where\n    // the answer is processed inside `port.send(hello)`, so a here-and-now send would race behind it).\n    pending.unshift(frame);\n    // Show the re-owned entry optimistically at once (the dot never flickers). A speculative\n    // local apply — `\"optimistic\"` provenance, like any other un-acked write echo.\n    project({ cause: \"optimistic\" });\n  };\n\n  /**\n   * (Re-)attach to the server. Every hello is **tracked** (Phase 1.1): its answer runs the recovery\n   * tail (revalidate + the transient re-own) regardless of shape, so a probe/rehello heals transient\n   * state exactly like a reconnect. `probe` is presentation only — it decides the status flip and\n   * the key-dict clear, not whether the answer heals:\n   *\n   * - A **non-probe** hello (first attach, reconnect) flips status to `connecting` and resets the\n   *   key dict — a genuine re-attach may face a fresh/woken session that reassigns interned ids from\n   *   zero.\n   * - A **probe** hello (staleness probe, wake rehello, `write_target_missing` resync) keeps `live`\n   *   status (no HUD flap on a link that never dropped) and KEEPS the dict: it rides the same-or-woken\n   *   session where the server re-sends a delta before first use of any id and `RealmKeyDict.load`\n   *   overwrites, so a reassigned id is corrected before it is ever resolved. It arms the\n   *   escalation deadline instead — no inbound within the window ⇒ the link is genuinely dead and\n   *   status flips to `connecting` truthfully (Phase 1.2).\n   */\n  const sendHello = (opts?: { probe?: boolean; forceFullHydrate?: boolean }): void => {\n    if (opts?.probe !== true) {\n      setStatus(\"connecting\");\n      attachError = undefined;\n      // Interned ids are session-scoped: a fresh/woken server session reassigns them and re-sends\n      // deltas before first use — stale entries must not survive into the new session. A probe rides\n      // the same session, so its dict stays (F4 — see the docstring).\n      dict.clear();\n    } else {\n      // Probe-flavored: keep `live`, arm the escalation backstop (Phase 1.2). `lastProbeAt` stamps\n      // the moment so escalation's \"did a reply arrive?\" check (`lastInboundAt >= lastProbeAt`) works.\n      lastProbeAt = Date.now();\n      armProbeEscalation();\n    }\n    // Tracked in EVERY shape (Phase 1.1 / the reconnect contract): until answered, a non-continuous patches frame\n    // that predates this hello drops instead of applying, and the answer runs the recovery tail.\n    helloInFlight = true;\n    helloSentAt = Date.now();\n    hydrateChunks = [];\n    // Queue the reassert-lane re-own (Phase 2) BEFORE sending the hello so it is already pending when\n    // the answer's revalidate runs — the answer sends it first, ahead of every rebased frame, so the\n    // server sees hello → assert → resent pending and a transient-reading intent runs against the\n    // re-owned entry (Overshot Issue 2). Sampled from `store.state` — the OPPORTUNISTIC pre-answer\n    // lane: an unconditional re-own fires here (flicker-free, pre-wake value preserved); a guarded\n    // one produces nothing yet (the wipe is not known) and is re-sampled from `confirmed` post-answer.\n    // No-op on the first attach / non-transient realm.\n    enqueueSystemAssert(store.state);\n    const hello = encodeHello({\n      slot,\n      realmId: realm.id,\n      schemaHash: realm.schemaHash,\n      // The reown-tripwire escalation (Phase 2) forces the server's full-hydrate branch by asking\n      // as if from genesis (`-1` fails the server's `lastKnownVersion >= 0` replay gate) — the\n      // in-place page-reload equivalent, landing on the Phase-1 hydrate re-own against fresh state.\n      // `confirmedVersion` is left untouched: the hydrate answer rebuilds it, and a lost escalation\n      // must not strand the client at `-1`.\n      lastKnownVersion: opts?.forceFullHydrate === true ? -1 : confirmedVersion,\n      epoch: serverEpoch,\n    });\n    devtools?.onFrame?.(\"out\", \"hello\", hello.byteLength);\n    port?.send(hello);\n    // Advertise egress features right after every hello (Phase 1) — including a probe/rehello, so a\n    // hibernation-woken server that lost this connection's feature state re-learns them for free. No\n    // probe-time pre-resend anymore (deleted: it round-tripped doomed frames into\n    // `write_target_missing` on a reset server; every answer now revalidates + resends instead).\n    const caps = encodeClientCaps({ slot, features: [REALM_FEATURE.batch] });\n    devtools?.onFrame?.(\"out\", \"clientCaps\", caps.byteLength);\n    port?.send(caps);\n  };\n\n  // Client-side security floor: if the connection's negotiated level is\n  // below the realm's required minimum, do NOT register handlers or send `hello` — that first frame\n  // would carry avatar identity/state onto the link as app-layer plaintext (the server gate stops\n  // *routing*, not *sending*). Fail the attach; whenLive() rejects with the reason. A bare-mux /\n  // loopback adapter reports no level and is skipped (documented in assertRealmSecurity).\n  let unsubscribeLinkEvents: (() => void) | undefined;\n  const securityShortfall = computeRealmSecurityShortfall(\n    options.connection,\n    realm,\n    options.security,\n  );\n  if (securityShortfall != null) {\n    attachError = securityShortfall;\n    setStatus(\"detached\");\n    options.connection.release();\n  } else {\n    port = options.connection.register({\n      onFrame,\n      onAttach: () => sendHello(),\n      onDetach: () => {\n        if (status !== \"detached\") setStatus(\"connecting\");\n      },\n    });\n    // The link may already be live (a realm attaching to an established action socket).\n    if (port.isOpen()) sendHello();\n    // Forward a link re-establishment into the diagnostics: the one\n    // transport event realm telemetry sees. `downForMs` present ⇒ a REdial (the first-ever\n    // establishment carries none and is not churn).\n    unsubscribeLinkEvents = options.connection.subscribeLinkEvents?.((event) => {\n      if (event.type === \"link_up\" && event.downForMs != null) {\n        onDiagnostic({ type: \"link_redialed\", downForMs: event.downForMs });\n      }\n    });\n  }\n\n  // ── The staleness probe + escalation ────────────\n  // (Config + `armProbeEscalation` are declared up top so the rehello/resync paths share them.)\n  let probeTimer: ReturnType<typeof setInterval> | undefined;\n  if (securityShortfall == null && staleProbeAfterMs > 0) {\n    probeTimer = setInterval(\n      () => {\n        if (status !== \"live\" || port?.isOpen() !== true) return;\n        const now = Date.now();\n        if (now - lastSyncInboundAt < staleProbeAfterMs) return;\n        if (now - lastProbeAt < staleProbeAfterMs) return; // one probe per quiet window\n        // Tracked (Phase 1.1) + escalation-armed inside `sendHello({ probe })`: the answer runs the\n        // full recovery tail (revalidate + transient re-own), closing the former silent-loss hole\n        // where an untracked probe answer skipped the re-own.\n        sendHello({ probe: true });\n      },\n      Math.max(1_000, Math.floor(staleProbeAfterMs / 2)),\n    );\n    // Never keep the process alive for a liveness probe.\n    unrefTimer(probeTimer);\n  }\n\n  // ── D4 write-through (experimental, the protocol contract) ───────────────────────────────\n\n  if (options.experimental_writeThroughStore === true) {\n    store.listenToPatches((allPatches) => {\n      // Our own projection flushes arrive here too (`store.replace` emits a root replace patch\n      // since replaces joined the patch stream) — the synchronous `projecting` window filters\n      // them out, leaving only raw user `store.update(...)` writes, already applied\n      // optimistically to the store by Store itself.\n      if (projecting) return;\n      // A root replace (path []) is a wholesale swap, not a realm write — never send it.\n      const patches = allPatches.filter((patch) => patch.path.length > 0);\n      if (patches.length === 0) return;\n      // Deferred one microtask: patch listeners fire *before* Store.update commits its state,\n      // so a synchronous rollback here would be overwritten by that commit (the re-entrancy\n      // hazard §9.2 flags — this deferral is the guard the gate suite exercises).\n      queueMicrotask(() => {\n        const canonical = canonicalizeStatePatches(patches, store.state, realm.stateDef);\n        if (canonical.length === 0) return;\n        const verdict = predictWrite({\n          realm,\n          patches: canonical,\n          avatar,\n          state: store.state,\n          basisVersion: confirmedVersion,\n        });\n        if (verdict !== true) {\n          emitRejection({\n            error: verdict,\n            kind: \"write\",\n            rolledBackPaths: canonical.map((patch) => patch.path.join(\".\")),\n          });\n          project(); // snap the raw store write back to the projection\n          return;\n        }\n        enqueueWrite(canonical);\n      });\n    });\n  } else {\n    // The silent-divergence footgun: with write-through off, a raw\n    // `realm.store.update()` mutates the local projection only — nothing is sent, nothing rolls\n    // back, and the next flush rebuilds the projection and the change *un-happens*. Catch it at\n    // the moment of the mistake, once per handle.\n    let warnedStoreWrite = false;\n    store.listenToPatches(() => {\n      if (projecting || warnedStoreWrite) return;\n      warnedStoreWrite = true;\n      console.warn(\n        `${warnTag()} realm.store was written directly. The store is a read projection — ` +\n          \"this change was never sent to the server and will vanish on the next incoming flush. \" +\n          \"Did you mean realm.update()? (Raw store write-through requires the \" +\n          \"experimental_writeThroughStore option.)\",\n      );\n    });\n  }\n\n  // ── The public handle ────────────────────────────────────────────────────────\n\n  const intents = Object.fromEntries(\n    realm.intentNames.map((name) => [name, (input: unknown) => runIntent(name, input)]),\n  ) as IRealmHandle<TView, TIntents>[\"intents\"];\n\n  const handle: IRealmHandle<TView, TIntents, TAvatarType> = {\n    store: store as Store<TView & object>,\n    avatar,\n    update,\n    intents,\n    pending: {\n      get count() {\n        // The reassert-lane re-own (Phase 2) is a library-internal write, not a user mutation —\n        // exclude it so `pendingCount` keeps meaning \"the user's writes awaiting the server\".\n        return (\n          pending.reduce((n, frame) => (frame.isSystemAssert ? n : n + 1), 0) + hydrateQueue.length\n        );\n      },\n      has(pathPrefix: string) {\n        return pending.some(\n          (frame) =>\n            !frame.isSystemAssert &&\n            frame.patches.some((patch) => patch.path.join(\".\").startsWith(pathPrefix)),\n        );\n      },\n      subscribe(listener) {\n        pendingListeners.add(listener);\n        return () => pendingListeners.delete(listener);\n      },\n    },\n    get status() {\n      return status;\n    },\n    get hasBeenLive() {\n      return hasBeenLive;\n    },\n    get version() {\n      return confirmedVersion;\n    },\n    get attachError() {\n      return attachError;\n    },\n    whenLive(opts?: { timeoutMs?: number }) {\n      if (status === \"live\") return Promise.resolve();\n      if (attachError != null) return Promise.reject(attachError);\n      if (status === \"detached\")\n        return Promise.reject(new Error(\"whenLive: the realm is detached\"));\n      return new Promise<void>((resolve, reject) => {\n        const timeoutMs = opts?.timeoutMs ?? 10_000;\n        const cleanup = (): void => {\n          clearTimeout(timer);\n          statusListeners.delete(listener);\n        };\n        const timer = setTimeout(() => {\n          cleanup();\n          reject(new Error(`whenLive: the realm did not hydrate within ${timeoutMs}ms`));\n        }, timeoutMs);\n        const listener = (): void => {\n          if (status === \"live\") {\n            cleanup();\n            resolve();\n          } else if (attachError != null || status === \"detached\") {\n            cleanup();\n            reject(attachError ?? new Error(\"whenLive: the realm detached before going live\"));\n          }\n        };\n        statusListeners.add(listener);\n      });\n    },\n    subscribeStatus(listener) {\n      statusListeners.add(listener);\n      return () => statusListeners.delete(listener);\n    },\n    subscribeDiagnostics(listener) {\n      diagnosticListeners.add(listener);\n      return () => diagnosticListeners.delete(listener);\n    },\n    listenToPatches(listener) {\n      patchListeners.add(listener);\n      return () => patchListeners.delete(listener);\n    },\n    get stats(): IRealmStats {\n      return { rttMs: statsRttMs, jitterMs: statsJitterMs, samples: statsSamples };\n    },\n    detach() {\n      if (probeTimer != null) clearInterval(probeTimer);\n      if (probeDeadline != null) clearTimeout(probeDeadline);\n      if (leadingCooldownTimer != null) {\n        clearTimeout(leadingCooldownTimer);\n        leadingCooldownTimer = undefined;\n      }\n      unsubscribeLinkEvents?.();\n      clearResyncRetry();\n      reownWatch.clear(); // drop the reown tripwire's watch (Phase 2) — the slot is going away\n      reownEscalated.clear();\n      if (port?.isOpen() === true) {\n        try {\n          const bye = encodeDetach({ slot, reason: undefined });\n          devtools?.onFrame?.(\"out\", \"detach\", bye.byteLength);\n          port.send(bye);\n        } catch {\n          // Best-effort — the slot is released either way.\n        }\n      }\n      helloInFlight = false;\n      // A throwing app callback must not leave the slot held or the pending count stale.\n      const guard = createStepGuard();\n      guard.run(() => setStatus(\"detached\"));\n      options.connection.release();\n      for (const frame of pending.splice(0)) {\n        guard.run(() =>\n          settleReject(\n            frame,\n            err_realm.fromId(\"frame_too_stale\", { basisVersion: frame.basisVersion }),\n          ),\n        );\n      }\n      // Re-project so the rolled-back optimistic writes leave the (now detached) store — the\n      // splice alone left them visible. `project` also notifies pending listeners.\n      guard.run(() => project());\n      guard.rethrow();\n    },\n  };\n\n  // Bind the devtools to the public surface last — the tap can now read the handle it observes.\n  devtools?.handleReady?.({\n    handle,\n    realmId: realm.id,\n    slot,\n    avatar,\n    peer: (options.connection.peer ?? options.connection.peerCoordinate)?.envId,\n  });\n\n  return handle;\n}\n\n/** Last write wins per exact path inside one coalesced frame. */\nfunction dedupeByPath(patches: readonly Patch[]): Patch[] {\n  const byPath = new Map<string, Patch>();\n  for (const patch of patches) {\n    byPath.set(patch.path.join(\" \"), patch);\n  }\n  return [...byPath.values()];\n}\n\nfunction concatChunks(chunks: readonly Uint8Array[]): Uint8Array {\n  if (chunks.length === 1) return chunks[0];\n  const total = chunks.reduce((sum, chunk) => sum + chunk.byteLength, 0);\n  const out = new Uint8Array(total);\n  let offset = 0;\n  for (const chunk of chunks) {\n    out.set(chunk, offset);\n    offset += chunk.byteLength;\n  }\n  return out;\n}\n","import { castNiceError, type NiceError } from \"@nice-code/error\";\nimport { unrefTimer } from \"@nice-code/util\";\nimport { applyPatches, enablePatches, type Patch, produceWithPatches } from \"immer\";\nimport { unpack } from \"msgpackr\";\nimport type { IRealmDefinition, TRealmSecurityLevel } from \"../RealmDefinition/defineRealm\";\nimport { err_realm } from \"../RealmDefinition/errors/err_realm\";\nimport type { IRealmIntentDef } from \"../RealmDefinition/Intents/intents.types\";\nimport type { TInferNode } from \"../RealmDefinition/Schema/schema.types\";\nimport { RealmKeyDict } from \"../RealmWire/keyDict\";\nimport {\n  REALM_DETACH_REASON_REHELLO,\n  REALM_FEATURE,\n  REALM_FRAME_KIND,\n  type TRealmFrame,\n} from \"../RealmWire/realmFrame.types\";\nimport {\n  encodeClientCaps,\n  encodeDetach,\n  encodeHello,\n  encodeIntent,\n  encodeWrite,\n} from \"../RealmWire/realmFrameCodec\";\nimport { pathHasUnsafeKey } from \"../RealmWire/unsafeKey\";\nimport {\n  canonicalizeStatePatches,\n  namePatchesToWireOps,\n  wireOpsToNamePatches,\n} from \"../RealmWire/wirePatch\";\nimport { computeRealmSecurityShortfall } from \"./assertRealmSecurity\";\nimport type {\n  IRealmClientPort,\n  IRealmConnectionAdapter,\n  TRealmDiagnosticEvent,\n  TRealmStatus,\n} from \"./RealmClient\";\nimport { withStructuralParents } from \"./structuralParents\";\nimport {\n  createWriteHandle,\n  type IRealmWriteHandle,\n  type IWriteHandleController,\n} from \"./writeHandle\";\n\nenablePatches();\n\n/**\n * A server-side realm **replica**: the client engine minus the optimistic\n * machinery — no pending queue, no prediction, no Store/React stack. Confirmed authoritative\n * state lands in a plain object with a patches callback, fit for a Worker/DO/server process\n * holding a live read copy. A replica is an ordinary **avatar type** of the realm (full or\n * partial visibility is just its view rules — \"replica is an avatar rule\"); it may issue writes\n * and intents like any avatar, sent non-optimistically, with no special authority.\n */\n\nexport interface IConnectRealmReplicaOptions<TAvatarType extends string = string> {\n  avatar: { type: TAvatarType; persistentId: string; instanceId?: string };\n  connection: IRealmConnectionAdapter;\n  /**\n   * Raise the client-side security floor above the realm's own `security` for this replica\n   *. The effective minimum is `max(realm.security, this)`, asserted\n   * against the connection's negotiated level before the first `hello` — a shortfall fails the attach\n   * with `insufficient_security` and never emits a frame. A replica is the highest-value connection\n   * (an \"everything\" view), so this block matters most here. Can only *raise* the bar.\n   */\n  security?: TRealmSecurityLevel;\n  /** Fired after each applied authoritative batch (hydrate delivers one synthetic batch). */\n  onPatches?: (patches: readonly Patch[], meta: { version: number }) => void;\n  /**\n   * How long an in-flight write/intent may wait for its ack before the handle rejects\n   * `frame_too_stale`. Until then it is\n   * resent on every recovery (reconnect / probe). A lost ack therefore surfaces as a bounded\n   * rejection instead of an `await` that hangs forever.\n   */\n  pendingExpiryMs?: number;\n  /**\n   * The staleness probe — replicas have the same silent-staleness hole as clients\n   * and a longer lifetime: while `live` with no inbound frame for this window, re-hello\n   * (idempotent — empty replay when current). Default 25 000 ms; `0` disables.\n   */\n  staleProbeAfterMs?: number;\n  /**\n   * Probe-escalation window — the client mirror: after a probe with no\n   * inbound reply within this window, flip to `\"connecting\"`, fire `probe_escalated`, and invoke\n   * the connection's `requestReconnect`. Default 10 000 ms; `0` disables (detect-only).\n   */\n  probeReplyTimeoutMs?: number;\n  /**\n   * Observe sync-health events — the replica mirror of\n   * `IConnectRealmOptions.onDiagnostic`. When absent, the first occurrence of each event type\n   * logs one `console.warn` per handle (silent-failure guard).\n   *\n   * **Transport-level drops that heal by redial do not surface here** (a healthy heal is silent\n   * at the sync layer) — use the connector's `onLinkEvent` for link observation; only\n   * `link_redialed` is forwarded into this stream.\n   */\n  onDiagnostic?: (event: TRealmDiagnosticEvent) => void;\n}\n\nexport interface IRealmReplicaHandle<\n  TState extends object,\n  TIntents extends Record<string, IRealmIntentDef<any, any, any, any>> = Record<\n    string,\n    IRealmIntentDef<any, any, any, any>\n  >,\n> {\n  /** The replica's confirmed slice of authoritative state (plain object, replaced per batch). */\n  readonly state: Readonly<TState>;\n  readonly version: number;\n  readonly status: TRealmStatus;\n  /**\n   * `true` once this handle has EVER been `\"live\"` — never reset. The\n   * RealmClient twin: distinguishes the initial `\"connecting\"` from a recovery one.\n   */\n  readonly hasBeenLive: boolean;\n  readonly attachError: NiceError<any, any> | undefined;\n  /**\n   * Subscribe to status transitions — fires on every change with the new status.\n   * The second argument carries {@link hasBeenLive} (joining vs reconnecting, one listener).\n   */\n  subscribeStatus(\n    listener: (status: TRealmStatus, meta: { hasBeenLive: boolean }) => void,\n  ): () => void;\n  /** Non-optimistic write — settles on the server verdict (LWW absolute-set contract applies). */\n  update(fn: (draft: TState) => void): IRealmWriteHandle;\n  /**\n   * Typed intent calls, mirroring the client handle — a misspelled\n   * intent is a compile error instead of a runtime `intent_unknown`.\n   */\n  intents: {\n    [K in keyof TIntents]: (input: TInferNode<TIntents[K][\"input\"]>) => IRealmWriteHandle;\n  };\n  /** Untyped fallback for dynamic intent names — prefer {@link intents}. */\n  intent(name: string, input: unknown): IRealmWriteHandle;\n  detach(): void;\n}\n\nexport function connectRealmReplica<\n  TState extends object,\n  TAvatarType extends string,\n  TIntents extends Record<string, IRealmIntentDef<any, any, any, any>>,\n>(\n  realm: IRealmDefinition<TState, TAvatarType, any, TIntents, any>,\n  options: IConnectRealmReplicaOptions<TAvatarType>,\n): IRealmReplicaHandle<TState, TIntents> {\n  const slot = options.connection.slot;\n  const dict = new RealmKeyDict();\n\n  let state: TState = {} as TState;\n  let version = -1;\n  /** The log epoch `version` belongs to — echoed in every hello. */\n  let serverEpoch: string | undefined;\n  let identityWarned = false;\n  let status: TRealmStatus = \"connecting\";\n  let attachError: NiceError<any, any> | undefined;\n  let nextSeq = 0;\n  let hydrateChunks: Uint8Array[] = [];\n  let port: IRealmClientPort | undefined;\n  /**\n   * In-flight write/intent hygiene: unlike the client engine, the replica has no\n   * optimistic queue — but a fire-and-forget `sendTracked` still needs an expiry (so `await\n   * update()` can't hang forever on a lost ack) and a resend-on-recovery (so a write lost to a\n   * drop is redelivered, not silently gone). `build` is kept for the resend and re-reads the\n   * current `version` when called, so a CAS rule sees an honest basis.\n   */\n  interface IReplicaInFlight {\n    controller: IWriteHandleController;\n    build: (clientSeq: number) => Uint8Array;\n    expiryTimer: ReturnType<typeof setTimeout> | undefined;\n  }\n  const inFlight = new Map<number, IReplicaInFlight>();\n  const expiryMs = options.pendingExpiryMs ?? 10_000;\n\n  /** Settle one in-flight entry (ack/reject/expiry): clear its timer, drop it, run the callback. */\n  const settleInFlight = (\n    clientSeq: number,\n    settle: (controller: IWriteHandleController) => void,\n  ): void => {\n    const entry = inFlight.get(clientSeq);\n    if (entry == null) return;\n    if (entry.expiryTimer != null) clearTimeout(entry.expiryTimer);\n    inFlight.delete(clientSeq);\n    settle(entry.controller);\n  };\n\n  /**\n   * Resend every in-flight frame after a recovery (reconnect / probe) — the replica's analog of\n   * the client's `revalidateAndResendPending`. Rebuilds at the CURRENT version; the\n   * server's replay high-water re-acks an already-processed seq idempotently and applies a\n   * genuinely lost one. Iterates a COPY: an in-memory link delivers the dup ack synchronously\n   * inside `send`, which would otherwise mutate the map mid-iteration.\n   */\n  const resendInFlight = (): void => {\n    if (port?.isOpen() !== true || inFlight.size === 0) return;\n    for (const [clientSeq, entry] of [...inFlight]) {\n      port.send(entry.build(clientSeq));\n    }\n  };\n  /** Staleness-probe clocks — stamped by every inbound frame / probe hello. */\n  let lastInboundAt = Date.now();\n  let lastProbeAt = 0;\n  /** One-shot probe-reply deadline — armed after a probe, cleared by any inbound. */\n  let probeDeadline: ReturnType<typeof setTimeout> | undefined;\n  const statusListeners = new Set<(status: TRealmStatus, meta: { hasBeenLive: boolean }) => void>();\n  /** Latched on the first `live` and never reset. */\n  let hasBeenLive = false;\n  const setStatus = (next: TRealmStatus): void => {\n    if (status === next) return;\n    status = next;\n    if (next === \"live\") hasBeenLive = true;\n    for (const listener of [...statusListeners]) listener(next, { hasBeenLive });\n  };\n\n  // ── Lost-sync recovery — the RealmClient twin, minus the optimistic queue ──────\n  /** An attach/recovery hello is out and unanswered — non-continuous frames drop, never apply. */\n  let helloInFlight = false;\n  let helloSentAt = 0;\n  const HELLO_REPLY_GRACE_MS = 10_000;\n\n  const warnedDiagnostics = new Set<string>();\n  /** Warn prefix — the epoch disambiguates several instances of one realm id (RealmClient twin). */\n  const warnTag = (): string =>\n    serverEpoch == null ? `[realm:${realm.id}]` : `[realm:${realm.id}#${serverEpoch.slice(0, 8)}]`;\n  const onDiagnostic = (event: TRealmDiagnosticEvent): void => {\n    if (options.onDiagnostic != null) {\n      options.onDiagnostic(event);\n      return;\n    }\n    if (!warnedDiagnostics.has(event.type)) {\n      warnedDiagnostics.add(event.type);\n      console.warn(`${warnTag()} replica sync-health event \"${event.type}\"`, event);\n    }\n  };\n\n  // ── Probe config + escalation — the RealmClient twin ──────\n  const staleProbeAfterMs = options.staleProbeAfterMs ?? 25_000;\n  const probeReplyTimeoutMs = options.probeReplyTimeoutMs ?? 10_000;\n  /**\n   * Arm the escalation deadline after a probe-flavored hello (Phase 1.2 backstop): a probe/rehello\n   * keeps `live` for a one-round-trip heal, but no inbound within the window ⇒ the link is dead, so\n   * flip to `connecting` truthfully and re-dial. Status moves on evidence of an outage, not a\n   * protocol chore. Cleared by any inbound frame.\n   */\n  const armProbeEscalation = (): void => {\n    if (probeReplyTimeoutMs <= 0) return;\n    if (probeDeadline != null) clearTimeout(probeDeadline);\n    probeDeadline = setTimeout(() => {\n      probeDeadline = undefined;\n      if (status !== \"live\") return;\n      if (lastInboundAt >= lastProbeAt) return; // a reply arrived — the link is alive\n      onDiagnostic({ type: \"probe_escalated\" });\n      setStatus(\"connecting\");\n      options.connection.requestReconnect?.();\n    }, probeReplyTimeoutMs);\n    unrefTimer(probeDeadline);\n  };\n\n  /** Probe-flavored recovery re-hello — see RealmClient's `requestResync` for the full why. */\n  const requestResync = (\n    reason: \"version_gap\" | \"frame_error\" | \"write_target_missing\",\n    detail?: { fromVersion?: number; toVersion?: number; confirmedVersion?: number },\n  ): void => {\n    if (status === \"detached\") return;\n    onDiagnostic({ type: \"resync\", reason, ...detail });\n    if (helloInFlight && Date.now() - helloSentAt < HELLO_REPLY_GRACE_MS) return;\n    if (port?.isOpen() !== true) return;\n    sendHello({ probe: true }); // sets helloInFlight + arms escalation (Phase 1.1/1.2)\n  };\n\n  /** Backoff retry for a recovery whose ANSWER failed to apply — the RealmClient twin. */\n  let resyncAttempts = 0;\n  let resyncTimer: ReturnType<typeof setTimeout> | undefined;\n  const clearResyncRetry = (): void => {\n    if (resyncTimer != null) {\n      clearTimeout(resyncTimer);\n      resyncTimer = undefined;\n    }\n  };\n  const scheduleResyncWithBackoff = (): void => {\n    helloInFlight = false; // the failed frame may have BEEN the answer — free the guard\n    if (resyncTimer != null) return;\n    const delay = Math.min(250 * 2 ** resyncAttempts, 5_000);\n    resyncAttempts += 1;\n    const timer = setTimeout(() => {\n      resyncTimer = undefined;\n      requestResync(\"frame_error\");\n    }, delay);\n    unrefTimer(timer);\n    resyncTimer = timer;\n  };\n\n  /**\n   * A `probe` hello keeps `live` status — see RealmClient's twin for the why. Only a\n   * non-probe hello clears the key dict: a probe rides the same live session and\n   * clearing there would strand in-flight interned ids.\n   */\n  const sendHello = (opts?: { probe?: boolean }): void => {\n    if (opts?.probe !== true) {\n      setStatus(\"connecting\");\n      attachError = undefined;\n      dict.clear();\n    } else {\n      // Probe-flavored: keep `live`, arm the escalation backstop (Phase 1.2). `lastProbeAt` stamps\n      // the moment so escalation's \"did a reply arrive?\" check has a basis.\n      lastProbeAt = Date.now();\n      armProbeEscalation();\n    }\n    // Tracked in EVERY shape (Phase 1.1): the answer runs the resend tail regardless of shape, so a\n    // probe/wake-rehello redelivers in-flight writes exactly like a reconnect (no pre-resend needed).\n    helloInFlight = true;\n    helloSentAt = Date.now();\n    hydrateChunks = [];\n    port?.send(\n      encodeHello({\n        slot,\n        realmId: realm.id,\n        schemaHash: realm.schemaHash,\n        lastKnownVersion: version,\n        epoch: serverEpoch,\n      }),\n    );\n    // Advertise egress features right after every hello (Phase 1) — a woken server re-learns them.\n    port?.send(encodeClientCaps({ slot, features: [REALM_FEATURE.batch] }));\n  };\n\n  // Batch coalescing (Phase 2): while applying a `batch` envelope's children, accumulate their\n  // applied patches and fire `onPatches` ONCE after the last child instead of per child.\n  let onPatchesSuppressed = false;\n  let accumulatedPatches: Patch[] = [];\n  const emitPatches = (patches: readonly Patch[]): void => {\n    if (onPatchesSuppressed) {\n      accumulatedPatches.push(...patches);\n      return;\n    }\n    options.onPatches?.(patches, { version });\n  };\n\n  const handleFrame = (frame: TRealmFrame): void => {\n    switch (frame.kind) {\n      case REALM_FRAME_KIND.batch: {\n        // Phase 2 egress envelope: apply every child (flat + non-batch by the codec fuzz gate), then\n        // one `onPatches` with the concatenated deltas at the final version. Settlements are not\n        // suppressed (inFlight confirm/reject run as the ack/reject children are applied).\n        const wasSuppressed = onPatchesSuppressed;\n        onPatchesSuppressed = true;\n        if (!wasSuppressed) accumulatedPatches = [];\n        let childFailed = false;\n        let childError: unknown;\n        try {\n          for (const child of frame.frames) {\n            // Per-child isolation: a poisoned child must not abort its siblings — the\n            // continuity guard (F2) drops any later patches child that would land on a wrong base.\n            try {\n              handleFrame(child);\n            } catch (error) {\n              if (!childFailed) {\n                childFailed = true;\n                childError = error;\n              }\n            }\n          }\n        } finally {\n          onPatchesSuppressed = wasSuppressed;\n        }\n        if (!onPatchesSuppressed && accumulatedPatches.length > 0) {\n          const emitted = accumulatedPatches;\n          accumulatedPatches = [];\n          options.onPatches?.(emitted, { version });\n        }\n        if (childFailed) throw childError;\n        return;\n      }\n      case REALM_FRAME_KIND.hydrate: {\n        dict.load(frame.keyDictSeed);\n        hydrateChunks.push(frame.stateBlob);\n        if (frame.more) return;\n        const blob = concatChunks(hydrateChunks);\n        hydrateChunks = [];\n        state = unpack(blob) as TState;\n        version = frame.version;\n        serverEpoch = frame.epoch;\n        // The identity echo — replicas have the same silent-mismatch class.\n        const [echoType, echoPersistentId] = frame.avatar;\n        if (\n          !identityWarned &&\n          (echoType !== options.avatar.type || echoPersistentId !== options.avatar.persistentId)\n        ) {\n          identityWarned = true;\n          console.warn(\n            `${warnTag()} replica identity mismatch — connected as ` +\n              `${options.avatar.type}/${options.avatar.persistentId} but the server resolved ` +\n              `${echoType}/${echoPersistentId}. Writes/intents will be judged ` +\n              \"against the server's identity.\",\n          );\n        }\n        setStatus(\"live\");\n        helloInFlight = false; // the hello is answered\n        resendInFlight(); // redeliver anything unacked across the reconnect\n        emitPatches([]);\n        return;\n      }\n      case REALM_FRAME_KIND.keyDict: {\n        dict.load(frame.entries);\n        return;\n      }\n      case REALM_FRAME_KIND.patches: {\n        // Version-continuity guard — the RealmClient twin: continuous frames advance\n        // from our version (transient-only frames have from === to), continuation chunks of a\n        // split flush share from/to and re-apply safely at the unchanged version; anything else\n        // is a gap or a foreign history — drop, and heal via re-hello.\n        const isContinuous = frame.fromVersion === version;\n        const isContinuation = frame.toVersion === version;\n        if (!isContinuous && !isContinuation) {\n          if (helloInFlight) {\n            onDiagnostic({\n              type: \"gap_dropped\",\n              fromVersion: frame.fromVersion,\n              toVersion: frame.toVersion,\n              confirmedVersion: version,\n            });\n          } else {\n            requestResync(\"version_gap\", {\n              fromVersion: frame.fromVersion,\n              toVersion: frame.toVersion,\n              confirmedVersion: version,\n            });\n          }\n          return;\n        }\n        const answeredHello = helloInFlight; // both resume shapes answer a tracked hello (1.1)\n        helloInFlight = false; // an acceptance-passing frame IS the recovery answer\n        const patches = wireOpsToNamePatches(frame.ops, realm.tokens, (id) => dict.keyOf(id));\n        const applicable = patches.filter((patch) => {\n          // Prototype-pollution deny-list (Phase 5): drop any patch carrying an unsafe record key\n          // before it touches state — defense against a hostile/replayed server frame. A replica is\n          // the highest-value \"everything\" view, so it screens the same as the client.\n          if (pathHasUnsafeKey(patch.path)) return false;\n          if (patch.op !== \"remove\") return true;\n          let cursor: unknown = state;\n          for (const seg of patch.path.slice(0, -1)) {\n            if (cursor == null || typeof cursor !== \"object\") return false;\n            cursor = (cursor as Record<string, unknown>)[seg];\n          }\n          return (\n            cursor != null &&\n            typeof cursor === \"object\" &&\n            String(patch.path[patch.path.length - 1]) in (cursor as object)\n          );\n        });\n        // A patch into a container this slice never received must not blow up the pipeline —\n        // synthesize the structural parents the schema declares (see structuralParents.ts).\n        const prepared = withStructuralParents(state, applicable, realm.stateDef);\n        state = applyPatches(state, prepared);\n        version = frame.toVersion;\n        // Resend on EVERY answered hello (Phase 1.1) — a probe/wake-rehello keeps `live` status, so\n        // gating the resend on the connecting→live transition (as before) skipped the probe answer.\n        if (answeredHello) resendInFlight(); // redeliver anything unacked across the recovery\n        if (status === \"connecting\") setStatus(\"live\"); // a replay answered our hello — live now\n        emitPatches(prepared);\n        return;\n      }\n      case REALM_FRAME_KIND.ack: {\n        settleInFlight(frame.clientSeq, (controller) =>\n          controller.confirm({ version: frame.version }),\n        );\n        return;\n      }\n      case REALM_FRAME_KIND.reject: {\n        const error = castNiceError(frame.error);\n        if (frame.clientSeq === -1) {\n          attachError = error;\n          helloInFlight = false; // answered, terminally\n          setStatus(\"detached\");\n          return;\n        }\n        settleInFlight(frame.clientSeq, (controller) => controller.reject(error));\n        // Structural divergence self-heal (Phase 1.5 / the recovery contract) — the RealmClient twin: a\n        // `write_target_missing` reject proves stale confirmed state; re-read via a tracked resync\n        // instead of looping on doomed writes.\n        if ((error.getIds() as string[]).includes(\"write_target_missing\")) {\n          requestResync(\"write_target_missing\");\n        }\n        return;\n      }\n      case REALM_FRAME_KIND.detach: {\n        if (frame.reason === REALM_DETACH_REASON_REHELLO) {\n          // Probe-flavored wake rehello (Phase 1.2) — keep `live`, no flap; the escalation deadline\n          // flips to `connecting` only if the re-hello goes unanswered.\n          if (status === \"live\") sendHello({ probe: true });\n          return;\n        }\n        helloInFlight = false;\n        setStatus(\"detached\");\n        return;\n      }\n      default:\n        return;\n    }\n  };\n\n  /**\n   * The defensive inbound boundary — the RealmClient twin: a decode/apply throw\n   * (unknown interned key id, non-resolving patch parent) must not escape into the wire mux,\n   * silently drop the frame, or abort a batch's siblings. On failure, heal via re-hello with\n   * backoff; `lastInboundAt` is stamped only after clean handling, so a throwing frame no longer\n   * fools the staleness probe.\n   */\n  const onFrame = (frame: TRealmFrame): void => {\n    try {\n      handleFrame(frame);\n    } catch (error) {\n      onDiagnostic({ type: \"frame_error\", error });\n      hydrateChunks = []; // a mid-hydrate failure must not poison the next hydrate's reassembly\n      scheduleResyncWithBackoff();\n      return;\n    }\n    lastInboundAt = Date.now(); // clean handling only — a liveness signal\n    resyncAttempts = 0;\n    clearResyncRetry();\n    if (probeDeadline != null) {\n      clearTimeout(probeDeadline); // a reply landed — cancel probe escalation\n      probeDeadline = undefined;\n    }\n  };\n\n  // Client-side security floor: the replica is the highest-value leak — an\n  // \"everything\" view of the realm — and a wholly separate connect path from `connectRealm`, so it\n  // needs the identical block. If the connection's negotiated level is below the realm's required\n  // minimum, do NOT register handlers or send `hello`; fail the attach instead (a bare-mux/loopback\n  // adapter reports no level and is skipped). Same shared check so the two paths can't drift.\n  let unsubscribeLinkEvents: (() => void) | undefined;\n  const securityShortfall = computeRealmSecurityShortfall(\n    options.connection,\n    realm,\n    options.security,\n  );\n  if (securityShortfall != null) {\n    attachError = securityShortfall;\n    setStatus(\"detached\");\n    options.connection.release();\n  } else {\n    port = options.connection.register({\n      onFrame,\n      onAttach: () => sendHello(),\n      onDetach: () => {\n        if (status !== \"detached\") setStatus(\"connecting\");\n      },\n    });\n    if (port.isOpen()) sendHello();\n    // Forward a link re-establishment into the diagnostics — the\n    // RealmClient twin: `downForMs` present ⇒ a REdial, not the first establishment.\n    unsubscribeLinkEvents = options.connection.subscribeLinkEvents?.((event) => {\n      if (event.type === \"link_up\" && event.downForMs != null) {\n        onDiagnostic({ type: \"link_redialed\", downForMs: event.downForMs });\n      }\n    });\n  }\n\n  // ── The staleness probe + escalation ────────────\n  // (Config + `armProbeEscalation` are declared up top so the rehello/resync paths share them.)\n  let probeTimer: ReturnType<typeof setInterval> | undefined;\n  if (securityShortfall == null && staleProbeAfterMs > 0) {\n    probeTimer = setInterval(\n      () => {\n        if (status !== \"live\" || port?.isOpen() !== true) return;\n        const now = Date.now();\n        if (now - lastInboundAt < staleProbeAfterMs) return;\n        if (now - lastProbeAt < staleProbeAfterMs) return; // one probe per quiet window\n        // Tracked (Phase 1.1) + escalation-armed inside `sendHello({ probe })`: the answer runs the\n        // resend tail, and a dead link escalates via the deadline.\n        sendHello({ probe: true });\n      },\n      Math.max(1_000, Math.floor(staleProbeAfterMs / 2)),\n    );\n    unrefTimer(probeTimer);\n  }\n\n  const runIntent = (name: string, input: unknown): IRealmWriteHandle => {\n    const intentToken = realm.intentNames.indexOf(name);\n    if (intentToken < 0) {\n      const controller = createWriteHandle();\n      controller.reject(err_realm.fromId(\"intent_unknown\", { intent: name }));\n      return controller.handle;\n    }\n    return sendTracked((clientSeq) => encodeIntent({ slot, clientSeq, intentToken, input }));\n  };\n\n  const sendTracked = (build: (clientSeq: number) => Uint8Array): IRealmWriteHandle => {\n    const controller = createWriteHandle();\n    if (port?.isOpen() !== true) {\n      controller.reject(err_realm.fromId(\"frame_too_stale\", { basisVersion: version }));\n      return controller.handle;\n    }\n    const clientSeq = nextSeq++;\n    const entry: IReplicaInFlight = { controller, build, expiryTimer: undefined };\n    // Bounded wait for the ack: past `expiryMs` the handle rejects instead of hanging.\n    // Until then the entry is redelivered on every recovery (reconnect / probe).\n    entry.expiryTimer = setTimeout(() => {\n      if (inFlight.get(clientSeq) !== entry) return;\n      inFlight.delete(clientSeq);\n      controller.reject(err_realm.fromId(\"frame_too_stale\", { basisVersion: version }));\n    }, expiryMs);\n    unrefTimer(entry.expiryTimer);\n    inFlight.set(clientSeq, entry);\n    port.send(build(clientSeq));\n    return controller.handle;\n  };\n\n  return {\n    get state() {\n      return state;\n    },\n    get version() {\n      return version;\n    },\n    get status() {\n      return status;\n    },\n    get hasBeenLive() {\n      return hasBeenLive;\n    },\n    get attachError() {\n      return attachError;\n    },\n    subscribeStatus(listener) {\n      statusListeners.add(listener);\n      return () => statusListeners.delete(listener);\n    },\n    update(fn) {\n      const [next, patches] = produceWithPatches(state, (draft) => {\n        fn(draft as TState);\n      });\n      const canonical = canonicalizeStatePatches(patches, next, realm.stateDef);\n      if (canonical.length === 0) {\n        const controller = createWriteHandle();\n        controller.confirm({ version });\n        return controller.handle;\n      }\n      return sendTracked((clientSeq) =>\n        encodeWrite({\n          slot,\n          clientSeq,\n          basisVersion: version,\n          ops: namePatchesToWireOps(canonical, realm.tokens),\n        }),\n      );\n    },\n    intents: Object.fromEntries(\n      realm.intentNames.map((name) => [name, (input: unknown) => runIntent(name, input)]),\n    ) as IRealmReplicaHandle<TState, TIntents>[\"intents\"],\n    intent: runIntent,\n    detach() {\n      if (probeTimer != null) clearInterval(probeTimer);\n      if (probeDeadline != null) clearTimeout(probeDeadline);\n      unsubscribeLinkEvents?.();\n      clearResyncRetry();\n      if (port?.isOpen() === true) {\n        try {\n          port.send(encodeDetach({ slot, reason: undefined }));\n        } catch {\n          // best-effort\n        }\n      }\n      helloInFlight = false;\n      setStatus(\"detached\");\n      options.connection.release();\n      for (const entry of inFlight.values()) {\n        if (entry.expiryTimer != null) clearTimeout(entry.expiryTimer);\n        entry.controller.reject(err_realm.fromId(\"frame_too_stale\", { basisVersion: version }));\n      }\n      inFlight.clear();\n    },\n  };\n}\n\nfunction concatChunks(chunks: readonly Uint8Array[]): Uint8Array {\n  if (chunks.length === 1) return chunks[0];\n  const total = chunks.reduce((sum, chunk) => sum + chunk.byteLength, 0);\n  const out = new Uint8Array(total);\n  let offset = 0;\n  for (const chunk of chunks) {\n    out.set(chunk, offset);\n    offset += chunk.byteLength;\n  }\n  return out;\n}\n","import { unrefTimer } from \"@nice-code/util\";\nimport type { ESecurityLevel, IRuntimeCoordinate, IWireProtocolPort } from \"@nice-code/wire\";\nimport { WIRE_PROTOCOL_PREFIX, WireProtocolMux } from \"@nice-code/wire\";\nimport {\n  REALM_BROADCAST_SLOT,\n  REALM_FRAME_KIND,\n  type TRealmFrame,\n} from \"../RealmWire/realmFrame.types\";\nimport { decodeRealmFrame } from \"../RealmWire/realmFrameCodec\";\nimport type { IRealmClientPort, IRealmConnectionAdapter, IRealmPortHandlers } from \"./RealmClient\";\n\n/**\n * The connector-side realm protocol: ONE `IWireFrameProtocol` registration\n * (id `\"realm\"`, prefix `0x01`) per {@link WireProtocolMux}, multiplexing any number of realm\n * clients over it by **slot** — several realms (or instances) share the one secure socket the\n * action channel already established. `realmConnection(mux)` hands each `connectRealm` its\n * slot-scoped adapter.\n */\n\ninterface IMuxManager {\n  nextSlot: number;\n  /** Released slot numbers, recycled before `nextSlot` grows — a long-lived app hopping realms never exhausts the space. */\n  freeSlots: number[];\n  slots: Map<number, IRealmPortHandlers>;\n  port: IWireProtocolPort;\n}\n\nconst managers = new WeakMap<WireProtocolMux, IMuxManager>();\n\n/** Grace period before a released slot number may be recycled — see `release()`. */\nconst SLOT_QUARANTINE_MS = 5_000;\n\nfunction managerFor(mux: WireProtocolMux): IMuxManager {\n  let manager = managers.get(mux);\n  if (manager != null) return manager;\n  const slots = new Map<number, IRealmPortHandlers>();\n  // Belt to the engine's own defensive wrap: a per-slot handler must never throw into\n  // the shared mux — one realm's frame-handling bug would otherwise take down every sibling realm\n  // on the connection (and escape into the wire transport). The engines already catch their own\n  // decode/apply failures; this is the last line if one ever doesn't.\n  const safeDeliver = (\n    handlers: IRealmPortHandlers,\n    frame: TRealmFrame,\n    byteSize?: number,\n  ): void => {\n    try {\n      handlers.onFrame(frame, byteSize);\n    } catch (error) {\n      console.error(\"[realm] a realm slot handler threw while dispatching an inbound frame\", error);\n    }\n  };\n  const dispatch = (frame: TRealmFrame, byteSize?: number): void => {\n    if (frame.slot === REALM_BROADCAST_SLOT) {\n      // Link-wide broadcast (M6 wake \"rehello\"): every attached realm handles it.\n      for (const handlers of slots.values()) safeDeliver(handlers, frame, byteSize);\n      return;\n    }\n    const handlers = slots.get(frame.slot);\n    if (handlers != null) safeDeliver(handlers, frame, byteSize);\n  };\n  const port = mux.registerProtocol({\n    id: \"realm\",\n    prefixByte: WIRE_PROTOCOL_PREFIX.realm,\n    onFrame: (payload) => {\n      let frame: TRealmFrame;\n      try {\n        frame = decodeRealmFrame(payload);\n      } catch {\n        return; // malformed server frame — drop (codec fuzz gate)\n      }\n      // The egress envelope (Phase 2): a batch is a connection-level wrapper, so route children by\n      // their OWN slot, but **regroup per slot** and hand each slot ONE synthetic batch — so the\n      // client engine applies that slot's frames and projects once (N re-renders → 1). Broadcast-slot\n      // children (wake rehello) fan out individually. Nesting/malformed children already rejected by\n      // the codec. In practice a server batch is single-slot, so this is one group.\n      if (frame.kind === REALM_FRAME_KIND.batch) {\n        const groups = new Map<number, TRealmFrame[]>();\n        for (const child of frame.frames) {\n          if (child.slot === REALM_BROADCAST_SLOT) {\n            dispatch(child);\n            continue;\n          }\n          const group = groups.get(child.slot);\n          if (group == null) groups.set(child.slot, [child]);\n          else group.push(child);\n        }\n        for (const [slot, children] of groups) {\n          const handlers = slots.get(slot);\n          if (handlers == null) continue;\n          safeDeliver(\n            handlers,\n            children.length === 1\n              ? children[0]\n              : { kind: REALM_FRAME_KIND.batch, slot, frames: children },\n            // Devtools byte attribution: honest only for the single-group case (children are\n            // decoded in place — per-child sizes don't exist, and splitting the total across\n            // slots would be a guess).\n            groups.size === 1 ? payload.byteLength : undefined,\n          );\n        }\n        return;\n      }\n      dispatch(frame, payload.byteLength);\n    },\n    onAttach: () => {\n      for (const handlers of slots.values()) handlers.onAttach();\n    },\n    onDetach: () => {\n      for (const handlers of slots.values()) handlers.onDetach();\n    },\n  });\n  manager = { nextSlot: 0, freeSlots: [], slots, port };\n  managers.set(mux, manager);\n  return manager;\n}\n\n/**\n * A connection-owning handle the realm can ride — structurally, nice-action's `ChannelConnector`\n *: it exposes the link's frame-protocol mux and the authenticated local\n * coordinate, without realm ever importing action (dependency direction D3 holds).\n */\nexport interface IRealmWireLink {\n  readonly wireMux: WireProtocolMux | undefined;\n  readonly localCoordinate?: IRuntimeCoordinate;\n  /**\n   * The coordinate of the peer this link dials — structurally `ChannelConnector.peer`. Purely\n   * observational: devtools reports it so a topology can attribute a realm to the backend it is\n   * actually connected to, rather than guessing from a realm id (two hosts can serve one realm id).\n   * Bare-mux loopbacks use the separate `WireProtocolMux` overload.\n   */\n  readonly peer: IRuntimeCoordinate;\n  /**\n   * The negotiated wire security level this link's realm frames ride at —\n   * `ChannelConnector.securityLevel`. `connectRealm`/`connectRealmReplica` assert it against the\n   * realm's required minimum before the first `hello`. Absent on a bare-mux source (test loopback),\n   * where the client-side assertion is skipped.\n   */\n  readonly securityLevel?: ESecurityLevel;\n  /**\n   * Tear down and re-dial the underlying link. Surfaced to the realm engine\n   * as the connection adapter's `requestReconnect`, invoked when a staleness probe goes unanswered\n   * (a half-open socket the realm layer can't otherwise detect). Optional: a bare mux / a connector\n   * without reconnect support omits it, and escalation then only flips status + fires the\n   * diagnostic. Phase 8b wires this to `ChannelConnector.reconnectLink()`.\n   */\n  readonly requestReconnect?: () => void;\n  /**\n   * Observe the link's transport state — structurally,\n   * `ChannelConnector.addLinkEventListener` (only the fields the realm reads are typed here; the\n   * full event union lives on the connector). The realm forwards a re-establishment into its\n   * `onDiagnostic` as `link_redialed`. Optional: a bare mux omits it.\n   */\n  addLinkEventListener?(\n    listener: (event: { type: string; downForMs?: number }) => void,\n  ): () => void;\n}\n\n/** @deprecated Provide the canonical `peer` property. */\nexport interface ILegacyRealmWireLink extends Omit<IRealmWireLink, \"peer\"> {\n  readonly peerClient: IRuntimeCoordinate;\n}\n\n/**\n * A slot-scoped connection adapter for `connectRealm({ connection })` — production path.\n *\n * **Call this (or `connectRealm` with it) BEFORE the first action runs on the link.** The\n * handshake advertises the mux's registered protocols as caps, and the acceptor persists them on\n * the connection's binding — that advertisement is what makes a hibernation-woken host re-attach\n * the realm protocol and send this connection its \"rehello\" resume broadcast. Registering after\n * the handshake still works live (server dispatch doesn't require negotiation, and the realm's\n * hello waits for the mux to attach), but an idle client would miss the wake resume and stay\n * stale until its own next write triggers the lazy unknown-slot heal.\n */\nexport function realmConnection(\n  source: WireProtocolMux | IRealmWireLink | ILegacyRealmWireLink,\n): IRealmConnectionAdapter {\n  const isMux = source instanceof WireProtocolMux;\n  const mux = isMux ? source : source.wireMux;\n  if (mux == null) {\n    throw new Error(\n      \"realmConnection: this link has no frame-protocol mux — connect it via connectChannel (which creates one per connection) or pass a WireProtocolMux directly.\",\n    );\n  }\n  // The connection-bound path also carries the link's authenticated local coordinate,\n  // so `connectRealm` can default the client identity from it.\n  const coordinate: IRuntimeCoordinate | undefined = isMux ? undefined : source.localCoordinate;\n  // …and the peer it dials, for devtools topology attribution (observational only).\n  const peer: IRuntimeCoordinate | undefined = isMux\n    ? undefined\n    : \"peer\" in source\n      ? source.peer\n      : source.peerClient;\n  // …and the connection's negotiated security level, so the client can refuse\n  // to send below the realm's required minimum. A bare mux carries none → the assertion is skipped.\n  const securityLevel: ESecurityLevel | undefined = isMux ? undefined : source.securityLevel;\n  // …and the link's re-dial hook, surfaced as the adapter's `requestReconnect`.\n  const requestReconnect: (() => void) | undefined = isMux ? undefined : source.requestReconnect;\n  // …and the link-state observation hook, surfaced as the adapter's\n  // `subscribeLinkEvents` so the engine can forward a redial into its diagnostics. Bound here —\n  // the engine stores the reference and calls it detached from the connector.\n  const linkEventSource = isMux ? undefined : source.addLinkEventListener?.bind(source);\n\n  const manager = managerFor(mux);\n  // Recycle released slots before growing — only a *concurrently attached* realm\n  // count beyond the space can exhaust it now, not a long app lifetime of joins/leaves.\n  const recycled = manager.freeSlots.pop();\n  if (recycled == null && manager.nextSlot >= REALM_BROADCAST_SLOT) {\n    throw new Error(`realmConnection: slot space exhausted (max ${REALM_BROADCAST_SLOT - 1})`);\n  }\n  const slot = recycled ?? manager.nextSlot++;\n  let released = false;\n  return {\n    slot,\n    coordinate,\n    peer,\n    peerCoordinate: peer,\n    securityLevel,\n    requestReconnect,\n    subscribeLinkEvents: linkEventSource,\n    register(handlers: IRealmPortHandlers): IRealmClientPort {\n      // No synchronous onAttach here: the engine checks `port.isOpen()` itself right after\n      // registering (its `port` binding does not exist yet inside this call).\n      manager.slots.set(slot, handlers);\n      return {\n        send: (bytes) => manager.port.send(bytes),\n        isOpen: () => manager.port.isOpen(),\n      };\n    },\n    release() {\n      // Idempotent: a double-release must not put the slot in the free list twice (two future\n      // realms would otherwise share one slot and cross their frames).\n      if (released) return;\n      released = true;\n      // Stop routing to this realm immediately (its handlers are gone)…\n      manager.slots.delete(slot);\n      // …but QUARANTINE the slot number before recycling it: a same-socket realm hop\n      // (lobby → match) could otherwise hand the slot to a new realm while a server frame for the\n      // old one is still in flight, and the mux routes strictly by slot — the new realm would\n      // decode a foreign frame. The grace window is ≫ any realistic server→client in-flight time;\n      // even if a frame somehow outlives it, Phase 2's continuity guard drops it (a fresh realm's\n      // hello is in flight, so it can't be flipped live at the old realm's version). Unref'd so a\n      // pending quarantine never keeps the process alive.\n      const timer = setTimeout(() => manager.freeSlots.push(slot), SLOT_QUARANTINE_MS);\n      unrefTimer(timer);\n    },\n  };\n}\n","import type { IRealmAvatarRef, TRuleVerdict } from \"../Rules/rules.types\";\nimport type { TInferNode, TSchemaNode } from \"../Schema/schema.types\";\n\n/**\n * Realm intents: named, atomic, settle-only, server-executed mutations — the\n * default write path. An intent's only outputs are its state effects plus the caller's settlement\n * (no result payloads: a result blob would live only in a losable ack frame; state-as-outcome is\n * versioned, logged, and replayed). Entities an intent creates use **avatar-supplied IDs** in the\n * input, with an \"already applied ⇒ commit as no-op\" idempotency guard as the standard shape.\n */\nexport interface IRealmIntentDef<\n  TState = unknown,\n  TAvatarType extends string = string,\n  TCtx = unknown,\n  TInput extends TSchemaNode = TSchemaNode,\n> {\n  /** The avatar types allowed to call this intent (the security gate, with the input schema). */\n  readonly allow: readonly TAvatarType[];\n  readonly input: TInput;\n  /**\n   * Optional client-side prediction — mutates a draft of the **caller's view** only; its patches\n   * join the pending queue like a write frame. A predictor that throws is treated as\n   * absent (prediction must never break the write).\n   */\n  readonly optimistic?: (context: {\n    view: TState;\n    avatar: IRealmAvatarRef<TAvatarType>;\n    input: TInferNode<TInput>;\n  }) => void;\n  /**\n   * Server-side, atomic: `state` is an immer draft of the **full authoritative state** (bypasses\n   * view/alter rules — trusted code; `allow` + the input schema are the boundary). Return `true`\n   * to commit (a no-op commit is the idempotent-retry ack) or a NiceError to reject — the draft\n   * is discarded entirely, never partially applied.\n   */\n  readonly apply: (context: {\n    state: TState;\n    avatar: IRealmAvatarRef<TAvatarType>;\n    input: TInferNode<TInput>;\n    ctx: TCtx;\n  }) => TRuleVerdict;\n}\n\n/** The `i` builder handed to a realm definition's `intents: (i) => ({ ... })` callback. */\nexport interface IIntentBuilder<TState, TAvatarType extends string, TCtx> {\n  define<TInput extends TSchemaNode>(\n    def: IRealmIntentDef<TState, TAvatarType, TCtx, TInput>,\n  ): IRealmIntentDef<TState, TAvatarType, TCtx, TInput>;\n}\n\nexport function createIntentBuilder<TState, TAvatarType extends string, TCtx>(): IIntentBuilder<\n  TState,\n  TAvatarType,\n  TCtx\n> {\n  return { define: (def) => def };\n}\n","import type { IResolvedRulePath, TResolveRulePath } from \"../Schema/infer.types\";\nimport type { TSchemaRoot } from \"../Schema/schema.types\";\nimport type {\n  IAlterCondAll,\n  IAlterCondServerChecked,\n  IAlterCondServerOnly,\n  IRealmRule,\n  IViewCondAvatarTypes,\n  IViewCondEveryone,\n  TAlterCond,\n  TViewCond,\n} from \"./rules.types\";\n\n/**\n * The `r` builder handed to a realm definition's `rules: (r) => [...]` callback.\n * `r.path(pattern)` resolves the pattern against the state shape at the type level, so plain\n * functions passed to `.view()` / `.alter()` get precise `params` and `prev`/`next` types.\n * Conditions built via `r.all` / `r.serverChecked` use the generic context tier (see\n * `rules.types.ts` module doc).\n */\n\nexport interface IRulePathBuilder<\n  TAvatarType extends string,\n  TState,\n  TCtx,\n  TRes extends IResolvedRulePath,\n> {\n  /** v1: view conditions are coordinate-only (`{ avatar, params }`) — the protocol contract restriction. */\n  view(cond: TViewCond<TAvatarType, TRes[\"params\"]>): {\n    alter(\n      cond: TAlterCond<TAvatarType, TRes[\"params\"], TRes[\"value\"], TState, TCtx>,\n    ): IRealmRule<TAvatarType, TState, TCtx>;\n  };\n}\n\n/**\n * `TState` is threaded in **pre-resolved** (the caller computes `TInferEntries<TStateDef>` once at\n * the `defineRealm` boundary) rather than re-derived here from `TStateDef`. Every `r.path(...)` call\n * would otherwise re-instantiate the full inferred state — a rich schema then trips TS2589\n * (\"excessively deep\") because the deep state type is expanded once per rule and combined with each\n * path's `TResolveRulePath` resolution. Keeping `TState` an opaque parameter lets TS reference it by\n * name instead of re-expanding the object shape on every rule.\n */\nexport interface IRuleBuilder<\n  TStateDef extends TSchemaRoot,\n  TState,\n  TAvatarType extends string,\n  TCtx,\n> {\n  path<P extends string>(\n    pattern: P,\n  ): IRulePathBuilder<TAvatarType, TState, TCtx, TResolveRulePath<TStateDef, P>>;\n  /** Everyone may view (includes replica-class clients — the protocol contract). */\n  readonly everyone: IViewCondEveryone;\n  /** Only `engine.update()` (server code) writes here. */\n  readonly serverOnly: IAlterCondServerOnly;\n  avatarTypes(...types: readonly TAvatarType[]): IViewCondAvatarTypes<TAvatarType>;\n  /**\n   * Wrap a check that needs the server context / patch log — server-evaluated only; avatar\n   * prediction auto-passes it (exactly the slice of optimism that can roll back, the protocol contract).\n   */\n  serverChecked(\n    fn: IAlterCondServerChecked<TAvatarType, TState, TCtx>[\"fn\"],\n  ): IAlterCondServerChecked<TAvatarType, TState, TCtx>;\n  /** Compose alter conditions — all must pass; first NiceError rejects. */\n  all(\n    ...conds: readonly TAlterCond<TAvatarType, Record<string, string>, any, TState, TCtx>[]\n  ): IAlterCondAll<TAvatarType, TState, TCtx>;\n}\n\n/** Runtime `r` — one shared instance is fine per definition (it holds no state). */\nexport function createRuleBuilder<\n  TStateDef extends TSchemaRoot,\n  TState,\n  TAvatarType extends string,\n  TCtx,\n>(): IRuleBuilder<TStateDef, TState, TAvatarType, TCtx> {\n  return {\n    path(pattern) {\n      return {\n        view: (view) => ({\n          alter: (alter) => ({ pattern, view, alter }),\n        }),\n      };\n    },\n    everyone: { kind: \"everyone\" },\n    serverOnly: { kind: \"serverOnly\" },\n    avatarTypes: (...types) => ({ kind: \"avatarTypes\", types }),\n    serverChecked: (fn) => ({ kind: \"serverChecked\", fn }),\n    all: (...conds) => ({ kind: \"all\", conds }),\n  };\n}\n","/**\n * Rule path patterns: dot-separated segments of four forms —\n * literal keys (`config`), `$var` binders (record levels), `{a,b}` brace groups (expanded at\n * compile time into one concrete pattern per member), and wildcards: `*` (exactly one trailing\n * segment) / `**` (one or more trailing segments). Wildcards are only valid as the final segment.\n */\n\nexport type TPatternSegment =\n  | { readonly kind: \"lit\"; readonly name: string }\n  | { readonly kind: \"var\"; readonly name: string }\n  | { readonly kind: \"star\" }\n  | { readonly kind: \"deep\" };\n\nexport interface IParsedPattern {\n  /** The concrete (post-brace-expansion) segments. */\n  readonly segments: readonly TPatternSegment[];\n  /** The original source pattern this expansion came from. */\n  readonly source: string;\n}\n\n/** Parse + brace-expand one pattern into its concrete forms. Throws on malformed patterns. */\nexport function parseRulePattern(pattern: string): IParsedPattern[] {\n  if (pattern.length === 0) throw new Error(\"rule pattern may not be empty\");\n  const rawSegments = pattern.split(\".\");\n\n  // Expand braces first: each `{a,b}` segment multiplies the pattern set.\n  let expanded: string[][] = [[]];\n  rawSegments.forEach((raw, index) => {\n    const isLast = index === rawSegments.length - 1;\n    if (raw.startsWith(\"{\") && raw.endsWith(\"}\")) {\n      const names = raw\n        .slice(1, -1)\n        .split(\",\")\n        .map((n) => n.trim());\n      if (names.some((n) => n.length === 0)) {\n        throw new Error(`rule pattern \"${pattern}\": empty name in brace group \"${raw}\"`);\n      }\n      expanded = expanded.flatMap((prefix) => names.map((n) => [...prefix, n]));\n      return;\n    }\n    if ((raw === \"*\" || raw === \"**\") && !isLast) {\n      throw new Error(`rule pattern \"${pattern}\": \"${raw}\" is only valid as the final segment`);\n    }\n    expanded = expanded.map((prefix) => [...prefix, raw]);\n  });\n\n  return expanded.map((names) => ({\n    source: pattern,\n    segments: names.map((name): TPatternSegment => {\n      if (name === \"*\") return { kind: \"star\" };\n      if (name === \"**\") return { kind: \"deep\" };\n      if (name.startsWith(\"$\")) {\n        const varName = name.slice(1);\n        if (varName.length === 0) throw new Error(`rule pattern \"${pattern}\": bare \"$\" segment`);\n        return { kind: \"var\", name: varName };\n      }\n      if (name.includes(\"{\") || name.includes(\"}\") || name.includes(\"$\")) {\n        throw new Error(`rule pattern \"${pattern}\": malformed segment \"${name}\"`);\n      }\n      return { kind: \"lit\", name };\n    }),\n  }));\n}\n","import type { TSchemaNode, TSchemaRoot } from \"../Schema/schema.types\";\nimport { parseRulePattern, type TPatternSegment } from \"./rulePattern\";\n\n/**\n * Compile-time (defineRealm-time) lint: every rule pattern must be able to match at least one\n * path the schema can ever produce. The failure mode this kills is the silent default-deny —\n * e.g. `terrain.**` over `terrain: t.array(...)` compiles happily but matches *nothing*, because\n * arrays (and every other wire-leaf) are patched and visibility-checked at exactly their own\n * path, and `**`/`*` need at least one further segment. Dead rules throw here, at definition\n * time, instead of a branch quietly never reaching any client.\n */\nexport function assertRulePatternsMatchSchema(\n  root: TSchemaRoot,\n  patterns: readonly string[],\n): void {\n  for (const pattern of patterns) {\n    for (const parsed of parseRulePattern(pattern)) {\n      const problem = checkSegments({ kind: \"object\", entries: root }, parsed.segments, 0);\n      if (problem != null) {\n        throw new Error(`rule pattern \"${pattern}\" can never match: ${problem}`);\n      }\n    }\n  }\n}\n\n/**\n * Validate + parse a realm's `transient` region paths. v1\n * accepts only **concrete, wildcard-free** dot-paths, each naming a subtree root that exists in the\n * schema (`\"presence\"`, `\"board.cursors\"`). Wildcards (`$var`, `*`, `**`, `{a,b}`) are rejected —\n * snapshot-strip and the replay refresh are a trivial root walk, not a pattern projection (that is a\n * recorded §7 deferral). Returns the parsed segment paths; throws at definition time on any problem.\n */\nexport function assertTransientRoots(root: TSchemaRoot, dotPaths: readonly string[]): string[][] {\n  const parsed: string[][] = [];\n  for (const dotPath of dotPaths) {\n    const segments = dotPath.split(\".\");\n    for (const seg of segments) {\n      if (seg.length === 0 || /[$*{}]/.test(seg)) {\n        throw new Error(\n          `transient path \"${dotPath}\" must be a concrete, wildcard-free path (no $var, *, ** or {a,b}); ` +\n            `offending segment \"${seg}\". Wildcard transient regions are not supported in v1.`,\n        );\n      }\n    }\n    if (resolveConcretePath({ kind: \"object\", entries: root }, segments, 0) == null) {\n      throw new Error(\n        `transient path \"${dotPath}\" does not resolve to any node in the realm schema.`,\n      );\n    }\n    parsed.push(segments);\n  }\n  return parsed;\n}\n\n/** Walk a concrete (literal-only) path through the schema; `undefined` if it leaves the schema. */\nfunction resolveConcretePath(\n  node: TSchemaNode,\n  segments: readonly string[],\n  index: number,\n): TSchemaNode | undefined {\n  if (index >= segments.length) return node;\n  const inner = unwrapOptional(node);\n  if (inner.kind === \"object\") {\n    const child = inner.entries[segments[index]];\n    return child == null ? undefined : resolveConcretePath(child, segments, index + 1);\n  }\n  if (inner.kind === \"record\") {\n    // A literal segment is a record key — descend into the value type.\n    return resolveConcretePath(inner.value, segments, index + 1);\n  }\n  return undefined; // a wire-leaf has no addressable children\n}\n\nfunction unwrapOptional(node: TSchemaNode): TSchemaNode {\n  return node.kind === \"optional\" ? unwrapOptional(node.inner) : node;\n}\n\n/** `undefined` = the pattern can match; otherwise a description of why it never will. */\nfunction checkSegments(\n  node: TSchemaNode,\n  segments: readonly TPatternSegment[],\n  index: number,\n): string | undefined {\n  if (index >= segments.length) return undefined;\n  const inner = unwrapOptional(node);\n  const seg = segments[index];\n  const at = describePrefix(segments, index);\n\n  if (inner.kind === \"object\") {\n    if (seg.kind === \"lit\") {\n      const child: TSchemaNode | undefined = inner.entries[seg.name];\n      if (child == null) return `\"${seg.name}\" is not a key of the object at ${at}`;\n      return checkSegments(child, segments, index + 1);\n    }\n    if (seg.kind === \"var\") {\n      // A `$var` over a fixed object matches any one key — dead only if no child admits the rest.\n      const children = Object.values(inner.entries);\n      if (children.length === 0) return `the object at ${at} has no keys`;\n      return children.some((child) => checkSegments(child, segments, index + 1) == null)\n        ? undefined\n        : `no key of the object at ${at} admits the rest of the pattern`;\n    }\n    return undefined; // `*` / `**` — the object has paths below it\n  }\n\n  if (inner.kind === \"record\") {\n    if (seg.kind === \"lit\" || seg.kind === \"var\") {\n      return checkSegments(inner.value, segments, index + 1);\n    }\n    return undefined; // `*` / `**` over record entries\n  }\n\n  // Everything else is a wire-leaf: patched — and visibility-checked — at exactly its own path.\n  // Any further segment (incl. `*`/`**`, which need one more) can never match a real path.\n  const hint =\n    inner.kind === \"array\"\n      ? ` (t.array is leaf-replace-only on the wire — rule it with the exact path, e.g. \"${describePrefix(segments, index, true)}\")`\n      : \"\";\n  return `it descends into the ${inner.kind} wire-leaf at ${at}${hint}`;\n}\n\nfunction describePrefix(segments: readonly TPatternSegment[], index: number, bare = false): string {\n  const prefix = segments\n    .slice(0, index)\n    .map((seg) =>\n      seg.kind === \"lit\"\n        ? seg.name\n        : seg.kind === \"var\"\n          ? `$${seg.name}`\n          : seg.kind === \"star\"\n            ? \"*\"\n            : \"**\",\n    )\n    .join(\".\");\n  if (prefix.length === 0) return \"the state root\";\n  return bare ? prefix : `\"${prefix}\"`;\n}\n","import type { IParsedPattern, TPatternSegment } from \"./rulePattern\";\nimport { parseRulePattern } from \"./rulePattern\";\nimport type { IRealmRule } from \"./rules.types\";\n\n/**\n * The compiled rule registry: a radix trie over path segments giving O(path-length)\n * rule *lookup* with **most-specific-pattern-wins** precedence — at each step a literal child\n * beats a `$var` child, which beats a trailing `*`, which beats `**`; ties across whole patterns\n * resolve by backtracking depth-first in that order, so the first match found is the most\n * specific. One rule decides per path (rules don't stack — compose inside a rule via `r.all`).\n *\n * The trie matches **name-space** paths (post-detokenization). Compiled once per realm\n * definition; connections bind only their coordinate context (never a per-connection trie).\n */\n\ninterface ITrieNode<TRule extends IRuleLike> {\n  lit?: Map<string, ITrieNode<TRule>>;\n  var?: { name: string; node: ITrieNode<TRule> };\n  /** A rule whose pattern ends `.*` at this depth (matches exactly one more segment). */\n  star?: IRuleMatchTarget<TRule>;\n  /** A rule whose pattern ends `.**` at this depth (matches one or more segments). */\n  deep?: IRuleMatchTarget<TRule>;\n  /** A rule whose pattern ends exactly here. */\n  exact?: IRuleMatchTarget<TRule>;\n}\n\n/** The one property the trie needs — keeps the registry generic over precisely-typed rules. */\ninterface IRuleLike {\n  readonly pattern: string;\n}\n\ninterface IRuleMatchTarget<TRule extends IRuleLike> {\n  rule: TRule;\n  /** var-name per segment index (sparse) — binds `params` during a match. */\n  varNames: (string | undefined)[];\n}\n\nexport interface IRuleMatch<TRule extends IRuleLike = IRealmRule> {\n  rule: TRule;\n  params: Record<string, string>;\n}\n\nexport class RealmRuleTrie<TRule extends IRuleLike = IRealmRule> {\n  private readonly _root: ITrieNode<TRule> = {};\n  private readonly _patterns: string[] = [];\n\n  constructor(rules: readonly TRule[]) {\n    for (const rule of rules) {\n      for (const parsed of parseRulePattern(rule.pattern)) {\n        this._insert(parsed, rule);\n      }\n      this._patterns.push(rule.pattern);\n    }\n  }\n\n  /** The source patterns, in definition order (schema-hash input). */\n  get patterns(): readonly string[] {\n    return this._patterns;\n  }\n\n  private _insert(parsed: IParsedPattern, rule: TRule): void {\n    const varNames: (string | undefined)[] = [];\n    let node = this._root;\n    for (let i = 0; i < parsed.segments.length; i++) {\n      const seg: TPatternSegment = parsed.segments[i];\n      if (seg.kind === \"star\") {\n        if (node.star != null) throw new Error(`duplicate rule pattern at \"${parsed.source}\"`);\n        node.star = { rule, varNames };\n        return;\n      }\n      if (seg.kind === \"deep\") {\n        if (node.deep != null) throw new Error(`duplicate rule pattern at \"${parsed.source}\"`);\n        node.deep = { rule, varNames };\n        return;\n      }\n      if (seg.kind === \"var\") {\n        varNames[i] = seg.name;\n        if (node.var == null) {\n          node.var = { name: seg.name, node: {} };\n        } else if (node.var.name !== seg.name) {\n          throw new Error(\n            `conflicting $var names at the same trie position: \"$${node.var.name}\" vs \"$${seg.name}\" (${parsed.source})`,\n          );\n        }\n        node = node.var.node;\n        continue;\n      }\n      node.lit ??= new Map();\n      let child = node.lit.get(seg.name);\n      if (child == null) {\n        child = {};\n        node.lit.set(seg.name, child);\n      }\n      node = child;\n    }\n    if (node.exact != null) throw new Error(`duplicate rule pattern at \"${parsed.source}\"`);\n    node.exact = { rule, varNames };\n  }\n\n  /** Match a concrete (name-space) path; `undefined` when no rule covers it. */\n  match(path: readonly string[]): IRuleMatch<TRule> | undefined {\n    const found = this._match(this._root, path, 0);\n    if (found == null) return undefined;\n    const params: Record<string, string> = {};\n    found.varNames.forEach((name, i) => {\n      if (name != null) params[name] = path[i];\n    });\n    return { rule: found.rule, params };\n  }\n\n  /**\n   * Whether some rule's pattern can match a path strictly BENEATH `path` (a `**` at or above it\n   * counts). Ignores `view` conditions — the answer is about schema reachability, not access.\n   */\n  reachesBeneath(path: readonly string[]): boolean {\n    return this._reachesBeneath(this._root, path, 0);\n  }\n\n  private _reachesBeneath(node: ITrieNode<TRule>, path: readonly string[], depth: number): boolean {\n    if (node.deep != null) return true;\n    if (depth === path.length) {\n      return (node.lit?.size ?? 0) > 0 || node.var != null || node.star != null;\n    }\n    const litChild = node.lit?.get(path[depth]);\n    if (litChild != null && this._reachesBeneath(litChild, path, depth + 1)) return true;\n    return node.var != null && this._reachesBeneath(node.var.node, path, depth + 1);\n  }\n\n  private _match(\n    node: ITrieNode<TRule>,\n    path: readonly string[],\n    depth: number,\n  ): IRuleMatchTarget<TRule> | undefined {\n    if (depth === path.length) return node.exact;\n\n    const seg = path[depth];\n    const isLast = depth === path.length - 1;\n\n    // Most-specific first: literal → $var → * (one segment, last only) → ** (any tail).\n    const litChild = node.lit?.get(seg);\n    if (litChild != null) {\n      const hit = this._match(litChild, path, depth + 1);\n      if (hit != null) return hit;\n    }\n    if (node.var != null) {\n      const hit = this._match(node.var.node, path, depth + 1);\n      if (hit != null) return hit;\n    }\n    if (isLast && node.star != null) return node.star;\n    if (node.deep != null) return node.deep;\n    return undefined;\n  }\n}\n","import type { TSchemaNode, TSchemaRoot } from \"./schema.types\";\nimport { sha256Hex } from \"./sha256\";\n\n/**\n * The realm schema hash: SHA-256 over a canonical serialization of\n * everything both sides must agree on for the wire to be meaningful — realm id, state shape\n * (sorted), client-type names, intent names + input shapes, and rule path patterns. It rides the\n * realm `hello` and hard-fails a mismatch (`err_realm.schema_mismatch`): silent token skew on a\n * stale mobile client would be data corruption, not an error.\n *\n * Known, documented limitation: an embedded standard-schema validator (`t.schema(...)`) is opaque\n * — its internals don't affect the hash (canonicalized as just `std`) unless the leaf opts in\n * with `t.schema(v, { hashTag })`, which the consumer bumps on contract changes. Untagged, treat\n * embedded-validator edits as value-rule changes, not shape changes.\n */\n\n// ⚠ Every encoding below is a deployed-hash contract (frozen goldens in schemaHash.test.ts).\n// A node with NO options must emit today's exact form — bare kind strings for primitives — or\n// every deployed realm's hash rotates. Optional fields append in a fixed property order.\nfunction canonNode(node: TSchemaNode): unknown {\n  switch (node.kind) {\n    case \"string\":\n      return node.maxLength == null ? node.kind : { k: \"string\", max: node.maxLength };\n    case \"number\": {\n      if (node.min == null && node.max == null && node.integer !== true) return node.kind;\n      return {\n        k: \"number\",\n        ...(node.min != null ? { min: node.min } : {}),\n        ...(node.max != null ? { max: node.max } : {}),\n        ...(node.integer === true ? { int: true } : {}),\n      };\n    }\n    case \"boolean\":\n      return node.kind;\n    case \"literal\":\n      return { k: \"lit\", v: node.value };\n    case \"union\":\n      // Union member order is meaning-preserving to keep sorted-stability simple: canonicalize\n      // members then sort their serialized forms, so reordering options never changes the hash.\n      return { k: \"u\", o: node.options.map((o) => JSON.stringify(canonNode(o))).sort() };\n    case \"optional\":\n      return { k: \"opt\", i: canonNode(node.inner) };\n    case \"object\": {\n      const names = Object.keys(node.entries).sort();\n      return { k: \"obj\", e: names.map((n) => [n, canonNode(node.entries[n])]) };\n    }\n    case \"record\": {\n      const base = { k: \"rec\", id: node.keyVar, v: canonNode(node.value) };\n      return node.maxKeys == null ? base : { ...base, max: node.maxKeys };\n    }\n    case \"array\": {\n      const base = { k: \"arr\", i: canonNode(node.item) };\n      return node.maxItems == null ? base : { ...base, max: node.maxItems };\n    }\n    case \"standard\":\n      return node.hashTag == null ? { k: \"std\" } : { k: \"std\", tag: node.hashTag };\n  }\n}\n\nexport interface ISchemaHashInputs {\n  id: string;\n  state: TSchemaRoot;\n  avatarTypes: readonly string[];\n  /** Sorted [name, inputNode] pairs. */\n  intents: readonly (readonly [string, TSchemaNode])[];\n  rulePatterns: readonly string[];\n}\n\n/** Canonical serialization (deterministic across platforms — everything sorted). */\nexport function canonicalSchemaString(inputs: ISchemaHashInputs): string {\n  const names = Object.keys(inputs.state).sort();\n  return JSON.stringify({\n    id: inputs.id,\n    state: names.map((n) => [n, canonNode(inputs.state[n])]),\n    clients: [...inputs.avatarTypes].sort(),\n    intents: [...inputs.intents]\n      .sort((a, b) => (a[0] < b[0] ? -1 : 1))\n      .map(([name, input]) => [name, canonNode(input)]),\n    rules: [...inputs.rulePatterns].sort(),\n  });\n}\n\nexport function computeSchemaHash(inputs: ISchemaHashInputs): string {\n  return sha256Hex(canonicalSchemaString(inputs));\n}\n","import type { TSchemaNode, TSchemaRoot } from \"./schema.types\";\n\n/**\n * The schema token map: object keys collapse to small integers on the wire; dynamic\n * record keys stay strings (interned per session later — the protocol contract). Tokens are assigned over\n * **sorted key names per object level**, so reordering keys in the definition never renumbers,\n * and adding a key only shifts tokens *after* it alphabetically — with the schema hash (which any\n * change does alter) guarding against skew, sorted assignment makes token layout deterministic\n * and reviewable rather than declaration-order-fragile.\n */\n\n/** A wire path element: an object-key token (int) or a dynamic record key (string, pre-intern). */\nexport type TWirePathSegment = number | string;\n\ninterface ITokenLevel {\n  /** name → token (sorted-name index) for an object level. */\n  toToken: Map<string, number>;\n  /** token → name. */\n  toName: string[];\n  /** Child level per entry name (object/record descend; leaves have none). */\n  children: Map<string, ITokenLevel | \"record\" | \"leaf\">;\n  /** For a record level's value side. */\n  recordChild?: ITokenLevel | \"record\" | \"leaf\";\n}\n\nfunction unwrapOptional(node: TSchemaNode): TSchemaNode {\n  return node.kind === \"optional\" ? unwrapOptional(node.inner) : node;\n}\n\nfunction buildLevelForNode(node: TSchemaNode): ITokenLevel | \"record\" | \"leaf\" {\n  const inner = unwrapOptional(node);\n  if (inner.kind === \"object\") return buildLevel(inner.entries);\n  if (inner.kind === \"record\") {\n    const level: ITokenLevel = {\n      toToken: new Map(),\n      toName: [],\n      children: new Map(),\n      recordChild: buildLevelForNode(inner.value),\n    };\n    return level;\n  }\n  return \"leaf\";\n}\n\nfunction buildLevel(entries: Record<string, TSchemaNode>): ITokenLevel {\n  const names = Object.keys(entries).sort();\n  const level: ITokenLevel = { toToken: new Map(), toName: [], children: new Map() };\n  names.forEach((name, i) => {\n    level.toToken.set(name, i);\n    level.toName.push(name);\n    level.children.set(name, buildLevelForNode(entries[name]));\n  });\n  return level;\n}\n\nexport class RealmTokenMap {\n  private readonly _root: ITokenLevel;\n\n  constructor(stateRoot: TSchemaRoot) {\n    this._root = buildLevel(stateRoot);\n  }\n\n  /**\n   * Name path → wire path (object keys → ints; record keys pass through as strings, or as\n   * interned ids when `internKey` resolves one — the protocol contract key interning).\n   */\n  tokenizePath(\n    path: readonly string[],\n    internKey?: (key: string) => number | undefined,\n  ): TWirePathSegment[] {\n    const out: TWirePathSegment[] = [];\n    let level: ITokenLevel | \"record\" | \"leaf\" = this._root;\n    for (const seg of path) {\n      if (level === \"leaf\" || level == null) {\n        throw new Error(`tokenizePath: path descends past a leaf at \"${seg}\" (${path.join(\".\")})`);\n      }\n      if (level === \"record\") {\n        throw new Error(`tokenizePath: internal record level error at \"${seg}\"`);\n      }\n      if (level.recordChild != null) {\n        // A record level: the segment is a dynamic key — interned id when known, else verbatim.\n        out.push(internKey?.(seg) ?? seg);\n        level = level.recordChild;\n        continue;\n      }\n      const token = level.toToken.get(seg);\n      if (token == null) {\n        throw new Error(`tokenizePath: unknown key \"${seg}\" in path ${path.join(\".\")}`);\n      }\n      out.push(token);\n      level = level.children.get(seg) ?? \"leaf\";\n    }\n    return out;\n  }\n\n  /**\n   * Wire path → name path (inverse of {@link tokenizePath}). At record levels an int segment is\n   * an interned key id, resolved through `resolveKey` (absence of a resolver, or an unknown id,\n   * is a hard error — silent misresolution would corrupt paths).\n   */\n  detokenizePath(\n    wirePath: readonly TWirePathSegment[],\n    resolveKey?: (id: number) => string | undefined,\n  ): string[] {\n    const out: string[] = [];\n    let level: ITokenLevel | \"record\" | \"leaf\" = this._root;\n    for (const seg of wirePath) {\n      if (level === \"leaf\" || level === \"record\" || level == null) {\n        throw new Error(`detokenizePath: path descends past a leaf (${wirePath.join(\".\")})`);\n      }\n      if (level.recordChild != null) {\n        if (typeof seg === \"number\") {\n          const key = resolveKey?.(seg);\n          if (key == null) {\n            throw new Error(`detokenizePath: unknown interned key id ${seg}`);\n          }\n          out.push(key);\n        } else {\n          out.push(seg);\n        }\n        level = level.recordChild;\n        continue;\n      }\n      if (typeof seg !== \"number\" || seg < 0 || seg >= level.toName.length) {\n        throw new Error(`detokenizePath: invalid token \"${seg}\" (${wirePath.join(\".\")})`);\n      }\n      const name = level.toName[seg];\n      out.push(name);\n      level = level.children.get(name) ?? \"leaf\";\n    }\n    return out;\n  }\n\n  /** The schema node names at the root level, in token order (test/debug surface). */\n  rootTokenNames(): readonly string[] {\n    return this._root.toName;\n  }\n}\n","import type { IIntentBuilder, IRealmIntentDef } from \"./Intents/intents.types\";\nimport { createIntentBuilder } from \"./Intents/intents.types\";\nimport type { IRuleBuilder } from \"./Rules/ruleBuilder\";\nimport { createRuleBuilder } from \"./Rules/ruleBuilder\";\nimport { assertRulePatternsMatchSchema, assertTransientRoots } from \"./Rules/ruleSchemaLint\";\nimport type { IRealmRule } from \"./Rules/rules.types\";\nimport { RealmRuleTrie } from \"./Rules/ruleTrie\";\nimport type {\n  ISchemaServerContext,\n  ISchemaString,\n  TInferEntries,\n  TInferNode,\n  TSchemaRoot,\n} from \"./Schema/schema.types\";\nimport { computeSchemaHash } from \"./Schema/schemaHash\";\nimport { RealmTokenMap } from \"./Schema/tokenMap\";\n\n/** An avatar-type entry in the realm's `avatars` registry. v1: string persistent ids. */\nexport interface IRealmAvatarTypeDef {\n  readonly persistentId: ISchemaString;\n}\n\n/**\n * The **minimum** wire security level a realm requires of the connection carrying it. Two members\n * only — there is deliberately no `\"none\"`: an unauthenticated realm is the `allowPlain` acceptor\n * door, kept off the realm's own contract (a dev/trusted-network endpoint opts into plain at the\n * acceptor, never by weakening a realm definition).\n *\n * This is a realm-local string union, **not** wire's `ESecurityLevel` — this module ships to\n * clients, and mapping to the enum happens at the serve/connect boundary. It is a **policy floor\n * enforced at attach** (the server rejects a lower connection, the client refuses to `hello` on\n * one), NOT a wire-compat fact: it is intentionally left OUT of the schema hash, so it changes no\n * bytes on the wire and re-declaring it never forces a migration.\n */\nexport type TRealmSecurityLevel = \"authenticated\" | \"encrypted\";\n\n/** Extract the ctx type a `t.serverContext<...>()` marker carries (`undefined` when absent). */\ntype TCtxOf<N> = N extends ISchemaServerContext<infer TCtx> ? TCtx : undefined;\n\ntype TIntentsRecord = Record<string, IRealmIntentDef<any, any, any, any>>;\n\nexport interface IDefineRealmInput<\n  TAvatars extends Record<string, IRealmAvatarTypeDef>,\n  TStateDef extends TSchemaRoot,\n  TCtxNode extends ISchemaServerContext | undefined,\n  TIntents extends TIntentsRecord,\n  // Resolved once (defaulted param) then referenced opaquely below — see `defineRealm`'s doc on\n  // why the full state type must not be re-expanded (`TInferEntries<TStateDef>`) at each use site.\n  TState = TInferEntries<TStateDef>,\n  TId extends string = string,\n> {\n  /** Stable wire identity — folded into the schema hash. */\n  id: TId;\n  /**\n   * The minimum wire security level this realm requires (default `\"authenticated\"`). Enforced at\n   * attach on both ends — see {@link TRealmSecurityLevel}. Deliberately not in the schema hash.\n   */\n  security?: TRealmSecurityLevel;\n  /** Avatar-type registry (replica-class avatars are ordinary entries). */\n  avatars: TAvatars;\n  /** TYPE-ONLY server context marker (`t.serverContext<...>()`); value injected at serve time. */\n  serverContext?: TCtxNode;\n  state: TStateDef;\n  /**\n   * Transient state regions: subtree roots whose writes are\n   * **not persisted** — not logged, not snapshotted, no CAS touch history. Presence/cursor shaped\n   * state, worthless a second later, that would otherwise pay the full durability cost on a durable\n   * realm. A resuming or cold-started client gets these regions fresh (replay refresh + hydrate) —\n   * and, crucially, a **same-epoch hibernation wake** reloads a durable realm's transient regions\n   * at their genesis value (they are stripped from every snapshot), so an attached client's own\n   * entry silently vanishes on every wake. Pair a transient region with `connectRealm`'s\n   * `assertOnAttach` to re-own your entry: it runs on the first hydrate AND (for a transient-bearing\n   * realm) after every resume answer, so the entry is re-created across reconnects and wakes alike.\n   *\n   * v1 accepts **concrete, wildcard-free dot-paths** naming a subtree root (`[\"presence\"]`,\n   * `[\"board.cursors\"]`) — validated at definition time. Not part of the schema hash (a persistence\n   * behavior, not a wire fact). Do NOT use CAS (`touchedSince`) under a transient region — it has no\n   * touch history; `durability: \"reassert\"` writes, by contrast, are the right pairing.\n   */\n  transient?: string[];\n  rules: (\n    r: IRuleBuilder<TStateDef, TState, keyof TAvatars & string, TCtxOf<TCtxNode>>,\n  ) => readonly IRealmRule<keyof TAvatars & string, TState, TCtxOf<TCtxNode>>[];\n  intents?: (i: IIntentBuilder<TState, keyof TAvatars & string, TCtxOf<TCtxNode>>) => TIntents;\n}\n\nexport interface IRealmDefinition<\n  TState = unknown,\n  TAvatarType extends string = string,\n  TCtx = unknown,\n  TIntents extends TIntentsRecord = TIntentsRecord,\n  TStateDef extends TSchemaRoot = TSchemaRoot,\n  TId extends string = string,\n> {\n  readonly id: TId;\n  /**\n   * The resolved minimum wire security level (defaulted to `\"authenticated\"`). Read by the serve\n   * host and `connectRealm`/`connectRealmReplica`; never hashed.\n   */\n  readonly security: TRealmSecurityLevel;\n  readonly avatarTypes: readonly TAvatarType[];\n  readonly stateDef: TStateDef;\n  readonly rules: readonly IRealmRule<TAvatarType, TState, TCtx>[];\n  readonly ruleTrie: RealmRuleTrie<IRealmRule<TAvatarType, TState, TCtx>>;\n  readonly intents: TIntents;\n  /** Intent names in sorted (wire-token) order. */\n  readonly intentNames: readonly string[];\n  readonly tokens: RealmTokenMap;\n  /**\n   * Parsed transient region roots — concrete segment paths, validated at define time.\n   * Empty for a fully-durable realm. Read by the engine (commit classification, replay refresh) and\n   * the DO host (snapshot strip); deliberately NOT in the schema hash.\n   */\n  readonly transient: readonly string[][];\n  /** SHA-256 over the canonical definition — the handshake gate. */\n  readonly schemaHash: string;\n  /** @internal phantom */\n  readonly _state?: TState;\n  /** @internal phantom */\n  readonly _ctx?: TCtx;\n}\n\n/**\n * The single source of truth: one block declaring the state shape, the client types,\n * the rules, and the intents — from which the types, token map, schema hash, rule trie, and\n * prediction bundle all derive. **This module ships to clients**: nothing here may close over\n * secrets; server-only data enters via `createRealmServerEngine(realm, { ctx })`.\n */\nexport function defineRealm<\n  const TAvatars extends Record<string, IRealmAvatarTypeDef>,\n  TStateDef extends TSchemaRoot,\n  TCtxNode extends ISchemaServerContext | undefined = undefined,\n  TIntents extends TIntentsRecord = Record<string, never>,\n  // Compute the full inferred state type **once** here, then thread it through the input's `rules`\n  // / `intents` callbacks and the returned definition as the opaque `TState`. Re-expanding\n  // `TInferEntries<TStateDef>` at each of those use sites made a rich schema trip TS2589\n  // (\"excessively deep\") — the whole `rules` array is contextually typed in one pass, so the deep\n  // state type was re-instantiated once per rule and the aggregate blew past the depth guard.\n  TState = TInferEntries<TStateDef>,\n  const TId extends string = string,\n>(\n  input: IDefineRealmInput<TAvatars, TStateDef, TCtxNode, TIntents, TState, TId>,\n): IRealmDefinition<TState, keyof TAvatars & string, TCtxOf<TCtxNode>, TIntents, TStateDef, TId> {\n  type TAvatarType = keyof TAvatars & string;\n  type TCtx = TCtxOf<TCtxNode>;\n\n  const rules = input.rules(createRuleBuilder<TStateDef, TState, TAvatarType, TCtx>());\n  // Dead-rule lint: a pattern the schema can never produce a path for (a typo'd key, or a\n  // wildcard descending into a wire-leaf like t.array) is a silent default-deny — throw instead.\n  assertRulePatternsMatchSchema(\n    input.state,\n    rules.map((rule) => rule.pattern),\n  );\n  const ruleTrie = new RealmRuleTrie(rules);\n  // Transient region roots (Phase 5): validated + parsed at define time (wildcard-free, in-schema).\n  const transient = assertTransientRoots(input.state, input.transient ?? []);\n  const intents =\n    input.intents?.(createIntentBuilder<TState, TAvatarType, TCtx>()) ?? ({} as TIntents);\n  const intentNames = Object.keys(intents).sort();\n  const avatarTypes = Object.keys(input.avatars).sort() as TAvatarType[];\n  const tokens = new RealmTokenMap(input.state);\n\n  const schemaHash = computeSchemaHash({\n    id: input.id,\n    state: input.state,\n    avatarTypes,\n    intents: intentNames.map((name) => [name, intents[name].input] as const),\n    rulePatterns: rules.map((rule) => rule.pattern),\n  });\n\n  return {\n    id: input.id,\n    // Policy floor, resolved once; enforced at attach (Phases 2/4), never hashed above.\n    security: input.security ?? \"authenticated\",\n    avatarTypes,\n    stateDef: input.state,\n    rules,\n    ruleTrie,\n    intents,\n    intentNames,\n    tokens,\n    transient,\n    schemaHash,\n  };\n}\n\n// ── Inference helpers ────────────────────────────────────────────\n\nexport type TInferRealmState<R> = R extends { _state?: infer TState } ? TState : never;\n\n/**\n * A client type's view of the realm state. v1: identical to the full state type — none of the\n * v1 `view` condition forms are statically decidable per branch (function conditions can't be\n * evaluated at the type level), so no branch can be soundly omitted yet. Static narrowing for\n * `r.avatarTypes(...)`-only branches is a recorded follow-up.\n */\nexport type TInferAvatarView<R, _TAvatarType extends string = string> = TInferRealmState<R>;\n\nexport type TInferIntentInput<\n  R extends { intents: TIntentsRecord },\n  K extends keyof R[\"intents\"],\n> = TInferNode<R[\"intents\"][K][\"input\"]>;\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type {\n  ISchemaArray,\n  ISchemaBoolean,\n  ISchemaId,\n  ISchemaLiteral,\n  ISchemaNumber,\n  ISchemaObject,\n  ISchemaOptional,\n  ISchemaRecord,\n  ISchemaServerContext,\n  ISchemaStandard,\n  ISchemaString,\n  ISchemaUnion,\n  TInferEntries,\n  TInferNode,\n  TSchemaNode,\n} from \"./schema.types\";\n\ntype TUnionOptions = readonly [TSchemaNode, TSchemaNode, ...TSchemaNode[]];\n\nexport interface IStringNodeOptions {\n  /** Max length in UTF-16 code units (`String.prototype.length`). */\n  maxLength?: number;\n}\nexport interface INumberNodeOptions {\n  min?: number;\n  max?: number;\n  integer?: boolean;\n}\nexport interface IArrayNodeOptions {\n  maxItems?: number;\n}\nexport interface IRecordNodeOptions {\n  maxKeys?: number;\n}\nexport interface IStandardNodeOptions {\n  /** Contributes to the schema hash — bump on every contract change of the embedded validator. */\n  hashTag?: string;\n}\n\n/** Bounds are declaration errors when malformed — caught at `defineRealm` time, not at runtime. */\nfunction checkCount(name: string, value: number | undefined): number | undefined {\n  if (value == null) return undefined;\n  if (!Number.isSafeInteger(value) || value < 0) {\n    throw new Error(`t: ${name} must be a non-negative safe integer, got ${value}`);\n  }\n  return value;\n}\n\nfunction checkNumberOptions(\n  options: INumberNodeOptions,\n): Pick<ISchemaNumber, \"min\" | \"max\" | \"integer\"> {\n  const { min, max, integer } = options;\n  if (min != null && !Number.isFinite(min))\n    throw new Error(`t: number min must be finite, got ${min}`);\n  if (max != null && !Number.isFinite(max))\n    throw new Error(`t: number max must be finite, got ${max}`);\n  if (min != null && max != null && min > max) {\n    throw new Error(`t: number min (${min}) must be <= max (${max})`);\n  }\n  if (integer != null && typeof integer !== \"boolean\") {\n    throw new Error(`t: number integer must be a boolean`);\n  }\n  return {\n    ...(min != null ? { min } : {}),\n    ...(max != null ? { max } : {}),\n    // `integer: false` is a no-op and is normalized to omission so it never moves the hash.\n    ...(integer === true ? { integer: true as const } : {}),\n  };\n}\n\n/**\n * A union of at least two nodes — spread the options, or pass one readonly array (both are\n * equivalent):\n * ```ts\n * t.union(t.literal(\"idle\"), t.literal(\"running\"))\n * t.union([t.literal(\"idle\"), t.literal(\"running\")])\n * ```\n */\nfunction union<const O extends TUnionOptions>(...options: O): ISchemaUnion<TInferNode<O[number]>>;\nfunction union<const O extends TUnionOptions>(options: O): ISchemaUnion<TInferNode<O[number]>>;\nfunction union(...args: readonly (TSchemaNode | TUnionOptions)[]): ISchemaUnion<unknown> {\n  const options = args.flatMap((arg) => (Array.isArray(arg) ? arg : [arg]));\n  if (options.length < 2) {\n    throw new Error(`t.union needs at least 2 options, got ${options.length}`);\n  }\n  return { kind: \"union\", options };\n}\n\n/**\n * The realm schema builder — `t.*`. One `defineRealm` block uses these to declare the\n * state shape; from that single declaration the library derives the TS types, the token map, the\n * schema hash, and (M4) the server-side value validator.\n */\nexport const t = {\n  string(options: IStringNodeOptions = {}): ISchemaString {\n    const maxLength = checkCount(\"string maxLength\", options.maxLength);\n    return { kind: \"string\", ...(maxLength != null ? { maxLength } : {}) };\n  },\n  number(options: INumberNodeOptions = {}): ISchemaNumber {\n    return { kind: \"number\", ...checkNumberOptions(options) };\n  },\n  boolean(): ISchemaBoolean {\n    return { kind: \"boolean\" };\n  },\n  literal<const V extends string | number | boolean>(value: V): ISchemaLiteral<V> {\n    return { kind: \"literal\", value };\n  },\n  union,\n  optional<N extends TSchemaNode>(inner: N): ISchemaOptional<TInferNode<N>, N> {\n    return { kind: \"optional\", inner };\n  },\n  object<E extends Record<string, TSchemaNode>>(entries: E): ISchemaObject<TInferEntries<E>, E> {\n    return { kind: \"object\", entries };\n  },\n  /** Record-key marker for {@link t.record} — binds `$varName` in rule paths. */\n  id<N extends string>(varName: N): ISchemaId<N> {\n    return { kind: \"id\", varName };\n  },\n  record<K extends ISchemaId, V extends TSchemaNode>(\n    key: K,\n    value: V,\n    options: IRecordNodeOptions = {},\n  ): ISchemaRecord<V, TInferNode<V>> {\n    const maxKeys = checkCount(\"record maxKeys\", options.maxKeys);\n    return { kind: \"record\", keyVar: key.varName, value, ...(maxKeys != null ? { maxKeys } : {}) };\n  },\n  /** Leaf-replace semantics only in v1 (proposal §7.8) — prefer keyed {@link t.record} collections. */\n  array<N extends TSchemaNode>(\n    item: N,\n    options: IArrayNodeOptions = {},\n  ): ISchemaArray<TInferNode<N>> {\n    const maxItems = checkCount(\"array maxItems\", options.maxItems);\n    return { kind: \"array\", item, ...(maxItems != null ? { maxItems } : {}) };\n  },\n  /**\n   * Embed a standard-schema validator (e.g. valibot) at a leaf. The embedded schema's internals\n   * are opaque to the schema hash — editing it does NOT change the realm's schemaHash. Pass a\n   * `hashTag` (and bump it on every contract change) to opt the leaf's contract into the hash;\n   * untagged, treat embedded-validator changes as value-rule changes, not shape changes.\n   */\n  schema<S extends StandardSchemaV1>(\n    schema: S,\n    options: IStandardNodeOptions = {},\n  ): ISchemaStandard<StandardSchemaV1.InferOutput<S>> {\n    if (\n      options.hashTag != null &&\n      (typeof options.hashTag !== \"string\" || options.hashTag === \"\")\n    ) {\n      throw new Error(\"t.schema: hashTag must be a non-empty string\");\n    }\n    return {\n      kind: \"standard\",\n      schema,\n      ...(options.hashTag != null ? { hashTag: options.hashTag } : {}),\n    };\n  },\n  /**\n   * Declare the server-only context TYPE. The value is injected at\n   * `createRealmServerEngine(realm, { ctx })` time — nothing here exists in client bundles, and\n   * nothing secret may be closed over in the definition module.\n   */\n  serverContext<TCtx>(): ISchemaServerContext<TCtx> {\n    return { kind: \"serverContext\" };\n  },\n};\n","import type { TSchemaNode, TSchemaRoot } from \"./schema.types\";\nimport { type IValueInvalid, validateValue } from \"./validateValue\";\n\n/**\n * State-aware bound enforcement (the second layer over `validateValue`'s per-value checks).\n * `validateValue` only ever sees the value being written, so it cannot catch a bound whose truth\n * lives in the *surrounding* state — the canonical case: `t.record(…, { maxKeys: 8 })` filled one\n * incremental `record.$id` add at a time, where each child value is individually valid. These\n * walks run against the **candidate next state** after a whole patch batch (so remove+add nets\n * out), and once over the full tree at boot/restore/migration.\n *\n * Everything here is bounds-only and skip-fast: a schema without bounds costs one memoized lookup\n * and nothing else, and subtrees carrying no bounds are never entered.\n */\n\nconst HAS_BOUNDS = new WeakMap<object, boolean>();\n\nfunction nodeHasBounds(node: TSchemaNode): boolean {\n  const cached = HAS_BOUNDS.get(node);\n  if (cached != null) return cached;\n  let result: boolean;\n  switch (node.kind) {\n    case \"string\":\n      result = node.maxLength != null;\n      break;\n    case \"number\":\n      result = node.min != null || node.max != null || node.integer === true;\n      break;\n    case \"boolean\":\n    case \"literal\":\n    case \"standard\":\n      result = false;\n      break;\n    case \"optional\":\n      result = nodeHasBounds(node.inner);\n      break;\n    case \"union\":\n      result = node.options.some(nodeHasBounds);\n      break;\n    case \"object\":\n      result = Object.values(node.entries).some(nodeHasBounds);\n      break;\n    case \"record\":\n      result = node.maxKeys != null || nodeHasBounds(node.value);\n      break;\n    case \"array\":\n      result = node.maxItems != null || nodeHasBounds(node.item);\n      break;\n  }\n  HAS_BOUNDS.set(node, result);\n  return result;\n}\n\n/** Whether any node in the state tree declares a bound — the engine's do-nothing fast path. */\nexport function schemaRootHasBounds(root: TSchemaRoot): boolean {\n  return Object.values(root).some(nodeHasBounds);\n}\n\nfunction unwrapOptional(node: TSchemaNode): TSchemaNode {\n  return node.kind === \"optional\" ? unwrapOptional(node.inner) : node;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n  return typeof value === \"object\" && value != null && !Array.isArray(value);\n}\n\nfunction getAtPath(state: unknown, path: readonly (string | number)[]): unknown {\n  let current: unknown = state;\n  for (const seg of path) {\n    if (current == null || typeof current !== \"object\") return undefined;\n    current = (current as Record<string | number, unknown>)[seg];\n  }\n  return current;\n}\n\n/**\n * Bounds-only walk of a value against its node. Type mismatches are NOT reported here — shape\n * validation belongs to `validateValue` on the paths that run it; this walk only answers \"does\n * any declared bound fail\". The one exception is a union carrying bounds: bounds inside a union\n * are only checkable by structurally matching an option, so `validateValue` (which includes\n * bounds) is the matcher and a value matching no option reports as invalid.\n */\nfunction checkBoundsDeep(node: TSchemaNode, value: unknown): IValueInvalid | undefined {\n  if (!nodeHasBounds(node)) return undefined;\n  switch (node.kind) {\n    case \"string\":\n      if (typeof value === \"string\" && node.maxLength != null && value.length > node.maxLength) {\n        return { path: [], expected: `a string of at most ${node.maxLength} characters` };\n      }\n      return undefined;\n    case \"number\":\n      // nodeHasBounds ⇒ this is a bounded number; validateValue applies exactly its bound checks.\n      return typeof value === \"number\" ? validateValue(node, value) : undefined;\n    case \"optional\":\n      return value === undefined ? undefined : checkBoundsDeep(node.inner, value);\n    case \"union\":\n      return validateValue(node, value);\n    case \"object\": {\n      if (!isPlainObject(value)) return undefined;\n      for (const [key, child] of Object.entries(node.entries)) {\n        const childValue = value[key];\n        if (childValue === undefined) continue;\n        const invalid = checkBoundsDeep(child, childValue);\n        if (invalid != null) return { path: [key, ...invalid.path], expected: invalid.expected };\n      }\n      return undefined;\n    }\n    case \"record\": {\n      if (!isPlainObject(value)) return undefined;\n      if (node.maxKeys != null && Object.keys(value).length > node.maxKeys) {\n        return { path: [], expected: `a record with at most ${node.maxKeys} entries` };\n      }\n      if (!nodeHasBounds(node.value)) return undefined;\n      for (const [key, entry] of Object.entries(value)) {\n        const invalid = checkBoundsDeep(node.value, entry);\n        if (invalid != null) return { path: [key, ...invalid.path], expected: invalid.expected };\n      }\n      return undefined;\n    }\n    case \"array\": {\n      if (!Array.isArray(value)) return undefined;\n      if (node.maxItems != null && value.length > node.maxItems) {\n        return { path: [], expected: `an array of at most ${node.maxItems} items` };\n      }\n      if (!nodeHasBounds(node.item)) return undefined;\n      for (let i = 0; i < value.length; i++) {\n        const invalid = checkBoundsDeep(node.item, value[i]);\n        if (invalid != null) return { path: [i, ...invalid.path], expected: invalid.expected };\n      }\n      return undefined;\n    }\n    default:\n      return undefined;\n  }\n}\n\n/** Full-tree bounds walk — boot, restore, and migration output, before any client attaches. */\nexport function validateBoundedStateTree(\n  root: TSchemaRoot,\n  state: Record<string, unknown>,\n): IValueInvalid | undefined {\n  for (const [name, node] of Object.entries(root)) {\n    if (!nodeHasBounds(node)) continue;\n    const invalid = checkBoundsDeep(node, state[name]);\n    if (invalid != null) return { path: [name, ...invalid.path], expected: invalid.expected };\n  }\n  return undefined;\n}\n\n/**\n * Bounds gate for one commit: given the **candidate next state** and the batch's canonical patch\n * paths, check (a) `maxKeys` on every record *ancestor* a path descends into — the constraint an\n * incremental entry add changes without ever writing the record itself — and (b) all bounds\n * within each patched subtree's final value. Checks dedupe across the batch and run against the\n * final state, so remove+add sequences net out and multi-patch frames are judged once, atomically.\n */\nexport function validateBoundedPatches(\n  root: TSchemaRoot,\n  stateAfter: unknown,\n  paths: readonly (readonly (string | number)[])[],\n): IValueInvalid | undefined {\n  const checked = new Set<string>();\n  for (const path of paths) {\n    let entries: Record<string, TSchemaNode> | undefined = root;\n    let node: TSchemaNode | undefined;\n    for (let i = 0; i < path.length; i++) {\n      const seg = path[i];\n      if (entries != null) {\n        node = typeof seg === \"string\" ? entries[seg] : undefined;\n        entries = undefined;\n      } else if (node != null) {\n        const inner = unwrapOptional(node);\n        if (inner.kind === \"object\") node = inner.entries[seg as string];\n        else if (inner.kind === \"record\") node = inner.value;\n        else node = undefined;\n      }\n      if (node == null) break;\n      const inner = unwrapOptional(node);\n      // A record the path descends THROUGH may have gained an entry; the terminal node (a path\n      // ending exactly at the record) is instead covered by the subtree check below.\n      if (inner.kind === \"record\" && inner.maxKeys != null && i + 1 < path.length) {\n        const prefix = path.slice(0, i + 1);\n        const key = `A:${prefix.join(\"\\0\")}`;\n        if (!checked.has(key)) {\n          checked.add(key);\n          const value = getAtPath(stateAfter, prefix);\n          if (isPlainObject(value) && Object.keys(value).length > inner.maxKeys) {\n            return {\n              path: [...prefix],\n              expected: `a record with at most ${inner.maxKeys} entries`,\n            };\n          }\n        }\n      }\n    }\n    if (node != null) {\n      const key = `T:${path.join(\"\\0\")}`;\n      if (!checked.has(key)) {\n        checked.add(key);\n        const value = getAtPath(stateAfter, path);\n        if (value !== undefined) {\n          const invalid = checkBoundsDeep(node, value);\n          if (invalid != null) {\n            return { path: [...path, ...invalid.path], expected: invalid.expected };\n          }\n        }\n      }\n    }\n  }\n  return undefined;\n}\n","import type { Patch } from \"immer\";\nimport { evalViewCond } from \"../RealmDefinition/Rules/evalRules\";\nimport type { IRealmRule, IViewAvatarRef } from \"../RealmDefinition/Rules/rules.types\";\nimport type { RealmRuleTrie } from \"../RealmDefinition/Rules/ruleTrie\";\nimport type { TSchemaNode, TSchemaRoot } from \"../RealmDefinition/Schema/schema.types\";\nimport { schemaNodeAtPath } from \"../RealmWire/wirePatch\";\n\n/**\n * The slicer: what of the state — and of each committed patch — a given avatar may\n * see. Visibility is decided **per leaf** by the most-specific matching rule's `view` condition\n * (default-deny: a path no rule covers is server-only). Fixed object containers are structural\n * (the schema ships to clients — their existence is not a secret) and always present in a slice;\n * **record entries** are omitted entirely when none of their leaves are visible (an entry's\n * existence *is* data — order ids, player ids).\n */\n\nexport interface IViewSliceContext {\n  schemaRoot: TSchemaRoot;\n  trie: RealmRuleTrie<IRealmRule<any, any, any>>;\n  /** View-only identity: `type`/`persistentId`, never `instanceId` — see {@link IViewAvatarRef}. */\n  avatar: IViewAvatarRef;\n}\n\nexport function leafVisible(ctx: IViewSliceContext, path: readonly string[]): boolean {\n  const match = ctx.trie.match(path);\n  if (match == null) return false;\n  return evalViewCond(match.rule.view, { avatar: ctx.avatar, params: match.params });\n}\n\nfunction unwrapOptional(node: TSchemaNode): TSchemaNode {\n  return node.kind === \"optional\" ? unwrapOptional(node.inner) : node;\n}\n\ninterface IPruned {\n  value: unknown;\n  /** Something beneath is visible to the avatar, so this node ships on its own. */\n  anyVisible: boolean;\n  /**\n   * A required container a rule reaches beneath: it ships (as `{}` when nothing in it is visible)\n   * wherever its parent ships, but never makes that parent ship.\n   */\n  structural: boolean;\n}\n\nconst OMIT: IPruned = { value: undefined, anyVisible: false, structural: false };\n\n/** Does `path` pass through a record entry? Its containers are then data, not structure. */\nfunction underRecordEntry(schemaRoot: TSchemaRoot, path: readonly string[]): boolean {\n  for (let depth = 1; depth < path.length; depth++) {\n    const parent = schemaNodeAtPath(schemaRoot, path.slice(0, depth));\n    if (parent != null && unwrapOptional(parent).kind === \"record\") return true;\n  }\n  return false;\n}\n\nfunction pruneNode(\n  ctx: IViewSliceContext,\n  node: TSchemaNode,\n  value: unknown,\n  path: string[],\n  inEntry = underRecordEntry(ctx.schemaRoot, path),\n): IPruned {\n  if (value === undefined) return OMIT;\n  const inner = unwrapOptional(node);\n  // An optional's presence is data: only something visible inside it may reveal it.\n  const required = node.kind !== \"optional\";\n  if (inner.kind === \"object\") {\n    const out: Record<string, unknown> = {};\n    let anyVisible = false;\n    let structural = false;\n    for (const [key, child] of Object.entries(inner.entries)) {\n      const pruned = pruneNode(\n        ctx,\n        child,\n        (value as Record<string, unknown>)[key],\n        [...path, key],\n        inEntry,\n      );\n      if (pruned.anyVisible || pruned.structural) out[key] = pruned.value;\n      if (pruned.anyVisible) anyVisible = true;\n      if (pruned.structural) structural = true;\n    }\n    // Structural: the object shell is always present, even when all of its leaves are hidden.\n    return { value: out, anyVisible, structural: required && structural };\n  }\n  if (inner.kind === \"record\") {\n    const out: Record<string, unknown> = {};\n    let anyVisible = false;\n    if (value != null && typeof value === \"object\") {\n      for (const [key, entry] of Object.entries(value)) {\n        const pruned = pruneNode(ctx, inner.value, entry, [...path, key], true);\n        if (pruned.anyVisible) {\n          out[key] = pruned.value; // entries with nothing visible are omitted entirely\n          anyVisible = true;\n        }\n      }\n    }\n    // The record *container* is structural, like an object shell — it is in the schema every\n    // avatar already has; only its ENTRIES are data. An empty (or fully-pruned) record whose own\n    // position a rule makes visible must still ship as `{}`: omitting the key would leave a later\n    // `add <path>/<entry>` patch no parent to resolve into on the avatar. Entry existence stays\n    // rule-gated — a container made visible by `x.**` grants exactly what that rule says.\n    //\n    // A container reached only through fixed keys also ships when any rule reaches BENEATH it\n    // (`a.rec.$id`), the same invariant the top level has — but only inside a parent that ships\n    // anyway: never inside a record entry or as an optional, whose existence is data.\n    const structural = required && !inEntry && ctx.trie.reachesBeneath(path);\n    return { value: out, anyVisible: anyVisible || leafVisible(ctx, path), structural };\n  }\n  // Leaf (incl. arrays and embedded validators — atomic on the wire).\n  return leafVisible(ctx, path) ? { value, anyVisible: true, structural: false } : OMIT;\n}\n\n/**\n * Whether the avatar holds `path`'s parent, so a structure-only patch there reveals nothing: true\n * unless an optional sits between the top level and `path` that neither state shows the avatar.\n */\nfunction holdsParent(\n  ctx: IViewSliceContext,\n  path: readonly string[],\n  states: readonly (object | undefined)[],\n): boolean {\n  // The innermost optional decides: a visible optional is shipped with everything above it.\n  for (let depth = path.length - 1; depth >= 2; depth--) {\n    const ancestorPath = path.slice(0, depth);\n    const ancestor = schemaNodeAtPath(ctx.schemaRoot, ancestorPath);\n    if (ancestor?.kind !== \"optional\") continue;\n    return states.some(\n      (state) =>\n        state != null &&\n        pruneNode(ctx, ancestor, getAtPath(state, ancestorPath), ancestorPath).anyVisible,\n    );\n  }\n  return true;\n}\n\n/** A sliced patch target ships for its visible content, or as structure inside a held parent. */\nfunction patchTargetShips(\n  ctx: IViewSliceContext,\n  pruned: IPruned,\n  path: readonly string[],\n  states: readonly (object | undefined)[],\n): boolean {\n  if (pruned.anyVisible) return true;\n  return pruned.structural && holdsParent(ctx, path, states);\n}\n\n/** The avatar's sliced view of the whole state — the hydrate payload. */\nexport function sliceStateForAvatar(ctx: IViewSliceContext, state: object): object {\n  const out: Record<string, unknown> = {};\n  for (const [key, node] of Object.entries(ctx.schemaRoot)) {\n    const pruned = pruneNode(ctx, node, (state as Record<string, unknown>)[key], [key]);\n    // Top-level branches are structural objects/records — always present, sliced inside.\n    out[key] = pruned.value ?? {};\n  }\n  return out;\n}\n\n/**\n * Slice one committed patch for an avatar: `undefined` = not visible at all; otherwise the patch,\n * possibly with a pruned value (a subtree patch spanning mixed-visibility leaves sends each\n * audience only its slice). `statePrev` (pre-commit) drives `remove` expansion; a replay path may\n * pass `undefined` — a `remove` that can't be proven invisible is then included (removing a key\n * the avatar never had must be a client-side no-op). `stateAfter` (post-commit), with `statePrev`,\n * decides whether the avatar holds an optional ancestor of a structure-only container patch.\n */\nexport function slicePatchForAvatar(\n  ctx: IViewSliceContext,\n  patch: Patch,\n  statePrev: object | undefined,\n  stateAfter?: object,\n): Patch | undefined {\n  const path = patch.path as string[];\n  const node = schemaNodeAtPath(ctx.schemaRoot, path);\n  if (node == null) return undefined;\n  const inner = unwrapOptional(node);\n\n  if (inner.kind !== \"object\" && inner.kind !== \"record\") {\n    return leafVisible(ctx, path) ? patch : undefined;\n  }\n\n  if (patch.op === \"remove\") {\n    // Visible if any covered leaf (enumerated from the pre-commit state) is visible.\n    const prev = statePrev == null ? undefined : getAtPath(statePrev, path);\n    if (prev === undefined) return patch; // can't prove invisible (replay) ⇒ include, no-op safe\n    const pruned = pruneNode(ctx, node, prev, [...path]);\n    return patchTargetShips(ctx, pruned, path, [statePrev, stateAfter]) ? patch : undefined;\n  }\n\n  const pruned = pruneNode(ctx, node, patch.value, [...path]);\n  if (!patchTargetShips(ctx, pruned, path, [statePrev, stateAfter])) return undefined;\n  return { op: patch.op, path, value: pruned.value };\n}\n\n/**\n * Slice a transient region's whole-region replay refresh (the `replace <root> = <regionValue>` ops\n * {@link RealmServerEngine._buildReplayOps} appends). Unlike {@link slicePatchForAvatar}, this\n * ALWAYS returns a patch: a fully-pruned or empty region ships as `replace <root> = {}` rather than\n * being dropped by the \"omit empty containers\" rule. That drop is the bug behind Overshot's\n * stranded-forever `write_target_missing`: when a same-epoch wake wipes a transient region to empty\n * (or leaves only entries the avatar can't see), the empty refresh was sliced away, so the resuming\n * avatar never learned its OWN entry had vanished — its `confirmed` kept the stale entry, its\n * guarded `assertOnAttach` saw the entry \"present\" and never re-owned, and it looped on doomed leaf\n * writes until a full reload. The region container is structural (already in every hydrate as `{}`),\n * so shipping an empty replace is safe — it only clears stale entries.\n */\nexport function sliceTransientRefreshForAvatar(ctx: IViewSliceContext, patch: Patch): Patch {\n  const path = patch.path as string[];\n  const node = schemaNodeAtPath(ctx.schemaRoot, path);\n  if (node == null) return patch; // no schema node — pass through untouched (defensive)\n  const pruned = pruneNode(ctx, node, patch.value, [...path]);\n  return { op: \"replace\", path, value: pruned.value ?? {} };\n}\n\nfunction getAtPath(state: object, path: readonly string[]): unknown {\n  let current: unknown = state;\n  for (const seg of path) {\n    if (current == null || typeof current !== \"object\") return undefined;\n    current = (current as Record<string, unknown>)[seg];\n  }\n  return current;\n}\n","import type { NiceError } from \"@nice-code/error\";\nimport { unrefTimer } from \"@nice-code/util\";\nimport { createMemoryReliableLogStore, type IReliableLogStore, ReliableLog } from \"@nice-code/wire\";\nimport { applyPatches, enablePatches, type Patch, produceWithPatches } from \"immer\";\nimport { pack } from \"msgpackr\";\nimport type { IRealmDefinition } from \"../RealmDefinition/defineRealm\";\nimport { err_realm } from \"../RealmDefinition/errors/err_realm\";\nimport {\n  evalAlterCond,\n  type IServerRuleExtras,\n  viewSignatureKey,\n} from \"../RealmDefinition/Rules/evalRules\";\nimport type { IRealmAvatarRef, TRuleVerdict } from \"../RealmDefinition/Rules/rules.types\";\nimport {\n  schemaRootHasBounds,\n  validateBoundedPatches,\n  validateBoundedStateTree,\n} from \"../RealmDefinition/Schema/boundedState\";\nimport { validateValue } from \"../RealmDefinition/Schema/validateValue\";\nimport { RealmKeyDict } from \"../RealmWire/keyDict\";\nimport type {\n  IRealmFrameIntent,\n  IRealmFrameWrite,\n  TRealmFrame,\n} from \"../RealmWire/realmFrame.types\";\nimport { REALM_FEATURE, REALM_FRAME_KIND } from \"../RealmWire/realmFrame.types\";\nimport {\n  encodeAck,\n  encodeBatch,\n  encodeDetach,\n  encodeHydrate,\n  encodeKeyDict,\n  encodePatches,\n  encodeReject,\n} from \"../RealmWire/realmFrameCodec\";\nimport { isUnsafeKey, pathHasUnsafeKey, valueHasUnsafeKey } from \"../RealmWire/unsafeKey\";\nimport {\n  canonicalizeStatePatches,\n  conflateOps,\n  namePatchesToWireOps,\n  schemaNodeAtPath,\n  wireOpsToNamePatches,\n} from \"../RealmWire/wirePatch\";\nimport { ExpansionOverflowError, expandWriteToLeaves } from \"./expandWrite\";\nimport {\n  type IViewSliceContext,\n  slicePatchForAvatar,\n  sliceStateForAvatar,\n  sliceTransientRefreshForAvatar,\n} from \"./viewSlice\";\n\n// The engine drives immer patches directly (nice-state's Store does the same on the avatar).\nenablePatches();\n\n/**\n * The authoritative realm server engine — host-agnostic: it never sees a socket, only\n * per-connection `send` callbacks the host adapter supplies. One engine = one live **instance**\n * of a realm definition; genesis runs in the constructor, exactly once.\n *\n * Pipelines: an avatar `write` runs limits → path decode → schema value validation →\n * subtree expansion → per-leaf alter rules (whole frame atomic) → commit; an `intent` runs allow →\n * input validation → atomic `apply` draft → commit. Both share the commit tail: version++ → log\n * append → per-view-signature slicing (encode once per signature group) → broadcast → ack to the\n * sender **after** its own patches frame (read-your-writes on settle, the protocol contract).\n */\n\nexport interface IRealmLimits {\n  /** Max patch ops in one write frame. */\n  maxPatchesPerFrame: number;\n  /** Max encoded bytes of one inbound realm frame (checked when the host reports a size). */\n  maxFrameBytes: number;\n  /** Max dynamic record-key length (also protects the intern dictionary). */\n  maxRecordKeyLength: number;\n  /** Max leaves one subtree write may expand to. */\n  maxExpandedLeaves: number;\n  /** Write/intent token-bucket rate per connection. */\n  writeRatePerSecond: number;\n  writeRateBurst: number;\n  /** Limit breaches on one connection before it is forcibly detached. */\n  maxBreachesBeforeDetach: number;\n}\n\nexport const DEFAULT_REALM_LIMITS: IRealmLimits = {\n  maxPatchesPerFrame: 64,\n  maxFrameBytes: 64 * 1024,\n  maxRecordKeyLength: 128,\n  maxExpandedLeaves: 256,\n  writeRatePerSecond: 100,\n  writeRateBurst: 200,\n  maxBreachesBeforeDetach: 10,\n};\n\nexport interface IRealmInstanceInfo {\n  instanceId: string;\n}\n\n/** How an `onAvatarDetach` fired — see the option's doc. */\nexport interface IRealmDetachDetail {\n  via: \"immediate\" | \"grace-expired\";\n  /** `grace-expired` only: ms between the last connection's drop and the hook firing. */\n  deferredMs?: number;\n}\n\n/** One parked detach — exposed so a host can persist it across evictions. */\nexport interface IRealmPendingDetach<TAvatarType extends string = string> {\n  avatar: IRealmAvatarRef<TAvatarType>;\n  reason: string;\n  /** When the last connection dropped (drives `deferredMs`). */\n  since: number;\n  /** When the grace window elapses and the detach fires. */\n  fireAt: number;\n}\n\nexport type TRealmMutationSource = \"write\" | \"intent\" | \"server\";\n\nexport interface IRealmServerEngineOptions<TState extends object, TCtx> {\n  /** Server-only context (secrets live here — never in the realm definition). */\n  ctx?: TCtx;\n  instanceId?: string;\n  /** Genesis: runs exactly once per instance, before the first attach. */\n  initialState: TState | ((info: IRealmInstanceInfo) => TState);\n  /**\n   * A avatar's first live connection attached. **Dispatch is deferred a microtask**: by the time it\n   * runs, the attach — including the hydrate/replay send — has completed,\n   * so the hook may freely call `engine.update()` (no re-entrancy wrapper needed; the resulting\n   * commit reaches the new avatar as an ordinary patches frame). Attach can re-fire for\n   * hibernation survivors without a paired detach — keep it idempotent.\n   */\n  onAvatarAttach?: (avatar: IRealmAvatarRef, ctx: TCtx) => void;\n  /**\n   * A avatar's last connection dropped. Deferred like {@link onAvatarAttach}.\n   * `detail` says how it fired: `\"immediate\"` (no grace / bypassed — e.g. a revocation) or\n   * `\"grace-expired\"` (the {@link avatarDetachGraceMs} window elapsed with no re-attach, with\n   * `deferredMs` = how long after the drop it fired).\n   */\n  onAvatarDetach?: (\n    avatar: IRealmAvatarRef,\n    reason: string,\n    ctx: TCtx,\n    detail?: IRealmDetachDetail,\n  ) => void;\n  /**\n   * Fire {@link onAvatarDetach} only if the avatar hasn't re-attached within this window\n   * (default `0` = immediate, today's behavior) — the presence-flap fix:\n   * with transport auto-redial a blip heals in ~1–2 s, and every roster/turn/ready consumer\n   * otherwise hand-rolls this debounce (unsafely, in a DO — a raw `setTimeout` is not\n   * hibernation-safe). A re-attach inside the window swallows BOTH hooks — no detach, no attach:\n   * the avatar never left (the timed twin of the probe/wake reattach swap, the reconnect contract).\n   *\n   * Scheduling: with {@link onDetachScheduleChanged} unset the engine self-schedules on an\n   * unref'd `setTimeout` (right for plain hosts; NOT hibernation-safe). The Cloudflare DO host\n   * (`createRealmHost`) provides the callback and backs the deadline with the DO alarm\n   * mux + persisted pending rows, so the deferred detach fires even across an eviction.\n   * `detachAvatar` (revocation) always bypasses the grace.\n   */\n  avatarDetachGraceMs?: number;\n  /**\n   * The host-scheduling seam for {@link avatarDetachGraceMs}: called whenever the pending-detach\n   * set changes (armed, swallowed by a re-attach, fired, restored). The host reads\n   * {@link RealmServerEngine.pendingDetaches} / {@link RealmServerEngine.nextDetachDeadline},\n   * persists/arms its own timer (the DO alarm mux), and calls\n   * {@link RealmServerEngine.fireExpiredDetaches} when it elapses. Providing this disables the\n   * engine's own `setTimeout` fallback.\n   */\n  onDetachScheduleChanged?: () => void;\n  /**\n   * Server-side mutation hook — fires **synchronously** after every commit with the canonical\n   * patches. **Observe-only**: it runs post-commit, so calling `engine.update()`\n   * from it is unbounded recursion, not re-entrancy — persist/report/throttle here (the DO\n   * host's snapshot cadence rides it), never write.\n   */\n  onMutation?: (\n    patches: readonly Patch[],\n    meta: { version: number; source: TRealmMutationSource; avatar?: IRealmAvatarRef },\n  ) => void;\n  /**\n   * Diagnostic hook: fired synchronously when a `write` passes schema + rules but cannot\n   * APPLY — its target's parent is gone (a pruned entry, or a transient region reset by a wake since\n   * the write's basis) — and is rejected `write_target_missing`. `liveConnections` is the writer\n   * avatar's current attached-socket count (a divergence under a live writer is the interesting\n   * case); a caller that also logs whether the write's transient root is wholly empty vs. partly\n   * populated can discriminate a *region reset* from a single-*entry prune* in production. Observe-only.\n   */\n  onWriteTargetMissing?: (detail: {\n    avatar: IRealmAvatarRef;\n    connKey: string;\n    path: string;\n    liveConnections: number;\n  }) => void;\n  limits?: Partial<IRealmLimits>;\n  /**\n   * Persist the replay high-water across a hibernation wake. Called\n   * whenever a connection's high-water advances (once per accepted `write`/`intent`), with the\n   * **client-handle** identity — `(avatar, slot)` — so a same-socket wake restores the same\n   * sequence. The host keys durable storage by `(realmId, avatar.persistentId, avatar.instanceId,\n   * slot)`; `instanceId` is fresh-per-boot ([RuntimeCoordinate] reliable-delivery contract), so a\n   * rebooted client (new `instanceId`) never restores a stale predecessor's high-water. Omit for\n   * in-memory-only realms (the guard still holds within a live session and across reconnects).\n   */\n  persistSeqHighWater?: (avatar: IRealmAvatarRef, slot: number, highWater: number) => void;\n  /**\n   * The wake-safe counterpart to {@link persistSeqHighWater}: on attach, return the persisted\n   * high-water for this `(avatar, slot)` client handle (or `undefined` if none). Only consulted for\n   * a `connKey` the engine has no live high-water for — a re-hello keeps its in-memory value; a\n   * post-wake attach (new `connKey`, lost in-memory map) restores from here.\n   */\n  restoreSeqHighWater?: (avatar: IRealmAvatarRef, slot: number) => number | undefined;\n  /** Patch-log store (default in-memory; a DO backs this with SQLite at M6). */\n  logStore?: IReliableLogStore;\n  /** Versions kept replayable behind the head (older reconnects fall back to full hydrate). */\n  logWindow?: number;\n  /** Clock for the rate bucket (injectable for tests; never visible to rules). */\n  now?: () => number;\n  /**\n   * Broadcast-coalescing window in ms. `undefined`/`0` (default)\n   * keeps the per-commit broadcast — every commit fans out immediately, today's exact behavior. When\n   * set, commits accumulate for up to this long and flush as ONE conflated `patches` frame per\n   * connection, so each client's inbound is bounded by `1/broadcastCoalesceMs` regardless of how many\n   * peers are writing (the fix for the participant-count amplification). The trade: a write's ack —\n   * and thus `await handle` — settles up to one window later (read-your-writes still holds; the ack\n   * rides the same flush, after its patches). Right for presence/cursor realms; leave off for a realm\n   * that wants the lowest possible settle latency.\n   */\n  broadcastCoalesceMs?: number;\n  /**\n   * Schedule the broadcast-window flush (injectable for deterministic tests — the twin of {@link now}\n   * for {@link broadcastCoalesceMs}). Returns a cancel function. Defaults to `setTimeout` (unref'd, so\n   * a pending window never keeps a process alive). Tests pass a scheduler that captures the callback\n   * and fire it via {@link RealmServerEngine.flushBroadcasts} to avoid real timers.\n   */\n  scheduleBroadcast?: (flush: () => void, ms: number) => () => void;\n  /**\n   * Boot from persisted state instead of genesis — the M6 cold-start path (snapshot + log-tail\n   * replay, assembled by the platform host). `initialState` is ignored when present. `epoch`\n   * carries the persisted log epoch; when absent (pre-epoch snapshot, or a\n   * migration — its history is new) the engine mints a fresh one, which is the safe direction:\n   * clients holding the old epoch full-hydrate instead of replaying a foreign history.\n   */\n  restore?: { state: TState; version: number; epoch?: string };\n  /**\n   * Hydrate frames whose state blob exceeds this split into chunks (`more` continuation flag,\n   * the protocol contract — Workers ws messages cap at 1 MiB). Default 900 KiB.\n   */\n  hydrateChunkBytes?: number;\n}\n\n/** Directional totals for one side of the engine's traffic. */\nexport interface IRealmEngineTrafficCounters {\n  /** Inbound decoded frames (writes/intents/caps/detach) and their byte sizes when the host knew them. */\n  ingressFrames: number;\n  ingressBytes: number;\n  /**\n   * Outbound **WS messages** — the unit platforms bill per-message (one `_transmit` raw send).\n   * With batch-envelope coalescing, several frames ride one message.\n   */\n  egressMessages: number;\n  /** Outbound realm frames (pre-coalescing) — `egressFrames / egressMessages` = the coalesce win. */\n  egressFrames: number;\n  egressBytes: number;\n}\n\n/** The engine's traffic snapshot — plain data, no devtools dependency. */\nexport interface IRealmEngineTrafficSnapshot extends IRealmEngineTrafficCounters {\n  sinceMs: number;\n  /** Frames per WS message (≥ 1); how much the batch envelope + broadcast tick actually saved. */\n  egressCoalesceRatio: number;\n  /**\n   * Live connections' own counters (a detached connection's counts remain in the totals), each\n   * tagged with the participant behind it (`avatarType`/`avatarId` — the avatar's `type` and\n   * `persistentId`) so a live-deployment view can name which client it is, not just its connection key.\n   */\n  connections: ({\n    connKey: string;\n    avatarType: string;\n    avatarId: string;\n  } & IRealmEngineTrafficCounters)[];\n}\n\n/**\n * One observed frame/message on the server wire (structurally an `ITrafficSample`, but declared here\n * so the engine stays devtools-agnostic). `bytes` is the ingress frame length / the raw egress WS\n * message length; `lane` is always `\"realm\"`; `linkId` is the connection key for per-connection stats.\n * Consumed by `serverWireTrafficScope` to feed a devtools traffic core — the server-side wire-tap that\n * mirrors the client's, so a backend's sidebar traffic panel is as live as a frontend's.\n */\nexport interface IRealmEngineTrafficSample {\n  atMs: number;\n  dir: \"in\" | \"out\";\n  bytes: number;\n  lane: string;\n  linkId?: string;\n}\n\nfunction newTrafficCounters(): IRealmEngineTrafficCounters {\n  return { ingressFrames: 0, ingressBytes: 0, egressMessages: 0, egressFrames: 0, egressBytes: 0 };\n}\n\ninterface IEngineConnection<TAvatarType extends string = string> {\n  key: string;\n  avatar: IRealmAvatarRef<TAvatarType>;\n  slot: number;\n  send: (bytes: Uint8Array) => void;\n  /** Per-connection traffic counters. */\n  traffic: IRealmEngineTrafficCounters;\n  /** Interned key ids already sent to this connection (keyDict deltas). */\n  sentKeyIds: Set<number>;\n  bucket: { tokens: number; last: number; breaches: number };\n  /**\n   * Egress features this connection advertised via `clientCaps` (the protocol contract Phase\n   * 1) — empty until its first `clientCaps` frame lands. Phase 2 reads {@link REALM_FEATURE.batch}\n   * here to decide whether an over-one-frame flush may ride a `batch` envelope.\n   */\n  features: Set<string>;\n  /**\n   * The egress outbox (Phase 2): frames accumulated during one engine entry point, flushed as one\n   * WS message per connection at the end of that entry point (a `batch` when >1 and the connection\n   * advertised {@link REALM_FEATURE.batch}, else bare sequential sends). Reference-swapped for `[]`\n   * at flush so a synchronous re-entrant enqueue lands in the next generation, not this one.\n   */\n  outbox: Uint8Array[];\n}\n\ninterface ILoggedOp {\n  op: Patch[\"op\"];\n  path: string[];\n  value?: unknown;\n}\n\nconst DEFAULT_LOG_WINDOW = 512;\n\nfunction clientKey(avatar: IRealmAvatarRef): string {\n  return `${avatar.type} ${avatar.persistentId}`;\n}\n\n/**\n * Mint a log epoch: a random id identifying one history of one realm instance.\n * Uniqueness only needs to hold across *rebuilds of the same realm* (wiped storage, re-created\n * DO, migration) — collision means a stale avatar silently replays a foreign diff, so time +\n * randomness is plenty. Platform-clean on purpose (no `crypto` dependency).\n */\nfunction mintEpoch(): string {\n  return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n}\n\nexport class RealmServerEngine<\n  TState extends object = object,\n  TAvatarType extends string = string,\n  TCtx = unknown,\n> {\n  private readonly _realm: IRealmDefinition<TState, TAvatarType, TCtx, any, any>;\n  private readonly _ctx: TCtx;\n  private readonly _limits: IRealmLimits;\n  private readonly _now: () => number;\n  private readonly _instanceId: string;\n\n  private _state: TState;\n  /** Whether the schema declares any bounds — false skips every bounded-state walk. */\n  private readonly _hasBounds: boolean;\n  private _version = 0;\n  private _mutating = false;\n  /** The log epoch: identifies this history — replay requires an exact match. */\n  private readonly _epoch: string;\n\n  private readonly _log: ReliableLog<ILoggedOp[]>;\n  private readonly _logWindow: number;\n  /** Recent write touches for `touchedSince` CAS — bounded by the log window. */\n  private _touches: { path: string[]; version: number }[] = [];\n\n  private readonly _dict = new RealmKeyDict();\n  private readonly _connections = new Map<string, IEngineConnection<TAvatarType>>();\n  private readonly _avatarConnCounts = new Map<string, number>();\n  /**\n   * Connections with queued egress (Phase 2). Holds the record even after `detachConnection` removes\n   * it from `_connections`, so a detach notice / breach reject already queued still flushes. Insertion\n   * order = flush order (Set preserves it).\n   */\n  private readonly _dirtyConns = new Set<IEngineConnection<TAvatarType>>();\n  /** Re-entrancy guard: a raw send can synchronously re-enter an entry point on an in-memory link\n   * (a resend), whose own flush must be a no-op — the owning drain loop picks up the new frames. */\n  private _flushing = false;\n\n  /** Server wire-tap listeners (devtools). Empty in production, so the emit is a hot-path no-op. */\n  private readonly _trafficListeners = new Set<(sample: IRealmEngineTrafficSample) => void>();\n\n  // ── Broadcast tick (Phase 4) — inert when `_broadcastCoalesceMs === 0` ──────\n  private readonly _broadcastCoalesceMs: number;\n  private readonly _scheduleBroadcast: (flush: () => void, ms: number) => () => void;\n  /** Canonical name-patches accumulated across the open window's commits (conflated at flush). */\n  private _windowOps: Patch[] = [];\n  /** The `statePrev` of the window's FIRST commit — the slicing basis for its `remove`s (V1). */\n  private _windowStartState: TState | undefined;\n  /** The version the open window began from — the flushed frame's `fromVersion`. */\n  private _windowFromVersion = 0;\n  /** Cancel handle for the armed window timer (undefined = disarmed / no open window). */\n  private _windowTimerCancel: (() => void) | undefined;\n  /**\n   * Acks deferred into the current window (P3): a successful write/intent's ack must reach the client\n   * AFTER that window's patches frame, so it rides the window flush — never the immediate outbox (which\n   * empties at the end of `receiveFrame`, ahead of the patches). Dropped for a connection that detaches\n   * mid-window.\n   */\n  private _pendingAcks: {\n    conn: IEngineConnection<TAvatarType>;\n    clientSeq: number;\n    version: number;\n  }[] = [];\n  /**\n   * Replay/duplicate high-water per connection **key** — the highest\n   * `clientSeq` accepted for processing on a `connKey`. Kept **outside** the `IEngineConnection`\n   * record on purpose: a same-avatar re-hello swaps the conn record in place (`attach()`'s\n   * reattach path, the reconnect contract — it no longer detaches at all), so a per-record counter would reset\n   * to `-1` and a replayed `hello` could reopen the window (Fact B). This map survives the\n   * re-attach trivially; `detachConnection` clears it on a *real* close. Phase 3b persists this\n   * across a hibernation wake (Fact C).\n   */\n  private readonly _seqHighWater = new Map<string, number>();\n\n  // ── Detach grace ────────────────────────────────────\n  private readonly _detachGraceMs: number;\n  /** Parked last-connection detaches, keyed by `clientKey` — a re-attach swallows its entry. */\n  private readonly _pendingDetaches = new Map<string, IRealmPendingDetach<TAvatarType>>();\n  /** The self-scheduling fallback timer (plain hosts — a host seam replaces it entirely). */\n  private _detachTimer: ReturnType<typeof setTimeout> | undefined;\n\n  // ── Traffic counters — see {@link getTrafficSnapshot} ───\n  private readonly _traffic: IRealmEngineTrafficCounters = newTrafficCounters();\n  private readonly _trafficSinceMs = Date.now();\n\n  private readonly _options: IRealmServerEngineOptions<TState, TCtx>;\n\n  constructor(\n    realm: IRealmDefinition<TState, TAvatarType, TCtx, any, any>,\n    options: IRealmServerEngineOptions<TState, TCtx>,\n  ) {\n    this._realm = realm;\n    this._options = options;\n    this._ctx = options.ctx as TCtx;\n    this._limits = { ...DEFAULT_REALM_LIMITS, ...options.limits };\n    this._now = options.now ?? (() => Date.now());\n    this._detachGraceMs = options.avatarDetachGraceMs ?? 0;\n    this._broadcastCoalesceMs = options.broadcastCoalesceMs ?? 0;\n    this._scheduleBroadcast =\n      options.scheduleBroadcast ??\n      ((flush, ms) => {\n        const handle = setTimeout(flush, ms);\n        unrefTimer(handle);\n        return () => clearTimeout(handle);\n      });\n    this._instanceId = options.instanceId ?? \"default\";\n    this._logWindow = options.logWindow ?? DEFAULT_LOG_WINDOW;\n    this._log = new ReliableLog(options.logStore ?? createMemoryReliableLogStore(), {\n      keepDelivered: this._logWindow,\n    });\n    if (options.restore != null) {\n      // Cold start from persistence (M6): the host assembled snapshot + log tail; genesis skipped.\n      this._state = options.restore.state;\n      this._version = options.restore.version;\n      this._epoch = options.restore.epoch ?? mintEpoch();\n    } else {\n      this._state =\n        typeof options.initialState === \"function\"\n          ? (options.initialState as (info: IRealmInstanceInfo) => TState)({\n              instanceId: this._instanceId,\n            })\n          : options.initialState;\n      this._epoch = mintEpoch();\n    }\n\n    // Declared bounds gate every state the engine will ever hold authoritative — including this\n    // starting one (initial, restored snapshot+log, or migration output), before any client\n    // attaches. A boundless schema pays one memoized lookup here and nothing per commit.\n    this._hasBounds = schemaRootHasBounds(this._realm.stateDef);\n    if (this._hasBounds) {\n      const invalid = validateBoundedStateTree(\n        this._realm.stateDef,\n        this._state as Record<string, unknown>,\n      );\n      if (invalid != null) {\n        throw err_realm.fromId(\"value_invalid\", {\n          path: invalid.path.join(\".\"),\n          expected: invalid.expected,\n        });\n      }\n    }\n  }\n\n  get state(): Readonly<TState> {\n    return this._state;\n  }\n\n  get version(): number {\n    return this._version;\n  }\n\n  get instanceId(): string {\n    return this._instanceId;\n  }\n\n  /** The log epoch — minted at genesis/migrate, persisted by the platform host. */\n  get epoch(): string {\n    return this._epoch;\n  }\n\n  get realmId(): string {\n    return this._realm.id;\n  }\n\n  get avatarTypes(): readonly TAvatarType[] {\n    return this._realm.avatarTypes;\n  }\n\n  // ── Attach / detach ────────────────────────────────────────────\n\n  /**\n   * Attach an authenticated avatar connection to this engine. Verifies the schema hash, sends\n   * the initial `hydrate` (or a patch replay when `lastKnownVersion` is inside the log window),\n   * and fires `onAvatarAttach` on an avatar's first live connection. Returns `false` (after a\n   * `reject` with `clientSeq -1`, the attach-failure sentinel) when the hash mismatches.\n   *\n   * Calling it for a `connKey` that is already attached with the **same avatar** is a\n   * **re-attach** (staleness probe / wake rehello): the connection record is swapped in place —\n   * fresh `sentKeyIds`/`features`, preserved rate bucket, migrated window acks — and the avatar\n   * lifecycle hooks do NOT fire. A different avatar on the\n   * same `connKey` first runs the old avatar's full detach bookkeeping.\n   */\n  attach(\n    connKey: string,\n    options: {\n      avatar: IRealmAvatarRef<TAvatarType>;\n      slot: number;\n      schemaHash: string;\n      lastKnownVersion: number;\n      /** The epoch the avatar's `lastKnownVersion` belongs to (from its hello — the epoch contract). */\n      epoch?: string;\n      send: (bytes: Uint8Array) => void;\n    },\n  ): boolean {\n    const { avatar, slot, send } = options;\n    if (options.schemaHash !== this._realm.schemaHash) {\n      send(\n        encodeReject({\n          slot,\n          clientSeq: -1,\n          error: err_realm\n            .fromId(\"schema_mismatch\", {\n              realmId: this._realm.id,\n              clientHash: options.schemaHash,\n              serverHash: this._realm.schemaHash,\n            })\n            .toWireJsonObject() as unknown as Record<string, unknown>,\n        }),\n      );\n      return false;\n    }\n\n    // Flush any open broadcast window to the EXISTING connections before this newcomer joins the map\n    // (P4/P2): otherwise it would receive both the window frame and its own fresh hydrate/replay. This\n    // enqueues only (the send rides this attach's own `_flushEgress`); a per-commit realm has no\n    // window and this is a no-op.\n    this._flushWindow();\n\n    // Same-avatar re-hello on a live connKey (the staleness probe, a wake \"rehello\", an\n    // unknown-slot heal) — swap the connection record in place WITHOUT the avatar lifecycle\n    //: the avatar never left, so `onAvatarDetach`/`onAvatarAttach` must not\n    // fire (a prune-on-detach app would delete live player state on every idle probe). A\n    // same-connKey hello that resolves a DIFFERENT avatar (re-auth on a live socket) is a\n    // genuine departure of the old avatar — run its full detach bookkeeping first.\n    const existing = this._connections.get(connKey);\n    const reattachFrom =\n      existing != null && clientKey(existing.avatar) === clientKey(avatar) ? existing : undefined;\n    if (existing != null && reattachFrom == null) {\n      this.detachConnection(connKey, \"identity-changed\", false, false);\n    }\n\n    const conn: IEngineConnection<TAvatarType> = {\n      key: connKey,\n      avatar,\n      slot,\n      send, // always take the newest send closure\n      // ALWAYS reset, reattach included: the client may have cleared its key dict on this hello,\n      // and re-sent deltas are harmless (`RealmKeyDict.load` overwrites) — the skew contract that\n      // keeps old clients working.\n      sentKeyIds: new Set(),\n      // A re-hello must not refill the rate bucket (hello spam would bypass writeRatePerSecond).\n      bucket: reattachFrom?.bucket ?? {\n        tokens: this._limits.writeRateBurst,\n        last: this._now(),\n        breaches: 0,\n      },\n      // Re-attach on the same connKey (re-hello) starts with no advertised features until the\n      // client's post-hello `clientCaps` re-lands — the client re-sends it after every hello.\n      features: new Set(),\n      outbox: [],\n      // A re-hello keeps the connection's traffic counters (same socket, same billing unit).\n      traffic: reattachFrom?.traffic ?? newTrafficCounters(),\n    };\n    this._connections.set(connKey, conn);\n\n    if (reattachFrom != null) {\n      // F2 guard: an avatar re-helloing on a LIVE connection (a staleness probe, a\n      // wake rehello) is demonstrably still here — cancel any parked detach for it, the timed twin\n      // of the new-connection grace swallow below. Without this, a detach parked by a wake-loop\n      // misread or a restored row that races a live re-hello would fire its prune under the\n      // attached avatar (the roster flap grace exists to prevent).\n      if (this._pendingDetaches.delete(clientKey(avatar))) this._detachScheduleChanged();\n      // Migrate window-deferred acks (P3) to the new record — they are keyed by object identity,\n      // and dropping them would falsely expire the client's already-accepted writes (F3).\n      for (const pendingAck of this._pendingAcks) {\n        if (pendingAck.conn === reattachFrom) pendingAck.conn = conn;\n      }\n      // Migrate any already-queued egress so nothing enqueued before the swap is orphaned.\n      if (this._dirtyConns.delete(reattachFrom)) {\n        conn.outbox = reattachFrom.outbox;\n        this._dirtyConns.add(conn);\n      }\n    }\n\n    // Replay high-water lifecycle: `_seqHighWater` (keyed by connKey) survives\n    // a re-hello's detach on the same connKey (Fact B). A **post-wake** attach is a new connKey with\n    // the in-memory map lost (eviction) — so when this connKey has no live entry, restore the\n    // persisted high-water for this client handle (Fact C). The has-guard means a re-hello keeps its\n    // (higher-or-equal) in-memory value rather than reloading a possibly-lagging persisted one.\n    if (!this._seqHighWater.has(connKey)) {\n      const persisted = this._options.restoreSeqHighWater?.(avatar, slot);\n      if (persisted != null) this._seqHighWater.set(connKey, persisted);\n    }\n\n    if (reattachFrom == null) {\n      const ck = clientKey(avatar);\n      const count = this._avatarConnCounts.get(ck) ?? 0;\n      this._avatarConnCounts.set(ck, count + 1);\n      if (count === 0) {\n        const pendingDetach = this._pendingDetaches.get(ck);\n        if (pendingDetach != null) {\n          // Grace re-attach: the avatar came back inside its\n          // `avatarDetachGraceMs` window — swallow BOTH hooks (no detach fired, no attach fires):\n          // the avatar never left. The timed twin of the F3 reattach swap above.\n          this._pendingDetaches.delete(ck);\n          this._detachScheduleChanged();\n        } else {\n          // Deferred dispatch: the hook runs after this attach (hydrate included)\n          // completes, so it may freely `engine.update()` — see the option's contract.\n          queueMicrotask(() => this._options.onAvatarAttach?.(avatar, this._ctx));\n        }\n      }\n    }\n\n    // Resume: replay the missed patches when the avatar's basis is inside the log window — and\n    // belongs to THIS history: an epoch mismatch (wiped storage, re-created realm,\n    // migration) means the version numbers count a different past, so replaying would silently\n    // diverge; full hydrate instead.\n    if (\n      options.lastKnownVersion >= 0 &&\n      options.lastKnownVersion <= this._version &&\n      options.epoch === this._epoch\n    ) {\n      const replay = this._buildReplayOps(options.lastKnownVersion);\n      if (replay != null) {\n        const sliced: Patch[] = [];\n        for (const patch of replay) {\n          // A transient-region refresh (`replace <root> = <regionValue>`, appended last by\n          // `_buildReplayOps`) is an ABSOLUTE, authoritative whole-region statement — it must reach\n          // the avatar even when the sliced value is empty, so a wake-wiped region converges to `{}`\n          // client-side and the avatar learns its own entry is gone. The general slicer would drop an\n          // empty/fully-pruned record; `sliceTransientRefreshForAvatar` always emits it (the Overshot\n          // stranded-write_target_missing fix).\n          if (patch.op === \"replace\" && this._isTransientRoot(patch.path as string[])) {\n            sliced.push(sliceTransientRefreshForAvatar(this._sliceCtx(avatar), patch));\n            continue;\n          }\n          const slicedPatch = slicePatchForAvatar(\n            this._sliceCtx(avatar),\n            patch,\n            undefined,\n            this._state,\n          );\n          if (slicedPatch != null) sliced.push(slicedPatch);\n        }\n        this._sendPatchesFrame(conn, sliced, options.lastKnownVersion, this._version);\n        this._flushEgress();\n        return true;\n      }\n    }\n\n    // Full hydrate: the avatar's sliced snapshot, chunked above the host's frame ceiling\n    //.\n    const slice = sliceStateForAvatar(this._sliceCtx(avatar), this._state);\n    const blob = pack(slice);\n    const chunkBytes = this._options.hydrateChunkBytes ?? 900 * 1024;\n    for (let offset = 0; offset === 0 || offset < blob.byteLength; offset += chunkBytes) {\n      const end = Math.min(offset + chunkBytes, blob.byteLength);\n      this._enqueue(\n        conn,\n        encodeHydrate({\n          slot,\n          version: this._version,\n          stateBlob: blob.subarray(offset, end),\n          keyDictSeed: [],\n          more: end < blob.byteLength,\n          epoch: this._epoch,\n          // The avatar-relevant ingress limits — the coalescer splits against them.\n          limits: [\n            this._limits.maxPatchesPerFrame,\n            this._limits.maxFrameBytes,\n            this._limits.writeRatePerSecond,\n          ],\n          // The resolved identity echo — who verdicts/slicing run against.\n          avatar: [avatar.type, avatar.persistentId, avatar.instanceId],\n        }),\n      );\n    }\n    this._flushEgress();\n    return true;\n  }\n\n  /**\n   * Detach one connection (socket closed / avatar left the realm / forced). Every real close\n   * clears the replay high-water (the `connKey` is never reused — the acceptor mints a fresh one\n   * per socket — so this is pure cleanup, not correctness). `preserveReplayHighWater` is retained\n   * for compatibility but no longer has an internal caller: a same-realm re-hello no longer\n   * detaches at all — `attach()` swaps the connection record in place without firing the avatar\n   * lifecycle, and the high-water survives trivially.\n   */\n  detachConnection(\n    connKey: string,\n    reason = \"detached\",\n    notifyPeer = false,\n    preserveReplayHighWater = false,\n    /** A revocation-class detach ignores `avatarDetachGraceMs` — it is not a blip. */\n    bypassGrace = false,\n  ): void {\n    const conn = this._connections.get(connKey);\n    if (conn == null) return;\n    this._connections.delete(connKey);\n    if (!preserveReplayHighWater) this._seqHighWater.delete(connKey);\n    // Drop any window-deferred acks for this connection (Phase 4) — the socket is gone.\n    if (this._pendingAcks.length > 0) {\n      this._pendingAcks = this._pendingAcks.filter((pending) => pending.conn !== conn);\n    }\n    if (notifyPeer) {\n      // Enqueue the notice, then flush this connection's whole outbox — a breach-detach already\n      // queued the `limits_exceeded` reject, and read-your-order requires reject-before-detach\n      // (F4). The conn is already out of `_connections` (unroutable) but still in `_dirtyConns`, so\n      // the drain sends it before we lose the record.\n      this._enqueue(conn, encodeDetach({ slot: conn.slot, reason }));\n    }\n    this._flushEgress();\n    const ck = clientKey(conn.avatar);\n    const count = this._avatarConnCounts.get(ck) ?? 0;\n    if (count <= 1) {\n      this._avatarConnCounts.delete(ck);\n      // Per-avatar detach fires when the *last* connection drops (multi-socket, the protocol contract) —\n      // parked for `avatarDetachGraceMs` first when configured.\n      this._deferOrFireDetach(conn.avatar, reason, bypassGrace);\n    } else {\n      this._avatarConnCounts.set(ck, count - 1);\n    }\n  }\n\n  /** Forced detach / revocation: drop every connection of a persistent avatar. */\n  detachAvatar(persistentId: string, reason = \"revoked\"): void {\n    for (const conn of [...this._connections.values()]) {\n      if (conn.avatar.persistentId === persistentId) {\n        // A revocation is not a blip — it bypasses any detach grace and fires immediately.\n        this.detachConnection(conn.key, reason, true, false, true);\n      }\n    }\n    // An already-disconnected avatar parked in its grace window is revoked too: fire now.\n    for (const [ck, pending] of [...this._pendingDetaches]) {\n      if (pending.avatar.persistentId !== persistentId) continue;\n      this._pendingDetaches.delete(ck);\n      queueMicrotask(() =>\n        this._options.onAvatarDetach?.(pending.avatar, reason, this._ctx, { via: \"immediate\" }),\n      );\n      this._detachScheduleChanged();\n    }\n  }\n\n  // ── Detach grace ────────────────────────────────────\n\n  /**\n   * Park the per-avatar detach for the grace window (or fire it now with no/ bypassed grace) —\n   * the one funnel every last-connection departure goes through, `reportAvatarLost` included.\n   * Dispatch stays microtask-deferred so the hook may freely `engine.update()`.\n   */\n  private _deferOrFireDetach(\n    avatar: IRealmAvatarRef<TAvatarType>,\n    reason: string,\n    bypassGrace: boolean,\n  ): void {\n    if (!bypassGrace && this._detachGraceMs > 0) {\n      const ck = clientKey(avatar);\n      // A duplicate report (a wake-loss racing a close) keeps the EARLIER deadline.\n      if (!this._pendingDetaches.has(ck)) {\n        const now = this._now();\n        this._pendingDetaches.set(ck, {\n          avatar,\n          reason,\n          since: now,\n          fireAt: now + this._detachGraceMs,\n        });\n        this._detachScheduleChanged();\n      }\n      return;\n    }\n    queueMicrotask(() =>\n      this._options.onAvatarDetach?.(avatar, reason, this._ctx, { via: \"immediate\" }),\n    );\n  }\n\n  /**\n   * Report an avatar known to be gone with no live engine connection — the DO host's wake\n   * reconciliation (a socket that vanished while the DO hibernated). Runs the same\n   * `avatarDetachGraceMs` funnel an ordinary last-connection close gets, so a prompt reconnect\n   * after the wake swallows the detach instead of flapping presence.\n   */\n  reportAvatarLost(avatar: IRealmAvatarRef<TAvatarType>, reason = \"hibernation-lost\"): void {\n    // F1 guard: only report a loss for an avatar with NO live engine connection. The\n    // wake reconciliation classifies \"surviving\" by resolving avatars off the live sockets at\n    // wake-microtask time; a misread there (an unreadable attachment, a resolver that returns\n    // `undefined` for a live socket) must not park — and later fire — a detach under an avatar that\n    // is demonstrably still attached (the roster flap grace exists to prevent).\n    if ((this._avatarConnCounts.get(clientKey(avatar)) ?? 0) > 0) return;\n    this._deferOrFireDetach(avatar, reason, false);\n  }\n\n  /** The earliest pending grace deadline (epoch ms), or `undefined` — the host's alarm target. */\n  nextDetachDeadline(): number | undefined {\n    let next: number | undefined;\n    for (const pending of this._pendingDetaches.values()) {\n      if (next == null || pending.fireAt < next) next = pending.fireAt;\n    }\n    return next;\n  }\n\n  /** The parked detaches — a durable host persists these so they survive an eviction. */\n  pendingDetaches(): readonly IRealmPendingDetach<TAvatarType>[] {\n    return [...this._pendingDetaches.values()];\n  }\n\n  /**\n   * Re-park persisted pending detaches after a wake (the durable host's boot path). Entries whose\n   * avatar re-attaches (the wake rehello) are swallowed as usual; the rest fire when the host's\n   * alarm calls {@link fireExpiredDetaches}. Keeps the earlier deadline on a key collision.\n   */\n  restorePendingDetaches(rows: readonly IRealmPendingDetach<TAvatarType>[]): void {\n    for (const row of rows) {\n      const ck = clientKey(row.avatar);\n      if (!this._pendingDetaches.has(ck)) this._pendingDetaches.set(ck, row);\n    }\n    if (rows.length > 0) this._detachScheduleChanged();\n  }\n\n  /**\n   * Fire (and clear) every pending detach whose grace window elapsed — called by the host's\n   * timer/alarm (or the engine's own fallback timer). Hooks fire with\n   * `{ via: \"grace-expired\", deferredMs }`, microtask-deferred like every lifecycle dispatch.\n   */\n  fireExpiredDetaches(now = this._now()): void {\n    let fired = false;\n    for (const [ck, pending] of [...this._pendingDetaches]) {\n      if (pending.fireAt > now) continue;\n      this._pendingDetaches.delete(ck);\n      fired = true;\n      const deferredMs = now - pending.since;\n      queueMicrotask(() =>\n        this._options.onAvatarDetach?.(pending.avatar, pending.reason, this._ctx, {\n          via: \"grace-expired\",\n          deferredMs,\n        }),\n      );\n    }\n    // ⚠ `fired ||` is not enough, and the difference is a stranded detach that never fires.\n    //\n    // The fallback timer clears its own handle (`_detachTimer = undefined`) BEFORE calling this.\n    // A wake with nothing yet due therefore used to return having both dropped the handle and\n    // skipped the re-arm, leaving a pending row with no timer behind it — presence that never\n    // clears, which is the exact flap `avatarDetachGraceMs` exists to prevent. And an early wake is\n    // not hypothetical: node timers may fire a hair before `Date.now()` reaches the deadline\n    // (millisecond rounding in libuv), so a 40 ms grace can wake at +39 and find `fireAt > now`.\n    // Re-arming whenever work remains makes the schedule self-healing under any clock skew; the\n    // retry lands ~1 ms later. A host that owns scheduling (the DO alarm mux) gets the same repair.\n    if (fired || this._pendingDetaches.size > 0) this._detachScheduleChanged();\n  }\n\n  /**\n   * The scheduling seam: hand the change to the host when it owns scheduling\n   * (`onDetachScheduleChanged`), else self-schedule with an unref'd timeout — correct for plain\n   * hosts; a DO host MUST own it (a raw timeout is not hibernation-safe).\n   */\n  private _detachScheduleChanged(): void {\n    if (this._options.onDetachScheduleChanged != null) {\n      this._options.onDetachScheduleChanged();\n      return;\n    }\n    if (this._detachTimer != null) {\n      clearTimeout(this._detachTimer);\n      this._detachTimer = undefined;\n    }\n    const next = this.nextDetachDeadline();\n    if (next == null) return;\n    const timer = setTimeout(\n      () => {\n        this._detachTimer = undefined;\n        this.fireExpiredDetaches();\n      },\n      Math.max(0, next - this._now()),\n    );\n    unrefTimer(timer);\n    this._detachTimer = timer;\n  }\n\n  /** Currently attached connection keys (host adapters / tests). */\n  get connectionCount(): number {\n    return this._connections.size;\n  }\n\n  /**\n   * The engine's traffic totals since construction: ingress frames/bytes,\n   * egress **messages** (the per-message billing unit) vs frames (pre-coalescing) and bytes.\n   * `egressCoalesceRatio` is the batch-envelope + broadcast-tick win made measurable — frames\n   * folded per WS message. Plain data; hosts expose it however they like (a dev-only debug\n   * action, or `realmEngineScope(engine, id)` plugged into a server devtools host, …).\n   * Hello/attach traffic is handled by the host adapter before the engine and is not counted here.\n   */\n  getTrafficSnapshot(): IRealmEngineTrafficSnapshot {\n    return {\n      ...this._traffic,\n      sinceMs: this._trafficSinceMs,\n      egressCoalesceRatio:\n        this._traffic.egressMessages > 0\n          ? this._traffic.egressFrames / this._traffic.egressMessages\n          : 1,\n      connections: [...this._connections.values()].map((conn) => ({\n        connKey: conn.key,\n        avatarType: conn.avatar.type,\n        avatarId: conn.avatar.persistentId,\n        ...conn.traffic,\n      })),\n    };\n  }\n\n  /**\n   * Subscribe to the server wire-tap: a per-frame `ITrafficSample`-shaped event for every ingress frame\n   * and egress WS message (with real byte lengths, on lane `\"realm\"`, tagged with the connection key).\n   * The devtools' `serverWireTrafficScope` feeds these into a traffic core so a backend's sidebar traffic\n   * panel is as live as a frontend's. No listeners ⇒ the emit below is a hot-path no-op, so this costs\n   * nothing in production. Returns an unsubscribe.\n   */\n  subscribeTraffic(listener: (sample: IRealmEngineTrafficSample) => void): () => void {\n    this._trafficListeners.add(listener);\n    return () => this._trafficListeners.delete(listener);\n  }\n\n  private _emitTraffic(dir: \"in\" | \"out\", bytes: number, connKey: string): void {\n    if (this._trafficListeners.size === 0) return;\n    const sample: IRealmEngineTrafficSample = {\n      atMs: this._now(),\n      dir,\n      bytes,\n      lane: \"realm\",\n      linkId: connKey,\n    };\n    for (const listener of this._trafficListeners) listener(sample);\n  }\n\n  /**\n   * The egress features a connection advertised via `clientCaps`\n   *, or `undefined` when the connKey is not attached. Phase 2\n   * consumes `REALM_FEATURE.batch` here to gate the `batch` envelope; exposed for hosts/tests.\n   */\n  connectionFeatures(connKey: string): ReadonlySet<string> | undefined {\n    return this._connections.get(connKey)?.features;\n  }\n\n  // ── Inbound frames ───────────────────────────────────────────────────────────\n\n  /**\n   * Feed one decoded inbound frame from an attached connection. `byteLength` (when the host\n   * knows it) drives the frame-size ingress limit.\n   */\n  receiveFrame(connKey: string, frame: TRealmFrame, byteLength?: number): void {\n    const conn = this._connections.get(connKey);\n    if (conn == null) return;\n    conn.traffic.ingressFrames += 1;\n    conn.traffic.ingressBytes += byteLength ?? 0;\n    this._traffic.ingressFrames += 1;\n    this._traffic.ingressBytes += byteLength ?? 0;\n    this._emitTraffic(\"in\", byteLength ?? 0, connKey);\n    switch (frame.kind) {\n      case REALM_FRAME_KIND.write:\n        this._handleWrite(conn, frame, byteLength);\n        break;\n      case REALM_FRAME_KIND.intent:\n        this._handleIntent(conn, frame, byteLength);\n        break;\n      case REALM_FRAME_KIND.clientCaps:\n        // Capability advertisement (Phase 1): record the connection's egress features. Replaces the\n        // set wholesale — a re-hello re-sends the full list, so the latest frame is authoritative.\n        conn.features = new Set(frame.features);\n        break;\n      case REALM_FRAME_KIND.detach:\n        this.detachConnection(connKey, frame.reason ?? \"avatar detached\");\n        break;\n      default:\n        // hello is handled by the adapter (attach); server-bound kinds end here.\n        break;\n    }\n    // One egress flush per inbound frame (Phase 2): everything this frame produced — the sender's\n    // patches + ack, a reject, a dup re-ack — leaves as one WS message per connection.\n    this._flushEgress();\n  }\n\n  // ── Server-authored mutations ────────────────────────────────────────────────\n\n  /**\n   * Mutate authoritative state from server code (`r.serverOnly` paths — game ticks, fulfilment;\n   * the protocol contract). Flows through the same version/log/slice tail, so server writes broadcast\n   * identically. Throws when called re-entrantly from an intent `apply` or a rule (single-writer\n   * invariant, the protocol contract).\n   */\n  update(fn: (draft: TState) => void): void {\n    this._guardReentrancy();\n    this._mutating = true;\n    let produced: readonly [TState, Patch[], Patch[]];\n    try {\n      produced = produceWithPatches(this._state, (draft) => {\n        fn(draft as TState);\n      });\n    } finally {\n      this._mutating = false;\n    }\n    const [nextState, patches] = produced;\n    if (patches.length === 0) return;\n    const canonical = canonicalizeStatePatches(patches, nextState, this._realm.stateDef);\n    // A server mutation breaking a declared bound is a server bug — thrown at the caller, before\n    // anything commits or broadcasts.\n    if (this._hasBounds) {\n      const bounded = validateBoundedPatches(\n        this._realm.stateDef,\n        nextState,\n        canonical.map((patch) => patch.path),\n      );\n      if (bounded != null) {\n        throw err_realm.fromId(\"value_invalid\", {\n          path: bounded.path.join(\".\"),\n          expected: bounded.expected,\n        });\n      }\n    }\n    this._commit(nextState, canonical, { source: \"server\" });\n    this._flushEgress(); // server-authored commit is an entry point too — flush its broadcast\n  }\n\n  // ── Write pipeline ───────────────────────────────────────────────\n\n  private _handleWrite(\n    conn: IEngineConnection<TAvatarType>,\n    frame: IRealmFrameWrite,\n    byteLength?: number,\n  ): void {\n    // Replay/dup guard first: before ingress, so a replay never drains the\n    // rate bucket or counts toward detach. A duplicate seq is re-acked inside `_passesSeq`.\n    if (!this._passesSeq(conn, frame.clientSeq)) return;\n    if (!this._passesIngress(conn, frame.clientSeq, byteLength, frame.ops.length)) return;\n    // Accepted past the seq + ingress gates → advance the high-water. AFTER ingress so a\n    // rate-limited frame the client legitimately retries with the same seq is not mistaken for a\n    // duplicate (a `limits_exceeded` retry re-presents its original seq — Fact A).\n    this._advanceSeqHighWater(conn, frame.clientSeq);\n\n    // Decode wire paths → name paths (unknown tokens / interned ids are malformed frames).\n    let namePatches: Patch[];\n    try {\n      namePatches = wireOpsToNamePatches(frame.ops, this._realm.tokens, (id) =>\n        this._dict.keyOf(id),\n      );\n    } catch (error) {\n      this._reject(\n        conn,\n        frame.clientSeq,\n        err_realm.fromId(\"frame_invalid\", {\n          reason: error instanceof Error ? error.message : \"bad wire path\",\n        }),\n      );\n      return;\n    }\n\n    const statePrev = this._state;\n    const extrasFor = (leafPath: string[]): IServerRuleExtras<TCtx> => ({\n      ctx: this._ctx,\n      touchedSince: (basisVersion) => this._touchedSince(leafPath, basisVersion),\n    });\n\n    for (const patch of namePatches) {\n      const path = patch.path as string[];\n\n      for (const seg of path) {\n        // Prototype-pollution deny-list (Phase 5): a dynamic record key that arrives as a path\n        // segment must never be `__proto__`/`constructor`/`prototype`. Hard reject — a malformed\n        // frame, not a rate breach.\n        if (isUnsafeKey(seg)) {\n          this._reject(\n            conn,\n            frame.clientSeq,\n            err_realm.fromId(\"frame_invalid\", { reason: \"unsafe record key\" }),\n          );\n          return;\n        }\n        // Record-key length limit (protects the intern dictionary).\n        if (typeof seg === \"string\" && seg.length > this._limits.maxRecordKeyLength) {\n          this._breach(conn, frame.clientSeq, \"maxRecordKeyLength\");\n          return;\n        }\n      }\n      // …and an unsafe key hidden *inside* a coarse subtree value (a whole-record `add`/`replace`\n      // carries its dynamic keys in the value, never the path). Same deny-list, value side.\n      if (patch.op !== \"remove\" && valueHasUnsafeKey(patch.value)) {\n        this._reject(\n          conn,\n          frame.clientSeq,\n          err_realm.fromId(\"frame_invalid\", { reason: \"unsafe record key\" }),\n        );\n        return;\n      }\n\n      const node = schemaNodeAtPath(this._realm.stateDef, path);\n      if (node == null) {\n        this._reject(\n          conn,\n          frame.clientSeq,\n          err_realm.fromId(\"value_invalid\", {\n            path: path.join(\".\"),\n            expected: \"a schema path\",\n          }),\n        );\n        return;\n      }\n\n      if (patch.op === \"remove\") {\n        // Removable = a record entry or an optional object key — anything else breaks the shape.\n        const parentNode =\n          path.length === 1 ? undefined : schemaNodeAtPath(this._realm.stateDef, path.slice(0, -1));\n        const parentKind = parentNode?.kind === \"optional\" ? \"optional\" : parentNode?.kind;\n        const removable = parentKind === \"record\" || node.kind === \"optional\";\n        if (!removable) {\n          this._reject(\n            conn,\n            frame.clientSeq,\n            err_realm.fromId(\"value_invalid\", {\n              path: path.join(\".\"),\n              expected: \"a removable path (record entry or optional key)\",\n            }),\n          );\n          return;\n        }\n      } else {\n        // Schema-validate the incoming value before any rule sees it (type-poisoning defense).\n        const invalid = validateValue(node, patch.value);\n        if (invalid != null) {\n          this._reject(\n            conn,\n            frame.clientSeq,\n            err_realm.fromId(\"value_invalid\", {\n              path: [...path, ...invalid.path].join(\".\"),\n              expected: invalid.expected,\n            }),\n          );\n          return;\n        }\n      }\n\n      // Subtree expansion: every covered leaf's own most-specific rule must pass.\n      let leaves: string[][];\n      try {\n        leaves = expandWriteToLeaves({\n          schemaRoot: this._realm.stateDef,\n          path,\n          op: patch.op,\n          value: patch.value,\n          state: statePrev,\n          maxLeaves: this._limits.maxExpandedLeaves,\n        });\n      } catch (error) {\n        if (error instanceof ExpansionOverflowError) {\n          this._breach(conn, frame.clientSeq, \"maxExpandedLeaves\");\n          return;\n        }\n        throw error;\n      }\n\n      for (const leafPath of leaves) {\n        const match = this._realm.ruleTrie.match(leafPath);\n        if (match == null) {\n          this._reject(\n            conn,\n            frame.clientSeq,\n            err_realm.fromId(\"unauthorized_coordinate\", {\n              path: leafPath.join(\".\"),\n            }),\n          );\n          return;\n        }\n        const rel = leafPath.slice(path.length);\n        const next = patch.op === \"remove\" ? undefined : getAtPath(patch.value, rel);\n        const verdict = evalAlterCond(\n          match.rule.alter,\n          {\n            avatar: conn.avatar,\n            params: match.params,\n            prev: getAtPath(statePrev, leafPath),\n            next,\n            state: statePrev,\n            basisVersion: frame.basisVersion,\n          },\n          extrasFor(leafPath),\n        );\n        if (verdict === \"serverOnly\") {\n          this._reject(\n            conn,\n            frame.clientSeq,\n            err_realm.fromId(\"unauthorized_coordinate\", {\n              path: leafPath.join(\".\"),\n            }),\n          );\n          return;\n        }\n        if (verdict !== true) {\n          this._reject(conn, frame.clientSeq, verdict);\n          return;\n        }\n      }\n    }\n\n    // Whole frame passed — apply atomically, then the shared commit tail.\n    let nextState: TState;\n    try {\n      nextState = applyPatches(this._state, namePatches);\n    } catch {\n      // Valid schema + rules, but the target's parent is gone (a pruned entry, or a transient\n      // region reset by a hibernation wake since the write's basis) — a distinct outcome from a\n      // malformed `frame_invalid`. The client re-reads state (an assert-on-resume\n      // re-creates a pruned own-entry) rather than blindly re-issuing.\n      const path = (namePatches[0]?.path as string[] | undefined)?.join(\".\") ?? \"(unknown)\";\n      // Production observability: a divergence under a LIVE writer is the interesting\n      // case, so surface the writer's live-socket count with the path.\n      this._options.onWriteTargetMissing?.({\n        avatar: conn.avatar,\n        connKey: conn.key,\n        path,\n        liveConnections: this._avatarConnCounts.get(clientKey(conn.avatar)) ?? 0,\n      });\n      this._reject(conn, frame.clientSeq, err_realm.fromId(\"write_target_missing\", { path }));\n      return;\n    }\n    // State-aware bounds (candidate next state): the check `validateValue` cannot make — e.g. a\n    // record's maxKeys when this write adds one more individually-valid entry.\n    if (this._hasBounds) {\n      const bounded = validateBoundedPatches(\n        this._realm.stateDef,\n        nextState,\n        namePatches.map((patch) => patch.path),\n      );\n      if (bounded != null) {\n        this._reject(\n          conn,\n          frame.clientSeq,\n          err_realm.fromId(\"value_invalid\", {\n            path: bounded.path.join(\".\"),\n            expected: bounded.expected,\n          }),\n        );\n        return;\n      }\n    }\n    const version = this._commit(nextState, namePatches, { source: \"write\", avatar: conn.avatar });\n    this._settleAck(conn, frame.clientSeq, version);\n  }\n\n  // ── Intent pipeline ──────────────────────────────────────────────\n\n  private _handleIntent(\n    conn: IEngineConnection<TAvatarType>,\n    frame: IRealmFrameIntent,\n    byteLength?: number,\n  ): void {\n    // Replay/dup guard first: a replayed intent must not re-run `apply`. A\n    // duplicate seq is re-acked (idempotent) inside `_passesSeq`, before ingress.\n    if (!this._passesSeq(conn, frame.clientSeq)) return;\n    if (!this._passesIngress(conn, frame.clientSeq, byteLength, 0)) return;\n    this._advanceSeqHighWater(conn, frame.clientSeq); // accepted past seq + ingress (see write path)\n\n    const name = this._realm.intentNames[frame.intentToken];\n    const def = name == null ? undefined : this._realm.intents[name];\n    if (name == null || def == null) {\n      this._reject(\n        conn,\n        frame.clientSeq,\n        err_realm.fromId(\"intent_unknown\", {\n          intent: `#${frame.intentToken}`,\n        }),\n      );\n      return;\n    }\n\n    if (!def.allow.includes(conn.avatar.type)) {\n      this._reject(\n        conn,\n        frame.clientSeq,\n        err_realm.fromId(\"unauthorized_avatar_type\", {\n          avatarType: conn.avatar.type,\n          expected: def.allow,\n        }),\n      );\n      return;\n    }\n\n    const invalid = validateValue(def.input, frame.input);\n    if (invalid != null) {\n      this._reject(\n        conn,\n        frame.clientSeq,\n        err_realm.fromId(\"value_invalid\", {\n          path: [name, ...invalid.path].join(\".\"),\n          expected: invalid.expected,\n        }),\n      );\n      return;\n    }\n\n    // Atomic apply on a draft of the full authoritative state.\n    this._guardReentrancy();\n    this._mutating = true;\n    let verdict: TRuleVerdict = true;\n    let produced: readonly [TState, Patch[], Patch[]];\n    try {\n      produced = produceWithPatches(this._state, (draft) => {\n        verdict = def.apply({\n          state: draft,\n          avatar: conn.avatar,\n          input: frame.input,\n          ctx: this._ctx,\n        });\n      });\n    } finally {\n      this._mutating = false;\n    }\n\n    if (verdict !== true) {\n      // Draft discarded entirely — no partial state.\n      this._reject(conn, frame.clientSeq, verdict);\n      return;\n    }\n\n    const [nextState, patches] = produced;\n    if (patches.length === 0) {\n      // No-op commit (the idempotent-retry shape): nothing to broadcast, ack settles the caller.\n      this._enqueue(\n        conn,\n        encodeAck({ slot: conn.slot, clientSeq: frame.clientSeq, version: this._version }),\n      );\n      return;\n    }\n    const canonical = canonicalizeStatePatches(patches, nextState, this._realm.stateDef);\n    // Phase 5: an intent's `apply` can turn an untrusted input value into a record key (e.g.\n    // `state.orders[input.orderId] = …`), which the write-path deny-list above never saw. Screen the\n    // produced patches — path *and* value (a freshly-created record entry carries its key in the\n    // value) — so no unsafe key reaches committed (and broadcast) state via an intent either.\n    // `nextState` is discarded on a hit — the draft never commits.\n    for (const patch of canonical) {\n      if (\n        pathHasUnsafeKey(patch.path) ||\n        (patch.op !== \"remove\" && valueHasUnsafeKey(patch.value))\n      ) {\n        this._reject(\n          conn,\n          frame.clientSeq,\n          err_realm.fromId(\"frame_invalid\", { reason: \"unsafe record key\" }),\n        );\n        return;\n      }\n    }\n    // Bounds against the candidate state — an intent's `apply` mutates the draft freely (no\n    // per-patch validateValue runs on its output), so this is where its bounds are enforced.\n    // The draft is discarded on a hit; nothing partial commits.\n    if (this._hasBounds) {\n      const bounded = validateBoundedPatches(\n        this._realm.stateDef,\n        nextState,\n        canonical.map((patch) => patch.path),\n      );\n      if (bounded != null) {\n        this._reject(\n          conn,\n          frame.clientSeq,\n          err_realm.fromId(\"value_invalid\", {\n            path: bounded.path.join(\".\"),\n            expected: bounded.expected,\n          }),\n        );\n        return;\n      }\n    }\n    const version = this._commit(nextState, canonical, { source: \"intent\", avatar: conn.avatar });\n    this._settleAck(conn, frame.clientSeq, version);\n  }\n\n  // ── Commit tail: version → log → slice → broadcast ─────────────\n\n  private _commit(\n    nextState: TState,\n    namePatches: Patch[],\n    meta: { source: TRealmMutationSource; avatar?: IRealmAvatarRef },\n  ): number {\n    const statePrev = this._state;\n    const versionBefore = this._version;\n    this._state = nextState;\n\n    // Commit classification (Phase 5): durable ops are logged, CAS-tracked, and advance the version;\n    // transient ops (presence-shaped, never persisted) change state and broadcast but pay none of\n    // that. A transient-ONLY commit does NOT advance the version — the log keeps one entry per\n    // version, so a gap would break replay reconstruction (a resume heals transient via the refresh).\n    const durableOps =\n      this._realm.transient.length === 0\n        ? namePatches\n        : namePatches.filter((patch) => !this._isTransientPath(patch.path as string[]));\n    const isDurable = durableOps.length > 0;\n\n    if (isDurable) {\n      this._version += 1;\n      // Log append (seq = version - 1) + CAS touch entries — DURABLE ops only, pruned to the window.\n      const ops: ILoggedOp[] = durableOps.map((patch) =>\n        patch.op === \"remove\"\n          ? { op: patch.op, path: patch.path as string[] }\n          : { op: patch.op, path: patch.path as string[], value: patch.value },\n      );\n      this._log.append(this._logStreamId(), ops);\n      for (const patch of durableOps) {\n        this._touches.push({ path: patch.path as string[], version: this._version });\n      }\n      const pruneBelow = this._version - this._logWindow;\n      if (pruneBelow > 0 && this._touches[0] != null && this._touches[0].version <= pruneBelow) {\n        this._touches = this._touches.filter((touch) => touch.version > pruneBelow);\n      }\n    }\n\n    // Broadcast ALL ops (durable + transient). A transient-only commit is version-neutral\n    // (`fromVersion === toVersion`): the client applies the ops and leaves `confirmedVersion` put —\n    // shape-compatible with an old client (Phase 5 design).\n    if (this._broadcastCoalesceMs > 0) {\n      // Tick mode (Phase 4): accumulate into the open window; the flush fans out one conflated frame.\n      if (this._windowStartState === undefined) {\n        this._windowStartState = statePrev;\n        this._windowFromVersion = versionBefore;\n        this._armWindowTimer();\n      }\n      for (const patch of namePatches) this._windowOps.push(patch);\n    } else {\n      this._broadcast(namePatches, statePrev, versionBefore, this._version);\n    }\n    // onMutation drives host persistence (snapshots) — fire only when something durable changed, so a\n    // cursor storm never triggers the snapshot cadence.\n    if (isDurable) {\n      this._options.onMutation?.(namePatches, { version: this._version, ...meta });\n    }\n    return this._version;\n  }\n\n  /** A path is transient (Phase 5) when a declared transient root is a prefix of it. */\n  private _isTransientPath(path: readonly string[]): boolean {\n    for (const root of this._realm.transient) {\n      if (root.length > path.length) continue;\n      let matches = true;\n      for (let i = 0; i < root.length; i++) {\n        if (root[i] !== path[i]) {\n          matches = false;\n          break;\n        }\n      }\n      if (matches) return true;\n    }\n    return false;\n  }\n\n  /** A path is EXACTLY a declared transient root — the whole-region refresh key in a replay. */\n  private _isTransientRoot(path: readonly string[]): boolean {\n    return this._realm.transient.some(\n      (root) => root.length === path.length && root.every((seg, i) => seg === path[i]),\n    );\n  }\n\n  // ── Broadcast tick (Phase 4) ─────────────────────────────────────────────────\n\n  /**\n   * Flush the open broadcast window (Phase 4): conflate its accumulated ops, fan out ONE patches\n   * frame per connection (chunked under the ws ceiling — P4), then the window's deferred acks, all\n   * via the outbox so each connection collapses to one WS message. Public so a host or test can force\n   * a tick boundary; also the timer callback and the pre-hydrate flush in `attach`. A no-op when no\n   * window is open (per-commit realms never open one).\n   */\n  flushBroadcasts(): void {\n    this._flushWindow();\n    this._flushEgress();\n  }\n\n  private _flushWindow(): void {\n    this._clearWindowTimer();\n    if (this._windowStartState === undefined) return;\n    const startState = this._windowStartState;\n    const fromVersion = this._windowFromVersion;\n    const ops = conflateOps(this._windowOps);\n    // Reset the window BEFORE broadcasting — a re-entrant commit (in-memory resend) opens a fresh one.\n    this._windowOps = [];\n    this._windowStartState = undefined;\n    this._broadcast(ops, startState, fromVersion, this._version);\n    this._flushPendingAcks();\n  }\n\n  private _armWindowTimer(): void {\n    if (this._windowTimerCancel != null) return;\n    this._windowTimerCancel = this._scheduleBroadcast(() => {\n      this._windowTimerCancel = undefined; // it fired — nothing to cancel\n      this.flushBroadcasts();\n    }, this._broadcastCoalesceMs);\n  }\n\n  private _clearWindowTimer(): void {\n    if (this._windowTimerCancel == null) return;\n    this._windowTimerCancel();\n    this._windowTimerCancel = undefined;\n  }\n\n  private _flushPendingAcks(): void {\n    if (this._pendingAcks.length === 0) return;\n    const acks = this._pendingAcks;\n    this._pendingAcks = [];\n    for (const { conn, clientSeq, version } of acks) {\n      // Skip a connection that detached mid-window (its record is gone; the socket is closed).\n      if (this._connections.get(conn.key) !== conn) continue;\n      this._enqueue(conn, encodeAck({ slot: conn.slot, clientSeq, version }));\n    }\n  }\n\n  /** Settle a committed write/intent: immediate ack per-commit, or deferred into the window (P3). */\n  private _settleAck(\n    conn: IEngineConnection<TAvatarType>,\n    clientSeq: number,\n    version: number,\n  ): void {\n    if (this._broadcastCoalesceMs > 0) {\n      this._pendingAcks.push({ conn, clientSeq, version });\n    } else {\n      this._enqueue(conn, encodeAck({ slot: conn.slot, clientSeq, version }));\n    }\n  }\n\n  private _broadcast(\n    namePatches: Patch[],\n    statePrev: TState,\n    fromVersion: number,\n    toVersion: number,\n  ): void {\n    if (this._connections.size === 0) return;\n    // Captured now: an in-memory loopback can commit re-entrantly while this loop sends.\n    const stateAfter = this._state;\n\n    // Encode once per (view-signature, slot) — identical bytes fan out to every group member. A\n    // group's sliced ops may split into several patches frames when they'd exceed the ws ceiling\n    // (P4 — a busy tick window); one frame in the common case, byte-identical to pre-Phase-4.\n    const cache = new Map<string, { bytes: Uint8Array; usedIds: Set<number> }[] | null>();\n    for (const conn of this._connections.values()) {\n      const groupKey = `${viewSignatureKey(conn.avatar)}/${conn.slot}`;\n      let chunks = cache.get(groupKey);\n      if (chunks === undefined) {\n        const sliced: Patch[] = [];\n        for (const patch of namePatches) {\n          const slicedPatch = slicePatchForAvatar(\n            this._sliceCtx(conn.avatar),\n            patch,\n            statePrev,\n            stateAfter,\n          );\n          if (slicedPatch != null) sliced.push(slicedPatch);\n        }\n        chunks =\n          sliced.length === 0\n            ? null\n            : this._encodePatchesChunked(sliced, conn.slot, fromVersion, toVersion);\n        cache.set(groupKey, chunks);\n      }\n      if (chunks == null) continue;\n      for (const chunk of chunks) {\n        this._sendKeyDictDelta(conn, chunk.usedIds);\n        this._enqueue(conn, chunk.bytes);\n      }\n    }\n  }\n\n  private _encodePatches(\n    sliced: Patch[],\n    slot: number,\n    fromVersion: number,\n    toVersion: number,\n  ): { bytes: Uint8Array; usedIds: Set<number> } {\n    const usedIds = new Set<number>();\n    const ops = namePatchesToWireOps(sliced, this._realm.tokens, (key) => {\n      const id = this._dict.intern(key);\n      usedIds.add(id);\n      return id;\n    });\n    return { bytes: encodePatches({ slot, fromVersion, toVersion, ops }), usedIds };\n  }\n\n  /**\n   * Encode sliced ops into one-or-more patches frames, each under the ws message ceiling (P4). Splits\n   * by op-count (recursive halving) — the parts share `fromVersion`/`toVersion` and apply in order to\n   * the same state, since server→client ops are order-preserving within a version. A single op that\n   * alone exceeds the ceiling is emitted anyway (indivisible — the same as a single over-limit commit\n   * today; the hydrate path is the only genuinely large payload and it chunks separately).\n   */\n  private _encodePatchesChunked(\n    sliced: Patch[],\n    slot: number,\n    fromVersion: number,\n    toVersion: number,\n  ): { bytes: Uint8Array; usedIds: Set<number> }[] {\n    const whole = this._encodePatches(sliced, slot, fromVersion, toVersion);\n    const ceiling = this._options.hydrateChunkBytes ?? 900 * 1024;\n    if (whole.bytes.byteLength <= ceiling || sliced.length <= 1) return [whole];\n    const mid = Math.ceil(sliced.length / 2);\n    return [\n      ...this._encodePatchesChunked(sliced.slice(0, mid), slot, fromVersion, toVersion),\n      ...this._encodePatchesChunked(sliced.slice(mid), slot, fromVersion, toVersion),\n    ];\n  }\n\n  private _sendPatchesFrame(\n    conn: IEngineConnection<TAvatarType>,\n    sliced: Patch[],\n    fromVersion: number,\n    toVersion: number,\n  ): void {\n    const entry = this._encodePatches(sliced, conn.slot, fromVersion, toVersion);\n    this._sendKeyDictDelta(conn, entry.usedIds);\n    this._enqueue(conn, entry.bytes);\n  }\n\n  private _sendKeyDictDelta(\n    conn: IEngineConnection<TAvatarType>,\n    usedIds: ReadonlySet<number>,\n  ): void {\n    const entries: [string, number][] = [];\n    for (const id of usedIds) {\n      if (conn.sentKeyIds.has(id)) continue;\n      const key = this._dict.keyOf(id);\n      if (key == null) continue;\n      entries.push([key, id]);\n      conn.sentKeyIds.add(id);\n    }\n    if (entries.length > 0) {\n      this._enqueue(conn, encodeKeyDict({ slot: conn.slot, entries }));\n    }\n  }\n\n  /** Merged replay ops for versions `basis+1 … head`, or `undefined` when outside the window. */\n  private _buildReplayOps(basisVersion: number): Patch[] | undefined {\n    // The log holds one entry per version (seq = version - 1). Compaction (`keepDelivered`)\n    // deletes from the *front*, so the surviving prefix covers versions\n    // `(head - prefix.length + 1) … head` — a basis older than that means a full hydrate.\n    const prefix = this._log.contiguousPrefix(this._logStreamId());\n    const oldestReplayableBasis = this._version - prefix.length;\n    if (basisVersion < oldestReplayableBasis) return undefined;\n\n    const merged: Patch[] = [];\n    for (let i = basisVersion - oldestReplayableBasis; i < prefix.length; i++) {\n      for (const op of prefix[i]) {\n        merged.push(\n          op.op === \"remove\"\n            ? { op: op.op, path: op.path }\n            : { op: op.op, path: op.path, value: op.value },\n        );\n      }\n    }\n    // Conflate before slicing (Phase 3): a resume that spans many versions of the same hot path\n    // (a cursor) collapses to the final value(s) instead of replaying every dead intermediate.\n    // Final-state-equivalent, so the resumed avatar converges identically to a full hydrate.\n    const conflated = conflateOps(merged);\n    // Replay refresh (Phase 5): transient regions live in state but never the log, so a resume would\n    // otherwise carry stale (or missing) presence. Append each root's CURRENT value as a whole-root\n    // replace — absolute, so entries added AND removed while the avatar was away both converge. This\n    // is also what makes the staleness probe (a hello at the current version → empty durable replay)\n    // heal transient state for free (F7). A fully-durable realm appends nothing.\n    for (const root of this._realm.transient) {\n      conflated.push({ op: \"replace\", path: [...root], value: getAtPath(this._state, root) });\n    }\n    return conflated;\n  }\n\n  private _logStreamId(): string {\n    return `realm:${this._realm.id}:${this._instanceId}`;\n  }\n\n  // ── Helpers ──────────────────────────────────────────────────────────────────\n\n  private _sliceCtx(avatar: IRealmAvatarRef): IViewSliceContext {\n    return {\n      schemaRoot: this._realm.stateDef,\n      trie: this._realm.ruleTrie,\n      // Strip `instanceId` at runtime: the per-signature broadcast cache groups by\n      // (type, persistentId), so a view rule reading `instanceId` would be silently mis-sliced\n      // across a client's tabs. The type already forbids it; this covers an untyped JS consumer.\n      avatar: { type: avatar.type, persistentId: avatar.persistentId },\n    };\n  }\n\n  private _touchedSince(leafPath: string[], basisVersion: number): boolean {\n    // CAS on a transient region is a program error (Phase 5): transient commits record no touches, so\n    // `touchedSince` would silently always answer \"not touched\" and the CAS would never fire. Throw\n    // loudly the first time a rule tries it, rather than shipping a stale-detection guard that is a\n    // no-op. (A define-time lint can't see `touchedSince` inside an opaque rule function; this is the\n    // earliest reliable point.)\n    if (this._isTransientPath(leafPath)) {\n      throw new Error(\n        `realm \"${this._realm.id}\": touchedSince()/CAS is not supported under the transient region ` +\n          `containing \"${leafPath.join(\".\")}\" — transient state keeps no touch history, so a CAS ` +\n          \"there would silently always pass. Drop the CAS, or make that region durable.\",\n      );\n    }\n    // A basis older than the replayable window is treated as stale.\n    if (basisVersion < this._version - this._logWindow) return true;\n    for (let i = this._touches.length - 1; i >= 0; i--) {\n      const touch = this._touches[i];\n      if (touch.version <= basisVersion) break;\n      if (pathsOverlap(touch.path, leafPath)) return true;\n    }\n    return false;\n  }\n\n  /**\n   * The replay/duplicate high-water gate. Returns `false` — caller\n   * must stop — when `clientSeq` is at or below the connection's high-water: the frame is either a\n   * replay (a captured frame re-injected into the framing layer) or a benign ack-lost resend, which\n   * by seq alone are indistinguishable and both safe to treat as already-processed. It is settled\n   * **idempotently** — re-ack the current authoritative version (the client's handle settles\n   * read-your-writes via the version; no per-seq bookkeeping needed) — never re-applied and never\n   * counted as a breach. New seqs (`> high-water`) return `true`; the caller advances the high-water\n   * only after ingress also passes (so a rate-limited retry keeps its seq — see `_handleWrite`).\n   */\n  private _passesSeq(conn: IEngineConnection<TAvatarType>, clientSeq: number): boolean {\n    // The reassert lane (Phase 2): a sentinel (negative) `clientSeq` is a system-assert — an\n    // idempotent LWW whole-entry re-own the client rides on a recovery hello to re-create a transient\n    // entry a wake reset. It SKIPS the replay/dup high-water entirely: it must never advance or\n    // consume a real seq (the §0 constraint — otherwise a resent intent at a lower seq would be\n    // dup-acked as already-processed and falsely confirmed but never run), and it needs no\n    // dup-tracking because re-applying the same whole-entry write within a session is a no-op. An old\n    // engine (≤ 0.47) lacking this branch instead hits the `<= -1` gate below and dup-acks it, which\n    // is the client's documented skew fallback (it re-owns post-answer instead).\n    if (clientSeq < 0) return true;\n    if (clientSeq <= (this._seqHighWater.get(conn.key) ?? -1)) {\n      this._enqueue(conn, encodeAck({ slot: conn.slot, clientSeq, version: this._version }));\n      return false;\n    }\n    return true;\n  }\n\n  /**\n   * Advance the connection's replay high-water and persist it. Persist\n   * runs per accepted frame so the durable value never lags an arbitrary hibernation point (a\n   * lagging value would reopen the wake-replay window). Cost: one host-side upsert per accepted\n   * `write`/`intent` — see the host's `persistSeqHighWater`, which may batch if it proves hot.\n   */\n  private _advanceSeqHighWater(conn: IEngineConnection<TAvatarType>, clientSeq: number): void {\n    if (clientSeq < 0) return; // sentinel (reassert lane) — never advances or lowers the high-water\n    this._seqHighWater.set(conn.key, clientSeq);\n    this._options.persistSeqHighWater?.(conn.avatar, conn.slot, clientSeq);\n  }\n\n  private _passesIngress(\n    conn: IEngineConnection<TAvatarType>,\n    clientSeq: number,\n    byteLength: number | undefined,\n    opsCount: number,\n  ): boolean {\n    if (byteLength != null && byteLength > this._limits.maxFrameBytes) {\n      this._breach(conn, clientSeq, \"maxFrameBytes\");\n      return false;\n    }\n    if (opsCount > this._limits.maxPatchesPerFrame) {\n      this._breach(conn, clientSeq, \"maxPatchesPerFrame\");\n      return false;\n    }\n    // Token bucket per connection.\n    const now = this._now();\n    const bucket = conn.bucket;\n    const elapsed = Math.max(0, now - bucket.last) / 1000;\n    bucket.tokens = Math.min(\n      this._limits.writeRateBurst,\n      bucket.tokens + elapsed * this._limits.writeRatePerSecond,\n    );\n    bucket.last = now;\n    if (bucket.tokens < 1) {\n      this._breach(conn, clientSeq, \"writeRatePerSecond\");\n      return false;\n    }\n    bucket.tokens -= 1;\n    return true;\n  }\n\n  private _breach(conn: IEngineConnection<TAvatarType>, clientSeq: number, limit: string): void {\n    this._reject(conn, clientSeq, err_realm.fromId(\"limits_exceeded\", { limit }));\n    conn.bucket.breaches += 1;\n    if (conn.bucket.breaches >= this._limits.maxBreachesBeforeDetach) {\n      this.detachConnection(conn.key, \"repeated limit breaches\", true);\n    }\n  }\n\n  /**\n   * Send a rejection to one connection. The wire carries **only** the error's public\n   * `toJsonObject()` (ids, user-provided error context, message, stack) — never the realm's\n   * `serverContext` (`ctx`), which the engine never places on an error (the protocol contract\n   * secret-scrub, verified). Discipline this implies for realm authors: a rule/intent error's\n   * **context and message are wire-visible**, so they must not embed server secrets (`ctx` values,\n   * internal ids) — the same rule as the client bundle. Documented in the security guide (Phase 8).\n   */\n  private _reject(\n    conn: IEngineConnection<TAvatarType>,\n    clientSeq: number,\n    error: NiceError<any, any>,\n  ): void {\n    this._enqueue(\n      conn,\n      encodeReject({\n        slot: conn.slot,\n        clientSeq,\n        // Wire-slim (Phase 3 / Overshot Issue 4): the reject carries ids + context + message, NOT the\n        // server `stack`/`originError`. Rejects fan out to every client and, on a bad path (a\n        // cursor-write reject storm), out-frequency the data — the full ~1.5 kB form is mostly stack,\n        // and the stack discloses server internals. The complete error stays server-side for logs.\n        error: error.toWireJsonObject() as unknown as Record<string, unknown>,\n      }),\n    );\n  }\n\n  private _guardReentrancy(): void {\n    if (this._mutating) {\n      throw new Error(\n        \"realm single-writer invariant: engine.update()/intents may not run inside an intent apply or a rule\",\n      );\n    }\n  }\n\n  // ── Egress outbox (Phase 2): one WS message per connection per entry point ────\n\n  /** Queue one already-encoded frame for a connection; the entry point's `_flushEgress` sends it. */\n  private _enqueue(conn: IEngineConnection<TAvatarType>, bytes: Uint8Array): void {\n    conn.outbox.push(bytes);\n    this._dirtyConns.add(conn);\n  }\n\n  /**\n   * Drain every connection's outbox (Phase 2). Runs at the end of each public entry point. Frames\n   * queued during ONE entry point collapse to one WS message per connection — a `batch` when the\n   * connection advertised {@link REALM_FEATURE.batch} and more than one frame is pending, else bare\n   * sequential sends (byte-identical to pre-Phase-2 for a non-batch peer). Re-entrancy safe (F4):\n   * the guard makes a nested flush (a raw send re-entered an entry point on an in-memory link) a\n   * no-op, and each connection's queue is reference-swapped before its frames go out, so frames a\n   * re-entrant call enqueues are picked up by the owning loop AFTER the current snapshot — never\n   * interleaved. Insertion order of `_dirtyConns` (Set) is the per-connection flush order.\n   */\n  private _flushEgress(): void {\n    if (this._flushing) return;\n    this._flushing = true;\n    try {\n      while (this._dirtyConns.size > 0) {\n        const conn = this._dirtyConns.values().next().value;\n        if (conn == null) break;\n        this._dirtyConns.delete(conn);\n        const frames = conn.outbox;\n        if (frames.length === 0) continue;\n        conn.outbox = []; // swap out BEFORE sending — re-entrant enqueues land in the next generation\n        this._transmit(conn, frames);\n      }\n    } finally {\n      this._flushing = false;\n    }\n  }\n\n  /**\n   * Send one connection's snapshot of queued frames. One frame → bare (no envelope overhead). More\n   * than one on a batch-capable connection → a `batch` envelope, split so no single message exceeds\n   * the host's ws ceiling (`hydrateChunkBytes`) — which also keeps near-ceiling hydrate chunks in\n   * their own message (never re-merged). A non-batch connection gets today's sequential bare sends.\n   */\n  private _transmit(conn: IEngineConnection<TAvatarType>, frames: Uint8Array[]): void {\n    // Frames counted pre-coalescing; messages+bytes at each raw send — their ratio IS the\n    // batch-envelope win, and messages are the unit platforms bill.\n    conn.traffic.egressFrames += frames.length;\n    this._traffic.egressFrames += frames.length;\n    const rawSend = (bytes: Uint8Array): void => {\n      conn.traffic.egressMessages += 1;\n      conn.traffic.egressBytes += bytes.byteLength;\n      this._traffic.egressMessages += 1;\n      this._traffic.egressBytes += bytes.byteLength;\n      this._emitTraffic(\"out\", bytes.byteLength, conn.key);\n      try {\n        conn.send(bytes);\n      } catch {\n        // The socket may already be gone (a detach flush races the close) — bookkeeping still ran.\n      }\n    };\n\n    if (frames.length === 1) {\n      rawSend(frames[0]);\n      return;\n    }\n    if (!conn.features.has(REALM_FEATURE.batch)) {\n      for (const bytes of frames) rawSend(bytes);\n      return;\n    }\n\n    // Batch, respecting the ws message ceiling. Envelope/payload overheads are estimated\n    // conservatively (msgpack array + bin32 headers) so the encoded envelope never crosses it.\n    const ceiling = this._options.hydrateChunkBytes ?? 900 * 1024;\n    let group: Uint8Array[] = [];\n    let groupBytes = ENVELOPE_BASE_BYTES;\n    const flushGroup = (): void => {\n      if (group.length === 0) return;\n      // A group of one goes bare — no point paying envelope overhead to wrap a lone frame.\n      rawSend(group.length === 1 ? group[0] : encodeBatch({ slot: conn.slot, payloads: group }));\n      group = [];\n      groupBytes = ENVELOPE_BASE_BYTES;\n    };\n    for (const bytes of frames) {\n      const cost = bytes.byteLength + PAYLOAD_HEADER_BYTES;\n      if (group.length > 0 && groupBytes + cost > ceiling) flushGroup();\n      group.push(bytes);\n      groupBytes += cost;\n    }\n    flushGroup();\n  }\n}\n\n/** Conservative msgpack overheads for the batch-envelope ceiling math (see {@link RealmServerEngine._transmit}). */\nconst ENVELOPE_BASE_BYTES = 16; // [kind, slot, payloads[]] array + slot header\nconst PAYLOAD_HEADER_BYTES = 5; // a bin32 length prefix per child\n\nfunction getAtPath(state: unknown, path: readonly string[]): unknown {\n  let current: unknown = state;\n  for (const seg of path) {\n    if (current == null || typeof current !== \"object\") return undefined;\n    current = (current as Record<string, unknown>)[seg];\n  }\n  return current;\n}\n\nfunction pathsOverlap(a: readonly string[], b: readonly string[]): boolean {\n  const len = Math.min(a.length, b.length);\n  for (let i = 0; i < len; i++) {\n    if (a[i] !== b[i]) return false;\n  }\n  return true;\n}\n\n/** Factory with full inference from the realm definition. */\nexport function createRealmServerEngine<TState extends object, TAvatarType extends string, TCtx>(\n  realm: IRealmDefinition<TState, TAvatarType, TCtx, any, any>,\n  options: IRealmServerEngineOptions<TState, TCtx>,\n): RealmServerEngine<TState, TAvatarType, TCtx> {\n  return new RealmServerEngine(realm, options);\n}\n","import {\n  ESecurityLevel,\n  type IWireAcceptorProtocolContext,\n  securityLevelMeets,\n  WIRE_PROTOCOL_PREFIX,\n} from \"@nice-code/wire\";\nimport { err_realm } from \"../RealmDefinition/errors/err_realm\";\nimport type { IRealmAvatarRef } from \"../RealmDefinition/Rules/rules.types\";\nimport {\n  REALM_DETACH_REASON_REHELLO,\n  REALM_FRAME_KIND,\n  type TRealmFrame,\n} from \"../RealmWire/realmFrame.types\";\nimport { decodeRealmFrame, encodeDetach, encodeReject } from \"../RealmWire/realmFrameCodec\";\nimport type { RealmServerEngine } from \"./RealmServerEngine\";\n\n/**\n * The acceptor-side realm protocol: one frame-protocol registration\n * (id `\"realm\"`, prefix `0x01`) hosting any number of realm engines behind one negotiated\n * protocol — frames route by `realmId` (at `hello`) then by **slot**. The returned object\n * *structurally* matches nice-action's `IAcceptorFrameProtocol<TConn>` — realm never imports\n * action; register it via `acceptorHandler.registerFrameProtocol(...)` or drive it\n * directly in tests.\n *\n * `resolveAvatar` maps an authenticated connection to realm coordinates (type / persistentId /\n * instanceId) — the identity source per D-13 (secure-duplex connections are authenticated before\n * any realm frame arrives; `hello` carries no credential).\n */\n\nexport interface IRealmHostedRealm<TConn> {\n  engine: RealmServerEngine<any, any, any>;\n  resolveAvatar?: (\n    connection: TConn,\n    context: IWireAcceptorProtocolContext,\n  ) => IRealmAvatarRef | undefined;\n  /** Stamp this avatar type onto the authenticated wire identity. */\n  avatarType?: string;\n  /**\n   * The minimum wire security level this realm requires. A `hello` below this level is rejected\n   * with `insufficient_security`, using trusted protocol context (or the legacy `levelFor`\n   * callback). Missing security facts are treated as `none`. Omit to keep the coarse wire\n   * gate as the only floor (the host still blocks `none` connections from all protocols).\n   */\n  minSecurity?: ESecurityLevel;\n}\n\nexport interface IRealmAcceptorProtocol<TConn> {\n  readonly id: \"realm\";\n  readonly prefixByte: number;\n  onFrame(\n    connection: TConn,\n    payload: Uint8Array,\n    send: (payload: Uint8Array) => void,\n    context?: IWireAcceptorProtocolContext,\n  ): void;\n  /**\n   * Fired by the hosting acceptor when a connection (re)attaches — `createRealmHost`\n   * uses it for the wake \"rehello\" resume broadcast; the bare acceptor doesn't implement it.\n   */\n  onAttach?(\n    connection: TConn,\n    send: (payload: Uint8Array) => void,\n    context?: IWireAcceptorProtocolContext,\n  ): void;\n  onDetach?(connection: TConn, context?: IWireAcceptorProtocolContext): void;\n}\n\ninterface IConnState {\n  key: string;\n  /** slot → realmId, for routing post-hello frames. */\n  slots: Map<number, string>;\n}\n\nexport interface ICreateRealmAcceptorOptions<TConn> {\n  realms: Record<string, IRealmHostedRealm<TConn>>;\n  /**\n   * Resolve a connection's negotiated wire security level — **injected** by\n   * the host (never imported, so realm stays action-free), exactly like `resolveAvatar`.\n   * Wake-safe hosts read it off the persisted socket attachment (wire's\n   * `securityLevelFromAttachment`) so the check holds across a hibernation wake, where the socket\n   * re-hellos with no fresh handshake. When omitted, per-realm `minSecurity` is **not** enforced —\n   * the coarse wire gate (which already blocks `none` connections) remains the only floor.\n   */\n  levelFor?: (connection: TConn) => ESecurityLevel;\n}\n\nexport function createRealmAcceptor<TConn extends object>(\n  options: ICreateRealmAcceptorOptions<TConn>,\n): IRealmAcceptorProtocol<TConn> {\n  for (const [realmId, hosted] of Object.entries(options.realms)) {\n    if ((hosted.resolveAvatar == null) === (hosted.avatarType == null)) {\n      throw new Error(\n        `createRealmAcceptor: realm \"${realmId}\" requires exactly one of \\`resolveAvatar\\` or \\`avatarType\\``,\n      );\n    }\n  }\n\n  const connStates = new WeakMap<TConn, IConnState>();\n  let connCounter = 0;\n\n  const stateFor = (connection: TConn): IConnState => {\n    let state = connStates.get(connection);\n    if (state == null) {\n      connCounter += 1;\n      state = { key: `conn-${connCounter}`, slots: new Map() };\n      connStates.set(connection, state);\n    }\n    return state;\n  };\n\n  const engineConnKey = (state: IConnState, slot: number): string => `${state.key}/${slot}`;\n\n  return {\n    id: \"realm\",\n    prefixByte: WIRE_PROTOCOL_PREFIX.realm,\n\n    onFrame(connection, payload, send, suppliedContext) {\n      const context: IWireAcceptorProtocolContext = suppliedContext ?? {\n        client: undefined,\n        level: options.levelFor?.(connection) ?? ESecurityLevel.none,\n      };\n      let frame: TRealmFrame;\n      try {\n        frame = decodeRealmFrame(payload);\n      } catch {\n        // Malformed frames from an authenticated peer are dropped (negotiation + codec fuzz\n        // gates make this the hostile/buggy path — there is no clientSeq to reject against).\n        return;\n      }\n      const state = stateFor(connection);\n\n      if (frame.kind === REALM_FRAME_KIND.hello) {\n        const hosted = options.realms[frame.realmId];\n        if (hosted == null) {\n          send(\n            encodeReject({\n              slot: frame.slot,\n              clientSeq: -1,\n              error: err_realm\n                .fromId(\"realm_unknown\", { realmId: frame.realmId })\n                .toWireJsonObject() as unknown as Record<string, unknown>,\n            }),\n          );\n          return;\n        }\n        const avatar =\n          hosted.resolveAvatar?.(connection, context) ??\n          (hosted.avatarType != null && context.client?.perId != null\n            ? {\n                type: hosted.avatarType,\n                persistentId: context.client.perId,\n                instanceId: context.client.insId ?? \"default\",\n              }\n            : undefined);\n        if (avatar == null) {\n          send(\n            encodeReject({\n              slot: frame.slot,\n              clientSeq: -1,\n              error: err_realm\n                .fromId(\"avatar_unresolved\", { realmId: frame.realmId })\n                .toWireJsonObject() as unknown as Record<string, unknown>,\n            }),\n          );\n          return;\n        }\n        // Security floor: reject a connection below the realm's declared\n        // minimum before attaching — fail-closed, so no avatar data ever flows below the required\n        // level. Missing trusted context fails closed to `none`; `levelFor` is retained only as a\n        // compatibility fallback for direct/custom hosts that call the protocol with three args.\n        if (hosted.minSecurity != null) {\n          const actual = context.level;\n          if (!securityLevelMeets(actual, hosted.minSecurity)) {\n            send(\n              encodeReject({\n                slot: frame.slot,\n                clientSeq: -1,\n                error: err_realm\n                  .fromId(\"insufficient_security\", {\n                    realmId: frame.realmId,\n                    required: hosted.minSecurity,\n                    actual,\n                  })\n                  .toWireJsonObject() as unknown as Record<string, unknown>,\n              }),\n            );\n            return;\n          }\n        }\n        // Re-hello on an occupied slot: detach the old attachment ONLY when the slot switches to\n        // a *different* realm — a genuine departure from the old one (its lifecycle hooks and\n        // replay high-water clear are correct there). A **same-realm** re-hello (staleness probe,\n        // wake rehello) flows straight into `attach()`, which swaps the connection record in\n        // place without firing the avatar lifecycle and with the replay high-water surviving\n        // untouched.\n        const previousRealmId = state.slots.get(frame.slot);\n        if (previousRealmId != null && previousRealmId !== frame.realmId) {\n          options.realms[previousRealmId]?.engine.detachConnection(\n            engineConnKey(state, frame.slot),\n            \"re-attached\",\n            false,\n          );\n        }\n        // Map the slot BEFORE attaching: the hydrate/replay `attach` sends can make the avatar\n        // resend pending frames synchronously (revalidate-on-reconnect), and those must route.\n        state.slots.set(frame.slot, frame.realmId);\n        const attached = hosted.engine.attach(engineConnKey(state, frame.slot), {\n          avatar,\n          slot: frame.slot,\n          schemaHash: frame.schemaHash,\n          lastKnownVersion: frame.lastKnownVersion,\n          epoch: frame.epoch,\n          send,\n        });\n        if (!attached) {\n          // The attach gate refused (schema mismatch). A same-realm re-hello skipped the\n          // pre-detach above, so a previous attachment may survive in the engine while the slot\n          // is no longer routable — detach it for real (the client was rejected and detached).\n          if (previousRealmId === frame.realmId) {\n            hosted.engine.detachConnection(engineConnKey(state, frame.slot), \"re-attached\", false);\n          }\n          state.slots.delete(frame.slot);\n        }\n        return;\n      }\n\n      const realmId = state.slots.get(frame.slot);\n      const hosted = realmId == null ? undefined : options.realms[realmId];\n      if (hosted == null) {\n        // A frame for a slot this (possibly freshly-woken) server never saw attach: ask the\n        // avatar to re-hello — it resumes from its lastKnownVersion via patch replay (M6 heal).\n        if (frame.kind !== REALM_FRAME_KIND.detach) {\n          send(encodeDetach({ slot: frame.slot, reason: REALM_DETACH_REASON_REHELLO }));\n        }\n        return;\n      }\n      hosted.engine.receiveFrame(engineConnKey(state, frame.slot), frame, payload.byteLength);\n      if (frame.kind === REALM_FRAME_KIND.detach) state.slots.delete(frame.slot);\n    },\n\n    onDetach(connection) {\n      const state = connStates.get(connection);\n      if (state == null) return;\n      for (const [slot, realmId] of state.slots) {\n        options.realms[realmId]?.engine.detachConnection(\n          engineConnKey(state, slot),\n          \"connection lost\",\n        );\n      }\n      state.slots.clear();\n    },\n  };\n}\n","// Finding a config's daemons by their command line — the discovery that still works when the\n// instance record does not.\n//\n// ⚠ The record is one file per config, and a daemon can outlive its own entry: a second daemon\n// that booted past it (onto the next free port) wrote over the record, then deleted it on its\n// own shutdown. The first daemon keeps running, holding a port and its processes, and every\n// record-based lookup reports \"not running\" — `shutdown` included. Argv is the one identity no\n// other daemon can overwrite: `<runtime> <bin> daemon --config <path> --data-dir <dir>`.\n\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { readProcessStartStamp } from \"@nice-code/process\";\nimport type { ICommanderInstanceRecord } from \"./instanceRecord\";\n\nconst exec = promisify(execFile);\n\nexport interface IDaemonProcess {\n  pid: number;\n  startStamp: ICommanderInstanceRecord[\"startStamp\"];\n}\n\n/** `pid<space>command line` for every process this user can see. */\nasync function processTable(): Promise<{ pid: number; commandLine: string }[]> {\n  if (process.platform === \"win32\") {\n    const { stdout } = await exec(\n      \"powershell.exe\",\n      [\n        \"-NoProfile\",\n        \"-NonInteractive\",\n        \"-Command\",\n        'Get-CimInstance Win32_Process | ForEach-Object { \"$($_.ProcessId) $($_.CommandLine)\" }',\n      ],\n      { maxBuffer: 16 * 1024 * 1024, timeout: 15_000, windowsHide: true },\n    );\n    return parseTable(stdout);\n  }\n  const { stdout } = await exec(\"ps\", [\"-axww\", \"-o\", \"pid=\", \"-o\", \"args=\"], {\n    maxBuffer: 16 * 1024 * 1024,\n    timeout: 10_000,\n  });\n  return parseTable(stdout);\n}\n\nexport function parseTable(text: string): { pid: number; commandLine: string }[] {\n  const rows: { pid: number; commandLine: string }[] = [];\n  for (const line of text.split(/\\r?\\n/)) {\n    const match = /^\\s*(\\d+)\\s+(.*)$/.exec(line);\n    if (match != null) rows.push({ pid: Number(match[1]), commandLine: match[2] ?? \"\" });\n  }\n  return rows;\n}\n\n/**\n * Is this command line the daemon for `configPath` under `dataDir`? Quotes are dropped first:\n * Windows quotes an argument holding a space (`--data-dir \"C:\\…\\App Data\"`), `ps` does not.\n */\nexport function isDaemonCommandLine(\n  commandLine: string,\n  configPath: string,\n  dataDir: string,\n): boolean {\n  const line = ` ${commandLine.replaceAll('\"', \"\")} `;\n  return (\n    line.includes(` daemon --config ${configPath} `) && line.includes(` --data-dir ${dataDir} `)\n  );\n}\n\n/** One sentence naming record-less daemons and the one command that clears them. */\nexport function orphanMessage(orphans: readonly IDaemonProcess[]): string {\n  const one = orphans.length === 1;\n  const pids = orphans.map((orphan) => orphan.pid).join(\", \");\n  const them = one ? \"it\" : \"them\";\n  return (\n    `${one ? \"a daemon\" : `${orphans.length} daemons`} for this config ${one ? \"is\" : \"are\"} ` +\n    `running without an instance record (pid ${pids}), so this CLI cannot talk to ${them}. ` +\n    `Run \\`nice-commander shutdown\\` (it stops ${them} and everything ${one ? \"it runs\" : \"they run\"}), ` +\n    \"then retry.\"\n  );\n}\n\n/**\n * Every live daemon process for this config and data dir, except `excludePid` (a daemon asking\n * about its peers, or a caller that already holds the recorded one). Best effort: a process\n * table that cannot be read answers \"none\", never an error — this is a fallback, not the path.\n */\nexport async function findDaemonProcesses(\n  configPath: string,\n  dataDir: string,\n  excludePid?: number,\n): Promise<IDaemonProcess[]> {\n  let table: { pid: number; commandLine: string }[];\n  try {\n    table = await processTable();\n  } catch {\n    return [];\n  }\n  const found: IDaemonProcess[] = [];\n  for (const row of table) {\n    if (row.pid === process.pid || row.pid === excludePid) continue;\n    if (!isDaemonCommandLine(row.commandLine, configPath, dataDir)) continue;\n    found.push({ pid: row.pid, startStamp: await readProcessStartStamp(row.pid) });\n  }\n  return found;\n}\n","// Data-dir resolution (D6): per-user per-OS state dir, one `<configKey>/` subdir per config\n// holding the instance record, ledger, and log files. Keeps clones clean; survives `git clean`.\n\nimport { mkdir } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { isAbsolute, join, resolve } from \"node:path\";\n\nexport function resolveCommanderDataDir(\n  environment: NodeJS.ProcessEnv = process.env,\n  platform = process.platform,\n): string {\n  const override = environment[\"NICE_COMMANDER_DATA_DIR\"];\n  if (override != null && override.trim() !== \"\") return resolve(override);\n  const home = homedir();\n  if (platform === \"win32\") {\n    return join(environment[\"LOCALAPPDATA\"] ?? join(home, \"AppData\", \"Local\"), \"nice-commander\");\n  }\n  if (platform === \"darwin\") {\n    return join(home, \"Library\", \"Application Support\", \"nice-commander\");\n  }\n  return join(environment[\"XDG_STATE_HOME\"] ?? join(home, \".local\", \"state\"), \"nice-commander\");\n}\n\n/** Everything a single config's daemon owns on disk, anchored at `<dataDir>/<configKey>`. */\nexport interface ICommanderStatePaths {\n  /** `<dataDir>/<configKey>` */\n  stateDir: string;\n  instanceRecordPath: string;\n  /** Ledger namespace = configKey (the ledger file itself lives in stateDir). */\n  ledgerNamespace: string;\n  /** Daemon's own rotated log. */\n  daemonLogDir: string;\n  /** Per-process file sinks + the supervisor aggregate sink. */\n  logsDir: string;\n  /** Serialized `up` lock (concurrent CLI spawns). */\n  upLockPath: string;\n  /** Small fixed handoff for boot failures before the daemon logger opens. */\n  bootLogPath: string;\n  /** Supervisor aggregate ingestSeq high-water mark. */\n  ingestSeqPath: string;\n  /** Sticky per-process env overrides (`nice-commander env`, the UI's knob fields). */\n  envOverridesPath: string;\n  /** Pinned tag groups and recent runs from the web UI. */\n  savedFiltersPath: string;\n  /** When each process was last started — the UI's \"recent\" order, across daemon restarts. */\n  lastStartsPath: string;\n  /** Each task's latest successful run times — the running task's estimate, across restarts. */\n  taskDurationsPath: string;\n}\n\nexport function commanderStatePaths(dataDir: string, configKey: string): ICommanderStatePaths {\n  const base = isAbsolute(dataDir) ? dataDir : resolve(dataDir);\n  const stateDir = join(base, configKey);\n  return {\n    stateDir,\n    instanceRecordPath: join(stateDir, \"instance.json\"),\n    ledgerNamespace: configKey,\n    daemonLogDir: join(stateDir, \"daemon-log\"),\n    logsDir: join(stateDir, \"logs\"),\n    upLockPath: join(stateDir, \"up.lock\"),\n    bootLogPath: join(stateDir, \"daemon-boot.log\"),\n    ingestSeqPath: join(stateDir, \"ingest-seq\"),\n    envOverridesPath: join(stateDir, \"env-overrides.json\"),\n    savedFiltersPath: join(stateDir, \"saved-filters.json\"),\n    lastStartsPath: join(stateDir, \"last-starts.json\"),\n    taskDurationsPath: join(stateDir, \"task-durations.json\"),\n  };\n}\n\nexport async function ensureStateDir(paths: ICommanderStatePaths): Promise<void> {\n  await mkdir(paths.stateDir, { recursive: true, mode: 0o700 });\n  await mkdir(paths.logsDir, { recursive: true, mode: 0o700 });\n}\n","/** Check before advertising a daemon whose HTTP works but whose wire handshake cannot run. */\nexport function commanderRuntimeError(): string | undefined {\n  const runtime =\n    process.versions.bun == null ? `Node ${process.version}` : `Bun ${process.versions.bun}`;\n  if (\n    (process.versions.bun == null && Number(process.versions.node.split(\".\")[0]) < 22) ||\n    globalThis.crypto?.subtle == null ||\n    typeof globalThis.WebSocket !== \"function\"\n  ) {\n    return (\n      `nice-commander requires Node >=22 or a current Bun with Web Crypto and WebSocket support; ` +\n      `running ${runtime} (${process.execPath}). Upgrade Node, or run \\`bunx --bun nice-commander\\`. ` +\n      `Plain \\`bunx\\` follows the binary's node shebang. If a daemon is already running, ` +\n      `run \\`nice-commander shutdown\\` before retrying; shutdown stops its managed processes.`\n    );\n  }\n  return undefined;\n}\n","// The status realm (D1): one server-owned tree every observer (CLI `status`, N browser tabs)\n// attaches to read-only. Bounded, low-churn state only — no log lines, no tails, no env values\n// ever (a realm is a state plane, not an append stream and not a secret store). Log volume\n// lives on the `/logs` lane; this tree carries cursors and verdicts.\n\nimport { defineRealm, t } from \"@nice-code/realm\";\nimport type { ISavedFilter } from \"./savedFilters\";\n\nexport interface IStatusEndpoint {\n  name: string;\n  protocol: string;\n  host: string;\n  port: number;\n  ownership: string;\n  /** Present for http(s) only — a tcp port is not something a browser can open. */\n  url?: string;\n}\n\n/**\n * One declared env knob. ⚠ `value` is present only for a NON-secret variable whose value this\n * config supplied — a declared default, or an override someone set here. A secret never carries\n * one, and neither does an `inherited` variable: that value comes from the daemon's own\n * environment, which is the thing this realm refuses to broadcast.\n */\nexport interface IStatusEnvVar {\n  name: string;\n  description?: string;\n  secret: boolean;\n  required: boolean;\n  values?: string[];\n  source: string;\n  value?: string;\n}\n\n/**\n * The resolved definition, so a viewer can answer \"what is this, exactly?\" without opening the\n * config. Low-churn (it moves only on a reload or an override change). ⚠ Never the resolved\n * `env` — only the `envVars` the config declared, filtered as above.\n */\nexport interface IStatusDetail {\n  command: string;\n  cwd: string;\n  dependsOn: string[];\n  /** The definition's own `url`, when declared — the primary link when no endpoint carries one. */\n  url?: string;\n  ready?: string;\n  endpoints: IStatusEndpoint[];\n  envVars: IStatusEnvVar[];\n  /** Declared flags — what a start may turn on, and the arguments each appends. */\n  flags: IStatusFlag[];\n  /** Tasks only: the run's hard cap — the UI draws elapsed/timeout from it. */\n  timeoutMs?: number;\n}\n\nexport interface IStatusFlag {\n  name: string;\n  /** The arguments it appends, joined for display. */\n  args: string;\n  description?: string;\n}\n\nexport type TStatusRunOutcome = \"succeeded\" | \"failed\" | \"stopped\" | \"crashed\" | \"timedOut\";\n\n/**\n * One recent run of a process, newest-last in a small bounded ring (the daemon caps it — this\n * is a state plane, not a log). `endedAt`/`outcome` are absent while the run is live; `timedOut`\n * is a peer of `failed` so a timeline can paint \"hung and killed\" apart from \"ran and failed\".\n */\nexport interface IStatusRun {\n  startedAt: number;\n  endedAt?: number;\n  outcome?: TStatusRunOutcome;\n}\n\n/**\n * How a task's most recent run ended — kept after the run so a viewer can answer \"what\n * happened\" without the start reply that carried it (a timeout kill otherwise reads as a bare\n * expected stop).\n */\nexport interface IStatusLastTask {\n  outcome: string;\n  reason?: string;\n  timedOut: boolean;\n  endedAt: number;\n  durationMs?: number;\n}\n\n/** One process entry — the supervisor's ISupervisedStatus with nulls mapped to absent fields. */\nexport interface IStatusProcessNode {\n  kind: string;\n  state: string;\n  pid?: number;\n  startedAt?: number;\n  /**\n   * The last start request that spawned. Persisted, so unlike `startedAt` and `recentRuns` it\n   * survives a daemon restart — the \"recent\" order. Absent = never started.\n   */\n  lastStartedAt?: number;\n  /** The flags the current (or most recent) run started with; `[]` for a plain run. */\n  flags: string[];\n  /**\n   * Tasks only: the mean of the latest successful runs with those flags — what a running task's\n   * progress fills toward. Absent until one has succeeded.\n   */\n  estimatedMs?: number;\n  /** First output of the current run; absent = the run has printed nothing (yet). */\n  sawOutputAt?: number;\n  lastTask?: IStatusLastTask;\n  /** Bounded ring of recent runs (newest last) — powers the UI's 30-minute timeline. */\n  recentRuns: IStatusRun[];\n  restarts: number;\n  lastExit?: { code?: number; signal?: string; expected: boolean };\n  stale: boolean;\n  removed: boolean;\n  envDrift: boolean;\n  blockedBy?: string;\n  /** Why the latest start attempt did not spawn; absent once a start succeeds or it is stopped. */\n  startError?: string;\n  degradedBy: string[];\n  unreadyReason?: string;\n  capability?: { treeMechanism: string; degraded: boolean; notes: string[] };\n  /** Every value a list — a single-valued tag is a list of one. */\n  tags: Record<string, string[]>;\n  /** Never a member of a bulk action — see `ICommanderProcessDefinition.optIn`. */\n  optIn: boolean;\n  detail: IStatusDetail;\n}\n\nexport interface TCommanderStatusState {\n  /** Daemon incarnation — pairs with the aggregate log timeline's major key. */\n  generation: number;\n  /** Config name — so a browser tab title can say which project this dashboard is for. */\n  configName: string;\n  configRevisionHash: string;\n  /** Validation errors from the latest config reload attempt; empty = last-good is clean. */\n  configError: string[];\n  processes: Record<string, IStatusProcessNode>;\n  suites: Record<string, IStatusSuite>;\n  /**\n   * The latest run per key — a suite name, or a saved filter's id for a tag-group run. Bounded by\n   * the daemon. A run with no `endedAt` is live, and that is what marks its members' rows.\n   */\n  runs: Record<string, IStatusRun_Suite>;\n  savedFilters: ISavedFilter[];\n}\n\nexport interface IStatusSuite {\n  description?: string;\n  /** DAG order — the order a run starts them in. */\n  members: string[];\n  parallel: number;\n  failFast: boolean;\n}\n\nexport type TRunMemberVerdict = \"pending\" | \"running\" | \"pass\" | \"fail\" | \"blocked\" | \"skipped\";\n\nexport interface IStatusRun_Suite {\n  /** The suite's name; absent for a tag-group run. */\n  suite?: string;\n  /** The saved filter a tag-group run came from — how a bucket heading finds its own run. */\n  filterId?: string;\n  startedAt: number;\n  endedAt?: number;\n  outcome?: \"passed\" | \"failed\";\n  /** How long the previous run under this key took — the card's \"vs last\" reference. */\n  previousDurationMs?: number;\n  members: Record<string, TRunMemberVerdict>;\n}\n\n/**\n * Read-only viewer for every authenticated identity — control authority lives in the ticket\n * gate at the upgrade, the realm floor (`authenticated`) just guarantees a real wire identity\n * behind every attach. No intents: clients never write.\n */\nexport const commanderStatusRealm = defineRealm({\n  id: \"commander_status\",\n  avatars: { viewer: { persistentId: t.string() } },\n  state: {\n    generation: t.number(),\n    configName: t.string(),\n    configRevisionHash: t.string(),\n    configError: t.array(t.string()),\n    processes: t.record(\n      t.id(\"processId\"),\n      t.object({\n        kind: t.string(),\n        state: t.string(),\n        pid: t.optional(t.number()),\n        startedAt: t.optional(t.number()),\n        lastStartedAt: t.optional(t.number()),\n        flags: t.array(t.string()),\n        estimatedMs: t.optional(t.number()),\n        sawOutputAt: t.optional(t.number()),\n        lastTask: t.optional(\n          t.object({\n            outcome: t.string(),\n            reason: t.optional(t.string()),\n            timedOut: t.boolean(),\n            endedAt: t.number(),\n            durationMs: t.optional(t.number()),\n          }),\n        ),\n        recentRuns: t.array(\n          t.object({\n            startedAt: t.number(),\n            endedAt: t.optional(t.number()),\n            outcome: t.optional(\n              t.union(\n                t.literal(\"succeeded\"),\n                t.literal(\"failed\"),\n                t.literal(\"stopped\"),\n                t.literal(\"crashed\"),\n                t.literal(\"timedOut\"),\n              ),\n            ),\n          }),\n        ),\n        restarts: t.number(),\n        lastExit: t.optional(\n          t.object({\n            code: t.optional(t.number()),\n            signal: t.optional(t.string()),\n            expected: t.boolean(),\n          }),\n        ),\n        stale: t.boolean(),\n        removed: t.boolean(),\n        envDrift: t.boolean(),\n        blockedBy: t.optional(t.string()),\n        startError: t.optional(t.string()),\n        degradedBy: t.array(t.string()),\n        unreadyReason: t.optional(t.string()),\n        capability: t.optional(\n          t.object({\n            treeMechanism: t.string(),\n            degraded: t.boolean(),\n            notes: t.array(t.string()),\n          }),\n        ),\n        tags: t.record(t.id(\"tag\"), t.array(t.string())),\n        optIn: t.boolean(),\n        detail: t.object({\n          command: t.string(),\n          cwd: t.string(),\n          dependsOn: t.array(t.string()),\n          url: t.optional(t.string()),\n          ready: t.optional(t.string()),\n          timeoutMs: t.optional(t.number()),\n          endpoints: t.array(\n            t.object({\n              name: t.string(),\n              protocol: t.string(),\n              host: t.string(),\n              port: t.number(),\n              ownership: t.string(),\n              url: t.optional(t.string()),\n            }),\n          ),\n          envVars: t.array(\n            t.object({\n              name: t.string(),\n              description: t.optional(t.string()),\n              secret: t.boolean(),\n              required: t.boolean(),\n              values: t.optional(t.array(t.string())),\n              source: t.string(),\n              value: t.optional(t.string()),\n            }),\n          ),\n          flags: t.array(\n            t.object({\n              name: t.string(),\n              args: t.string(),\n              description: t.optional(t.string()),\n            }),\n          ),\n        }),\n      }),\n    ),\n    suites: t.record(\n      t.id(\"suiteName\"),\n      t.object({\n        description: t.optional(t.string()),\n        members: t.array(t.string()),\n        parallel: t.number(),\n        failFast: t.boolean(),\n      }),\n    ),\n    runs: t.record(\n      t.id(\"runKey\"),\n      t.object({\n        suite: t.optional(t.string()),\n        filterId: t.optional(t.string()),\n        startedAt: t.number(),\n        endedAt: t.optional(t.number()),\n        outcome: t.optional(t.union(t.literal(\"passed\"), t.literal(\"failed\"))),\n        previousDurationMs: t.optional(t.number()),\n        members: t.record(\n          t.id(\"processId\"),\n          t.union(\n            t.literal(\"pending\"),\n            t.literal(\"running\"),\n            t.literal(\"pass\"),\n            t.literal(\"fail\"),\n            t.literal(\"blocked\"),\n            t.literal(\"skipped\"),\n          ),\n        ),\n      }),\n    ),\n    savedFilters: t.array(\n      t.object({\n        id: t.string(),\n        name: t.optional(t.string()),\n        mode: t.union(t.literal(\"all\"), t.literal(\"any\")),\n        terms: t.array(t.string()),\n        bucket: t.optional(t.array(t.string())),\n        pinned: t.boolean(),\n        lastRunAt: t.optional(t.number()),\n      }),\n    ),\n  },\n  rules: (r) => [r.path(\"**\").view(r.everyone).alter(r.serverOnly)],\n});\n","// Cross-process file lock (the stateStore.ts precedent, G3): exclusive-create, owner-liveness\n// (a stale lock is unlinked only when the recorded pid is DEAD — age never proves death),\n// id-checked release so a late releaser never unlinks a replacement owner.\n\nimport { randomUUID } from \"node:crypto\";\nimport { mkdir, open, readFile, rename, unlink } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\n\nconst LOCK_RETRY_LIMIT = 250; // ~10 s at the default interval — an `up` spawn can be slow\nconst LOCK_RETRY_MS = 40;\n\ninterface ILockOwner {\n  id: string;\n  pid: number;\n  acquiredAt: number;\n}\n\nfunction pidAlive(pid: number): boolean {\n  if (!Number.isInteger(pid) || pid <= 0) return false;\n  try {\n    process.kill(pid, 0);\n    return true;\n  } catch (error) {\n    return (error as NodeJS.ErrnoException).code === \"EPERM\";\n  }\n}\n\nconst wait = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));\n\n/**\n * Drop a dead owner's lock atomically (M3). A plain `unlink` let two waiters that both diagnosed\n * the same corpse each delete a lock — the second deleting the FIRST's freshly created one, so\n * both entered the critical section together. `rename` is atomic: exactly one waiter claims a\n * given file, and anything that turns out not to be the diagnosed corpse is put back.\n */\nasync function stealStaleLock(path: string, deadOwnerId: string): Promise<void> {\n  const claim = `${path}.stale-${randomUUID()}`;\n  try {\n    await rename(path, claim);\n  } catch {\n    return; // another waiter claimed it first — retry the exclusive create\n  }\n  let stolen: Partial<ILockOwner> | null = null;\n  try {\n    stolen = JSON.parse(await readFile(claim, \"utf8\")) as Partial<ILockOwner>;\n  } catch {\n    // Unreadable: treat as the corpse and drop it below.\n  }\n  if (stolen != null && stolen.id !== deadOwnerId) {\n    await rename(claim, path).catch(() => unlink(claim).catch(() => {}));\n    return;\n  }\n  await unlink(claim).catch(() => {});\n}\n\nexport class CommanderLockBusyError extends Error {\n  constructor(path: string) {\n    super(`commander lock is busy: ${path}`);\n    this.name = \"CommanderLockBusyError\";\n  }\n}\n\n/** Serialize a cross-process critical section on `path` (e.g. ensure-daemon in `up`). */\nexport async function withCommanderLock<T>(path: string, action: () => Promise<T>): Promise<T> {\n  await mkdir(dirname(path), { recursive: true, mode: 0o700 });\n  const owner: ILockOwner = { id: randomUUID(), pid: process.pid, acquiredAt: Date.now() };\n  let acquired = false;\n  for (let attempt = 0; attempt < LOCK_RETRY_LIMIT; attempt += 1) {\n    try {\n      const handle = await open(path, \"wx\", 0o600);\n      await handle.writeFile(JSON.stringify(owner), \"utf8\");\n      await handle.close();\n      acquired = true;\n      break;\n    } catch (error) {\n      if ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n      let current: Partial<ILockOwner> | null = null;\n      try {\n        current = JSON.parse(await readFile(path, \"utf8\")) as Partial<ILockOwner>;\n      } catch {\n        // A creator may sit between exclusive create and writing its owner — retry first.\n      }\n      if (current?.pid != null && current.id != null && !pidAlive(current.pid)) {\n        await stealStaleLock(path, current.id);\n        continue;\n      }\n      await wait(LOCK_RETRY_MS);\n    }\n  }\n  if (!acquired) throw new CommanderLockBusyError(path);\n  try {\n    return await action();\n  } finally {\n    try {\n      const current = JSON.parse(await readFile(path, \"utf8\")) as Partial<ILockOwner>;\n      if (current.id === owner.id) await unlink(path);\n    } catch {\n      // A missing lock is already released; never unlink a replacement owner blindly.\n    }\n  }\n}\n","// Ensure-daemon (the CLI's reuse-or-spawn path, serialized on the up lock): a live record +\n// pid/startStamp liveness + an authed ping means reuse; anything else spawns a fresh detached\n// daemon and waits for its record/handshake, surfacing the boot log on a boot failure.\n\nimport { type ChildProcess, spawn } from \"node:child_process\";\nimport { closeSync, openSync, readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { openProcessLedger, signalProcessGroup, taskkillTree } from \"@nice-code/process\";\nimport type { IResolvedCommanderConfig } from \"../config/types\";\nimport { commanderStatusRealm } from \"../protocol/statusRealm\";\nimport { findDaemonProcesses, orphanMessage } from \"./daemonProcesses\";\nimport {\n  commanderStatePaths,\n  ensureStateDir,\n  type ICommanderStatePaths,\n  resolveCommanderDataDir,\n} from \"./dataDir\";\nimport {\n  COMMANDER_PROTOCOL_VERSION,\n  type ICommanderInstanceRecord,\n  type ISkewedInstanceRecord,\n  pidAlive,\n  pingDaemon,\n  readInstanceRecord,\n  readSkewedInstanceRecord,\n  recordDaemonAlive,\n  signalDaemonShutdown,\n} from \"./instanceRecord\";\nimport { withCommanderLock } from \"./lockfile\";\nimport { commanderRuntimeError } from \"./runtime\";\n\nconst HANDSHAKE_TIMEOUT_MS = 15_000;\nconst POLL_MS = 100;\n/** Grace for a boot child to run its own ladder before the tree is taken by force. */\nconst BOOT_KILL_GRACE_MS = 3_000;\n\n/**\n * Kill a boot child that never handshaked (M4's other half). A timeout is not proof of death —\n * the child may just be SLOW, and one that binds a minute later would then be supervising this\n * config invisibly, with nothing but its pid to find it by, while the CLI reported \"boot failed\".\n *\n * SIGTERM first, because a daemon far enough along to have started children runs its own shutdown\n * ladder over them; SIGKILL only for one too wedged to answer. Detached ⇒ the child leads its own\n * group (POSIX) / tree (Windows), so this reaches what it spawned.\n */\nasync function stopBootChild(child: ChildProcess): Promise<void> {\n  const pid = child.pid;\n  if (pid == null) return;\n  const exited = new Promise<boolean>((settle) => {\n    if (child.exitCode != null || child.signalCode != null) return settle(true);\n    child.once(\"exit\", () => settle(true));\n    setTimeout(() => settle(false), BOOT_KILL_GRACE_MS).unref();\n  });\n  try {\n    if (process.platform === \"win32\") {\n      await taskkillTree(pid);\n      return;\n    }\n    signalProcessGroup(pid, \"SIGTERM\");\n    if (!(await exited)) signalProcessGroup(pid, \"SIGKILL\");\n  } catch {\n    // Best effort: the boot error the caller is about to throw is the report that matters.\n  }\n}\n\nexport interface IEnsureDaemonOptions {\n  /** The resolved config the caller already loaded (its configKey names the state dir). */\n  config: IResolvedCommanderConfig;\n  dataDir?: string;\n  /**\n   * How to launch the daemon: `<runtime> <script> daemon …` — production passes the CLI's own\n   * path; tests pass a fixture shim that imports the sources.\n   */\n  daemonScript: string;\n  handshakeTimeoutMs?: number;\n}\n\nexport interface IEnsureDaemonResult {\n  record: ICommanderInstanceRecord;\n  reused: boolean;\n  paths: ICommanderStatePaths;\n  /** A skewed idle daemon this call stopped and replaced — the CLI narrates it. */\n  replaced?: { pid: number; packageVersion: string };\n}\n\nexport class CommanderDaemonBootError extends Error {\n  constructor(\n    message: string,\n    readonly bootLogTail: string,\n  ) {\n    super(message);\n    this.name = \"CommanderDaemonBootError\";\n  }\n}\n\n/**\n * Stop a skewed daemon so the boot below can proceed — ONLY when nothing of it is running.\n * \"Running\" is answered by the ledger, the one surface both builds share regardless of wire\n * protocol: any record whose pid is alive (a supervised child, or a foreground `run` lease) is\n * a live dev environment, and an upgrade must never be the thing that kills one.\n */\nasync function replaceSkewedDaemon(\n  paths: ICommanderStatePaths,\n  skewed: ISkewedInstanceRecord,\n): Promise<IEnsureDaemonResult[\"replaced\"]> {\n  const daemonLabel =\n    `the daemon for this config (pid ${skewed.pid}, build ${skewed.packageVersion}, ` +\n    `protocol v${skewed.protocolVersion}) predates this CLI (protocol ` +\n    `v${COMMANDER_PROTOCOL_VERSION}${skewed.skew === \"realm-schema\" ? \", different status schema\" : \"\"})`;\n  let liveIds: string[];\n  try {\n    const ledger = openProcessLedger({ dir: paths.stateDir, namespace: paths.ledgerNamespace });\n    liveIds = (await ledger.list())\n      .filter((record) => pidAlive(record.pid))\n      .map((record) => record.id);\n  } catch {\n    // An unreadable ledger cannot prove idleness — refuse below rather than kill into the dark.\n    throw new Error(\n      `${daemonLabel}, and its ledger could not be read to prove nothing is running. ` +\n        \"Run `nice-commander shutdown` (it stops the daemon and everything it runs), then retry.\",\n    );\n  }\n  if (liveIds.length > 0) {\n    throw new Error(\n      `${daemonLabel} and is still running: ${liveIds.join(\", \")}. Replacing it would stop ` +\n        \"them. Run `nice-commander shutdown` when you are ready (it stops the daemon and \" +\n        \"everything it runs), then `up` again.\",\n    );\n  }\n  const result = await signalDaemonShutdown({ pid: skewed.pid, startStamp: skewed.startStamp });\n  switch (result.outcome) {\n    case \"exited\":\n      return { pid: skewed.pid, packageVersion: skewed.packageVersion };\n    case \"not-running\":\n      return undefined; // it died on its own — the stale record is handled by the boot below\n    case \"still-stopping\":\n      throw new Error(\n        `${daemonLabel}; nothing of it is running, so it was asked to shut down — but it is ` +\n          \"still stopping. Retry in a moment (a second attempt escalates).\",\n      );\n    case \"identity-unverified\":\n      throw new Error(\n        `${daemonLabel}, but pid ${skewed.pid} could not be verified as that daemon (start ` +\n          \"stamp missing or changed — possibly pid reuse). Nothing was killed. Verify the pid \" +\n          `yourself, and if the daemon is really gone remove ${paths.instanceRecordPath}.`,\n      );\n  }\n}\n\n/** How long `ensureDaemon` lets a record-less daemon finish exiting before calling it an orphan. */\nconst ORPHAN_GRACE_MS = 5_000;\n\nasync function waitForOrphansToExit(configPath: string, dataDir: string, recordedPid?: number) {\n  const deadline = Date.now() + ORPHAN_GRACE_MS;\n  for (;;) {\n    const orphans = await findDaemonProcesses(configPath, dataDir, recordedPid);\n    if (orphans.length === 0 || Date.now() > deadline) return orphans;\n    await new Promise((resolveWait) => setTimeout(resolveWait, 250));\n  }\n}\n\nexport async function ensureDaemon(options: IEnsureDaemonOptions): Promise<IEnsureDaemonResult> {\n  const runtimeError = commanderRuntimeError();\n  if (runtimeError != null) throw new Error(runtimeError);\n  const dataDir = options.dataDir != null ? resolve(options.dataDir) : resolveCommanderDataDir();\n  const paths = commanderStatePaths(dataDir, options.config.configKey);\n  const timeoutMs = options.handshakeTimeoutMs ?? HANDSHAKE_TIMEOUT_MS;\n\n  return withCommanderLock(paths.upLockPath, async () => {\n    const existing = await readInstanceRecord(paths.instanceRecordPath);\n    // Reuse needs more than a valid record: the daemon must speak THIS build's status schema —\n    // a record passes shape validation with any hash, so the comparison lives here.\n    const compatible =\n      existing != null && existing.realmSchemaHash === commanderStatusRealm.schemaHash;\n    if (compatible && (await recordDaemonAlive(existing))) {\n      const ping = await pingDaemon(existing);\n      if (ping != null) return { record: existing, reused: true, paths };\n    }\n    // A daemon this build cannot talk to — another protocol version, or the same protocol with\n    // a different status-realm schema (a change whose bump was forgotten) — is IN THE WAY, not\n    // absent (edge 18). Booting past it would collide on its port and report `EADDRINUSE` —\n    // true, but about the wrong problem. When it is IDLE it is replaced right here (the upgrade\n    // path should just work); with live processes it is refused BY NAME, because replacing the\n    // daemon would kill a dev environment nobody asked to stop.\n    let replaced: IEnsureDaemonResult[\"replaced\"];\n    if (!compatible) {\n      const skewed = await readSkewedInstanceRecord(\n        paths.instanceRecordPath,\n        commanderStatusRealm.schemaHash,\n      );\n      if (skewed != null && pidAlive(skewed.pid)) {\n        replaced = await replaceSkewedDaemon(paths, skewed);\n      }\n    }\n    // A daemon that lost its record is in the way just the same, and booting past it is how it\n    // got lost: the newcomer takes the next free port, overwrites the record, and a later\n    // shutdown deletes it — leaving the first one running where no lookup can see it. Grace\n    // first: a daemon that just removed its record on shutdown is still walking its ladder.\n    const recordedPid = existing != null ? existing.pid : undefined;\n    const orphans = await waitForOrphansToExit(options.config.configPath, dataDir, recordedPid);\n    if (orphans.length > 0) throw new Error(orphanMessage(orphans));\n\n    // A stale record stays: the new daemon reads its generation off it, then atomically\n    // replaces it after binding.\n\n    await ensureStateDir(paths);\n    // Boot-error handoff: the daemon's early stderr lands here until its own logger opens.\n    // Opened TRUNCATING (and only ever from here, under the up lock) so the handoff stays the\n    // small fixed thing it is documented to be — appending left one file accumulating every\n    // boot of every daemon this state dir ever had, with no rotation to bound it.\n    const bootFd = openSync(paths.bootLogPath, \"w\", 0o600);\n    const child = spawn(\n      process.execPath,\n      [\n        options.daemonScript,\n        \"daemon\",\n        \"--config\",\n        options.config.configPath,\n        \"--data-dir\",\n        dataDir,\n      ],\n      { detached: true, stdio: [\"ignore\", bootFd, bootFd], windowsHide: true },\n    );\n    child.unref();\n    // The child dup'd the fd during spawn; the parent's copy is a leak on a CLI that may go on\n    // to do other work, and on Windows it keeps a handle on a file the next boot wants to truncate.\n    try {\n      closeSync(bootFd);\n    } catch {\n      // already gone — nothing to release\n    }\n    let exited: number | null = null;\n    child.on(\"exit\", (code) => {\n      exited = code ?? -1;\n    });\n\n    const deadline = Date.now() + timeoutMs;\n    for (;;) {\n      const record = await readInstanceRecord(paths.instanceRecordPath);\n      if (record != null && record.pid === child.pid) {\n        const ping = await pingDaemon(record);\n        if (ping != null) {\n          return { record, reused: false, paths, ...(replaced != null ? { replaced } : {}) };\n        }\n      }\n      if (exited != null) {\n        let tail = \"\";\n        try {\n          tail = readFileSync(paths.bootLogPath, \"utf8\").split(\"\\n\").slice(-20).join(\"\\n\").trim();\n        } catch {\n          // no boot log — the error below stands alone\n        }\n        throw new CommanderDaemonBootError(\n          `daemon exited during boot (code ${exited})${tail === \"\" ? \"\" : `:\\n${tail}`}`,\n          tail,\n        );\n      }\n      if (Date.now() > deadline) {\n        await stopBootChild(child);\n        throw new CommanderDaemonBootError(\n          `daemon did not write its instance record within ${timeoutMs} ms (its process tree was stopped)`,\n          \"\",\n        );\n      }\n      await new Promise((resolveWait) => setTimeout(resolveWait, POLL_MS));\n    }\n  });\n}\n","// Auth surface constants shared by the daemon (which enforces them) and the CLI/UI clients\n// (which dial them). The token/capability/ticket VALUES never appear here — only the shapes.\n\n/** The wire socket (control actions + status realm on one connection, D1). */\nexport const COMMANDER_WS_PATH = \"/wire\";\n/** The log socket (D5) — a separate plain-JSON lane, same ticket gate. */\nexport const COMMANDER_LOGS_PATH = \"/logs\";\n/** Credential-free, no-store, same-origin-guarded bootstrap that mints a browser capability. */\nexport const COMMANDER_BOOTSTRAP_PATH = \"/bootstrap\";\n/** Exchanges a capability or the root token for a one-use ws ticket. */\nexport const COMMANDER_TICKET_PATH = \"/ticket\";\n/** CLI liveness/discovery probe (instance-record root token only). */\nexport const COMMANDER_HEALTH_PATH = \"/health\";\n/**\n * Plain-HTTP shutdown, capability-gated. It needs no realm, so a page from another build — one\n * that can never attach the status realm — can still stop the daemon it is stuck on.\n */\nexport const COMMANDER_SHUTDOWN_PATH = \"/shutdown\";\n\n/**\n * ws tickets ride the subprotocol negotiation (browsers cannot set arbitrary ws headers):\n * the client offers `commander-auth.<ticket>`, the daemon selects it to complete the upgrade.\n */\nexport const COMMANDER_TICKET_PROTOCOL_PREFIX = \"commander-auth.\";\n","/** A short-lived inspection token selects one verified listener, never an arbitrary PID. */\nexport interface IPortListener {\n  id: string;\n  endpoint: string;\n  host: string;\n  port: number;\n  pid: number;\n  command: string;\n  ppid: number | null;\n  cwd: string | null;\n  startStamp: string | null;\n  /**\n   * A stray: this definition's own command (argv + cwd), running outside the daemon. `strayRoot`\n   * is the pid in the listener's ancestry that matched — the listener itself, or the wrapper\n   * (`bun run dev`) that spawned it. A stray is stopped as that tree; a stranger only as `pid`.\n   */\n  stray: boolean;\n  strayRoot: number | null;\n  token: string | null;\n  refusal: string | null;\n}\nexport interface IPortsInput {\n  ids: string[];\n  token?: string;\n  force?: boolean;\n}\nexport interface IPortsReport {\n  listeners: IPortListener[];\n  warnings: string[];\n}\nexport function checkPortsInput(value: unknown): IPortsInput | string {\n  if (value == null || typeof value !== \"object\") return \"expected an object\";\n  const v = { ...value } as Record<string, unknown>;\n  if (!Array.isArray(v.ids) || !v.ids.every((id) => typeof id === \"string\" && id.length > 0))\n    return \"expected ids\";\n  if (v.token != null && (typeof v.token !== \"string\" || !v.token)) return \"expected token\";\n  if (v.force != null && typeof v.force !== \"boolean\") return \"expected force boolean\";\n  if (v.force && !v.token) return \"force requires a listener token\";\n  return {\n    ids: v.ids,\n    ...(typeof v.token === \"string\" ? { token: v.token } : {}),\n    ...(typeof v.force === \"boolean\" ? { force: v.force } : {}),\n  };\n}\nexport function checkPortsReport(value: unknown): IPortsReport | string {\n  if (value == null || typeof value !== \"object\") return \"expected an object\";\n  const v = { ...value } as Record<string, unknown>;\n  if (\n    !Array.isArray(v.warnings) ||\n    !v.warnings.every((s) => typeof s === \"string\") ||\n    !Array.isArray(v.listeners)\n  )\n    return \"expected listeners and warnings\";\n  const listeners: IPortListener[] = [];\n  for (const item of v.listeners) {\n    if (item == null || typeof item !== \"object\") return \"invalid listener\";\n    const r = { ...item } as Record<string, unknown>;\n    if (\n      ![r.id, r.endpoint, r.host, r.command].every((s) => typeof s === \"string\") ||\n      !Number.isInteger(r.pid) ||\n      Number(r.pid) < 1 ||\n      !Number.isInteger(r.port) ||\n      Number(r.port) < 1 ||\n      Number(r.port) > 65535 ||\n      !(r.ppid === null || (Number.isInteger(r.ppid) && Number(r.ppid) >= 0)) ||\n      !(r.cwd === null || typeof r.cwd === \"string\") ||\n      typeof r.stray !== \"boolean\" ||\n      !(r.strayRoot === null || (Number.isInteger(r.strayRoot) && Number(r.strayRoot) >= 1)) ||\n      ![r.startStamp, r.token, r.refusal].every((s) => s === null || typeof s === \"string\")\n    )\n      return \"invalid listener\";\n    listeners.push(item as IPortListener);\n  }\n  return { listeners, warnings: v.warnings };\n}\n","// The control action channel (D1): `start`/`stop`/`restart` × explicit id sets (the daemon\n// closes over transitive dependencies and DAG-orders), `runSuite`, `reloadConfig`, `shutdown`. Typed,\n// acked, idempotent — the supervisor makes every effect overlap-safe, so a retried or\n// double-fired action converges instead of corrupting state. Failures arrive as values\n// (per-id outcomes), never as thrown action errors.\n\nimport { actionSchema, createActionRootDomain, defineChannel } from \"@nice-code/action\";\nimport { checkPortsInput, checkPortsReport } from \"./ports\";\nimport { checkSavedFilterQuery, type TSavedFilterQuery } from \"./savedFilters\";\n\n/**\n * Per-request timeout for control actions, passed as the channel's `defaultTimeout` by BOTH\n * clients (the CLI's daemonClient and the web session).\n *\n * ⚠ Without this, every control request inherited the wire stack's 10 s\n * `DEFAULT_TRANSPORT_TIMEOUT` — and `start`/`up` of a real group legitimately runs for minutes,\n * so the client aborted with \"transport timed out\" while the daemon carried on and the status\n * realm streamed live progress into the same UI (REVIEW-AND-FIX F2). A verdict-bearing RPC gets a\n * deadline sized for the work it names, not for a ping. Fifteen minutes matches the largest\n * `timeoutMs` any row in a config is likely to carry; a daemon that is actually gone still fails\n * fast through the link layer, not through this.\n */\nexport const COMMANDER_CONTROL_TIMEOUT_MS = 900_000;\n\nexport type TActionOutcome =\n  | \"ready\"\n  | \"spawned\"\n  | \"already-running\"\n  | \"blocked\"\n  | \"failed\"\n  | \"succeeded\"\n  | \"stopped\"\n  | \"already-stopped\";\n\nexport interface IProcessActionResult {\n  id: string;\n  outcome: TActionOutcome;\n  reason?: string;\n}\n\nexport interface IActionReport {\n  results: IProcessActionResult[];\n  warnings: string[];\n}\n\n/**\n * Structural mirror of StandardSchemaV1 — the action stack consumes schemas structurally, and\n * hand-rolling keeps a validation library out of the daemon (config validation is hand-rolled\n * for the same reason). The phantom `types` field carries inference; it never exists at runtime.\n */\ninterface IHandSchema<T> {\n  readonly \"~standard\": {\n    readonly version: 1;\n    readonly vendor: string;\n    readonly validate: (\n      value: unknown,\n    ) => { readonly value: T } | { readonly issues: readonly { readonly message: string }[] };\n    readonly types?: { readonly input: T; readonly output: T } | undefined;\n  };\n}\n\nfunction handSchema<T>(check: (value: unknown) => T | string): IHandSchema<T> {\n  return {\n    \"~standard\": {\n      version: 1,\n      vendor: \"nice-commander\",\n      validate: (value) => {\n        const result = check(value);\n        return typeof result === \"string\" ? { issues: [{ message: result }] } : { value: result };\n      },\n    },\n  };\n}\n\nfunction asIdList(value: unknown): string[] | null {\n  if (!Array.isArray(value)) return null;\n  const ids: string[] = [];\n  for (const entry of value) {\n    if (typeof entry !== \"string\" || entry === \"\") return null;\n    ids.push(entry);\n  }\n  return ids;\n}\n\ninterface IStartInput {\n  ids: string[];\n  wait?: boolean;\n  staggerMs?: number;\n  /** Replace a stray (this definition's own command, outside the daemon) on an exclusive port. */\n  replaceSame?: boolean;\n  /**\n   * Declared flag names per id. An id without an entry starts plain — or, on `restart`, with the\n   * flags of its last run.\n   */\n  flags?: Record<string, string[]>;\n}\n\n/**\n * The one place `unknown` becomes something indexable. A shallow spread gets there by inference\n * rather than a cast, so no validator has to assert a shape it is in the middle of checking.\n * Control payloads are tiny id lists, so the copy costs nothing worth counting.\n */\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n  if (value == null || typeof value !== \"object\" || Array.isArray(value)) return null;\n  return { ...value };\n}\n\nfunction checkStart(value: unknown): IStartInput | string {\n  const record = asRecord(value);\n  if (record == null) return \"expected an object\";\n  const ids = asIdList(record[\"ids\"]);\n  if (ids == null) return \"ids: expected an array of process ids\";\n  const wait = record[\"wait\"];\n  if (wait != null && typeof wait !== \"boolean\") return \"wait: expected a boolean\";\n  const staggerMs = record[\"staggerMs\"];\n  if (staggerMs != null && (typeof staggerMs !== \"number\" || staggerMs < 0))\n    return \"staggerMs: expected a non-negative number\";\n  const replaceSame = record[\"replaceSame\"];\n  if (replaceSame != null && typeof replaceSame !== \"boolean\") {\n    return \"replaceSame: expected a boolean\";\n  }\n  const input: IStartInput = { ids };\n  if (wait != null) input.wait = wait;\n  if (staggerMs != null) input.staggerMs = staggerMs;\n  if (replaceSame != null) input.replaceSame = replaceSame;\n  if (record[\"flags\"] != null) {\n    const flags = checkFlagsById(record[\"flags\"]);\n    if (typeof flags === \"string\") return `flags${flags}`;\n    input.flags = flags;\n  }\n  return input;\n}\n\nfunction checkFlagsById(value: unknown): Record<string, string[]> | string {\n  const record = asRecord(value);\n  if (record == null) return \": expected an object keyed by process id\";\n  const checked: Record<string, string[]> = {};\n  for (const [id, names] of Object.entries(record)) {\n    const list = asIdList(names);\n    if (list == null) return `[${JSON.stringify(id)}]: expected an array of flag names`;\n    checked[id] = list;\n  }\n  return checked;\n}\n\n/** A run the foreground `run` did on its own — see `noteRuns`. */\nexport interface IForegroundRun {\n  id: string;\n  startedAt: number;\n  /** Declared flag names, in declaration order. */\n  flags: string[];\n  /** Present only for a task that SUCCEEDED with declared flags only — the estimate's sample. */\n  durationMs?: number;\n}\n\nexport interface INoteRunsInput {\n  runs: IForegroundRun[];\n}\n\nfunction checkNoteRuns(value: unknown): INoteRunsInput | string {\n  const runs = asRecord(value)?.[\"runs\"];\n  if (!Array.isArray(runs)) return \"runs: expected an array\";\n  const checked: IForegroundRun[] = [];\n  for (const entry of runs) {\n    const run = asRecord(entry);\n    if (run == null) return \"runs: expected objects\";\n    const { id, startedAt, durationMs } = run;\n    const flags = asIdList(run[\"flags\"]);\n    if (typeof id !== \"string\" || id === \"\") return \"runs: id expected a process id\";\n    if (typeof startedAt !== \"number\" || !Number.isFinite(startedAt)) {\n      return \"runs: startedAt expected epoch ms\";\n    }\n    if (flags == null) return \"runs: flags expected an array of flag names\";\n    if (durationMs != null && (typeof durationMs !== \"number\" || !(durationMs >= 0))) {\n      return \"runs: durationMs expected a non-negative number\";\n    }\n    checked.push(\n      typeof durationMs === \"number\"\n        ? { id, startedAt, flags, durationMs }\n        : { id, startedAt, flags },\n    );\n  }\n  return { runs: checked };\n}\n\n/**\n * Sticky env-override mutations. A string sets, `null` drops the override back to the declared\n * default — distinct from a config `env` value of `null`, which SETS \"unset this for the child\".\n * `clear` empties an id entirely, and is the only thing that removes a stored entry the config can\n * no longer explain.\n */\nexport interface ISetEnvInput {\n  processes: Record<string, Record<string, string | null>>;\n  clear?: string[];\n}\n\nexport interface IEnvReport {\n  ok: true;\n  /** Refused mutations (undeclared name, unknown id, value outside a declared set). */\n  warnings: string[];\n}\n\nfunction checkSetEnv(value: unknown): ISetEnvInput | string {\n  const record = asRecord(value);\n  if (record == null) return \"expected an object\";\n  const processes = asRecord(record[\"processes\"]);\n  if (processes == null) return \"processes: expected an object keyed by process id\";\n  const checked: Record<string, Record<string, string | null>> = {};\n  for (const [id, values] of Object.entries(processes)) {\n    const entries = asRecord(values);\n    if (entries == null) return `processes[${JSON.stringify(id)}]: expected an object`;\n    const mutations: Record<string, string | null> = {};\n    for (const [name, entry] of Object.entries(entries)) {\n      if (entry !== null && typeof entry !== \"string\") {\n        return `processes[${JSON.stringify(id)}][${JSON.stringify(name)}]: expected string | null`;\n      }\n      mutations[name] = entry;\n    }\n    checked[id] = mutations;\n  }\n  const clear = record[\"clear\"];\n  if (clear == null) return { processes: checked };\n  const ids = asIdList(clear);\n  return ids == null\n    ? \"clear: expected an array of process ids\"\n    : { processes: checked, clear: ids };\n}\n\nfunction checkEnvReport(value: unknown): IEnvReport | string {\n  const record = asRecord(value);\n  if (record == null || record[\"ok\"] !== true) return \"expected { ok: true }\";\n  const warnings = record[\"warnings\"];\n  if (!Array.isArray(warnings) || !warnings.every((entry) => typeof entry === \"string\")) {\n    return \"warnings: expected an array of strings\";\n  }\n  return { ok: true, warnings };\n}\n\nexport interface IStopInput {\n  ids: string[];\n  /** Also stop what `ids` depend on — except a dependency some other live process still needs. */\n  withDependencies?: boolean;\n}\n\nfunction checkStop(value: unknown): IStopInput | string {\n  const record = asRecord(value);\n  if (record == null) return \"expected an object\";\n  const ids = asIdList(record[\"ids\"]);\n  if (ids == null) return \"ids: expected an array of process ids\";\n  const withDependencies = record[\"withDependencies\"];\n  if (withDependencies != null && typeof withDependencies !== \"boolean\") {\n    return \"withDependencies: expected a boolean\";\n  }\n  return withDependencies === true ? { ids, withDependencies } : { ids };\n}\n\nexport interface IRunSuiteInput {\n  /** A declared suite — it supplies the members and the policy. */\n  suite?: string;\n  /** A tag group's exact members, when no suite is named. */\n  ids?: string[];\n  parallel?: number;\n  failFast?: boolean;\n  /** The filter a tag-group run came from — recorded as a recent run. */\n  filter?: TSavedFilterQuery;\n}\n\nexport interface IRunSuiteReport {\n  accepted: boolean;\n  /** The key under `runs` on the status realm; progress and the verdict arrive there. */\n  runKey?: string;\n  reason?: string;\n}\n\nfunction checkRunSuite(value: unknown): IRunSuiteInput | string {\n  const record = asRecord(value);\n  if (record == null) return \"expected an object\";\n  const input: IRunSuiteInput = {};\n  const suite = record[\"suite\"];\n  if (suite != null) {\n    if (typeof suite !== \"string\" || suite === \"\") return \"suite: expected a suite name\";\n    input.suite = suite;\n  }\n  if (record[\"ids\"] != null) {\n    const ids = asIdList(record[\"ids\"]);\n    if (ids == null) return \"ids: expected an array of process ids\";\n    input.ids = ids;\n  }\n  if ((input.suite == null) === (input.ids == null)) return \"expected exactly one of suite | ids\";\n  const parallel = record[\"parallel\"];\n  if (parallel != null) {\n    if (typeof parallel !== \"number\" || !Number.isInteger(parallel) || parallel < 1) {\n      return \"parallel: expected an integer ≥ 1\";\n    }\n    input.parallel = parallel;\n  }\n  const failFast = record[\"failFast\"];\n  if (failFast != null) {\n    if (typeof failFast !== \"boolean\") return \"failFast: expected a boolean\";\n    input.failFast = failFast;\n  }\n  if (record[\"filter\"] != null) {\n    const filter = checkSavedFilterQuery(record[\"filter\"]);\n    if (typeof filter === \"string\") return `filter.${filter}`;\n    input.filter = filter;\n  }\n  return input;\n}\n\nfunction checkRunSuiteReport(value: unknown): IRunSuiteReport | string {\n  const record = asRecord(value);\n  if (record == null || typeof record[\"accepted\"] !== \"boolean\") return \"expected { accepted }\";\n  const { runKey, reason } = record;\n  return {\n    accepted: record[\"accepted\"],\n    ...(typeof runKey === \"string\" ? { runKey } : {}),\n    ...(typeof reason === \"string\" ? { reason } : {}),\n  };\n}\n\nexport interface ISaveFilterInput {\n  filter: TSavedFilterQuery;\n  name: string;\n}\n\nfunction checkSaveFilter(value: unknown): ISaveFilterInput | string {\n  const record = asRecord(value);\n  if (record == null) return \"expected an object\";\n  const filter = checkSavedFilterQuery(record[\"filter\"]);\n  if (typeof filter === \"string\") return `filter.${filter}`;\n  const name = record[\"name\"];\n  if (typeof name !== \"string\") return \"name: expected a string\";\n  return { filter, name };\n}\n\nfunction checkRemoveFilter(value: unknown): { id: string } | string {\n  const id = asRecord(value)?.[\"id\"];\n  return typeof id === \"string\" && id !== \"\" ? { id } : \"id: expected a saved filter id\";\n}\n\nfunction checkOk(value: unknown): { ok: true } | string {\n  return asRecord(value)?.[\"ok\"] === true ? { ok: true } : \"expected { ok: true }\";\n}\n\nfunction checkEmpty(value: unknown): Record<string, never> | string {\n  return asRecord(value) == null ? \"expected an object\" : {};\n}\n\n/** What a reload attempt actually did — see `reloadConfig`'s note below. */\nexport interface IReloadResult {\n  ok: true;\n  /** True when the new file validated and is now live; false when last-good was kept. */\n  applied: boolean;\n  /** The revision hash in force after the attempt — unchanged when `applied` is false. */\n  configRevisionHash: string;\n  /** Validation errors that kept the reload out, empty when it applied. */\n  errors: string[];\n}\n\nfunction checkReloadResult(value: unknown): IReloadResult | string {\n  const result = asRecord(value);\n  if (result == null) return \"expected an object\";\n  const errors = result[\"errors\"];\n  if (result[\"ok\"] !== true) return \"expected { ok: true }\";\n  if (typeof result[\"applied\"] !== \"boolean\") return \"applied: expected a boolean\";\n  if (typeof result[\"configRevisionHash\"] !== \"string\") {\n    return \"configRevisionHash: expected a string\";\n  }\n  if (!Array.isArray(errors) || !errors.every((entry) => typeof entry === \"string\")) {\n    return \"errors: expected an array of strings\";\n  }\n  return {\n    ok: true,\n    applied: result[\"applied\"],\n    configRevisionHash: result[\"configRevisionHash\"],\n    errors,\n  };\n}\n\n/** Re-check a reload ack that arrived from a daemon — see `parseActionReport`. */\nexport function parseReloadResult(value: unknown): IReloadResult | null {\n  const checked = checkReloadResult(value);\n  return typeof checked === \"string\" ? null : checked;\n}\n\nconst OUTCOMES: ReadonlySet<string> = new Set([\n  \"ready\",\n  \"spawned\",\n  \"already-running\",\n  \"blocked\",\n  \"failed\",\n  \"succeeded\",\n  \"stopped\",\n  \"already-stopped\",\n]);\n\nfunction isOutcome(value: unknown): value is TActionOutcome {\n  return typeof value === \"string\" && OUTCOMES.has(value);\n}\n\nfunction checkReport(value: unknown): IActionReport | string {\n  const record = asRecord(value);\n  if (record == null) return \"expected an object\";\n  const { results, warnings } = record;\n  if (!Array.isArray(results) || !Array.isArray(warnings)) return \"expected { results, warnings }\";\n  // Built up rather than blessed: returning the input under an `as IActionReport` handed callers\n  // a value the checks above never actually produced, so any field they missed rode along typed.\n  const checkedResults: IProcessActionResult[] = [];\n  for (const entry of results) {\n    const result = asRecord(entry);\n    if (result == null) return \"results: expected objects\";\n    const { id, outcome, reason } = result;\n    if (typeof id !== \"string\" || !isOutcome(outcome)) return \"results: malformed entry\";\n    if (reason != null && typeof reason !== \"string\") return \"results: reason must be a string\";\n    checkedResults.push(reason == null ? { id, outcome } : { id, outcome, reason });\n  }\n  const checkedWarnings: string[] = [];\n  for (const warning of warnings) {\n    if (typeof warning !== \"string\") return \"warnings: expected strings\";\n    checkedWarnings.push(warning);\n  }\n  return { results: checkedResults, warnings: checkedWarnings };\n}\n\n/**\n * Re-check a report that arrived from a daemon. The action stack validates an output where it is\n * PRODUCED; a client that writes `as IActionReport` over what came back off the wire is asserting\n * that the daemon it reached is the build it was compiled against — the one thing\n * `COMMANDER_PROTOCOL_VERSION` exists to doubt. Null means \"not a report\", for the caller to\n * report as a mismatch rather than to dereference.\n */\nexport function parseActionReport(value: unknown): IActionReport | null {\n  const checked = checkReport(value);\n  return typeof checked === \"string\" ? null : checked;\n}\n\nexport const commanderControlDomain = createActionRootDomain({\n  domain: \"commander\",\n}).createChildDomain({\n  domain: \"control\",\n  actions: {\n    ports: actionSchema()\n      .input({ schema: handSchema(checkPortsInput) })\n      .output({ schema: handSchema(checkPortsReport) }),\n    start: actionSchema()\n      .input({ schema: handSchema(checkStart) })\n      .output({ schema: handSchema(checkReport) }),\n    stop: actionSchema()\n      .input({ schema: handSchema(checkStop) })\n      .output({ schema: handSchema(checkReport) }),\n    restart: actionSchema()\n      .input({ schema: handSchema(checkStart) })\n      .output({ schema: handSchema(checkReport) }),\n    // Mutates the sticky override store; the realm carries the result. Deliberately does NOT\n    // touch a running process — see `applyEnvOverrides`.\n    // Answers on ACCEPTANCE — a suite run legitimately takes minutes; its progress and verdict\n    // travel on the status realm (`runs`).\n    runSuite: actionSchema()\n      .input({ schema: handSchema(checkRunSuite) })\n      .output({ schema: handSchema(checkRunSuiteReport) }),\n    saveFilter: actionSchema()\n      .input({ schema: handSchema(checkSaveFilter) })\n      .output({ schema: handSchema(checkOk) }),\n    removeFilter: actionSchema()\n      .input({ schema: handSchema(checkRemoveFilter) })\n      .output({ schema: handSchema(checkOk) }),\n    setEnv: actionSchema()\n      .input({ schema: handSchema(checkSetEnv) })\n      .output({ schema: handSchema(checkEnvReport) }),\n    // A foreground `run` reporting what it ran, so \"recently started\" and the estimates count it.\n    noteRuns: actionSchema()\n      .input({ schema: handSchema(checkNoteRuns) })\n      .output({ schema: handSchema(checkOk) }),\n    reloadConfig: actionSchema()\n      .input({ schema: handSchema(checkEmpty) })\n      // The ack carries the revision that is now LIVE. `ok: true` alone said only \"the attempt\n      // finished\" — indistinguishable from a reload that failed validation and kept last-good,\n      // so a caller could never tell whether the edit it just saved had actually taken effect.\n      .output({ schema: handSchema(checkReloadResult) }),\n    shutdown: actionSchema()\n      .input({ schema: handSchema(checkEmpty) })\n      .output({ schema: handSchema(checkOk) }),\n  },\n});\n\n/** One socket carries control actions (toAcceptor) + the status realm (a mux protocol, D1). */\nexport const commanderChannel = defineChannel({\n  toAcceptor: [commanderControlDomain],\n  toConnector: [],\n});\n","/** Retain cold-start retries, but report a failed dial instead of hiding it behind hydration. */\nexport async function waitForStatusRealm(\n  connector: { connect(): Promise<void> },\n  realm: {\n    whenLive(options: { timeoutMs: number }): Promise<void>;\n    readonly attachError?: unknown;\n  },\n  timeoutMs: number,\n): Promise<void> {\n  let connectionError: unknown;\n  void connector.connect().catch((error: unknown) => {\n    connectionError = error;\n  });\n  try {\n    await realm.whenLive({ timeoutMs });\n  } catch (error) {\n    throw realm.attachError ?? connectionError ?? error;\n  }\n}\n","// The CLI's daemon client: instance-record discovery (never a pid match alone), a root-token\n// ticket mint, and one wire socket carrying control actions + the status realm (D1). The\n// read-only commands use `findDaemon`/`requireDaemon` and never autostart; only `up` and `ui`\n// call `ensureDaemon`.\n\nimport { randomUUID } from \"node:crypto\";\nimport {\n  ActionRuntime,\n  connectChannel,\n  ESecurityLevel,\n  RuntimeCoordinate,\n  wsCarrier,\n} from \"@nice-code/action\";\nimport { connectRealm, type IRealmHandle, realmConnection } from \"@nice-code/realm\";\nimport { createMemoryStorageMethods_json, StorageAdapter } from \"@nice-code/util\";\nimport { WebSocket } from \"ws\";\nimport type { IResolvedCommanderConfig } from \"../config/types\";\nimport { findDaemonProcesses, type IDaemonProcess, orphanMessage } from \"../daemon/daemonProcesses\";\nimport {\n  commanderStatePaths,\n  type ICommanderStatePaths,\n  resolveCommanderDataDir,\n} from \"../daemon/dataDir\";\nimport {\n  COMMANDER_PROTOCOL_VERSION,\n  type ICommanderInstanceRecord,\n  pidAlive,\n  pingDaemon,\n  readInstanceRecord,\n  readSkewedInstanceRecord,\n  recordDaemonAlive,\n} from \"../daemon/instanceRecord\";\nimport { commanderPackageVersion } from \"../daemon/packageVersion\";\nimport { commanderRuntimeError } from \"../daemon/runtime\";\nimport { ensureDaemon } from \"../daemon/spawnDaemon\";\nimport {\n  COMMANDER_LOGS_PATH,\n  COMMANDER_TICKET_PATH,\n  COMMANDER_TICKET_PROTOCOL_PREFIX,\n  COMMANDER_WS_PATH,\n} from \"../protocol/auth\";\nimport {\n  COMMANDER_CONTROL_TIMEOUT_MS,\n  commanderChannel,\n  commanderControlDomain,\n  type IActionReport,\n  type INoteRunsInput,\n  type IReloadResult,\n  type ISetEnvInput,\n  parseActionReport,\n  parseReloadResult,\n} from \"../protocol/control\";\nimport { commanderStatusRealm, type TCommanderStatusState } from \"../protocol/statusRealm\";\nimport { waitForStatusRealm } from \"../protocol/waitForStatusRealm\";\nimport { CliExit, EXIT } from \"./load\";\n\nexport interface IDaemonHandle {\n  record: ICommanderInstanceRecord;\n  paths: ICommanderStatePaths;\n  /**\n   * True when THIS invocation booted the daemon (vs reused). The spawned child handle pins\n   * the event loop when the CLI itself was launched via WSL interop (detached-child tie) —\n   * the CLI hard-exits after such commands instead of draining naturally.\n   */\n  spawned: boolean;\n  /** A skewed idle daemon `up` stopped and replaced on the way — worth a line of narrative. */\n  replaced?: { pid: number; packageVersion: string };\n}\n\n/** The running daemon for this config, or null (dead record, failed ping, nothing on disk). */\nexport async function findDaemon(config: IResolvedCommanderConfig): Promise<IDaemonHandle | null> {\n  const paths = commanderStatePaths(resolveCommanderDataDir(), config.configKey);\n  const record = await readInstanceRecord(paths.instanceRecordPath);\n  if (record == null || !(await recordDaemonAlive(record))) return null;\n  return (await pingDaemon(record)) != null ? { record, paths, spawned: false } : null;\n}\n\n/**\n * A daemon this build cannot talk to is IN THE WAY, not absent — the same distinction `up`\n * makes (edge 18). Reporting \"not running\" while one plainly IS sends you to `up`, which then\n * fails on something else entirely. The remedy is always the same and always THIS build's:\n * `shutdown` falls back to a verified signal when it cannot speak to the daemon.\n */\nexport async function findSkewedDaemon(config: IResolvedCommanderConfig): Promise<{\n  message: string;\n  pid: number;\n  port: number;\n  packageVersion: string;\n  startStamp: ICommanderInstanceRecord[\"startStamp\"];\n  /** Its page works as-is (it serves its own client) — `ui` opens it rather than replacing it. */\n  servesOwnClient: boolean;\n} | null> {\n  const paths = commanderStatePaths(resolveCommanderDataDir(), config.configKey);\n  const skewed = await readSkewedInstanceRecord(\n    paths.instanceRecordPath,\n    commanderStatusRealm.schemaHash,\n  );\n  if (skewed == null || !pidAlive(skewed.pid)) return null;\n  const difference =\n    skewed.skew === \"protocol\"\n      ? `speaks protocol v${skewed.protocolVersion}; this build speaks v${COMMANDER_PROTOCOL_VERSION}`\n      : \"was started before an upgrade changed the status schema\";\n  return {\n    message:\n      `the daemon for this config (pid ${skewed.pid}, port ${skewed.port}, build ` +\n      `${skewed.packageVersion}) ${difference} — this CLI (build ` +\n      `${await commanderPackageVersion()}) cannot talk to it. Run \\`nice-commander shutdown\\` ` +\n      \"(it stops a daemon from any build), then retry.\",\n    pid: skewed.pid,\n    port: skewed.port,\n    packageVersion: skewed.packageVersion,\n    startStamp: skewed.startStamp,\n    servesOwnClient: skewed.servesOwnClient,\n  };\n}\n\n/**\n * This config's daemons that no instance record points at (see `daemonProcesses.ts`). The CLI\n * cannot talk to them — no token — but it can name them, and `shutdown` can stop them.\n */\nexport async function findOrphanDaemons(\n  config: IResolvedCommanderConfig,\n  recordedPid?: number,\n): Promise<IDaemonProcess[]> {\n  return findDaemonProcesses(config.configPath, resolveCommanderDataDir(), recordedPid);\n}\n\n/** Read-only commands' daemon-or-report: never starts anything, exit 3 when not running. */\nexport async function requireDaemon(config: IResolvedCommanderConfig): Promise<IDaemonHandle> {\n  const handle = await findDaemon(config);\n  if (handle != null) return handle;\n  const skewed = await findSkewedDaemon(config);\n  if (skewed != null) throw new CliExit(EXIT.notRunning, skewed.message);\n  const orphans = await findOrphanDaemons(config);\n  if (orphans.length > 0) throw new CliExit(EXIT.notRunning, orphanMessage(orphans));\n  throw new CliExit(\n    EXIT.notRunning,\n    `daemon not running for \"${config.name}\" (start one with \\`up\\`)`,\n  );\n}\n\n/** `up`/`ui`'s spawn-or-reuse; the daemon child reruns THIS bin (`daemon` subcommand). */\nexport async function ensureDaemonRunning(\n  config: IResolvedCommanderConfig,\n): Promise<IDaemonHandle> {\n  const result = await ensureDaemon({\n    config,\n    daemonScript: process.argv[1] as string, // the invoked bin (build/cli.mjs, or the test shim)\n  });\n  return {\n    record: result.record,\n    paths: result.paths,\n    spawned: !result.reused,\n    ...(result.replaced != null ? { replaced: result.replaced } : {}),\n  };\n}\n\nasync function mintTicket(record: ICommanderInstanceRecord): Promise<string> {\n  let response: Response;\n  try {\n    response = await fetch(`http://127.0.0.1:${record.port}${COMMANDER_TICKET_PATH}`, {\n      method: \"POST\",\n      headers: { authorization: `Bearer ${record.token}` },\n      signal: AbortSignal.timeout(5_000),\n    });\n  } catch {\n    throw new CliExit(EXIT.failure, `daemon on port ${record.port} did not answer the ticket mint`);\n  }\n  if (!response.ok) {\n    throw new CliExit(EXIT.failure, `ticket mint refused (HTTP ${response.status})`);\n  }\n  const body = (await response.json()) as { ticket?: string };\n  if (typeof body.ticket !== \"string\") {\n    throw new CliExit(EXIT.failure, \"ticket mint returned a malformed body\");\n  }\n  return body.ticket;\n}\n\nexport interface IDaemonClient {\n  readonly record: ICommanderInstanceRecord;\n  readonly realm: IRealmHandle<TCommanderStatusState & object, Record<string, never>>;\n  state(): TCommanderStatusState;\n  /** The three actions that answer with a per-process report. */\n  control(\n    action: \"start\" | \"stop\" | \"restart\",\n    input: {\n      ids: string[];\n      wait?: boolean;\n      staggerMs?: number;\n      replaceSame?: boolean;\n      flags?: Record<string, string[]>;\n      /** `stop` only: also stop the dependencies no other live process needs. */\n      withDependencies?: boolean;\n    },\n  ): Promise<IActionReport>;\n  /** Mutate the sticky env-override store; refusals come back as warnings, never as a throw. */\n  setEnv(input: ISetEnvInput): Promise<string[]>;\n  /** Report what a foreground `run` ran, for \"recently started\" and the task estimates. */\n  noteRuns(input: INoteRunsInput): Promise<void>;\n  /**\n   * Have the daemon load the config from disk now; the ack says which revision is live after.\n   * Null when the daemon refuses, or answers with something this build does not recognise.\n   */\n  reloadConfig(): Promise<IReloadResult | null>;\n  shutdown(): Promise<void>;\n  dispose(): void;\n}\n\nexport async function connectDaemon(handle: IDaemonHandle): Promise<IDaemonClient> {\n  const runtimeError = commanderRuntimeError();\n  if (runtimeError != null) throw new CliExit(EXIT.failure, runtimeError);\n  const { record } = handle;\n  // Same protocol version, different realm schema — a schema change whose version bump was\n  // forgotten (the 0.79→0.80 incident). Refusing BEFORE the dial turns \"could not attach the\n  // status realm (…hash soup…)\" into a name and a remedy.\n  if (record.realmSchemaHash !== commanderStatusRealm.schemaHash) {\n    throw new CliExit(\n      EXIT.failure,\n      `the daemon for this config (pid ${record.pid}, build ${record.packageVersion}) was ` +\n        `started before an upgrade changed the status schema — this CLI (build ` +\n        `${await commanderPackageVersion()}) cannot read its state. Run \\`nice-commander ` +\n        \"shutdown` (it stops a daemon from any build), then retry.\",\n    );\n  }\n  // One ticket for the wire dial; /logs lanes mint per call (tickets are one-use).\n  const ticket = await mintTicket(record);\n  // A per-session perId + ephemeral identity: the daemon's TOFU verify-key pin binds\n  // envId::perId to the first key it sees, so a STABLE perId with a fresh-per-boot key bricks\n  // every later dial (identity_pin_mismatch — parked silently). A random perId per invocation\n  // is the pairing ephemeralIdentity exists for (wireConnectionParts §ephemeral-identity trap).\n  const runtime = new ActionRuntime(\n    RuntimeCoordinate.env(\"commander_cli\").withPersistentId(`cli-${randomUUID().slice(0, 8)}`),\n  );\n  const connector = connectChannel(runtime, commanderChannel, {\n    peer: RuntimeCoordinate.env(\"commander_daemon\"),\n    storage: new StorageAdapter({ methods: createMemoryStorageMethods_json(new Map()) }),\n    ephemeralIdentity: true,\n    securityLevel: ESecurityLevel.authenticated,\n    // `up`/`restart` deliberately BLOCK for their report (that narrative is the command's value),\n    // and a real group takes minutes — the wire stack's 10 s default aborted them mid-run with\n    // \"transport timed out\" while the daemon carried on (REVIEW-AND-FIX F2).\n    defaultTimeout: COMMANDER_CONTROL_TIMEOUT_MS,\n    reconnect: false, // a CLI invocation is one dial; a dead daemon ends the command\n    onLinkEvent: (event) => {\n      if (process.env[\"NICE_COMMANDER_DEBUG\"] != null) {\n        process.stderr.write(`[link] ${JSON.stringify(event)}\\n`);\n      }\n    },\n    carriers: [\n      wsCarrier(() => ({ url: `ws://127.0.0.1:${record.port}${COMMANDER_WS_PATH}` }), {\n        createWebSocket: (url) => {\n          if (process.env[\"NICE_COMMANDER_DEBUG\"] != null) {\n            process.stderr.write(`[ws] dialing ${url}\\n`);\n          }\n          const socket = new WebSocket(url, [`${COMMANDER_TICKET_PROTOCOL_PREFIX}${ticket}`]);\n          if (process.env[\"NICE_COMMANDER_DEBUG\"] != null) {\n            socket.on(\"open\", () => process.stderr.write(\"[ws] open\\n\"));\n            socket.on(\"error\", (error) => process.stderr.write(`[ws] error ${error.message}\\n`));\n            socket.on(\"close\", (code) => process.stderr.write(`[ws] close ${code}\\n`));\n          }\n          return socket as unknown as globalThis.WebSocket;\n        },\n      }),\n    ],\n  });\n  const realm = connectRealm(commanderStatusRealm, {\n    onDiagnostic: (event) => {\n      if (process.env[\"NICE_COMMANDER_DEBUG\"] != null) {\n        process.stderr.write(`[realm] ${JSON.stringify(event)}\\n`);\n      }\n    },\n    avatar: { type: \"viewer\" },\n    connection: realmConnection(connector),\n    assertOnAttach: () => {},\n  });\n  // Realm attaches before the first dispatch so the mux advertises it in the handshake (D1).\n  try {\n    await waitForStatusRealm(connector, realm, 10_000);\n  } catch (error) {\n    realm.detach();\n    connector.dispose();\n    const reason = String(error);\n    // The hash guard above catches known skew; this catch-all still names the likely cause and\n    // the remedy, because a raw refusal with no next step is how an operator gets stuck.\n    const hint = reason.includes(\"schema_mismatch\")\n      ? ` The daemon (pid ${record.pid}, build ${record.packageVersion}) and this CLI were ` +\n        \"built from different realm definitions — run `nice-commander shutdown` (it stops a \" +\n        \"daemon from any build), then retry.\"\n      : \"\";\n    throw new CliExit(EXIT.failure, `could not attach the status realm (${reason}).${hint}`);\n  }\n  return {\n    record,\n    realm,\n    state: () => realm.store.state,\n    control: async (action, input) => {\n      // ⚠ A literal id per branch, on purpose: `actionForId(<a union of ids>)` collapses the\n      // input type to `never`, and the `as never` that unblocks it is precisely the assertion\n      // this client should not be making about the daemon's schema.\n      const request =\n        action === \"start\"\n          ? commanderControlDomain.actionForId(\"start\").request(input)\n          : action === \"stop\"\n            ? commanderControlDomain.actionForId(\"stop\").request(input)\n            : commanderControlDomain.actionForId(\"restart\").request(input);\n      const payload = await (await runtime.handleActionPayload(request)).waitForResultPayload();\n      if (!payload.result.ok) {\n        throw new CliExit(EXIT.failure, `action \"${action}\" rejected by the daemon`);\n      }\n      const report = parseActionReport(payload.result.output);\n      if (report == null) {\n        throw new CliExit(\n          EXIT.failure,\n          `the daemon answered \"${action}\" with something this CLI does not recognise — ` +\n            `protocol ${record.protocolVersion} vs ${COMMANDER_PROTOCOL_VERSION}`,\n        );\n      }\n      return report;\n    },\n    setEnv: async (input) => {\n      const request = commanderControlDomain.actionForId(\"setEnv\").request(input);\n      const payload = await (await runtime.handleActionPayload(request)).waitForResultPayload();\n      if (!payload.result.ok) {\n        throw new CliExit(EXIT.failure, `action \"setEnv\" rejected by the daemon`);\n      }\n      const warnings = (payload.result.output as { warnings?: unknown }).warnings;\n      return Array.isArray(warnings) ? warnings.filter((entry) => typeof entry === \"string\") : [];\n    },\n    noteRuns: async (input) => {\n      const request = commanderControlDomain.actionForId(\"noteRuns\").request(input);\n      const payload = await (await runtime.handleActionPayload(request)).waitForResultPayload();\n      if (!payload.result.ok) {\n        throw new CliExit(EXIT.failure, `action \"noteRuns\" rejected by the daemon`);\n      }\n    },\n    reloadConfig: async () => {\n      const request = commanderControlDomain.actionForId(\"reloadConfig\").request({});\n      const payload = await (await runtime.handleActionPayload(request)).waitForResultPayload();\n      return payload.result.ok ? parseReloadResult(payload.result.output) : null;\n    },\n    shutdown: async () => {\n      const request = commanderControlDomain.actionForId(\"shutdown\").request({});\n      const payload = await (await runtime.handleActionPayload(request)).waitForResultPayload();\n      if (!payload.result.ok) {\n        throw new CliExit(EXIT.failure, `action \"shutdown\" rejected by the daemon`);\n      }\n    },\n    dispose: () => {\n      realm.detach();\n      connector.dispose();\n    },\n  };\n}\n\n/** The /logs lane needs a fresh one-use ticket per socket — hence its own async opener. */\nexport async function openLogsLane(record: ICommanderInstanceRecord): Promise<WebSocket> {\n  const ticket = await mintTicket(record);\n  return new WebSocket(`ws://127.0.0.1:${record.port}${COMMANDER_LOGS_PATH}`, [\n    `${COMMANDER_TICKET_PROTOCOL_PREFIX}${ticket}`,\n  ]);\n}\n","// up/down/restart/shutdown — the control verbs. `up` reports the state narrative live (the\n// status realm streams every transition while the action runs) and ends in the structured\n// ready/blocked/failed report; `--no-wait` detaches at \"spawned\". Read-only discovery rules:\n// down/restart/shutdown report \"not running\" (exit 3) instead of autostarting.\n\nimport { signalDaemonShutdown } from \"../../daemon/instanceRecord\";\nimport type { IActionReport } from \"../../protocol/control\";\nimport type { IStatusProcessNode, TCommanderStatusState } from \"../../protocol/statusRealm\";\nimport { unknownFlags } from \"../args\";\nimport { syncDaemonConfig } from \"../configSync\";\nimport type { ICommandContext } from \"../context\";\nimport { flagsOrExit, requireSelectionTerms, selectOrExit, staggerFor } from \"../context\";\nimport {\n  connectDaemon,\n  ensureDaemonRunning,\n  findDaemon,\n  findOrphanDaemons,\n  findSkewedDaemon,\n  type IDaemonClient,\n  type IDaemonHandle,\n  requireDaemon,\n} from \"../daemonClient\";\nimport { CliExit, EXIT } from \"../load\";\nimport type { IOut } from \"../out\";\n\nfunction stateSymbol(out: IOut, state: string): string {\n  switch (state) {\n    case \"ready\":\n    case \"succeeded\":\n      return out.paint(\"green\", \"✓\");\n    case \"failed\":\n    case \"crashed\":\n      return out.paint(\"red\", \"✗\");\n    case \"blocked\":\n    case \"unready\":\n      return out.paint(\"yellow\", \"⚠\");\n    case \"stopped\":\n    case \"not-started\":\n      return out.paint(\"gray\", \"▪\");\n    default:\n      return out.paint(\"cyan\", \"▸\");\n  }\n}\n\n/** Where a ready process can be reached: its http endpoints' URLs, else its declared `url`. */\nfunction urlsOf(node: IStatusProcessNode | undefined): string[] {\n  if (node == null) return [];\n  const urls = node.detail.endpoints.flatMap((endpoint) =>\n    endpoint.url != null ? [endpoint.url] : [],\n  );\n  if (urls.length === 0 && node.detail.url != null) urls.push(node.detail.url);\n  return urls;\n}\n\n/** `✓ web ready → http://localhost:3050` — the address is declared, so the line can carry it. */\nfunction reachLine(out: IOut, node: IStatusProcessNode | undefined): string {\n  const urls = urlsOf(node);\n  return urls.length === 0 ? \"\" : ` → ${urls.map((url) => out.paint(\"cyan\", url)).join(\" \")}`;\n}\n\n/** Stream the transition narrative for the touched ids while an action runs. */\nasync function withProgress<T>(\n  client: IDaemonClient,\n  out: IOut,\n  ids: ReadonlySet<string>,\n  run: () => Promise<T>,\n): Promise<T> {\n  if (out.json || ids.size === 0) return run();\n  const last = new Map<string, string>();\n  const note = () => {\n    const state = client.state();\n    for (const id of ids) {\n      const proc = state.processes[id];\n      if (proc == null) continue;\n      const current = `${proc.state}${proc.blockedBy != null ? ` — ${proc.blockedBy}` : \"\"}`;\n      if (last.get(id) === current) continue;\n      last.set(id, current);\n      const reach = proc.state === \"ready\" ? reachLine(out, proc) : \"\";\n      out.print(`${stateSymbol(out, proc.state)} ${out.accent(id, id)} ${current}${reach}`);\n    }\n  };\n  const off = client.realm.listenToPatches(() => note());\n  try {\n    return await run();\n  } finally {\n    off();\n  }\n}\n\nconst FINAL_BAD = new Set([\"failed\", \"blocked\"]);\n/** Outcomes the live narrative already showed as transitions — re-printing them is pure noise. */\nconst NARRATED = new Set([\"ready\", \"spawned\", \"stopped\", \"succeeded\", \"blocked\"]);\n\n/**\n * `--json` carries the generation's verdict as data: the action outcome per id, plus the state,\n * pid and endpoints the realm holds for it once the action has settled — so a script can decide\n * from one object what `status --json` would otherwise have to be asked for next.\n */\nfunction enrichReport(report: IActionReport, state: TCommanderStatusState) {\n  return {\n    results: report.results.map((result) => {\n      const node = state.processes[result.id];\n      return {\n        ...result,\n        state: node?.state ?? \"unknown\",\n        ...(node?.pid != null ? { pid: node.pid } : {}),\n        ...(node?.blockedBy != null ? { blockedBy: node.blockedBy } : {}),\n        ...(node?.startError != null ? { startError: node.startError } : {}),\n        endpoints: node?.detail.endpoints ?? [],\n        urls: urlsOf(node),\n      };\n    }),\n    warnings: report.warnings,\n  };\n}\n\nfunction printReport(out: IOut, report: IActionReport, state: TCommanderStatusState): number {\n  if (out.json) {\n    out.printJson(enrichReport(report, state));\n  } else {\n    for (const result of report.results) {\n      if (NARRATED.has(result.outcome)) continue;\n      const node = state.processes[result.id];\n      const note = result.reason != null ? ` — ${result.reason}` : \"\";\n      const reach = result.outcome === \"already-running\" ? reachLine(out, node) : \"\";\n      out.print(\n        `${stateSymbol(out, result.outcome)} ${out.accent(result.id, result.id)} ${result.outcome}${note}${reach}`,\n      );\n      // A start never restarts what runs, so a change made since is still waiting — say so here,\n      // where \"already-running, exit 0\" would otherwise read as \"the change is live\".\n      if (\n        result.outcome === \"already-running\" &&\n        (node?.stale === true || node?.envDrift === true)\n      ) {\n        out.print(\n          out.paint(\n            \"yellow\",\n            `  ${result.id} runs what it was started with — its ` +\n              `${node.stale ? \"definition\" : \"env\"} has changed since; ` +\n              `\\`restart ${result.id}\\` applies it`,\n          ),\n        );\n      }\n    }\n    for (const warning of report.warnings) {\n      out.warn(`${out.paint(\"yellow\", \"⚠\")} ${warning}`);\n    }\n  }\n  return report.results.some((result) => FINAL_BAD.has(result.outcome)) ? EXIT.failure : EXIT.ok;\n}\n\nexport async function cmdUp(ctx: ICommandContext): Promise<number> {\n  const bad = unknownFlags(ctx.args.flags, [\n    \"--no-wait\",\n    \"--dry-run\",\n    \"--replace-same\",\n    \"--with\",\n    \"--all\",\n    \"--any\",\n  ]);\n  if (bad != null) throw new CliExit(EXIT.usage, bad);\n  const selection = selectOrExit(ctx, { bare: \"default\" });\n  const flags = flagsOrExit(ctx);\n  if (ctx.args.flags.has(\"--dry-run\")) {\n    const { out } = ctx;\n    if (out.json) out.printJson(selection);\n    else {\n      out.print(`start order (${selection.ordered.length}):`);\n      selection.ordered.forEach((id, index) => {\n        const tag = selection.autoIncluded.includes(id) ? out.paint(\"gray\", \" (dep)\") : \"\";\n        out.print(`  ${index + 1}. ${id}${tag}`);\n      });\n    }\n    return EXIT.ok; // a dry run never starts the daemon\n  }\n  const handle = await ensureDaemonRunning(ctx.config);\n  ctx.spawnedDaemon = handle.spawned;\n  if (handle.replaced != null && !ctx.out.json) {\n    ctx.out.print(\n      ctx.out.paint(\n        \"gray\",\n        `· replaced the previous daemon (pid ${handle.replaced.pid}, build ` +\n          `${handle.replaced.packageVersion}) — it predated this CLI and nothing was running`,\n      ),\n    );\n  }\n  const client = await connectDaemon(handle);\n  try {\n    await syncDaemonConfig(ctx.config, client, ctx.out);\n    const wait = !ctx.args.flags.has(\"--no-wait\");\n    const staggerMs = staggerFor(ctx.config, ctx.args.positionals);\n    const replaceSame = ctx.args.flags.has(\"--replace-same\");\n    const report = await withProgress(client, ctx.out, new Set(selection.ordered), () =>\n      client.control(\"start\", {\n        ids: selection.ordered,\n        wait,\n        ...(staggerMs > 0 ? { staggerMs } : {}),\n        ...(replaceSame ? { replaceSame } : {}),\n        ...(flags != null ? { flags: { [flags.id]: flags.flags } } : {}),\n      }),\n    );\n    return printReport(ctx.out, report, client.state());\n  } finally {\n    client.dispose();\n  }\n}\n\nasync function controlVerb(ctx: ICommandContext, verb: \"stop\" | \"restart\"): Promise<number> {\n  const known =\n    verb === \"restart\"\n      ? [\"--no-wait\", \"--replace-same\", \"--with\", \"--all\", \"--any\"]\n      : [\"--only\", \"--all\", \"--any\"];\n  const bad = unknownFlags(ctx.args.flags, known);\n  if (bad != null) throw new CliExit(EXIT.usage, bad);\n  if (ctx.args.flags.has(\"--only\") && ctx.args.flags.get(\"--only\") !== true) {\n    throw new CliExit(EXIT.usage, \"--only takes no value\");\n  }\n  // The bare-selection guard is pure argv and reports before any daemon lookup; id resolution\n  // happens after, so a process REMOVED from the config while still running stays addressable\n  // by exact id and is included by `--all` instead of surviving until a full shutdown (M1).\n  requireSelectionTerms(ctx);\n  const handle = await requireDaemon(ctx.config);\n  const client = await connectDaemon(handle);\n  try {\n    // A restart must spawn the definition on disk now; a stop needs nothing from the config.\n    if (verb === \"restart\") await syncDaemonConfig(ctx.config, client, ctx.out);\n    const declared = new Set(ctx.config.processes.map((proc) => proc.id));\n    const stillHeld = Object.keys(client.state().processes ?? {}).filter((id) => !declared.has(id));\n    const selection = selectOrExit(ctx, { bare: \"required\", extraIds: stillHeld });\n    const replaceSame = ctx.args.flags.has(\"--replace-same\");\n    const flags = verb === \"restart\" ? flagsOrExit(ctx) : null;\n    // ⚠ Only the ids that were NAMED go on the wire, never `selection.ordered`: the closure\n    // holds every dependency, and a dependency is usually somebody else's too. The daemon\n    // decides which of them a `down` may take along; a restart starts any that are not up.\n    const report = await withProgress(client, ctx.out, new Set(selection.ordered), () =>\n      verb === \"stop\"\n        ? client.control(\n            \"stop\",\n            ctx.args.flags.has(\"--only\")\n              ? { ids: selection.direct }\n              : { ids: selection.direct, withDependencies: true },\n          )\n        : client.control(\"restart\", {\n            ids: selection.direct,\n            wait: !ctx.args.flags.has(\"--no-wait\"),\n            staggerMs: staggerFor(ctx.config, ctx.args.positionals),\n            ...(replaceSame ? { replaceSame } : {}),\n            ...(flags != null ? { flags: { [flags.id]: flags.flags } } : {}),\n          }),\n    );\n    return printReport(ctx.out, report, client.state());\n  } finally {\n    client.dispose();\n  }\n}\n\nexport async function cmdDown(ctx: ICommandContext): Promise<number> {\n  return controlVerb(ctx, \"stop\");\n}\n\nexport async function cmdRestart(ctx: ICommandContext): Promise<number> {\n  return controlVerb(ctx, \"restart\");\n}\n\n/**\n * `shutdown` must be the command that ALWAYS works — it is the remedy every skew message names.\n * The wire is tried first (the graceful ask); when the daemon cannot be talked to — another\n * build's protocol, a changed realm schema, a wedged socket — it falls back to a verified\n * SIGTERM, which runs the daemon's own shutdown ladder. Without this fallback, the one command\n * that fixes \"the CLI cannot talk to the daemon\" was itself behind that same wall.\n */\nexport async function cmdShutdown(ctx: ICommandContext): Promise<number> {\n  const bad = unknownFlags(ctx.args.flags, []);\n  if (bad != null) throw new CliExit(EXIT.usage, bad);\n  const { out, config } = ctx;\n  const reports: Record<string, unknown>[] = [];\n  let code: number | null = null;\n  let recordedPid: number | undefined;\n  const handle = await findDaemon(config);\n  if (handle != null) {\n    recordedPid = handle.record.pid;\n    code = await shutdownRecorded(ctx, handle, reports);\n  } else {\n    const skewed = await findSkewedDaemon(config);\n    if (skewed != null) {\n      recordedPid = skewed.pid;\n      if (!out.json) out.print(out.paint(\"gray\", skewed.message));\n      code = reportSignalShutdown(\n        ctx,\n        await signalDaemonShutdown({ pid: skewed.pid, startStamp: skewed.startStamp }),\n        \"could not be reached over the wire\",\n        reports,\n      );\n    }\n  }\n  // Daemons the record lost track of — booted past, then had their entry overwritten. They are\n  // invisible to every lookup above, so without this `shutdown` reports \"not running\" while they\n  // hold a port and run processes. Found by argv; `signalDaemonShutdown` re-verifies the stamp.\n  for (const orphan of await findOrphanDaemons(config, recordedPid)) {\n    const next = reportSignalShutdown(\n      ctx,\n      await signalDaemonShutdown(orphan),\n      \"was running without an instance record (the CLI had lost track of it)\",\n      reports,\n    );\n    code = code == null ? next : Math.max(code, next);\n  }\n  if (code == null) throw new CliExit(EXIT.notRunning, `daemon not running for \"${config.name}\"`);\n  if (out.json) {\n    out.printJson(\n      reports.length === 1\n        ? reports[0]\n        : { ok: reports.every((report) => report[\"ok\"] === true), daemons: reports },\n    );\n  }\n  return code;\n}\n\n/** The recorded daemon: the wire first (the graceful ask), a verified signal when it refuses. */\nasync function shutdownRecorded(\n  ctx: ICommandContext,\n  handle: IDaemonHandle,\n  reports: Record<string, unknown>[],\n): Promise<number> {\n  try {\n    const client = await connectDaemon(handle);\n    try {\n      await client.shutdown();\n      reports.push({ ok: true, via: \"wire\" });\n      if (!ctx.out.json) ctx.out.print(`daemon for \"${ctx.config.name}\" is shutting down`);\n      return EXIT.ok;\n    } finally {\n      client.dispose();\n    }\n  } catch (error) {\n    if (!(error instanceof CliExit)) throw error;\n    // The wire refused us (schema skew, wedged socket…) — the record's identity was already\n    // verified by findDaemon, so the signal path takes over from here.\n    return reportSignalShutdown(\n      ctx,\n      await signalDaemonShutdown({ pid: handle.record.pid, startStamp: handle.record.startStamp }),\n      \"could not be reached over the wire\",\n      reports,\n    );\n  }\n}\n\nfunction reportSignalShutdown(\n  ctx: ICommandContext,\n  result: Awaited<ReturnType<typeof signalDaemonShutdown>>,\n  why: string,\n  reports: Record<string, unknown>[],\n): number {\n  const { out } = ctx;\n  const code =\n    result.outcome === \"exited\" || result.outcome === \"not-running\" ? EXIT.ok : EXIT.failure;\n  reports.push({ ok: result.outcome === \"exited\", via: \"signal\", ...result });\n  if (out.json) return code;\n  switch (result.outcome) {\n    case \"exited\":\n      out.print(\n        `daemon for \"${ctx.config.name}\" (pid ${result.pid}) ${why} — stopped via signal ` +\n          \"(its own shutdown ladder ran)\",\n      );\n      break;\n    case \"still-stopping\":\n      out.print(\n        out.paint(\n          \"yellow\",\n          `⚠ daemon (pid ${result.pid}) was signalled and is still stopping — run ` +\n            \"`shutdown` again to escalate if it stays stuck\",\n        ),\n      );\n      break;\n    case \"identity-unverified\":\n      out.print(\n        out.paint(\n          \"yellow\",\n          `⚠ pid ${result.pid} could not be verified as this config's daemon (start stamp ` +\n            \"missing or changed — possibly pid reuse). Nothing was killed; verify the pid \" +\n            \"yourself, and remove the instance record if the daemon is really gone.\",\n        ),\n      );\n      break;\n    case \"not-running\":\n      out.print(`daemon not running for \"${ctx.config.name}\" (stale record)`);\n      break;\n  }\n  return code;\n}\n","// The sticky env-override store: `<stateDir>/env-overrides.json`, one file per config (D6).\n// Values set from the UI or `nice-commander env` live here and apply to EVERY later start until\n// cleared — so this file is the answer to \"why is that port weird\", and every surface that can\n// print it does.\n//\n// One writer at a time: the daemon owns the file while it is alive (CLI mutations arrive as the\n// `setEnv` control action), and the CLI writes it directly only when no daemon is running — the\n// same split as `up` vs `run`.\n\nimport { mkdir, readFile, rename, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { checkEnvMutations, type TEnvMutations, type TEnvOverrides } from \"../config/envVars\";\nimport type { IResolvedCommanderConfig } from \"../config/types\";\n\nconst STORE_VERSION = 1;\n/** A knob is a port or a log level, not a payload. Bounds keep a mistake from becoming a file. */\nconst MAX_VALUE_LENGTH = 4096;\n\nexport interface IEnvOverrideStore {\n  version: number;\n  processes: Record<string, Record<string, string>>;\n}\n\nexport const EMPTY_ENV_OVERRIDES: TEnvOverrides = Object.freeze({});\n\nfunction readable(value: unknown): Record<string, Record<string, string>> | null {\n  if (value == null || typeof value !== \"object\") return null;\n  const processes = (value as { processes?: unknown }).processes;\n  if (processes == null || typeof processes !== \"object\" || Array.isArray(processes)) return null;\n  const clean: Record<string, Record<string, string>> = {};\n  for (const [id, values] of Object.entries(processes)) {\n    if (values == null || typeof values !== \"object\" || Array.isArray(values)) continue;\n    const entries: Record<string, string> = {};\n    for (const [name, entry] of Object.entries(values)) {\n      if (typeof entry === \"string\" && entry.length <= MAX_VALUE_LENGTH) entries[name] = entry;\n    }\n    if (Object.keys(entries).length > 0) clean[id] = entries;\n  }\n  return clean;\n}\n\n/**\n * Missing, unreadable or corrupt all read as \"no overrides\". A bad file must never block a start:\n * the config alone is always enough to run, and the surfaces that report overrides say when the\n * store could not be read.\n */\nexport async function readEnvOverrides(path: string): Promise<TEnvOverrides> {\n  try {\n    return readable(JSON.parse(await readFile(path, \"utf8\"))) ?? EMPTY_ENV_OVERRIDES;\n  } catch {\n    return EMPTY_ENV_OVERRIDES;\n  }\n}\n\n/** 0600 and atomic — it can hold a token, and a half-written file must never be read as empty. */\nexport async function writeEnvOverrides(path: string, overrides: TEnvOverrides): Promise<void> {\n  await mkdir(dirname(path), { recursive: true, mode: 0o700 });\n  const store: IEnvOverrideStore = {\n    version: STORE_VERSION,\n    processes: Object.fromEntries(\n      Object.entries(overrides)\n        .filter(([, values]) => Object.keys(values).length > 0)\n        .map(([id, values]) => [id, { ...values }]),\n    ),\n  };\n  const temp = `${path}.${process.pid}.tmp`;\n  await writeFile(temp, `${JSON.stringify(store, null, 2)}\\n`, { encoding: \"utf8\", mode: 0o600 });\n  await rename(temp, path);\n}\n\nexport interface IEnvMutation {\n  mutations?: TEnvMutations;\n  /** Ids whose every override is dropped first — `--clear`, and the only thing that removes a\n   *  stale entry the config can no longer explain. */\n  clear?: readonly string[];\n}\n\n/** Pure: the store that results from applying `change`. Empty processes are pruned. */\nexport function mutateEnvOverrides(current: TEnvOverrides, change: IEnvMutation): TEnvOverrides {\n  const next: Record<string, Record<string, string>> = {};\n  for (const [id, values] of Object.entries(current)) next[id] = { ...values };\n  for (const id of change.clear ?? []) delete next[id];\n  for (const [id, values] of Object.entries(change.mutations ?? {})) {\n    const entries = next[id] ?? {};\n    for (const [name, value] of Object.entries(values)) {\n      if (value == null) delete entries[name];\n      else entries[name] = value;\n    }\n    if (Object.keys(entries).length > 0) next[id] = entries;\n    else delete next[id];\n  }\n  return next;\n}\n\n/**\n * Read → check against the config → mutate → write, atomically enough for a file two surfaces\n * touch. The one implementation behind both writers, so the daemon's `setEnv` and the CLI's\n * no-daemon path can never diverge on what they accept.\n */\nexport async function applyEnvMutation(\n  path: string,\n  config: IResolvedCommanderConfig,\n  input: {\n    processes: Readonly<Record<string, Readonly<Record<string, string | null>>>>;\n    clear?: readonly string[];\n  },\n): Promise<{ overrides: TEnvOverrides; warnings: string[] }> {\n  const checked = checkEnvMutations(config, input);\n  const next = mutateEnvOverrides(await readEnvOverrides(path), checked);\n  await writeEnvOverrides(path, next);\n  return { overrides: next, warnings: checked.warnings };\n}\n\nexport function countOverrides(overrides: TEnvOverrides): number {\n  return Object.values(overrides).reduce((total, values) => total + Object.keys(values).length, 0);\n}\n","// \"Is this port owner a copy of the definition it is blocking?\" — the question behind a port\n// takeover. A listener started by hand (`bun run dev` in a terminal that has since gone away) is\n// not a stranger: its argv and cwd are the definition's own. Matching walks the listener's\n// ancestry because the socket is usually held by a grandchild (`bun run dev` → vite → the\n// listener), so the definition's command sits a few parents up.\n//\n// A match is argv + cwd, both exact after normalization. Nothing weaker: a port owner that\n// merely runs the same binary from elsewhere is still a stranger and is still never killed.\n\nimport { execFile } from \"node:child_process\";\nimport { realpath } from \"node:fs/promises\";\nimport { basename } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { readProcessStartStamp } from \"@nice-code/process\";\nimport type { IResolvedCommanderProcess } from \"../config/types\";\n\nconst exec = promisify(execFile);\n\n/** How many parents above the listener are examined. Deeper than any dev-server wrapper stack. */\nconst MAX_ANCESTRY = 8;\n\nconst SHELLS = new Set([\"sh\", \"bash\", \"zsh\", \"dash\", \"fish\", \"ksh\"]);\n\n/** One process in the listener's ancestry, identity-stamped so a later signal can re-verify it. */\nexport interface IStrayMember {\n  pid: number;\n  startStamp: string | null;\n}\n\n/**\n * A port owner that IS the definition: `root` is the ancestor whose argv+cwd matched (often the\n * listener itself), `chain` runs from the listener up to and including that root — the whole\n * stray tree, every member of which was verified to be the previous one's parent.\n */\nexport interface IStray {\n  root: IStrayMember;\n  chain: IStrayMember[];\n}\n\n/** argv as a single comparable string: argv[0] reduced to its basename, whitespace collapsed. */\nexport function canonicalCommand(args: string): string {\n  const tokens = args\n    .trim()\n    .split(/\\s+/)\n    .filter((token) => token !== \"\");\n  if (tokens.length === 0) return \"\";\n  tokens[0] = basename(tokens[0] ?? \"\");\n  // A shell-string definition runs as `sh -c <string>`; compare what the shell was handed.\n  if (tokens.length >= 3 && SHELLS.has(tokens[0] ?? \"\") && tokens[1] === \"-c\") {\n    return tokens.slice(2).join(\" \");\n  }\n  return tokens.join(\" \");\n}\n\n/** The definition's command in the same canonical form a live process's argv reduces to. */\nexport function definitionCommand(definition: Pick<IResolvedCommanderProcess, \"run\">): string {\n  return canonicalCommand(\n    typeof definition.run === \"string\" ? definition.run : definition.run.join(\" \"),\n  );\n}\n\ninterface IProcessIdentity {\n  ppid: number | null;\n  args: string;\n}\n\nasync function readIdentity(pid: number): Promise<IProcessIdentity | null> {\n  const ps = await exec(\"ps\", [\"-p\", String(pid), \"-o\", \"ppid=\", \"-o\", \"args=\"], {\n    timeout: 5000,\n  }).catch(() => null);\n  const match = ps?.stdout.trim().match(/^(\\d+)\\s+(.*)$/s);\n  if (match == null) return null;\n  const ppid = Number(match[1]);\n  return { ppid: Number.isInteger(ppid) ? ppid : null, args: match[2] ?? \"\" };\n}\n\nasync function readCwd(pid: number): Promise<string | null> {\n  const lsof = await exec(\"lsof\", [\"-a\", \"-p\", String(pid), \"-d\", \"cwd\", \"-Fn\"], {\n    timeout: 5000,\n  }).catch(() => null);\n  const line = lsof?.stdout.split(\"\\n\").find((entry) => entry.startsWith(\"n\"));\n  return line == null ? null : line.slice(1);\n}\n\nasync function samePath(a: string, b: string): Promise<boolean> {\n  if (a === b) return true;\n  const [ra, rb] = await Promise.all([realpath(a).catch(() => a), realpath(b).catch(() => b)]);\n  return ra === rb;\n}\n\n/**\n * Walk up from `listenerPid` looking for the definition's argv+cwd. Null when nothing in the\n * bounded ancestry matches, when the platform cannot answer (no `ps`/`lsof`), or when the walk\n * reaches a protected pid — commander itself and its ancestors are never part of a stray.\n */\nexport async function findStray(\n  listenerPid: number,\n  definition: Pick<IResolvedCommanderProcess, \"run\" | \"cwd\">,\n  protectedPids: ReadonlySet<number>,\n): Promise<IStray | null> {\n  if (process.platform === \"win32\") return null;\n  const wanted = definitionCommand(definition);\n  if (wanted === \"\") return null;\n  const chain: IStrayMember[] = [];\n  let pid = listenerPid;\n  for (let depth = 0; depth <= MAX_ANCESTRY; depth += 1) {\n    if (pid <= 1 || protectedPids.has(pid)) return null;\n    const identity = await readIdentity(pid);\n    if (identity == null) return null;\n    const stamp = await readProcessStartStamp(pid);\n    const member: IStrayMember = { pid, startStamp: stamp?.stamp ?? null };\n    chain.push(member);\n    if (canonicalCommand(identity.args) === wanted) {\n      const cwd = await readCwd(pid);\n      if (cwd != null && (await samePath(cwd, definition.cwd))) return { root: member, chain };\n    }\n    if (identity.ppid == null) return null;\n    pid = identity.ppid;\n  }\n  return null;\n}\n\n/** Still the process we saw? A reused pid fails this and is left alone. */\nasync function stillSame(member: IStrayMember): Promise<boolean> {\n  if (member.startStamp == null) return false;\n  const stamp = await readProcessStartStamp(member.pid);\n  return stamp?.stamp === member.startStamp;\n}\n\n/**\n * Signal every verified member of the stray tree, root first (a wrapper such as `bun run`\n * forwards the signal and exits; signalling the leaf alone lets a watcher respawn it). Members\n * whose identity no longer checks out are skipped, never guessed at.\n */\nexport async function signalStray(stray: IStray, signal: \"SIGTERM\" | \"SIGKILL\"): Promise<number> {\n  let signalled = 0;\n  for (const member of [...stray.chain].reverse()) {\n    if (!(await stillSame(member))) continue;\n    try {\n      process.kill(member.pid, signal);\n      signalled += 1;\n    } catch {\n      // already gone\n    }\n  }\n  return signalled;\n}\n","import { execFile } from \"node:child_process\";\nimport { randomUUID } from \"node:crypto\";\nimport { lookup } from \"node:dns/promises\";\nimport { networkInterfaces } from \"node:os\";\nimport { promisify } from \"node:util\";\nimport { readProcessStartStamp } from \"@nice-code/process\";\nimport type { IResolvedCommanderConfig } from \"../config/types\";\nimport type { IPortListener, IPortsInput, IPortsReport } from \"../protocol/ports\";\nimport { findStray, type IStray, signalStray } from \"./definitionMatch\";\n\nconst exec = promisify(execFile);\nconst ACTIVE = new Set([\"starting\", \"running\", \"ready\", \"unready\", \"backoff\"]);\nconst normalize = (host: string) => host.replace(/^\\[|\\]$/g, \"\").replace(/^::ffff:/, \"\");\n\n/** Machine-readable lsof output: keep the address attached to its PID (multiple FDs/PIDs allowed). */\nexport function parseLsof(text: string): { pid: number; command: string; address: string }[] {\n  const result: { pid: number; command: string; address: string }[] = [];\n  let pid = 0;\n  let command = \"\";\n  for (const line of text.split(\"\\n\")) {\n    if (line.startsWith(\"p\")) {\n      pid = Number(line.slice(1));\n      command = \"\";\n    }\n    if (line.startsWith(\"c\")) command = line.slice(1);\n    if (line.startsWith(\"n\") && Number.isInteger(pid) && pid > 0)\n      result.push({ pid, command, address: line.slice(1) });\n  }\n  return result;\n}\n\nexport async function listeners(port: number) {\n  if (process.platform === \"win32\")\n    throw new Error(\n      \"Port owner inspection requires lsof on macOS/Linux; Windows is not supported yet.\",\n    );\n  try {\n    const { stdout } = await exec(\"lsof\", [\"-nP\", `-iTCP:${port}`, \"-sTCP:LISTEN\", \"-Fpcn\"], {\n      timeout: 5000,\n      maxBuffer: 1024 * 1024,\n    });\n    return parseLsof(stdout);\n  } catch (error) {\n    const e = error as NodeJS.ErrnoException & { stdout?: string; stderr?: string };\n    if (Number(e.code) === 1 && !e.stderr?.trim()) return parseLsof(e.stdout ?? \"\");\n    throw new Error(\n      `Cannot inspect TCP ${port}: ${e.code === \"ENOENT\" ? \"install lsof and retry\" : e.message}`,\n      { cause: error },\n    );\n  }\n}\n\nexport async function localAddresses(host: string): Promise<string[]> {\n  const local = new Set([\n    \"127.0.0.1\",\n    \"::1\",\n    \"0.0.0.0\",\n    \"::\",\n    ...Object.values(networkInterfaces()).flatMap(\n      (entries) => entries?.map((e) => normalize(e.address)) ?? [],\n    ),\n  ]);\n  const addresses = (await lookup(host, { all: true })).map((a) => normalize(a.address));\n  if (!addresses.length || addresses.some((a) => !local.has(a) && !a.startsWith(\"127.\")))\n    throw new Error(`Endpoint host ${host} is not local; no local processes will be selected.`);\n  return addresses;\n}\n\nexport function addressMatches(address: string, port: number, hosts: string[]): boolean {\n  const split = address.lastIndexOf(\":\");\n  if (Number(address.slice(split + 1)) !== port) return false;\n  const host = normalize(address.slice(0, split));\n  return (\n    host === \"*\" ||\n    host === \"0.0.0.0\" ||\n    host === \"::\" ||\n    hosts.includes(host) ||\n    hosts.includes(\"0.0.0.0\") ||\n    hosts.includes(\"::\")\n  );\n}\n\nasync function processDetails(pid: number) {\n  const [ps, cwd] = await Promise.all([\n    exec(\"ps\", [\"-p\", String(pid), \"-o\", \"ppid=\", \"-o\", \"comm=\"], { timeout: 5000 }).catch(\n      () => null,\n    ),\n    exec(\"lsof\", [\"-a\", \"-p\", String(pid), \"-d\", \"cwd\", \"-Fn\"], { timeout: 5000 }).catch(\n      () => null,\n    ),\n  ]);\n  const match = ps?.stdout.trim().match(/^(\\d+)\\s+(.+)$/);\n  return {\n    ppid: match ? Number(match[1]) : null,\n    command: match?.[2],\n    cwd:\n      cwd?.stdout\n        .split(\"\\n\")\n        .find((l) => l.startsWith(\"n\"))\n        ?.slice(1) ?? null,\n  };\n}\n\n/** Commander itself and everything above it — never a kill target, never part of a stray. */\nexport async function ancestors(): Promise<number[]> {\n  const result = [1, process.pid, process.ppid];\n  let pid = process.ppid;\n  while (pid > 1) {\n    const ps = await exec(\"ps\", [\"-p\", String(pid), \"-o\", \"ppid=\"], { timeout: 5000 }).catch(\n      () => null,\n    );\n    const parent = Number(ps?.stdout.trim());\n    if (!Number.isInteger(parent) || parent < 1 || result.includes(parent)) break;\n    result.push(parent);\n    pid = parent;\n  }\n  return result;\n}\n\n/** What holds a definition's exclusive endpoint, with the stray verdict the supervisor acts on. */\nexport interface IEndpointOwner {\n  pid: number;\n  command: string;\n  cwd: string | null;\n  /** Non-null when the owner is this definition's own command running outside the daemon. */\n  stray: IStray | null;\n}\n\n/**\n * The first visible listener on one exclusive endpoint, identified. Null when nothing local is\n * visible on it; throws where the platform cannot answer (no `lsof`, Windows) — the caller\n * falls back to \"in use by something\" rather than guessing.\n */\nexport async function identifyEndpointOwner(\n  definition: IResolvedCommanderConfig[\"processes\"][number],\n  endpoint: { host: string; port: number },\n  protectedPids: ReadonlySet<number>,\n): Promise<IEndpointOwner | null> {\n  const hosts = await localAddresses(endpoint.host);\n  const owners = await listeners(endpoint.port);\n  const owner = owners.find(\n    (candidate) =>\n      addressMatches(candidate.address, endpoint.port, hosts) && !protectedPids.has(candidate.pid),\n  );\n  if (owner == null) return null;\n  const details = await processDetails(owner.pid);\n  return {\n    pid: owner.pid,\n    command: details.command ?? owner.command,\n    cwd: details.cwd,\n    stray: await findStray(owner.pid, definition, protectedPids),\n  };\n}\n\n/** Inspection and mutation share this service in the CLI and authenticated daemon control plane. */\nexport function createPortInspector(options: {\n  config: () => IResolvedCommanderConfig;\n  states: () => Promise<Map<string, string>>;\n  protectedPids?: () => Promise<number[]>;\n}) {\n  const snapshots = new Map<\n    string,\n    { listener: IPortListener; stray: IStray | null; expires: number }\n  >();\n  async function inspect(ids: string[]): Promise<IPortsReport> {\n    for (const [key, entry] of snapshots) if (entry.expires < Date.now()) snapshots.delete(key);\n    const report: IPortsReport = { listeners: [], warnings: [] };\n    const states = await options.states();\n    const protectedPids = new Set([\n      ...(await ancestors()),\n      ...((await options.protectedPids?.()) ?? []),\n    ]);\n    const config = options.config();\n    const ports = new Map<number, Awaited<ReturnType<typeof listeners>>>();\n    for (const id of new Set(ids)) {\n      const proc = config.processes.find((p) => p.id === id);\n      if (!proc) {\n        report.warnings.push(`Unknown process: ${id}`);\n        continue;\n      }\n      for (const endpoint of proc.endpoints) {\n        if (endpoint.ownership !== \"exclusive\") continue;\n        try {\n          const hosts = await localAddresses(endpoint.host);\n          let found = ports.get(endpoint.port);\n          if (!found) {\n            found = await listeners(endpoint.port);\n            ports.set(endpoint.port, found);\n          }\n          const seen = new Set<number>();\n          for (const owner of found) {\n            if (!addressMatches(owner.address, endpoint.port, hosts) || seen.has(owner.pid))\n              continue;\n            seen.add(owner.pid);\n            const stamp = await readProcessStartStamp(owner.pid);\n            const details = await processDetails(owner.pid);\n            const stray = await findStray(owner.pid, proc, protectedPids);\n            // Any active definition sharing this port may own the listener via a child process.\n            const managed = config.processes.some(\n              (p) =>\n                ACTIVE.has(states.get(p.id) ?? \"\") &&\n                p.endpoints.some((e) => e.port === endpoint.port),\n            );\n            const refusal = protectedPids.has(owner.pid)\n              ? \"Commander or its parent cannot be terminated here\"\n              : managed\n                ? \"A configured process using this port is active; use its stop control first\"\n                : stamp == null\n                  ? \"Process identity is unavailable\"\n                  : null;\n            const listener: IPortListener = {\n              id,\n              endpoint: endpoint.name,\n              host: endpoint.host,\n              port: endpoint.port,\n              pid: owner.pid,\n              command: details.command ?? owner.command,\n              ppid: details.ppid,\n              cwd: details.cwd,\n              startStamp: stamp?.stamp ?? null,\n              stray: stray != null,\n              strayRoot: stray?.root.pid ?? null,\n              refusal,\n              token: refusal == null ? randomUUID() : null,\n            };\n            if (listener.token) {\n              if (snapshots.size >= 1000) snapshots.delete(snapshots.keys().next().value!);\n              snapshots.set(listener.token, { listener, stray, expires: Date.now() + 300_000 });\n            }\n            report.listeners.push(listener);\n          }\n        } catch (error) {\n          report.warnings.push(`${id}.${endpoint.name}: ${(error as Error).message}`);\n        }\n      }\n    }\n    return report;\n  }\n  async function run(input: IPortsInput): Promise<IPortsReport> {\n    if (!input.token) return inspect(input.ids);\n    const snapshot = snapshots.get(input.token);\n    snapshots.delete(input.token); // one use, including refusals\n    if (!snapshot || snapshot.expires < Date.now() || !input.ids.includes(snapshot.listener.id))\n      return {\n        listeners: [],\n        warnings: [\"Inspection expired or does not match this selection. Inspect ports again.\"],\n      };\n    const target = snapshot.listener;\n    const fresh = await inspect([target.id]);\n    const current = fresh.listeners.find(\n      (l) =>\n        l.pid === target.pid &&\n        l.endpoint === target.endpoint &&\n        l.host === target.host &&\n        l.port === target.port &&\n        l.startStamp === target.startStamp &&\n        l.command === target.command &&\n        l.strayRoot === target.strayRoot,\n    );\n    if (!current || current.refusal)\n      return {\n        listeners: fresh.listeners,\n        warnings: [\n          ...fresh.warnings,\n          current?.refusal ??\n            \"Listener changed or exited; nothing was killed. Inspect ports again.\",\n        ],\n      };\n    // Inspection may cover several endpoints. Recheck this socket and the current managed\n    // states after that work, so a release or intervening start cannot use a cached port list.\n    try {\n      const hosts = await localAddresses(target.host);\n      const owners = await listeners(target.port);\n      const states = await options.states();\n      const config = options.config();\n      const endpointStillConfigured = config.processes\n        .find((p) => p.id === target.id)\n        ?.endpoints.some(\n          (e) =>\n            e.name === target.endpoint &&\n            e.host === target.host &&\n            e.port === target.port &&\n            e.ownership === \"exclusive\",\n        );\n      const managed = config.processes.some(\n        (p) =>\n          ACTIVE.has(states.get(p.id) ?? \"\") && p.endpoints.some((e) => e.port === target.port),\n      );\n      if (\n        !endpointStillConfigured ||\n        managed ||\n        !owners.some((p) => p.pid === target.pid && addressMatches(p.address, target.port, hosts))\n      ) {\n        return {\n          listeners: [],\n          warnings: [\"Endpoint ownership changed; nothing was killed. Inspect ports again.\"],\n        };\n      }\n    } catch (error) {\n      return {\n        listeners: [],\n        warnings: [`Cannot verify endpoint ownership: ${(error as Error).message}`],\n      };\n    }\n    // Re-read immediately before signalling; never signal a group or descendants of an unknown owner.\n    const stamp = await readProcessStartStamp(target.pid);\n    if (!stamp || stamp.stamp !== target.startStamp)\n      return { listeners: [], warnings: [\"Process identity changed; nothing was killed.\"] };\n    const signal = input.force ? \"SIGKILL\" : \"SIGTERM\";\n    // A stray is ended as the tree that was matched, root first: signalling only the listener\n    // leaves its `bun run` wrapper — or a watcher — alive to respawn it. Every member was\n    // verified as the previous one's parent, and each is re-verified by start stamp here.\n    if (snapshot.stray != null) {\n      if ((await signalStray(snapshot.stray, signal)) === 0) {\n        return { listeners: [], warnings: [\"Stray tree already gone; nothing was killed.\"] };\n      }\n    } else {\n      try {\n        process.kill(target.pid, signal);\n      } catch (error) {\n        return {\n          listeners: fresh.listeners,\n          warnings: [`Cannot stop PID ${target.pid}: ${(error as Error).message}`],\n        };\n      }\n    }\n    const deadline = Date.now() + 2000;\n    while (Date.now() < deadline) {\n      await new Promise((resolve) => setTimeout(resolve, 100));\n      const owners = await listeners(target.port).catch(() => null);\n      if (owners && !owners.some((p) => p.pid === target.pid)) return inspect(input.ids);\n    }\n    const after = await inspect(input.ids);\n    after.warnings.push(\n      `PID ${target.pid} was signalled but has not released the port. Inspect again; force kill is a separate choice.`,\n    );\n    return after;\n  }\n  return { run };\n}\n","// \"Is this variable set?\" is a question about the environment a start inherits: the daemon's when\n// one is up — its children get that one, whatever shell typed the command — and this shell's\n// otherwise. The daemon already answers it on the status realm (each declared variable's `source`\n// is judged there, in its own environment), so asking it needs nothing new on the wire.\n\nimport { describeJudgedIn, type TEnvJudgedIn } from \"../config/envVars\";\nimport type { IResolvedCommanderConfig, IResolvedCommanderProcess } from \"../config/types\";\nimport { connectDaemon, findDaemon, type IDaemonHandle } from \"./daemonClient\";\nimport { CliExit } from \"./load\";\n\nexport interface IEnvJudge {\n  judgedIn: TEnvJudgedIn;\n  /** One line for the reader: which environment answered, and why that one. */\n  note: string;\n  /** What `envVarViews` / `missingRequired` read presence from, for one process. */\n  baseEnv(definition: IResolvedCommanderProcess): NodeJS.ProcessEnv;\n}\n\nexport function shellEnvJudge(unreachable?: string): IEnvJudge {\n  return {\n    judgedIn: \"shell\",\n    note:\n      unreachable == null\n        ? `no daemon is running — whether a variable is set is judged in ` +\n          `${describeJudgedIn(\"shell\")}, which a daemon started from here inherits`\n        : `the daemon could not be asked (${unreachable}) — whether a variable is set is ` +\n          `judged in ${describeJudgedIn(\"shell\")} instead`,\n    baseEnv: () => process.env,\n  };\n}\n\n/** The part of the status realm a judge reads: each declared variable's `source`, per process. */\nexport interface IJudgedEnvState {\n  processes: Readonly<\n    Record<string, { detail: { envVars: readonly { name: string; source: string }[] } }>\n  >;\n}\n\n/** Reads `state` now, not when asked: the judge outlives the connection it came from. */\nexport function daemonEnvJudge(state: IJudgedEnvState, daemonPid: number): IEnvJudge {\n  const judged = new Map(\n    Object.entries(state.processes).map(([id, node]) => [\n      id,\n      new Map(node.detail.envVars.map((view) => [view.name, view.source])),\n    ]),\n  );\n  return {\n    judgedIn: \"daemon\",\n    note:\n      `whether a variable is set is judged in ${describeJudgedIn(\"daemon\")} (pid ${daemonPid}) ` +\n      \"— what `up` starts inherits that one, not this shell's\",\n    baseEnv: (definition) => {\n      // Only presence is ever read from a base env, so \"the daemon has it\" is an empty value.\n      const env: NodeJS.ProcessEnv = {};\n      for (const declared of definition.envVars) {\n        const source = judged.get(definition.id)?.get(declared.name);\n        // The daemon looked in its environment only where no override or default came first. A\n        // name it never judged — its config is a revision behind this one — is read here instead.\n        const set =\n          source === \"inherited\" || (source !== \"unset\" && process.env[declared.name] != null);\n        if (set) env[declared.name] = \"\";\n      }\n      return env;\n    },\n  };\n}\n\n/**\n * The judge for a read-only command. A daemon this build cannot talk to must not fail a command\n * that only wanted its opinion — the shell answers, and the note says why.\n */\nexport async function judgeEnv(\n  config: IResolvedCommanderConfig,\n  known?: IDaemonHandle | null,\n): Promise<IEnvJudge> {\n  const handle = known === undefined ? await findDaemon(config) : known;\n  if (handle == null) return shellEnvJudge();\n  try {\n    const client = await connectDaemon(handle);\n    try {\n      return daemonEnvJudge(client.state(), handle.record.pid);\n    } finally {\n      client.dispose();\n    }\n  } catch (error) {\n    if (!(error instanceof CliExit)) throw error;\n    return shellEnvJudge(error.message);\n  }\n}\n","import { createInterface } from \"node:readline/promises\";\nimport { createPortInspector } from \"../../ports/listeners\";\nimport type { IPortListener, IPortsReport } from \"../../protocol/ports\";\nimport { numericFlag, unknownFlags } from \"../args\";\nimport { type ICommandContext, selectOrExit } from \"../context\";\nimport { connectDaemon, findDaemon } from \"../daemonClient\";\nimport { CliExit, EXIT } from \"../load\";\n\nexport async function portProcessStates(ctx: ICommandContext): Promise<Map<string, string>> {\n  const handle = await findDaemon(ctx.config);\n  if (!handle) return new Map();\n  const client = await connectDaemon(handle);\n  try {\n    return new Map(Object.entries(client.state().processes).map(([id, p]) => [id, p.state]));\n  } finally {\n    client.dispose();\n  }\n}\n\n/** One row per listener; the STRAY column is the verdict that decides what a stop will end. */\nexport function renderListeners(ctx: ICommandContext, result: IPortsReport): string {\n  return ctx.out.table(\n    [\"PROCESS\", \"ENDPOINT\", \"PID\", \"PARENT\", \"COMMAND\", \"CWD\", \"STRAY\", \"IDENTITY\", \"STOP\"],\n    result.listeners.map((l) => [\n      l.id,\n      `${l.host}:${l.port}`,\n      String(l.pid),\n      String(l.ppid ?? \"unknown\"),\n      l.command,\n      l.cwd ?? \"unavailable\",\n      strayCell(l),\n      l.startStamp ?? \"unknown\",\n      l.refusal ?? \"available\",\n    ]),\n  );\n}\n\nexport function strayCell(listener: IPortListener): string {\n  if (!listener.stray) return \"no\";\n  return listener.strayRoot != null && listener.strayRoot !== listener.pid\n    ? `yes (root ${listener.strayRoot})`\n    : \"yes\";\n}\n\n/** `[y/N]` on a TTY; scripts pass `--yes` or get a usage error, never a silent kill. */\nexport async function confirmKill(\n  ctx: ICommandContext,\n  question: string,\n  reportForRefusal: () => void,\n): Promise<boolean> {\n  if (ctx.args.flags.has(\"--yes\")) return true;\n  reportForRefusal();\n  if (!process.stdin.isTTY || ctx.out.json) {\n    throw new CliExit(\n      EXIT.usage,\n      \"Stopping requires interactive confirmation, or --yes for scripts\",\n    );\n  }\n  const rl = createInterface({ input: process.stdin, output: process.stdout });\n  try {\n    const answer = await rl.question(`${question} [y/N] `);\n    return /^y(es)?$/i.test(answer.trim());\n  } finally {\n    rl.close();\n  }\n}\n\nexport async function cmdPorts(ctx: ICommandContext): Promise<number> {\n  const bad = unknownFlags(ctx.args.flags, [\"--all\", \"--kill\", \"--kill-owner\", \"--yes\", \"--force\"]);\n  if (bad) throw new CliExit(EXIT.usage, bad);\n  const pid = numericFlag(ctx.args.flags, \"--kill\");\n  if (pid != null && typeof pid !== \"number\") throw new CliExit(EXIT.usage, pid.error);\n  for (const flag of [\"--yes\", \"--force\", \"--all\", \"--kill-owner\"]) {\n    if (ctx.args.flags.has(flag) && ctx.args.flags.get(flag) !== true)\n      throw new CliExit(EXIT.usage, `${flag} takes no value`);\n  }\n  const killOwner = ctx.args.flags.has(\"--kill-owner\");\n  if (pid != null && killOwner) {\n    throw new CliExit(EXIT.usage, \"--kill PID and --kill-owner are alternatives; pass one\");\n  }\n  if (!pid && !killOwner && (ctx.args.flags.has(\"--force\") || ctx.args.flags.has(\"--yes\")))\n    throw new CliExit(EXIT.usage, \"--force/--yes require --kill PID or --kill-owner\");\n  if (killOwner && ctx.args.positionals.length === 0 && !ctx.args.flags.has(\"--all\")) {\n    throw new CliExit(EXIT.usage, \"--kill-owner needs a selection (ids, suite, tag=val) or --all\");\n  }\n  const ids =\n    ctx.args.positionals.length || ctx.args.flags.has(\"--all\")\n      ? selectOrExit(ctx, { bare: \"required\" }).direct\n      : ctx.config.processes.map((p) => p.id);\n  const inspector = createPortInspector({\n    config: () => ctx.config,\n    states: () => portProcessStates(ctx),\n    protectedPids: async () => {\n      const daemon = await findDaemon(ctx.config);\n      return daemon ? [daemon.record.pid] : [];\n    },\n  });\n  const report = await inspector.run({ ids });\n  const print = (result: IPortsReport) => {\n    if (ctx.out.json) {\n      ctx.out.printJson(result);\n      return;\n    }\n    ctx.out.print(renderListeners(ctx, result));\n    if (!result.listeners.length)\n      ctx.out.print(\"No visible listeners on the selected exclusive TCP endpoints.\");\n    for (const warning of result.warnings) ctx.out.warn(warning);\n  };\n  const force = ctx.args.flags.has(\"--force\");\n  const verb = force ? \"Force kill\" : \"Stop\";\n  const describe = (target: IPortListener) =>\n    `${target.stray ? \"stray \" : \"\"}PID ${target.pid} (${target.command}) on ${target.host}:${target.port}` +\n    (target.stray && target.strayRoot != null && target.strayRoot !== target.pid\n      ? ` and its root PID ${target.strayRoot}`\n      : \"\");\n\n  if (killOwner) {\n    // Whatever holds the selection's exclusive endpoints, one verified listener at a time; each\n    // stop re-inspects, so the next target is chosen against the live picture, never a cached one.\n    let current = report;\n    const attempted = new Set<number>();\n    const warnings: string[] = [];\n    let stopped = 0;\n    for (;;) {\n      const target = current.listeners.find((l) => l.token != null && !attempted.has(l.pid));\n      if (target?.token == null) break;\n      attempted.add(target.pid);\n      const go = await confirmKill(ctx, `${verb} ${describe(target)}?`, () => print(current));\n      if (!go) continue;\n      current = await inspector.run({ ids, token: target.token, force });\n      warnings.push(...current.warnings);\n      if (!current.listeners.some((l) => l.pid === target.pid)) stopped += 1;\n    }\n    const refused = current.listeners.filter((l) => l.refusal != null);\n    print({ listeners: current.listeners, warnings: [...new Set(warnings)] });\n    if (!ctx.out.json) {\n      ctx.out.print(\n        `kill-owner: ${stopped} stopped` +\n          (refused.length > 0 ? `, ${refused.length} refused (see STOP)` : \"\") +\n          (current.listeners.length === 0 ? \" — selected endpoints are free\" : \"\"),\n      );\n    }\n    return warnings.length > 0 || current.listeners.some((l) => l.token != null)\n      ? EXIT.failure\n      : EXIT.ok;\n  }\n\n  if (!pid) {\n    print(report);\n    return report.warnings.length ? EXIT.failure : EXIT.ok;\n  }\n  const target = report.listeners.find((l) => l.pid === pid);\n  if (!target?.token) {\n    print(report);\n    throw new CliExit(\n      EXIT.failure,\n      target?.refusal ?? `PID ${pid} is not a verified listener on the selected endpoints`,\n    );\n  }\n  const go = await confirmKill(ctx, `${verb} ${describe(target)}?`, () => print(report));\n  if (!go) return EXIT.ok;\n  const result = await inspector.run({ ids, token: target.token, force });\n  print(result);\n  return result.warnings.length ? EXIT.failure : EXIT.ok;\n}\n","// `doctor` — read-only diagnostics over config, ledger, capability, endpoints and environment.\n// It reports; it never kills, never adopts, never autostarts. A cross-world or foreign endpoint\n// holder is an actionable diagnostic, never an authorization to kill.\n//\n// Two explicit exceptions, each behind its own flag. `--reap` is the same orphan reap the next\n// daemon boot would run, invocable by the operator who just diagnosed a crash — refused while a\n// live daemon owns the ledger, and carrying every safety rail the boot-time scavenger has.\n// `--reap-strays` stops the listeners on configured exclusive ports that are this config's OWN\n// commands running outside the daemon (argv + cwd verified) — and only those; a stranger on a\n// port is listed and left alone.\n\nimport { statSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { connect } from \"node:net\";\nimport { detectCapability, matchProcessStartStamp, openProcessLedger } from \"@nice-code/process\";\nimport {\n  missingRequired,\n  overridesOffEndpoint,\n  requiredRefusal,\n  staleOverrides,\n} from \"../../config/envVars\";\nimport { commanderStatePaths, resolveCommanderDataDir } from \"../../daemon/dataDir\";\nimport { countOverrides, readEnvOverrides } from \"../../daemon/envOverrides\";\nimport { pingDaemon } from \"../../daemon/instanceRecord\";\nimport { createPortInspector } from \"../../ports/listeners\";\nimport type { IPortListener } from \"../../protocol/ports\";\nimport { unknownFlags } from \"../args\";\nimport type { ICommandContext } from \"../context\";\nimport { connectDaemon, findDaemon, findSkewedDaemon, type IDaemonHandle } from \"../daemonClient\";\nimport { judgeEnv } from \"../envJudge\";\nimport { CliExit, EXIT } from \"../load\";\nimport { confirmKill, renderListeners } from \"./ports\";\n\n/** Quarantine entries listed individually — the rest are counted, not dumped. */\nconst QUARANTINE_SHOWN = 10;\n\nfunction formatAge(ms: number): string {\n  if (ms < 60_000) return `${Math.round(ms / 1000)}s`;\n  if (ms < 3_600_000) return `${Math.round(ms / 60_000)}m`;\n  return `${(ms / 3_600_000).toFixed(1)}h`;\n}\n\nlet cachedWsl: boolean | null = null;\n\n/** WSL detection (fs.watch is flaky on /mnt/c; also drives the browser ladder). */\nexport async function isWsl(): Promise<boolean> {\n  if (cachedWsl != null) return cachedWsl;\n  if (process.platform !== \"linux\") {\n    cachedWsl = false;\n    return false;\n  }\n  if (process.env[\"WSL_DISTRO_NAME\"] != null) {\n    cachedWsl = true;\n    return true;\n  }\n  try {\n    const release = await readFile(\"/proc/sys/kernel/osrelease\", \"utf8\");\n    cachedWsl = /microsoft/i.test(release);\n    return cachedWsl;\n  } catch {\n    cachedWsl = false;\n    return false;\n  }\n}\n\nfunction tryConnectTcp(host: string, port: number, timeoutMs = 600): Promise<boolean> {\n  return new Promise((resolve) => {\n    const socket = connect({ host, port });\n    const timer = setTimeout(() => {\n      socket.destroy();\n      resolve(false);\n    }, timeoutMs);\n    socket.once(\"connect\", () => {\n      clearTimeout(timer);\n      socket.destroy();\n      resolve(true);\n    });\n    socket.once(\"error\", () => {\n      clearTimeout(timer);\n      resolve(false);\n    });\n  });\n}\n\ninterface IDoctorReport {\n  ok: string[];\n  warnings: string[];\n  info: string[];\n  listeners: IPortListener[];\n}\n\nasync function diagnose(\n  ctx: ICommandContext,\n  handle: IDaemonHandle | null,\n): Promise<IDoctorReport> {\n  const { config } = ctx;\n  const report: IDoctorReport = { ok: [], warnings: [...config.warnings], info: [], listeners: [] };\n  const paths = commanderStatePaths(resolveCommanderDataDir(), config.configKey);\n\n  report.info.push(\n    handle != null\n      ? `daemon: running (pid ${handle.record.pid}, port ${handle.record.port}, generation ${handle.record.generation})`\n      : `daemon: not running`,\n  );\n  // \"Not running\" while a daemon from ANOTHER build plainly is running would send the operator\n  // to `up`, which fails on something else — name the skew and its one remedy instead.\n  if (handle == null) {\n    const skewed = await findSkewedDaemon(config);\n    if (skewed != null) report.warnings.push(skewed.message);\n  }\n\n  // Env-snapshot honesty (edge 62): children inherit the env the DAEMON booted with, so a\n  // proto/PATH change made in a fresh terminal does not reach them until the daemon restarts.\n  // Surfacing the snapshot's age is what turns that from a mystery into a one-line answer.\n  if (handle != null) {\n    const ping = await pingDaemon(handle.record).catch(() => null);\n    if (ping != null) {\n      report.info.push(\n        `daemon env snapshot: ${formatAge(ping.uptimeMs)} old — children inherit the environment ` +\n          \"the daemon booted with; restart it (`nice-commander shutdown` then `up`) to pick up a \" +\n          \"changed PATH, toolchain or global env\",\n      );\n    }\n  }\n\n  // Ledger: stale records (dead pid), quarantine-suspects (pid reuse), orphans (live, no daemon).\n  const ledger = openProcessLedger({ dir: paths.stateDir, namespace: paths.ledgerNamespace });\n  let records: Awaited<ReturnType<typeof ledger.list>> = [];\n  try {\n    records = await ledger.list();\n  } catch {\n    report.info.push(\"ledger: unreadable (treated as empty)\");\n  }\n  for (const record of records) {\n    const alive = (() => {\n      try {\n        process.kill(record.pid, 0);\n        return true;\n      } catch {\n        return false;\n      }\n    })();\n    if (!alive) {\n      report.warnings.push(\n        `ledger \"${record.id}\": stale record (pid ${record.pid} gone) — reaped on next daemon start`,\n      );\n      continue;\n    }\n    if (record.startStamp != null) {\n      if ((await matchProcessStartStamp(record.pid, record.startStamp)) !== \"match\") {\n        report.warnings.push(\n          `ledger \"${record.id}\": pid ${record.pid} fails the fingerprint check (reuse?) — quarantine-suspect`,\n        );\n        continue;\n      }\n    }\n    if (handle == null) {\n      report.warnings.push(\n        `ledger \"${record.id}\": orphan (pid ${record.pid} alive, no daemon) — reaped on next daemon start`,\n      );\n    }\n  }\n\n  // Quarantine history: trees a past reap deliberately did NOT kill. Until now this file was\n  // write-only, so the one decision an operator most needs explained — \"why is that still\n  // running?\" — was invisible. These are diagnostics, never a kill list.\n  const quarantined = await ledger.listQuarantined().catch(() => []);\n  if (quarantined.length > 0) {\n    const recent = quarantined.slice(-QUARANTINE_SHOWN);\n    report.info.push(\n      `ledger quarantine: ${quarantined.length} record(s) a reap refused to kill` +\n        (quarantined.length > recent.length ? ` (newest ${recent.length} shown)` : \"\"),\n    );\n    for (const entry of recent) {\n      report.warnings.push(\n        `quarantined \"${entry.record.id}\" (pid ${entry.record.pid}): ${entry.reason} — never ` +\n          \"killed on an ambiguous identity; verify it yourself before ending it\",\n      );\n    }\n  }\n\n  // Sticky env overrides outlive every process that used them, so a forgotten one is exactly the\n  // kind of thing `doctor` exists to name — \"why is that on a weird port\" has an answer here.\n  const overrides = await readEnvOverrides(paths.envOverridesPath);\n  const overrideCount = countOverrides(overrides);\n  if (overrideCount > 0) {\n    report.info.push(\n      `env overrides: ${overrideCount} set in ${paths.envOverridesPath} — they apply to every ` +\n        \"start (`nice-commander env` lists them, `--clear` drops them)\",\n    );\n  }\n  for (const entry of staleOverrides(config, overrides)) {\n    report.warnings.push(\n      `env override ${entry.id}.${entry.name} is stored but inert (${entry.reason}) — ` +\n        `clear it with \\`env ${entry.id} --clear\\``,\n    );\n  }\n  // The same check a start makes, against the same environment: the daemon's when one is up.\n  const judge = await judgeEnv(config, handle);\n  for (const proc of config.processes) {\n    const missing = missingRequired(proc, overrides, judge.baseEnv(proc));\n    if (missing.length > 0) {\n      report.warnings.push(\n        `\"${proc.id}\" ${requiredRefusal(proc.id, missing, judge.judgedIn)} — a start refuses until then`,\n      );\n    }\n    for (const off of overridesOffEndpoint(proc, overrides)) {\n      report.warnings.push(\n        `\"${proc.id}\" ${off.name}=${off.value} but its endpoint and readiness are still on ` +\n          `${off.port} — it will bind somewhere nothing points at`,\n      );\n    }\n  }\n\n  const capability = detectCapability();\n  report.info.push(`tree ownership: ${capability.treeMechanism}`);\n  for (const note of capability.notes) report.warnings.push(note);\n\n  report.info.push(`data dir: ${resolveCommanderDataDir()}`);\n  if (process.env[\"NICE_COMMANDER_DATA_DIR\"] != null) {\n    report.info.push(\"NICE_COMMANDER_DATA_DIR override is set\");\n  }\n  if (process.platform !== \"win32\") {\n    try {\n      const mode = statSync(resolveCommanderDataDir()).mode & 0o777;\n      if ((mode & 0o077) !== 0) {\n        report.warnings.push(`data dir permissions are loose (${mode.toString(8)}) — expected 700`);\n      }\n    } catch {\n      // not created yet — nothing to check\n    }\n  }\n\n  report.info.push(\n    `runtime: node ${process.version}${process.versions.bun != null ? ` · bun ${process.versions.bun}` : \"\"}`,\n  );\n  if ((await isWsl()) && config.configDir.startsWith(\"/mnt/\")) {\n    report.warnings.push(\n      \"config lives under /mnt — fs.watch is flaky on Windows drives from WSL (the 5 s stat-reconcile covers it)\",\n    );\n  }\n\n  // Exclusive endpoints: held by something that is NOT the owning active process?\n  const stateById = handle != null ? await fetchProcessStates(handle) : new Map<string, string>();\n  for (const proc of config.processes) {\n    for (const endpoint of proc.endpoints) {\n      if (endpoint.ownership !== \"exclusive\") continue;\n      const held = await tryConnectTcp(endpoint.host, endpoint.port);\n      if (!held) continue;\n      const ownerActive = ACTIVE_LIKE.has(stateById.get(proc.id) ?? \"\");\n      if (ownerActive) continue; // presumably the owned tree answering\n      report.warnings.push(\n        `endpoint ${endpoint.name} (${endpoint.host}:${endpoint.port}) on \"${proc.id}\" accepts connections` +\n          (handle == null\n            ? \" while no daemon runs — held by something else\"\n            : ` while \"${proc.id}\" is ${stateById.get(proc.id) ?? \"unknown\"} — held by something else`),\n      );\n    }\n  }\n  const occupied = await createPortInspector({\n    config: () => config,\n    states: async () => stateById,\n    protectedPids: async () => (handle ? [handle.record.pid] : []),\n  }).run({\n    ids: config.processes\n      .filter((p) => !ACTIVE_LIKE.has(stateById.get(p.id) ?? \"\"))\n      .map((p) => p.id),\n  });\n  report.listeners = occupied.listeners.map((l) => ({ ...l, token: null }));\n  report.warnings.push(...occupied.warnings);\n  for (const owner of occupied.listeners) {\n    const verdict = owner.stray\n      ? `STRAY — \"${owner.id}\"'s own command outside the daemon` +\n        (owner.strayRoot != null && owner.strayRoot !== owner.pid\n          ? ` (root PID ${owner.strayRoot})`\n          : \"\") +\n        \"; `doctor --reap-strays` stops it, `up --replace-same` replaces it\"\n      : `not \"${owner.id}\"'s command — never stopped automatically`;\n    report.info.push(\n      `port owner ${owner.id}.${owner.endpoint} (${owner.host}:${owner.port}): PID ${owner.pid}, ${owner.command}, identity ${owner.startStamp ?? \"unknown\"} — ${verdict} — ${owner.refusal ?? `inspect/stop with \\`nice-commander ports ${owner.id} --kill ${owner.pid}\\``}`,\n    );\n  }\n  return report;\n}\n\n/**\n * `--reap-strays`: stop every stray on a configured exclusive port. Strangers are printed with\n * the same table and left where they are — the stray verdict (argv + cwd, identity re-checked\n * before every signal) is the only thing that authorizes a kill here.\n */\nasync function reapStrays(ctx: ICommandContext, handle: IDaemonHandle | null): Promise<number> {\n  const { out, config } = ctx;\n  const stateById = handle != null ? await fetchProcessStates(handle) : new Map<string, string>();\n  const ids = config.processes\n    .filter((proc) => !ACTIVE_LIKE.has(stateById.get(proc.id) ?? \"\"))\n    .map((proc) => proc.id);\n  const inspector = createPortInspector({\n    config: () => config,\n    states: async () => stateById,\n    protectedPids: async () => (handle ? [handle.record.pid] : []),\n  });\n  const force = ctx.args.flags.has(\"--force\");\n  let current = await inspector.run({ ids });\n  const attempted = new Set<number>();\n  const warnings = [...current.warnings];\n  let stopped = 0;\n  for (;;) {\n    const target = current.listeners.find(\n      (l) => l.stray && l.token != null && !attempted.has(l.pid),\n    );\n    if (target?.token == null) break;\n    attempted.add(target.pid);\n    const go = await confirmKill(\n      ctx,\n      `${force ? \"Force kill\" : \"Stop\"} stray PID ${target.pid} (${target.command}) on ` +\n        `${target.host}:${target.port}, \"${target.id}\"'s own command${\n          target.strayRoot != null && target.strayRoot !== target.pid\n            ? ` (tree root PID ${target.strayRoot})`\n            : \"\"\n        }?`,\n      () => {\n        if (!out.json) out.print(renderListeners(ctx, current));\n      },\n    );\n    if (!go) continue;\n    current = await inspector.run({ ids, token: target.token, force });\n    warnings.push(...current.warnings);\n    if (!current.listeners.some((l) => l.pid === target.pid)) stopped += 1;\n  }\n  const strangers = current.listeners.filter((l) => !l.stray);\n  if (out.json) {\n    out.printJson({\n      stopped,\n      listeners: current.listeners.map((l) => ({ ...l, token: null })),\n      warnings: [...new Set(warnings)],\n    });\n  } else {\n    out.print(\n      `reap-strays: ${stopped} stray listener(s) stopped` +\n        (strangers.length > 0\n          ? `, ${strangers.length} left alone (not this config's commands — see STRAY)`\n          : \"\"),\n    );\n    if (current.listeners.length > 0) out.print(renderListeners(ctx, current));\n    for (const warning of new Set(warnings)) out.print(`${out.paint(\"yellow\", \"⚠\")} ${warning}`);\n  }\n  return warnings.length > 0 || current.listeners.some((l) => l.stray && l.token != null)\n    ? EXIT.failure\n    : EXIT.ok;\n}\n\nconst ACTIVE_LIKE = new Set([\"starting\", \"running\", \"ready\", \"unready\", \"backoff\"]);\n\nasync function fetchProcessStates(handle: IDaemonHandle): Promise<Map<string, string>> {\n  const client = await connectDaemon(handle);\n  try {\n    return new Map(Object.entries(client.state().processes).map(([id, proc]) => [id, proc.state]));\n  } finally {\n    client.dispose();\n  }\n}\n\nexport async function cmdDoctor(ctx: ICommandContext): Promise<number> {\n  const bad = unknownFlags(ctx.args.flags, [\"--reap\", \"--reap-strays\", \"--yes\", \"--force\"]);\n  if (bad != null) throw new CliExit(EXIT.usage, bad);\n  for (const flag of [\"--reap\", \"--reap-strays\", \"--yes\", \"--force\"]) {\n    if (ctx.args.flags.has(flag) && ctx.args.flags.get(flag) !== true)\n      throw new CliExit(EXIT.usage, `${flag} takes no value`);\n  }\n  if (\n    !ctx.args.flags.has(\"--reap-strays\") &&\n    (ctx.args.flags.has(\"--yes\") || ctx.args.flags.has(\"--force\"))\n  ) {\n    throw new CliExit(EXIT.usage, \"--yes/--force belong to --reap-strays\");\n  }\n  const handle = await findDaemon(ctx.config);\n  if (ctx.args.flags.has(\"--reap-strays\")) return reapStrays(ctx, handle);\n\n  // `--reap` — the one deliberate exception to doctor's read-only rule (REVIEW-AND-FIX F3c).\n  // Scavenging is otherwise successor-boot-triggered, so after a daemon crash the orphans run\n  // until somebody happens to `up` again with the same data dir; an operator who only DIAGNOSED\n  // the crash had no way to act on what doctor showed them. This calls the exact reap the next\n  // boot would run — same ledger, same safety rails (owner-lease skip, pid+startStamp identity,\n  // quarantine-not-kill on any ambiguity) — and refuses while a live daemon owns the ledger,\n  // because a live daemon's children are not orphans.\n  if (ctx.args.flags.has(\"--reap\")) {\n    const { out } = ctx;\n    if (handle != null) {\n      out.warn(\n        out.paint(\n          \"yellow\",\n          \"⚠ --reap refused: a live daemon owns this config's ledger — its children are not \" +\n            \"orphans. Stop it first (`nice-commander shutdown`) if you really mean this.\",\n        ),\n      );\n      return EXIT.failure;\n    }\n    const paths = commanderStatePaths(resolveCommanderDataDir(), ctx.config.configKey);\n    const ledger = openProcessLedger({ dir: paths.stateDir, namespace: paths.ledgerNamespace });\n    const result = await ledger.reapOrphans();\n    if (result.schemaUnknown) {\n      out.warn(\n        out.paint(\n          \"yellow\",\n          \"⚠ ledger schema is newer than this build understands — nothing touched\",\n        ),\n      );\n      return EXIT.failure;\n    }\n    out.print(\n      `reap: ${result.reaped.length} orphan record(s) reaped, ${result.quarantined.length} quarantined`,\n    );\n    for (const entry of result.reaped) {\n      out.print(\n        `  ${out.paint(\"green\", \"✓\")} reaped \"${entry.record.id}\" (pid ${entry.record.pid}, ${entry.how})`,\n      );\n    }\n    for (const entry of result.quarantined) {\n      out.print(\n        `  ${out.paint(\"yellow\", \"⚠\")} quarantined \"${entry.record.id}\" (pid ${entry.record.pid}): ` +\n          `${entry.reason} — ambiguous identity, never killed blind`,\n      );\n    }\n    return EXIT.ok;\n  }\n\n  const report = await diagnose(ctx, handle);\n  const { out } = ctx;\n  if (out.json) {\n    out.printJson(report);\n    return EXIT.ok;\n  }\n  for (const line of report.info) out.print(`${out.paint(\"cyan\", \"·\")} ${line}`);\n  for (const line of report.warnings) out.print(`${out.paint(\"yellow\", \"⚠\")} ${line}`);\n  if (report.warnings.length === 0) out.print(out.paint(\"green\", \"✓ no findings\"));\n  return EXIT.ok;\n}\n","// `env [selection]` — the declared knobs of the selected processes, their effective values, and\n// where each one came from; `--set`/`--unset`/`--clear` mutate the STICKY override store.\n//\n// Sticky is the whole design: a value set here applies to every later start, from any surface,\n// until it is cleared. So every printout says so, and a running process whose values have moved\n// says \"restart to apply\" rather than pretending the change already took.\n\nimport {\n  describeJudgedIn,\n  envVarViews,\n  type IEnvVarView,\n  overridesOffEndpoint,\n  staleOverrides,\n  type TEnvJudgedIn,\n  type TEnvOverrides,\n} from \"../../config/envVars\";\nimport type { IResolvedCommanderProcess } from \"../../config/types\";\nimport { commanderStatePaths, resolveCommanderDataDir } from \"../../daemon/dataDir\";\nimport { applyEnvMutation, countOverrides, readEnvOverrides } from \"../../daemon/envOverrides\";\nimport type { ISetEnvInput } from \"../../protocol/control\";\nimport { unknownFlags } from \"../args\";\nimport type { ICommandContext } from \"../context\";\nimport { selectOrExit } from \"../context\";\nimport { connectDaemon, findDaemon, type IDaemonClient } from \"../daemonClient\";\nimport { daemonEnvJudge, shellEnvJudge } from \"../envJudge\";\nimport { CliExit, EXIT } from \"../load\";\nimport type { IOut } from \"../out\";\n\n/** `NAME=VALUE` for `--set`. */\nfunction parseAssignments(values: readonly string[]): Record<string, string> | { error: string } {\n  const parsed: Record<string, string> = {};\n  for (const entry of values) {\n    const eq = entry.indexOf(\"=\");\n    if (eq <= 0) return { error: `--set expects NAME=VALUE, got ${JSON.stringify(entry)}` };\n    parsed[entry.slice(0, eq)] = entry.slice(eq + 1);\n  }\n  return parsed;\n}\n\nfunction parseNames(values: readonly string[]): string[] | { error: string } {\n  for (const entry of values) {\n    if (entry.includes(\"=\")) {\n      return { error: `--unset expects a NAME, got ${JSON.stringify(entry)}` };\n    }\n  }\n  return [...values];\n}\n\nfunction describeValue(view: IEnvVarView, judgedIn: TEnvJudgedIn): string {\n  if (view.secret) return view.source === \"unset\" ? \"-\" : \"••••••\";\n  return view.value ?? (view.source === \"inherited\" ? `(${describeJudgedIn(judgedIn)})` : \"-\");\n}\n\nfunction renderProcess(\n  out: IOut,\n  definition: IResolvedCommanderProcess,\n  views: readonly IEnvVarView[],\n  judgedIn: TEnvJudgedIn,\n): void {\n  out.print(out.paint(\"bold\", definition.id));\n  if (views.length === 0) {\n    out.print(out.paint(\"gray\", \"  declares no env vars — add `envVars` to the config to tune it\"));\n    return;\n  }\n  out.print(\n    out.table(\n      [\"  NAME\", \"VALUE\", \"SOURCE\", \"NOTES\"],\n      views.map((view) => [\n        `  ${view.name}`,\n        describeValue(view, judgedIn),\n        view.source,\n        [\n          view.description,\n          view.required && view.source === \"unset\" ? out.paint(\"red\", \"required, unset\") : null,\n          view.values != null ? `one of: ${view.values.join(\", \")}` : null,\n        ]\n          .filter((note) => note != null)\n          .join(\" · \"),\n      ]),\n    ),\n  );\n}\n\nexport async function cmdEnv(ctx: ICommandContext): Promise<number> {\n  const bad = unknownFlags(ctx.args.flags, [\"--set\", \"--unset\", \"--clear\", \"--all\"]);\n  if (bad != null) throw new CliExit(EXIT.usage, bad);\n  const sets = parseAssignments(ctx.args.repeated.get(\"--set\") ?? []);\n  if (\"error\" in sets) throw new CliExit(EXIT.usage, sets.error);\n  const unsets = parseNames(ctx.args.repeated.get(\"--unset\") ?? []);\n  if (\"error\" in unsets) throw new CliExit(EXIT.usage, unsets.error);\n  const clearing = ctx.args.flags.get(\"--clear\") === true;\n  const mutating = Object.keys(sets).length > 0 || unsets.length > 0 || clearing;\n\n  const { out, config } = ctx;\n  const paths = commanderStatePaths(resolveCommanderDataDir(), config.configKey);\n  // Writing names what it changes — like `down`, never an implicit `--all`. Reading with no\n  // selection answers \"what can I tune here?\": every process that declares something.\n  const targeted = mutating || ctx.args.positionals.length > 0 || ctx.args.flags.has(\"--all\");\n  const definitions = targeted\n    ? idsToDefinitions(ctx, selectOrExit(ctx, { bare: \"required\" }).direct)\n    : config.processes.filter((proc) => proc.envVars.length > 0);\n\n  // A live daemon owns the store, so a MUTATION goes through it or not at all. A read asks it\n  // one thing — which declared variables its own environment sets — and ⚠ must survive a daemon\n  // it cannot talk to (another build's): the shell answers then, and the output says so.\n  const handle = await findDaemon(config);\n  let client: IDaemonClient | null = null;\n  let unreachable: string | undefined;\n  if (handle != null) {\n    try {\n      client = await connectDaemon(handle);\n    } catch (error) {\n      if (mutating || !(error instanceof CliExit)) throw error;\n      unreachable = error.message;\n    }\n  }\n  try {\n    const result = mutating\n      ? await mutate(ctx, paths.envOverridesPath, client, {\n          processes: Object.fromEntries(\n            definitions.map((definition) => [\n              definition.id,\n              { ...sets, ...Object.fromEntries(unsets.map((name) => [name, null])) },\n            ]),\n          ),\n          ...(clearing ? { clear: definitions.map((definition) => definition.id) } : {}),\n        })\n      : { overrides: await readEnvOverrides(paths.envOverridesPath), warnings: [] };\n\n    // After the mutation: an override taken off changes what the daemon had to look up.\n    const judge =\n      client != null\n        ? daemonEnvJudge(client.state(), client.record.pid)\n        : shellEnvJudge(unreachable);\n    const views = new Map(\n      definitions.map((definition) => [\n        definition.id,\n        envVarViews(definition, result.overrides, judge.baseEnv(definition)),\n      ]),\n    );\n    const stale = staleOverrides(config, result.overrides);\n\n    if (out.json) {\n      out.printJson({\n        overridesPath: paths.envOverridesPath,\n        judgedAgainst: judge.judgedIn,\n        processes: definitions.map((definition) => ({\n          id: definition.id,\n          envVars: views.get(definition.id) ?? [],\n        })),\n        stale,\n        warnings: result.warnings,\n      });\n      return result.warnings.length > 0 ? EXIT.failure : EXIT.ok;\n    }\n\n    for (const definition of definitions) {\n      renderProcess(out, definition, views.get(definition.id) ?? [], judge.judgedIn);\n      out.print();\n    }\n    if ([...views.values()].some((listed) => listed.length > 0)) {\n      out.print(out.paint(\"gray\", judge.note));\n    }\n    const total = countOverrides(result.overrides);\n    if (total > 0) {\n      out.print(\n        out.paint(\n          \"gray\",\n          `${total} sticky override(s) — they apply to every start until ` +\n            \"`nice-commander env <sel> --clear`.\",\n        ),\n      );\n    }\n    // Nothing above touched a running process, deliberately (same rule as the config watcher).\n    // Say which ones are now up with something other than what a start would use.\n    if (client != null) {\n      const processes = client.state().processes;\n      for (const definition of definitions) {\n        if (processes[definition.id]?.envDrift !== true) continue;\n        out.print(\n          out.paint(\"yellow\", `${definition.id} is running with the previous values — restart it`),\n        );\n      }\n    }\n    for (const definition of definitions) {\n      for (const off of overridesOffEndpoint(definition, result.overrides)) {\n        out.warn(\n          out.paint(\n            \"yellow\",\n            `⚠ ${definition.id} ${off.name}=${off.value} but its endpoint and readiness are ` +\n              `still on ${off.port} — it will bind somewhere nothing points at`,\n          ),\n        );\n      }\n    }\n    for (const entry of stale) {\n      out.warn(\n        out.paint(\n          \"yellow\",\n          `⚠ stored override ${entry.id}.${entry.name} is inert (${entry.reason}) — ` +\n            `\\`env ${entry.id} --clear\\` removes it`,\n        ),\n      );\n    }\n    for (const warning of result.warnings) out.warn(out.paint(\"yellow\", `⚠ ${warning}`));\n    return result.warnings.length > 0 ? EXIT.failure : EXIT.ok;\n  } finally {\n    client?.dispose();\n  }\n}\n\nfunction idsToDefinitions(\n  ctx: ICommandContext,\n  ids: readonly string[],\n): IResolvedCommanderProcess[] {\n  return ctx.config.processes.filter((proc) => ids.includes(proc.id));\n}\n\n/**\n * The daemon owns the store while it is alive, so a live one does the write — two writers would\n * race, and its in-memory view would go stale the instant we wrote behind its back.\n */\nasync function mutate(\n  ctx: ICommandContext,\n  path: string,\n  client: IDaemonClient | null,\n  input: ISetEnvInput,\n): Promise<{ overrides: TEnvOverrides; warnings: string[] }> {\n  if (client == null) return applyEnvMutation(path, ctx.config, input);\n  const warnings = await client.setEnv(input);\n  return { overrides: await readEnvOverrides(path), warnings };\n}\n","// `list` / `explain <selection>` — pure config introspection: the expanded ids, excludes,\n// auto-included dependencies and DAG order, WITHOUT mutating anything (same rendering backs\n// `up --dry-run`). Only `explain --env` reads from a running daemon, and only which declared\n// variables its environment sets.\n\nimport { describeJudgedIn, envVarViews } from \"../../config/envVars\";\nimport { tagTermsOf } from \"../../config/tags\";\nimport { commanderStatePaths, resolveCommanderDataDir } from \"../../daemon/dataDir\";\nimport { readEnvOverrides } from \"../../daemon/envOverrides\";\nimport { unknownFlags } from \"../args\";\nimport type { ICommandContext } from \"../context\";\nimport { selectOrExit } from \"../context\";\nimport { judgeEnv } from \"../envJudge\";\nimport { CliExit, EXIT } from \"../load\";\n\nexport async function cmdList(ctx: ICommandContext): Promise<number> {\n  const bad = unknownFlags(ctx.args.flags, []);\n  if (bad != null) throw new CliExit(EXIT.usage, bad);\n  const { out, config } = ctx;\n  if (out.json) {\n    out.printJson({\n      name: config.name,\n      configRevisionHash: config.configRevisionHash,\n      defaultSelection: config.defaultSelection ?? null,\n      processes: config.processes.map((proc) => ({\n        id: proc.id,\n        kind: proc.kind,\n        cwd: proc.cwd,\n        tags: proc.tags,\n        dependsOn: proc.dependsOn,\n        endpoints: proc.endpoints,\n        url: proc.url ?? null,\n        // Declarations only — a value belongs to `env`, which reads the override store.\n        envVars: proc.envVars,\n        flags: proc.flags,\n        optIn: proc.optIn,\n      })),\n      suites: Object.fromEntries(\n        Object.entries(config.suites).map(([name, { name: _name, ...suite }]) => [name, suite]),\n      ),\n      warnings: config.warnings,\n    });\n    return EXIT.ok;\n  }\n  out.print(\n    out.table(\n      [\"ID\", \"KIND\", \"TAGS\", \"DEPS\", \"ENDPOINTS\"],\n      config.processes.map((proc) => [\n        proc.id,\n        proc.kind,\n        [...tagTermsOf(proc.tags), ...(proc.optIn ? [\"(opt-in)\"] : [])].join(\" \"),\n        proc.dependsOn.join(\" \"),\n        proc.endpoints.map((endpoint) => `${endpoint.name}:${endpoint.port}`).join(\" \"),\n      ]),\n    ),\n  );\n  const suiteRows = Object.values(config.suites).map((suite) => [\n    suite.name,\n    String(suite.ids.length),\n    `parallel ${suite.parallel}${suite.failFast ? \" · fail-fast\" : \"\"}`,\n    suite.ids.join(\" \"),\n  ]);\n  if (suiteRows.length > 0) {\n    out.print(\"\");\n    out.print(out.table([\"SUITE\", \"N\", \"POLICY\", \"IDS\"], suiteRows));\n  }\n  if (config.defaultSelection != null) {\n    out.print(out.paint(\"gray\", `\\ndefaultSelection: ${config.defaultSelection}`));\n  }\n  for (const warning of config.warnings) out.warn(`${out.paint(\"yellow\", \"⚠\")} ${warning}`);\n  return EXIT.ok;\n}\n\nexport async function cmdExplain(ctx: ICommandContext): Promise<number> {\n  const bad = unknownFlags(ctx.args.flags, [\"--all\", \"--any\", \"--env\"]);\n  if (bad != null) throw new CliExit(EXIT.usage, bad);\n  const selection = selectOrExit(ctx, { bare: \"default\" });\n  const { out } = ctx;\n  if (out.json) {\n    out.printJson(selection);\n    return EXIT.ok;\n  }\n  out.print(`direct:      ${selection.direct.join(\", \") || \"(none)\"}`);\n  out.print(\n    `auto-included: ${selection.autoIncluded.length > 0 ? selection.autoIncluded.join(\", \") : \"(none)\"}`,\n  );\n  const [onlyTerm] = ctx.args.positionals.length === 1 ? ctx.args.positionals : [];\n  const suite = onlyTerm == null ? undefined : ctx.config.suites[onlyTerm];\n  if (suite != null) {\n    out.print(\n      `suite policy:  parallel ${suite.parallel}, fail-fast ${suite.failFast ? \"on\" : \"off\"}, stagger ${suite.staggerMs}ms`,\n    );\n  }\n  out.print(`DAG order:`);\n  selection.ordered.forEach((id, index) => {\n    out.print(`  ${index + 1}. ${id}`);\n  });\n  const flagged = ctx.config.processes.filter(\n    (proc) => selection.direct.includes(proc.id) && proc.flags.length > 0,\n  );\n  if (flagged.length > 0) out.print(\"flags:\");\n  for (const proc of flagged) {\n    for (const flag of proc.flags) {\n      const about = flag.description != null ? ` — ${flag.description}` : \"\";\n      out.print(`  ${proc.id} --with ${flag.name}  appends ${flag.args.join(\" \")}${about}`);\n    }\n  }\n\n  // The spawn environment, made inspectable (REVIEW-AND-FIX F6). A consumer burned a day on\n  // \"the tool is eating my PATH\" precisely because nothing would SHOW what a task spawns with —\n  // the misdiagnosis went into their config as fact before being retracted. Secrets stay masked\n  // (envVarViews never carries a secret's value); a config-declared `env` pair is the user's own\n  // file echoed back. Behind `--env`: the DAG is what most `explain` calls are for, and the\n  // inheritance note repeated on every one of them was noise — one line keeps it findable.\n  if (!ctx.args.flags.has(\"--env\")) {\n    out.print(out.paint(\"gray\", \"env: `explain <sel> --env` shows each id's spawn environment\"));\n    return EXIT.ok;\n  }\n  const overrides = await readEnvOverrides(\n    commanderStatePaths(resolveCommanderDataDir(), ctx.config.configKey).envOverridesPath,\n  );\n  const judge = await judgeEnv(ctx.config);\n  out.print(\"env:\");\n  out.print(\n    \"  note: `run` children inherit THIS shell's environment; daemon-owned starts (`up`) inherit\",\n  );\n  out.print(\"  the daemon's boot-time snapshot — `doctor` shows that snapshot's age.\");\n  out.print(`  ${judge.note}`);\n  for (const id of selection.ordered) {\n    const def = ctx.config.processes.find((proc) => proc.id === id);\n    if (def == null) continue;\n    const parts: string[] = [];\n    for (const [key, value] of Object.entries(def.env)) {\n      parts.push(value == null ? `${key}=(unset)` : `${key}=${value} (config)`);\n    }\n    for (const view of envVarViews(def, overrides, judge.baseEnv(def))) {\n      const shown = view.secret\n        ? \"•••\"\n        : (view.value ??\n          (view.source === \"inherited\" ? `(from ${describeJudgedIn(judge.judgedIn)})` : \"(unset)\"));\n      parts.push(\n        `${view.name}=${shown} (${view.source}${view.source === \"override\" ? \", sticky\" : \"\"})`,\n      );\n    }\n    if (parts.length > 0) out.print(`  ${id}: ${parts.join(\"  \")}`);\n  }\n  return EXIT.ok;\n}\n","// The `/logs` lane protocol (D5): plain JSON frames on a dedicated ws, separate from the wire\n// socket. Subscribe per process id → bounded ring backfill + live tail, batched on a short\n// coalesce; a client that falls behind gets an explicit `gap` then a `reset` batch resnap —\n// it never silently loses lines and the daemon never grows an unbounded queue for it.\n\nimport type { INiceProcessLine } from \"@nice-code/process\";\n\nexport interface ILogsSubscribe {\n  k: \"sub\";\n  proc: string;\n  /**\n   * Resume cursor — the highest `seq` the client still holds. Absent = the whole ring. Honored\n   * only where the daemon's ring can prove continuity from it; otherwise the reply is a `gap`\n   * and/or a `reset` batch, never a silently spliced log.\n   */\n  fromSeq?: number;\n}\n\nexport interface ILogsUnsubscribe {\n  k: \"unsub\";\n  proc: string;\n}\n\n/**\n * The merged timeline (edge 52). Ordered by the DAEMON's `(g, s)` — its incarnation and the\n * sequence it stamps at receipt — never by wall clocks (which jump) and never by per-process\n * `seq` (which are incomparable between processes). `s` continues across daemon restarts from a\n * persisted high-water mark, so replaying yesterday's file next to today's live tail still sorts.\n */\nexport interface ILogsSubscribeMerged {\n  k: \"sub-merged\";\n  /** Restrict to these ids; absent = every process. */\n  procs?: string[];\n  /** Resume cursor: the highest `s` the client holds. */\n  fromS?: number;\n}\n\nexport interface ILogsUnsubscribeMerged {\n  k: \"unsub-merged\";\n}\n\n/**\n * A bounded, cancellable search over the daemon's on-disk history (ring included, since every\n * line reaches the aggregate). Bounded because a naive grep over rotated segments is an\n * unbounded read on the daemon's event loop; cancellable because the common case is a viewer\n * who retypes their query three times a second.\n */\nexport interface ILogsSearch {\n  k: \"search\";\n  /** Client-chosen id, echoed on every reply — late results from a stale query are discardable. */\n  id: string;\n  query: string;\n  procs?: string[];\n  /** Matches to return, newest first. Server-capped. */\n  limit?: number;\n}\n\nexport interface ILogsSearchCancel {\n  k: \"search-cancel\";\n  id: string;\n}\n\nexport type TLogsClientMessage =\n  | ILogsSubscribe\n  | ILogsUnsubscribe\n  | ILogsSubscribeMerged\n  | ILogsUnsubscribeMerged\n  | ILogsSearch\n  | ILogsSearchCancel;\n\nexport interface ILogsBatch {\n  k: \"batch\";\n  proc: string;\n  /** True = replace everything held for this proc (initial backfill and post-gap resnap). */\n  reset?: boolean;\n  lines: INiceProcessLine[];\n}\n\nexport interface ILogsGap {\n  k: \"gap\";\n  proc: string;\n  /** Lines dropped while the client was behind; a `reset` batch follows immediately. */\n  dropped: number;\n}\n\n/** One line as the DAEMON saw it: the library's line, plus the ordering key it stamped on receipt. */\nexport interface ILogsEntry {\n  /** Daemon incarnation. */\n  g: number;\n  /** Daemon-wide ingest sequence — the timeline's minor key. */\n  s: number;\n  id: string;\n  line: INiceProcessLine;\n}\n\nexport interface ILogsMergedBatch {\n  k: \"merged\";\n  /** True = replace everything held for the merged view. */\n  reset?: boolean;\n  entries: ILogsEntry[];\n}\n\nexport interface ILogsMergedGap {\n  k: \"merged-gap\";\n  dropped: number;\n}\n\nexport interface ILogsSearchResult {\n  k: \"search-result\";\n  id: string;\n  /** Newest first. */\n  entries: ILogsEntry[];\n  /** False = the scan budget ran out before the history did; the answer may be incomplete. */\n  complete: boolean;\n  scanned: number;\n}\n\nexport type TLogsServerMessage =\n  | ILogsBatch\n  | ILogsGap\n  | ILogsMergedBatch\n  | ILogsMergedGap\n  | ILogsSearchResult;\n\nfunction isLine(value: unknown): value is INiceProcessLine {\n  if (value == null || typeof value !== \"object\" || Array.isArray(value)) return false;\n  const line = value as Record<string, unknown>;\n  return typeof line[\"text\"] === \"string\" && typeof line[\"seq\"] === \"number\";\n}\n\nfunction isEntry(value: unknown): value is ILogsEntry {\n  if (value == null || typeof value !== \"object\" || Array.isArray(value)) return false;\n  const entry = value as Record<string, unknown>;\n  return (\n    typeof entry[\"g\"] === \"number\" &&\n    typeof entry[\"s\"] === \"number\" &&\n    typeof entry[\"id\"] === \"string\" &&\n    isLine(entry[\"line\"])\n  );\n}\n\n/** Ids the client may name in a selection. Bounded so one frame cannot fan out unboundedly. */\nconst MAX_SELECTED_PROCS = 128;\n\nfunction procList(value: unknown): string[] | null | undefined {\n  if (value == null) return undefined;\n  if (!Array.isArray(value) || value.length > MAX_SELECTED_PROCS) return null;\n  return value.every((entry) => typeof entry === \"string\" && entry !== \"\")\n    ? (value as string[])\n    : null;\n}\n\n/**\n * Shape check on frames arriving FROM the daemon. The daemon is trusted, but a bare\n * `JSON.parse(...) as TLogsServerMessage` inside a ws `message` handler is not: a truncated or\n * mismatched frame throws where nothing can catch it, taking the CLI down mid-tail — and the\n * cast means the compiler never asked for the check.\n */\nexport function parseLogsServerMessage(text: string): TLogsServerMessage | null {\n  let parsed: unknown;\n  try {\n    parsed = JSON.parse(text);\n  } catch {\n    return null;\n  }\n  if (parsed == null || typeof parsed !== \"object\" || Array.isArray(parsed)) return null;\n  const message = parsed as Record<string, unknown>;\n\n  if (message[\"k\"] === \"merged-gap\") {\n    const dropped = message[\"dropped\"];\n    return typeof dropped === \"number\" ? { k: \"merged-gap\", dropped } : null;\n  }\n  if (message[\"k\"] === \"merged\") {\n    const entries = message[\"entries\"];\n    if (!Array.isArray(entries) || !entries.every(isEntry)) return null;\n    return message[\"reset\"] === true\n      ? { k: \"merged\", reset: true, entries }\n      : { k: \"merged\", entries };\n  }\n  if (message[\"k\"] === \"search-result\") {\n    const entries = message[\"entries\"];\n    if (typeof message[\"id\"] !== \"string\") return null;\n    if (!Array.isArray(entries) || !entries.every(isEntry)) return null;\n    if (typeof message[\"complete\"] !== \"boolean\" || typeof message[\"scanned\"] !== \"number\") {\n      return null;\n    }\n    return {\n      k: \"search-result\",\n      id: message[\"id\"],\n      entries,\n      complete: message[\"complete\"],\n      scanned: message[\"scanned\"],\n    };\n  }\n\n  const proc = message[\"proc\"];\n  if (typeof proc !== \"string\") return null;\n  if (message[\"k\"] === \"gap\") {\n    const dropped = message[\"dropped\"];\n    return typeof dropped === \"number\" ? { k: \"gap\", proc, dropped } : null;\n  }\n  if (message[\"k\"] === \"batch\") {\n    const lines = message[\"lines\"];\n    if (!Array.isArray(lines) || !lines.every(isLine)) return null;\n    return message[\"reset\"] === true\n      ? { k: \"batch\", proc, reset: true, lines }\n      : { k: \"batch\", proc, lines };\n  }\n  return null;\n}\n\n/** Bounded shape check on inbound frames (control frames are tiny; anything larger is junk). */\nexport function parseLogsClientMessage(text: string): TLogsClientMessage | null {\n  if (text.length > 4096) return null;\n  let parsed: unknown;\n  try {\n    parsed = JSON.parse(text);\n  } catch {\n    return null;\n  }\n  if (parsed == null || typeof parsed !== \"object\" || Array.isArray(parsed)) return null;\n  const message = parsed as Record<string, unknown>;\n\n  if (message[\"k\"] === \"unsub-merged\") return { k: \"unsub-merged\" };\n  if (message[\"k\"] === \"sub-merged\") {\n    const procs = procList(message[\"procs\"]);\n    if (procs === null) return null;\n    const fromS = message[\"fromS\"];\n    if (fromS != null && (typeof fromS !== \"number\" || !Number.isFinite(fromS))) return null;\n    return {\n      k: \"sub-merged\",\n      ...(procs == null ? {} : { procs }),\n      ...(fromS == null ? {} : { fromS: Number(fromS) }),\n    };\n  }\n  if (message[\"k\"] === \"search-cancel\") {\n    return typeof message[\"id\"] === \"string\" && message[\"id\"] !== \"\"\n      ? { k: \"search-cancel\", id: message[\"id\"] }\n      : null;\n  }\n  if (message[\"k\"] === \"search\") {\n    const procs = procList(message[\"procs\"]);\n    if (procs === null) return null;\n    const { id, query, limit } = message;\n    if (typeof id !== \"string\" || id === \"\" || typeof query !== \"string\") return null;\n    if (limit != null && (typeof limit !== \"number\" || !Number.isFinite(limit))) return null;\n    return {\n      k: \"search\",\n      id,\n      query,\n      ...(procs == null ? {} : { procs }),\n      ...(limit == null ? {} : { limit: Number(limit) }),\n    };\n  }\n\n  if (typeof message[\"proc\"] !== \"string\" || message[\"proc\"] === \"\") return null;\n  if (message[\"k\"] === \"unsub\") return { k: \"unsub\", proc: message[\"proc\"] };\n  if (message[\"k\"] === \"sub\") {\n    const fromSeq = message[\"fromSeq\"];\n    if (fromSeq != null && (typeof fromSeq !== \"number\" || !Number.isFinite(fromSeq))) return null;\n    return fromSeq == null\n      ? { k: \"sub\", proc: message[\"proc\"] }\n      : { k: \"sub\", proc: message[\"proc\"], fromSeq };\n  }\n  return null;\n}\n","// `logs <selection> [-f]` — the merged interleaved tail with colored id prefixes: each\n// process's ring backfill merge-sorted by wall-clock, then live batches as they arrive. A\n// `gap` frame prints an explicit marker (never silent loss). Read-only: never autostarts.\n\nimport type { INiceProcessLine } from \"@nice-code/process\";\nimport { parseLogsServerMessage } from \"../../protocol/logs\";\nimport { unknownFlags } from \"../args\";\nimport type { ICommandContext } from \"../context\";\nimport { selectOrExit } from \"../context\";\nimport { openLogsLane, requireDaemon } from \"../daemonClient\";\nimport { CliExit, EXIT } from \"../load\";\nimport type { IOut } from \"../out\";\n\ninterface ISourcedLine {\n  proc: string;\n  line: INiceProcessLine;\n}\n\nfunction printLine(out: IOut, entry: ISourcedLine): void {\n  if (out.json) {\n    process.stdout.write(`${JSON.stringify({ proc: entry.proc, ...entry.line })}\\n`);\n    return;\n  }\n  process.stdout.write(`${out.accent(entry.proc, entry.proc.padEnd(2))} │ ${entry.line.text}\\n`);\n}\n\nexport async function cmdLogs(ctx: ICommandContext): Promise<number> {\n  const bad = unknownFlags(ctx.args.flags, [\"--any\", \"-f\", \"--follow\", \"--all\"]);\n  if (bad != null) throw new CliExit(EXIT.usage, bad);\n  const follow = ctx.args.flags.has(\"-f\") || ctx.args.flags.has(\"--follow\");\n  const selection = selectOrExit(ctx, { bare: \"required\" });\n  const handle = await requireDaemon(ctx.config);\n  const { out } = ctx;\n  const ids = selection.ordered;\n\n  const ws = await openLogsLane(handle.record);\n  try {\n    const backfill = new Map<string, INiceProcessLine[]>();\n    await new Promise<void>((resolve, reject) => {\n      const deadline = setTimeout(\n        () => reject(new CliExit(EXIT.timeout, \"logs backfill timed out\")),\n        15_000,\n      );\n      ws.on(\"open\", () => {\n        for (const id of ids) ws.send(JSON.stringify({ k: \"sub\", proc: id }));\n      });\n      ws.on(\"error\", () =>\n        reject(new CliExit(EXIT.failure, \"the /logs lane refused the connection\")),\n      );\n      ws.on(\"message\", (data) => {\n        const frame = parseLogsServerMessage(data.toString());\n        if (frame == null) return;\n        if (frame.k === \"batch\" && frame.reset === true && !backfill.has(frame.proc)) {\n          backfill.set(frame.proc, [...frame.lines]);\n          if (backfill.size === ids.length) {\n            clearTimeout(deadline);\n            resolve();\n          }\n        }\n      });\n    });\n\n    // Merge the rings by wall-clock (then per-proc seq) — the best interleave a backfill has.\n    const merged: ISourcedLine[] = [];\n    for (const [proc, lines] of backfill) {\n      for (const line of lines) merged.push({ proc, line });\n    }\n    merged.sort((a, b) => a.line.ts - b.line.ts || a.line.seq - b.line.seq);\n    for (const entry of merged) printLine(out, entry);\n    if (!follow) return EXIT.ok;\n\n    await new Promise<void>((resolve) => {\n      ws.on(\"message\", (data) => {\n        const frame = parseLogsServerMessage(data.toString());\n        if (frame == null) return;\n        if (frame.k === \"gap\") {\n          if (!out.json) {\n            out.print(\n              out.paint(\"yellow\", `… ${frame.proc}: ${frame.dropped} line(s) dropped — resnap …`),\n            );\n          }\n          return;\n        }\n        if (frame.k === \"batch\") {\n          for (const line of frame.lines) printLine(out, { proc: frame.proc, line });\n        }\n      });\n      ws.on(\"close\", () => resolve());\n      process.on(\"SIGINT\", () => resolve());\n    });\n    return EXIT.ok;\n  } finally {\n    ws.close();\n  }\n}\n","// The last-start store: `<stateDir>/last-starts.json`, one file per config. When each process was\n// last started, kept across daemon restarts so the UI's \"recent\" order still means \"what I was\n// working on\" after a reboot. The daemon writes it while it runs; a foreground `run` with no\n// daemon up writes it directly.\n\nimport { mkdir, readFile, rename, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\n\nconst STORE_VERSION = 1;\n/** Ids renamed out of the config linger here; the bound keeps them from accumulating forever. */\nexport const MAX_LAST_STARTS = 256;\n\n/** Process id → epoch ms of its last start. */\nexport type TLastStarts = Readonly<Record<string, number>>;\n\n/** Newest first, capped at `MAX_LAST_STARTS`. */\nfunction bounded(entries: Iterable<[string, number]>): TLastStarts {\n  return Object.fromEntries([...entries].sort(([, a], [, b]) => b - a).slice(0, MAX_LAST_STARTS));\n}\n\n/** Missing, unreadable or corrupt all read as \"nothing started yet\" — never a reason to fail a boot. */\nexport async function readLastStarts(path: string): Promise<TLastStarts> {\n  try {\n    const parsed: unknown = JSON.parse(await readFile(path, \"utf8\"));\n    if (parsed == null || typeof parsed !== \"object\" || !(\"processes\" in parsed)) return {};\n    const processes = parsed.processes;\n    if (processes == null || typeof processes !== \"object\" || Array.isArray(processes)) return {};\n    return bounded(\n      Object.entries(processes).filter(\n        (entry): entry is [string, number] =>\n          typeof entry[1] === \"number\" && Number.isFinite(entry[1]),\n      ),\n    );\n  } catch {\n    return {};\n  }\n}\n\nexport async function writeLastStarts(path: string, lastStarts: TLastStarts): Promise<void> {\n  await mkdir(dirname(path), { recursive: true, mode: 0o700 });\n  const temp = `${path}.${process.pid}.tmp`;\n  const store = { version: STORE_VERSION, processes: bounded(Object.entries(lastStarts)) };\n  await writeFile(temp, `${JSON.stringify(store, null, 2)}\\n`, { encoding: \"utf8\", mode: 0o600 });\n  await rename(temp, path);\n}\n","// The task-duration store: `<stateDir>/task-durations.json`, one file per config. How long each\n// task's last few successful runs took — the estimate a running task's progress bar fills toward,\n// kept across daemon restarts. The daemon writes it while it runs; a foreground `run` with no\n// daemon up writes it directly.\n\nimport { mkdir, readFile, rename, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\n\nconst STORE_VERSION = 1;\n/** How many of the latest successful runs an estimate averages. */\nexport const DURATION_SAMPLES = 3;\n/** Ids and flag sets renamed out of the config linger here; the bound keeps them from piling up. */\nexport const MAX_DURATION_KEYS = 256;\n\n/** Duration key → the latest successful run times in ms, oldest first. */\nexport type TTaskDurations = Readonly<Record<string, readonly number[]>>;\n\n/** Each flag set keeps its own samples — `dev-reset+hosted` runs as long as it runs, not as `dev-reset`. */\nexport function durationKey(id: string, flags: readonly string[]): string {\n  return [id, ...flags].join(\"+\");\n}\n\n/** `durations` with one more sample under `key`, which moves to the newest end of the bound. */\nexport function withDuration(durations: TTaskDurations, key: string, ms: number): TTaskDurations {\n  const samples = [...(durations[key] ?? []), ms].slice(-DURATION_SAMPLES);\n  const rest = Object.entries(durations).filter(([existing]) => existing !== key);\n  return Object.fromEntries([...rest, [key, samples]].slice(-MAX_DURATION_KEYS));\n}\n\n/** The mean of the samples, or null with nothing to go on. */\nexport function estimateMs(samples: readonly number[] | undefined): number | null {\n  if (samples == null || samples.length === 0) return null;\n  return Math.round(samples.reduce((total, ms) => total + ms, 0) / samples.length);\n}\n\n/** Missing, unreadable or corrupt all read as \"no history yet\" — never a reason to fail a boot. */\nexport async function readTaskDurations(path: string): Promise<TTaskDurations> {\n  try {\n    const parsed: unknown = JSON.parse(await readFile(path, \"utf8\"));\n    if (parsed == null || typeof parsed !== \"object\" || !(\"tasks\" in parsed)) return {};\n    const tasks = parsed.tasks;\n    if (tasks == null || typeof tasks !== \"object\" || Array.isArray(tasks)) return {};\n    const entries = Object.entries(tasks).flatMap(([key, samples]): [string, number[]][] => {\n      if (!Array.isArray(samples)) return [];\n      const valid = samples.filter(\n        (ms): ms is number => typeof ms === \"number\" && Number.isFinite(ms) && ms >= 0,\n      );\n      return valid.length > 0 ? [[key, valid.slice(-DURATION_SAMPLES)]] : [];\n    });\n    return Object.fromEntries(entries.slice(-MAX_DURATION_KEYS));\n  } catch {\n    return {};\n  }\n}\n\nexport async function writeTaskDurations(path: string, durations: TTaskDurations): Promise<void> {\n  await mkdir(dirname(path), { recursive: true, mode: 0o700 });\n  const temp = `${path}.${process.pid}.tmp`;\n  const store = { version: STORE_VERSION, tasks: durations };\n  await writeFile(temp, `${JSON.stringify(store, null, 2)}\\n`, { encoding: \"utf8\", mode: 0o600 });\n  await rename(temp, path);\n}\n","// The dependency-gated task pool behind a suite run — one implementation for the foreground\n// `run` and the daemon's `runSuite`, so the two can never schedule differently. Pure: the caller\n// supplies what \"run a task\" means.\n\nimport type { IDependencyNode } from \"../config/resolve\";\n\nexport interface ITaskPoolOptions<T extends IDependencyNode> {\n  /** DAG-ordered. */\n  tasks: readonly T[];\n  parallel: number;\n  failFast: boolean;\n  /** Resolves true when the task SUCCEEDED. Must not reject. */\n  run: (task: T) => Promise<boolean>;\n  /** A task skipped because an in-selection dependency failed. It counts as failed. */\n  onBlocked: (task: T, blockedBy: string) => void;\n  /** Fired once, by the first failure under `failFast` — the caller stops the survivors. */\n  onFailFast?: () => void;\n}\n\nexport interface ITaskPoolResult<T> {\n  succeeded: Set<string>;\n  failed: Set<string>;\n  /** Never became runnable (cut short by fail-fast, or waiting on something that never ran). */\n  leftover: T[];\n}\n\nexport async function runTaskPool<T extends IDependencyNode>(\n  options: ITaskPoolOptions<T>,\n): Promise<ITaskPoolResult<T>> {\n  const { failFast } = options;\n  // ⚠ DAG ORDER IS NOT ENOUGH once `parallel` > 1. Ordering only decides who is picked up first;\n  // with two workers, a task and the dependency it was ordered after start together. That is not\n  // theoretical — `devtools-cli-build` begins by DELETING `build/`, so the checks that `dependsOn`\n  // it were testing an artifact being removed underneath them. A worker therefore takes only a\n  // task whose in-selection dependencies have SUCCEEDED.\n  const pending = [...options.tasks];\n  const succeeded = new Set<string>();\n  const failed = new Set<string>();\n  const running = new Set<string>();\n  const selected = new Set(options.tasks.map((task) => task.id));\n  const depsOf = (task: T) => task.dependsOn.filter((id) => selected.has(id));\n  let cut = false;\n\n  // ⚠ Wake-ALL, never a single-slot resolver. This was `let wake = resolve` — each parked worker\n  // OVERWROTE the previous waiter's resolver, so with ≥2 workers parked at once the earlier one\n  // awaited a promise nobody held, `Promise.all(workers)` never settled, the event loop drained,\n  // and a FAILING RUN EXITED 0. Broadcast is safe: each woken worker re-derives its decision from\n  // pending/succeeded/failed/running at the top of its loop.\n  let waiters: Array<() => void> = [];\n  const settled = (): Promise<void> =>\n    new Promise<void>((resolve) => {\n      waiters.push(resolve);\n    });\n  const wake = (): void => {\n    const current = waiters;\n    waiters = [];\n    for (const resolve of current) resolve();\n  };\n\n  const workers = Array.from(\n    { length: Math.min(Math.max(1, options.parallel), pending.length) },\n    async () => {\n      for (;;) {\n        if (cut) return;\n        const index = pending.findIndex((task) =>\n          depsOf(task).every((id) => succeeded.has(id) || failed.has(id)),\n        );\n        if (index < 0) {\n          // Everything left is waiting on something still running; if nothing is running, the\n          // remaining tasks are unreachable and come back as `leftover`.\n          if (running.size === 0) return;\n          await settled();\n          continue;\n        }\n        const [task] = pending.splice(index, 1);\n        if (task == null) return;\n        const blockedBy = depsOf(task).find((id) => failed.has(id));\n        if (blockedBy != null) {\n          failed.add(task.id);\n          options.onBlocked(task, blockedBy);\n          wake();\n          continue;\n        }\n        running.add(task.id);\n        const ok = await options.run(task);\n        running.delete(task.id);\n        (ok ? succeeded : failed).add(task.id);\n        if (!ok && failFast && !cut) {\n          cut = true;\n          options.onFailFast?.();\n        }\n        wake();\n        if (cut) return;\n      }\n    },\n  );\n  await Promise.all(workers);\n  return { succeeded, failed, leftover: pending };\n}\n","// `run <selection>` — foreground mode, no daemon: tasks run to completion with exit-code\n// propagation (`--parallel N` / `--fail-fast` — the local-CI shape), services run under\n// prefixed interleaved output until Ctrl+C walks every stop ladder (a second Ctrl+C forces).\n// A single id gets raw inherited stdio so TTY-key tools (vitest watch, wrangler hotkeys)\n// work — the v1 answer to no-PTY. Coordinates on the same ledger (the next daemon boot reaps\n// a crashed CLI's trees) and refuses ids the daemon actively owns — never a silent double-start.\n\nimport {\n  createNiceProcess,\n  type INiceProcess,\n  openProcessLedger,\n  signalProcessGroup,\n  taskkillTree,\n} from \"@nice-code/process\";\nimport { effectiveEnv, missingRequired, requiredRefusal } from \"../../config/envVars\";\nimport { runWithArgs, SHELL_PLAIN_ARG } from \"../../config/flags\";\nimport type { IResolvedCommanderConfig, IResolvedCommanderProcess } from \"../../config/types\";\nimport {\n  commanderStatePaths,\n  type ICommanderStatePaths,\n  resolveCommanderDataDir,\n} from \"../../daemon/dataDir\";\nimport { readEnvOverrides } from \"../../daemon/envOverrides\";\nimport { readLastStarts, writeLastStarts } from \"../../daemon/lastStarts\";\nimport {\n  durationKey,\n  readTaskDurations,\n  withDuration,\n  writeTaskDurations,\n} from \"../../daemon/taskDurations\";\nimport type { IForegroundRun } from \"../../protocol/control\";\nimport { runTaskPool } from \"../../run/scheduler\";\nimport { numericFlag, unknownFlags } from \"../args\";\nimport { syncDaemonConfig } from \"../configSync\";\nimport type { ICommandContext } from \"../context\";\nimport { flagsOrExit, selectOrExit, singleProcessOrExit } from \"../context\";\nimport { connectDaemon, findDaemon } from \"../daemonClient\";\nimport { CliExit, EXIT } from \"../load\";\nimport type { IOut } from \"../out\";\n\nconst ACTIVE_STATES = new Set([\"starting\", \"running\", \"ready\", \"unready\", \"backoff\", \"stopping\"]);\nconst TERMINAL_STATES = new Set([\"stopped\", \"succeeded\", \"failed\", \"crashed\"]);\n/** How long a `--timeout` exit waits on the graceful ladders before forcing the trees. */\nconst TIMEOUT_STOP_GRACE_MS = 5_000;\n\ninterface IRunTaskResult {\n  id: string;\n  /** The task's exit code; 1 when killed/timed out before it could exit. */\n  code: number;\n  failed: boolean;\n}\n\nfunction forceKillTree(pid: number): void {\n  if (process.platform === \"win32\") void taskkillTree(pid);\n  else {\n    try {\n      signalProcessGroup(pid, \"SIGKILL\");\n    } catch {\n      // already gone\n    }\n  }\n}\n\ninterface IPump {\n  done: Promise<void>;\n  close: () => void;\n}\n\n/**\n * Stream one process's lines to stdout. The iterator is held explicitly so it can be CLOSED.\n *\n * WARNING: a `lines()` iterator only ends when its process reaches a terminal state — so one\n * belonging to a process that NEVER STARTS (the tail of a `--fail-fast` queue that was cut\n * short) waits forever. Awaiting it left `cmdRun` suspended before its `return`, and with\n * nothing left keeping the loop alive Node exited 0 with no error: a FAILING RUN REPORTED\n * SUCCESS. Closing is what makes every early-exit path terminate.\n */\nfunction startPump(out: IOut, proc: INiceProcess): IPump {\n  const iterator = proc.lines()[Symbol.asyncIterator]();\n  const done = (async () => {\n    for (;;) {\n      const next = await iterator.next();\n      if (next.done === true) return;\n      const line = next.value;\n      if (out.json) {\n        process.stdout.write(`${JSON.stringify({ proc: proc.id, ...line })}\\n`);\n      } else if (line.op === \"replace\" && out.color) {\n        process.stdout.write(`\\r\\u001b[K${out.accent(proc.id, proc.id)} │ ${line.text}`);\n      } else {\n        process.stdout.write(`${out.accent(proc.id, proc.id)} │ ${line.text}\\n`);\n      }\n    }\n  })();\n  return {\n    done,\n    close: () => {\n      void iterator.return?.();\n    },\n  };\n}\n\n/**\n * What this run ran reaches the \"recently started\" order and the task estimates — through the\n * daemon when one is up (it owns those stores while it runs), else straight into the stores.\n */\nasync function noteForegroundRuns(\n  config: IResolvedCommanderConfig,\n  paths: ICommanderStatePaths,\n  runs: readonly IForegroundRun[],\n): Promise<void> {\n  if (runs.length === 0) return;\n  try {\n    const handle = await findDaemon(config);\n    if (handle != null) {\n      const client = await connectDaemon(handle);\n      try {\n        await client.noteRuns({ runs: [...runs] });\n      } finally {\n        client.dispose();\n      }\n      return;\n    }\n    let lastStarts = await readLastStarts(paths.lastStartsPath);\n    let durations = await readTaskDurations(paths.taskDurationsPath);\n    for (const run of runs) {\n      if ((lastStarts[run.id] ?? 0) < run.startedAt) {\n        lastStarts = { ...lastStarts, [run.id]: run.startedAt };\n      }\n      if (run.durationMs != null) {\n        durations = withDuration(durations, durationKey(run.id, run.flags), run.durationMs);\n      }\n    }\n    await writeLastStarts(paths.lastStartsPath, lastStarts);\n    await writeTaskDurations(paths.taskDurationsPath, durations);\n  } catch {\n    // Bookkeeping only: a run's verdict and exit code never depend on it.\n  }\n}\n\n/** Let the last lines flush, then close every pump — the only way each one is guaranteed to end. */\nasync function drainPumps(pumps: readonly IPump[], graceMs = 250): Promise<void> {\n  if (pumps.length === 0) return;\n  await Promise.race([\n    Promise.allSettled(pumps.map((pump) => pump.done)),\n    new Promise((resolve) => setTimeout(resolve, graceMs)),\n  ]);\n  for (const pump of pumps) pump.close();\n  await Promise.allSettled(pumps.map((pump) => pump.done));\n}\n\nexport async function cmdRun(ctx: ICommandContext): Promise<number> {\n  const bad = unknownFlags(ctx.args.flags, [\n    \"--parallel\",\n    \"--fail-fast\",\n    \"--with\",\n    \"--all\",\n    \"--any\",\n  ]);\n  if (bad != null) throw new CliExit(EXIT.usage, bad);\n  const flags = flagsOrExit(ctx);\n  // Raw arguments are this caller's own, run under their own authority — unlike a daemon start,\n  // which only ever appends declared flags.\n  const passthrough = ctx.args.passthrough;\n  const target = passthrough.length > 0 ? singleProcessOrExit(ctx, \"--\") : null;\n  const unquotable =\n    typeof target?.run === \"string\"\n      ? passthrough.find((arg) => !SHELL_PLAIN_ARG.test(arg))\n      : undefined;\n  if (target != null && unquotable != null) {\n    throw new CliExit(\n      EXIT.usage,\n      `\"${target.id}\" runs through a shell, where ${JSON.stringify(unquotable)} would need ` +\n        \"quoting — pass plain arguments, or declare a flag for it\",\n    );\n  }\n  /** The one id `--with` / `--` select gets its flags' arguments, then the raw ones. */\n  const extraArgs = (id: string): string[] => [\n    ...(flags?.id === id ? flags.args : []),\n    ...(target?.id === id ? passthrough : []),\n  ];\n  const parallel = numericFlag(ctx.args.flags, \"--parallel\");\n  if (parallel != null && typeof parallel === \"object\") {\n    throw new CliExit(EXIT.usage, parallel.error);\n  }\n  const selection = selectOrExit(ctx, { bare: \"required\" });\n  const { out, config } = ctx;\n  // A suite carries its own policy, so `run verify` needs no flags to mean what the UI's ▶ means.\n  const [onlyTerm] = ctx.args.positionals.length === 1 ? ctx.args.positionals : [];\n  const suitePolicy = onlyTerm == null ? undefined : config.suites[onlyTerm];\n  const failFast = ctx.args.flags.has(\"--fail-fast\") || suitePolicy?.failFast === true;\n  const byId = new Map(config.processes.map((proc) => [proc.id, proc]));\n  // `selection.ordered` only ever names ids resolved from this same config, so a miss is a bug\n  // in resolution rather than user input — filter rather than assert it away with a cast.\n  const defs = selection.ordered.flatMap((id) => {\n    const def = byId.get(id);\n    return def == null ? [] : [def];\n  });\n\n  // `--parallel` only means anything for the task queue: services all come up together and stay\n  // up. Silently ignoring it on a service selection reads as \"my flag did something\".\n  if (parallel != null && !defs.some((def) => def.kind === \"task\")) {\n    out.warn(\n      out.paint(\"yellow\", \"note: --parallel applies to tasks; this selection has none — ignored.\"),\n    );\n  }\n\n  const paths = commanderStatePaths(resolveCommanderDataDir(), config.configKey);\n  // The same sticky overrides `up` would apply. A foreground run that disagreed with the daemon\n  // about a port would be worse than having no overrides at all.\n  const overrides = await readEnvOverrides(paths.envOverridesPath);\n  // A foreground child inherits THIS shell, so that is where a `required` variable may come from.\n  const unmet = defs.flatMap((def) => {\n    const missing = missingRequired(def, overrides, process.env);\n    return missing.length === 0 ? [] : [`\"${def.id}\" ${requiredRefusal(def.id, missing, \"shell\")}`];\n  });\n  if (unmet.length > 0) {\n    throw new CliExit(EXIT.failure, `nothing was started — ${unmet.join(\"\\n\")}`);\n  }\n  const ledger = openProcessLedger({\n    dir: paths.stateDir,\n    namespace: paths.ledgerNamespace,\n    ownerKind: \"run\", // our lease: the next daemon boot reaps around this session, never through it\n  });\n\n  // Daemon-collision refusal: a selected id the daemon actively owns is never double-started.\n  // A reachable daemon answers first because it can name itself; the ledger sweep below is the\n  // socket-free backstop that still holds when it cannot be reached.\n  const handle = await findDaemon(config);\n  if (handle != null) {\n    const client = await connectDaemon(handle);\n    try {\n      // This run spawns from the config on disk; the daemon's rows should describe the same one.\n      await syncDaemonConfig(config, client, out);\n      const owned = defs.filter((def) =>\n        ACTIVE_STATES.has(client.state().processes[def.id]?.state ?? \"\"),\n      );\n      if (owned.length > 0) {\n        throw new CliExit(\n          EXIT.failure,\n          `\"${owned.map((def) => def.id).join('\", \"')}\" is owned by the running daemon — ` +\n            `\\`down\\` it there first (silent double-start is never allowed).`,\n        );\n      }\n    } finally {\n      client.dispose();\n    }\n    out.warn(\n      out.paint(\n        \"yellow\",\n        \"note: a daemon is running; processes started here do not show in its status.\",\n      ),\n    );\n  }\n\n  // Ledger-backed collision refusal (C1) — symmetric and socket-free, so it holds when the\n  // daemon is unreachable and against another foreground `run`. The realm check above covers the\n  // one gap this cannot see: the window between a daemon spawning a child and its record landing.\n  let leases: ReadonlyMap<string, string>;\n  try {\n    leases = new Map(\n      (await ledger.liveLeases()).map((record) => [record.id, record.owner?.kind ?? \"another\"]),\n    );\n  } catch {\n    leases = new Map(); // an unreadable ledger must not block foreground work\n  }\n  const leased = defs.filter((def) => leases.has(def.id));\n  if (leased.length > 0) {\n    throw new CliExit(\n      EXIT.failure,\n      `\"${leased.map((def) => def.id).join('\", \"')}\" is held by a live ` +\n        `\\`${leases.get(leased[0]?.id ?? \"\") ?? \"supervisor\"}\\` process — stop it there first ` +\n        \"(silent double-start is never allowed).\",\n    );\n  }\n\n  const single = defs.length === 1;\n  const procs = defs.map((def) => {\n    let ready = def.ready;\n    if (single && ready?.kind === \"logMatch\") {\n      out.warn(\n        out.paint(\n          \"yellow\",\n          `note: \"${def.id}\" uses logMatch readiness, unreadable in raw-stdio mode — treated as ready-on-spawn.`,\n        ),\n      );\n      ready = undefined;\n    }\n    return createNiceProcess({\n      id: def.id,\n      run: runWithArgs(def.run, extraArgs(def.id)),\n      ...(def.shell != null ? { shell: def.shell } : {}),\n      cwd: def.cwd,\n      env: effectiveEnv(def, overrides),\n      kind: def.kind,\n      ...(ready != null ? { ready } : {}),\n      stop: def.stop,\n      log: def.log,\n      ledger,\n      stdio: single ? \"inherit\" : \"pipe\",\n      ...(single ? {} : { stdin: def.stdin }),\n    });\n  });\n\n  // `procs` is built from `defs` one-for-one, so this lookup cannot miss — saying that with a\n  // Map and a throw beats asserting it at three call sites with a cast the compiler can't check.\n  const procById = new Map(procs.map((proc) => [proc.id, proc]));\n  const procFor = (id: string): INiceProcess => {\n    const proc = procById.get(id);\n    if (proc == null) throw new CliExit(EXIT.failure, `internal: no process built for \"${id}\"`);\n    return proc;\n  };\n\n  // The two-Ctrl+C ladder: first walks every stop ladder gracefully, second forces the trees.\n  let sigintResolve: (() => void) | null = null;\n  const sigintSeen = new Promise<void>((resolve) => {\n    sigintResolve = resolve;\n  });\n  let sigints = 0;\n  let stopping: Promise<unknown> | null = null;\n  const onSigint = () => {\n    sigints += 1;\n    if (sigints === 1) {\n      out.warn(out.paint(\"yellow\", \"stopping gracefully — Ctrl+C again to force immediately\"));\n      stopping = Promise.allSettled(procs.map((proc) => proc.stop()));\n      sigintResolve?.();\n      return;\n    }\n    for (const proc of procs) {\n      if (proc.pid != null) forceKillTree(proc.pid);\n    }\n    process.exit(EXIT.failure);\n  };\n  process.on(\"SIGINT\", onSigint);\n\n  // A wall-clock `--timeout` exits hard, so it must take the trees with it — the same two-rung\n  // contract as Ctrl+C, on a clock instead of a keypress. `pid` is undefined once a process has\n  // exited, so the force rung can never land on a reused pid.\n  ctx.onTimeout = async () => {\n    const graceful = Promise.allSettled(procs.map((proc) => proc.stop()));\n    const stopped = await Promise.race([\n      graceful.then(() => true),\n      new Promise<boolean>((settle) => setTimeout(() => settle(false), TIMEOUT_STOP_GRACE_MS)),\n    ]);\n    if (stopped) return;\n    for (const proc of procs) {\n      if (proc.pid != null) forceKillTree(proc.pid);\n    }\n  };\n\n  // A run with raw arguments is not a sample of any flag set's duration — it is its own thing.\n  const ran: IForegroundRun[] = [];\n  const noteStart = (def: IResolvedCommanderProcess): IForegroundRun => {\n    const run = {\n      id: def.id,\n      startedAt: Date.now(),\n      flags: flags?.id === def.id ? flags.flags : [],\n    };\n    ran.push(run);\n    return run;\n  };\n\n  const runTask = async (def: IResolvedCommanderProcess): Promise<IRunTaskResult> => {\n    const proc = procFor(def.id);\n    if (!single) out.print(`${out.paint(\"cyan\", \"▸\")} ${out.accent(def.id, def.id)} running…`);\n    const exitPromise = new Promise<void>((resolve) => {\n      const off = proc.on(\"exit\", () => {\n        off();\n        resolve();\n      });\n    });\n    let timer: ReturnType<typeof setTimeout> | null = null;\n    let timedOut = false;\n    let run: IForegroundRun;\n    try {\n      await proc.start();\n      run = noteStart(def);\n      if (def.timeoutMs != null) {\n        timer = setTimeout(() => {\n          timedOut = true;\n          void proc.stop();\n        }, def.timeoutMs);\n        timer.unref();\n      }\n      // An already-terminal process emits no new exit (instant tasks).\n      if (!TERMINAL_STATES.has(proc.state)) await exitPromise;\n    } catch (error) {\n      if (timer != null) clearTimeout(timer);\n      out.print(\n        `${out.paint(\"red\", \"✗\")} ${out.accent(def.id, def.id)} ${(error as Error).message}`,\n      );\n      return { id: def.id, code: 1, failed: true };\n    }\n    if (timer != null) clearTimeout(timer);\n    if (timedOut) {\n      out.print(\n        `${out.paint(\"red\", \"✗\")} ${out.accent(def.id, def.id)} timeout after ${def.timeoutMs} ms`,\n      );\n      return { id: def.id, code: 1, failed: true };\n    }\n    const code = proc.lastExit?.code ?? (proc.state === \"succeeded\" ? 0 : 1);\n    const failed = code !== 0;\n    if (!failed && passthrough.length === 0) {\n      run.durationMs = Date.now() - run.startedAt;\n    }\n    out.print(\n      failed\n        ? `${out.paint(\"red\", \"✗\")} ${out.accent(def.id, def.id)} exit ${code}`\n        : `${out.paint(\"green\", \"✓\")} ${out.accent(def.id, def.id)} ok`,\n    );\n    return { id: def.id, code, failed };\n  };\n\n  const tasks = defs.filter((def) => def.kind === \"task\");\n  const services = defs.filter((def) => def.kind === \"service\");\n  const failures: IRunTaskResult[] = [];\n  /**\n   * Record a failure AND set `process.exitCode` eagerly — belt-and-braces for the drain class.\n   *\n   * This command has twice reached \"a FAILING RUN REPORTED SUCCESS\" via the same shape: something\n   * left the run's promise suspended, the event loop drained, and Node exited with the default 0\n   * (see the startPump warning above, and the lost-wakeup pool defect this file carried until\n   * 2026-07). The proper exit code is still returned at the end and overwrites this; the eager\n   * assignment just guarantees that NO future scheduling hang can ever turn a printed ✗ into a\n   * green exit again.\n   */\n  const recordFailure = (result: IRunTaskResult): void => {\n    failures.push(result);\n    process.exitCode = result.code === 0 ? EXIT.failure : result.code;\n  };\n  /** `run: N ok, M failed (ids…)` — the human-readable verdict beside the exit code. */\n  const printSummary = (ok: number, skipped: number): void => {\n    if (tasks.length === 0) return;\n    const parts = [`${ok} ok`];\n    if (failures.length > 0) {\n      parts.push(`${failures.length} failed (${failures.map((entry) => entry.id).join(\", \")})`);\n    }\n    if (skipped > 0) parts.push(`${skipped} not run`);\n    const line = `run: ${parts.join(\", \")}`;\n    out.print(failures.length > 0 ? out.paint(\"red\", line) : out.paint(\"green\", line));\n  };\n\n  try {\n    const pumps = single ? [] : procs.map((proc) => startPump(out, proc));\n\n    if (tasks.length > 0 && services.length === 0) {\n      // The local-CI shape: a dependency-gated pool over the task list.\n      const pool = await runTaskPool({\n        tasks,\n        parallel: parallel ?? suitePolicy?.parallel ?? 1,\n        failFast,\n        run: async (def) => {\n          const result = await runTask(def);\n          if (result.failed) recordFailure(result);\n          return !result.failed;\n        },\n        onBlocked: (def, blockedBy) => {\n          out.print(\n            `${out.paint(\"yellow\", \"⊘\")} ${out.accent(def.id, def.id)} blocked: \"${blockedBy}\" failed`,\n          );\n          recordFailure({ id: def.id, code: 1, failed: true });\n        },\n        onFailFast: () => {\n          for (const proc of procs) {\n            if (!TERMINAL_STATES.has(proc.state)) void proc.stop();\n          }\n        },\n      });\n      const { succeeded } = pool;\n      // A task left over never became runnable — say so rather than exiting green with it\n      // silently skipped.\n      for (const def of pool.leftover) {\n        const blockedBy =\n          def.dependsOn.find((id) => tasks.some((t) => t.id === id) && !succeeded.has(id)) ??\n          \"a dependency\";\n        out.print(\n          `${out.paint(\"yellow\", \"⊘\")} ${out.accent(def.id, def.id)} blocked: \"${blockedBy}\" did not succeed`,\n        );\n        recordFailure({ id: def.id, code: 1, failed: true });\n      }\n      await drainPumps(pumps); // flush the last lines, then guarantee every pump ends\n      printSummary(succeeded.size, tasks.length - succeeded.size - failures.length);\n      return failures.length > 0 ? (failures[0]?.code ?? 1) : EXIT.ok;\n    }\n\n    // Mixed / service shape: tasks complete inline (DAG order), services stay up until Ctrl+C.\n    let mixedOk = 0;\n    for (const def of defs) {\n      if (failFast && failures.length > 0) break;\n      if (def.kind === \"task\") {\n        const result = await runTask(def);\n        if (result.failed) recordFailure(result);\n        else mixedOk += 1;\n        continue;\n      }\n      for (const depId of def.dependsOn) {\n        const dep = procs.find((candidate) => candidate.id === depId);\n        if (dep != null && byId.get(depId)?.kind === \"service\" && ACTIVE_STATES.has(dep.state)) {\n          await dep.whenReady().catch(() => {\n            out.warn(\n              out.paint(\"yellow\", `⚠ dependency \"${depId}\" did not become ready — starting anyway`),\n            );\n          });\n        }\n      }\n      const proc = procFor(def.id);\n      await proc.start();\n      noteStart(def);\n      if (!single)\n        out.print(\n          `${out.paint(\"cyan\", \"▸\")} ${out.accent(def.id, def.id)} started (pid ${proc.pid ?? \"?\"})`,\n        );\n    }\n\n    if (services.length > 0 && !(failFast && failures.length > 0)) {\n      const allDone = new Promise<void>((resolve) => {\n        const check = () => {\n          const done = services.every((def) => {\n            return TERMINAL_STATES.has(procFor(def.id).state);\n          });\n          if (done) resolve();\n        };\n        for (const proc of procs) proc.on(\"state\", check);\n        check();\n      });\n      await Promise.race([sigintSeen, allDone]);\n      stopping ??= Promise.allSettled(procs.map((proc) => proc.stop()));\n      await stopping;\n    }\n    await drainPumps(pumps);\n    printSummary(mixedOk, tasks.length - mixedOk - failures.length);\n    return failures.length > 0 ? (failures[0]?.code ?? 1) : EXIT.ok;\n  } finally {\n    process.removeListener(\"SIGINT\", onSigint);\n    // Nothing outlives the CLI: any survivor of the flow above is stopped now (and the ledger\n    // lets the next daemon boot reap a force-killed remainder).\n    await Promise.allSettled(\n      procs.filter((proc) => !TERMINAL_STATES.has(proc.state)).map((proc) => proc.stop()),\n    );\n    await noteForegroundRuns(config, paths, ran);\n  }\n}\n","// Terminal output: color honoring --no-color / NO_COLOR / non-TTY, --json printing, and a\n// minimal padded table. No dependencies — the CLI stays cold-start fast.\n\nexport type TPaint = \"green\" | \"red\" | \"yellow\" | \"cyan\" | \"magenta\" | \"gray\" | \"bold\";\n\nconst CODES: Record<TPaint, [number, number]> = {\n  green: [32, 39],\n  red: [31, 39],\n  yellow: [33, 39],\n  cyan: [36, 39],\n  magenta: [35, 39],\n  gray: [90, 39],\n  bold: [1, 22],\n};\n\nexport interface IOut {\n  readonly json: boolean;\n  readonly color: boolean;\n  print(line?: string): void;\n  warn(line: string): void;\n  printJson(value: unknown): void;\n  paint(kind: TPaint, text: string): string;\n  /** A stable per-id accent color for log prefixes (palette rotates by hash). */\n  accent(seed: string, text: string): string;\n  table(headers: readonly string[], rows: readonly (readonly string[])[]): string;\n}\n\nexport function createOut(options: { json: boolean; noColor: boolean }): IOut {\n  const color =\n    !options.noColor && process.env[\"NO_COLOR\"] == null && process.stdout.isTTY === true;\n  const paint = (kind: TPaint, text: string): string => {\n    if (!color) return text;\n    const [open, close] = CODES[kind];\n    return `\\u001b[${open}m${text}\\u001b[${close}m`;\n  };\n  const palette: TPaint[] = [\"cyan\", \"green\", \"yellow\", \"magenta\"];\n  return {\n    json: options.json,\n    color,\n    print: (line = \"\") => process.stdout.write(`${line}\\n`),\n    warn: (line) => process.stderr.write(`${line}\\n`),\n    printJson: (value) => process.stdout.write(`${JSON.stringify(value, null, 2)}\\n`),\n    paint,\n    accent: (seed, text) => {\n      let hash = 0;\n      for (const char of seed) hash = (hash * 31 + char.charCodeAt(0)) | 0;\n      return paint(palette[Math.abs(hash) % palette.length] as TPaint, text);\n    },\n    table: (headers, rows) => {\n      const widths = headers.map((header, index) =>\n        Math.max(header.length, ...rows.map((row) => (row[index] ?? \"\").length)),\n      );\n      const render = (cells: readonly string[]) =>\n        cells\n          .map((cell, index) => (cell ?? \"\").padEnd(widths[index] ?? 0))\n          .join(\"  \")\n          .trimEnd();\n      return [render(headers), ...rows.map(render)].join(\"\\n\");\n    },\n  };\n}\n\n/** Wall-clock uptime, compact: 8s, 3m04s, 2h11m. */\nexport function formatUptime(sinceMs: number, now = Date.now()): string {\n  const seconds = Math.max(0, Math.floor((now - sinceMs) / 1000));\n  if (seconds < 60) return `${seconds}s`;\n  const minutes = Math.floor(seconds / 60);\n  if (minutes < 60) return `${minutes}m${String(seconds % 60).padStart(2, \"0\")}s`;\n  return `${Math.floor(minutes / 60)}h${String(minutes % 60).padStart(2, \"0\")}m`;\n}\n","// `status [--watch]` — one-shot table from the status realm, or a live-updating table that\n// re-renders on patches. Read-only: never starts a missing daemon.\n\nimport type { IStatusProcessNode, TCommanderStatusState } from \"../../protocol/statusRealm\";\nimport { unknownFlags } from \"../args\";\nimport type { ICommandContext } from \"../context\";\nimport { connectDaemon, requireDaemon } from \"../daemonClient\";\nimport { CliExit, EXIT } from \"../load\";\nimport { formatUptime, type IOut } from \"../out\";\n\nconst ACTIVE_STATES = new Set([\"starting\", \"running\", \"ready\", \"unready\", \"backoff\", \"stopping\"]);\n\n/** Beyond this, a run that has printed nothing reads as wedged, not quiet — say so. */\nconst SILENT_START_NOTE_MS = 15_000;\n\nfunction notesFor(proc: IStatusProcessNode, now: number): string {\n  const notes: string[] = [];\n  if (proc.blockedBy != null) notes.push(`blocked: ${proc.blockedBy}`);\n  if (proc.startError != null) notes.push(`start failed: ${proc.startError}`);\n  if (proc.degradedBy.length > 0) notes.push(`degraded by ${proc.degradedBy.join(\", \")}`);\n  if (proc.unreadyReason != null) notes.push(`unready: ${proc.unreadyReason}`);\n  // The eye-mobile-app incident's two invisible facts, made table-visible: a run hung before its\n  // first print, and how the last completed task run actually ended once the reply is gone.\n  if (\n    ACTIVE_STATES.has(proc.state) &&\n    proc.sawOutputAt == null &&\n    proc.startedAt != null &&\n    now - proc.startedAt > SILENT_START_NOTE_MS\n  ) {\n    notes.push(`no output since start (${formatUptime(proc.startedAt, now)})`);\n  }\n  const lastTask = proc.lastTask;\n  if (!ACTIVE_STATES.has(proc.state) && lastTask?.outcome === \"failed\" && lastTask.reason != null) {\n    notes.push(`last run failed: ${lastTask.reason} (${formatUptime(lastTask.endedAt, now)} ago)`);\n  }\n  if (proc.stale) notes.push(\"stale (config changed — restart to apply)\");\n  // Mirrors the web card's chip: sticky overrides outlive every run and are the easiest thing on\n  // this surface to forget — `status` must say so, not just `env`.\n  const sticky = proc.detail.envVars.filter((declared) => declared.source === \"override\").length;\n  if (sticky > 0)\n    notes.push(`${sticky} sticky env override${sticky === 1 ? \"\" : \"s\"} (see \\`env\\`)`);\n  if (proc.envDrift) notes.push(\"env override changed — restart to apply\");\n  if (proc.removed) notes.push(\"removed from config\");\n  return notes.join(\"; \");\n}\n\n/**\n * Degraded tree ownership is a host-wide fact (every process shares one mechanism), so it prints\n * once under the table instead of drowning every row's NOTES — on WSL that would be every row.\n */\nfunction capabilityFooter(state: TCommanderStatusState): string {\n  const seen = new Set<string>();\n  for (const proc of Object.values(state.processes)) {\n    if (proc.capability?.degraded !== true) continue;\n    const notes = proc.capability.notes.length > 0 ? `: ${proc.capability.notes.join(\" \")}` : \"\";\n    seen.add(`⚠ tree ownership degraded (${proc.capability.treeMechanism})${notes}`);\n  }\n  return [...seen].map((line) => `\\n${line}`).join(\"\");\n}\n\nfunction renderTable(out: IOut, state: TCommanderStatusState): string {\n  const now = Date.now();\n  const rows = Object.entries(state.processes).map(([id, proc]) => [\n    id,\n    proc.kind,\n    proc.state,\n    proc.pid != null ? String(proc.pid) : \"-\",\n    // A terminal process has no uptime — the old render kept counting from `startedAt`, so a\n    // stopped task read as \"up 3m50s\".\n    ACTIVE_STATES.has(proc.state) && proc.startedAt != null\n      ? formatUptime(proc.startedAt, now)\n      : \"-\",\n    String(proc.restarts),\n    notesFor(proc, now),\n  ]);\n  const head = `${state.configName} · generation ${state.generation} · revision ${state.configRevisionHash}`;\n  const configError =\n    state.configError.length > 0 ? `\\nconfig error (last-good kept): ${state.configError[0]}` : \"\";\n  return `${out.paint(\"gray\", head)}\\n${out.table([\"ID\", \"KIND\", \"STATE\", \"PID\", \"UPTIME\", \"R\", \"NOTES\"], rows)}${capabilityFooter(state)}${configError}`;\n}\n\nexport async function cmdStatus(ctx: ICommandContext): Promise<number> {\n  const bad = unknownFlags(ctx.args.flags, [\"--watch\"]);\n  if (bad != null) throw new CliExit(EXIT.usage, bad);\n  const handle = await requireDaemon(ctx.config);\n  const client = await connectDaemon(handle);\n  const watch = ctx.args.flags.has(\"--watch\");\n  try {\n    if (ctx.out.json && !watch) {\n      ctx.out.printJson(client.state());\n      return EXIT.ok;\n    }\n    ctx.out.print(renderTable(ctx.out, client.state()));\n    if (!watch) return EXIT.ok;\n    // Live mode: re-render throttled on every patch; Ctrl+C detaches cleanly.\n    await new Promise<void>((resolve) => {\n      let scheduled = false;\n      const rerender = () => {\n        if (scheduled) return;\n        scheduled = true;\n        setTimeout(() => {\n          scheduled = false;\n          if (ctx.out.json) {\n            process.stdout.write(`${JSON.stringify(client.state())}\\n`);\n          } else if (ctx.out.color) {\n            process.stdout.write(\"\\u001b[2J\\u001b[H\");\n            ctx.out.print(renderTable(ctx.out, client.state()));\n          } else {\n            ctx.out.print(renderTable(ctx.out, client.state()));\n          }\n        }, 100);\n      };\n      const off = client.realm.listenToPatches(rerender);\n      process.on(\"SIGINT\", () => {\n        off();\n        resolve();\n      });\n    });\n    return EXIT.ok;\n  } finally {\n    client.dispose();\n  }\n}\n","// Browser opening, devtools-ladder style + the WSL branch the devtools ladder lacks:\n// wslview → powershell.exe start → xdg-open. Best-effort by design; the caller always prints\n// the URL as the fallback.\n\nimport { spawn } from \"node:child_process\";\nimport { isWsl } from \"./commands/doctor\";\n\ninterface ICandidate {\n  command: string;\n  args: (url: string) => string[];\n}\n\nasync function candidates(): Promise<ICandidate[]> {\n  if (process.platform === \"win32\") {\n    return [{ command: \"cmd\", args: (url) => [\"/c\", \"start\", \"\", url] }];\n  }\n  if (process.platform === \"darwin\") {\n    return [{ command: \"open\", args: (url) => [url] }];\n  }\n  if (await isWsl()) {\n    return [\n      { command: \"wslview\", args: (url) => [url] },\n      { command: \"powershell.exe\", args: (url) => [\"-NoProfile\", \"Start\", url] },\n      { command: \"xdg-open\", args: (url) => [url] },\n    ];\n  }\n  return [{ command: \"xdg-open\", args: (url) => [url] }];\n}\n\n/** Try each opener in turn; resolves true when one spawns without an immediate failure. */\nexport async function openBrowser(url: string): Promise<boolean> {\n  // Headless boxes and tests: the caller prints the URL either way.\n  if (process.env[\"NICE_COMMANDER_NO_BROWSER\"] === \"1\") return false;\n  for (const candidate of await candidates()) {\n    const spawned = await new Promise<boolean>((resolve) => {\n      try {\n        const child = spawn(candidate.command, candidate.args(url), {\n          detached: true,\n          stdio: \"ignore\",\n          windowsHide: true,\n        });\n        child.once(\"error\", () => resolve(false));\n        child.once(\"spawn\", () => resolve(true));\n        child.unref();\n      } catch {\n        resolve(false);\n      }\n    });\n    if (spawned) return true;\n  }\n  return false;\n}\n","// `ui` — the one non-`up` command that may start the daemon: ensure it, then open the browser\n// (WSL-aware ladder) at the daemon's URL, always printing the URL as the copy-paste fallback.\n//\n// A daemon already running for this config is ATTACHED to, even one from another build, as long\n// as it serves its own client (its page then works whatever is installed now). Replacing it\n// stops everything it runs, so that is never implicit: `--fresh` asks for it.\n\nimport { pidAlive, signalDaemonShutdown } from \"../../daemon/instanceRecord\";\nimport { commanderPackageVersion } from \"../../daemon/packageVersion\";\nimport { unknownFlags } from \"../args\";\nimport type { ICommandContext } from \"../context\";\nimport {\n  connectDaemon,\n  ensureDaemonRunning,\n  findDaemon,\n  findOrphanDaemons,\n  findSkewedDaemon,\n  type IDaemonHandle,\n} from \"../daemonClient\";\nimport { CliExit, EXIT } from \"../load\";\nimport { openBrowser } from \"../openBrowser\";\n\n/** How long a wire-requested shutdown gets to finish its ladder before a signal follows it. */\nconst FRESH_EXIT_WAIT_MS = 30_000;\n\nexport async function cmdUi(ctx: ICommandContext): Promise<number> {\n  const bad = unknownFlags(ctx.args.flags, [\"--fresh\"]);\n  if (bad != null) throw new CliExit(EXIT.usage, bad);\n  const { out } = ctx;\n\n  if (ctx.args.flags.get(\"--fresh\") === true) {\n    await stopExistingDaemon(ctx);\n  } else {\n    const skewed = await findSkewedDaemon(ctx.config);\n    if (skewed?.servesOwnClient === true) {\n      const url = `http://127.0.0.1:${skewed.port}`;\n      const opened = await openBrowser(url);\n      if (out.json) {\n        out.printJson({ url, opened, attached: true, daemonBuild: skewed.packageVersion });\n      } else {\n        out.print(opened ? `opened ${url}` : `could not open a browser — visit ${url}`);\n        out.print(\n          out.paint(\n            \"gray\",\n            `attached to the running daemon (build ${skewed.packageVersion}; this CLI is ` +\n              `${await commanderPackageVersion()}). \\`nice-commander ui --fresh\\` restarts it ` +\n              \"on this build — that stops everything it runs.\",\n          ),\n        );\n      }\n      return EXIT.ok;\n    }\n  }\n\n  const handle = await ensureDaemonRunning(ctx.config);\n  ctx.spawnedDaemon = handle.spawned;\n  const url = `http://127.0.0.1:${handle.record.port}`;\n  const opened = await openBrowser(url);\n  if (out.json) {\n    out.printJson({ url, opened, attached: !handle.spawned });\n  } else {\n    if (handle.replaced != null) {\n      out.print(\n        out.paint(\n          \"gray\",\n          `replaced an idle daemon from build ${handle.replaced.packageVersion} (pid ${handle.replaced.pid})`,\n        ),\n      );\n    }\n    out.print(opened ? `opened ${url}` : `could not open a browser — visit ${url}`);\n  }\n  return EXIT.ok;\n}\n\n/**\n * `--fresh`: stop this config's daemon, whatever build it is, and wait until it has exited — the\n * boot that follows must not find (and reuse) a daemon that is still walking its ladder.\n * The wire goes first when it speaks our build: a signal is the fallback, because on Windows it\n * is a hard kill that skips the ladder.\n */\nasync function stopExistingDaemon(ctx: ICommandContext): Promise<void> {\n  const { config, out } = ctx;\n  const live = await findDaemon(config);\n  const skewed = live == null ? await findSkewedDaemon(config) : null;\n  const recorded =\n    live != null\n      ? { pid: live.record.pid, startStamp: live.record.startStamp }\n      : skewed != null\n        ? { pid: skewed.pid, startStamp: skewed.startStamp }\n        : null;\n  // Record-less daemons too: `--fresh` is the recovery path, and they are what needs recovering.\n  const targets = [\n    ...(recorded != null ? [recorded] : []),\n    ...(await findOrphanDaemons(config, recorded?.pid)),\n  ];\n  for (const target of targets) {\n    if (!out.json) {\n      out.print(out.paint(\"gray\", `--fresh: stopping the daemon (pid ${target.pid})…`));\n    }\n    if (target === recorded && live != null && (await stopOverWire(live))) continue;\n    const result = await signalDaemonShutdown(target);\n    if (result.outcome === \"exited\" || result.outcome === \"not-running\") continue;\n    throw new CliExit(\n      EXIT.failure,\n      result.outcome === \"still-stopping\"\n        ? `--fresh: the daemon (pid ${target.pid}) is still stopping — retry in a moment`\n        : `--fresh: pid ${target.pid} could not be verified as this config's daemon (possibly ` +\n            \"pid reuse), so nothing was stopped — verify it yourself, then retry\",\n    );\n  }\n}\n\n/** The graceful ask; false when the wire refuses us or the ladder outlasts the wait. */\nasync function stopOverWire(live: IDaemonHandle): Promise<boolean> {\n  try {\n    const client = await connectDaemon(live);\n    try {\n      await client.shutdown();\n    } finally {\n      client.dispose();\n    }\n  } catch (error) {\n    // The wire refused us (a wedged socket, a skew) — the caller's signal takes over.\n    if (!(error instanceof CliExit)) throw error;\n    return false;\n  }\n  return waitForExit(live.record.pid, FRESH_EXIT_WAIT_MS);\n}\n\nasync function waitForExit(pid: number, timeoutMs: number): Promise<boolean> {\n  const deadline = Date.now() + timeoutMs;\n  while (Date.now() < deadline) {\n    if (!pidAlive(pid)) return true;\n    await new Promise((resolve) => setTimeout(resolve, 150));\n  }\n  return !pidAlive(pid);\n}\n","// The saved-filter store: `<stateDir>/saved-filters.json`, one file per config. Pins and recent\n// runs from the web UI live here rather than in a browser, so every tab shares them and the CLI\n// can address a pin (`up @name`).\n//\n// One writer at a time, the same split as env-overrides.json: the daemon owns the file while it\n// is alive; the CLI only ever reads it.\n\nimport { mkdir, readFile, rename, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport {\n  checkSavedFilterQuery,\n  type ISavedFilter,\n  MAX_PIN_NAME_LENGTH,\n  MAX_PINS,\n  MAX_RECENTS,\n  savedFilterId,\n  type TSavedFilterQuery,\n} from \"../protocol/savedFilters\";\n\nconst STORE_VERSION = 1;\n\nfunction readable(value: unknown): ISavedFilter[] {\n  const filters = (value as { filters?: unknown } | null)?.filters;\n  if (!Array.isArray(filters)) return [];\n  const clean: ISavedFilter[] = [];\n  for (const entry of filters) {\n    const query = checkSavedFilterQuery(entry);\n    if (typeof query === \"string\") continue;\n    const record: Record<string, unknown> = { ...entry };\n    const name = record[\"name\"];\n    const lastRunAt = record[\"lastRunAt\"];\n    clean.push({\n      id: savedFilterId(query),\n      ...query,\n      pinned: record[\"pinned\"] === true,\n      ...(typeof name === \"string\" && name !== \"\"\n        ? { name: name.slice(0, MAX_PIN_NAME_LENGTH) }\n        : {}),\n      ...(typeof lastRunAt === \"number\" ? { lastRunAt } : {}),\n    });\n  }\n  return bounded(clean);\n}\n\n/** Pins are kept (newest-first cap); recents are a small ring, most recently run first. */\nfunction bounded(filters: readonly ISavedFilter[]): ISavedFilter[] {\n  const pins = filters.filter((filter) => filter.pinned).slice(0, MAX_PINS);\n  const recents = filters\n    .filter((filter) => !filter.pinned)\n    .sort((a, b) => (b.lastRunAt ?? 0) - (a.lastRunAt ?? 0))\n    .slice(0, MAX_RECENTS);\n  return [...pins, ...recents];\n}\n\n/** Missing, unreadable or corrupt all read as \"nothing saved\" — never a reason to fail a boot. */\nexport async function readSavedFilters(path: string): Promise<ISavedFilter[]> {\n  try {\n    return readable(JSON.parse(await readFile(path, \"utf8\")));\n  } catch {\n    return [];\n  }\n}\n\nexport async function writeSavedFilters(\n  path: string,\n  filters: readonly ISavedFilter[],\n): Promise<void> {\n  await mkdir(dirname(path), { recursive: true, mode: 0o700 });\n  const temp = `${path}.${process.pid}.tmp`;\n  await writeFile(temp, `${JSON.stringify({ version: STORE_VERSION, filters }, null, 2)}\\n`, {\n    encoding: \"utf8\",\n    mode: 0o600,\n  });\n  await rename(temp, path);\n}\n\nexport type TSavedFilterChange =\n  | { kind: \"pin\"; query: TSavedFilterQuery; name: string }\n  | { kind: \"ran\"; query: TSavedFilterQuery; at: number }\n  | { kind: \"remove\"; id: string };\n\n/** Pure: the list that results from `change`. */\nexport function mutateSavedFilters(\n  current: readonly ISavedFilter[],\n  change: TSavedFilterChange,\n): ISavedFilter[] {\n  if (change.kind === \"remove\") return current.filter((filter) => filter.id !== change.id);\n  const id = savedFilterId(change.query);\n  const existing = current.find((filter) => filter.id === id);\n  const rest = current.filter((filter) => filter.id !== id);\n  if (change.kind === \"pin\") {\n    const name = change.name.trim().slice(0, MAX_PIN_NAME_LENGTH);\n    return bounded([\n      { ...existing, id, ...change.query, pinned: true, ...(name !== \"\" ? { name } : {}) },\n      ...rest,\n    ]);\n  }\n  // A run refreshes whatever is there — a pin stays a pin, it just learns when it last ran.\n  return bounded([\n    { ...existing, id, ...change.query, pinned: existing?.pinned === true, lastRunAt: change.at },\n    ...rest,\n  ]);\n}\n","#!/usr/bin/env node\n\n// `nice-commander` bin. `daemon` is the hidden supervisor entry (spawned detached by\n// ensureDaemon); everything else is the user-facing surface. Exit codes are stable and\n// documented in --help.\n\nimport { parseCliArgs } from \"./cli/args\";\nimport { cmdDown, cmdRestart, cmdShutdown, cmdUp } from \"./cli/commands/control\";\nimport { cmdDoctor } from \"./cli/commands/doctor\";\nimport { cmdEnv } from \"./cli/commands/env\";\nimport { cmdExplain, cmdList } from \"./cli/commands/inspect\";\nimport { cmdLogs } from \"./cli/commands/logs\";\nimport { cmdPorts } from \"./cli/commands/ports\";\nimport { cmdRun } from \"./cli/commands/run\";\nimport { cmdStatus } from \"./cli/commands/status\";\nimport { cmdUi } from \"./cli/commands/ui\";\nimport type { ICommandContext } from \"./cli/context\";\nimport { CliExit, EXIT, loadConfigOrExit } from \"./cli/load\";\nimport { createOut } from \"./cli/out\";\nimport { commanderStatePaths, resolveCommanderDataDir } from \"./daemon/dataDir\";\nimport { readSavedFilters } from \"./daemon/savedFilters\";\n\nconst USAGE = `nice-commander — one typed config, one control surface, for dev environments.\n\nusage: nice-commander [--config <path>] [--json] [--no-color] [--timeout <ms>] [command] [selection] [flags]\n\nWith NO command, \"ui\" runs: the daemon is ensured and the browser opened. --help prints this text;\n<command> --help prints that command's section.\n\nselection: process ids, suite names, @pin names, tag=val, or --all. Several tag=val terms AND\ntogether; --any ORs them instead. A tag selection and --all never start an optIn process.\nBare up/explain use the config's defaultSelection (or print the suites and exit);\nbare down/restart/logs/run always require a selection — omission never means --all.\n`;\n\n/**\n * One entry per command, so `up --help` can answer with `up` alone. The full text is the usage\n * block followed by every entry, in this order.\n */\nconst COMMAND_HELP: readonly (readonly [string, string])[] = [\n  [\n    \"up\",\n    `  up [sel] [--no-wait] [--dry-run] [--replace-same] [--with <flag>]\n                                        start: deps auto-included, DAG order, live progress;\n                                        a ready service prints its URL. --with turns on a\n                                        flag the selected process declares (repeat it, or\n                                        a,b) — one id only. --replace-same lets a\n                                        start take an exclusive port from a STRAY — this same\n                                        command in the same cwd, started outside the daemon\n                                        (a stranger on the port still refuses). --json reports\n                                        every id's outcome, state, pid and endpoints as data.`,\n  ],\n  [\n    \"down\",\n    `  down <sel> [--only]                   stop the selection (dependents first) and each of its\n                                        dependencies that no other live process needs; one\n                                        that is still needed stays up and is named, with what\n                                        needs it. --only stops exactly the selection.`,\n  ],\n  [\n    \"restart\",\n    `  restart <sel> [--no-wait] [--replace-same] [--with <flag>]\n                                        stop + start exactly the selection, with the flags of\n                                        the run it replaces unless --with names others. Its\n                                        dependencies keep running; one that is down is\n                                        started first.`,\n  ],\n  [\"status\", \"  status [--watch]                      table from the live status realm\"],\n  [\n    \"logs\",\n    \"  logs <sel> [-f]                       merged interleaved tail with colored id prefixes\",\n  ],\n  [\n    \"list\",\n    \"  list                                  config introspection (processes, suites, warnings)\",\n  ],\n  [\n    \"explain\",\n    `  explain [sel] [--env]                 expanded ids, auto-included deps, DAG order, suite\n                                        policy; --env adds each id's spawn environment`,\n  ],\n  [\n    \"env\",\n    `  env [sel] [--set N=V] [--unset N]     declared env vars and their values; --clear drops\n                                        overrides. A set value is STICKY: it applies to every\n                                        later start until cleared, and never restarts anything.`,\n  ],\n  [\n    \"run\",\n    `  run <sel> [--parallel N] [--fail-fast] [--with <flag>] [-- <args>]\n                                        foreground, no daemon; tasks = local CI shape\n                                        (a suite supplies its own parallel/fail-fast),\n                                        a single id gets raw inherited stdio (interactive).\n                                        --with turns on declared flags; anything after --\n                                        is appended to that one id's command as-is.\n                                        --fail-fast = stop at the FIRST failure and stop the\n                                        survivors; without it every task still runs, every\n                                        failure is reported, and the exit code is still\n                                        non-zero. Children inherit THIS shell's environment;\n                                        daemon-owned processes (up) inherit the daemon's\n                                        boot-time snapshot instead — see doctor.`,\n  ],\n  [\n    \"ui\",\n    `  ui [--fresh]                          open the browser at this config's daemon (prints URL),\n                                        starting one if none runs. A running daemon is attached\n                                        to, even from an older build. --fresh stops it (and\n                                        everything it runs) and starts one on this build.`,\n  ],\n  [\n    \"doctor\",\n    `  doctor [--reap] [--reap-strays [--yes] [--force]]\n                                        diagnostics: ledger, capability, endpoints (each port\n                                        owner marked STRAY or not), env.\n                                        --reap collects a crashed daemon's orphans NOW\n                                        (same reap the next boot runs; refused while a\n                                        daemon is live). --reap-strays stops every stray —\n                                        a listener that is this config's own command outside\n                                        the daemon — after confirmation (--yes for scripts);\n                                        strangers are listed and left alone.`,\n  ],\n  [\n    \"ports\",\n    `  ports [sel] [--kill PID | --kill-owner] [--yes] [--force]\n                                        inspect exclusive TCP port owners (STRAY = this\n                                        definition's own command outside the daemon).\n                                        --kill PID stops that listener; --kill-owner stops\n                                        whatever holds the selection's exclusive endpoints,\n                                        no PID needed. Both prompt (--yes for scripts); a\n                                        stray is stopped as its tree, a stranger only as the\n                                        listener. --force sends SIGKILL instead of SIGTERM.`,\n  ],\n  [\"shutdown\", \"  shutdown                              stop the daemon (graceful ladder)\"],\n];\n\nconst FOOTER = `\nstatus/down/logs/doctor/shutdown never start a missing daemon — they report \"not running\".\nexit codes: 0 ok · 1 failure · 2 usage · 3 daemon not running · 4 timeout\n`;\n\nconst HELP = `${USAGE}\ncommands:\n${COMMAND_HELP.map(([, text]) => text).join(\"\\n\")}\n${FOOTER}`;\n\nfunction helpFor(command: string | null): string {\n  const entry = command == null ? undefined : COMMAND_HELP.find(([name]) => name === command);\n  if (entry == null) return HELP;\n  return `usage: nice-commander [--config <path>] [--json] [--no-color] [--timeout <ms>] ${entry[0]} …\\n\\n${entry[1]}\\n${FOOTER}`;\n}\n\nconst COMMANDS: Record<string, (ctx: ICommandContext) => Promise<number>> = {\n  up: cmdUp,\n  down: cmdDown,\n  restart: cmdRestart,\n  status: cmdStatus,\n  logs: cmdLogs,\n  list: cmdList,\n  explain: cmdExplain,\n  env: cmdEnv,\n  run: cmdRun,\n  ui: cmdUi,\n  doctor: cmdDoctor,\n  ports: cmdPorts,\n  shutdown: cmdShutdown,\n};\n\n/**\n * `--timeout` as a wall-clock bound on the whole command.\n *\n * ⚠ Two traps, both of which made the flag do the opposite of what it says. The timer must be\n * unref'd — a live one held the loop open for the FULL duration after a fast command had already\n * printed its answer. And a command that loses the race is still in flight: it owns a ws/realm the\n * CLI has no cancellation channel into, so merely returning exit 4 left the process running\n * forever. Detach the loser (its late settle must not surface as an unhandled rejection), let a\n * command that owns children stop them, then take the same hard-exit door as the interop tie.\n */\nasync function withTimeout(ctx: ICommandContext, run: Promise<number>): Promise<number> {\n  const timeoutMs = ctx.args.timeoutMs;\n  if (timeoutMs == null) return run;\n  const done = run.then((code) => ({ timedOut: false as const, code }));\n  const raced = await Promise.race([\n    done,\n    new Promise<{ timedOut: true }>((settle) => {\n      setTimeout(() => settle({ timedOut: true }), timeoutMs).unref();\n    }),\n  ]);\n  if (!raced.timedOut) return raced.code;\n  void done.catch(() => {});\n  await ctx.onTimeout?.().catch(() => {});\n  // Bounded flush: stderr is asynchronous on Windows pipes, so exiting on the next line can cut\n  // the message off — and waiting on the callback alone can hang under WSL interop.\n  await new Promise<void>((flushed) => {\n    process.stderr.write(`nice-commander: timed out after ${timeoutMs} ms\\n`, () => flushed());\n    setTimeout(flushed, 250).unref();\n  });\n  process.exit(EXIT.timeout);\n}\n\nasync function main(): Promise<number> {\n  const argv = process.argv.slice(2);\n  if (argv[0] === \"daemon\") {\n    const { runCommanderDaemon } = await import(\"./daemon/main.js\");\n    return runCommanderDaemon(argv.slice(1));\n  }\n  const parsed = parseCliArgs(argv);\n  if (\"error\" in parsed) {\n    process.stderr.write(`nice-commander: ${parsed.error}\\n`);\n    return EXIT.usage;\n  }\n  if (parsed.passthrough.length > 0 && parsed.command !== \"run\") {\n    process.stderr.write(\n      \"nice-commander: arguments after `--` go to a foreground `run` only — a daemon start \" +\n        \"appends only the flags a process declares (`--with <flag>`)\\n\",\n    );\n    return EXIT.usage;\n  }\n  if (parsed.help || parsed.command === \"help\") {\n    process.stdout.write(helpFor(parsed.command === \"help\" ? null : parsed.command));\n    return EXIT.ok;\n  }\n  // No command = \"show me my dev environment\", which is `ui` — the sibling `nice-devtools` CLI\n  // serves its dashboard bare for the same reason. Help stays one `--help` away; `ui` starts the\n  // daemon and nothing else, so a mistyped bare invocation costs one `shutdown`.\n  const requested = parsed.command ?? \"ui\";\n  const command = COMMANDS[requested];\n  if (command == null) {\n    process.stderr.write(`nice-commander: unknown command \"${requested}\" (--help lists them)\\n`);\n    return EXIT.usage;\n  }\n  try {\n    const config = await loadConfigOrExit(parsed.configPath);\n    const ctx: ICommandContext = { args: parsed, out: createOut(parsed), config };\n    if (parsed.positionals.some((term) => term.startsWith(\"@\"))) {\n      const paths = commanderStatePaths(resolveCommanderDataDir(), config.configKey);\n      ctx.pins = await readSavedFilters(paths.savedFiltersPath);\n    }\n    const code = await withTimeout(ctx, command(ctx));\n    // A daemon spawned this run pins the event loop when the CLI itself was launched via WSL\n    // interop (a DETACHED child holds the interop session while it lives — unref is not\n    // enough, and even a stdout flush callback never fires). The daemon survives regardless,\n    // so hard-exit instead of draining — identical user-visible behavior everywhere else.\n    if (ctx.spawnedDaemon === true) process.exit(code);\n    return code;\n  } catch (error) {\n    if (error instanceof CliExit) {\n      process.stderr.write(`nice-commander: ${error.message}\\n`);\n      return error.code;\n    }\n    process.stderr.write(`nice-commander: ${(error as Error).message}\\n`);\n    return EXIT.failure;\n  }\n}\n\nmain().then(\n  (code) => {\n    process.exitCode = code;\n  },\n  (error: unknown) => {\n    process.stderr.write(`nice-commander: ${(error as Error).message}\\n`);\n    process.exitCode = EXIT.failure;\n  },\n);\n"],"x_google_ignoreList":[52,67,84,85,93,94,95,96,97,98,99,100,101,102,138,139,140,141,142,143,148,202,203],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAoBA,MAAM,qBAAqB,IAAI,IAAI,CAAC,YAAY,WAAW,CAAC;;;;;;AAO5D,MAAM,yBAAyB,IAAI,IAAI;CAAC;CAAS;CAAW;AAAQ,CAAC;;;;;;;AAQrE,MAAM,sBAAsB,IAAI,IAAI,CAAC,cAAc,QAAQ,CAAC;AAE5D,SAAgB,aAAa,MAAuD;CAClF,MAAM,wBAAQ,IAAI,IAA2B;CAC7C,MAAM,2BAAW,IAAI,IAAsB;CAC3C,MAAM,cAAwB,CAAC;CAC/B,MAAM,cAAwB,CAAC;CAC/B,IAAI,UAAyB;CAC7B,IAAI,OAAO;CACX,IAAI,UAAU;CACd,IAAI,OAAO;CACX,IAAI;CACJ,IAAI;CAEJ,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK,GAAG;EACvC,MAAM,QAAQ,KAAK;EACnB,IAAI,UAAU,MAAM;GAClB,YAAY,KAAK,GAAG,KAAK,MAAM,IAAI,CAAC,CAAC;GACrC;EACF;EAEA,MAAM,KAAK,MAAM,WAAW,IAAI,IAAI,MAAM,QAAQ,GAAG,IAAI;EACzD,MAAM,MAAM,KAAK,IAAI,MAAM,MAAM,GAAG,EAAE,IAAI;EAC1C,MAAM,cAAc,KAAK,IAAI,M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