@athrio/loom 0.0.8 → 0.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"design-S_129JVC.js","names":["types","standardTypes","otherTypes","Mime","TypeId","Data.Error","Data.TaggedError","Proto","Inspectable.BaseProto","Record.map","Duration.seconds","empty","Record.isEmptyRecord","Duration.toSeconds","Duration.fromInputUnsafe","TypeId","Proto","Redactable.symbolRedactable","Context.get","Redactable.redact","Equal.symbol","Equivalence","Hash.symbol","Hash.structure","Inspectable.NodeInspectSymbol","Inspectable.BaseProto","make","empty","fromInput","Redacted.make","TypeId","Data.TaggedError","Schema.ErrorClass","TypeId","Proto","Equal.symbol","Hash.symbol","Hash.array","make","Arr.fromIterable","Schema.link","Schema.Array","Schema.Tuple","Schema.String","SchemaTransformation.transform","TypeId","Data.TaggedError","Proto","Inspectable.NodeInspectSymbol","Empty","empty","raw","Uint8Array","uint8Array","encoder","text","json","Effect.try","Stream","stream","TypeId","schemaBodyJson","Schema.decodeEffect","Schema.toCodecJson","Effect.flatMap","Effect.runSync","redact","TypeId","Inspectable.Class","HttpIncomingMessage.TypeId","HttpIncomingMessage.inspect","Headers.fromInput","Cookies.fromSetCookie","Option.none","Stream.fromReadableStream","Error.HttpClientError","Error.DecodeError","Stream.fail","Error.EmptyBodyError","Effect.flatMap","Effect.try","Effect.tryPromise","Effect.cached","Effect.runSync","Effect.map","UrlParams.fromInput","Option.isSome","Option.none","Option.some","Tracer.externalSpan","parse","make","QS.parse","make","internal.make","TypeId","Headers.fromInput","Headers.empty","Cookies.empty","Body.uint8Array","Body.text","Effect.map","Body.json","Body.raw","stream","Body.stream","Effect.flatMap","Headers.set","Headers.setAll","Inspectable.Class","HttpIncomingMessage.TypeId","HttpClientResponse.TypeId","HttpIncomingMessage.inspect","Headers.merge","Option.none","Stream.empty","Stream.mapError","Stream.succeed","Stream.fromReadableStream","isReadableStream","Stream.unwrap","Effect.try","HttpClientError.HttpClientError","HttpClientError.DecodeError","Effect.succeed","Stream.mkUint8Array","Effect.tryPromise","textDecoder","UrlParams.fromInput","Effect.contextWith","Stream.toReadableStreamWith","Proto","ErrorReporter.ignore","redact","Body.empty","Headers.fromRecordUnsafe","notFound","Response.isHttpServerResponse","Effect.succeed","Effect.catchCause","Schema.isSchemaError","Cause.isNoSuchElementError","TypeId","Data.TaggedError","Respondable.symbol","ErrorReporter.ignore","Effect.succeed","Response.empty","InternalError","ClientAbort","Context.Service","Cause.StackTrace","Respondable.toResponseOrElse","Response.isHttpServerResponse","Respondable.toResponseOrElseDefect","Cause.fromReasons","Effect.mapEager","Cause.makeDieReason","Option.some","Option.none","TypeId","make","decoder","Predicate.hasProperty","Schema.ErrorClass","Schema.Number","Schema.String","Result.succeed","Result.fail","Schema.TaggedErrorClass","WebSocket","Context.Service","Effect.withFiber","Latch.makeUnsafe","Effect.scopedWith","Effect.fnUntraced","FiberSet.make","Scope.provide","Effect.provideService","FiberSet.runtime","Effect.flatMap","Effect.promise","Effect.isEffect","Effect.void","Effect.fail","Deferred.makeUnsafe","Deferred.await","Effect.timeoutOrElse","Effect.raceFirst","FiberSet.join","Effect.catchFilter","Effect.updateContext","Context.merge","Effect.ensuring","Effect.sync","Effect.succeed","State","make","make","defaultIsFile","CT.parse","make","HP.make","Search.make","decodeField","make","internal.make","internal.defaultIsFile","internal.decodeField","TypeId","Data.Error","Data.TaggedError","Effect.withFiber","Context.get","Effect.succeed","UndefinedOr.map","IncomingMessage.MaxBodySize","MP.defaultIsFile","Channel.fromTransform","Effect.map","Option.none","MP.make","FieldImpl","MP.decodeField","Channel.fromPull","Effect.suspend","Arr.isReadonlyArrayNonEmpty","Cause.done","Effect.flatMap","FileImpl","Option.some","Exit.fail","convertError","Cause.Done","Effect.void","Effect.catchCause","Pull.isDoneCause","Exit.failCause","Option.isSome","PartBase","Inspectable.Class","Stream.fromChannel","Effect.mapError","FileSystem.FileSystem","Stream.run","Channel.runFold","Effect.gen","Path.Path","Stream.runForEach","Effect.catchTag","Effect.fail","TypeId","Context.Service","HttpIncomingMessage.schemaBodyJson","Effect.flatMap","ServerRequestImpl","Inspectable.Class","HttpIncomingMessage.TypeId","HttpIncomingMessage.inspect","Option.none","Headers.fromInput","Cookies.parseHeader","Stream.fromReadableStream","Stream.fail","Effect.runSync","Effect.cached","Effect.tryPromise","Effect.try","UrlParams.fromInput","Multipart.toPersisted","Stream.pipeThroughChannel","Stream.mapError","Multipart.makeChannel","Effect.fail","Stream.empty","Stream.succeed","Effect.succeed","Stream.mkUint8Array","Effect.map","Stream.fromIterable","Multipart.TypeId","Option.some","Effect.flatMap","make","Effect.withFiber","Context.getUnsafe","Effect.withLogSpan","Effect.flatMap","Effect.exit","Effect.andThen","Effect.annotateLogs","Effect.log","Option.getOrElse","internalEffect.makeSpanUnsafe","Option.getOrUndefined","TraceContext.fromHeaders","Context.add","Effect.onExitPrimitive","Request.toURL","Option.isSome","Headers.CurrentRedactedNames","Headers.redact","Exit.isFailure","Exit.failCause","Exit.succeed","cors","Headers.fromRecordUnsafe","Effect.succeed","Response.setHeaders","Response.empty","Effect.flatMapEager","Fiber.getCurrent","Context.getUnsafe","Effect.succeed","Effect.failCause","Effect.matchCauseEffect","Effect.mapEager","Effect.void","Effect.matchCauseEffectEager","Response.empty","Request.HttpServerRequest","Effect.uninterruptible","Effect.withFiber","Scope.makeUnsafe","Context.add","Scope.Scope","Effect.onExitPrimitive","Scope.closeUnsafe","Context.Service","Option.match","layer","Effect.sync","Context.Service","make","FileSystem.FileSystem","Etag.Generator","Effect.fnUntraced","Headers.set","Headers.fromInput","Headers.empty","Etag.toString","Option.isSome","Effect.map","Headers.merge","Headers.fromRecordUnsafe","Context.Service","make","serve","Effect.isEffect","Layer.effectDiscard","Effect.flatMap","Effect.log","Layer.provideMerge","TypeId","make","FindMyWay.make","Effect.contextWith","Effect.void","HttpServerResponse.isHttpServerResponse","Effect.succeed","Effect.isEffect","Effect.flatMap","HttpServerRequest.HttpServerRequest","Effect.sync","Effect.withFiber","Effect.fail","HttpServerError.HttpServerError","HttpServerError.RouteNotFound","Option.isSome","Effect.provideContext","Effect.interruptible","Context.makeUnsafe","Arr.reverse","Context.Service","Layer.effectDiscard","layer","Option.some","Option.none","Option.match","Effect.gen","Layer.effectContext","Effect.map","Layer.succeedContext","context","Effect.context","Layer.CurrentMemoMap","Context.get","Scope.Scope","Layer.buildWithMemoMap","Layer.provide","Layer.provideMerge","Arr.empty","Arr.fromIterable","HttpMiddleware.cors","HttpMiddleware.withLoggerDisabled","HttpMiddleware.logger","Layer.succeed","HttpServer.serve","Layer.unwrap","HttpServer.withLogAddress","Context.Service","Effect.sync","Predicate.hasProperty","Option.some","Option.none","Stream_.isStream","Schema.make","Context.Service","Cause.StackTrace","TypeId","Context.empty","Context.add","Proto","makeProto","Schema.isSchema","Schema.Struct","Context.merge","make","Schema.Void","Schema.Never","Schema.Defect","Schema.Class","PrimaryKey.symbol","RpcSchema.Stream","RpcSchema.getStreamSchemas","Option.isSome","Schema.Exit","Schema.Union","RequestId","position","bundledStrings","fs","Context.Service","Predicate.isNullish","Predicate.hasProperty","Layer.succeed","Effect.suspend","Semaphore.makeUnsafe","Effect.contextWith","Effect.void","Effect.map","Effect.gen","Effect.provideContext","Effect.onExit","Effect.never","makeNoSerialization","Effect.context","Context.get","Scope.Scope","Scope.addFinalizer","Effect.withFiber","Exit.interrupt","Effect.fnUntraced","Queue.end","Queue.failCause","RpcSchema.isStreamSchema","Headers.fromInput","Headers.empty","Context.empty","Effect.useSpan","Stream.unwrap","Effect.map","Stream.fromQueue","Effect.interrupt","Headers.merge","Effect.onInterrupt","Effect.callback","Effect.withParentSpan","Effect.runForkWith","Effect.andThen","Fiber.interrupt","Effect.makeSpanScoped","Fiber.getCurrent","Context.getUnsafe","Scope.addFinalizerExit","Effect.void","Exit.isFailure","Cause.interruptors","Queue.bounded","Effect.catchCause","Effect.interruptible","Effect.forkIn","Effect.timeout","Queue.offerAll","Effect.flatMap","Exit.die","make","Protocol","Transferable.makeCollectorUnsafe","Context.add","Transferable.Collector","Effect.provideContext","Effect.orDie","RequestId","Option.isNone","Effect.onError","Exit.failCause","Effect.matchCauseEffect","Exit.fail","Effect.forEach","Effect.logError","Effect.forkScoped","RpcSchema.getStreamSchemas","Option.map","Schema.decodeUnknownEffect","Schema.toCodecJson","Schema.NonEmptyArray","Schema.encodeEffect","Rpc.exitSchema","Context.Service","Effect.context","Context.get","Scope.Scope","Fiber.runIn","Scope.forkUnsafe","Semaphore.make","Latch.makeUnsafe","Scope.addFinalizer","Effect.withFiber","Effect.runForkWith","Effect.void","Effect.catchDefect","Effect.interrupt","Rpc.ServerClient","Exit.interrupt","Effect.andThen","Exit.die","Effect.ensuring","RpcSchema.isStreamSchema","isWrapper","Rpc.isWrapper","Scope.makeUnsafe","Effect.onExit","Deferred.isDeferred","Cause.hasDies","Cause.hasInterrupts","Cause.squash","Scope.closeUnsafe","Fiber.getCurrent","Effect.withSpan","Tracer.externalSpan","Context.makeUnsafe","onExit","Deferred.await","Effect.isEffect","Effect.flatMap","Effect.whileLoop","Queue.takeAll","Pull.catchDone","Effect.scoped","Stream.runForEachArray","Effect.suspend","Context.getUnsafe","make","Scope.make","Effect.provideContext","Scope.provide","Effect.forkChild","Queue.take","RpcSchema.getStreamSchemas","Schema.decodeUnknownEffect","Schema.toCodecJson","Schema.encodeUnknownEffect","Schema.Array","Option.isSome","Schema.Any","Rpc.exitSchema","Effect.provideService","Transferable.Collector","Effect.catchCause","Cause.map","Effect.annotateLogs","Effect.logDebug","Predicate.hasProperty","RequestId","Effect.succeed","Effect.matchEffect","Transferable.makeCollectorUnsafe","Headers.fromInput","Effect.tapCause","Effect.logFatal","Scope.close","Context.Service","RpcSerialization.RpcSerialization","Queue.make","Effect.gen","HttpServerRequest.HttpServerRequest","Effect.orDie","Effect.map","offer","Queue.offer","Queue.end","Scope.addFinalizerExit","Effect.forEach","Queue.collect","HttpServerResponse.text","HttpServerResponse.uint8Array","HttpServerResponse.stream","Stream.fromArray","Stream.concat","Stream.fromQueue","Effect.sync","Effect.succeedNone","HttpRouter.HttpRouter","Layer.effect","makeProto","Context.makeUnsafe","Effect.gen","Effect.context","Effect.isEffect","Layer.effectContext","Effect.contextWith","Effect.succeed","Rpc.isWrapper","Effect.provide","Stream.provideContext","Context.add","Context.make","Context.merge","make","Context.empty","EventEmitter","http","URL","createHash","Duplex","Inspectable.Class","IncomingMessage.TypeId","Headers.fromInput","Option.fromNullishOr","Effect.runSync","Effect.cached","Effect.flatMap","IncomingMessage.MaxBodySize","NodeStream.toString","Effect.map","Effect.try","UrlParams.fromInput","NodeStream.fromReadable","Effect.withFiber","NodeStream.toArrayBuffer","make","ServerResponse.raw","Mime","Headers.merge","Headers.fromRecordUnsafe","layer","Platform.HttpPlatform","NodeFileSystem.layer","EtagImpl.layer","MP.make","make","Multipart.makeConfig","Effect.map","NodeStream.fromReadable","MP.make","Stream.unwrap","Stream.map","Multipart.toPersisted","Effect.tryPromise","NFS","Inspectable.Class","Multipart.TypeId","MP.decodeField","NodeStream.toUint8Array","make","scope","Effect.scope","Effect.callback","Effect.void","Effect.die","Effect.cached","Effect.timeoutOrElse","Duration.seconds","Scope.addFinalizer","Effect.fail","Effect.acquireRelease","Effect.sync","Scope.provide","HttpServer.make","Effect.fnUntraced","Scope.forkUnsafe","Scope.addFinalizerExit","HttpEffect.toHandled","Effect.withFiber","Effect.succeed","Fiber.runIn","Effect.runForkWith","Context.makeUnsafe","ClientAbort","Socket.fromWebSocket","Effect.flatMap","Request.TypeId","Cookies.parseHeader","Effect.runSync","NodeMultipart.persisted","NodeMultipart.stream","HttpIncomingMessage.inspect","HttpServer.HttpServer","NodeHttpPlatform.layer","Etag.layerWeak","NodeServices.layer","layer","Layer.mergeAll","Cookies.isEmpty","Cookies.toSetCookieHeaders","Effect.tryPromise","Effect.interruptible","Effect.tapCause","Effect.suspend","Latch.makeUnsafe","Stream.orDie","Stream.runForEachArray","Effect.matchCauseEffect","Effect.failCause","Cause.combine","Cause.die","Schema.Literals","Schema.String","Schema.Array","Schema.Tuple","Schema.UndefinedOr","Schema.Record","Schema.Union","Schema.Redacted","Schema.Number","Schema.Class","Schema.withConstructorDefault","Effect.succeed","Schema.withDecodingDefault","redact","Redacted.isRedacted","Schema.ErrorClass","Schema.String","Option.getOrUndefined","Schema.MutableJson","Schema.optional","Schema.Number","Schema.Duration","Duration.format","Schema.DateTimeUtc","Schema.Json","Schema.Unknown","TypeId","Predicate.hasProperty","make","TypeId","Proto","Predicate.isUndefined","Schema.Union","AiError.AiError","Schema.isSchema","Schema.decodeUnknownEffect","Effect.succeed","Schema.encodeUnknownEffect","Effect.fnUntraced","Effect.annotateCurrentSpan","AiError.make","AiError.ToolNotFoundError","Effect.mapError","AiError.ToolParameterValidationError","Queue.make","Effect.asVoid","Queue.offer","Effect.flatMap","Effect.updateContext","Context.merge","Effect.matchCauseEffect","Queue.failCause","Queue.end","Effect.forkChild","AiError.ToolResultEncodingError","Schema.isSchemaError","AiError.InvalidToolResultError","AiError.isAiErrorReason","Stream.fromQueue","Stream.catch","Stream.fail","Stream.succeed","Stream.mapEffect","Stream.onEnd","Fiber.interrupt","Effect.gen","Effect.context","Effect.isEffect","context","Context.makeUnsafe","Layer.effectContext","make","TypeId","Predicate.hasProperty","Context.add","Context.merge","Schema.Void","Schema.Never","Context.empty","Schema.isSchema","SchemaAST.resolveDescription","Predicate.isNotUndefined","Schema.toJsonSchemaDocument","Context.Service","Schema.String","Context.Service","Schema.Never","Effect.sync","Schema.optionalKey","Schema.decode","SchemaGetter.withDefault","SchemaGetter.passthrough","Schema.withConstructorDefault","Schema.decodeTo","Schema.optional","SchemaGetter.transformOptional","Option.flatMap","Option.fromUndefinedOr","Schema.String","Schema.Number","Schema.Opaque","Schema.Json","Schema.Class","Schema.Boolean","Schema.Any","Schema.ErrorClass","Rpc.make","Schema.Uint8Array","Context.Service","RpcMiddleware.Service","RpcGroup.make","Context.Service","Arr.empty","Queue.make","RpcClient.makeNoSerialization","Effect.suspend","Effect.void","Exit.void","Effect.fail","Effect.succeed","Effect.fnUntraced","RpcServer.Protocol","Option.isSome","Effect.serviceOption","HttpRouter.HttpRouter","Layer.build","RcMap.make","RpcClient.make","Effect.provideServiceEffect","RpcClient.Protocol","Fiber.getCurrent","Context.getOrUndefined","HttpServerRequest.HttpServerRequest","HttpServerResponse.empty","Effect.die","Effect.provideService","RcMap.get","Effect.map","Context.getUnsafe","HttpServerResponse.setHeader","RpcMessage.RequestId","Rpc.ServerClient","Headers.fromInput","Effect.flatMap","Effect.scoped","Schema.encodeUnknownEffect","Schema.Union","Queue.take","Effect.catchCause","Effect.forever","Effect.forkScoped","RpcServer.make","Effect.provide","Layer.effectDiscard","Layer.provideMerge","Layer.provide","RpcServer.layerProtocolHttp","RpcSerialization.layerJsonRpc","Effect.context","Tool.Meta","McpTool","Tool.getDescription","Tool.getJsonSchema","Context.getOption","Tool.Title","Option.map","Option.getOrUndefined","Context.get","Tool.Readonly","Tool.Destructive","Tool.Idempotent","Tool.OpenWorld","Stream.unwrap","Stream.run","Sink.last","Effect.fromOption","Effect.provideContext","Effect.matchCause","Cause.pretty","Effect.tapCause","Effect.log","toolkit","FindMyWay.make","Effect.gen","Effect.withFiber","HttpServerResponse.setHeaders","Effect.sync"],"sources":["../../../node_modules/@effect/platform-node/node_modules/mime/dist/types/other.js","../../../node_modules/@effect/platform-node/node_modules/mime/dist/types/standard.js","../../../node_modules/@effect/platform-node/node_modules/mime/dist/src/Mime.js","../../../node_modules/@effect/platform-node/node_modules/mime/dist/src/index.js","../../../node_modules/@effect/platform-node/dist/Mime.js","../../../node_modules/effect/dist/unstable/http/Cookies.js","../../../node_modules/effect/dist/unstable/http/Headers.js","../../../node_modules/effect/dist/unstable/http/HttpClientError.js","../../../node_modules/effect/dist/unstable/http/UrlParams.js","../../../node_modules/effect/dist/unstable/http/HttpBody.js","../../../node_modules/effect/dist/unstable/http/HttpIncomingMessage.js","../../../node_modules/effect/dist/unstable/http/HttpClientResponse.js","../../../node_modules/effect/dist/unstable/http/HttpTraceContext.js","../../../node_modules/find-my-way-ts/dist/esm/QueryString.js","../../../node_modules/find-my-way-ts/dist/esm/internal/router.js","../../../node_modules/find-my-way-ts/dist/esm/index.js","../../../node_modules/effect/dist/unstable/http/HttpServerResponse.js","../../../node_modules/effect/dist/unstable/http/HttpServerRespondable.js","../../../node_modules/effect/dist/unstable/http/HttpServerError.js","../../../node_modules/effect/dist/unstable/socket/Socket.js","../../../node_modules/multipasta/dist/esm/internal/contentType.js","../../../node_modules/multipasta/dist/esm/internal/headers.js","../../../node_modules/multipasta/dist/esm/internal/search.js","../../../node_modules/multipasta/dist/esm/internal/multipart.js","../../../node_modules/multipasta/dist/esm/index.js","../../../node_modules/effect/dist/unstable/http/Multipart.js","../../../node_modules/effect/dist/unstable/http/HttpServerRequest.js","../../../node_modules/effect/dist/unstable/http/internal/preResponseHandler.js","../../../node_modules/effect/dist/unstable/http/HttpMiddleware.js","../../../node_modules/effect/dist/unstable/http/HttpEffect.js","../../../node_modules/effect/dist/unstable/http/Etag.js","../../../node_modules/effect/dist/unstable/http/HttpPlatform.js","../../../node_modules/effect/dist/unstable/http/HttpServer.js","../../../node_modules/effect/dist/unstable/http/HttpRouter.js","../../../node_modules/effect/dist/unstable/workers/Transferable.js","../../../node_modules/effect/dist/unstable/rpc/RpcSchema.js","../../../node_modules/effect/dist/unstable/rpc/Rpc.js","../../../node_modules/effect/dist/unstable/rpc/RpcMessage.js","../../../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","../../../node_modules/effect/dist/unstable/rpc/RpcSerialization.js","../../../node_modules/effect/dist/unstable/rpc/Utils.js","../../../node_modules/effect/dist/unstable/rpc/RpcClient.js","../../../node_modules/effect/dist/unstable/rpc/RpcServer.js","../../../node_modules/effect/dist/unstable/rpc/RpcGroup.js","../../../node_modules/ws/lib/constants.js","../__vite-optional-peer-dep:bufferutil:ws","../../../node_modules/ws/lib/buffer-util.js","../../../node_modules/ws/lib/limiter.js","../../../node_modules/ws/lib/permessage-deflate.js","../__vite-optional-peer-dep:utf-8-validate:ws","../../../node_modules/ws/lib/validation.js","../../../node_modules/ws/lib/receiver.js","../../../node_modules/ws/lib/sender.js","../../../node_modules/ws/lib/event-target.js","../../../node_modules/ws/lib/extension.js","../../../node_modules/ws/lib/websocket.js","../../../node_modules/ws/lib/stream.js","../../../node_modules/ws/lib/subprotocol.js","../../../node_modules/ws/lib/websocket-server.js","../../../node_modules/ws/wrapper.mjs","../../../node_modules/@effect/platform-node/dist/NodeHttpIncomingMessage.js","../../../node_modules/@effect/platform-node/dist/NodeHttpPlatform.js","../../../node_modules/multipasta/dist/esm/node.js","../../../node_modules/@effect/platform-node/dist/NodeMultipart.js","../../../node_modules/@effect/platform-node/dist/NodeHttpServer.js","../../../node_modules/effect/dist/unstable/ai/Response.js","../../../node_modules/effect/dist/unstable/ai/AiError.js","../../../node_modules/effect/dist/unstable/ai/Toolkit.js","../../../node_modules/effect/dist/unstable/ai/Tool.js","../../../node_modules/effect/dist/unstable/rpc/RpcMiddleware.js","../../../node_modules/effect/dist/unstable/ai/McpSchema.js","../../../node_modules/effect/dist/unstable/ai/McpServer.js","../../loom-design/src/mcp.ts","../../loom-design/src/api.ts","../../loom-design/src/design.ts"],"sourcesContent":["const types = {\n 'application/prs.cww': ['cww'],\n 'application/prs.xsf+xml': ['xsf'],\n 'application/vnd.1000minds.decision-model+xml': ['1km'],\n 'application/vnd.3gpp.pic-bw-large': ['plb'],\n 'application/vnd.3gpp.pic-bw-small': ['psb'],\n 'application/vnd.3gpp.pic-bw-var': ['pvb'],\n 'application/vnd.3gpp2.tcap': ['tcap'],\n 'application/vnd.3m.post-it-notes': ['pwn'],\n 'application/vnd.accpac.simply.aso': ['aso'],\n 'application/vnd.accpac.simply.imp': ['imp'],\n 'application/vnd.acucobol': ['acu'],\n 'application/vnd.acucorp': ['atc', 'acutc'],\n 'application/vnd.adobe.air-application-installer-package+zip': ['air'],\n 'application/vnd.adobe.formscentral.fcdt': ['fcdt'],\n 'application/vnd.adobe.fxp': ['fxp', 'fxpl'],\n 'application/vnd.adobe.xdp+xml': ['xdp'],\n 'application/vnd.adobe.xfdf': ['*xfdf'],\n 'application/vnd.age': ['age'],\n 'application/vnd.ahead.space': ['ahead'],\n 'application/vnd.airzip.filesecure.azf': ['azf'],\n 'application/vnd.airzip.filesecure.azs': ['azs'],\n 'application/vnd.amazon.ebook': ['azw'],\n 'application/vnd.americandynamics.acc': ['acc'],\n 'application/vnd.amiga.ami': ['ami'],\n 'application/vnd.android.package-archive': ['apk'],\n 'application/vnd.anser-web-certificate-issue-initiation': ['cii'],\n 'application/vnd.anser-web-funds-transfer-initiation': ['fti'],\n 'application/vnd.antix.game-component': ['atx'],\n 'application/vnd.apple.installer+xml': ['mpkg'],\n 'application/vnd.apple.keynote': ['key'],\n 'application/vnd.apple.mpegurl': ['m3u8'],\n 'application/vnd.apple.numbers': ['numbers'],\n 'application/vnd.apple.pages': ['pages'],\n 'application/vnd.apple.pkpass': ['pkpass'],\n 'application/vnd.aristanetworks.swi': ['swi'],\n 'application/vnd.astraea-software.iota': ['iota'],\n 'application/vnd.audiograph': ['aep'],\n 'application/vnd.autodesk.fbx': ['fbx'],\n 'application/vnd.balsamiq.bmml+xml': ['bmml'],\n 'application/vnd.blueice.multipass': ['mpm'],\n 'application/vnd.bmi': ['bmi'],\n 'application/vnd.businessobjects': ['rep'],\n 'application/vnd.chemdraw+xml': ['cdxml'],\n 'application/vnd.chipnuts.karaoke-mmd': ['mmd'],\n 'application/vnd.cinderella': ['cdy'],\n 'application/vnd.citationstyles.style+xml': ['csl'],\n 'application/vnd.claymore': ['cla'],\n 'application/vnd.cloanto.rp9': ['rp9'],\n 'application/vnd.clonk.c4group': ['c4g', 'c4d', 'c4f', 'c4p', 'c4u'],\n 'application/vnd.cluetrust.cartomobile-config': ['c11amc'],\n 'application/vnd.cluetrust.cartomobile-config-pkg': ['c11amz'],\n 'application/vnd.commonspace': ['csp'],\n 'application/vnd.contact.cmsg': ['cdbcmsg'],\n 'application/vnd.cosmocaller': ['cmc'],\n 'application/vnd.crick.clicker': ['clkx'],\n 'application/vnd.crick.clicker.keyboard': ['clkk'],\n 'application/vnd.crick.clicker.palette': ['clkp'],\n 'application/vnd.crick.clicker.template': ['clkt'],\n 'application/vnd.crick.clicker.wordbank': ['clkw'],\n 'application/vnd.criticaltools.wbs+xml': ['wbs'],\n 'application/vnd.ctc-posml': ['pml'],\n 'application/vnd.cups-ppd': ['ppd'],\n 'application/vnd.curl.car': ['car'],\n 'application/vnd.curl.pcurl': ['pcurl'],\n 'application/vnd.dart': ['dart'],\n 'application/vnd.data-vision.rdz': ['rdz'],\n 'application/vnd.dbf': ['dbf'],\n 'application/vnd.dcmp+xml': ['dcmp'],\n 'application/vnd.dece.data': ['uvf', 'uvvf', 'uvd', 'uvvd'],\n 'application/vnd.dece.ttml+xml': ['uvt', 'uvvt'],\n 'application/vnd.dece.unspecified': ['uvx', 'uvvx'],\n 'application/vnd.dece.zip': ['uvz', 'uvvz'],\n 'application/vnd.denovo.fcselayout-link': ['fe_launch'],\n 'application/vnd.dna': ['dna'],\n 'application/vnd.dolby.mlp': ['mlp'],\n 'application/vnd.dpgraph': ['dpg'],\n 'application/vnd.dreamfactory': ['dfac'],\n 'application/vnd.ds-keypoint': ['kpxx'],\n 'application/vnd.dvb.ait': ['ait'],\n 'application/vnd.dvb.service': ['svc'],\n 'application/vnd.dynageo': ['geo'],\n 'application/vnd.ecowin.chart': ['mag'],\n 'application/vnd.enliven': ['nml'],\n 'application/vnd.epson.esf': ['esf'],\n 'application/vnd.epson.msf': ['msf'],\n 'application/vnd.epson.quickanime': ['qam'],\n 'application/vnd.epson.salt': ['slt'],\n 'application/vnd.epson.ssf': ['ssf'],\n 'application/vnd.eszigno3+xml': ['es3', 'et3'],\n 'application/vnd.ezpix-album': ['ez2'],\n 'application/vnd.ezpix-package': ['ez3'],\n 'application/vnd.fdf': ['*fdf'],\n 'application/vnd.fdsn.mseed': ['mseed'],\n 'application/vnd.fdsn.seed': ['seed', 'dataless'],\n 'application/vnd.flographit': ['gph'],\n 'application/vnd.fluxtime.clip': ['ftc'],\n 'application/vnd.framemaker': ['fm', 'frame', 'maker', 'book'],\n 'application/vnd.frogans.fnc': ['fnc'],\n 'application/vnd.frogans.ltf': ['ltf'],\n 'application/vnd.fsc.weblaunch': ['fsc'],\n 'application/vnd.fujitsu.oasys': ['oas'],\n 'application/vnd.fujitsu.oasys2': ['oa2'],\n 'application/vnd.fujitsu.oasys3': ['oa3'],\n 'application/vnd.fujitsu.oasysgp': ['fg5'],\n 'application/vnd.fujitsu.oasysprs': ['bh2'],\n 'application/vnd.fujixerox.ddd': ['ddd'],\n 'application/vnd.fujixerox.docuworks': ['xdw'],\n 'application/vnd.fujixerox.docuworks.binder': ['xbd'],\n 'application/vnd.fuzzysheet': ['fzs'],\n 'application/vnd.genomatix.tuxedo': ['txd'],\n 'application/vnd.geogebra.file': ['ggb'],\n 'application/vnd.geogebra.slides': ['ggs'],\n 'application/vnd.geogebra.tool': ['ggt'],\n 'application/vnd.geometry-explorer': ['gex', 'gre'],\n 'application/vnd.geonext': ['gxt'],\n 'application/vnd.geoplan': ['g2w'],\n 'application/vnd.geospace': ['g3w'],\n 'application/vnd.gmx': ['gmx'],\n 'application/vnd.google-apps.document': ['gdoc'],\n 'application/vnd.google-apps.drawing': ['gdraw'],\n 'application/vnd.google-apps.form': ['gform'],\n 'application/vnd.google-apps.jam': ['gjam'],\n 'application/vnd.google-apps.map': ['gmap'],\n 'application/vnd.google-apps.presentation': ['gslides'],\n 'application/vnd.google-apps.script': ['gscript'],\n 'application/vnd.google-apps.site': ['gsite'],\n 'application/vnd.google-apps.spreadsheet': ['gsheet'],\n 'application/vnd.google-earth.kml+xml': ['kml'],\n 'application/vnd.google-earth.kmz': ['kmz'],\n 'application/vnd.gov.sk.xmldatacontainer+xml': ['xdcf'],\n 'application/vnd.grafeq': ['gqf', 'gqs'],\n 'application/vnd.groove-account': ['gac'],\n 'application/vnd.groove-help': ['ghf'],\n 'application/vnd.groove-identity-message': ['gim'],\n 'application/vnd.groove-injector': ['grv'],\n 'application/vnd.groove-tool-message': ['gtm'],\n 'application/vnd.groove-tool-template': ['tpl'],\n 'application/vnd.groove-vcard': ['vcg'],\n 'application/vnd.hal+xml': ['hal'],\n 'application/vnd.handheld-entertainment+xml': ['zmm'],\n 'application/vnd.hbci': ['hbci'],\n 'application/vnd.hhe.lesson-player': ['les'],\n 'application/vnd.hp-hpgl': ['hpgl'],\n 'application/vnd.hp-hpid': ['hpid'],\n 'application/vnd.hp-hps': ['hps'],\n 'application/vnd.hp-jlyt': ['jlt'],\n 'application/vnd.hp-pcl': ['pcl'],\n 'application/vnd.hp-pclxl': ['pclxl'],\n 'application/vnd.hydrostatix.sof-data': ['sfd-hdstx'],\n 'application/vnd.ibm.minipay': ['mpy'],\n 'application/vnd.ibm.modcap': ['afp', 'listafp', 'list3820'],\n 'application/vnd.ibm.rights-management': ['irm'],\n 'application/vnd.ibm.secure-container': ['sc'],\n 'application/vnd.iccprofile': ['icc', 'icm'],\n 'application/vnd.igloader': ['igl'],\n 'application/vnd.immervision-ivp': ['ivp'],\n 'application/vnd.immervision-ivu': ['ivu'],\n 'application/vnd.insors.igm': ['igm'],\n 'application/vnd.intercon.formnet': ['xpw', 'xpx'],\n 'application/vnd.intergeo': ['i2g'],\n 'application/vnd.intu.qbo': ['qbo'],\n 'application/vnd.intu.qfx': ['qfx'],\n 'application/vnd.ipunplugged.rcprofile': ['rcprofile'],\n 'application/vnd.irepository.package+xml': ['irp'],\n 'application/vnd.is-xpr': ['xpr'],\n 'application/vnd.isac.fcs': ['fcs'],\n 'application/vnd.jam': ['jam'],\n 'application/vnd.jcp.javame.midlet-rms': ['rms'],\n 'application/vnd.jisp': ['jisp'],\n 'application/vnd.joost.joda-archive': ['joda'],\n 'application/vnd.kahootz': ['ktz', 'ktr'],\n 'application/vnd.kde.karbon': ['karbon'],\n 'application/vnd.kde.kchart': ['chrt'],\n 'application/vnd.kde.kformula': ['kfo'],\n 'application/vnd.kde.kivio': ['flw'],\n 'application/vnd.kde.kontour': ['kon'],\n 'application/vnd.kde.kpresenter': ['kpr', 'kpt'],\n 'application/vnd.kde.kspread': ['ksp'],\n 'application/vnd.kde.kword': ['kwd', 'kwt'],\n 'application/vnd.kenameaapp': ['htke'],\n 'application/vnd.kidspiration': ['kia'],\n 'application/vnd.kinar': ['kne', 'knp'],\n 'application/vnd.koan': ['skp', 'skd', 'skt', 'skm'],\n 'application/vnd.kodak-descriptor': ['sse'],\n 'application/vnd.las.las+xml': ['lasxml'],\n 'application/vnd.llamagraphics.life-balance.desktop': ['lbd'],\n 'application/vnd.llamagraphics.life-balance.exchange+xml': ['lbe'],\n 'application/vnd.lotus-1-2-3': ['123'],\n 'application/vnd.lotus-approach': ['apr'],\n 'application/vnd.lotus-freelance': ['pre'],\n 'application/vnd.lotus-notes': ['nsf'],\n 'application/vnd.lotus-organizer': ['org'],\n 'application/vnd.lotus-screencam': ['scm'],\n 'application/vnd.lotus-wordpro': ['lwp'],\n 'application/vnd.macports.portpkg': ['portpkg'],\n 'application/vnd.mapbox-vector-tile': ['mvt'],\n 'application/vnd.mcd': ['mcd'],\n 'application/vnd.medcalcdata': ['mc1'],\n 'application/vnd.mediastation.cdkey': ['cdkey'],\n 'application/vnd.mfer': ['mwf'],\n 'application/vnd.mfmp': ['mfm'],\n 'application/vnd.micrografx.flo': ['flo'],\n 'application/vnd.micrografx.igx': ['igx'],\n 'application/vnd.mif': ['mif'],\n 'application/vnd.mobius.daf': ['daf'],\n 'application/vnd.mobius.dis': ['dis'],\n 'application/vnd.mobius.mbk': ['mbk'],\n 'application/vnd.mobius.mqy': ['mqy'],\n 'application/vnd.mobius.msl': ['msl'],\n 'application/vnd.mobius.plc': ['plc'],\n 'application/vnd.mobius.txf': ['txf'],\n 'application/vnd.mophun.application': ['mpn'],\n 'application/vnd.mophun.certificate': ['mpc'],\n 'application/vnd.mozilla.xul+xml': ['xul'],\n 'application/vnd.ms-artgalry': ['cil'],\n 'application/vnd.ms-cab-compressed': ['cab'],\n 'application/vnd.ms-excel': ['xls', 'xlm', 'xla', 'xlc', 'xlt', 'xlw'],\n 'application/vnd.ms-excel.addin.macroenabled.12': ['xlam'],\n 'application/vnd.ms-excel.sheet.binary.macroenabled.12': ['xlsb'],\n 'application/vnd.ms-excel.sheet.macroenabled.12': ['xlsm'],\n 'application/vnd.ms-excel.template.macroenabled.12': ['xltm'],\n 'application/vnd.ms-fontobject': ['eot'],\n 'application/vnd.ms-htmlhelp': ['chm'],\n 'application/vnd.ms-ims': ['ims'],\n 'application/vnd.ms-lrm': ['lrm'],\n 'application/vnd.ms-officetheme': ['thmx'],\n 'application/vnd.ms-outlook': ['msg'],\n 'application/vnd.ms-pki.seccat': ['cat'],\n 'application/vnd.ms-pki.stl': ['*stl'],\n 'application/vnd.ms-powerpoint': ['ppt', 'pps', 'pot'],\n 'application/vnd.ms-powerpoint.addin.macroenabled.12': ['ppam'],\n 'application/vnd.ms-powerpoint.presentation.macroenabled.12': ['pptm'],\n 'application/vnd.ms-powerpoint.slide.macroenabled.12': ['sldm'],\n 'application/vnd.ms-powerpoint.slideshow.macroenabled.12': ['ppsm'],\n 'application/vnd.ms-powerpoint.template.macroenabled.12': ['potm'],\n 'application/vnd.ms-project': ['*mpp', 'mpt'],\n 'application/vnd.ms-visio.viewer': ['vdx'],\n 'application/vnd.ms-word.document.macroenabled.12': ['docm'],\n 'application/vnd.ms-word.template.macroenabled.12': ['dotm'],\n 'application/vnd.ms-works': ['wps', 'wks', 'wcm', 'wdb'],\n 'application/vnd.ms-wpl': ['wpl'],\n 'application/vnd.ms-xpsdocument': ['xps'],\n 'application/vnd.mseq': ['mseq'],\n 'application/vnd.musician': ['mus'],\n 'application/vnd.muvee.style': ['msty'],\n 'application/vnd.mynfc': ['taglet'],\n 'application/vnd.nato.bindingdataobject+xml': ['bdo'],\n 'application/vnd.neurolanguage.nlu': ['nlu'],\n 'application/vnd.nitf': ['ntf', 'nitf'],\n 'application/vnd.noblenet-directory': ['nnd'],\n 'application/vnd.noblenet-sealer': ['nns'],\n 'application/vnd.noblenet-web': ['nnw'],\n 'application/vnd.nokia.n-gage.ac+xml': ['*ac'],\n 'application/vnd.nokia.n-gage.data': ['ngdat'],\n 'application/vnd.nokia.n-gage.symbian.install': ['n-gage'],\n 'application/vnd.nokia.radio-preset': ['rpst'],\n 'application/vnd.nokia.radio-presets': ['rpss'],\n 'application/vnd.novadigm.edm': ['edm'],\n 'application/vnd.novadigm.edx': ['edx'],\n 'application/vnd.novadigm.ext': ['ext'],\n 'application/vnd.oasis.opendocument.chart': ['odc'],\n 'application/vnd.oasis.opendocument.chart-template': ['otc'],\n 'application/vnd.oasis.opendocument.database': ['odb'],\n 'application/vnd.oasis.opendocument.formula': ['odf'],\n 'application/vnd.oasis.opendocument.formula-template': ['odft'],\n 'application/vnd.oasis.opendocument.graphics': ['odg'],\n 'application/vnd.oasis.opendocument.graphics-template': ['otg'],\n 'application/vnd.oasis.opendocument.image': ['odi'],\n 'application/vnd.oasis.opendocument.image-template': ['oti'],\n 'application/vnd.oasis.opendocument.presentation': ['odp'],\n 'application/vnd.oasis.opendocument.presentation-template': ['otp'],\n 'application/vnd.oasis.opendocument.spreadsheet': ['ods'],\n 'application/vnd.oasis.opendocument.spreadsheet-template': ['ots'],\n 'application/vnd.oasis.opendocument.text': ['odt'],\n 'application/vnd.oasis.opendocument.text-master': ['odm'],\n 'application/vnd.oasis.opendocument.text-template': ['ott'],\n 'application/vnd.oasis.opendocument.text-web': ['oth'],\n 'application/vnd.olpc-sugar': ['xo'],\n 'application/vnd.oma.dd2+xml': ['dd2'],\n 'application/vnd.openblox.game+xml': ['obgx'],\n 'application/vnd.openofficeorg.extension': ['oxt'],\n 'application/vnd.openstreetmap.data+xml': ['osm'],\n 'application/vnd.openxmlformats-officedocument.presentationml.presentation': [\n 'pptx',\n ],\n 'application/vnd.openxmlformats-officedocument.presentationml.slide': [\n 'sldx',\n ],\n 'application/vnd.openxmlformats-officedocument.presentationml.slideshow': [\n 'ppsx',\n ],\n 'application/vnd.openxmlformats-officedocument.presentationml.template': [\n 'potx',\n ],\n 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': ['xlsx'],\n 'application/vnd.openxmlformats-officedocument.spreadsheetml.template': [\n 'xltx',\n ],\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': [\n 'docx',\n ],\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.template': [\n 'dotx',\n ],\n 'application/vnd.osgeo.mapguide.package': ['mgp'],\n 'application/vnd.osgi.dp': ['dp'],\n 'application/vnd.osgi.subsystem': ['esa'],\n 'application/vnd.palm': ['pdb', 'pqa', 'oprc'],\n 'application/vnd.pawaafile': ['paw'],\n 'application/vnd.pg.format': ['str'],\n 'application/vnd.pg.osasli': ['ei6'],\n 'application/vnd.picsel': ['efif'],\n 'application/vnd.pmi.widget': ['wg'],\n 'application/vnd.pocketlearn': ['plf'],\n 'application/vnd.powerbuilder6': ['pbd'],\n 'application/vnd.previewsystems.box': ['box'],\n 'application/vnd.procrate.brushset': ['brushset'],\n 'application/vnd.procreate.brush': ['brush'],\n 'application/vnd.procreate.dream': ['drm'],\n 'application/vnd.proteus.magazine': ['mgz'],\n 'application/vnd.publishare-delta-tree': ['qps'],\n 'application/vnd.pvi.ptid1': ['ptid'],\n 'application/vnd.pwg-xhtml-print+xml': ['xhtm'],\n 'application/vnd.quark.quarkxpress': [\n 'qxd',\n 'qxt',\n 'qwd',\n 'qwt',\n 'qxl',\n 'qxb',\n ],\n 'application/vnd.rar': ['rar'],\n 'application/vnd.realvnc.bed': ['bed'],\n 'application/vnd.recordare.musicxml': ['mxl'],\n 'application/vnd.recordare.musicxml+xml': ['musicxml'],\n 'application/vnd.rig.cryptonote': ['cryptonote'],\n 'application/vnd.rim.cod': ['cod'],\n 'application/vnd.rn-realmedia': ['rm'],\n 'application/vnd.rn-realmedia-vbr': ['rmvb'],\n 'application/vnd.route66.link66+xml': ['link66'],\n 'application/vnd.sailingtracker.track': ['st'],\n 'application/vnd.seemail': ['see'],\n 'application/vnd.sema': ['sema'],\n 'application/vnd.semd': ['semd'],\n 'application/vnd.semf': ['semf'],\n 'application/vnd.shana.informed.formdata': ['ifm'],\n 'application/vnd.shana.informed.formtemplate': ['itp'],\n 'application/vnd.shana.informed.interchange': ['iif'],\n 'application/vnd.shana.informed.package': ['ipk'],\n 'application/vnd.simtech-mindmapper': ['twd', 'twds'],\n 'application/vnd.smaf': ['mmf'],\n 'application/vnd.smart.teacher': ['teacher'],\n 'application/vnd.software602.filler.form+xml': ['fo'],\n 'application/vnd.solent.sdkm+xml': ['sdkm', 'sdkd'],\n 'application/vnd.spotfire.dxp': ['dxp'],\n 'application/vnd.spotfire.sfs': ['sfs'],\n 'application/vnd.stardivision.calc': ['sdc'],\n 'application/vnd.stardivision.draw': ['sda'],\n 'application/vnd.stardivision.impress': ['sdd'],\n 'application/vnd.stardivision.math': ['smf'],\n 'application/vnd.stardivision.writer': ['sdw', 'vor'],\n 'application/vnd.stardivision.writer-global': ['sgl'],\n 'application/vnd.stepmania.package': ['smzip'],\n 'application/vnd.stepmania.stepchart': ['sm'],\n 'application/vnd.sun.wadl+xml': ['wadl'],\n 'application/vnd.sun.xml.calc': ['sxc'],\n 'application/vnd.sun.xml.calc.template': ['stc'],\n 'application/vnd.sun.xml.draw': ['sxd'],\n 'application/vnd.sun.xml.draw.template': ['std'],\n 'application/vnd.sun.xml.impress': ['sxi'],\n 'application/vnd.sun.xml.impress.template': ['sti'],\n 'application/vnd.sun.xml.math': ['sxm'],\n 'application/vnd.sun.xml.writer': ['sxw'],\n 'application/vnd.sun.xml.writer.global': ['sxg'],\n 'application/vnd.sun.xml.writer.template': ['stw'],\n 'application/vnd.sus-calendar': ['sus', 'susp'],\n 'application/vnd.svd': ['svd'],\n 'application/vnd.symbian.install': ['sis', 'sisx'],\n 'application/vnd.syncml+xml': ['xsm'],\n 'application/vnd.syncml.dm+wbxml': ['bdm'],\n 'application/vnd.syncml.dm+xml': ['xdm'],\n 'application/vnd.syncml.dmddf+xml': ['ddf'],\n 'application/vnd.tao.intent-module-archive': ['tao'],\n 'application/vnd.tcpdump.pcap': ['pcap', 'cap', 'dmp'],\n 'application/vnd.tmobile-livetv': ['tmo'],\n 'application/vnd.trid.tpt': ['tpt'],\n 'application/vnd.triscape.mxs': ['mxs'],\n 'application/vnd.trueapp': ['tra'],\n 'application/vnd.ufdl': ['ufd', 'ufdl'],\n 'application/vnd.uiq.theme': ['utz'],\n 'application/vnd.umajin': ['umj'],\n 'application/vnd.unity': ['unityweb'],\n 'application/vnd.uoml+xml': ['uoml', 'uo'],\n 'application/vnd.vcx': ['vcx'],\n 'application/vnd.visio': ['vsd', 'vst', 'vss', 'vsw', 'vsdx', 'vtx'],\n 'application/vnd.visionary': ['vis'],\n 'application/vnd.vsf': ['vsf'],\n 'application/vnd.wap.wbxml': ['wbxml'],\n 'application/vnd.wap.wmlc': ['wmlc'],\n 'application/vnd.wap.wmlscriptc': ['wmlsc'],\n 'application/vnd.webturbo': ['wtb'],\n 'application/vnd.wolfram.player': ['nbp'],\n 'application/vnd.wordperfect': ['wpd'],\n 'application/vnd.wqd': ['wqd'],\n 'application/vnd.wt.stf': ['stf'],\n 'application/vnd.xara': ['xar'],\n 'application/vnd.xfdl': ['xfdl'],\n 'application/vnd.yamaha.hv-dic': ['hvd'],\n 'application/vnd.yamaha.hv-script': ['hvs'],\n 'application/vnd.yamaha.hv-voice': ['hvp'],\n 'application/vnd.yamaha.openscoreformat': ['osf'],\n 'application/vnd.yamaha.openscoreformat.osfpvg+xml': ['osfpvg'],\n 'application/vnd.yamaha.smaf-audio': ['saf'],\n 'application/vnd.yamaha.smaf-phrase': ['spf'],\n 'application/vnd.yellowriver-custom-menu': ['cmp'],\n 'application/vnd.zul': ['zir', 'zirz'],\n 'application/vnd.zzazz.deck+xml': ['zaz'],\n 'application/x-7z-compressed': ['7z'],\n 'application/x-abiword': ['abw'],\n 'application/x-ace-compressed': ['ace'],\n 'application/x-apple-diskimage': ['*dmg'],\n 'application/x-arj': ['arj'],\n 'application/x-authorware-bin': ['aab', 'x32', 'u32', 'vox'],\n 'application/x-authorware-map': ['aam'],\n 'application/x-authorware-seg': ['aas'],\n 'application/x-bcpio': ['bcpio'],\n 'application/x-bdoc': ['*bdoc'],\n 'application/x-bittorrent': ['torrent'],\n 'application/x-blender': ['blend'],\n 'application/x-blorb': ['blb', 'blorb'],\n 'application/x-bzip': ['bz'],\n 'application/x-bzip2': ['bz2', 'boz'],\n 'application/x-cbr': ['cbr', 'cba', 'cbt', 'cbz', 'cb7'],\n 'application/x-cdlink': ['vcd'],\n 'application/x-cfs-compressed': ['cfs'],\n 'application/x-chat': ['chat'],\n 'application/x-chess-pgn': ['pgn'],\n 'application/x-chrome-extension': ['crx'],\n 'application/x-cocoa': ['cco'],\n 'application/x-compressed': ['*rar'],\n 'application/x-conference': ['nsc'],\n 'application/x-cpio': ['cpio'],\n 'application/x-csh': ['csh'],\n 'application/x-debian-package': ['*deb', 'udeb'],\n 'application/x-dgc-compressed': ['dgc'],\n 'application/x-director': [\n 'dir',\n 'dcr',\n 'dxr',\n 'cst',\n 'cct',\n 'cxt',\n 'w3d',\n 'fgd',\n 'swa',\n ],\n 'application/x-doom': ['wad'],\n 'application/x-dtbncx+xml': ['ncx'],\n 'application/x-dtbook+xml': ['dtb'],\n 'application/x-dtbresource+xml': ['res'],\n 'application/x-dvi': ['dvi'],\n 'application/x-envoy': ['evy'],\n 'application/x-eva': ['eva'],\n 'application/x-font-bdf': ['bdf'],\n 'application/x-font-ghostscript': ['gsf'],\n 'application/x-font-linux-psf': ['psf'],\n 'application/x-font-pcf': ['pcf'],\n 'application/x-font-snf': ['snf'],\n 'application/x-font-type1': ['pfa', 'pfb', 'pfm', 'afm'],\n 'application/x-freearc': ['arc'],\n 'application/x-futuresplash': ['spl'],\n 'application/x-gca-compressed': ['gca'],\n 'application/x-glulx': ['ulx'],\n 'application/x-gnumeric': ['gnumeric'],\n 'application/x-gramps-xml': ['gramps'],\n 'application/x-gtar': ['gtar'],\n 'application/x-hdf': ['hdf'],\n 'application/x-httpd-php': ['php'],\n 'application/x-install-instructions': ['install'],\n 'application/x-ipynb+json': ['ipynb'],\n 'application/x-iso9660-image': ['*iso'],\n 'application/x-iwork-keynote-sffkey': ['*key'],\n 'application/x-iwork-numbers-sffnumbers': ['*numbers'],\n 'application/x-iwork-pages-sffpages': ['*pages'],\n 'application/x-java-archive-diff': ['jardiff'],\n 'application/x-java-jnlp-file': ['jnlp'],\n 'application/x-keepass2': ['kdbx'],\n 'application/x-latex': ['latex'],\n 'application/x-lua-bytecode': ['luac'],\n 'application/x-lzh-compressed': ['lzh', 'lha'],\n 'application/x-makeself': ['run'],\n 'application/x-mie': ['mie'],\n 'application/x-mobipocket-ebook': ['*prc', 'mobi'],\n 'application/x-ms-application': ['application'],\n 'application/x-ms-shortcut': ['lnk'],\n 'application/x-ms-wmd': ['wmd'],\n 'application/x-ms-wmz': ['wmz'],\n 'application/x-ms-xbap': ['xbap'],\n 'application/x-msaccess': ['mdb'],\n 'application/x-msbinder': ['obd'],\n 'application/x-mscardfile': ['crd'],\n 'application/x-msclip': ['clp'],\n 'application/x-msdos-program': ['*exe'],\n 'application/x-msdownload': ['*exe', '*dll', 'com', 'bat', '*msi'],\n 'application/x-msmediaview': ['mvb', 'm13', 'm14'],\n 'application/x-msmetafile': ['*wmf', '*wmz', '*emf', 'emz'],\n 'application/x-msmoney': ['mny'],\n 'application/x-mspublisher': ['pub'],\n 'application/x-msschedule': ['scd'],\n 'application/x-msterminal': ['trm'],\n 'application/x-mswrite': ['wri'],\n 'application/x-netcdf': ['nc', 'cdf'],\n 'application/x-ns-proxy-autoconfig': ['pac'],\n 'application/x-nzb': ['nzb'],\n 'application/x-perl': ['pl', 'pm'],\n 'application/x-pilot': ['*prc', '*pdb'],\n 'application/x-pkcs12': ['p12', 'pfx'],\n 'application/x-pkcs7-certificates': ['p7b', 'spc'],\n 'application/x-pkcs7-certreqresp': ['p7r'],\n 'application/x-rar-compressed': ['*rar'],\n 'application/x-redhat-package-manager': ['rpm'],\n 'application/x-research-info-systems': ['ris'],\n 'application/x-sea': ['sea'],\n 'application/x-sh': ['sh'],\n 'application/x-shar': ['shar'],\n 'application/x-shockwave-flash': ['swf'],\n 'application/x-silverlight-app': ['xap'],\n 'application/x-sql': ['*sql'],\n 'application/x-stuffit': ['sit'],\n 'application/x-stuffitx': ['sitx'],\n 'application/x-subrip': ['srt'],\n 'application/x-sv4cpio': ['sv4cpio'],\n 'application/x-sv4crc': ['sv4crc'],\n 'application/x-t3vm-image': ['t3'],\n 'application/x-tads': ['gam'],\n 'application/x-tar': ['tar'],\n 'application/x-tcl': ['tcl', 'tk'],\n 'application/x-tex': ['tex'],\n 'application/x-tex-tfm': ['tfm'],\n 'application/x-texinfo': ['texinfo', 'texi'],\n 'application/x-tgif': ['*obj'],\n 'application/x-ustar': ['ustar'],\n 'application/x-virtualbox-hdd': ['hdd'],\n 'application/x-virtualbox-ova': ['ova'],\n 'application/x-virtualbox-ovf': ['ovf'],\n 'application/x-virtualbox-vbox': ['vbox'],\n 'application/x-virtualbox-vbox-extpack': ['vbox-extpack'],\n 'application/x-virtualbox-vdi': ['vdi'],\n 'application/x-virtualbox-vhd': ['vhd'],\n 'application/x-virtualbox-vmdk': ['vmdk'],\n 'application/x-wais-source': ['src'],\n 'application/x-web-app-manifest+json': ['webapp'],\n 'application/x-x509-ca-cert': ['der', 'crt', 'pem'],\n 'application/x-xfig': ['fig'],\n 'application/x-xliff+xml': ['*xlf'],\n 'application/x-xpinstall': ['xpi'],\n 'application/x-xz': ['xz'],\n 'application/x-zip-compressed': ['*zip'],\n 'application/x-zmachine': ['z1', 'z2', 'z3', 'z4', 'z5', 'z6', 'z7', 'z8'],\n 'audio/vnd.dece.audio': ['uva', 'uvva'],\n 'audio/vnd.digital-winds': ['eol'],\n 'audio/vnd.dra': ['dra'],\n 'audio/vnd.dts': ['dts'],\n 'audio/vnd.dts.hd': ['dtshd'],\n 'audio/vnd.lucent.voice': ['lvp'],\n 'audio/vnd.ms-playready.media.pya': ['pya'],\n 'audio/vnd.nuera.ecelp4800': ['ecelp4800'],\n 'audio/vnd.nuera.ecelp7470': ['ecelp7470'],\n 'audio/vnd.nuera.ecelp9600': ['ecelp9600'],\n 'audio/vnd.rip': ['rip'],\n 'audio/x-aac': ['*aac'],\n 'audio/x-aiff': ['aif', 'aiff', 'aifc'],\n 'audio/x-caf': ['caf'],\n 'audio/x-flac': ['flac'],\n 'audio/x-m4a': ['*m4a'],\n 'audio/x-matroska': ['mka'],\n 'audio/x-mpegurl': ['m3u'],\n 'audio/x-ms-wax': ['wax'],\n 'audio/x-ms-wma': ['wma'],\n 'audio/x-pn-realaudio': ['ram', 'ra'],\n 'audio/x-pn-realaudio-plugin': ['rmp'],\n 'audio/x-realaudio': ['*ra'],\n 'audio/x-wav': ['*wav'],\n 'chemical/x-cdx': ['cdx'],\n 'chemical/x-cif': ['cif'],\n 'chemical/x-cmdf': ['cmdf'],\n 'chemical/x-cml': ['cml'],\n 'chemical/x-csml': ['csml'],\n 'chemical/x-xyz': ['xyz'],\n 'image/prs.btif': ['btif', 'btf'],\n 'image/prs.pti': ['pti'],\n 'image/vnd.adobe.photoshop': ['psd'],\n 'image/vnd.airzip.accelerator.azv': ['azv'],\n 'image/vnd.blockfact.facti': ['facti'],\n 'image/vnd.dece.graphic': ['uvi', 'uvvi', 'uvg', 'uvvg'],\n 'image/vnd.djvu': ['djvu', 'djv'],\n 'image/vnd.dvb.subtitle': ['*sub'],\n 'image/vnd.dwg': ['dwg'],\n 'image/vnd.dxf': ['dxf'],\n 'image/vnd.fastbidsheet': ['fbs'],\n 'image/vnd.fpx': ['fpx'],\n 'image/vnd.fst': ['fst'],\n 'image/vnd.fujixerox.edmics-mmr': ['mmr'],\n 'image/vnd.fujixerox.edmics-rlc': ['rlc'],\n 'image/vnd.microsoft.icon': ['ico'],\n 'image/vnd.ms-dds': ['dds'],\n 'image/vnd.ms-modi': ['mdi'],\n 'image/vnd.ms-photo': ['wdp'],\n 'image/vnd.net-fpx': ['npx'],\n 'image/vnd.pco.b16': ['b16'],\n 'image/vnd.tencent.tap': ['tap'],\n 'image/vnd.valve.source.texture': ['vtf'],\n 'image/vnd.wap.wbmp': ['wbmp'],\n 'image/vnd.xiff': ['xif'],\n 'image/vnd.zbrush.pcx': ['pcx'],\n 'image/x-3ds': ['3ds'],\n 'image/x-adobe-dng': ['dng'],\n 'image/x-cmu-raster': ['ras'],\n 'image/x-cmx': ['cmx'],\n 'image/x-freehand': ['fh', 'fhc', 'fh4', 'fh5', 'fh7'],\n 'image/x-icon': ['*ico'],\n 'image/x-jng': ['jng'],\n 'image/x-mrsid-image': ['sid'],\n 'image/x-ms-bmp': ['*bmp'],\n 'image/x-pcx': ['*pcx'],\n 'image/x-pict': ['pic', 'pct'],\n 'image/x-portable-anymap': ['pnm'],\n 'image/x-portable-bitmap': ['pbm'],\n 'image/x-portable-graymap': ['pgm'],\n 'image/x-portable-pixmap': ['ppm'],\n 'image/x-rgb': ['rgb'],\n 'image/x-tga': ['tga'],\n 'image/x-xbitmap': ['xbm'],\n 'image/x-xpixmap': ['xpm'],\n 'image/x-xwindowdump': ['xwd'],\n 'message/vnd.wfa.wsc': ['wsc'],\n 'model/vnd.bary': ['bary'],\n 'model/vnd.cld': ['cld'],\n 'model/vnd.collada+xml': ['dae'],\n 'model/vnd.dwf': ['dwf'],\n 'model/vnd.gdl': ['gdl'],\n 'model/vnd.gtw': ['gtw'],\n 'model/vnd.mts': ['*mts'],\n 'model/vnd.opengex': ['ogex'],\n 'model/vnd.parasolid.transmit.binary': ['x_b'],\n 'model/vnd.parasolid.transmit.text': ['x_t'],\n 'model/vnd.pytha.pyox': ['pyo', 'pyox'],\n 'model/vnd.sap.vds': ['vds'],\n 'model/vnd.usda': ['usda'],\n 'model/vnd.usdz+zip': ['usdz'],\n 'model/vnd.valve.source.compiled-map': ['bsp'],\n 'model/vnd.vtu': ['vtu'],\n 'text/prs.lines.tag': ['dsc'],\n 'text/vnd.curl': ['curl'],\n 'text/vnd.curl.dcurl': ['dcurl'],\n 'text/vnd.curl.mcurl': ['mcurl'],\n 'text/vnd.curl.scurl': ['scurl'],\n 'text/vnd.dvb.subtitle': ['sub'],\n 'text/vnd.familysearch.gedcom': ['ged'],\n 'text/vnd.fly': ['fly'],\n 'text/vnd.fmi.flexstor': ['flx'],\n 'text/vnd.graphviz': ['gv'],\n 'text/vnd.in3d.3dml': ['3dml'],\n 'text/vnd.in3d.spot': ['spot'],\n 'text/vnd.sun.j2me.app-descriptor': ['jad'],\n 'text/vnd.wap.wml': ['wml'],\n 'text/vnd.wap.wmlscript': ['wmls'],\n 'text/x-asm': ['s', 'asm'],\n 'text/x-c': ['c', 'cc', 'cxx', 'cpp', 'h', 'hh', 'dic'],\n 'text/x-component': ['htc'],\n 'text/x-fortran': ['f', 'for', 'f77', 'f90'],\n 'text/x-handlebars-template': ['hbs'],\n 'text/x-java-source': ['java'],\n 'text/x-lua': ['lua'],\n 'text/x-markdown': ['mkd'],\n 'text/x-nfo': ['nfo'],\n 'text/x-opml': ['opml'],\n 'text/x-org': ['*org'],\n 'text/x-pascal': ['p', 'pas'],\n 'text/x-processing': ['pde'],\n 'text/x-sass': ['sass'],\n 'text/x-scss': ['scss'],\n 'text/x-setext': ['etx'],\n 'text/x-sfv': ['sfv'],\n 'text/x-suse-ymp': ['ymp'],\n 'text/x-uuencode': ['uu'],\n 'text/x-vcalendar': ['vcs'],\n 'text/x-vcard': ['vcf'],\n 'video/vnd.dece.hd': ['uvh', 'uvvh'],\n 'video/vnd.dece.mobile': ['uvm', 'uvvm'],\n 'video/vnd.dece.pd': ['uvp', 'uvvp'],\n 'video/vnd.dece.sd': ['uvs', 'uvvs'],\n 'video/vnd.dece.video': ['uvv', 'uvvv'],\n 'video/vnd.dvb.file': ['dvb'],\n 'video/vnd.fvt': ['fvt'],\n 'video/vnd.mpegurl': ['mxu', 'm4u'],\n 'video/vnd.ms-playready.media.pyv': ['pyv'],\n 'video/vnd.uvvu.mp4': ['uvu', 'uvvu'],\n 'video/vnd.vivo': ['viv'],\n 'video/x-f4v': ['f4v'],\n 'video/x-fli': ['fli'],\n 'video/x-flv': ['flv'],\n 'video/x-m4v': ['m4v'],\n 'video/x-matroska': ['mkv', 'mk3d', 'mks'],\n 'video/x-mng': ['mng'],\n 'video/x-ms-asf': ['asf', 'asx'],\n 'video/x-ms-vob': ['vob'],\n 'video/x-ms-wm': ['wm'],\n 'video/x-ms-wmv': ['wmv'],\n 'video/x-ms-wmx': ['wmx'],\n 'video/x-ms-wvx': ['wvx'],\n 'video/x-msvideo': ['avi'],\n 'video/x-sgi-movie': ['movie'],\n 'video/x-smv': ['smv'],\n 'x-conference/x-cooltalk': ['ice'],\n};\nObject.freeze(types);\nexport default types;\n","const types = {\n 'application/andrew-inset': ['ez'],\n 'application/appinstaller': ['appinstaller'],\n 'application/applixware': ['aw'],\n 'application/appx': ['appx'],\n 'application/appxbundle': ['appxbundle'],\n 'application/atom+xml': ['atom'],\n 'application/atomcat+xml': ['atomcat'],\n 'application/atomdeleted+xml': ['atomdeleted'],\n 'application/atomsvc+xml': ['atomsvc'],\n 'application/atsc-dwd+xml': ['dwd'],\n 'application/atsc-held+xml': ['held'],\n 'application/atsc-rsat+xml': ['rsat'],\n 'application/automationml-aml+xml': ['aml'],\n 'application/automationml-amlx+zip': ['amlx'],\n 'application/bdoc': ['bdoc'],\n 'application/calendar+xml': ['xcs'],\n 'application/ccxml+xml': ['ccxml'],\n 'application/cdfx+xml': ['cdfx'],\n 'application/cdmi-capability': ['cdmia'],\n 'application/cdmi-container': ['cdmic'],\n 'application/cdmi-domain': ['cdmid'],\n 'application/cdmi-object': ['cdmio'],\n 'application/cdmi-queue': ['cdmiq'],\n 'application/cpl+xml': ['cpl'],\n 'application/cu-seeme': ['cu'],\n 'application/cwl': ['cwl'],\n 'application/dash+xml': ['mpd'],\n 'application/dash-patch+xml': ['mpp'],\n 'application/davmount+xml': ['davmount'],\n 'application/dicom': ['dcm'],\n 'application/docbook+xml': ['dbk'],\n 'application/dssc+der': ['dssc'],\n 'application/dssc+xml': ['xdssc'],\n 'application/ecmascript': ['ecma'],\n 'application/emma+xml': ['emma'],\n 'application/emotionml+xml': ['emotionml'],\n 'application/epub+zip': ['epub'],\n 'application/exi': ['exi'],\n 'application/express': ['exp'],\n 'application/fdf': ['fdf'],\n 'application/fdt+xml': ['fdt'],\n 'application/font-tdpfr': ['pfr'],\n 'application/geo+json': ['geojson'],\n 'application/gml+xml': ['gml'],\n 'application/gpx+xml': ['gpx'],\n 'application/gxf': ['gxf'],\n 'application/gzip': ['gz'],\n 'application/hjson': ['hjson'],\n 'application/hyperstudio': ['stk'],\n 'application/inkml+xml': ['ink', 'inkml'],\n 'application/ipfix': ['ipfix'],\n 'application/its+xml': ['its'],\n 'application/java-archive': ['jar', 'war', 'ear'],\n 'application/java-serialized-object': ['ser'],\n 'application/java-vm': ['class'],\n 'application/javascript': ['*js'],\n 'application/json': ['json', 'map'],\n 'application/json5': ['json5'],\n 'application/jsonml+json': ['jsonml'],\n 'application/ld+json': ['jsonld'],\n 'application/lgr+xml': ['lgr'],\n 'application/lost+xml': ['lostxml'],\n 'application/mac-binhex40': ['hqx'],\n 'application/mac-compactpro': ['cpt'],\n 'application/mads+xml': ['mads'],\n 'application/manifest+json': ['webmanifest'],\n 'application/marc': ['mrc'],\n 'application/marcxml+xml': ['mrcx'],\n 'application/mathematica': ['ma', 'nb', 'mb'],\n 'application/mathml+xml': ['mathml'],\n 'application/mbox': ['mbox'],\n 'application/media-policy-dataset+xml': ['mpf'],\n 'application/mediaservercontrol+xml': ['mscml'],\n 'application/metalink+xml': ['metalink'],\n 'application/metalink4+xml': ['meta4'],\n 'application/mets+xml': ['mets'],\n 'application/mmt-aei+xml': ['maei'],\n 'application/mmt-usd+xml': ['musd'],\n 'application/mods+xml': ['mods'],\n 'application/mp21': ['m21', 'mp21'],\n 'application/mp4': ['*mp4', '*mpg4', 'mp4s', 'm4p'],\n 'application/msix': ['msix'],\n 'application/msixbundle': ['msixbundle'],\n 'application/msword': ['doc', 'dot'],\n 'application/mxf': ['mxf'],\n 'application/n-quads': ['nq'],\n 'application/n-triples': ['nt'],\n 'application/node': ['cjs'],\n 'application/octet-stream': [\n 'bin',\n 'dms',\n 'lrf',\n 'mar',\n 'so',\n 'dist',\n 'distz',\n 'pkg',\n 'bpk',\n 'dump',\n 'elc',\n 'deploy',\n 'exe',\n 'dll',\n 'deb',\n 'dmg',\n 'iso',\n 'img',\n 'msi',\n 'msp',\n 'msm',\n 'buffer',\n ],\n 'application/oda': ['oda'],\n 'application/oebps-package+xml': ['opf'],\n 'application/ogg': ['ogx'],\n 'application/omdoc+xml': ['omdoc'],\n 'application/onenote': [\n 'onetoc',\n 'onetoc2',\n 'onetmp',\n 'onepkg',\n 'one',\n 'onea',\n ],\n 'application/oxps': ['oxps'],\n 'application/p2p-overlay+xml': ['relo'],\n 'application/patch-ops-error+xml': ['xer'],\n 'application/pdf': ['pdf'],\n 'application/pgp-encrypted': ['pgp'],\n 'application/pgp-keys': ['asc'],\n 'application/pgp-signature': ['sig', '*asc'],\n 'application/pics-rules': ['prf'],\n 'application/pkcs10': ['p10'],\n 'application/pkcs7-mime': ['p7m', 'p7c'],\n 'application/pkcs7-signature': ['p7s'],\n 'application/pkcs8': ['p8'],\n 'application/pkix-attr-cert': ['ac'],\n 'application/pkix-cert': ['cer'],\n 'application/pkix-crl': ['crl'],\n 'application/pkix-pkipath': ['pkipath'],\n 'application/pkixcmp': ['pki'],\n 'application/pls+xml': ['pls'],\n 'application/postscript': ['ai', 'eps', 'ps'],\n 'application/provenance+xml': ['provx'],\n 'application/pskc+xml': ['pskcxml'],\n 'application/raml+yaml': ['raml'],\n 'application/rdf+xml': ['rdf', 'owl'],\n 'application/reginfo+xml': ['rif'],\n 'application/relax-ng-compact-syntax': ['rnc'],\n 'application/resource-lists+xml': ['rl'],\n 'application/resource-lists-diff+xml': ['rld'],\n 'application/rls-services+xml': ['rs'],\n 'application/route-apd+xml': ['rapd'],\n 'application/route-s-tsid+xml': ['sls'],\n 'application/route-usd+xml': ['rusd'],\n 'application/rpki-ghostbusters': ['gbr'],\n 'application/rpki-manifest': ['mft'],\n 'application/rpki-roa': ['roa'],\n 'application/rsd+xml': ['rsd'],\n 'application/rss+xml': ['rss'],\n 'application/rtf': ['rtf'],\n 'application/sbml+xml': ['sbml'],\n 'application/scvp-cv-request': ['scq'],\n 'application/scvp-cv-response': ['scs'],\n 'application/scvp-vp-request': ['spq'],\n 'application/scvp-vp-response': ['spp'],\n 'application/sdp': ['sdp'],\n 'application/senml+xml': ['senmlx'],\n 'application/sensml+xml': ['sensmlx'],\n 'application/set-payment-initiation': ['setpay'],\n 'application/set-registration-initiation': ['setreg'],\n 'application/shf+xml': ['shf'],\n 'application/sieve': ['siv', 'sieve'],\n 'application/smil+xml': ['smi', 'smil'],\n 'application/sparql-query': ['rq'],\n 'application/sparql-results+xml': ['srx'],\n 'application/sql': ['sql'],\n 'application/srgs': ['gram'],\n 'application/srgs+xml': ['grxml'],\n 'application/sru+xml': ['sru'],\n 'application/ssdl+xml': ['ssdl'],\n 'application/ssml+xml': ['ssml'],\n 'application/swid+xml': ['swidtag'],\n 'application/tei+xml': ['tei', 'teicorpus'],\n 'application/thraud+xml': ['tfi'],\n 'application/timestamped-data': ['tsd'],\n 'application/toml': ['toml'],\n 'application/trig': ['trig'],\n 'application/ttml+xml': ['ttml'],\n 'application/ubjson': ['ubj'],\n 'application/urc-ressheet+xml': ['rsheet'],\n 'application/urc-targetdesc+xml': ['td'],\n 'application/voicexml+xml': ['vxml'],\n 'application/wasm': ['wasm'],\n 'application/watcherinfo+xml': ['wif'],\n 'application/widget': ['wgt'],\n 'application/winhlp': ['hlp'],\n 'application/wsdl+xml': ['wsdl'],\n 'application/wspolicy+xml': ['wspolicy'],\n 'application/xaml+xml': ['xaml'],\n 'application/xcap-att+xml': ['xav'],\n 'application/xcap-caps+xml': ['xca'],\n 'application/xcap-diff+xml': ['xdf'],\n 'application/xcap-el+xml': ['xel'],\n 'application/xcap-ns+xml': ['xns'],\n 'application/xenc+xml': ['xenc'],\n 'application/xfdf': ['xfdf'],\n 'application/xhtml+xml': ['xhtml', 'xht'],\n 'application/xliff+xml': ['xlf'],\n 'application/xml': ['xml', 'xsl', 'xsd', 'rng'],\n 'application/xml-dtd': ['dtd'],\n 'application/xop+xml': ['xop'],\n 'application/xproc+xml': ['xpl'],\n 'application/xslt+xml': ['*xsl', 'xslt'],\n 'application/xspf+xml': ['xspf'],\n 'application/xv+xml': ['mxml', 'xhvml', 'xvml', 'xvm'],\n 'application/yang': ['yang'],\n 'application/yin+xml': ['yin'],\n 'application/zip': ['zip'],\n 'application/zip+dotlottie': ['lottie'],\n 'audio/3gpp': ['*3gpp'],\n 'audio/aac': ['adts', 'aac'],\n 'audio/adpcm': ['adp'],\n 'audio/amr': ['amr'],\n 'audio/basic': ['au', 'snd'],\n 'audio/midi': ['mid', 'midi', 'kar', 'rmi'],\n 'audio/mobile-xmf': ['mxmf'],\n 'audio/mp3': ['*mp3'],\n 'audio/mp4': ['m4a', 'mp4a', 'm4b'],\n 'audio/mpeg': ['mpga', 'mp2', 'mp2a', 'mp3', 'm2a', 'm3a'],\n 'audio/ogg': ['oga', 'ogg', 'spx', 'opus'],\n 'audio/s3m': ['s3m'],\n 'audio/silk': ['sil'],\n 'audio/wav': ['wav'],\n 'audio/wave': ['*wav'],\n 'audio/webm': ['weba'],\n 'audio/xm': ['xm'],\n 'font/collection': ['ttc'],\n 'font/otf': ['otf'],\n 'font/ttf': ['ttf'],\n 'font/woff': ['woff'],\n 'font/woff2': ['woff2'],\n 'image/aces': ['exr'],\n 'image/apng': ['apng'],\n 'image/avci': ['avci'],\n 'image/avcs': ['avcs'],\n 'image/avif': ['avif'],\n 'image/bmp': ['bmp', 'dib'],\n 'image/cgm': ['cgm'],\n 'image/dicom-rle': ['drle'],\n 'image/dpx': ['dpx'],\n 'image/emf': ['emf'],\n 'image/fits': ['fits'],\n 'image/g3fax': ['g3'],\n 'image/gif': ['gif'],\n 'image/heic': ['heic'],\n 'image/heic-sequence': ['heics'],\n 'image/heif': ['heif'],\n 'image/heif-sequence': ['heifs'],\n 'image/hej2k': ['hej2'],\n 'image/ief': ['ief'],\n 'image/jaii': ['jaii'],\n 'image/jais': ['jais'],\n 'image/jls': ['jls'],\n 'image/jp2': ['jp2', 'jpg2'],\n 'image/jpeg': ['jpg', 'jpeg', 'jpe'],\n 'image/jph': ['jph'],\n 'image/jphc': ['jhc'],\n 'image/jpm': ['jpm', 'jpgm'],\n 'image/jpx': ['jpx', 'jpf'],\n 'image/jxl': ['jxl'],\n 'image/jxr': ['jxr'],\n 'image/jxra': ['jxra'],\n 'image/jxrs': ['jxrs'],\n 'image/jxs': ['jxs'],\n 'image/jxsc': ['jxsc'],\n 'image/jxsi': ['jxsi'],\n 'image/jxss': ['jxss'],\n 'image/ktx': ['ktx'],\n 'image/ktx2': ['ktx2'],\n 'image/pjpeg': ['jfif'],\n 'image/png': ['png'],\n 'image/sgi': ['sgi'],\n 'image/svg+xml': ['svg', 'svgz'],\n 'image/t38': ['t38'],\n 'image/tiff': ['tif', 'tiff'],\n 'image/tiff-fx': ['tfx'],\n 'image/webp': ['webp'],\n 'image/wmf': ['wmf'],\n 'message/disposition-notification': ['disposition-notification'],\n 'message/global': ['u8msg'],\n 'message/global-delivery-status': ['u8dsn'],\n 'message/global-disposition-notification': ['u8mdn'],\n 'message/global-headers': ['u8hdr'],\n 'message/rfc822': ['eml', 'mime', 'mht', 'mhtml'],\n 'model/3mf': ['3mf'],\n 'model/gltf+json': ['gltf'],\n 'model/gltf-binary': ['glb'],\n 'model/iges': ['igs', 'iges'],\n 'model/jt': ['jt'],\n 'model/mesh': ['msh', 'mesh', 'silo'],\n 'model/mtl': ['mtl'],\n 'model/obj': ['obj'],\n 'model/prc': ['prc'],\n 'model/step': ['step', 'stp', 'stpnc', 'p21', '210'],\n 'model/step+xml': ['stpx'],\n 'model/step+zip': ['stpz'],\n 'model/step-xml+zip': ['stpxz'],\n 'model/stl': ['stl'],\n 'model/u3d': ['u3d'],\n 'model/vrml': ['wrl', 'vrml'],\n 'model/x3d+binary': ['*x3db', 'x3dbz'],\n 'model/x3d+fastinfoset': ['x3db'],\n 'model/x3d+vrml': ['*x3dv', 'x3dvz'],\n 'model/x3d+xml': ['x3d', 'x3dz'],\n 'model/x3d-vrml': ['x3dv'],\n 'text/cache-manifest': ['appcache', 'manifest'],\n 'text/calendar': ['ics', 'ifb'],\n 'text/coffeescript': ['coffee', 'litcoffee'],\n 'text/css': ['css'],\n 'text/csv': ['csv'],\n 'text/html': ['html', 'htm', 'shtml'],\n 'text/jade': ['jade'],\n 'text/javascript': ['js', 'mjs'],\n 'text/jsx': ['jsx'],\n 'text/less': ['less'],\n 'text/markdown': ['md', 'markdown'],\n 'text/mathml': ['mml'],\n 'text/mdx': ['mdx'],\n 'text/n3': ['n3'],\n 'text/plain': ['txt', 'text', 'conf', 'def', 'list', 'log', 'in', 'ini'],\n 'text/richtext': ['rtx'],\n 'text/rtf': ['*rtf'],\n 'text/sgml': ['sgml', 'sgm'],\n 'text/shex': ['shex'],\n 'text/slim': ['slim', 'slm'],\n 'text/spdx': ['spdx'],\n 'text/stylus': ['stylus', 'styl'],\n 'text/tab-separated-values': ['tsv'],\n 'text/troff': ['t', 'tr', 'roff', 'man', 'me', 'ms'],\n 'text/turtle': ['ttl'],\n 'text/uri-list': ['uri', 'uris', 'urls'],\n 'text/vcard': ['vcard'],\n 'text/vtt': ['vtt'],\n 'text/wgsl': ['wgsl'],\n 'text/xml': ['*xml'],\n 'text/yaml': ['yaml', 'yml'],\n 'video/3gpp': ['3gp', '3gpp'],\n 'video/3gpp2': ['3g2'],\n 'video/h261': ['h261'],\n 'video/h263': ['h263'],\n 'video/h264': ['h264'],\n 'video/iso.segment': ['m4s'],\n 'video/jpeg': ['jpgv'],\n 'video/jpm': ['*jpm', '*jpgm'],\n 'video/mj2': ['mj2', 'mjp2'],\n 'video/mp2t': ['ts', 'm2t', 'm2ts', 'mts'],\n 'video/mp4': ['mp4', 'mp4v', 'mpg4'],\n 'video/mpeg': ['mpeg', 'mpg', 'mpe', 'm1v', 'm2v'],\n 'video/ogg': ['ogv'],\n 'video/quicktime': ['qt', 'mov'],\n 'video/webm': ['webm'],\n};\nObject.freeze(types);\nexport default types;\n","var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _Mime_extensionToType, _Mime_typeToExtension, _Mime_typeToExtensions;\nclass Mime {\n constructor(...args) {\n _Mime_extensionToType.set(this, new Map());\n _Mime_typeToExtension.set(this, new Map());\n _Mime_typeToExtensions.set(this, new Map());\n for (const arg of args) {\n this.define(arg);\n }\n }\n define(typeMap, force = false) {\n for (let [type, extensions] of Object.entries(typeMap)) {\n type = type.toLowerCase();\n extensions = extensions.map((ext) => ext.toLowerCase());\n if (!__classPrivateFieldGet(this, _Mime_typeToExtensions, \"f\").has(type)) {\n __classPrivateFieldGet(this, _Mime_typeToExtensions, \"f\").set(type, new Set());\n }\n const allExtensions = __classPrivateFieldGet(this, _Mime_typeToExtensions, \"f\").get(type);\n let first = true;\n for (let extension of extensions) {\n const starred = extension.startsWith('*');\n extension = starred ? extension.slice(1) : extension;\n allExtensions?.add(extension);\n if (first) {\n __classPrivateFieldGet(this, _Mime_typeToExtension, \"f\").set(type, extension);\n }\n first = false;\n if (starred)\n continue;\n const currentType = __classPrivateFieldGet(this, _Mime_extensionToType, \"f\").get(extension);\n if (currentType && currentType != type && !force) {\n throw new Error(`\"${type} -> ${extension}\" conflicts with \"${currentType} -> ${extension}\". Pass \\`force=true\\` to override this definition.`);\n }\n __classPrivateFieldGet(this, _Mime_extensionToType, \"f\").set(extension, type);\n }\n }\n return this;\n }\n getType(path) {\n if (typeof path !== 'string')\n return null;\n const last = path.replace(/^.*[/\\\\]/s, '').toLowerCase();\n const ext = last.replace(/^.*\\./s, '').toLowerCase();\n const hasPath = last.length < path.length;\n const hasDot = ext.length < last.length - 1;\n if (!hasDot && hasPath)\n return null;\n return __classPrivateFieldGet(this, _Mime_extensionToType, \"f\").get(ext) ?? null;\n }\n getExtension(type) {\n if (typeof type !== 'string')\n return null;\n type = type?.split?.(';')[0];\n return ((type && __classPrivateFieldGet(this, _Mime_typeToExtension, \"f\").get(type.trim().toLowerCase())) ?? null);\n }\n getAllExtensions(type) {\n if (typeof type !== 'string')\n return null;\n return __classPrivateFieldGet(this, _Mime_typeToExtensions, \"f\").get(type.toLowerCase()) ?? null;\n }\n _freeze() {\n this.define = () => {\n throw new Error('define() not allowed for built-in Mime objects. See https://github.com/broofa/mime/blob/main/README.md#custom-mime-instances');\n };\n Object.freeze(this);\n for (const extensions of __classPrivateFieldGet(this, _Mime_typeToExtensions, \"f\").values()) {\n Object.freeze(extensions);\n }\n return this;\n }\n _getTestState() {\n return {\n types: __classPrivateFieldGet(this, _Mime_extensionToType, \"f\"),\n extensions: __classPrivateFieldGet(this, _Mime_typeToExtension, \"f\"),\n };\n }\n}\n_Mime_extensionToType = new WeakMap(), _Mime_typeToExtension = new WeakMap(), _Mime_typeToExtensions = new WeakMap();\nexport default Mime;\n","import otherTypes from '../types/other.js';\nimport standardTypes from '../types/standard.js';\nimport Mime from './Mime.js';\nexport { default as Mime } from './Mime.js';\nexport default new Mime(standardTypes, otherTypes)._freeze();\n","/**\n * Re-exports the `mime` package through the `@effect/platform-node/Mime`\n * module and the `Mime` namespace in the package barrel.\n *\n * @since 4.0.0\n */\n/* oxlint-disable no-named-as-default */\n/**\n * @since 4.0.0\n */\nimport Mime from \"mime\";\n/**\n * @category re-exports\n * @since 4.0.0\n */\nexport * from \"mime\";\n/**\n * @category re-exports\n * @since 4.0.0\n */\nexport default Mime;\n//# sourceMappingURL=Mime.js.map","/**\n * Models HTTP cookies and cookie collections for requests and responses.\n *\n * A `Cookie` stores a name, value, encoded value, and standard cookie\n * attributes. A `Cookies` value is an immutable collection keyed by cookie\n * name. This module parses request `Cookie` headers, builds response\n * `Set-Cookie` headers, and provides helpers for adding, removing, merging, and\n * expiring cookies.\n *\n * @since 4.0.0\n */\nimport * as Data from \"../../Data.js\";\nimport * as Duration from \"../../Duration.js\";\nimport { dual } from \"../../Function.js\";\nimport * as Inspectable from \"../../Inspectable.js\";\nimport * as Option from \"../../Option.js\";\nimport { pipeArguments } from \"../../Pipeable.js\";\nimport * as Predicate from \"../../Predicate.js\";\nimport * as Record from \"../../Record.js\";\nimport * as Result from \"../../Result.js\";\nimport * as Schema from \"../../Schema.js\";\nimport * as SchemaTransformation from \"../../SchemaTransformation.js\";\nconst TypeId = \"~effect/http/Cookies\";\n/**\n * Returns `true` when a value is a `Cookies` collection.\n *\n * @category refinements\n * @since 4.0.0\n */\nexport const isCookies = u => Predicate.hasProperty(u, TypeId);\n/**\n * Schema for `Cookies` collections.\n *\n * **Details**\n *\n * JSON encoding uses `Set-Cookie` header strings, while isomorphic encoding uses\n * a readonly record of cookie values.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const CookiesSchema = /*#__PURE__*/Schema.declare(isCookies, {\n typeConstructor: {\n _tag: \"effect/http/Cookies\"\n },\n generation: {\n runtime: `Cookies.CookiesSchema`,\n Type: `Cookies.Cookies`,\n Encoded: `typeof Cookies.CookiesSchema[\"Encoded\"]`,\n importDeclaration: `import * as Cookies from \"effect/unstable/http/Cookies\"`\n },\n expected: \"Cookies\",\n toCodecJson: () => Schema.link()(Schema.Array(Schema.String), SchemaTransformation.transform({\n decode: input => fromSetCookie(input),\n encode: cookies => toSetCookieHeaders(cookies)\n })),\n toCodecIso: () => Schema.link()(Schema.Record(Schema.String, CookieSchema), SchemaTransformation.transform({\n decode: input => fromReadonlyRecord(input),\n encode: cookies => cookies.cookies\n }))\n});\nconst CookieTypeId = \"~effect/http/Cookies/Cookie\";\n/**\n * Returns `true` when a value is a `Cookie`.\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isCookie = u => Predicate.hasProperty(u, CookieTypeId);\n/**\n * Schema for `Cookie` values.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const CookieSchema = /*#__PURE__*/Schema.declare(isCookie, {\n typeConstructor: {\n _tag: \"effect/http/Cookie\"\n },\n generation: {\n runtime: `Cookies.CookieSchema`,\n Type: `Cookies.Cookie`,\n importDeclaration: `import * as Cookie from \"effect/unstable/http/Cookies\"`\n },\n expected: \"Cookie\"\n});\nconst CookieErrorTypeId = \"~effect/http/Cookies/CookieError\";\n/**\n * Error reason describing why cookie construction failed, such as invalid name,\n * value, domain, path, or infinite max-age.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class CookiesErrorReason extends Data.Error {}\n/**\n * Error returned when a cookie name, value, domain, path, or max-age option is invalid.\n *\n * **Details**\n *\n * Inspect `reason` to determine the specific validation failure.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class CookiesError extends /*#__PURE__*/Data.TaggedError(\"CookieError\") {\n /**\n * Creates a cookie error from a reason tag and optional cause.\n *\n * @since 4.0.0\n */\n static fromReason(reason, cause) {\n return new CookiesError({\n reason: new CookiesErrorReason({\n _tag: reason,\n cause\n })\n });\n }\n /**\n * Marks this value as a cookie validation error for runtime guards.\n *\n * @since 4.0.0\n */\n [CookieErrorTypeId] = CookieErrorTypeId;\n /**\n * Uses the concrete cookie error reason as the public message.\n *\n * @since 4.0.0\n */\n get message() {\n return this.reason._tag;\n }\n}\nconst Proto = {\n [TypeId]: TypeId,\n ...Inspectable.BaseProto,\n toJSON() {\n return {\n _id: \"effect/Cookies\",\n cookies: Record.map(this.cookies, cookie => cookie.toJSON())\n };\n },\n pipe() {\n return pipeArguments(this, arguments);\n }\n};\n/**\n * Creates a `Cookies` collection from an existing readonly record of cookies keyed by cookie name.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromReadonlyRecord = cookies => {\n const self = Object.create(Proto);\n self.cookies = cookies;\n return self;\n};\n/**\n * Create a Cookies object from an Iterable\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromIterable = cookies => {\n const record = {};\n for (const cookie of cookies) {\n record[cookie.name] = cookie;\n }\n return fromReadonlyRecord(record);\n};\n/**\n * Create a Cookies object from a set of Set-Cookie headers\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromSetCookie = headers => {\n const arrayHeaders = typeof headers === \"string\" ? [headers] : headers;\n const cookies = [];\n for (const header of arrayHeaders) {\n const cookie = parseSetCookie(header.trim());\n if (cookie) {\n cookies.push(cookie);\n }\n }\n return fromIterable(cookies);\n};\nfunction parseSetCookie(header) {\n const parts = header.split(\";\").map(_ => _.trim()).filter(_ => _ !== \"\");\n if (parts.length === 0) {\n return undefined;\n }\n const firstEqual = parts[0].indexOf(\"=\");\n if (firstEqual === -1) {\n return undefined;\n }\n const name = parts[0].slice(0, firstEqual);\n if (!fieldContentRegExp.test(name)) {\n return undefined;\n }\n const valueEncoded = parts[0].slice(firstEqual + 1);\n const value = tryDecodeURIComponent(valueEncoded);\n if (parts.length === 1) {\n return Object.assign(Object.create(CookieProto), {\n name,\n value,\n valueEncoded\n });\n }\n const options = {};\n for (let i = 1; i < parts.length; i++) {\n const part = parts[i];\n const equalIndex = part.indexOf(\"=\");\n const key = equalIndex === -1 ? part : part.slice(0, equalIndex).trim();\n const value = equalIndex === -1 ? undefined : part.slice(equalIndex + 1).trim();\n switch (key.toLowerCase()) {\n case \"domain\":\n {\n if (value === undefined) {\n break;\n }\n const domain = value.trim().replace(/^\\./, \"\");\n if (domain) {\n options.domain = domain;\n }\n break;\n }\n case \"expires\":\n {\n if (value === undefined) {\n break;\n }\n const date = new Date(value);\n if (!isNaN(date.getTime())) {\n options.expires = date;\n }\n break;\n }\n case \"max-age\":\n {\n if (value === undefined) {\n break;\n }\n const maxAge = parseInt(value, 10);\n if (!isNaN(maxAge)) {\n options.maxAge = Duration.seconds(maxAge);\n }\n break;\n }\n case \"path\":\n {\n if (value === undefined) {\n break;\n }\n if (value[0] === \"/\") {\n options.path = value;\n }\n break;\n }\n case \"priority\":\n {\n if (value === undefined) {\n break;\n }\n switch (value.toLowerCase()) {\n case \"low\":\n options.priority = \"low\";\n break;\n case \"medium\":\n options.priority = \"medium\";\n break;\n case \"high\":\n options.priority = \"high\";\n break;\n }\n break;\n }\n case \"httponly\":\n {\n options.httpOnly = true;\n break;\n }\n case \"secure\":\n {\n options.secure = true;\n break;\n }\n case \"partitioned\":\n {\n options.partitioned = true;\n break;\n }\n case \"samesite\":\n {\n if (value === undefined) {\n break;\n }\n switch (value.toLowerCase()) {\n case \"lax\":\n options.sameSite = \"lax\";\n break;\n case \"strict\":\n options.sameSite = \"strict\";\n break;\n case \"none\":\n options.sameSite = \"none\";\n break;\n }\n break;\n }\n }\n }\n return Object.assign(Object.create(CookieProto), {\n name,\n value,\n valueEncoded,\n options: Object.keys(options).length > 0 ? options : undefined\n });\n}\n/**\n * An empty Cookies object\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const empty = /*#__PURE__*/fromIterable([]);\n/**\n * Returns `true` when the `Cookies` collection contains no cookies.\n *\n * @category refinements\n * @since 4.0.0\n */\nexport const isEmpty = self => Record.isEmptyRecord(self.cookies);\n// oxlint-disable-next-line no-control-regex\nconst fieldContentRegExp = /^[\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+$/;\nconst CookieProto = {\n [CookieTypeId]: CookieTypeId,\n ...Inspectable.BaseProto,\n toJSON() {\n return {\n _id: \"effect/Cookies/Cookie\",\n name: this.name,\n value: this.value,\n options: this.options\n };\n }\n};\n/**\n * Creates a cookie, validating the name, encoded value, domain, path, and finite `maxAge`.\n *\n * **Details**\n *\n * Returns a `CookiesError` in the `Result` failure channel when validation fails.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport function makeCookie(name, value, options) {\n if (!fieldContentRegExp.test(name)) {\n return Result.fail(CookiesError.fromReason(\"InvalidCookieName\"));\n }\n const encodedValue = encodeURIComponent(value);\n if (encodedValue && !fieldContentRegExp.test(encodedValue)) {\n return Result.fail(CookiesError.fromReason(\"InvalidCookieValue\"));\n }\n if (options !== undefined) {\n if (options.domain !== undefined && !fieldContentRegExp.test(options.domain)) {\n return Result.fail(CookiesError.fromReason(\"InvalidCookieDomain\"));\n }\n if (options.path !== undefined && !fieldContentRegExp.test(options.path)) {\n return Result.fail(CookiesError.fromReason(\"InvalidCookiePath\"));\n }\n if (options.maxAge !== undefined && !Duration.isFinite(Duration.fromInputUnsafe(options.maxAge))) {\n return Result.fail(CookiesError.fromReason(\"CookieInfinityMaxAge\"));\n }\n }\n return Result.succeed(Object.assign(Object.create(CookieProto), {\n name,\n value,\n valueEncoded: encodedValue,\n options\n }));\n}\n/**\n * Create a new cookie, throwing an error if invalid\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const makeCookieUnsafe = (name, value, options) => Result.getOrThrow(makeCookie(name, value, options));\n/**\n * Adds a cookie to a Cookies object\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const setCookie = /*#__PURE__*/dual(2, (self, cookie) => fromReadonlyRecord(Record.set(self.cookies, cookie.name, cookie)));\n/**\n * Adds multiple cookies to a Cookies object\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const setAllCookie = /*#__PURE__*/dual(2, (self, cookies) => {\n const record = {\n ...self.cookies\n };\n for (const cookie of cookies) {\n record[cookie.name] = cookie;\n }\n return fromReadonlyRecord(record);\n});\n/**\n * Combines two Cookies objects, removing duplicates from the first\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const merge = /*#__PURE__*/dual(2, (self, that) => fromReadonlyRecord({\n ...self.cookies,\n ...that.cookies\n}));\n/**\n * Removes a cookie by name\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const remove = /*#__PURE__*/dual(2, (self, name) => fromReadonlyRecord(Record.remove(self.cookies, name)));\n/**\n * Gets a cookie from a Cookies object safely.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const get = /*#__PURE__*/dual(args => isCookies(args[0]), (self, name) => Option.fromUndefinedOr(self.cookies[name]));\n/**\n * Gets the decoded value of a cookie by name safely.\n *\n * **Details**\n *\n * Returns `Option.none()` when the cookie is not present.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const getValue = /*#__PURE__*/dual(args => isCookies(args[0]), (self, name) => Option.map(get(self, name), cookie => cookie.value));\n/**\n * Creates and adds a cookie safely by name and value.\n *\n * **Details**\n *\n * The cookie fields are validated first; invalid input returns a `CookiesError` in the `Result` failure channel.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const set = /*#__PURE__*/dual(args => isCookies(args[0]), (self, name, value, options) => Result.map(makeCookie(name, value, options), cookie => fromReadonlyRecord(Record.set(self.cookies, name, cookie))));\n/**\n * Creates and adds a cookie by name and value, throwing if the cookie fields are invalid.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const setUnsafe = /*#__PURE__*/dual(args => isCookies(args[0]), (self, name, value, options) => fromReadonlyRecord(Record.set(self.cookies, name, makeCookieUnsafe(name, value, options))));\n/**\n * Adds an expired cookie safely with an empty value, `Max-Age=0`, and an epoch `Expires` value.\n *\n * **Details**\n *\n * Returns a `CookiesError` in the `Result` failure channel when the name or options are invalid.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const expireCookie = /*#__PURE__*/dual(args => isCookies(args[0]), (self, name, options) => set(self, name, \"\", {\n ...options,\n maxAge: 0,\n expires: new Date(0)\n}));\n/**\n * Adds an expired cookie to a Cookies object, throwing an error if invalid\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const expireCookieUnsafe = /*#__PURE__*/dual(args => isCookies(args[0]), (self, name, options) => setUnsafe(self, name, \"\", {\n ...options,\n maxAge: 0,\n expires: new Date(0)\n}));\n/**\n * Creates and adds multiple cookies safely from name/value/options tuples.\n *\n * **Details**\n *\n * If any tuple is invalid, returns the first `CookiesError` and leaves the original collection unchanged.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const setAll = /*#__PURE__*/dual(2, (self, cookies) => {\n const record = {\n ...self.cookies\n };\n for (const [name, value, options] of cookies) {\n const result = makeCookie(name, value, options);\n if (Result.isFailure(result)) {\n return result;\n }\n record[name] = result.success;\n }\n return Result.succeed(fromReadonlyRecord(record));\n});\n/**\n * Adds multiple cookies to a Cookies object, throwing an error if invalid\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const setAllUnsafe = /*#__PURE__*/dual(2, (self, cookies) => Result.getOrThrow(setAll(self, cookies)));\n/**\n * Serializes a cookie into a string.\n *\n * **Details**\n *\n * Adapted from https://github.com/fastify/fastify-cookie under MIT License\n *\n * @category encoding\n * @since 4.0.0\n */\nexport function serializeCookie(self) {\n let str = self.name + \"=\" + self.valueEncoded;\n if (self.options === undefined) {\n return str;\n }\n const options = self.options;\n if (options.maxAge !== undefined) {\n const maxAge = Duration.toSeconds(Duration.fromInputUnsafe(options.maxAge));\n str += \"; Max-Age=\" + Math.trunc(maxAge);\n }\n if (options.domain !== undefined) {\n str += \"; Domain=\" + options.domain;\n }\n if (options.path !== undefined) {\n str += \"; Path=\" + options.path;\n }\n if (options.priority !== undefined) {\n switch (options.priority) {\n case \"low\":\n str += \"; Priority=Low\";\n break;\n case \"medium\":\n str += \"; Priority=Medium\";\n break;\n case \"high\":\n str += \"; Priority=High\";\n break;\n }\n }\n if (options.expires !== undefined) {\n str += \"; Expires=\" + options.expires.toUTCString();\n }\n if (options.httpOnly) {\n str += \"; HttpOnly\";\n }\n if (options.secure) {\n str += \"; Secure\";\n }\n // Draft implementation to support Chrome from 2024-Q1 forward.\n // See https://datatracker.ietf.org/doc/html/draft-cutler-httpbis-partitioned-cookies#section-2.1\n if (options.partitioned) {\n str += \"; Partitioned\";\n }\n if (options.sameSite !== undefined) {\n switch (options.sameSite) {\n case \"lax\":\n str += \"; SameSite=Lax\";\n break;\n case \"strict\":\n str += \"; SameSite=Strict\";\n break;\n case \"none\":\n str += \"; SameSite=None\";\n break;\n }\n }\n return str;\n}\n/**\n * Serializes a `Cookies` object into a Cookie header.\n *\n * @category encoding\n * @since 4.0.0\n */\nexport const toCookieHeader = self => Object.values(self.cookies).map(cookie => `${cookie.name}=${cookie.valueEncoded}`).join(\"; \");\n/**\n * Converts a `Cookies` collection to a record of decoded cookie values keyed by cookie name.\n *\n * @category encoding\n * @since 4.0.0\n */\nexport const toRecord = self => {\n const record = {};\n const cookies = Object.values(self.cookies);\n for (let index = 0; index < cookies.length; index++) {\n const cookie = cookies[index];\n record[cookie.name] = cookie.value;\n }\n return record;\n};\n/**\n * Schema for transforming `Cookies` into records of decoded string values keyed\n * by cookie name.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const schemaRecord = /*#__PURE__*/CookiesSchema.pipe(/*#__PURE__*/Schema.decodeTo(/*#__PURE__*/Schema.Record(Schema.String, Schema.String), /*#__PURE__*/SchemaTransformation.transform({\n decode: toRecord,\n encode: self => fromIterable(Object.entries(self).map(([name, value]) => makeCookieUnsafe(name, value)))\n})));\n/**\n * Serializes a `Cookies` collection into an array of `Set-Cookie` header values.\n *\n * @category encoding\n * @since 4.0.0\n */\nexport const toSetCookieHeaders = self => Object.values(self.cookies).map(serializeCookie);\n/**\n * Parses a cookie header into a record of key-value pairs\n *\n * **Details**\n *\n * Adapted from https://github.com/fastify/fastify-cookie under MIT License\n *\n * @category decoding\n * @since 4.0.0\n */\nexport function parseHeader(header) {\n const result = {};\n const strLen = header.length;\n let pos = 0;\n let terminatorPos = 0;\n while (true) {\n if (terminatorPos === strLen) break;\n terminatorPos = header.indexOf(\";\", pos);\n if (terminatorPos === -1) terminatorPos = strLen; // This is the last pair\n let eqIdx = header.indexOf(\"=\", pos);\n if (eqIdx === -1) break; // No key-value pairs left\n if (eqIdx > terminatorPos) {\n // Malformed key-value pair\n pos = terminatorPos + 1;\n continue;\n }\n const key = header.substring(pos, eqIdx++).trim();\n if (result[key] === undefined) {\n const val = header.charCodeAt(eqIdx) === 0x22 ? header.substring(eqIdx + 1, terminatorPos - 1).trim() : header.substring(eqIdx, terminatorPos).trim();\n result[key] = !(val.indexOf(\"%\") === -1) ? tryDecodeURIComponent(val) : val;\n }\n pos = terminatorPos + 1;\n }\n return result;\n}\nconst tryDecodeURIComponent = str => {\n try {\n return decodeURIComponent(str);\n // oxlint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (_) {\n return str;\n }\n};\n//# sourceMappingURL=Cookies.js.map","/**\n * Models HTTP headers for the unstable HTTP client and server modules.\n *\n * `Headers` values are immutable maps keyed by lowercase header name. This\n * module converts common header inputs into that shape, provides helpers for\n * reading and updating header values, and redacts configured sensitive headers\n * when values are inspected.\n *\n * @since 4.0.0\n */\nimport * as Context from \"../../Context.js\";\nimport * as Equal from \"../../Equal.js\";\nimport * as Equ from \"../../Equivalence.js\";\nimport { dual } from \"../../Function.js\";\nimport * as Hash from \"../../Hash.js\";\nimport * as Inspectable from \"../../Inspectable.js\";\nimport * as Option from \"../../Option.js\";\nimport * as Predicate from \"../../Predicate.js\";\nimport * as Record from \"../../Record.js\";\nimport * as Redactable from \"../../Redactable.js\";\nimport * as Redacted from \"../../Redacted.js\";\nimport * as Schema from \"../../Schema.js\";\nimport * as SchemaTransformation from \"../../SchemaTransformation.js\";\n/**\n * Runtime type identifier for `Headers` values.\n *\n * @category type IDs\n * @since 4.0.0\n */\nexport const TypeId = /*#__PURE__*/Symbol.for(\"~effect/http/Headers\");\n/**\n * Returns `true` if the provided value is a `Headers` value.\n *\n * @category refinements\n * @since 4.0.0\n */\nexport const isHeaders = u => Predicate.hasProperty(u, TypeId);\n// the properties are folded into the initializer (rather than a separate\n// `Object.defineProperties(Proto, ...)` statement) so the whole definition\n// is pure-annotated by the build and tree-shakable.\nconst Proto = /*#__PURE__*/Object.defineProperties(/*#__PURE__*/Object.create(null), {\n [TypeId]: {\n value: TypeId\n },\n [Redactable.symbolRedactable]: {\n value(context) {\n return redact(this, Context.get(context, CurrentRedactedNames));\n }\n },\n toJSON: {\n value() {\n return Redactable.redact(this);\n }\n },\n [Equal.symbol]: {\n value(that) {\n return Equivalence(this, that);\n }\n },\n [Hash.symbol]: {\n value() {\n return Hash.structure(this);\n }\n },\n toString: {\n value: Inspectable.BaseProto.toString\n },\n [Inspectable.NodeInspectSymbol]: {\n value: Inspectable.BaseProto[Inspectable.NodeInspectSymbol]\n }\n});\nconst make = input => Object.assign(Object.create(Proto), input);\n/**\n * Provides an `Equivalence` instance that compares `Headers` by header names\n * and string values.\n *\n * @category instances\n * @since 4.0.0\n */\nexport const Equivalence = /*#__PURE__*/Record.makeEquivalence(/*#__PURE__*/Equ.strictEqual());\n/**\n * Schema for `Headers` values encoded as records of string header values.\n *\n * **Details**\n *\n * Decoding normalizes header names through `fromInput`; encoding returns a plain record.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const HeadersSchema = /*#__PURE__*/Schema.declare(isHeaders, {\n typeConstructor: {\n _tag: \"effect/http/Headers\"\n },\n generation: {\n runtime: `Headers.HeadersSchema`,\n Type: `Headers.Headers`,\n Encoded: `typeof Headers.HeadersSchema[\"Encoded\"]`,\n importDeclaration: `import * as Headers from \"effect/unstable/http/Headers\"`\n },\n expected: \"Headers\",\n toEquivalence: () => Equivalence,\n toCodec: () => Schema.link()(Schema.Record(Schema.String, Schema.String), SchemaTransformation.transform({\n decode: input => fromInput(input),\n encode: headers => ({\n ...headers\n })\n }))\n});\n/**\n * An empty `Headers` collection.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const empty = /*#__PURE__*/Object.create(Proto);\n/**\n * Creates `Headers` from a record or iterable of header entries.\n *\n * **Details**\n *\n * Header names are normalized to lowercase. Array values in record input are joined with `\", \"`, and `undefined` values are omitted.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromInput = input => {\n if (input === undefined) {\n return empty;\n } else if (Symbol.iterator in input) {\n const out = Object.create(Proto);\n for (const [k, v] of input) {\n out[k.toLowerCase()] = v;\n }\n return out;\n }\n const out = Object.create(Proto);\n for (const [k, v] of Object.entries(input)) {\n if (Array.isArray(v)) {\n out[k.toLowerCase()] = v.join(\", \");\n } else if (v !== undefined) {\n out[k.toLowerCase()] = v;\n }\n }\n return out;\n};\n/**\n * Treats an existing record as `Headers` unsafely.\n *\n * **Gotchas**\n *\n * This mutates the record's prototype and does not normalize header names; callers must provide the expected lowercase keys.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromRecordUnsafe = input => Object.setPrototypeOf(input, Proto);\n/**\n * Returns `true` when a header with the given name is present.\n *\n * **Details**\n *\n * The lookup lowercases the provided header name.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const has = /*#__PURE__*/dual(2, (self, key) => key.toLowerCase() in self);\n/**\n * Gets a header value by name safely.\n *\n * **Details**\n *\n * The lookup lowercases the provided header name and returns `Option.none()` when absent.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const get = /*#__PURE__*/dual(2, (self, key) => Option.fromUndefinedOr(self[key.toLowerCase()]));\n/**\n * Returns a new `Headers` collection with the given header set.\n *\n * **Details**\n *\n * The header name is normalized to lowercase.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const set = /*#__PURE__*/dual(3, (self, key, value) => {\n const out = make(self);\n out[key.toLowerCase()] = value;\n return out;\n});\n/**\n * Returns a new `Headers` collection with all provided headers set.\n *\n * **Details**\n *\n * Input headers are normalized with `fromInput` and override existing headers with the same lowercase name.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const setAll = /*#__PURE__*/dual(2, (self, headers) => make({\n ...self,\n ...fromInput(headers)\n}));\n/**\n * Returns a new `Headers` collection containing headers from both collections.\n *\n * **Details**\n *\n * Headers from the second collection override headers from the first collection with the same name.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const merge = /*#__PURE__*/dual(2, (self, headers) => {\n const out = make(self);\n Object.assign(out, headers);\n return out;\n});\n/**\n * Returns a new `Headers` collection with the named header removed.\n *\n * **Details**\n *\n * The provided header name is normalized to lowercase before removal.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const remove = /*#__PURE__*/dual(2, (self, key) => {\n const out = make(self);\n delete out[key.toLowerCase()];\n return out;\n});\n/**\n * Returns a new `Headers` collection with each named header removed.\n *\n * **Details**\n *\n * Each provided header name is normalized to lowercase before removal.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const removeMany = /*#__PURE__*/dual(2, (self, keys) => {\n const out = make(self);\n for (const key of keys) {\n delete out[key.toLowerCase()];\n }\n return out;\n});\n/**\n * Returns a plain record with selected header values wrapped in `Redacted`.\n *\n * **Details**\n *\n * String keys are normalized to lowercase before matching; regular expressions are tested against the stored header names.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const redact = /*#__PURE__*/dual(2, (self, key) => {\n const out = {\n ...self\n };\n const modify = key => {\n if (typeof key === \"string\") {\n const k = key.toLowerCase();\n if (k in self) {\n out[k] = Redacted.make(self[k]);\n }\n } else {\n for (const name in self) {\n if (key.test(name)) {\n out[name] = Redacted.make(self[name]);\n }\n }\n }\n };\n if (Array.isArray(key)) {\n for (let i = 0; i < key.length; i++) {\n modify(key[i]);\n }\n } else {\n modify(key);\n }\n return out;\n});\n/**\n * Context reference listing header names or patterns that should be redacted when `Headers` are inspected or rendered.\n *\n * **Details**\n *\n * Defaults include `authorization`, `cookie`, `set-cookie`, and `x-api-key`.\n *\n * @category fiber refs\n * @since 4.0.0\n */\nexport const CurrentRedactedNames = /*#__PURE__*/Context.Reference(\"effect/Headers/CurrentRedactedNames\", {\n defaultValue: () => [\"authorization\", \"cookie\", \"set-cookie\", \"x-api-key\"]\n});\n//# sourceMappingURL=Headers.js.map","/**\n * Typed failure model for Effect HTTP client operations.\n *\n * HTTP clients wrap request construction, transport, status-code validation, and\n * response decoding failures in `HttpClientError`. The wrapper keeps the failed\n * request and the specific failure reason together, so callers can handle client\n * failures uniformly while still matching on the reason `_tag` for retry\n * policy, logging, metrics, and user-facing messages.\n *\n * @since 4.0.0\n */\nimport * as Data from \"../../Data.js\";\nimport { hasProperty } from \"../../Predicate.js\";\nimport * as Schema from \"../../Schema.js\";\nconst TypeId = \"~effect/http/HttpClientError\";\n/**\n * Returns `true` when a value is an `HttpClientError`.\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isHttpClientError = u => hasProperty(u, TypeId);\n/**\n * Error wrapper for HTTP client failures, exposing the failed request and the optional response through its `reason`.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class HttpClientError extends /*#__PURE__*/Data.TaggedError(\"HttpClientError\") {\n constructor(props) {\n if (\"cause\" in props.reason) {\n super({\n ...props,\n cause: props.reason.cause\n });\n } else {\n super(props);\n }\n }\n /**\n * Marks this value as an HTTP client error for runtime guards.\n *\n * @since 4.0.0\n */\n [TypeId] = TypeId;\n /**\n * HTTP request associated with the client failure.\n *\n * @since 4.0.0\n */\n get request() {\n return this.reason.request;\n }\n /**\n * HTTP response associated with the client failure, when one was received.\n *\n * @since 4.0.0\n */\n get response() {\n return \"response\" in this.reason ? this.reason.response : undefined;\n }\n get message() {\n return this.reason.message;\n }\n}\nconst formatReason = tag => tag.endsWith(\"Error\") ? tag.slice(0, -5) : tag;\nconst formatMessage = (reason, description, info) => description ? `${reason}: ${description} (${info})` : `${reason} error (${info})`;\n/**\n * Error describing transport-level failures that occur while sending an HTTP request.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class TransportError extends /*#__PURE__*/Data.TaggedError(\"TransportError\") {\n /**\n * Formats the request method and URL for transport error messages.\n *\n * @since 4.0.0\n */\n get methodAndUrl() {\n return `${this.request.method} ${this.request.url}`;\n }\n /**\n * Builds the transport error message from the optional description and request details.\n *\n * @since 4.0.0\n */\n get message() {\n return formatMessage(formatReason(this._tag), this.description, this.methodAndUrl);\n }\n}\n/**\n * Error describing failures while encoding an HTTP request body.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class EncodeError extends /*#__PURE__*/Data.TaggedError(\"EncodeError\") {\n /**\n * Formats the request method and URL for request encoding error messages.\n *\n * @since 4.0.0\n */\n get methodAndUrl() {\n return `${this.request.method} ${this.request.url}`;\n }\n /**\n * Builds the request encoding error message from the optional description and request details.\n *\n * @since 4.0.0\n */\n get message() {\n return formatMessage(formatReason(this._tag), this.description, this.methodAndUrl);\n }\n}\n/**\n * Error describing failures while constructing a URL from an HTTP client request.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class InvalidUrlError extends /*#__PURE__*/Data.TaggedError(\"InvalidUrlError\") {\n /**\n * Formats the request method and URL for invalid URL error messages.\n *\n * @since 4.0.0\n */\n get methodAndUrl() {\n return `${this.request.method} ${this.request.url}`;\n }\n /**\n * Builds the invalid URL error message from the optional description and request details.\n *\n * @since 4.0.0\n */\n get message() {\n return formatMessage(formatReason(this._tag), this.description, this.methodAndUrl);\n }\n}\n/**\n * Response error for HTTP responses rejected because of their status code.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class StatusCodeError extends /*#__PURE__*/Data.TaggedError(\"StatusCodeError\") {\n /**\n * Formats the request method and URL for status code error messages.\n *\n * @since 4.0.0\n */\n get methodAndUrl() {\n return `${this.request.method} ${this.request.url}`;\n }\n /**\n * Builds the status code error message from the response status, optional description, and request details.\n *\n * @since 4.0.0\n */\n get message() {\n const info = `${this.response.status} ${this.methodAndUrl}`;\n return formatMessage(formatReason(this._tag), this.description, info);\n }\n}\n/**\n * Response error for failures while decoding an HTTP response body.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class DecodeError extends /*#__PURE__*/Data.TaggedError(\"DecodeError\") {\n /**\n * Formats the request method and URL for response decoding error messages.\n *\n * @since 4.0.0\n */\n get methodAndUrl() {\n return `${this.request.method} ${this.request.url}`;\n }\n /**\n * Builds the response decoding error message from the response status, optional description, and request details.\n *\n * @since 4.0.0\n */\n get message() {\n const info = `${this.response.status} ${this.methodAndUrl}`;\n return formatMessage(formatReason(this._tag), this.description, info);\n }\n}\n/**\n * Response error for operations that expected a response body but received an empty body.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class EmptyBodyError extends /*#__PURE__*/Data.TaggedError(\"EmptyBodyError\") {\n /**\n * Formats the request method and URL for empty response body error messages.\n *\n * @since 4.0.0\n */\n get methodAndUrl() {\n return `${this.request.method} ${this.request.url}`;\n }\n /**\n * Builds the empty body error message from the response status, optional description, and request details.\n *\n * @since 4.0.0\n */\n get message() {\n const info = `${this.response.status} ${this.methodAndUrl}`;\n return formatMessage(formatReason(this._tag), this.description, info);\n }\n}\n/**\n * Schema for serializable HTTP client errors, preserving the specific error kind\n * and cause.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport class HttpClientErrorSchema extends /*#__PURE__*/Schema.ErrorClass(TypeId)({\n _tag: /*#__PURE__*/Schema.tag(\"HttpError\"),\n kind: /*#__PURE__*/Schema.Literals([\"EncodeError\", \"DecodeError\", \"TransportError\", \"InvalidUrlError\", \"StatusCodeError\", \"EmptyBodyError\"]),\n cause: /*#__PURE__*/Schema.optional(/*#__PURE__*/Schema.Defect())\n}) {\n /**\n * Builds the serializable schema representation for an HTTP client error.\n *\n * @since 4.0.0\n */\n static fromHttpClientError(error) {\n return new HttpClientErrorSchema({\n _tag: \"HttpError\",\n kind: error.reason._tag,\n cause: error.reason\n });\n }\n}\n//# sourceMappingURL=HttpClientError.js.map","/**\n * Models URL query parameters as ordered string pairs.\n *\n * `UrlParams` is used for HTTP client query strings, URL-encoded form bodies,\n * and server-side decoding. Values can be built from records, iterables, or\n * native `URLSearchParams`, then updated, serialized, converted to a `URL`, or\n * decoded with schemas.\n *\n * @since 4.0.0\n */\nimport * as Arr from \"../../Array.js\";\nimport * as Effect from \"../../Effect.js\";\nimport * as Equal from \"../../Equal.js\";\nimport * as Equ from \"../../Equivalence.js\";\nimport { dual } from \"../../Function.js\";\nimport * as Hash from \"../../Hash.js\";\nimport { PipeInspectableProto } from \"../../internal/core.js\";\nimport * as Option from \"../../Option.js\";\nimport { hasProperty } from \"../../Predicate.js\";\nimport * as Schema from \"../../Schema.js\";\nimport * as SchemaIssue from \"../../SchemaIssue.js\";\nimport * as SchemaTransformation from \"../../SchemaTransformation.js\";\nimport * as Tuple from \"../../Tuple.js\";\nconst TypeId = \"~effect/http/UrlParams\";\n/**\n * Returns `true` when a value is a `UrlParams` instance.\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isUrlParams = u => hasProperty(u, TypeId);\nconst Proto = {\n ...PipeInspectableProto,\n [TypeId]: TypeId,\n [Symbol.iterator]() {\n return this.params[Symbol.iterator]();\n },\n toJSON() {\n return {\n _id: \"UrlParams\",\n params: Object.fromEntries(this.params)\n };\n },\n [Equal.symbol](that) {\n return Equivalence(this, that);\n },\n [Hash.symbol]() {\n return Hash.array(this.params.flat());\n }\n};\n/**\n * Creates `UrlParams` from ordered string key-value pairs.\n *\n * **Details**\n *\n * The input pairs are used as-is and are not coerced or normalized.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = params => {\n const self = Object.create(Proto);\n self.params = params;\n return self;\n};\n/**\n * Creates `UrlParams` from a supported input shape.\n *\n * **Details**\n *\n * Primitive values are converted to strings, arrays produce repeated parameters,\n * nested records use bracket notation, and `undefined` values are omitted.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromInput = input => {\n if (isUrlParams(input)) {\n return input;\n }\n const parsed = fromInputNested(input);\n const out = [];\n for (let i = 0; i < parsed.length; i++) {\n if (Array.isArray(parsed[i][0])) {\n const [keys, value] = parsed[i];\n out.push([`${keys[0]}[${keys.slice(1).join(\"][\")}]`, value]);\n } else {\n out.push(parsed[i]);\n }\n }\n return make(out);\n};\nconst fromInputNested = input => {\n const entries = typeof input[Symbol.iterator] === \"function\" ? Arr.fromIterable(input) : Object.entries(input);\n const out = [];\n for (const [key, value] of entries) {\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) {\n if (value[i] !== undefined) {\n out.push([key, String(value[i])]);\n }\n }\n } else if (typeof value === \"object\") {\n const nested = fromInputNested(value);\n for (const [k, v] of nested) {\n out.push([[key, ...(typeof k === \"string\" ? [k] : k)], v]);\n }\n } else if (value !== undefined) {\n out.push([key, String(value)]);\n }\n }\n return out;\n};\n/**\n * Provides an order-sensitive `Equivalence` instance for `UrlParams`.\n *\n * **Details**\n *\n * Two values are equivalent when they contain the same key-value pairs in the same\n * order.\n *\n * @category instances\n * @since 4.0.0\n */\nexport const Equivalence = /*#__PURE__*/Equ.make((a, b) => arrayEquivalence(a.params, b.params));\nconst arrayEquivalence = /*#__PURE__*/Arr.makeEquivalence(/*#__PURE__*/Tuple.makeEquivalence([/*#__PURE__*/Equ.strictEqual(), /*#__PURE__*/Equ.strictEqual()]));\n/**\n * Schema for `UrlParams`.\n *\n * **Details**\n *\n * The encoded representation is an array of string key-value tuples.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const UrlParamsSchema = /*#__PURE__*/Schema.declare(isUrlParams, {\n typeConstructor: {\n _tag: \"effect/http/UrlParams\"\n },\n generation: {\n runtime: `UrlParams.UrlParamsSchema`,\n Type: `UrlParams.UrlParams`,\n Encoded: `typeof UrlParams.UrlParamsSchema[\"Encoded\"]`,\n importDeclaration: `import * as UrlParams from \"effect/unstable/http/UrlParams\"`\n },\n expected: \"UrlParams\",\n toEquivalence: () => Equivalence,\n toCodec: () => Schema.link()(Schema.Array(Schema.Tuple([Schema.String, Schema.String])), SchemaTransformation.transform({\n decode: make,\n encode: self => self.params\n }))\n});\n/**\n * An empty `UrlParams` value.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const empty = /*#__PURE__*/make([]);\n/**\n * Returns all values for a query parameter key in insertion order.\n *\n * **Details**\n *\n * Returns an empty array when the key is absent.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const getAll = /*#__PURE__*/dual(2, (self, key) => Arr.reduce(self.params, [], (acc, [k, value]) => {\n if (k === key) {\n acc.push(value);\n }\n return acc;\n}));\n/**\n * Returns the first value for a query parameter key safely.\n *\n * **When to use**\n *\n * Use when duplicate query parameters are ordered and the first occurrence has\n * precedence.\n *\n * **Details**\n *\n * Returns `Option.none` when the key is absent.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const getFirst = /*#__PURE__*/dual(2, (self, key) => Arr.findFirst(self.params, ([k]) => k === key).pipe(Option.map(([, value]) => value)));\n/**\n * Returns the last value for a query parameter key safely.\n *\n * **When to use**\n *\n * Use when duplicate query parameters are ordered and the last occurrence has\n * precedence.\n *\n * **Details**\n *\n * Returns `Option.none` when the key is absent.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const getLast = /*#__PURE__*/dual(2, (self, key) => Arr.findLast(self.params, ([k]) => k === key).pipe(Option.map(([, value]) => value)));\n/**\n * Sets a query parameter to a single value.\n *\n * **Details**\n *\n * Existing values for the same key are removed, and the new value is appended to\n * the end.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const set = /*#__PURE__*/dual(3, (self, key, value) => make(Arr.append(Arr.filter(self.params, ([k]) => k !== key), [key, String(value)])));\n/**\n * Transforms the underlying ordered key-value pairs of `UrlParams`.\n *\n * **Details**\n *\n * The result is wrapped in a new `UrlParams` value.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const transform = /*#__PURE__*/dual(2, (self, f) => make(f(self.params)));\n/**\n * Sets multiple query parameters from input.\n *\n * **Details**\n *\n * Keys present in the input replace existing values for those keys, while\n * unmentioned existing parameters are preserved.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const setAll = /*#__PURE__*/dual(2, (self, input) => {\n const out = fromInput(input);\n const params = out.params;\n const keys = new Set();\n for (let i = 0; i < params.length; i++) {\n keys.add(params[i][0]);\n }\n for (let i = 0; i < self.params.length; i++) {\n if (keys.has(self.params[i][0])) continue;\n params.push(self.params[i]);\n }\n return out;\n});\n/**\n * Appends a query parameter value without removing existing values for the key.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const append = /*#__PURE__*/dual(3, (self, key, value) => make(Arr.append(self.params, [key, String(value)])));\n/**\n * Appends all query parameters produced from the supplied input.\n *\n * **Details**\n *\n * Existing parameters are preserved.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const appendAll = /*#__PURE__*/dual(2, (self, input) => transform(self, Arr.appendAll(fromInput(input).params)));\n/**\n * Removes all query parameter values for the specified key.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const remove = /*#__PURE__*/dual(2, (self, key) => transform(self, Arr.filter(([k]) => k !== key)));\n/**\n * Serializes `UrlParams` to a URL query string without a leading question mark.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toString = input => new URLSearchParams(fromInput(input).params).toString();\n/**\n * Builds a `Record` containing all the key-value pairs in the given `UrlParams`\n * as `string` (if only one value for a key) or a `NonEmptyArray<string>`\n * (when more than one value for a key)\n *\n * **Example** (Converting parameters to a record)\n *\n * ```ts\n * import { UrlParams } from \"effect/unstable/http\"\n * import * as assert from \"node:assert\"\n *\n * const urlParams = UrlParams.fromInput({\n * a: 1,\n * b: true,\n * c: \"string\",\n * e: [1, 2, 3]\n * })\n * const result = UrlParams.toRecord(urlParams)\n *\n * assert.deepStrictEqual(\n * result,\n * { \"a\": \"1\", \"b\": \"true\", \"c\": \"string\", \"e\": [\"1\", \"2\", \"3\"] }\n * )\n * ```\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toRecord = self => {\n const out = {};\n for (const [k, value] of self.params) {\n const curr = out[k];\n if (curr === undefined) {\n out[k] = value;\n } else if (typeof curr === \"string\") {\n out[k] = [curr, value];\n } else {\n curr.push(value);\n }\n }\n return out;\n};\n/**\n * Builds a readonly record from `UrlParams`.\n *\n * **Details**\n *\n * Keys with one value map to a string, and keys with multiple values map to a\n * non-empty readonly array of strings.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toReadonlyRecord = toRecord;\n/**\n * Extracts a JSON value from the first occurrence of the given `field` in the\n * `UrlParams`.\n *\n * **Example** (Decoding JSON parameter fields)\n *\n * ```ts\n * import { Schema } from \"effect\"\n * import { UrlParams } from \"effect/unstable/http\"\n *\n * const extractFoo = UrlParams.schemaJsonField(\"foo\").pipe(\n * Schema.decodeTo(Schema.Struct({\n * some: Schema.String,\n * number: Schema.Number\n * }))\n * )\n *\n * console.log(\n * Schema.decodeSync(extractFoo)(UrlParams.fromInput({\n * foo: JSON.stringify({ some: \"bar\", number: 42 }),\n * baz: \"qux\"\n * }))\n * )\n * ```\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const schemaJsonField = field => UrlParamsSchema.pipe(Schema.decodeTo(Schema.UnknownFromJsonString, SchemaTransformation.transformOrFail({\n decode: params => Option.match(getFirst(params, field), {\n onNone: () => Effect.fail(new SchemaIssue.Pointer([field], new SchemaIssue.MissingKey(undefined))),\n onSome: Effect.succeed\n }),\n encode: value => Effect.succeed(make([[field, value]]))\n})));\n/**\n * Schema that decodes `UrlParams` into a record of key-value pairs.\n *\n * **Details**\n *\n * Keys with one value decode to a string, and keys with multiple values decode to\n * a non-empty readonly array of strings.\n *\n * **Example** (Decoding URL parameters to a record)\n *\n * ```ts\n * import { Schema } from \"effect\"\n * import { UrlParams } from \"effect/unstable/http\"\n *\n * const toStruct = UrlParams.schemaRecord.pipe(\n * Schema.decodeTo(Schema.Struct({\n * some: Schema.String,\n * number: Schema.FiniteFromString\n * }))\n * )\n *\n * console.log(\n * Schema.decodeSync(toStruct)(UrlParams.fromInput({\n * some: \"value\",\n * number: 42\n * }))\n * )\n * ```\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const schemaRecord = /*#__PURE__*/UrlParamsSchema.pipe(/*#__PURE__*/Schema.decodeTo(/*#__PURE__*/Schema.Record(Schema.String, /*#__PURE__*/Schema.Union([Schema.String, /*#__PURE__*/Schema.NonEmptyArray(Schema.String)])), /*#__PURE__*/SchemaTransformation.transform({\n decode: toReadonlyRecord,\n encode: fromInput\n})));\n//# sourceMappingURL=UrlParams.js.map","/**\n * Describes HTTP request and response bodies before they reach a platform\n * adapter.\n *\n * `HttpBody` is the shared body representation used by the HTTP modules. Each\n * variant stores the payload together with metadata that can be known before\n * sending it, such as `contentType` and `contentLength`. This module includes\n * body constructors for common payload shapes, support for schema-encoded JSON\n * bodies, streaming and file-backed bodies, and the error type used when body\n * construction fails.\n *\n * @since 4.0.0\n */\nimport * as Data from \"../../Data.js\";\nimport * as Effect from \"../../Effect.js\";\nimport * as FileSystem from \"../../FileSystem.js\";\nimport { format } from \"../../Formatter.js\";\nimport * as Inspectable from \"../../Inspectable.js\";\nimport * as Predicate from \"../../Predicate.js\";\nimport * as Schema from \"../../Schema.js\";\nimport * as SchemaParser from \"../../SchemaParser.js\";\nimport * as UrlParams from \"./UrlParams.js\";\nconst TypeId = \"~effect/http/HttpBody\";\n/**\n * Returns `true` if the provided value is an `HttpBody`.\n *\n * @category refinements\n * @since 4.0.0\n */\nexport const isHttpBody = u => Predicate.hasProperty(u, TypeId);\nconst HttpBodyErrorTypeId = \"~effect/http/HttpBody/HttpBodyError\";\n/**\n * Error produced while constructing an HTTP body from JSON or schema-encoded input.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class HttpBodyError extends /*#__PURE__*/Data.TaggedError(\"HttpBodyError\") {\n /**\n * Marks this value as an HTTP body error for runtime guards.\n *\n * @since 4.0.0\n */\n [HttpBodyErrorTypeId] = HttpBodyErrorTypeId;\n}\nclass Proto {\n [TypeId];\n constructor() {\n this[TypeId] = TypeId;\n }\n [Inspectable.NodeInspectSymbol]() {\n return this.toJSON();\n }\n toString() {\n return format(this, {\n ignoreToString: true\n });\n }\n}\n/**\n * HTTP body variant representing the absence of request content.\n *\n * @category models\n * @since 4.0.0\n */\nexport class Empty extends Proto {\n _tag = \"Empty\";\n toJSON() {\n return {\n _id: \"effect/HttpBody\",\n _tag: \"Empty\"\n };\n }\n}\n/**\n * Provides the singleton empty HTTP body.\n *\n * **When to use**\n *\n * Use when you need an HTTP body value that represents no body content.\n *\n * @category constants\n * @since 4.0.0\n */\nexport const empty = /*#__PURE__*/new Empty();\n/**\n * HTTP body variant containing an arbitrary runtime body value with optional content metadata.\n *\n * @category models\n * @since 4.0.0\n */\nexport class Raw extends Proto {\n _tag = \"Raw\";\n body;\n contentType;\n contentLength;\n constructor(body, contentType, contentLength) {\n super();\n this.body = body;\n this.contentType = contentType;\n this.contentLength = contentLength;\n }\n toJSON() {\n return {\n _id: \"effect/HttpBody\",\n _tag: \"Raw\",\n body: this.body,\n contentType: this.contentType,\n contentLength: this.contentLength\n };\n }\n}\n/**\n * Creates a raw HTTP body from an arbitrary value and optional `contentType` and `contentLength` metadata.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const raw = (body, options) => new Raw(body, options?.contentType, options?.contentLength);\n/**\n * HTTP body variant backed by a `Uint8Array`.\n *\n * **Details**\n *\n * It stores the bytes, content type, and byte length.\n *\n * @category models\n * @since 4.0.0\n */\nexport class Uint8Array extends Proto {\n _tag = \"Uint8Array\";\n body;\n contentType;\n contentLength;\n constructor(body, contentType, contentLength) {\n super();\n this.body = body;\n this.contentType = contentType;\n this.contentLength = contentLength;\n }\n toJSON() {\n const toString = this.contentType.startsWith(\"text/\") || this.contentType.endsWith(\"json\");\n return {\n _id: \"effect/HttpBody\",\n _tag: \"Uint8Array\",\n body: toString ? new TextDecoder().decode(this.body) : `Uint8Array(${this.body.length})`,\n contentType: this.contentType,\n contentLength: this.contentLength\n };\n }\n}\n/**\n * Creates a byte-array HTTP body.\n *\n * **Details**\n *\n * The content type defaults to `application/octet-stream`, and the content length is the byte array length.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const uint8Array = (body, contentType) => new Uint8Array(body, contentType ?? \"application/octet-stream\", body.length);\nconst encoder = /*#__PURE__*/new TextEncoder();\n/**\n * Creates a UTF-8 encoded text HTTP body.\n *\n * **Details**\n *\n * The content type defaults to `text/plain`.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const text = (body, contentType) => uint8Array(encoder.encode(body), contentType ?? \"text/plain\");\n/**\n * Creates a JSON HTTP body using `JSON.stringify`, throwing if serialization fails.\n *\n * **Details**\n *\n * The content type defaults to `application/json`.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const jsonUnsafe = (body, contentType) => text(JSON.stringify(body), contentType ?? \"application/json\");\n/**\n * Creates a JSON HTTP body in an `Effect`.\n *\n * **Details**\n *\n * `JSON.stringify` failures are captured as `HttpBodyError` values, and the content type defaults to `application/json`.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const json = (body, contentType) => Effect.try({\n try: () => text(JSON.stringify(body), contentType ?? \"application/json\"),\n catch: cause => new HttpBodyError({\n reason: {\n _tag: \"JsonError\"\n },\n cause\n })\n});\n/**\n * Creates a JSON body constructor that first encodes values with the schema's JSON codec.\n *\n * **Details**\n *\n * Schema encoding issues and JSON serialization failures are returned as `HttpBodyError` values.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const jsonSchema = (schema, options) => {\n const encode = SchemaParser.encodeUnknownEffect(Schema.toCodecJson(schema));\n return (body, contentType) => encode(body, options).pipe(Effect.mapError(issue => new HttpBodyError({\n reason: {\n _tag: \"SchemaError\",\n issue\n },\n cause: issue\n })), Effect.flatMap(body => json(body, contentType)));\n};\n/**\n * Creates an `application/x-www-form-urlencoded` HTTP body from `UrlParams`.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const urlParams = (urlParams, contentType) => text(UrlParams.toString(UrlParams.fromInput(urlParams)), contentType ?? \"application/x-www-form-urlencoded\");\n/**\n * HTTP body variant backed by Web `FormData`.\n *\n * **Details**\n *\n * The content type and content length are left unset so the runtime can supply multipart boundaries.\n *\n * @category models\n * @since 4.0.0\n */\nexport class FormData extends Proto {\n _tag = \"FormData\";\n contentType = undefined;\n contentLength = undefined;\n formData;\n constructor(formData) {\n super();\n this.formData = formData;\n }\n toJSON() {\n return {\n _id: \"effect/HttpBody\",\n _tag: \"FormData\",\n formData: this.formData\n };\n }\n}\n/**\n * Wraps a Web `FormData` value as an HTTP body.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const formData = body => new FormData(body);\nconst appendFormDataValue = (formData, key, value) => {\n if (value == null) {\n return;\n }\n if (typeof value === \"object\") {\n formData.append(key, value);\n return;\n }\n formData.append(key, String(value));\n};\n/**\n * Creates a `FormData` HTTP body from a record.\n *\n * **Details**\n *\n * Array fields append each item under the same key; primitive values are stringified, `File` and `Blob` values are appended directly, and nullish values are skipped.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const formDataRecord = entries => {\n const data = new globalThis.FormData();\n for (const [key, value] of Object.entries(entries)) {\n if (Array.isArray(value)) {\n for (const item of value) {\n appendFormDataValue(data, key, item);\n }\n } else {\n appendFormDataValue(data, key, value);\n }\n }\n return formData(data);\n};\n/**\n * HTTP body variant backed by a stream of `Uint8Array` chunks.\n *\n * @category models\n * @since 4.0.0\n */\nexport class Stream extends Proto {\n _tag = \"Stream\";\n stream;\n contentType;\n contentLength;\n constructor(stream, contentType, contentLength) {\n super();\n this.stream = stream;\n this.contentType = contentType;\n this.contentLength = contentLength;\n }\n toJSON() {\n return {\n _id: \"effect/HttpBody\",\n _tag: \"Stream\",\n contentType: this.contentType,\n contentLength: this.contentLength\n };\n }\n}\n/**\n * Creates a streaming HTTP body from a stream of byte chunks.\n *\n * **Details**\n *\n * The content type defaults to `application/octet-stream`; content length is optional.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const stream = (body, contentType, contentLength) => new Stream(body, contentType ?? \"application/octet-stream\", contentLength);\n/**\n * Creates a streaming HTTP body for a file path.\n *\n * **Details**\n *\n * The effect requires `FileSystem`, stats the file to set the content length, and can fail with `PlatformError`.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const file = (path, options) => Effect.flatMap(FileSystem.FileSystem, fs => Effect.map(fs.stat(path), info => stream(fs.stream(path, options), options?.contentType, Number(info.size))));\n/**\n * Creates a streaming HTTP body for a file path using already-known file information.\n *\n * **Details**\n *\n * The effect requires `FileSystem`, uses the provided file size as the content length, and can fail with `PlatformError`.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fileFromInfo = (path, info, options) => Effect.map(FileSystem.FileSystem, fs => stream(fs.stream(path, options), options?.contentType, Number(info.size)));\n//# sourceMappingURL=HttpBody.js.map","/**\n * Common model for incoming HTTP messages.\n *\n * `HttpIncomingMessage` is used by server requests and client responses to\n * expose headers, an optional remote address, and body accessors. This module\n * provides decoders for JSON bodies, URL-encoded bodies, and headers, plus the\n * shared body-size setting and inspection helper used by request and response\n * implementations.\n *\n * @since 4.0.0\n */\nimport * as Context from \"../../Context.js\";\nimport * as Effect from \"../../Effect.js\";\nimport { hasProperty } from \"../../Predicate.js\";\nimport { redact } from \"../../Redactable.js\";\nimport * as Schema from \"../../Schema.js\";\nimport * as UrlParams from \"./UrlParams.js\";\n/**\n * Type identifier for `HttpIncomingMessage` values.\n *\n * @category type IDs\n * @since 4.0.0\n */\nexport const TypeId = \"~effect/http/HttpIncomingMessage\";\n/**\n * Returns `true` when a value is an `HttpIncomingMessage`.\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isHttpIncomingMessage = u => hasProperty(u, TypeId);\n/**\n * Creates a decoder that reads an incoming message's JSON body and decodes it with the supplied schema.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const schemaBodyJson = (schema, options) => {\n const decode = Schema.decodeEffect(Schema.toCodecJson(schema));\n return self => Effect.flatMap(self.json, u => decode(u, options));\n};\n/**\n * Creates a decoder that reads an incoming message's URL-encoded body parameters and decodes them with the supplied schema.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const schemaBodyUrlParams = (schema, options) => {\n const decode = UrlParams.schemaRecord.pipe(Schema.decodeTo(schema), Schema.decodeEffect);\n return self => Effect.flatMap(self.urlParamsBody, u => decode(u, options));\n};\n/**\n * Creates a decoder that validates and decodes an incoming message's headers with the supplied schema.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const schemaHeaders = (schema, options) => {\n const decode = Schema.decodeUnknownEffect(schema);\n return self => decode(self.headers, options);\n};\n/**\n * Context reference for the optional maximum size allowed when reading an incoming message body.\n *\n * @category references\n * @since 4.0.0\n */\nexport const MaxBodySize = /*#__PURE__*/Context.Reference(\"effect/http/HttpIncomingMessage/MaxBodySize\", {\n defaultValue: () => undefined\n});\n/**\n * Builds an inspectable object for an incoming message, redacting headers and including a synchronously readable JSON or text body when available.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const inspect = (self, that) => {\n const contentType = self.headers[\"content-type\"] ?? \"\";\n let body;\n if (contentType.includes(\"application/json\")) {\n try {\n body = Effect.runSync(self.json);\n // oxlint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (_) {\n //\n }\n } else if (contentType.includes(\"text/\") || contentType.includes(\"urlencoded\")) {\n try {\n body = Effect.runSync(self.text);\n // oxlint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (_) {\n //\n }\n }\n const obj = {\n ...that,\n headers: redact(self.headers),\n remoteAddress: self.remoteAddress\n };\n if (body !== undefined) {\n obj.body = body;\n }\n return obj;\n};\n//# sourceMappingURL=HttpIncomingMessage.js.map","/**\n * Represents responses returned by the Effect HTTP client.\n *\n * An `HttpClientResponse` keeps the original request together with the response\n * status, headers, cookies, and body accessors from the shared incoming-message\n * model. This module includes constructors, schema-based decoders, helpers for\n * streaming response bodies, and utilities for matching or filtering by HTTP\n * status.\n *\n * @since 4.0.0\n */\nimport * as Effect from \"../../Effect.js\";\nimport { dual } from \"../../Function.js\";\nimport * as Inspectable from \"../../Inspectable.js\";\nimport * as Option from \"../../Option.js\";\nimport { pipeArguments } from \"../../Pipeable.js\";\nimport * as Schema from \"../../Schema.js\";\nimport * as Stream from \"../../Stream.js\";\nimport * as Cookies from \"./Cookies.js\";\nimport * as Headers from \"./Headers.js\";\nimport * as Error from \"./HttpClientError.js\";\nimport * as HttpIncomingMessage from \"./HttpIncomingMessage.js\";\nimport * as UrlParams from \"./UrlParams.js\";\nexport {\n/**\n * Creates a decoder that reads a response JSON body and decodes it with the supplied schema.\n *\n * @category schemas\n * @since 4.0.0\n */\nschemaBodyJson,\n/**\n * Creates a decoder that reads response URL-encoded body parameters and decodes them with the supplied schema.\n *\n * @category schemas\n * @since 4.0.0\n */\nschemaBodyUrlParams,\n/**\n * Creates a decoder that validates and decodes response headers with the supplied schema.\n *\n * @category schemas\n * @since 4.0.0\n */\nschemaHeaders } from \"./HttpIncomingMessage.js\";\n/**\n * Type identifier for `HttpClientResponse` values.\n *\n * @category type IDs\n * @since 4.0.0\n */\nexport const TypeId = \"~effect/http/HttpClientResponse\";\n/**\n * Wraps a Web `Response` and its original `HttpClientRequest` as an `HttpClientResponse`.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromWeb = (request, source) => new WebHttpClientResponse(request, source);\n/**\n * Creates a decoder for a response's status, headers, and JSON body using the supplied schema.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const schemaJson = (schema, options) => {\n const decode = Schema.decodeEffect(Schema.toCodecJson(schema).annotate({\n options\n }));\n return self => Effect.flatMap(self.json, body => decode({\n status: self.status,\n headers: self.headers,\n body\n }));\n};\n/**\n * Creates a decoder for a response's status and headers without reading a response body.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const schemaNoBody = (schema, options) => {\n const decode = Schema.decodeEffect(schema.annotate({\n options\n }));\n return self => decode({\n status: self.status,\n headers: self.headers\n });\n};\n/**\n * Converts an effect producing an `HttpClientResponse` into a stream of response body bytes.\n *\n * @category accessors\n * @since 4.0.0\n */\nexport const stream = effect => Stream.unwrap(Effect.map(effect, self => self.stream));\n/**\n * Pattern matches on a response status, checking exact status handlers before status-class handlers and `orElse`.\n *\n * @category pattern matching\n * @since 4.0.0\n */\nexport const matchStatus = /*#__PURE__*/dual(2, (self, cases) => {\n const status = self.status;\n if (cases[status]) {\n return cases[status](self);\n } else if (status >= 200 && status < 300 && cases[\"2xx\"]) {\n return cases[\"2xx\"](self);\n } else if (status >= 300 && status < 400 && cases[\"3xx\"]) {\n return cases[\"3xx\"](self);\n } else if (status >= 400 && status < 500 && cases[\"4xx\"]) {\n return cases[\"4xx\"](self);\n } else if (status >= 500 && status < 600 && cases[\"5xx\"]) {\n return cases[\"5xx\"](self);\n }\n return cases.orElse(self);\n});\n/**\n * Succeeds with the response when its status satisfies the predicate, otherwise fails with `HttpClientError`.\n *\n * @category filters\n * @since 4.0.0\n */\nexport const filterStatus = /*#__PURE__*/dual(2, (self, f) => Effect.suspend(() => f(self.status) ? Effect.succeed(self) : Effect.fail(new Error.HttpClientError({\n reason: new Error.StatusCodeError({\n response: self,\n request: self.request,\n description: \"invalid status code\"\n })\n}))));\n/**\n * Succeeds with the response only when its status is in the 2xx range, otherwise fails with `HttpClientError`.\n *\n * @category filters\n * @since 4.0.0\n */\nexport const filterStatusOk = self => self.status >= 200 && self.status < 300 ? Effect.succeed(self) : Effect.fail(new Error.HttpClientError({\n reason: new Error.StatusCodeError({\n response: self,\n request: self.request,\n description: \"non 2xx status code\"\n })\n}));\n// -----------------------------------------------------------------------------\n// internal\n// -----------------------------------------------------------------------------\nclass WebHttpClientResponse extends Inspectable.Class {\n [HttpIncomingMessage.TypeId];\n [TypeId];\n request;\n source;\n constructor(request, source) {\n super();\n this.request = request;\n this.source = source;\n this[HttpIncomingMessage.TypeId] = HttpIncomingMessage.TypeId;\n this[TypeId] = TypeId;\n }\n toJSON() {\n return HttpIncomingMessage.inspect(this, {\n _id: \"HttpClientResponse\",\n request: this.request.toJSON(),\n status: this.status\n });\n }\n get status() {\n return this.source.status;\n }\n get headers() {\n return Headers.fromInput(this.source.headers);\n }\n cachedCookies;\n get cookies() {\n if (this.cachedCookies) {\n return this.cachedCookies;\n }\n return this.cachedCookies = Cookies.fromSetCookie(this.source.headers.getSetCookie());\n }\n get remoteAddress() {\n return Option.none();\n }\n get stream() {\n return this.source.body ? Stream.fromReadableStream({\n evaluate: () => this.source.body,\n onError: cause => new Error.HttpClientError({\n reason: new Error.DecodeError({\n request: this.request,\n response: this,\n cause\n })\n })\n }) : Stream.fail(new Error.HttpClientError({\n reason: new Error.EmptyBodyError({\n request: this.request,\n response: this,\n description: \"can not create stream from empty body\"\n })\n }));\n }\n get json() {\n return Effect.flatMap(this.text, text => Effect.try({\n try: () => text === \"\" ? null : JSON.parse(text),\n catch: cause => new Error.HttpClientError({\n reason: new Error.DecodeError({\n request: this.request,\n response: this,\n cause\n })\n })\n }));\n }\n textBody;\n get text() {\n if (this.textBody) {\n return this.textBody;\n }\n this.textBody = Effect.tryPromise({\n try: () => this.source.text(),\n catch: cause => new Error.HttpClientError({\n reason: new Error.DecodeError({\n request: this.request,\n response: this,\n cause\n })\n })\n }).pipe(Effect.cached, Effect.runSync);\n this.arrayBufferBody = Effect.map(this.textBody, _ => new TextEncoder().encode(_).buffer);\n return this.textBody;\n }\n get urlParamsBody() {\n return Effect.flatMap(this.text, _ => Effect.try({\n try: () => UrlParams.fromInput(new URLSearchParams(_)),\n catch: cause => new Error.HttpClientError({\n reason: new Error.DecodeError({\n request: this.request,\n response: this,\n cause\n })\n })\n }));\n }\n formDataBody;\n get formData() {\n return this.formDataBody ??= Effect.tryPromise({\n try: () => this.source.formData(),\n catch: cause => new Error.HttpClientError({\n reason: new Error.DecodeError({\n request: this.request,\n response: this,\n cause\n })\n })\n }).pipe(Effect.cached, Effect.runSync);\n }\n arrayBufferBody;\n get arrayBuffer() {\n if (this.arrayBufferBody) {\n return this.arrayBufferBody;\n }\n this.arrayBufferBody = Effect.tryPromise({\n try: () => this.source.arrayBuffer(),\n catch: cause => new Error.HttpClientError({\n reason: new Error.DecodeError({\n request: this.request,\n response: this,\n cause\n })\n })\n }).pipe(Effect.cached, Effect.runSync);\n this.textBody = Effect.map(this.arrayBufferBody, _ => new TextDecoder().decode(_));\n return this.arrayBufferBody;\n }\n pipe() {\n return pipeArguments(this, arguments);\n }\n}\n//# sourceMappingURL=HttpClientResponse.js.map","/**\n * HTTP propagation helpers for Effect tracing context.\n *\n * This module converts Effect `Tracer.Span` values into outbound trace headers\n * and decodes inbound propagation headers into `Tracer.ExternalSpan` parents.\n * HTTP clients use it to continue the current span across outgoing requests, and\n * server middleware uses it to parent request spans from upstream services.\n *\n * @since 4.0.0\n */\nimport * as Option from \"../../Option.js\";\nimport * as Tracer from \"../../Tracer.js\";\nimport * as Headers from \"./Headers.js\";\n/**\n * Encodes a span into HTTP trace propagation headers.\n *\n * **Details**\n *\n * The generated headers include both compact B3 (`b3`) and W3C `traceparent`\n * formats.\n *\n * @category encoding\n * @since 4.0.0\n */\nexport const toHeaders = span => Headers.fromRecordUnsafe({\n b3: `${span.traceId}-${span.spanId}-${span.sampled ? \"1\" : \"0\"}${Option.match(span.parent, {\n onNone: () => \"\",\n onSome: parent => `-${parent.spanId}`\n })}`,\n traceparent: `00-${span.traceId}-${span.spanId}-${span.sampled ? \"01\" : \"00\"}`\n});\n/**\n * Decodes an external span safely from HTTP trace propagation headers.\n *\n * **Details**\n *\n * W3C `traceparent` is tried first, followed by compact B3 (`b3`) and then\n * multi-header B3 (`x-b3-*`).\n *\n * @category decoding\n * @since 4.0.0\n */\nexport const fromHeaders = headers => {\n let span = w3c(headers);\n if (Option.isSome(span)) {\n return span;\n }\n span = b3(headers);\n if (Option.isSome(span)) {\n return span;\n }\n return xb3(headers);\n};\n/**\n * Decodes an external span safely from the compact B3 `b3` header.\n *\n * **Details**\n *\n * Returns `Option.none` when the header is missing or does not contain trace and\n * span identifiers.\n *\n * @category decoding\n * @since 4.0.0\n */\nexport const b3 = headers => {\n if (!(\"b3\" in headers)) {\n return Option.none();\n }\n const parts = headers[\"b3\"].split(\"-\");\n if (parts.length < 2) {\n return Option.none();\n }\n return Option.some(Tracer.externalSpan({\n traceId: parts[0],\n spanId: parts[1],\n sampled: parts[2] ? parts[2] === \"1\" : true\n }));\n};\n/**\n * Decodes an external span safely from multi-header B3 propagation headers.\n *\n * **Details**\n *\n * The decoder reads `x-b3-traceid`, `x-b3-spanid`, and optional `x-b3-sampled`\n * headers.\n *\n * @category decoding\n * @since 4.0.0\n */\nexport const xb3 = headers => {\n if (!headers[\"x-b3-traceid\"] || !headers[\"x-b3-spanid\"]) {\n return Option.none();\n }\n return Option.some(Tracer.externalSpan({\n traceId: headers[\"x-b3-traceid\"],\n spanId: headers[\"x-b3-spanid\"],\n sampled: headers[\"x-b3-sampled\"] ? headers[\"x-b3-sampled\"] === \"1\" : true\n }));\n};\nconst w3cTraceId = /^[0-9a-f]{32}$/i;\nconst w3cSpanId = /^[0-9a-f]{16}$/i;\n/**\n * Decodes an external span safely from the W3C `traceparent` header.\n *\n * **Details**\n *\n * Only version `00` headers with valid trace and span identifiers are accepted.\n *\n * @category decoding\n * @since 4.0.0\n */\nexport const w3c = headers => {\n if (!headers[\"traceparent\"]) {\n return Option.none();\n }\n const parts = headers[\"traceparent\"].split(\"-\");\n if (parts.length !== 4) {\n return Option.none();\n }\n const [version, traceId, spanId, flags] = parts;\n switch (version) {\n case \"00\":\n {\n if (w3cTraceId.test(traceId) === false || w3cSpanId.test(spanId) === false) {\n return Option.none();\n }\n return Option.some(Tracer.externalSpan({\n traceId,\n spanId,\n sampled: (parseInt(flags, 16) & 1) === 1\n }));\n }\n default:\n {\n return Option.none();\n }\n }\n};\n//# sourceMappingURL=HttpTraceContext.js.map","/**\n * @since 1.0.0\n */\n// Taken from https://github.com/anonrig/fast-querystring under MIT License\nconst plusRegex = /\\+/g;\nconst Empty = function () {};\nEmpty.prototype = /*#__PURE__*/Object.create(null);\n/**\n * @category parsing\n * @since 1.0.0\n */\nexport function parse(input) {\n // Optimization: Use new Empty() instead of Object.create(null) for performance\n // v8 has a better optimization for initializing functions compared to Object\n const result = new Empty();\n if (typeof input !== \"string\") {\n return result;\n }\n const inputLength = input.length;\n let key = \"\";\n let value = \"\";\n let startingIndex = -1;\n let equalityIndex = -1;\n let shouldDecodeKey = false;\n let shouldDecodeValue = false;\n let keyHasPlus = false;\n let valueHasPlus = false;\n let hasBothKeyValuePair = false;\n let c = 0;\n // Have a boundary of input.length + 1 to access last pair inside the loop.\n for (let i = 0; i < inputLength + 1; i++) {\n c = i !== inputLength ? input.charCodeAt(i) : 38;\n // Handle '&' and end of line to pass the current values to result\n if (c === 38) {\n hasBothKeyValuePair = equalityIndex > startingIndex;\n // Optimization: Reuse equality index to store the end of key\n if (!hasBothKeyValuePair) {\n equalityIndex = i;\n }\n key = input.slice(startingIndex + 1, equalityIndex);\n // Add key/value pair only if the range size is greater than 1; a.k.a. contains at least \"=\"\n if (hasBothKeyValuePair || key.length > 0) {\n // Optimization: Replace '+' with space\n if (keyHasPlus) {\n key = key.replace(plusRegex, \" \");\n }\n // Optimization: Do not decode if it's not necessary.\n if (shouldDecodeKey) {\n try {\n key = decodeURIComponent(key) || key;\n } catch {}\n }\n if (hasBothKeyValuePair) {\n value = input.slice(equalityIndex + 1, i);\n if (valueHasPlus) {\n value = value.replace(plusRegex, \" \");\n }\n if (shouldDecodeValue) {\n try {\n value = decodeURIComponent(value) || value;\n } catch {}\n }\n }\n const currentValue = result[key];\n if (currentValue === undefined) {\n result[key] = value;\n } else {\n // Optimization: value.pop is faster than Array.isArray(value)\n if (currentValue.pop) {\n currentValue.push(value);\n } else {\n result[key] = [currentValue, value];\n }\n }\n }\n // Reset reading key value pairs\n value = \"\";\n startingIndex = i;\n equalityIndex = i;\n shouldDecodeKey = false;\n shouldDecodeValue = false;\n keyHasPlus = false;\n valueHasPlus = false;\n }\n // Check '='\n else if (c === 61) {\n if (equalityIndex <= startingIndex) {\n equalityIndex = i;\n }\n // If '=' character occurs again, we should decode the input.\n else {\n shouldDecodeValue = true;\n }\n }\n // Check '+', and remember to replace it with empty space.\n else if (c === 43) {\n if (equalityIndex > startingIndex) {\n valueHasPlus = true;\n } else {\n keyHasPlus = true;\n }\n }\n // Check '%' character for encoding\n else if (c === 37) {\n if (equalityIndex > startingIndex) {\n shouldDecodeValue = true;\n } else {\n shouldDecodeKey = true;\n }\n }\n }\n return result;\n}\nfunction getAsPrimitive(value) {\n const type = typeof value;\n if (type === \"string\") {\n // Length check is handled inside encodeString function\n return encodeString(value);\n } else if (type === \"bigint\" || type === \"boolean\") {\n return \"\" + value;\n } else if (type === \"number\" && Number.isFinite(value)) {\n return value < 1e21 ? \"\" + value : encodeString(\"\" + value);\n }\n return \"\";\n}\n/**\n * @category encoding\n * @since 1.0.0\n */\nexport function stringify(input) {\n let result = \"\";\n if (input === null || typeof input !== \"object\") {\n return result;\n }\n const separator = \"&\";\n const keys = Object.keys(input);\n const keyLength = keys.length;\n let valueLength = 0;\n for (let i = 0; i < keyLength; i++) {\n const key = keys[i];\n const value = input[key];\n const encodedKey = encodeString(key) + \"=\";\n if (i) {\n result += separator;\n }\n if (Array.isArray(value)) {\n valueLength = value.length;\n for (let j = 0; j < valueLength; j++) {\n if (j) {\n result += separator;\n }\n // Optimization: Dividing into multiple lines improves the performance.\n // Since v8 does not need to care about the '+' character if it was one-liner.\n result += encodedKey;\n result += getAsPrimitive(value[j]);\n }\n } else {\n result += encodedKey;\n result += getAsPrimitive(value);\n }\n }\n return result;\n}\n// -----------------------------------------------------------------------------\n// This has been taken from Node.js project.\n// Full implementation can be found from https://github.com/nodejs/node/blob/main/lib/internal/querystring.js\nconst hexTable = /*#__PURE__*/Array.from({\n length: 256\n}, (_, i) => \"%\" + ((i < 16 ? \"0\" : \"\") + i.toString(16)).toUpperCase());\n// These characters do not need escaping when generating query strings:\n// ! - . _ ~\n// ' ( ) *\n// digits\n// alpha (uppercase)\n// alpha (lowercase)\n// biome-ignore format: the array should not be formatted\nconst noEscape = /*#__PURE__*/new Int8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n// 0 - 15\n0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n// 16 - 31\n0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0,\n// 32 - 47\n1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,\n// 48 - 63\n0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n// 64 - 79\n1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,\n// 80 - 95\n0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n// 96 - 111\n1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0 // 112 - 127\n]);\nfunction encodeString(str) {\n const len = str.length;\n if (len === 0) return \"\";\n let out = \"\";\n let lastPos = 0;\n let i = 0;\n outer: for (; i < len; i++) {\n let c = str.charCodeAt(i);\n // ASCII\n while (c < 0x80) {\n if (noEscape[c] !== 1) {\n if (lastPos < i) out += str.slice(lastPos, i);\n lastPos = i + 1;\n out += hexTable[c];\n }\n if (++i === len) break outer;\n c = str.charCodeAt(i);\n }\n if (lastPos < i) out += str.slice(lastPos, i);\n // Multi-byte characters ...\n if (c < 0x800) {\n lastPos = i + 1;\n out += hexTable[0xc0 | c >> 6] + hexTable[0x80 | c & 0x3f];\n continue;\n }\n if (c < 0xd800 || c >= 0xe000) {\n lastPos = i + 1;\n out += hexTable[0xe0 | c >> 12] + hexTable[0x80 | c >> 6 & 0x3f] + hexTable[0x80 | c & 0x3f];\n continue;\n }\n // Surrogate pair\n ++i;\n // This branch should never happen because all URLSearchParams entries\n // should already be converted to USVString. But, included for\n // completion's sake anyway.\n if (i >= len) {\n throw new Error(\"URI malformed\");\n }\n const c2 = str.charCodeAt(i) & 0x3ff;\n lastPos = i + 1;\n c = 0x10000 + ((c & 0x3ff) << 10 | c2);\n out += hexTable[0xf0 | c >> 18] + hexTable[0x80 | c >> 12 & 0x3f] + hexTable[0x80 | c >> 6 & 0x3f] + hexTable[0x80 | c & 0x3f];\n }\n if (lastPos === 0) return str;\n if (lastPos < len) return out + str.slice(lastPos);\n return out;\n}\n//# sourceMappingURL=QueryString.js.map","import * as QS from \"../QueryString.js\";\nconst FULL_PATH_REGEXP = /^https?:\\/\\/.*?\\//;\nconst OPTIONAL_PARAM_REGEXP = /(\\/:[^/()]*?)\\?(\\/?)/;\n/** @internal */\nexport const make = (options = {}) => new RouterImpl(options);\nclass RouterImpl {\n constructor(options = {}) {\n this.options = {\n ignoreTrailingSlash: true,\n ignoreDuplicateSlashes: true,\n caseSensitive: false,\n maxParamLength: 100,\n ...options\n };\n }\n options;\n routes = [];\n trees = {};\n on(method, path, handler) {\n const optionalParamMatch = path.match(OPTIONAL_PARAM_REGEXP);\n if (optionalParamMatch && optionalParamMatch.index !== undefined) {\n assert(path.length === optionalParamMatch.index + optionalParamMatch[0].length, \"Optional Parameter needs to be the last parameter of the path\");\n const pathFull = path.replace(OPTIONAL_PARAM_REGEXP, \"$1$2\");\n const pathOptional = path.replace(OPTIONAL_PARAM_REGEXP, \"$2\");\n this.on(method, pathFull, handler);\n this.on(method, pathOptional, handler);\n return;\n }\n if (this.options.ignoreDuplicateSlashes) {\n path = removeDuplicateSlashes(path);\n }\n if (this.options.ignoreTrailingSlash) {\n path = trimLastSlash(path);\n }\n const methods = typeof method === \"string\" ? [method] : method;\n for (const method of methods) {\n this._on(method, path, handler);\n }\n }\n all(path, handler) {\n this.on(httpMethods, path, handler);\n }\n _on(method, path, handler) {\n if (this.trees[method] === undefined) {\n this.trees[method] = new StaticNode(\"/\");\n }\n let pattern = path;\n if (pattern === \"*\" && this.trees[method].prefix.length !== 0) {\n const currentRoot = this.trees[method];\n this.trees[method] = new StaticNode(\"\");\n this.trees[method].staticChildren[\"/\"] = currentRoot;\n }\n let parentNodePathIndex = this.trees[method].prefix.length;\n let currentNode = this.trees[method];\n const params = [];\n for (let i = 0; i <= pattern.length; i++) {\n if (pattern.charCodeAt(i) === 58 && pattern.charCodeAt(i + 1) === 58) {\n // It's a double colon\n i++;\n continue;\n }\n const isParametricNode = pattern.charCodeAt(i) === 58 && pattern.charCodeAt(i + 1) !== 58;\n const isWildcardNode = pattern.charCodeAt(i) === 42;\n if (isParametricNode || isWildcardNode || i === pattern.length && i !== parentNodePathIndex) {\n let staticNodePath = pattern.slice(parentNodePathIndex, i);\n if (!this.options.caseSensitive) {\n staticNodePath = staticNodePath.toLowerCase();\n }\n staticNodePath = staticNodePath.split(\"::\").join(\":\");\n staticNodePath = staticNodePath.split(\"%\").join(\"%25\");\n // add the static part of the route to the tree\n currentNode = currentNode.createStaticChild(staticNodePath);\n }\n if (isParametricNode) {\n let isRegexNode = false;\n const regexps = [];\n let lastParamStartIndex = i + 1;\n for (let j = lastParamStartIndex;; j++) {\n const charCode = pattern.charCodeAt(j);\n const isRegexParam = charCode === 40;\n const isStaticPart = charCode === 45 || charCode === 46;\n const isEndOfNode = charCode === 47 || j === pattern.length;\n if (isRegexParam || isStaticPart || isEndOfNode) {\n const paramName = pattern.slice(lastParamStartIndex, j);\n params.push(paramName);\n isRegexNode = isRegexNode || isRegexParam || isStaticPart;\n if (isRegexParam) {\n const endOfRegexIndex = getClosingParenthensePosition(pattern, j);\n const regexString = pattern.slice(j, endOfRegexIndex + 1);\n regexps.push(trimRegExpStartAndEnd(regexString));\n j = endOfRegexIndex + 1;\n } else {\n regexps.push(\"(.*?)\");\n }\n const staticPartStartIndex = j;\n for (; j < pattern.length; j++) {\n const charCode = pattern.charCodeAt(j);\n if (charCode === 47) break;\n if (charCode === 58) {\n const nextCharCode = pattern.charCodeAt(j + 1);\n if (nextCharCode === 58) j++;else break;\n }\n }\n let staticPart = pattern.slice(staticPartStartIndex, j);\n if (staticPart) {\n staticPart = staticPart.split(\"::\").join(\":\");\n staticPart = staticPart.split(\"%\").join(\"%25\");\n regexps.push(escapeRegExp(staticPart));\n }\n lastParamStartIndex = j + 1;\n if (isEndOfNode || pattern.charCodeAt(j) === 47 || j === pattern.length) {\n const nodePattern = isRegexNode ? \"()\" + staticPart : staticPart;\n const nodePath = pattern.slice(i, j);\n pattern = pattern.slice(0, i + 1) + nodePattern + pattern.slice(j);\n i += nodePattern.length;\n const regex = isRegexNode ? new RegExp(\"^\" + regexps.join(\"\") + \"$\") : undefined;\n currentNode = currentNode.createParametricChild(regex, staticPart, nodePath);\n parentNodePathIndex = i + 1;\n break;\n }\n }\n }\n } else if (isWildcardNode) {\n // add the wildcard parameter\n params.push(\"*\");\n currentNode = currentNode.createWildcardChild();\n parentNodePathIndex = i + 1;\n if (i !== pattern.length - 1) {\n throw new Error(\"Wildcard must be the last character in the route\");\n }\n }\n }\n if (!this.options.caseSensitive) {\n pattern = pattern.toLowerCase();\n }\n if (pattern === \"*\") {\n pattern = \"/*\";\n }\n for (const existRoute of this.routes) {\n if (existRoute.method === method && existRoute.pattern === pattern) {\n throw new Error(`Method '${method}' already declared for route '${pattern}'`);\n }\n }\n const route = {\n method,\n path,\n pattern,\n params,\n handler\n };\n this.routes.push(route);\n currentNode.addRoute(route);\n }\n has(method, path) {\n const node = this.trees[method];\n if (node === undefined) {\n return false;\n }\n const staticNode = node.getStaticChild(path);\n if (staticNode === undefined) {\n return false;\n }\n return staticNode.isLeafNode;\n }\n find(method, path) {\n let currentNode = this.trees[method];\n if (currentNode === undefined) return undefined;\n if (path.charCodeAt(0) !== 47) {\n // 47 is '/'\n path = path.replace(FULL_PATH_REGEXP, \"/\");\n }\n // This must be run before sanitizeUrl as the resulting function\n // .sliceParameter must be constructed with same URL string used\n // throughout the rest of this function.\n if (this.options.ignoreDuplicateSlashes) {\n path = removeDuplicateSlashes(path);\n }\n let sanitizedUrl;\n let querystring;\n let shouldDecodeParam;\n try {\n sanitizedUrl = safeDecodeURI(path);\n path = sanitizedUrl.path;\n querystring = sanitizedUrl.querystring;\n shouldDecodeParam = sanitizedUrl.shouldDecodeParam;\n } catch (error) {\n return undefined;\n }\n if (this.options.ignoreTrailingSlash) {\n path = trimLastSlash(path);\n }\n const originPath = path;\n if (this.options.caseSensitive === false) {\n path = path.toLowerCase();\n }\n const maxParamLength = this.options.maxParamLength;\n let pathIndex = currentNode.prefix.length;\n const params = [];\n const pathLen = path.length;\n const brothersNodesStack = [];\n while (true) {\n if (pathIndex === pathLen && currentNode.isLeafNode) {\n const handle = currentNode.handlerStorage?.find();\n if (handle !== undefined) {\n return {\n handler: handle.handler,\n params: handle.createParams(params),\n searchParams: QS.parse(querystring)\n };\n }\n }\n let node = currentNode.getNextNode(path, pathIndex, brothersNodesStack, params.length);\n if (node === undefined) {\n if (brothersNodesStack.length === 0) {\n return undefined;\n }\n const brotherNodeState = brothersNodesStack.pop();\n pathIndex = brotherNodeState.brotherPathIndex;\n params.splice(brotherNodeState.paramsCount);\n node = brotherNodeState.brotherNode;\n }\n currentNode = node;\n // static route\n if (currentNode._tag === \"StaticNode\") {\n pathIndex += currentNode.prefix.length;\n continue;\n }\n if (currentNode._tag === \"WildcardNode\") {\n let param = originPath.slice(pathIndex);\n if (shouldDecodeParam) {\n param = safeDecodeURIComponent(param);\n }\n params.push(param);\n pathIndex = pathLen;\n continue;\n }\n if (currentNode._tag === \"ParametricNode\") {\n let paramEndIndex = originPath.indexOf(\"/\", pathIndex);\n if (paramEndIndex === -1) {\n paramEndIndex = pathLen;\n }\n let param = originPath.slice(pathIndex, paramEndIndex);\n if (shouldDecodeParam) {\n param = safeDecodeURIComponent(param);\n }\n if (currentNode.regex !== undefined) {\n const matchedParameters = currentNode.regex.exec(param);\n if (matchedParameters === null) continue;\n for (let i = 1; i < matchedParameters.length; i++) {\n const matchedParam = matchedParameters[i];\n if (matchedParam.length > maxParamLength) {\n return undefined;\n }\n params.push(matchedParam);\n }\n } else {\n if (param.length > maxParamLength) {\n return undefined;\n }\n params.push(param);\n }\n pathIndex = paramEndIndex;\n }\n }\n }\n}\nclass HandlerStorage {\n handlers = [];\n unconstrainedHandler;\n find() {\n return this.unconstrainedHandler;\n }\n add(route) {\n const handler = {\n params: route.params,\n handler: route.handler,\n createParams: compileCreateParams(route.params)\n };\n this.handlers.push(handler);\n this.unconstrainedHandler = this.handlers[0];\n }\n}\nclass NodeBase {\n isLeafNode = false;\n routes;\n handlerStorage;\n addRoute(route) {\n if (this.routes === undefined) {\n this.routes = [route];\n } else {\n this.routes.push(route);\n }\n if (this.handlerStorage === undefined) {\n this.handlerStorage = new HandlerStorage();\n }\n this.isLeafNode = true;\n this.handlerStorage.add(route);\n }\n}\nclass ParentNode extends NodeBase {\n staticChildren = {};\n findStaticMatchingChild(path, pathIndex) {\n const staticChild = this.staticChildren[path.charAt(pathIndex)];\n if (staticChild === undefined || !staticChild.matchPrefix(path, pathIndex)) {\n return undefined;\n }\n return staticChild;\n }\n getStaticChild(path, pathIndex = 0) {\n if (path.length === pathIndex) {\n return this;\n }\n const staticChild = this.findStaticMatchingChild(path, pathIndex);\n if (staticChild === undefined) {\n return undefined;\n }\n return staticChild.getStaticChild(path, pathIndex + staticChild.prefix.length);\n }\n createStaticChild(path) {\n if (path.length === 0) {\n return this;\n }\n let staticChild = this.staticChildren[path.charAt(0)];\n if (staticChild) {\n let i = 1;\n for (; i < staticChild.prefix.length; i++) {\n if (path.charCodeAt(i) !== staticChild.prefix.charCodeAt(i)) {\n staticChild = staticChild.split(this, i);\n break;\n }\n }\n return staticChild.createStaticChild(path.slice(i));\n }\n const label = path.charAt(0);\n this.staticChildren[label] = new StaticNode(path);\n return this.staticChildren[label];\n }\n}\nclass StaticNode extends ParentNode {\n _tag = \"StaticNode\";\n constructor(prefix) {\n super();\n this.setPrefix(prefix);\n }\n prefix;\n matchPrefix;\n parametricChildren = [];\n wildcardChild;\n setPrefix(prefix) {\n this.prefix = prefix;\n if (prefix.length === 1) {\n this.matchPrefix = (_path, _pathIndex) => true;\n } else {\n const len = prefix.length;\n this.matchPrefix = function (path, pathIndex) {\n for (let i = 1; i < len; i++) {\n if (path.charCodeAt(pathIndex + i) !== this.prefix.charCodeAt(i)) {\n return false;\n }\n }\n return true;\n };\n }\n }\n getParametricChild(regex) {\n if (regex === undefined) {\n return this.parametricChildren.find(child => child.isRegex === false);\n }\n const source = regex.source;\n return this.parametricChildren.find(child => {\n if (child.regex === undefined) {\n return false;\n }\n return child.regex.source === source;\n });\n }\n createParametricChild(regex, staticSuffix, nodePath) {\n let child = this.getParametricChild(regex);\n if (child !== undefined) {\n child.nodePaths.add(nodePath);\n return child;\n }\n child = new ParametricNode(regex, staticSuffix, nodePath);\n this.parametricChildren.push(child);\n this.parametricChildren.sort((child1, child2) => {\n if (!child1.isRegex) return 1;\n if (!child2.isRegex) return -1;\n if (child1.staticSuffix === undefined) return 1;\n if (child2.staticSuffix === undefined) return -1;\n if (child2.staticSuffix.endsWith(child1.staticSuffix)) return 1;\n if (child1.staticSuffix.endsWith(child2.staticSuffix)) return -1;\n return 0;\n });\n return child;\n }\n createWildcardChild() {\n if (this.wildcardChild === undefined) {\n this.wildcardChild = new WildcardNode();\n }\n return this.wildcardChild;\n }\n split(parentNode, length) {\n const parentPrefix = this.prefix.slice(0, length);\n const childPrefix = this.prefix.slice(length);\n this.setPrefix(childPrefix);\n const staticNode = new StaticNode(parentPrefix);\n staticNode.staticChildren[childPrefix.charAt(0)] = this;\n parentNode.staticChildren[parentPrefix.charAt(0)] = staticNode;\n return staticNode;\n }\n getNextNode(path, pathIndex, nodeStack, paramsCount) {\n let node = this.findStaticMatchingChild(path, pathIndex);\n let parametricBrotherNodeIndex = 0;\n if (node === undefined) {\n if (this.parametricChildren.length === 0) {\n return this.wildcardChild;\n }\n node = this.parametricChildren[0];\n parametricBrotherNodeIndex = 1;\n }\n if (this.wildcardChild !== undefined) {\n nodeStack.push({\n paramsCount,\n brotherPathIndex: pathIndex,\n brotherNode: this.wildcardChild\n });\n }\n for (let i = this.parametricChildren.length - 1; i >= parametricBrotherNodeIndex; i--) {\n nodeStack.push({\n paramsCount,\n brotherPathIndex: pathIndex,\n brotherNode: this.parametricChildren[i]\n });\n }\n return node;\n }\n}\nclass ParametricNode extends ParentNode {\n regex;\n staticSuffix;\n _tag = \"ParametricNode\";\n constructor(regex, staticSuffix, nodePath) {\n super();\n this.regex = regex;\n this.staticSuffix = staticSuffix;\n this.isRegex = !!regex;\n this.nodePaths = new Set([nodePath]);\n }\n isRegex;\n nodePaths;\n getNextNode(path, pathIndex) {\n return this.findStaticMatchingChild(path, pathIndex);\n }\n}\nclass WildcardNode extends NodeBase {\n _tag = \"WildcardNode\";\n getNextNode(_path, _pathIndex, _nodeStack, _paramsCount) {\n return undefined;\n }\n}\nconst assert = (condition, message) => {\n if (!condition) {\n throw new Error(message);\n }\n};\nfunction removeDuplicateSlashes(path) {\n return path.replace(/\\/\\/+/g, \"/\");\n}\nfunction trimLastSlash(path) {\n if (path.length > 1 && path.charCodeAt(path.length - 1) === 47) {\n return path.slice(0, -1);\n }\n return path;\n}\nfunction compileCreateParams(params) {\n const len = params.length;\n return function (paramsArray) {\n const paramsObject = {};\n for (let i = 0; i < len; i++) {\n paramsObject[params[i]] = paramsArray[i];\n }\n return paramsObject;\n };\n}\nfunction getClosingParenthensePosition(path, idx) {\n // `path.indexOf()` will always return the first position of the closing parenthese,\n // but it's inefficient for grouped or wrong regexp expressions.\n // see issues #62 and #63 for more info\n let parentheses = 1;\n while (idx < path.length) {\n idx++;\n // ignore skipped chars\n if (path[idx] === \"\\\\\") {\n idx++;\n continue;\n }\n if (path[idx] === \")\") {\n parentheses--;\n } else if (path[idx] === \"(\") {\n parentheses++;\n }\n if (!parentheses) return idx;\n }\n throw new TypeError('Invalid regexp expression in \"' + path + '\"');\n}\nfunction trimRegExpStartAndEnd(regexString) {\n // removes chars that marks start \"^\" and end \"$\" of regexp\n if (regexString.charCodeAt(1) === 94) {\n regexString = regexString.slice(0, 1) + regexString.slice(2);\n }\n if (regexString.charCodeAt(regexString.length - 2) === 36) {\n regexString = regexString.slice(0, regexString.length - 2) + regexString.slice(regexString.length - 1);\n }\n return regexString;\n}\nfunction escapeRegExp(string) {\n return string.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n// It must spot all the chars where decodeURIComponent(x) !== decodeURI(x)\n// The chars are: # $ & + , / : ; = ? @\nfunction decodeComponentChar(highCharCode, lowCharCode) {\n if (highCharCode === 50) {\n if (lowCharCode === 53) return \"%\";\n if (lowCharCode === 51) return \"#\";\n if (lowCharCode === 52) return \"$\";\n if (lowCharCode === 54) return \"&\";\n if (lowCharCode === 66) return \"+\";\n if (lowCharCode === 98) return \"+\";\n if (lowCharCode === 67) return \",\";\n if (lowCharCode === 99) return \",\";\n if (lowCharCode === 70) return \"/\";\n if (lowCharCode === 102) return \"/\";\n return undefined;\n }\n if (highCharCode === 51) {\n if (lowCharCode === 65) return \":\";\n if (lowCharCode === 97) return \":\";\n if (lowCharCode === 66) return \";\";\n if (lowCharCode === 98) return \";\";\n if (lowCharCode === 68) return \"=\";\n if (lowCharCode === 100) return \"=\";\n if (lowCharCode === 70) return \"?\";\n if (lowCharCode === 102) return \"?\";\n return undefined;\n }\n if (highCharCode === 52 && lowCharCode === 48) {\n return \"@\";\n }\n return undefined;\n}\nfunction safeDecodeURI(path) {\n let shouldDecode = false;\n let shouldDecodeParam = false;\n let querystring = \"\";\n for (let i = 1; i < path.length; i++) {\n const charCode = path.charCodeAt(i);\n if (charCode === 37) {\n const highCharCode = path.charCodeAt(i + 1);\n const lowCharCode = path.charCodeAt(i + 2);\n if (decodeComponentChar(highCharCode, lowCharCode) === undefined) {\n shouldDecode = true;\n } else {\n shouldDecodeParam = true;\n // %25 - encoded % char. We need to encode one more time to prevent double decoding\n if (highCharCode === 50 && lowCharCode === 53) {\n shouldDecode = true;\n path = path.slice(0, i + 1) + \"25\" + path.slice(i + 1);\n i += 2;\n }\n i += 2;\n }\n // Some systems do not follow RFC and separate the path and query\n // string with a `;` character (code 59), e.g. `/foo;jsessionid=123456`.\n // Thus, we need to split on `;` as well as `?` and `#`.\n } else if (charCode === 63 || charCode === 59 || charCode === 35) {\n querystring = path.slice(i + 1);\n path = path.slice(0, i);\n break;\n }\n }\n const decodedPath = shouldDecode ? decodeURI(path) : path;\n return {\n path: decodedPath,\n querystring,\n shouldDecodeParam\n };\n}\nfunction safeDecodeURIComponent(uriComponent) {\n const startIndex = uriComponent.indexOf(\"%\");\n if (startIndex === -1) return uriComponent;\n let decoded = \"\";\n let lastIndex = startIndex;\n for (let i = startIndex; i < uriComponent.length; i++) {\n if (uriComponent.charCodeAt(i) === 37) {\n const highCharCode = uriComponent.charCodeAt(i + 1);\n const lowCharCode = uriComponent.charCodeAt(i + 2);\n const decodedChar = decodeComponentChar(highCharCode, lowCharCode);\n decoded += uriComponent.slice(lastIndex, i) + decodedChar;\n lastIndex = i + 3;\n }\n }\n return uriComponent.slice(0, startIndex) + decoded + uriComponent.slice(lastIndex);\n}\nconst httpMethods = [\"ACL\", \"BIND\", \"CHECKOUT\", \"CONNECT\", \"COPY\", \"DELETE\", \"GET\", \"HEAD\", \"LINK\", \"LOCK\", \"M-SEARCH\", \"MERGE\", \"MKACTIVITY\", \"MKCALENDAR\", \"MKCOL\", \"MOVE\", \"NOTIFY\", \"OPTIONS\", \"PATCH\", \"POST\", \"PROPFIND\", \"PROPPATCH\", \"PURGE\", \"PUT\", \"REBIND\", \"REPORT\", \"SEARCH\", \"SOURCE\", \"SUBSCRIBE\", \"TRACE\", \"UNBIND\", \"UNLINK\", \"UNLOCK\", \"UNSUBSCRIBE\"];\n//# sourceMappingURL=router.js.map","/**\n * @since 1.0.0\n */\nimport * as internal from \"./internal/router.js\";\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const make = internal.make;\n//# sourceMappingURL=index.js.map","/**\n * Describes immutable responses returned by Effect HTTP handlers.\n *\n * An `HttpServerResponse` stores the status, optional status text, headers,\n * cookies, and body that the server runtime later turns into a platform\n * response such as a Web `Response`. This module includes constructors for\n * common response bodies, helpers for updating response data, file response\n * support through `HttpPlatform`, and conversions to or from Web and Effect\n * HTTP client responses.\n *\n * @since 4.0.0\n */\nimport * as Context from \"../../Context.js\";\nimport * as Effect from \"../../Effect.js\";\nimport * as ErrorReporter from \"../../ErrorReporter.js\";\nimport { dual } from \"../../Function.js\";\nimport * as Inspectable from \"../../Inspectable.js\";\nimport { PipeInspectableProto } from \"../../internal/core.js\";\nimport * as Option from \"../../Option.js\";\nimport { pipeArguments } from \"../../Pipeable.js\";\nimport { hasProperty } from \"../../Predicate.js\";\nimport { redact } from \"../../Redactable.js\";\nimport * as Stream from \"../../Stream.js\";\nimport * as Cookies from \"./Cookies.js\";\nimport * as Headers from \"./Headers.js\";\nimport * as Body from \"./HttpBody.js\";\nimport * as HttpClientError from \"./HttpClientError.js\";\nimport * as HttpClientRequest from \"./HttpClientRequest.js\";\nimport * as HttpClientResponse from \"./HttpClientResponse.js\";\nimport * as HttpIncomingMessage from \"./HttpIncomingMessage.js\";\nimport * as Template from \"./Template.js\";\nimport * as UrlParams from \"./UrlParams.js\";\nconst TypeId = \"~effect/http/HttpServerResponse\";\n/**\n * Returns `true` when the supplied value is an `HttpServerResponse`.\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isHttpServerResponse = u => hasProperty(u, TypeId);\n/**\n * Creates an empty HTTP response.\n *\n * **Details**\n *\n * The default status is `204`.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const empty = options => makeResponse({\n status: options?.status ?? 204,\n statusText: options?.statusText,\n headers: options?.headers ? Headers.fromInput(options.headers) : undefined,\n cookies: options?.cookies\n});\n/**\n * Creates a redirect response with a `Location` header.\n *\n * **Details**\n *\n * The default status is `302`; custom headers are merged with the generated\n * `Location` header.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const redirect = (location, options) => {\n const headers = Headers.fromRecordUnsafe({\n location: location.toString()\n });\n return makeResponse({\n status: options?.status ?? 302,\n statusText: options?.statusText,\n headers: options?.headers ? Headers.merge(headers, Headers.fromInput(options.headers)) : headers,\n cookies: options?.cookies ?? Cookies.empty\n });\n};\n/**\n * Creates an HTTP response whose body is a `Uint8Array`.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const uint8Array = (body, options) => {\n const headers = options?.headers ? Headers.fromInput(options.headers) : Headers.empty;\n return makeResponse({\n status: options?.status ?? 200,\n statusText: options?.statusText,\n headers,\n cookies: options?.cookies ?? Cookies.empty,\n body: Body.uint8Array(body, getContentType(options, headers))\n });\n};\nconst getContentType = (options, headers) => {\n if (options?.contentType) {\n return options.contentType;\n } else if (options?.headers) {\n return headers[\"content-type\"];\n }\n};\n/**\n * Creates an HTTP response whose body is a string.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const text = (body, options) => {\n const headers = options?.headers ? Headers.fromInput(options.headers) : Headers.empty;\n return makeResponse({\n status: options?.status ?? 200,\n statusText: options?.statusText,\n headers,\n cookies: options?.cookies ?? Cookies.empty,\n body: Body.text(body, getContentType(options, headers))\n });\n};\n/**\n * Creates an HTML response with the `text/html` content type.\n *\n * **Details**\n *\n * Passing a string returns a response directly. Using it as a template tag returns\n * an effect so interpolated values can be rendered with their required services\n * and errors.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const html = (strings, ...args) => {\n if (typeof strings === \"string\") {\n return text(strings, {\n contentType: \"text/html\"\n });\n }\n return Effect.map(Template.make(strings, ...args), _ => text(_, {\n contentType: \"text/html\"\n }));\n};\n/**\n * Creates a streaming HTML response from a template.\n *\n * **Details**\n *\n * The template is encoded as a byte stream and can use streaming interpolated\n * values from the current context.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const htmlStream = (strings, ...args) => Effect.map(Effect.context(), context => stream(Stream.provideContext(Stream.encodeText(Template.stream(strings, ...args)), context), {\n contentType: \"text/html\"\n}));\n/**\n * Creates a JSON HTTP response.\n *\n * **Details**\n *\n * The body is serialized with `JSON.stringify`; serialization errors are captured\n * as `HttpBodyError` failures.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const json = (body, options) => {\n const headers = options?.headers ? Headers.fromInput(options.headers) : Headers.empty;\n return Effect.map(Body.json(body, getContentType(options, headers)), body => makeResponse({\n status: options?.status ?? 200,\n statusText: options?.statusText,\n headers,\n cookies: options?.cookies,\n body\n }));\n};\n/**\n * Creates a JSON response constructor backed by a schema encoder.\n *\n * **Details**\n *\n * The returned function encodes the value with the supplied schema before\n * serializing it as JSON, and can fail with `HttpBodyError` if schema encoding or\n * JSON serialization fails.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const schemaJson = (schema, options) => {\n const encode = Body.jsonSchema(schema, options);\n return (body, options) => {\n const headers = options?.headers ? Headers.fromInput(options.headers) : Headers.empty;\n return Effect.map(encode(body, getContentType(options, headers)), body => makeResponse({\n status: options?.status ?? 200,\n statusText: options?.statusText,\n headers,\n cookies: options?.cookies,\n body\n }));\n };\n};\n/**\n * Creates a JSON HTTP response synchronously.\n *\n * **When to use**\n *\n * Use when the response body is known to be JSON-serializable and you need a\n * synchronous `HttpServerResponse`.\n *\n * **Gotchas**\n *\n * Unlike `json`, serialization errors from `JSON.stringify` are not captured in\n * `Effect`.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const jsonUnsafe = (body, options) => {\n const headers = options?.headers ? Headers.fromInput(options.headers) : Headers.empty;\n return makeResponse({\n status: options?.status ?? 200,\n statusText: options?.statusText,\n headers,\n cookies: options?.cookies,\n body: Body.jsonUnsafe(body, getContentType(options, headers))\n });\n};\n/**\n * Creates a response from URL parameters using the\n * `application/x-www-form-urlencoded` content type by default.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const urlParams = (body, options) => {\n const headers = options?.headers ? Headers.fromInput(options.headers) : Headers.empty;\n return makeResponse({\n status: options?.status ?? 200,\n statusText: options?.statusText,\n headers,\n cookies: options?.cookies,\n body: Body.text(UrlParams.toString(UrlParams.fromInput(body)), getContentType(options, headers) ?? \"application/x-www-form-urlencoded\")\n });\n};\n/**\n * Creates a response with a raw body value.\n *\n * **When to use**\n *\n * Use when you want to pass through a body value already understood by the\n * underlying runtime, such as a Web `Response`, `Blob`, or `ReadableStream`,\n * for later platform conversion.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const raw = (body, options) => makeResponse({\n status: options?.status ?? 200,\n statusText: options?.statusText,\n headers: options?.headers && Headers.fromInput(options.headers),\n cookies: options?.cookies,\n body: Body.raw(body, {\n contentType: options?.contentType,\n contentLength: options?.contentLength\n })\n});\n/**\n * Creates a response whose body is a Web `FormData` value.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const formData = (body, options) => makeResponse({\n status: options?.status ?? 200,\n statusText: options?.statusText,\n headers: options?.headers && Headers.fromInput(options.headers),\n cookies: options?.cookies,\n body: Body.formData(body)\n});\n/**\n * Creates a streaming response from a stream of byte chunks.\n *\n * **Details**\n *\n * Optional response metadata can supply the status, headers, content type, and\n * content length.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const stream = (body, options) => {\n const headers = options?.headers ? Headers.fromInput(options.headers) : Headers.empty;\n return makeResponse({\n status: options?.status ?? 200,\n statusText: options?.statusText,\n headers,\n cookies: options?.cookies,\n body: Body.stream(body, getContentType(options, headers), options?.contentLength)\n });\n};\nconst HttpPlatformKey = /*#__PURE__*/Context.Service(\"effect/http/HttpPlatform\");\n/**\n * Creates a streamed file response for a file system path.\n *\n * **Details**\n *\n * The effect requires `HttpPlatform`, can fail with a platform error, and supports\n * options for status, headers, offset, and byte range.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const file = (path, options) => Effect.flatMap(HttpPlatformKey, platform => platform.fileResponse(path, options));\n/**\n * Creates a streamed file response for a Web `File`-like value.\n *\n * **Details**\n *\n * The effect requires `HttpPlatform` and supports options for status, headers,\n * offset, and byte range.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fileWeb = (file, options) => Effect.flatMap(HttpPlatformKey, platform => platform.fileWebResponse(file, options));\n/**\n * Returns a response with the specified header set to the supplied value.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const setHeader = /*#__PURE__*/dual(3, (self, key, value) => makeResponse({\n ...self,\n headers: Headers.set(self.headers, key, value)\n}));\n/**\n * Returns a response with all supplied headers set on the existing header map.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const setHeaders = /*#__PURE__*/dual(2, (self, input) => makeResponse({\n ...self,\n headers: Headers.setAll(self.headers, input)\n}));\n/**\n * Returns a response with the cookie of the specified name removed.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const removeCookie = /*#__PURE__*/dual(2, (self, name) => makeResponse({\n ...self,\n cookies: Cookies.remove(self.cookies, name)\n}));\n/**\n * Returns a response with its cookie collection replaced by the supplied cookies.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const replaceCookies = /*#__PURE__*/dual(2, (self, cookies) => makeResponse({\n ...self,\n cookies\n}));\n/**\n * Sets a cookie on the response.\n *\n * **Details**\n *\n * The effect fails with `CookiesError` if the cookie name, value, or options are\n * invalid.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const setCookie = /*#__PURE__*/dual(args => isHttpServerResponse(args[0]), (self, name, value, options) => Effect.map(Effect.fromResult(Cookies.set(self.cookies, name, value, options)), cookies => makeResponse({\n ...self,\n cookies\n})));\n/**\n * Sets an expired cookie on an `HttpServerResponse`.\n *\n * **Details**\n *\n * Returns an effect because cookie encoding can fail. The original response is not\n * mutated; the effect succeeds with a response containing the updated cookie set.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const expireCookie = /*#__PURE__*/dual(args => isHttpServerResponse(args[0]), (self, name, options) => Effect.map(Effect.fromResult(Cookies.expireCookie(self.cookies, name, options)), cookies => makeResponse({\n ...self,\n cookies\n})));\n/**\n * Sets a cookie on an `HttpServerResponse`, throwing if the cookie cannot be\n * encoded.\n *\n * **When to use**\n *\n * Use when you need to set one trusted cookie and want encoding failures to\n * throw instead of being represented as `CookiesError` failures.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const setCookieUnsafe = /*#__PURE__*/dual(args => isHttpServerResponse(args[0]), (self, name, value, options) => makeResponse({\n ...self,\n cookies: Cookies.setUnsafe(self.cookies, name, value, options)\n}));\n/**\n * Sets an expired cookie on an `HttpServerResponse`, throwing if the expiration cookie\n * cannot be encoded.\n *\n * **When to use**\n *\n * Use when you need to expire one trusted cookie and want encoding failures to\n * throw instead of being represented as `CookiesError` failures.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const expireCookieUnsafe = /*#__PURE__*/dual(args => isHttpServerResponse(args[0]), (self, name, options) => makeResponse({\n ...self,\n cookies: Cookies.expireCookieUnsafe(self.cookies, name, options)\n}));\n/**\n * Updates the cookies attached to an `HttpServerResponse` using the supplied\n * function.\n *\n * **Details**\n *\n * The original response is not mutated; a new response is returned with the\n * callback result as its cookie collection.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const updateCookies = /*#__PURE__*/dual(2, (self, f) => makeResponse({\n ...self,\n cookies: f(self.cookies)\n}));\n/**\n * Merges additional cookies into the cookies attached to an\n * `HttpServerResponse`.\n *\n * **Details**\n *\n * The original response is not mutated; a new response is returned with the merged\n * cookie collection.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const mergeCookies = /*#__PURE__*/dual(2, (self, cookies) => makeResponse({\n ...self,\n cookies: Cookies.merge(self.cookies, cookies)\n}));\n/**\n * Sets multiple cookies on an `HttpServerResponse`.\n *\n * **Details**\n *\n * Each input entry contains a cookie name, value, and optional cookie options. The\n * returned effect fails with `CookiesError` if any cookie cannot be encoded.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const setCookies = /*#__PURE__*/dual(2, (self, cookies) => Effect.map(Effect.fromResult(Cookies.setAll(self.cookies, cookies)), cookies => makeResponse({\n ...self,\n cookies\n})));\n/**\n * Sets multiple cookies on an `HttpServerResponse`, throwing if any cookie cannot\n * be encoded.\n *\n * **When to use**\n *\n * Use when you need to set multiple trusted cookies and want encoding failures\n * to throw instead of being represented as `CookiesError` failures.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const setCookiesUnsafe = /*#__PURE__*/dual(2, (self, cookies) => makeResponse({\n ...self,\n cookies: Cookies.setAllUnsafe(self.cookies, cookies)\n}));\n/**\n * Replaces the body of an `HttpServerResponse`.\n *\n * **Details**\n *\n * When the body carries a content type or content length, the returned response\n * includes the corresponding headers.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const setBody = /*#__PURE__*/dual(2, (self, body) => makeResponse({\n ...self,\n body\n}));\n/**\n * Sets the HTTP status code of an `HttpServerResponse`.\n *\n * **Details**\n *\n * When `statusText` is omitted, the existing status text is preserved.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const setStatus = /*#__PURE__*/dual(args => isHttpServerResponse(args[0]), (self, status, statusText) => makeResponse({\n ...self,\n status,\n statusText: statusText ?? self.statusText\n}));\n/**\n * Converts an `HttpServerResponse` to a Web `Response`.\n *\n * **Details**\n *\n * Cookies are appended as `Set-Cookie` headers. Stream bodies are converted using\n * the supplied context, and `withoutBody` can be used for responses such as HEAD\n * responses.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toWeb = (response, options) => {\n const headers = new globalThis.Headers(response.headers);\n if (!Cookies.isEmpty(response.cookies)) {\n const toAdd = Cookies.toSetCookieHeaders(response.cookies);\n for (const header of toAdd) {\n headers.append(\"set-cookie\", header);\n }\n }\n if (options?.withoutBody) {\n return new Response(undefined, {\n status: response.status,\n statusText: response.statusText,\n headers\n });\n }\n const body = response.body;\n switch (body._tag) {\n case \"Empty\":\n {\n return new Response(undefined, {\n status: response.status,\n statusText: response.statusText,\n headers\n });\n }\n case \"Uint8Array\":\n case \"Raw\":\n {\n if (body.body instanceof Response) {\n for (const [key, value] of headers) {\n body.body.headers.set(key, value);\n }\n return body.body;\n }\n return new Response(body.body, {\n status: response.status,\n statusText: response.statusText,\n headers\n });\n }\n case \"FormData\":\n {\n return new Response(body.formData, {\n status: response.status,\n statusText: response.statusText,\n headers\n });\n }\n case \"Stream\":\n {\n return new Response(Stream.toReadableStreamWith(body.stream, options?.context ?? Context.empty()), {\n status: response.status,\n statusText: response.statusText,\n headers\n });\n }\n }\n};\n/**\n * Wraps an `HttpServerResponse` as an `HttpClientResponse`.\n *\n * **Details**\n *\n * An optional request can be supplied for client-response metadata and decode\n * errors.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toClientResponse = (response, options) => new ServerHttpClientResponse(options?.request ?? HttpClientRequest.empty, response);\nclass ServerHttpClientResponse extends Inspectable.Class {\n [HttpIncomingMessage.TypeId];\n [HttpClientResponse.TypeId];\n request;\n response;\n constructor(request, response) {\n super();\n this.request = request;\n this.response = response;\n this[HttpIncomingMessage.TypeId] = HttpIncomingMessage.TypeId;\n this[HttpClientResponse.TypeId] = HttpClientResponse.TypeId;\n }\n toJSON() {\n return HttpIncomingMessage.inspect(this, {\n _id: \"HttpClientResponse\",\n request: this.request.toJSON(),\n status: this.status\n });\n }\n get status() {\n return this.response.status;\n }\n cachedHeaders;\n get headers() {\n return this.cachedHeaders ??= this.response.body._tag === \"FormData\" ? Headers.merge(this.response.headers, Headers.fromInput(this.getFormDataResponse().headers)) : this.response.headers;\n }\n get cookies() {\n return this.response.cookies;\n }\n get remoteAddress() {\n return Option.none();\n }\n get stream() {\n const body = this.response.body;\n switch (body._tag) {\n case \"Empty\":\n {\n return Stream.empty;\n }\n case \"Stream\":\n {\n return Stream.mapError(body.stream, cause => this.decodeError(cause));\n }\n case \"Uint8Array\":\n {\n return Stream.succeed(body.body);\n }\n case \"Raw\":\n {\n const rawBody = body.body;\n if (rawBody instanceof Response) {\n return rawBody.body ? Stream.fromReadableStream({\n evaluate: () => rawBody.body,\n onError: cause => this.decodeError(cause)\n }) : Stream.empty;\n }\n if (isReadableStream(rawBody)) {\n return Stream.fromReadableStream({\n evaluate: () => rawBody,\n onError: cause => this.decodeError(cause)\n });\n }\n if (rawBody instanceof Blob) {\n return Stream.fromReadableStream({\n evaluate: () => rawBody.stream(),\n onError: cause => this.decodeError(cause)\n });\n }\n return Stream.unwrap(Effect.map(this.bytes, Stream.succeed));\n }\n case \"FormData\":\n {\n const response = this.getFormDataResponse();\n return Stream.fromReadableStream({\n evaluate: () => response.body,\n onError: cause => this.decodeError(cause)\n });\n }\n }\n }\n get json() {\n return Effect.flatMap(this.text, text => Effect.try({\n try: () => text === \"\" ? null : JSON.parse(text),\n catch: cause => new HttpClientError.HttpClientError({\n reason: new HttpClientError.DecodeError({\n request: this.request,\n response: this,\n cause\n })\n })\n }));\n }\n get bytes() {\n const body = this.response.body;\n switch (body._tag) {\n case \"Empty\":\n {\n return Effect.succeed(new Uint8Array(0));\n }\n case \"Uint8Array\":\n {\n return Effect.succeed(body.body);\n }\n case \"Stream\":\n {\n return Stream.mkUint8Array(this.stream);\n }\n case \"Raw\":\n {\n const rawBody = body.body;\n if (rawBody instanceof Response) {\n return Effect.tryPromise({\n try: () => rawBody.arrayBuffer().then(buffer => new Uint8Array(buffer)),\n catch: cause => this.decodeError(cause)\n });\n }\n return Effect.tryPromise({\n try: () => new Response(rawBody).arrayBuffer().then(buffer => new Uint8Array(buffer)),\n catch: cause => this.decodeError(cause)\n });\n }\n case \"FormData\":\n {\n return Effect.tryPromise({\n try: () => new Response(body.formData).arrayBuffer().then(buffer => new Uint8Array(buffer)),\n catch: cause => this.decodeError(cause)\n });\n }\n }\n }\n get text() {\n return Effect.map(this.bytes, bytes => textDecoder.decode(bytes));\n }\n get urlParamsBody() {\n return Effect.flatMap(this.text, _ => Effect.try({\n try: () => UrlParams.fromInput(new URLSearchParams(_)),\n catch: cause => new HttpClientError.HttpClientError({\n reason: new HttpClientError.DecodeError({\n request: this.request,\n response: this,\n cause\n })\n })\n }));\n }\n get formData() {\n const body = this.response.body;\n if (body._tag === \"FormData\") {\n return Effect.succeed(body.formData);\n }\n return Effect.contextWith(context => {\n const readableStream = Stream.toReadableStreamWith(this.stream, context);\n return Effect.tryPromise({\n try: () => new Response(readableStream, {\n headers: this.headers\n }).formData(),\n catch: cause => this.decodeError(cause)\n });\n });\n }\n get arrayBuffer() {\n return Effect.map(this.bytes, bytes => bytes.slice().buffer);\n }\n decodeError(cause) {\n return new HttpClientError.HttpClientError({\n reason: new HttpClientError.DecodeError({\n request: this.request,\n response: this,\n cause\n })\n });\n }\n formDataResponse;\n getFormDataResponse() {\n return this.formDataResponse ??= new Response(this.response.body.formData);\n }\n pipe() {\n return pipeArguments(this, arguments);\n }\n}\nconst textDecoder = /*#__PURE__*/new TextDecoder();\n/**\n * Converts an `HttpClientResponse` to an `HttpServerResponse`.\n *\n * **Details**\n *\n * The response body is streamed from the client response. `Set-Cookie` headers are\n * removed from the header map and represented in the response cookie collection.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const fromClientResponse = response => {\n const headers = Headers.remove(response.headers, \"set-cookie\");\n return makeResponse({\n status: response.status,\n headers,\n cookies: response.cookies,\n body: Body.stream(Stream.catchIf(response.stream, isEmptyBodyError, () => Stream.empty), Option.getOrUndefined(Headers.get(headers, \"content-type\")), getContentLength(headers))\n });\n};\nconst isReadableStream = u => typeof ReadableStream !== \"undefined\" && u instanceof ReadableStream;\nconst isEmptyBodyError = error => HttpClientError.isHttpClientError(error) && error.reason._tag === \"EmptyBodyError\";\nconst getContentLength = headers => {\n const contentLength = Option.getOrUndefined(Headers.get(headers, \"content-length\"));\n if (contentLength === undefined) {\n return undefined;\n }\n const parsed = Number(contentLength);\n return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;\n};\nconst Proto = {\n ...PipeInspectableProto,\n [TypeId]: TypeId,\n [ErrorReporter.ignore]: true,\n toJSON() {\n return {\n _id: \"HttpServerResponse\",\n status: this.status,\n statusText: this.statusText,\n headers: redact(this.headers),\n cookies: this.cookies.toJSON(),\n body: this.body.toJSON()\n };\n }\n};\nconst makeResponse = options => {\n const self = Object.create(Proto);\n self.status = options.status;\n self.statusText = options.statusText;\n self.cookies = options.cookies ?? Cookies.empty;\n self.body = options.body ?? Body.empty;\n if (self.body._tag !== \"Empty\" && (self.body.contentType || self.body.contentLength)) {\n const newHeaders = Headers.fromRecordUnsafe({\n ...options.headers\n });\n if (self.body.contentType) {\n newHeaders[\"content-type\"] = self.body.contentType;\n }\n if (self.body.contentLength) {\n newHeaders[\"content-length\"] = self.body.contentLength.toString();\n }\n self.headers = newHeaders;\n } else {\n self.headers = options.headers ?? Headers.empty;\n }\n return self;\n};\n/**\n * Converts a Web `Response` to an `HttpServerResponse`.\n *\n * **Details**\n *\n * `Set-Cookie` headers are parsed into the response cookie collection and removed\n * from the header map. A present Web body is exposed as a stream body.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const fromWeb = response => {\n const headers = new globalThis.Headers(response.headers);\n const setCookieHeaders = headers.getSetCookie();\n headers.delete(\"set-cookie\");\n let self = empty({\n status: response.status,\n statusText: response.statusText,\n headers: headers,\n cookies: Cookies.fromSetCookie(setCookieHeaders)\n });\n if (response.body) {\n const contentType = response.headers.get(\"content-type\");\n self = setBody(self, Body.stream(Stream.fromReadableStream({\n evaluate: () => response.body,\n onError: e => e\n }), contentType ?? undefined));\n }\n return self;\n};\n//# sourceMappingURL=HttpServerResponse.js.map","/**\n * Converts supported values into HTTP server responses.\n *\n * Server-side errors and helper values can implement `Respondable` when they\n * know which status, headers, cookies, or body should be sent to the client.\n * This module detects those values and converts them to `HttpServerResponse`\n * values, with fallback handling for schema errors and missing values.\n *\n * @since 4.0.0\n */\nimport * as Cause from \"../../Cause.js\";\nimport * as Effect from \"../../Effect.js\";\nimport { hasProperty } from \"../../Predicate.js\";\nimport * as Schema from \"../../Schema.js\";\nimport * as Response from \"./HttpServerResponse.js\";\n/**\n * Protocol key used by values that can render themselves as\n * `HttpServerResponse` values.\n *\n * @category type IDs\n * @since 4.0.0\n */\nexport const symbol = \"~effect/http/HttpServerRespondable\";\n/**\n * Returns `true` when the supplied value implements the `Respondable` protocol.\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isRespondable = u => hasProperty(u, symbol);\nconst badRequest = /*#__PURE__*/Response.empty({\n status: 400\n});\nconst notFound = /*#__PURE__*/Response.empty({\n status: 404\n});\n/**\n * Converts a `Respondable` value into an `HttpServerResponse`.\n *\n * **Details**\n *\n * If the value is already an HTTP server response it is returned directly; errors\n * from the response conversion are converted to defects.\n *\n * @category accessors\n * @since 4.0.0\n */\nexport const toResponse = self => {\n if (Response.isHttpServerResponse(self)) {\n return Effect.succeed(self);\n }\n return Effect.orDie(self[symbol]());\n};\n/**\n * Attempts to convert an unknown value into an `HttpServerResponse`, falling back\n * to the supplied response when no conversion is available.\n *\n * **Details**\n *\n * `HttpServerResponse` and `Respondable` values are used directly, schema errors\n * become `400` responses, and no-such-element errors become `404` responses.\n *\n * @category accessors\n * @since 4.0.0\n */\nexport const toResponseOrElse = (u, orElse) => {\n if (Response.isHttpServerResponse(u)) {\n return Effect.succeed(u);\n } else if (isRespondable(u)) {\n return Effect.catchCause(u[symbol](), () => Effect.succeed(orElse));\n // add support for some commmon types\n } else if (Schema.isSchemaError(u)) {\n return Effect.succeed(badRequest);\n } else if (Cause.isNoSuchElementError(u)) {\n return Effect.succeed(notFound);\n }\n return Effect.succeed(orElse);\n};\n/**\n * Attempts to convert an unknown defect into an `HttpServerResponse`, falling\n * back to the supplied response when no conversion is available.\n *\n * **Details**\n *\n * Only `HttpServerResponse` and `Respondable` values receive special handling.\n *\n * @category accessors\n * @since 4.0.0\n */\nexport const toResponseOrElseDefect = (u, orElse) => {\n if (Response.isHttpServerResponse(u)) {\n return Effect.succeed(u);\n } else if (isRespondable(u)) {\n return Effect.catchCause(u[symbol](), () => Effect.succeed(orElse));\n }\n return Effect.succeed(orElse);\n};\n//# sourceMappingURL=HttpServerRespondable.js.map","/**\n * Describes failures raised while handling HTTP server requests.\n *\n * `HttpServerError` covers failures that happen while accepting a request,\n * matching a route, running a handler, or building and sending a response.\n * Request-scoped failures keep the request that caused them, and response\n * failures keep the response being produced. This module also includes helpers\n * for turning failed causes or exits into HTTP responses and an annotation for\n * interrupts caused by client aborts.\n *\n * @since 4.0.0\n */\nimport * as Cause from \"../../Cause.js\";\nimport * as Context from \"../../Context.js\";\nimport * as Data from \"../../Data.js\";\nimport * as Effect from \"../../Effect.js\";\nimport * as ErrorReporter from \"../../ErrorReporter.js\";\nimport { constUndefined } from \"../../Function.js\";\nimport * as Option from \"../../Option.js\";\nimport { hasProperty } from \"../../Predicate.js\";\nimport * as Respondable from \"./HttpServerRespondable.js\";\nimport * as Response from \"./HttpServerResponse.js\";\nconst TypeId = \"~effect/http/HttpServerError\";\n/**\n * Tagged error for failures that occur while handling an HTTP server request.\n *\n * **Details**\n *\n * It wraps a `HttpServerErrorReason`, exposes the associated request and optional\n * response, and can be converted to an HTTP response through the `Respondable`\n * protocol.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class HttpServerError extends /*#__PURE__*/Data.TaggedError(\"HttpServerError\") {\n constructor(props) {\n if (\"cause\" in props.reason) {\n super({\n ...props,\n cause: props.reason.cause\n });\n } else {\n super(props);\n }\n }\n [TypeId] = TypeId;\n stack = `${this.name}: ${this.message}`;\n get request() {\n return this.reason.request;\n }\n get response() {\n return \"response\" in this.reason ? this.reason.response : undefined;\n }\n [Respondable.symbol]() {\n return this.reason[Respondable.symbol]();\n }\n get [ErrorReporter.ignore]() {\n return this.reason[ErrorReporter.ignore] ?? false;\n }\n get message() {\n return this.reason.message;\n }\n}\n/**\n * Error describing a failure to parse or read an incoming request.\n *\n * **Details**\n *\n * When converted to a response it produces an empty `400` response.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class RequestParseError extends /*#__PURE__*/Data.TaggedError(\"RequestParseError\") {\n /**\n * Converts the request error into a `400 Bad Request` response.\n *\n * @since 4.0.0\n */\n [Respondable.symbol]() {\n return Effect.succeed(Response.empty({\n status: 400\n }));\n }\n get methodAndUrl() {\n return `${this.request.method} ${this.request.url}`;\n }\n get message() {\n return formatRequestMessage(this._tag, this.description, this.methodAndUrl);\n }\n}\n/**\n * Error indicating that no route matched the incoming request.\n *\n * **Details**\n *\n * When converted to a response it produces an empty `404` response, and it is\n * ignored by the error reporter.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class RouteNotFound extends /*#__PURE__*/Data.TaggedError(\"RouteNotFound\") {\n [Respondable.symbol]() {\n return Effect.succeed(Response.empty({\n status: 404\n }));\n }\n [ErrorReporter.ignore] = true;\n get methodAndUrl() {\n return `${this.request.method} ${this.request.url}`;\n }\n get message() {\n return formatRequestMessage(this._tag, this.description, this.methodAndUrl);\n }\n}\n/**\n * Error describing an unexpected server-side failure while handling a request.\n *\n * **Details**\n *\n * When converted to a response it produces an empty `500` response.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class InternalError extends /*#__PURE__*/Data.TaggedError(\"InternalError\") {\n /**\n * Converts the server error into a `500 Internal Server Error` response.\n *\n * @since 4.0.0\n */\n [Respondable.symbol]() {\n return Effect.succeed(Response.empty({\n status: 500\n }));\n }\n get methodAndUrl() {\n return `${this.request.method} ${this.request.url}`;\n }\n get message() {\n return formatRequestMessage(this._tag, this.description, this.methodAndUrl);\n }\n}\n/**\n * Returns `true` when the supplied value is an `HttpServerError`.\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const isHttpServerError = u => hasProperty(u, TypeId);\n/**\n * Error describing a failure related to an HTTP response.\n *\n * **Details**\n *\n * It carries the request and response involved in the failure. When converted to\n * a response it produces an empty `500` response.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class ResponseError extends /*#__PURE__*/Data.TaggedError(\"ResponseError\") {\n [Respondable.symbol]() {\n return Effect.succeed(Response.empty({\n status: 500\n }));\n }\n get methodAndUrl() {\n return `${this.request.method} ${this.request.url}`;\n }\n get message() {\n const info = `${this._tag} (${this.response.status} ${this.methodAndUrl})`;\n return this.description ? `${info}: ${this.description}` : info;\n }\n}\n/**\n * Error wrapping a low-level failure from the HTTP server implementation.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class ServeError extends /*#__PURE__*/Data.TaggedError(\"ServeError\") {}\n/**\n * Context annotation used to mark an interrupt as caused by the client aborting\n * the request.\n *\n * **Details**\n *\n * `causeResponse` uses this annotation to map a pure client abort to a `499`\n * response instead of a server abort response.\n *\n * @category annotations\n * @since 4.0.0\n */\nexport class ClientAbort extends /*#__PURE__*/Context.Service()(\"effect/http/HttpServerError/ClientAbort\") {\n static annotation = /*#__PURE__*/this.context(true).pipe(/*#__PURE__*/Context.add(Cause.StackTrace, {\n name: \"ClientAbort\",\n stack: constUndefined,\n parent: undefined\n }));\n}\nconst formatRequestMessage = (reason, description, info) => {\n const prefix = `${reason} (${info})`;\n return description ? `${prefix}: ${description}` : prefix;\n};\n/**\n * Converts a failed handler cause into the HTTP response that should be sent and\n * the cause that should be reported.\n *\n * **Details**\n *\n * Respondable failures and defects can choose their own response, defects that\n * are already `HttpServerResponse` values are used directly, and pure interrupts\n * produce either `499` for client aborts or `503` for server aborts.\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const causeResponse = cause => {\n let response;\n let effect = succeedInternalServerError;\n const failures = [];\n let interrupts = [];\n let isClientInterrupt = false;\n for (let i = 0; i < cause.reasons.length; i++) {\n const reason = cause.reasons[i];\n switch (reason._tag) {\n case \"Fail\":\n {\n effect = Respondable.toResponseOrElse(reason.error, internalServerError);\n failures.push(reason);\n break;\n }\n case \"Die\":\n {\n if (Response.isHttpServerResponse(reason.defect)) {\n response = reason.defect;\n } else {\n effect = Respondable.toResponseOrElseDefect(reason.defect, internalServerError);\n failures.push(reason);\n }\n break;\n }\n case \"Interrupt\":\n {\n isClientInterrupt = reason.annotations.has(ClientAbort.key);\n if (failures.length > 0) break;\n interrupts.push(reason);\n break;\n }\n }\n }\n if (response) {\n return Effect.succeed([response, Cause.fromReasons(failures)]);\n } else if (interrupts.length > 0 && failures.length === 0) {\n failures.push(...interrupts);\n effect = isClientInterrupt ? clientAbortError : serverAbortError;\n }\n return Effect.mapEager(effect, response => {\n failures.push(Cause.makeDieReason(response));\n return [response, Cause.fromReasons(failures)];\n });\n};\n/**\n * Derives an HTTP response from a failed handler cause synchronously.\n *\n * **Details**\n *\n * If the cause contains a defect that is already an `HttpServerResponse`, that\n * response is used and removed from the remaining cause. Otherwise the response\n * defaults to `500`.\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const causeResponseStripped = cause => {\n let response;\n const failures = cause.reasons.filter(f => {\n if (f._tag === \"Die\" && Response.isHttpServerResponse(f.defect)) {\n response = f.defect;\n return false;\n }\n return true;\n });\n return [response ?? internalServerError, failures.length > 0 ? Option.some(Cause.fromReasons(failures)) : Option.none()];\n};\nconst internalServerError = /*#__PURE__*/Response.empty({\n status: 500\n});\nconst succeedInternalServerError = /*#__PURE__*/Effect.succeed(internalServerError);\nconst clientAbortError = /*#__PURE__*/Effect.succeed(/*#__PURE__*/Response.empty({\n status: 499\n}));\nconst serverAbortError = /*#__PURE__*/Effect.succeed(/*#__PURE__*/Response.empty({\n status: 503\n}));\n/**\n * Extracts the response from a successful handler exit, or derives a response\n * from the failure cause.\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const exitResponse = exit => {\n if (exit._tag === \"Success\") {\n return exit.value;\n }\n return causeResponseStripped(exit.cause)[0];\n};\n//# sourceMappingURL=HttpServerError.js.map","import * as Channel from \"../../Channel.js\";\nimport * as Context from \"../../Context.js\";\nimport * as Deferred from \"../../Deferred.js\";\nimport * as Effect from \"../../Effect.js\";\nimport * as Exit from \"../../Exit.js\";\nimport * as FiberSet from \"../../FiberSet.js\";\nimport { constVoid, dual, flow } from \"../../Function.js\";\nimport * as Latch from \"../../Latch.js\";\nimport * as Layer from \"../../Layer.js\";\nimport * as Predicate from \"../../Predicate.js\";\nimport * as Pull from \"../../Pull.js\";\nimport * as Queue from \"../../Queue.js\";\nimport * as Result from \"../../Result.js\";\nimport * as Schema from \"../../Schema.js\";\nimport * as Scope from \"../../Scope.js\";\n/**\n * Runtime type identifier attached to `Socket` services.\n *\n * @category type IDs\n * @since 4.0.0\n */\nexport const TypeId = \"~effect/socket/Socket\";\n/**\n * Returns `true` when a value is a `Socket`.\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isSocket = u => Predicate.hasProperty(u, TypeId);\n/**\n * Service tag for bidirectional socket transports.\n *\n * **When to use**\n *\n * Use to access or provide the socket implementation used by programs that\n * read and write frames through the Effect environment.\n *\n * @category services\n * @since 4.0.0\n */\nexport const Socket = /*#__PURE__*/Context.Service(\"effect/socket/Socket\");\n/**\n * Constructs a `Socket` from a raw read loop and scoped writer, deriving binary\n * and string read loops when they are not provided.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = options => Socket.of({\n [TypeId]: TypeId,\n runRaw: options.runRaw,\n run: options.run ?? ((handler, opts) => options.runRaw(data => typeof data === \"string\" ? handler(encoder.encode(data)) : data instanceof Uint8Array ? handler(data) : handler(new Uint8Array(data)), opts)),\n runString: options.runString ?? (options.run ? (handler, opts) => options.run(data => handler(decoder.decode(data)), opts) : (handler, opts) => options.runRaw(data => typeof data === \"string\" ? handler(data) : data instanceof Uint8Array ? handler(decoder.decode(data)) : handler(decoder.decode(new Uint8Array(data))), opts)),\n writer: options.writer\n});\nconst encoder = /*#__PURE__*/new TextEncoder();\nconst decoder = /*#__PURE__*/new TextDecoder();\nconst CloseEventTypeId = \"~effect/socket/Socket/CloseEvent\";\n/**\n * Represents a socket close event value carrying a close code and optional\n * reason.\n *\n * @category models\n * @since 4.0.0\n */\nexport class CloseEvent {\n /**\n * Marks this value as a socket close event for runtime guards.\n *\n * @since 4.0.0\n */\n [CloseEventTypeId];\n code;\n reason;\n constructor(code = 1000, reason) {\n this[CloseEventTypeId] = CloseEventTypeId;\n this.code = code;\n this.reason = reason;\n }\n /**\n * Formats the close code and optional reason for display.\n *\n * @since 4.0.0\n */\n toString() {\n return this.reason ? `${this.code}: ${this.reason}` : `${this.code}`;\n }\n}\n/**\n * Returns `true` when a value is a `CloseEvent`.\n *\n * @category refinements\n * @since 4.0.0\n */\nexport const isCloseEvent = u => Predicate.hasProperty(u, CloseEventTypeId);\n/**\n * Runtime type identifier attached to `SocketError` values.\n *\n * @category type IDs\n * @since 4.0.0\n */\nexport const SocketErrorTypeId = \"~effect/socket/Socket/SocketError\";\n/**\n * Returns `true` when a value is a `SocketError`.\n *\n * @category refinements\n * @since 4.0.0\n */\nexport const isSocketError = u => Predicate.hasProperty(u, SocketErrorTypeId);\n/**\n * Typed error for failures that occur while reading from a socket.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class SocketReadError extends /*#__PURE__*/Schema.ErrorClass(\"effect/socket/Socket/SocketReadError\")({\n _tag: /*#__PURE__*/Schema.tag(\"SocketReadError\"),\n cause: /*#__PURE__*/Schema.Defect()\n}) {\n /**\n * Default message used for socket read failures.\n *\n * @since 4.0.0\n */\n message = `An error occurred during Read`;\n}\n/**\n * Typed error for failures that occur while writing to a socket.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class SocketWriteError extends /*#__PURE__*/Schema.ErrorClass(\"effect/socket/Socket/SocketWriteError\")({\n _tag: /*#__PURE__*/Schema.tag(\"SocketWriteError\"),\n cause: /*#__PURE__*/Schema.Defect()\n}) {\n /**\n * Default message used for socket write failures.\n *\n * @since 4.0.0\n */\n message = `An error occurred during Write`;\n}\n/**\n * Typed error for failures that occur while opening a socket, including\n * unknown open failures and open timeouts.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class SocketOpenError extends /*#__PURE__*/Schema.ErrorClass(\"effect/socket/Socket/SocketOpenError\")({\n _tag: /*#__PURE__*/Schema.tag(\"SocketOpenError\"),\n kind: /*#__PURE__*/Schema.Literals([\"Unknown\", \"Timeout\"]),\n cause: /*#__PURE__*/Schema.Defect()\n}) {\n /**\n * Formats timeout and unknown open failures for display.\n *\n * @since 4.0.0\n */\n get message() {\n return this.kind === \"Timeout\" ? `timeout waiting for \"open\"` : `An error occurred during Open`;\n }\n}\n/**\n * Typed error for a socket close event, carrying the close code and optional\n * close reason.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class SocketCloseError extends /*#__PURE__*/Schema.ErrorClass(\"effect/socket/Socket/SocketCloseError\")({\n _tag: /*#__PURE__*/Schema.tag(\"SocketCloseError\"),\n code: Schema.Number,\n closeReason: /*#__PURE__*/Schema.optional(Schema.String)\n}) {\n /**\n * Separates clean socket close errors from errors that should remain failures.\n *\n * @since 4.0.0\n */\n static filterClean(isClean) {\n return function (u) {\n return SocketError.is(u) && u.reason._tag === \"SocketCloseError\" && isClean(u.reason.code) ? Result.succeed(u.reason) : Result.fail(u);\n };\n }\n get message() {\n if (this.closeReason) {\n return `${this.code}: ${this.closeReason}`;\n }\n return `${this.code}`;\n }\n}\n/**\n * Schema for all socket-specific error reasons.\n *\n * @category errors\n * @since 4.0.0\n */\nexport const SocketErrorReason = /*#__PURE__*/Schema.Union([SocketReadError, SocketWriteError, SocketOpenError, SocketCloseError]);\n/**\n * Tagged error that wraps socket read, write, open, and close failures while\n * preserving the underlying reason.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class SocketError extends /*#__PURE__*/Schema.TaggedErrorClass(SocketErrorTypeId)(\"SocketError\", {\n _tag: /*#__PURE__*/Schema.tag(\"SocketError\"),\n reason: SocketErrorReason\n}) {\n // @effect-diagnostics-next-line overriddenSchemaConstructor:off\n constructor(props) {\n if (\"cause\" in props.reason) {\n super({\n ...props,\n cause: props.reason.cause\n });\n } else {\n super(props);\n }\n }\n /**\n * Marks this value as a socket error wrapper for runtime guards.\n *\n * @since 4.0.0\n */\n [SocketErrorTypeId] = SocketErrorTypeId;\n /**\n * Returns `true` when the value is a `SocketError`.\n *\n * @since 4.0.0\n */\n static is(u) {\n return isSocketError(u);\n }\n message = this.reason.message;\n}\n/**\n * Converts a `Socket` into a bidirectional `Channel`, mapping incoming string\n * or binary frames and writing outgoing frame batches to the socket.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const toChannelMap = (self, f) => Channel.fromTransform(Effect.fnUntraced(function* (upstream, scope) {\n const queue = yield* Queue.make();\n const writeScope = yield* Scope.fork(scope);\n const write = yield* Scope.provide(self.writer, writeScope);\n let chunk;\n let index = 0;\n const writeChunk = Effect.whileLoop({\n while: () => index < chunk.length,\n body: () => write(chunk[index++]),\n step: constVoid\n });\n yield* upstream.pipe(Effect.flatMap(arr => {\n if (arr.length === 1) return write(arr[0]);\n chunk = arr;\n index = 0;\n return writeChunk;\n }), Effect.forever({\n disableYield: true\n }), Effect.catchCauseFilter(Pull.filterNoDone, cause => Queue.failCause(queue, cause)), Effect.ensuring(Scope.close(writeScope, Exit.void)), Effect.forkIn(scope));\n yield* self.runRaw(data => {\n Queue.offerUnsafe(queue, f(data));\n }).pipe(Queue.into(queue), Effect.forkIn(scope));\n // @effect-diagnostics-next-line returnEffectInGen:off\n return Queue.takeAll(queue);\n}));\n/**\n * Converts a `Socket` into a binary `Channel`, encoding incoming string frames\n * as UTF-8 bytes.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const toChannel = self => {\n const encoder = new TextEncoder();\n return toChannelMap(self, data => typeof data === \"string\" ? encoder.encode(data) : data);\n};\n/**\n * Converts a `Socket` into a string `Channel`, decoding binary frames with the\n * optional text encoding.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const toChannelString = /*#__PURE__*/dual(args => isSocket(args[0]), (self, encoding) => {\n const decoder = new TextDecoder(encoding);\n return toChannelMap(self, data => typeof data === \"string\" ? data : decoder.decode(data));\n});\n/**\n * Creates a `Socket` to binary `Channel` adapter with a fixed upstream error\n * type.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const toChannelWith = () => self => toChannel(self);\n/**\n * Creates a binary socket `Channel` from the `Socket` service in the\n * environment.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const makeChannel = () => Channel.unwrap(Effect.map(Socket, toChannelWith()));\n/**\n * Default close-code classifier that treats every socket close code as an\n * error.\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const defaultCloseCodeIsError = _code => true;\n/**\n * Context service for the active `WebSocket` instance available while a\n * WebSocket-backed socket run is handling events.\n *\n * @category services\n * @since 4.0.0\n */\nexport class WebSocket extends /*#__PURE__*/Context.Service()(\"~effect/socket/Socket/WebSocket\") {}\n/**\n * Context service for constructing `WebSocket` instances from a URL and\n * optional protocols.\n *\n * @category services\n * @since 4.0.0\n */\nexport class WebSocketConstructor extends /*#__PURE__*/Context.Service()(\"@effect/platform/Socket/WebSocketConstructor\") {}\n/**\n * Layer that provides `WebSocketConstructor` using `globalThis.WebSocket`.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerWebSocketConstructorGlobal = /*#__PURE__*/Layer.succeed(WebSocketConstructor)((url, protocols) => new globalThis.WebSocket(url, protocols));\n/**\n * Creates a `Socket` backed by a `WebSocketConstructor`, acquiring the\n * WebSocket for each run and using the close-code classifier to decide which\n * closes fail the run.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const makeWebSocket = (url, options) => WebSocketConstructor.use(makeWs => fromWebSocket(Effect.acquireRelease((typeof url === \"string\" ? Effect.succeed(url) : url).pipe(Effect.map(url => makeWs(url, options?.protocols))), ws => Effect.sync(() => ws.close(1000))), options));\n/**\n * Builds a `Socket` from a scoped WebSocket acquisition effect, waiting for the\n * socket to open, dispatching message handlers in fibers, and translating\n * open, read, and close events into `SocketError` values.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromWebSocket = (acquire, options) => Effect.withFiber(fiber => {\n let currentWS;\n const latch = Latch.makeUnsafe(false);\n const acquireContext = fiber.context;\n const closeCodeIsError = options?.closeCodeIsError ?? defaultCloseCodeIsError;\n const runRaw = (handler, opts) => Effect.scopedWith(Effect.fnUntraced(function* (scope) {\n const fiberSet = yield* FiberSet.make().pipe(Scope.provide(scope));\n const ws = yield* Scope.provide(acquire, scope);\n const run = yield* Effect.provideService(FiberSet.runtime(fiberSet)(), WebSocket, ws);\n let open = false;\n function onMessage(event) {\n if (event.data instanceof Blob) {\n const effect = Effect.flatMap(Effect.promise(() => event.data.arrayBuffer()), buffer => {\n const result = handler(new Uint8Array(buffer));\n return Effect.isEffect(result) ? result : Effect.void;\n });\n return run(effect);\n }\n const result = handler(event.data);\n if (Effect.isEffect(result)) {\n run(result);\n }\n }\n function onError(cause) {\n ws.removeEventListener(\"message\", onMessage);\n ws.removeEventListener(\"close\", onClose);\n Deferred.doneUnsafe(fiberSet.deferred, Effect.fail(new SocketError({\n reason: open ? new SocketReadError({\n cause\n }) : new SocketOpenError({\n kind: \"Unknown\",\n cause\n })\n })));\n }\n function onClose(event) {\n const code = typeof event.code === \"number\" ? event.code : 1001;\n ws.removeEventListener(\"message\", onMessage);\n ws.removeEventListener(\"error\", onError);\n Deferred.doneUnsafe(fiberSet.deferred, Effect.fail(new SocketError({\n reason: new SocketCloseError({\n code,\n closeReason: event.reason\n })\n })));\n }\n ws.addEventListener(\"close\", onClose, {\n once: true\n });\n ws.addEventListener(\"error\", onError, {\n once: true\n });\n ws.addEventListener(\"message\", onMessage);\n if (ws.readyState !== 1) {\n const openDeferred = Deferred.makeUnsafe();\n ws.addEventListener(\"open\", () => {\n open = true;\n Deferred.doneUnsafe(openDeferred, Effect.void);\n }, {\n once: true\n });\n yield* Deferred.await(openDeferred).pipe(Effect.timeoutOrElse({\n duration: options?.openTimeout ?? 10000,\n orElse: () => Effect.fail(new SocketError({\n reason: new SocketOpenError({\n kind: \"Timeout\",\n cause: new Error(\"timeout waiting for \\\"open\\\"\")\n })\n }))\n }), Effect.raceFirst(FiberSet.join(fiberSet)));\n }\n open = true;\n currentWS = ws;\n latch.openUnsafe();\n if (opts?.onOpen) yield* opts.onOpen;\n return yield* Effect.catchFilter(FiberSet.join(fiberSet), SocketCloseError.filterClean(_ => !closeCodeIsError(_)), () => Effect.void);\n })).pipe(Effect.updateContext(input => Context.merge(acquireContext, input)), Effect.ensuring(Effect.sync(() => {\n latch.closeUnsafe();\n currentWS = undefined;\n })));\n const write = chunk => latch.whenOpen(Effect.sync(() => {\n const ws = currentWS;\n if (isCloseEvent(chunk)) {\n ws.close(chunk.code, chunk.reason);\n } else {\n ws.send(chunk);\n }\n }));\n const writer = Effect.succeed(write);\n return Effect.succeed(make({\n runRaw,\n writer\n }));\n});\n/**\n * Creates a binary `Channel` backed by a WebSocket URL, requiring a\n * `WebSocketConstructor` service.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const makeWebSocketChannel = (url, options) => Channel.unwrap(Effect.map(makeWebSocket(url, options), toChannelWith()));\n/**\n * Layer that provides a `Socket` service backed by a WebSocket URL or URL\n * effect.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerWebSocket = /*#__PURE__*/flow(makeWebSocket, /*#__PURE__*/Layer.effect(Socket));\n/**\n * Context reference for socket send queue capacity, defaulting to `16`.\n *\n * @category fiber refs\n * @since 4.0.0\n */\nexport const SendQueueCapacity = /*#__PURE__*/Context.Reference(\"~effect/socket/Socket/SendQueueCapacity\", {\n defaultValue: () => 16\n});\n/**\n * Builds a `Socket` from a scoped `InputTransformStream`, reading incoming\n * chunks through socket handlers and writing outgoing chunks to the writable\n * stream, encoding strings as UTF-8 and using close-code classification for\n * `CloseEvent` values.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromTransformStream = (acquire, options) => Effect.withFiber(fiber => {\n const latch = Latch.makeUnsafe(false);\n let currentStream;\n const acquireServices = fiber.context;\n const closeCodeIsError = options?.closeCodeIsError ?? defaultCloseCodeIsError;\n const runRaw = (handler, opts) => Effect.scopedWith(Effect.fnUntraced(function* (scope) {\n const stream = yield* Scope.provide(acquire, scope);\n const reader = stream.readable.getReader();\n yield* Scope.addFinalizer(scope, Effect.promise(() => reader.cancel()));\n const fiberSet = yield* FiberSet.make().pipe(Scope.provide(scope));\n const runFork = yield* FiberSet.runtime(fiberSet)();\n yield* Effect.tryPromise({\n try: async () => {\n while (true) {\n const {\n done,\n value\n } = await reader.read();\n if (done) {\n throw new SocketError({\n reason: new SocketCloseError({\n code: 1000\n })\n });\n }\n const result = handler(value);\n if (Effect.isEffect(result)) {\n runFork(result);\n }\n }\n },\n catch: cause => isSocketError(cause) ? cause : new SocketError({\n reason: new SocketReadError({\n cause\n })\n })\n }).pipe(FiberSet.run(fiberSet));\n currentStream = {\n stream,\n fiberSet\n };\n yield* latch.open;\n if (opts?.onOpen) yield* opts.onOpen;\n return yield* Effect.catchFilter(FiberSet.join(fiberSet), SocketCloseError.filterClean(_ => !closeCodeIsError(_)), () => Effect.void);\n })).pipe(_ => _, Effect.updateContext(input => Context.merge(acquireServices, input)), Effect.ensuring(Effect.sync(() => {\n latch.closeUnsafe();\n currentStream = undefined;\n })));\n const writers = new WeakMap();\n const getWriter = stream => {\n let writer = writers.get(stream);\n if (!writer) {\n writer = stream.writable.getWriter();\n writers.set(stream, writer);\n }\n return writer;\n };\n const write = chunk => latch.whenOpen(Effect.suspend(() => {\n const {\n fiberSet,\n stream\n } = currentStream;\n if (isCloseEvent(chunk)) {\n return Deferred.fail(fiberSet.deferred, new SocketError({\n reason: new SocketCloseError({\n code: chunk.code,\n closeReason: chunk.reason\n })\n }));\n }\n return Effect.promise(() => getWriter(stream).write(typeof chunk === \"string\" ? encoder.encode(chunk) : chunk));\n }));\n const writer = Effect.acquireRelease(Effect.succeed(write), () => Effect.promise(async () => {\n if (!currentStream) return;\n await getWriter(currentStream.stream).close();\n }));\n return Effect.succeed(make({\n runRaw,\n writer\n }));\n});\n//# sourceMappingURL=Socket.js.map","// taken from https://github.com/fastify/fast-content-type-parse\n// under the MIT license\n/**\n * RegExp to match *( \";\" parameter ) in RFC 7231 sec 3.1.1.1\n *\n * parameter = token \"=\" ( token / quoted-string )\n * token = 1*tchar\n * tchar = \"!\" / \"#\" / \"$\" / \"%\" / \"&\" / \"'\" / \"*\"\n * / \"+\" / \"-\" / \".\" / \"^\" / \"_\" / \"`\" / \"|\" / \"~\"\n * / DIGIT / ALPHA\n * ; any VCHAR, except delimiters\n * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE\n * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text\n * obs-text = %x80-FF\n * quoted-pair = \"\\\" ( HTAB / SP / VCHAR / obs-text )\n */\nconst paramRE = /; *([!#$%&'*+.^\\w`|~-]+)=(\"(?:[\\v\\u0020\\u0021\\u0023-\\u005b\\u005d-\\u007e\\u0080-\\u00ff]|\\\\[\\v\\u0020-\\u00ff])*\"|[!#$%&'*+.^\\w`|~-]+) */gu;\n/**\n * RegExp to match quoted-pair in RFC 7230 sec 3.2.6\n *\n * quoted-pair = \"\\\" ( HTAB / SP / VCHAR / obs-text )\n * obs-text = %x80-FF\n */\nconst quotedPairRE = /\\\\([\\v\\u0020-\\u00ff])/gu;\n/**\n * RegExp to match type in RFC 7231 sec 3.1.1.1\n *\n * media-type = type \"/\" subtype\n * type = token\n * subtype = token\n */\nconst mediaTypeRE = /^[!#$%&'*+.^\\w|~-]+\\/[!#$%&'*+.^\\w|~-]+$/u;\nconst mediaTypeRENoSlash = /^[!#$%&'*+.^\\w|~-]+$/u;\n// default ContentType to prevent repeated object creation\nconst defaultContentType = {\n value: \"\",\n parameters: /*#__PURE__*/Object.create(null)\n};\nexport function parse(header, withoutSlash = false) {\n if (typeof header !== \"string\") {\n return defaultContentType;\n }\n let index = header.indexOf(\";\");\n const type = index !== -1 ? header.slice(0, index).trim() : header.trim();\n const mediaRE = withoutSlash ? mediaTypeRENoSlash : mediaTypeRE;\n if (mediaRE.test(type) === false) {\n return defaultContentType;\n }\n const result = {\n value: type.toLowerCase(),\n parameters: Object.create(null)\n };\n // parse parameters\n if (index === -1) {\n return result;\n }\n let key;\n let match;\n let value;\n paramRE.lastIndex = index;\n while (match = paramRE.exec(header)) {\n if (match.index !== index) {\n return defaultContentType;\n }\n index += match[0].length;\n key = match[1].toLowerCase();\n value = match[2];\n if (value[0] === '\"') {\n // remove quotes and escapes\n value = value.slice(1, value.length - 1);\n !withoutSlash && quotedPairRE.test(value) && (value = value.replace(quotedPairRE, \"$1\"));\n }\n result.parameters[key] = value;\n }\n if (index !== header.length) {\n return defaultContentType;\n }\n return result;\n}\n//# sourceMappingURL=contentType.js.map","const constMaxPairs = 100;\nconst constMaxSize = 16 * 1024;\nvar State;\n(function (State) {\n State[State[\"key\"] = 0] = \"key\";\n State[State[\"whitespace\"] = 1] = \"whitespace\";\n State[State[\"value\"] = 2] = \"value\";\n})(State || (State = {}));\nconst constContinue = {\n _tag: \"Continue\"\n};\nconst constNameChars = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1];\nconst constValueChars = [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1];\nexport function make() {\n const decoder = new TextDecoder();\n const state = {\n state: State.key,\n headers: Object.create(null),\n key: \"\",\n value: undefined,\n crlf: 0,\n previousChunk: undefined,\n pairs: 0,\n size: 0\n };\n function reset(value) {\n state.state = State.key;\n state.headers = Object.create(null);\n state.key = \"\";\n state.value = undefined;\n state.crlf = 0;\n state.previousChunk = undefined;\n state.pairs = 0;\n state.size = 0;\n return value;\n }\n function concatUint8Array(a, b) {\n const newUint8Array = new Uint8Array(a.length + b.length);\n newUint8Array.set(a);\n newUint8Array.set(b, a.length);\n return newUint8Array;\n }\n function error(reason) {\n return reset({\n _tag: \"Failure\",\n reason,\n headers: state.headers\n });\n }\n return function write(chunk, start) {\n let endOffset = 0;\n let previousCursor;\n if (state.previousChunk !== undefined) {\n endOffset = state.previousChunk.length;\n previousCursor = endOffset;\n const newChunk = new Uint8Array(chunk.length + endOffset);\n newChunk.set(state.previousChunk);\n newChunk.set(chunk, endOffset);\n state.previousChunk = undefined;\n chunk = newChunk;\n }\n const end = chunk.length;\n outer: while (start < end) {\n if (state.state === State.key) {\n let i = start;\n for (; i < end; i++) {\n if (state.size++ > constMaxSize) {\n return error(\"HeaderTooLarge\");\n }\n if (chunk[i] === 58) {\n state.key += decoder.decode(chunk.subarray(start, i)).toLowerCase();\n if (state.key.length === 0) {\n return error(\"InvalidHeaderName\");\n }\n if (chunk[i + 1] === 32 && chunk[i + 2] !== 32 && chunk[i + 2] !== 9) {\n start = i + 2;\n state.state = State.value;\n state.size++;\n } else if (chunk[i + 1] !== 32 && chunk[i + 1] !== 9) {\n start = i + 1;\n state.state = State.value;\n } else {\n start = i + 1;\n state.state = State.whitespace;\n }\n break;\n } else if (constNameChars[chunk[i]] !== 1) {\n return error(\"InvalidHeaderName\");\n }\n }\n if (i === end) {\n state.key += decoder.decode(chunk.subarray(start, end)).toLowerCase();\n return constContinue;\n }\n }\n if (state.state === State.whitespace) {\n for (; start < end; start++) {\n if (state.size++ > constMaxSize) {\n return error(\"HeaderTooLarge\");\n }\n if (chunk[start] !== 32 && chunk[start] !== 9) {\n state.state = State.value;\n break;\n }\n }\n if (start === end) {\n return constContinue;\n }\n }\n if (state.state === State.value) {\n let i = start;\n if (previousCursor !== undefined) {\n i = previousCursor;\n previousCursor = undefined;\n }\n for (; i < end; i++) {\n if (state.size++ > constMaxSize) {\n return error(\"HeaderTooLarge\");\n }\n if (chunk[i] === 13 || state.crlf > 0) {\n let byte = chunk[i];\n if (byte === 13 && state.crlf === 0) {\n state.crlf = 1;\n i++;\n state.size++;\n byte = chunk[i];\n }\n if (byte === 10 && state.crlf === 1) {\n state.crlf = 2;\n i++;\n state.size++;\n byte = chunk[i];\n }\n if (byte === 13 && state.crlf === 2) {\n state.crlf = 3;\n i++;\n state.size++;\n byte = chunk[i];\n }\n if (byte === 10 && state.crlf === 3) {\n state.crlf = 4;\n i++;\n state.size++;\n }\n if (state.crlf < 4 && i >= end) {\n state.previousChunk = chunk.subarray(start);\n return constContinue;\n } else if (state.crlf >= 2) {\n state.value = state.value === undefined ? chunk.subarray(start, i - state.crlf) : concatUint8Array(state.value, chunk.subarray(start, i - state.crlf));\n const value = decoder.decode(state.value);\n if (state.headers[state.key] === undefined) {\n state.headers[state.key] = value;\n } else if (typeof state.headers[state.key] === \"string\") {\n state.headers[state.key] = [state.headers[state.key], value];\n } else {\n ;\n state.headers[state.key].push(value);\n }\n start = i;\n state.size--;\n if (state.crlf !== 4 && state.pairs === constMaxPairs) {\n return error(\"TooManyHeaders\");\n } else if (state.crlf === 3) {\n return error(\"InvalidHeaderValue\");\n } else if (state.crlf === 4) {\n return reset({\n _tag: \"Headers\",\n headers: state.headers,\n endPosition: start - endOffset\n });\n }\n state.pairs++;\n state.key = \"\";\n state.value = undefined;\n state.crlf = 0;\n state.state = State.key;\n continue outer;\n }\n } else if (constValueChars[chunk[i]] !== 1) {\n return error(\"InvalidHeaderValue\");\n }\n }\n if (i === end) {\n state.value = state.value === undefined ? chunk.subarray(start, end) : concatUint8Array(state.value, chunk.subarray(start, end));\n return constContinue;\n }\n }\n }\n if (start > end) {\n state.size += end - start;\n }\n return constContinue;\n };\n}\n//# sourceMappingURL=headers.js.map","function makeState(needle_) {\n const needle = new TextEncoder().encode(needle_);\n const needleLength = needle.length;\n const indexes = {};\n for (let i = 0; i < needleLength; i++) {\n const b = needle[i];\n if (indexes[b] === undefined) indexes[b] = [];\n indexes[b].push(i);\n }\n return {\n needle,\n needleLength,\n indexes,\n firstByte: needle[0],\n previousChunk: undefined,\n previousChunkLength: 0,\n matchIndex: 0\n };\n}\nexport function make(needle, callback, seed) {\n const state = makeState(needle);\n if (seed !== undefined) {\n state.previousChunk = seed;\n state.previousChunkLength = seed.length;\n }\n function makeIndexOf() {\n // on node.js use the Buffer api\n if (\"Buffer\" in globalThis && !(\"Bun\" in globalThis || \"Deno\" in globalThis)) {\n return function (chunk, needle, fromIndex) {\n return Buffer.prototype.indexOf.call(chunk, needle, fromIndex);\n };\n }\n const skipTable = new Uint8Array(256).fill(state.needle.length);\n for (let i = 0, lastIndex = state.needle.length - 1; i < lastIndex; ++i) {\n skipTable[state.needle[i]] = lastIndex - i;\n }\n return function (chunk, needle, fromIndex) {\n const lengthTotal = chunk.length;\n let i = fromIndex + state.needleLength - 1;\n while (i < lengthTotal) {\n for (let j = state.needleLength - 1, k = i; j >= 0 && chunk[k] === needle[j]; j--, k--) {\n if (j === 0) return k;\n }\n i += skipTable[chunk[i]];\n }\n return -1;\n };\n }\n const indexOf = makeIndexOf();\n function write(chunk) {\n let chunkLength = chunk.length;\n if (state.previousChunk !== undefined) {\n const newChunk = new Uint8Array(state.previousChunkLength + chunkLength);\n newChunk.set(state.previousChunk);\n newChunk.set(chunk, state.previousChunkLength);\n chunk = newChunk;\n chunkLength = state.previousChunkLength + chunkLength;\n state.previousChunk = undefined;\n }\n if (chunkLength < state.needleLength) {\n state.previousChunk = chunk;\n state.previousChunkLength = chunkLength;\n return;\n }\n let pos = 0;\n while (pos < chunkLength) {\n const match = indexOf(chunk, state.needle, pos);\n if (match > -1) {\n if (match > pos) {\n callback(state.matchIndex, chunk.subarray(pos, match));\n }\n state.matchIndex += 1;\n pos = match + state.needleLength;\n continue;\n } else if (chunk[chunkLength - 1] in state.indexes) {\n const indexes = state.indexes[chunk[chunkLength - 1]];\n let earliestIndex = -1;\n for (let i = 0, len = indexes.length; i < len; i++) {\n const index = indexes[i];\n if (chunk[chunkLength - 1 - index] === state.firstByte && i > earliestIndex) {\n earliestIndex = index;\n }\n }\n if (earliestIndex === -1) {\n if (pos === 0) {\n callback(state.matchIndex, chunk);\n } else {\n callback(state.matchIndex, chunk.subarray(pos));\n }\n } else {\n if (chunkLength - 1 - earliestIndex > pos) {\n callback(state.matchIndex, chunk.subarray(pos, chunkLength - 1 - earliestIndex));\n }\n state.previousChunk = chunk.subarray(chunkLength - 1 - earliestIndex);\n state.previousChunkLength = earliestIndex + 1;\n }\n } else if (pos === 0) {\n callback(state.matchIndex, chunk);\n } else {\n callback(state.matchIndex, chunk.subarray(pos));\n }\n break;\n }\n }\n function end() {\n if (state.previousChunk !== undefined && state.previousChunk !== seed) {\n callback(state.matchIndex, state.previousChunk);\n }\n state.previousChunk = seed;\n state.previousChunkLength = seed?.length ?? 0;\n state.matchIndex = 0;\n }\n return {\n write,\n end\n };\n}\n//# sourceMappingURL=search.js.map","import * as CT from \"./contentType.js\";\nimport * as HP from \"./headers.js\";\nimport * as Search from \"./search.js\";\nvar State;\n(function (State) {\n State[State[\"headers\"] = 0] = \"headers\";\n State[State[\"body\"] = 1] = \"body\";\n})(State || (State = {}));\nconst errInvalidDisposition = {\n _tag: \"InvalidDisposition\"\n};\nconst errEndNotReached = {\n _tag: \"EndNotReached\"\n};\nconst errMaxParts = {\n _tag: \"ReachedLimit\",\n limit: \"MaxParts\"\n};\nconst errMaxTotalSize = {\n _tag: \"ReachedLimit\",\n limit: \"MaxTotalSize\"\n};\nconst errMaxPartSize = {\n _tag: \"ReachedLimit\",\n limit: \"MaxPartSize\"\n};\nconst errMaxFieldSize = {\n _tag: \"ReachedLimit\",\n limit: \"MaxFieldSize\"\n};\nconst constCR = /*#__PURE__*/new TextEncoder().encode(\"\\r\\n\");\nexport function defaultIsFile(info) {\n return info.filename !== undefined || info.contentType === \"application/octet-stream\";\n}\nfunction parseBoundary(headers) {\n const contentType = CT.parse(headers[\"content-type\"]);\n return contentType.parameters.boundary;\n}\nfunction noopOnChunk(_chunk) {}\nexport function make({\n headers,\n onFile: onPart,\n onField,\n onError,\n onDone,\n isFile = defaultIsFile,\n maxParts = Infinity,\n maxTotalSize = Infinity,\n maxPartSize = Infinity,\n maxFieldSize = 1024 * 1024\n}) {\n const boundary = parseBoundary(headers);\n if (boundary === undefined) {\n onError({\n _tag: \"InvalidBoundary\"\n });\n return {\n write: noopOnChunk,\n end() {}\n };\n }\n const state = {\n state: State.headers,\n index: 0,\n parts: 0,\n onChunk: noopOnChunk,\n info: undefined,\n headerSkip: 0,\n partSize: 0,\n totalSize: 0,\n isFile: false,\n fieldChunks: [],\n fieldSize: 0\n };\n function skipBody() {\n state.state = State.body;\n state.isFile = true;\n state.onChunk = noopOnChunk;\n }\n const headerParser = HP.make();\n const split = Search.make(`\\r\\n--${boundary}`, function (index, chunk) {\n if (index === 0) {\n // data before the first boundary\n skipBody();\n return;\n } else if (index !== state.index) {\n if (state.index > 0) {\n if (state.isFile) {\n state.onChunk(null);\n state.partSize = 0;\n } else {\n if (state.fieldChunks.length === 1) {\n onField(state.info, state.fieldChunks[0]);\n } else {\n const buf = new Uint8Array(state.fieldSize);\n let offset = 0;\n for (let i = 0; i < state.fieldChunks.length; i++) {\n const chunk = state.fieldChunks[i];\n buf.set(chunk, offset);\n offset += chunk.length;\n }\n onField(state.info, buf);\n }\n state.fieldSize = 0;\n state.fieldChunks = [];\n }\n }\n state.state = State.headers;\n state.index = index;\n state.headerSkip = 2; // skip the first \\r\\n\n // trailing --\n if (chunk[0] === 45 && chunk[1] === 45) {\n return onDone();\n }\n state.parts++;\n if (state.parts > maxParts) {\n onError(errMaxParts);\n }\n }\n if ((state.partSize += chunk.length) > maxPartSize) {\n onError(errMaxPartSize);\n }\n if (state.state === State.headers) {\n const result = headerParser(chunk, state.headerSkip);\n state.headerSkip = 0;\n if (result._tag === \"Continue\") {\n return;\n } else if (result._tag === \"Failure\") {\n skipBody();\n return onError({\n _tag: \"BadHeaders\",\n error: result\n });\n }\n const contentType = CT.parse(result.headers[\"content-type\"]);\n const contentDisposition = CT.parse(result.headers[\"content-disposition\"], true);\n if (\"form-data\" === contentDisposition.value && !(\"name\" in contentDisposition.parameters)) {\n skipBody();\n return onError(errInvalidDisposition);\n }\n let encodedFilename;\n if (\"filename*\" in contentDisposition.parameters) {\n const parts = contentDisposition.parameters[\"filename*\"].split(\"''\");\n if (parts.length === 2) {\n encodedFilename = decodeURIComponent(parts[1]);\n }\n }\n state.info = {\n name: contentDisposition.parameters.name ?? \"\",\n filename: encodedFilename ?? contentDisposition.parameters.filename,\n contentType: contentType.value === \"\" ? contentDisposition.parameters.filename !== undefined ? \"application/octet-stream\" : \"text/plain\" : contentType.value,\n contentTypeParameters: contentType.parameters,\n contentDisposition: contentDisposition.value,\n contentDispositionParameters: contentDisposition.parameters,\n headers: result.headers\n };\n state.state = State.body;\n state.isFile = isFile(state.info);\n if (state.isFile) {\n state.onChunk = onPart(state.info);\n }\n if (result.endPosition < chunk.length) {\n if (state.isFile) {\n state.onChunk(chunk.subarray(result.endPosition));\n } else {\n const buf = chunk.subarray(result.endPosition);\n if ((state.fieldSize += buf.length) > maxFieldSize) {\n onError(errMaxFieldSize);\n }\n state.fieldChunks.push(buf);\n }\n }\n } else if (state.isFile) {\n state.onChunk(chunk);\n } else {\n if ((state.fieldSize += chunk.length) > maxFieldSize) {\n onError(errMaxFieldSize);\n }\n state.fieldChunks.push(chunk);\n }\n }, constCR);\n return {\n write(chunk) {\n if ((state.totalSize += chunk.length) > maxTotalSize) {\n return onError(errMaxTotalSize);\n }\n return split.write(chunk);\n },\n end() {\n split.end();\n if (state.state === State.body) {\n onError(errEndNotReached);\n }\n state.state = State.headers;\n state.index = 0;\n state.parts = 0;\n state.onChunk = noopOnChunk;\n state.info = undefined;\n state.totalSize = 0;\n state.partSize = 0;\n state.fieldChunks = [];\n state.fieldSize = 0;\n }\n };\n}\nconst utf8Decoder = /*#__PURE__*/new TextDecoder(\"utf-8\");\nfunction getDecoder(charset) {\n if (charset === \"utf-8\" || charset === \"utf8\" || charset === \"\") {\n return utf8Decoder;\n }\n try {\n return new TextDecoder(charset);\n } catch (error) {\n return utf8Decoder;\n }\n}\nexport function decodeField(info, value) {\n return getDecoder(info.contentTypeParameters.charset ?? \"utf-8\").decode(value);\n}\n//# sourceMappingURL=multipart.js.map","import * as internal from \"./internal/multipart.js\";\nexport const make = internal.make;\nexport const defaultIsFile = internal.defaultIsFile;\nexport const decodeField = internal.decodeField;\n//# sourceMappingURL=index.js.map","/**\n * Parses and persists HTTP `multipart/form-data` request bodies.\n *\n * `Multipart` turns incoming byte streams into typed form parts. Text parts\n * become decoded fields, while upload parts stay as streamed files until they\n * are collected or written to scoped temporary files. The persisted\n * representation can then be decoded with schemas for handlers that receive\n * fields and uploaded files together. This module also includes multipart error\n * types, schema helpers for persisted files, and parser limit settings.\n *\n * @since 4.0.0\n */\nimport * as Arr from \"../../Array.js\";\nimport * as Cause from \"../../Cause.js\";\nimport * as Channel from \"../../Channel.js\";\nimport * as Context from \"../../Context.js\";\nimport * as Data from \"../../Data.js\";\nimport * as Effect from \"../../Effect.js\";\nimport * as Exit from \"../../Exit.js\";\nimport * as FileSystem from \"../../FileSystem.js\";\nimport { constant, dual } from \"../../Function.js\";\nimport * as Inspectable from \"../../Inspectable.js\";\nimport * as Option from \"../../Option.js\";\nimport * as Path from \"../../Path.js\";\nimport * as Predicate from \"../../Predicate.js\";\nimport * as Pull from \"../../Pull.js\";\nimport * as Schema from \"../../Schema.js\";\nimport * as SchemaTransformation from \"../../SchemaTransformation.js\";\nimport * as Stream from \"../../Stream.js\";\nimport * as UndefinedOr from \"../../UndefinedOr.js\";\nimport * as IncomingMessage from \"./HttpIncomingMessage.js\";\nimport * as MP from \"./Multipasta.js\";\n/**\n * Type identifier used to brand multipart part values.\n *\n * @category type IDs\n * @since 4.0.0\n */\nexport const TypeId = \"~effect/http/Multipart\";\n/**\n * Returns `true` when a value is a multipart `Part`.\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isPart = u => Predicate.hasProperty(u, TypeId);\n/**\n * Returns `true` when a value is a multipart text `Field`.\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isField = u => isPart(u) && u._tag === \"Field\";\n/**\n * Returns `true` when a value is a multipart `File`.\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isFile = u => isPart(u) && u._tag === \"File\";\n/**\n * Returns `true` when a value is a persisted multipart file.\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isPersistedFile = u => Predicate.hasProperty(u, TypeId) && Predicate.isTagged(u, \"PersistedFile\");\nconst MultipartErrorTypeId = \"~effect/http/Multipart/MultipartError\";\n/**\n * Error reason carried by a `MultipartError`.\n *\n * **Details**\n *\n * It identifies parser and limit failures such as oversized files or fields, too\n * many parts, total body size limits, parse errors, and internal errors.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class MultipartErrorReason extends Data.Error {}\n/**\n * Error raised while parsing, streaming, or persisting multipart form data.\n *\n * **Details**\n *\n * The `reason` field contains the concrete `MultipartErrorReason`.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class MultipartError extends /*#__PURE__*/Data.TaggedError(\"MultipartError\") {\n /**\n * Creates a multipart error from a reason tag and optional cause.\n *\n * @since 4.0.0\n */\n static fromReason(reason, cause) {\n return new MultipartError({\n reason: new MultipartErrorReason({\n _tag: reason,\n cause\n })\n });\n }\n /**\n * Marks this value as a multipart error for runtime guards.\n *\n * @since 4.0.0\n */\n [MultipartErrorTypeId] = MultipartErrorTypeId;\n /**\n * Uses the concrete multipart error reason as the public message.\n *\n * @since 4.0.0\n */\n get message() {\n return this.reason._tag;\n }\n}\n/**\n * Schema for persisted multipart files.\n *\n * **Details**\n *\n * The encoded form contains the field key, original file name, content type, and\n * filesystem path.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const PersistedFileSchema = /*#__PURE__*/Schema.declare(isPersistedFile, {\n typeConstructor: {\n _tag: \"effect/http/PersistedFile\"\n },\n generation: {\n runtime: `Multipart.PersistedFileSchema`,\n Type: `Multipart.PersistedFile`,\n importDeclaration: `import * as Multipart from \"effect/unstable/http/Multipart\"`\n },\n expected: \"PersistedFile\",\n toCodecJson: () => Schema.link()(Schema.Struct({\n key: Schema.String,\n name: Schema.String,\n contentType: Schema.String.annotate({\n contentEncoding: \"binary\"\n }),\n path: Schema.String\n }), SchemaTransformation.transform({\n decode: ({\n contentType,\n key,\n name,\n path\n }) => new PersistedFileImpl(key, name, contentType, path),\n encode: file => ({\n key: file.key,\n name: file.name,\n contentType: file.contentType,\n path: file.path\n })\n }))\n});\n/**\n * Schema for an array of persisted multipart files.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const FilesSchema = /*#__PURE__*/Schema.Array(PersistedFileSchema);\n/**\n * Schema for exactly one persisted multipart file.\n *\n * **Details**\n *\n * The encoded form is a one-element file array, while the decoded value is the\n * single `PersistedFile`.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const SingleFileSchema = /*#__PURE__*/FilesSchema.check(Schema.isLengthBetween(1, 1)).pipe(/*#__PURE__*/Schema.decodeTo(PersistedFileSchema, /*#__PURE__*/SchemaTransformation.transform({\n decode: ([file]) => file,\n encode: file => [file]\n})));\n/**\n * Creates a decoder for persisted multipart data using the supplied schema.\n *\n * **Details**\n *\n * The returned function decodes an unknown input into the schema output and fails\n * with `SchemaError` when validation fails.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const schemaPersisted = schema => Schema.decodeUnknownEffect(schema);\n/**\n * Creates a decoder for a JSON-encoded field in persisted multipart data.\n *\n * **Details**\n *\n * The selected field is parsed from a JSON string and decoded with the supplied\n * schema.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const schemaJson = (schema, options) => {\n const fromJson = Schema.fromJsonString(schema);\n return dual(2, (persisted, field) => Effect.map(Schema.decodeUnknownEffect(Schema.Struct({\n [field]: fromJson\n }))(persisted, options), _ => _[field]));\n};\n/**\n * Builds the low-level multipart parser configuration from request headers and\n * the current fiber context.\n *\n * **Details**\n *\n * Parser limits are read from the multipart references, including maximum parts,\n * field size, file size, total body size, and field MIME type overrides.\n *\n * @category configuration\n * @since 4.0.0\n */\nexport const makeConfig = headers => Effect.withFiber(fiber => {\n const mimeTypes = Context.get(fiber.context, FieldMimeTypes);\n return Effect.succeed({\n headers,\n maxParts: fiber.getRef(MaxParts),\n maxFieldSize: Number(fiber.getRef(MaxFieldSize)),\n maxPartSize: UndefinedOr.map(fiber.getRef(MaxFileSize), Number),\n maxTotalSize: UndefinedOr.map(fiber.getRef(IncomingMessage.MaxBodySize), Number),\n isFile: mimeTypes.length === 0 ? undefined : info => !mimeTypes.some(_ => info.contentType.includes(_)) && MP.defaultIsFile(info)\n });\n});\n/**\n * Creates a channel that parses multipart byte chunks into multipart parts.\n *\n * **Details**\n *\n * The channel consumes non-empty batches of `Uint8Array` chunks and emits\n * non-empty batches of parsed `Part` values, failing with `MultipartError` for\n * parser and limit failures.\n *\n * @category Parsers\n * @since 4.0.0\n */\nexport const makeChannel = headers => Channel.fromTransform(upstream => Effect.map(makeConfig(headers), config => {\n let partsBuffer = [];\n let exit = Option.none();\n const parser = MP.make({\n ...config,\n onField(info, value) {\n partsBuffer.push(new FieldImpl(info.name, info.contentType, MP.decodeField(info, value)));\n },\n onFile(info) {\n let chunks = [];\n let finished = false;\n const pullChunks = Channel.fromPull(Effect.succeed(Effect.suspend(function loop() {\n if (!Arr.isReadonlyArrayNonEmpty(chunks)) {\n return finished ? Cause.done() : Effect.flatMap(pump, loop);\n }\n const chunk = chunks;\n chunks = [];\n return Effect.succeed(chunk);\n })));\n partsBuffer.push(new FileImpl(info, pullChunks));\n return function (chunk) {\n if (chunk === null) {\n finished = true;\n } else {\n chunks.push(chunk);\n }\n };\n },\n onError(error_) {\n exit = Option.some(Exit.fail(convertError(error_)));\n },\n onDone() {\n exit = Option.some(Exit.fail(Cause.Done()));\n }\n });\n const pump = upstream.pipe(Effect.flatMap(chunk => {\n for (let i = 0; i < chunk.length; i++) {\n parser.write(chunk[i]);\n }\n return Effect.void;\n }), Effect.catchCause(cause => {\n if (Pull.isDoneCause(cause)) {\n parser.end();\n } else {\n exit = Option.some(Exit.failCause(cause));\n }\n return Effect.void;\n }));\n return pump.pipe(Effect.flatMap(function loop() {\n if (!Arr.isReadonlyArrayNonEmpty(partsBuffer)) {\n if (Option.isSome(exit)) {\n return exit.value;\n }\n return Effect.flatMap(pump, loop);\n }\n const parts = partsBuffer;\n partsBuffer = [];\n return Effect.succeed(parts);\n }));\n}));\nfunction convertError(cause) {\n switch (cause._tag) {\n case \"ReachedLimit\":\n {\n switch (cause.limit) {\n case \"MaxParts\":\n {\n return MultipartError.fromReason(\"TooManyParts\", cause);\n }\n case \"MaxFieldSize\":\n {\n return MultipartError.fromReason(\"FieldTooLarge\", cause);\n }\n case \"MaxPartSize\":\n {\n return MultipartError.fromReason(\"FileTooLarge\", cause);\n }\n case \"MaxTotalSize\":\n {\n return MultipartError.fromReason(\"BodyTooLarge\", cause);\n }\n }\n }\n default:\n {\n return MultipartError.fromReason(\"Parse\", cause);\n }\n }\n}\nclass PartBase extends Inspectable.Class {\n [TypeId];\n constructor() {\n super();\n this[TypeId] = TypeId;\n }\n}\nclass FieldImpl extends PartBase {\n _tag = \"Field\";\n key;\n contentType;\n value;\n constructor(key, contentType, value) {\n super();\n this.key = key;\n this.contentType = contentType;\n this.value = value;\n }\n toJSON() {\n return {\n _id: \"@effect/platform/Multipart/Part\",\n _tag: \"Field\",\n key: this.key,\n contentType: this.contentType,\n value: this.value\n };\n }\n}\nclass FileImpl extends PartBase {\n _tag = \"File\";\n key;\n name;\n contentType;\n content;\n contentEffect;\n constructor(info, channel) {\n super();\n this.key = info.name;\n this.name = info.filename ?? info.name;\n this.contentType = info.contentType;\n this.content = Stream.fromChannel(channel);\n this.contentEffect = channel.pipe(collectUint8Array, Effect.mapError(cause => MultipartError.fromReason(\"InternalError\", cause)));\n }\n toJSON() {\n return {\n _id: \"@effect/platform/Multipart/Part\",\n _tag: \"File\",\n key: this.key,\n name: this.name,\n contentType: this.contentType\n };\n }\n}\nconst defaultWriteFile = (path, file) => Effect.flatMap(FileSystem.FileSystem, fs => Effect.mapError(Stream.run(file.content, fs.sink(path)), cause => MultipartError.fromReason(\"InternalError\", cause)));\n/**\n * Runs a channel of byte chunks and collects all output into a single\n * `Uint8Array`.\n *\n * **Gotchas**\n *\n * This materializes the full content in memory.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const collectUint8Array = self => Channel.runFold(self, constant(new Uint8Array(0)), (accumulator, chunk) => {\n const totalLength = chunk.reduce((sum, element) => sum + element.length, accumulator.length);\n const newAccumulator = new Uint8Array(totalLength);\n newAccumulator.set(accumulator, 0);\n let offset = accumulator.length;\n for (const element of chunk) {\n newAccumulator.set(element, offset);\n offset += element.length;\n }\n return newAccumulator;\n});\n/**\n * Persists a stream of multipart parts into a record.\n *\n * **Details**\n *\n * Text fields are collected as strings, and file parts are written to files in a\n * scoped temporary directory.\n *\n * **Gotchas**\n *\n * Persisted file paths remain valid for the lifetime of the scope.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toPersisted = (stream, writeFile = defaultWriteFile) => Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path_ = yield* Path.Path;\n const dir = yield* fs.makeTempDirectoryScoped();\n const persisted = Object.create(null);\n yield* Stream.runForEach(stream, part => {\n if (part._tag === \"Field\") {\n if (!(part.key in persisted)) {\n persisted[part.key] = part.value;\n } else if (typeof persisted[part.key] === \"string\") {\n persisted[part.key] = [persisted[part.key], part.value];\n } else {\n ;\n persisted[part.key].push(part.value);\n }\n return Effect.void;\n } else if (part.name === \"\") {\n return Effect.void;\n }\n const file = part;\n const path = path_.join(dir, path_.basename(file.name).slice(-128));\n const filePart = new PersistedFileImpl(file.key, file.name, file.contentType, path);\n if (Array.isArray(persisted[part.key])) {\n ;\n persisted[part.key].push(filePart);\n } else {\n persisted[part.key] = [filePart];\n }\n return writeFile(path, file);\n });\n return persisted;\n}).pipe(Effect.catchTag(\"PlatformError\", cause => Effect.fail(MultipartError.fromReason(\"InternalError\", cause))));\nclass PersistedFileImpl extends PartBase {\n _tag = \"PersistedFile\";\n key;\n name;\n contentType;\n path;\n constructor(key, name, contentType, path) {\n super();\n this.key = key;\n this.name = name;\n this.contentType = contentType;\n this.path = path;\n }\n toJSON() {\n return {\n _id: \"@effect/platform/Multipart/Part\",\n _tag: \"PersistedFile\",\n key: this.key,\n name: this.name,\n contentType: this.contentType,\n path: this.path\n };\n }\n}\n/**\n * Creates a context containing multipart parser limit settings.\n *\n * **Details**\n *\n * The context can provide maximum part count, field size, file size, total body\n * size, and MIME types that should be parsed as fields.\n *\n * @category references\n * @since 4.0.0\n */\nexport const limitsServices = options => {\n const map = new Map();\n if (options.maxParts !== undefined) {\n map.set(MaxParts.key, options.maxParts);\n }\n if (options.maxFieldSize !== undefined) {\n map.set(MaxFieldSize.key, FileSystem.Size(options.maxFieldSize));\n }\n if (options.maxFileSize !== undefined) {\n map.set(MaxFileSize.key, UndefinedOr.map(options.maxFileSize, FileSystem.Size));\n }\n if (options.maxTotalSize !== undefined) {\n map.set(IncomingMessage.MaxBodySize.key, UndefinedOr.map(options.maxTotalSize, FileSystem.Size));\n }\n if (options.fieldMimeTypes !== undefined) {\n map.set(FieldMimeTypes.key, options.fieldMimeTypes);\n }\n return Context.makeUnsafe(map);\n};\n/**\n * Context reference for the maximum number of multipart parts allowed.\n *\n * **Details**\n *\n * The default is `undefined`, meaning no explicit part-count limit.\n *\n * @category references\n * @since 4.0.0\n */\nexport const MaxParts = /*#__PURE__*/Context.Reference(\"effect/http/Multipart/MaxParts\", {\n defaultValue: () => undefined\n});\n/**\n * Context reference for the maximum size of a multipart field value.\n *\n * **Details**\n *\n * The default limit is 10 MiB.\n *\n * @category references\n * @since 4.0.0\n */\nexport const MaxFieldSize = /*#__PURE__*/Context.Reference(\"effect/http/Multipart/MaxFieldSize\", {\n defaultValue: /*#__PURE__*/constant(/*#__PURE__*/FileSystem.Size(10 * 1024 * 1024))\n});\n/**\n * Context reference for the maximum size of a multipart file part.\n *\n * **Details**\n *\n * The default is `undefined`, meaning no explicit per-file limit.\n *\n * @category references\n * @since 4.0.0\n */\nexport const MaxFileSize = /*#__PURE__*/Context.Reference(\"effect/http/Multipart/MaxFileSize\", {\n defaultValue: () => undefined\n});\n/**\n * Context reference for MIME type fragments that should be parsed as multipart\n * fields instead of files.\n *\n * **Details**\n *\n * The default treats `application/json` parts as fields.\n *\n * @category references\n * @since 4.0.0\n */\nexport const FieldMimeTypes = /*#__PURE__*/Context.Reference(\"effect/http/Multipart/FieldMimeTypes\", {\n defaultValue: /*#__PURE__*/constant([\"application/json\"])\n});\n//# sourceMappingURL=Multipart.js.map","import * as Channel from \"../../Channel.js\";\nimport * as Context from \"../../Context.js\";\nimport * as Effect from \"../../Effect.js\";\nimport * as Inspectable from \"../../Inspectable.js\";\nimport * as Option from \"../../Option.js\";\nimport * as Result from \"../../Result.js\";\nimport * as Schema from \"../../Schema.js\";\nimport * as Stream from \"../../Stream.js\";\nimport * as Socket from \"../socket/Socket.js\";\nimport * as Cookies from \"./Cookies.js\";\nimport * as Headers from \"./Headers.js\";\nimport * as HttpBody from \"./HttpBody.js\";\nimport * as HttpClientRequest from \"./HttpClientRequest.js\";\nimport * as HttpIncomingMessage from \"./HttpIncomingMessage.js\";\nimport { hasBody } from \"./HttpMethod.js\";\nimport { HttpServerError, RequestParseError } from \"./HttpServerError.js\";\nimport * as Multipart from \"./Multipart.js\";\nimport * as UrlParams from \"./UrlParams.js\";\nexport {\n/**\n * Provides the `MaxBodySize` fiber reference for configuring request body limits.\n *\n * **When to use**\n *\n * Use to configure the maximum body size accepted while reading server\n * request bodies.\n *\n * @category fiber refs\n * @since 4.0.0\n */\nMaxBodySize } from \"./HttpIncomingMessage.js\";\n/**\n * Runtime type identifier for `HttpServerRequest` values.\n *\n * @category type IDs\n * @since 4.0.0\n */\nexport const TypeId = \"~effect/http/HttpServerRequest\";\n/**\n * Service tag for the active server-side HTTP request.\n *\n * **When to use**\n *\n * Use to access the request currently being handled by HTTP server routes and\n * middleware.\n *\n * @category context\n * @since 4.0.0\n */\nexport const HttpServerRequest = /*#__PURE__*/Context.Service(\"effect/http/HttpServerRequest\");\n/**\n * Service that contains decoded URL query parameters for the current request.\n *\n * **When to use**\n *\n * Use to access query parameters that have already been parsed for the current\n * server request.\n *\n * **Details**\n *\n * Each key maps to a string value, or to an array when the parameter appears more\n * than once.\n *\n * @category search params\n * @since 4.0.0\n */\nexport class ParsedSearchParams extends /*#__PURE__*/Context.Service()(\"effect/http/ParsedSearchParams\") {}\n/**\n * Converts a `URL` object's search parameters into a record.\n *\n * **Details**\n *\n * Repeated parameters are represented as arrays in insertion order.\n *\n * @category search params\n * @since 4.0.0\n */\nexport const searchParamsFromURL = url => {\n const out = {};\n for (const [key, value] of url.searchParams.entries()) {\n const entry = out[key];\n if (entry !== undefined) {\n if (Array.isArray(entry)) {\n entry.push(value);\n } else {\n out[key] = [entry, value];\n }\n } else {\n out[key] = value;\n }\n }\n return out;\n};\n/**\n * Creates a channel backed by the current request's upgraded socket.\n *\n * **Details**\n *\n * The channel reads incoming socket messages and writes byte chunks to the\n * socket, failing if the request cannot be upgraded or the socket fails.\n *\n * @category accessors\n * @since 4.0.0\n */\nexport const upgradeChannel = () => HttpServerRequest.pipe(Effect.flatMap(_ => _.upgrade), Effect.map(Socket.toChannelWith()), Channel.unwrap);\n/**\n * Decodes a schema from the cookies of the current request.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const schemaCookies = (schema, options) => {\n const parse = Schema.decodeUnknownEffect(schema);\n return Effect.flatMap(HttpServerRequest, req => parse(req.cookies, options));\n};\n/**\n * Decodes a schema from the headers of the current request.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const schemaHeaders = (schema, options) => {\n const parse = Schema.decodeUnknownEffect(schema);\n return Effect.flatMap(HttpServerRequest, req => parse(req.headers, options));\n};\n/**\n * Decodes a schema from the parsed search parameters of the current request.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const schemaSearchParams = (schema, options) => {\n const parse = Schema.decodeUnknownEffect(schema);\n return Effect.flatMap(ParsedSearchParams, params => parse(params, options));\n};\n/**\n * Reads the current request body as JSON and decodes it with the supplied schema.\n *\n * **Details**\n *\n * The effect can fail if the body cannot be read or parsed, or if schema decoding\n * fails.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const schemaBodyJson = (schema, options) => {\n const parse = HttpIncomingMessage.schemaBodyJson(schema, options);\n return Effect.flatMap(HttpServerRequest, parse);\n};\nconst isMultipart = request => request.headers[\"content-type\"]?.toLowerCase().includes(\"multipart/form-data\") === true || getFormDataBody(request) !== undefined;\n/**\n * Decodes the current request body as form data.\n *\n * **Details**\n *\n * Multipart requests are persisted and decoded as multipart data; other form\n * requests are decoded from URL-encoded body parameters.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const schemaBodyForm = (schema, options) => {\n const parseMultipart = Multipart.schemaPersisted(schema);\n const parseUrlParams = HttpIncomingMessage.schemaBodyUrlParams(schema, options);\n return Effect.flatMap(HttpServerRequest, request => {\n if (isMultipart(request)) {\n return Effect.flatMap(request.multipart, _ => parseMultipart(_, options));\n }\n return parseUrlParams(request);\n });\n};\n/**\n * Reads the current request body as URL-encoded parameters and decodes them with\n * the supplied schema.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const schemaBodyUrlParams = (schema, options) => {\n const parse = HttpIncomingMessage.schemaBodyUrlParams(schema, options);\n return Effect.flatMap(HttpServerRequest, parse);\n};\n/**\n * Persists the current multipart request body and decodes it with the supplied\n * schema.\n *\n * **Details**\n *\n * The effect requires the services needed to persist multipart files, including a\n * scope, file system, and path service.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const schemaBodyMultipart = (schema, options) => {\n const parse = Multipart.schemaPersisted(schema);\n return HttpServerRequest.pipe(Effect.flatMap(_ => _.multipart), Effect.flatMap(_ => parse(_, options)));\n};\n/**\n * Creates a decoder for a JSON value stored in a form field.\n *\n * **Details**\n *\n * For multipart requests, the named multipart field is decoded as JSON. For\n * URL-encoded requests, the named parameter is decoded as JSON and then decoded\n * with the supplied schema.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const schemaBodyFormJson = (schema, options) => {\n const parseMultipart = Multipart.schemaJson(schema, options);\n return field => {\n const parseUrlParams = UrlParams.schemaJsonField(field).pipe(Schema.decodeTo(schema), Schema.decodeEffect);\n return Effect.flatMap(HttpServerRequest, request => {\n if (isMultipart(request)) {\n return Effect.flatMap(Effect.mapError(request.multipart, cause => new HttpServerError({\n reason: new RequestParseError({\n request,\n cause\n })\n })), parseMultipart(field));\n }\n return Effect.flatMap(request.urlParamsBody, _ => parseUrlParams(_, options));\n });\n };\n};\n/**\n * Creates an `HttpServerRequest` view of an `HttpClientRequest`.\n *\n * **Details**\n *\n * If the client request can be converted to an absolute URL, that URL is used as\n * the original URL.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const fromClientRequest = request => {\n const url = Option.match(HttpClientRequest.toUrl(request), {\n onNone: () => request.url,\n onSome: url => url.toString()\n });\n return new ClientRequestImpl(request, url);\n};\n/**\n * Wraps a Web `Request` as an `HttpServerRequest`.\n *\n * **Details**\n *\n * The request's current URL is stored without the scheme and host, while the\n * original Web URL remains available as `originalUrl`.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const fromWeb = request => new ServerRequestImpl(request, removeHost(request.url));\n/**\n * Converts an `HttpServerRequest` into an `HttpClientRequest`.\n *\n * **Details**\n *\n * The converted request preserves the method, headers, body stream, and a URL\n * derived from the request when possible.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toClientRequest = request => HttpClientRequest.setUrl(HttpClientRequest.makeWith(request.method, \"\", UrlParams.empty, Option.none(), request.headers, toClientBody(request)), Option.getOrElse(toURL(request), () => request.url));\nconst toClientBody = request => hasBody(request.method) ? HttpBody.stream(request.stream, request.headers[\"content-type\"], parseContentLength(request.headers[\"content-length\"])) : HttpBody.empty;\nconst parseContentLength = contentLength => {\n if (contentLength === undefined) {\n return undefined;\n }\n const parsed = Number.parseInt(contentLength, 10);\n return Number.isNaN(parsed) ? undefined : parsed;\n};\nconst removeHost = url => {\n if (url[0] === \"/\") {\n return url;\n }\n const index = url.indexOf(\"/\", url.indexOf(\"//\") + 2);\n return index === -1 ? \"/\" : url.slice(index);\n};\nclass ServerRequestImpl extends Inspectable.Class {\n [TypeId];\n [HttpIncomingMessage.TypeId];\n source;\n url;\n headersOverride;\n remoteAddressOverride;\n constructor(source, url, headersOverride, remoteAddressOverride) {\n super();\n this[TypeId] = TypeId;\n this[HttpIncomingMessage.TypeId] = HttpIncomingMessage.TypeId;\n this.source = source;\n this.url = url;\n this.headersOverride = headersOverride;\n this.remoteAddressOverride = remoteAddressOverride;\n }\n toJSON() {\n return HttpIncomingMessage.inspect(this, {\n _id: \"HttpServerRequest\",\n method: this.method,\n url: this.originalUrl\n });\n }\n modify(options) {\n return new ServerRequestImpl(this.source, options.url ?? this.url, options.headers ?? this.headersOverride, \"remoteAddress\" in options ? options.remoteAddress : this.remoteAddressOverride);\n }\n get method() {\n return this.source.method.toUpperCase();\n }\n get originalUrl() {\n return this.source.url;\n }\n get remoteAddress() {\n return this.remoteAddressOverride ?? Option.none();\n }\n get headers() {\n this.headersOverride ??= Headers.fromInput(this.source.headers);\n return this.headersOverride;\n }\n cachedCookies;\n get cookies() {\n if (this.cachedCookies) {\n return this.cachedCookies;\n }\n return this.cachedCookies = Cookies.parseHeader(this.headers.cookie ?? \"\");\n }\n get stream() {\n return this.source.body ? Stream.fromReadableStream({\n evaluate: () => this.source.body,\n onError: cause => new HttpServerError({\n reason: new RequestParseError({\n request: this,\n cause\n })\n })\n }) : Stream.fail(new HttpServerError({\n reason: new RequestParseError({\n request: this,\n description: \"can not create stream from empty body\"\n })\n }));\n }\n textEffect;\n get text() {\n if (this.textEffect) {\n return this.textEffect;\n }\n this.textEffect = Effect.runSync(Effect.cached(Effect.tryPromise({\n try: () => this.source.text(),\n catch: cause => new HttpServerError({\n reason: new RequestParseError({\n request: this,\n cause\n })\n })\n })));\n return this.textEffect;\n }\n get json() {\n return Effect.flatMap(this.text, text => Effect.try({\n try: () => JSON.parse(text),\n catch: cause => new HttpServerError({\n reason: new RequestParseError({\n request: this,\n cause\n })\n })\n }));\n }\n get urlParamsBody() {\n return Effect.flatMap(this.text, _ => Effect.try({\n try: () => UrlParams.fromInput(new URLSearchParams(_)),\n catch: cause => new HttpServerError({\n reason: new RequestParseError({\n request: this,\n cause\n })\n })\n }));\n }\n multipartEffect;\n get multipart() {\n if (this.multipartEffect) {\n return this.multipartEffect;\n }\n this.multipartEffect = Effect.runSync(Effect.cached(Multipart.toPersisted(this.multipartStream)));\n return this.multipartEffect;\n }\n get multipartStream() {\n return Stream.pipeThroughChannel(Stream.mapError(this.stream, cause => Multipart.MultipartError.fromReason(\"InternalError\", cause)), Multipart.makeChannel(this.headers));\n }\n arrayBufferEffect;\n get arrayBuffer() {\n if (this.arrayBufferEffect) {\n return this.arrayBufferEffect;\n }\n this.arrayBufferEffect = Effect.runSync(Effect.cached(Effect.tryPromise({\n try: () => this.source.arrayBuffer(),\n catch: cause => new HttpServerError({\n reason: new RequestParseError({\n request: this,\n cause\n })\n })\n })));\n return this.arrayBufferEffect;\n }\n get upgrade() {\n return Effect.fail(new HttpServerError({\n reason: new RequestParseError({\n request: this,\n description: \"Not an upgradeable ServerRequest\"\n })\n }));\n }\n}\nclass ClientRequestImpl extends Inspectable.Class {\n [TypeId];\n [HttpIncomingMessage.TypeId];\n source;\n originalUrl;\n headersOverride;\n remoteAddressOverride;\n urlOverride;\n constructor(source, originalUrl, urlOverride, headersOverride, remoteAddressOverride) {\n super();\n this[TypeId] = TypeId;\n this[HttpIncomingMessage.TypeId] = HttpIncomingMessage.TypeId;\n this.source = source;\n this.originalUrl = originalUrl;\n this.urlOverride = urlOverride;\n this.headersOverride = headersOverride;\n this.remoteAddressOverride = remoteAddressOverride;\n }\n toJSON() {\n return HttpIncomingMessage.inspect(this, {\n _id: \"HttpServerRequest\",\n method: this.method,\n url: this.originalUrl\n });\n }\n modify(options) {\n return new ClientRequestImpl(this.source, this.originalUrl, options.url ?? this.url, options.headers ?? this.headersOverride, \"remoteAddress\" in options ? options.remoteAddress : this.remoteAddressOverride);\n }\n get method() {\n return this.source.method;\n }\n get url() {\n return this.urlOverride ?? removeHost(this.originalUrl);\n }\n get remoteAddress() {\n return this.remoteAddressOverride ?? Option.none();\n }\n get headers() {\n return this.headersOverride ??= this.source.headers;\n }\n cachedCookies;\n get cookies() {\n if (this.cachedCookies) {\n return this.cachedCookies;\n }\n return this.cachedCookies = Cookies.parseHeader(this.headers.cookie ?? \"\");\n }\n get stream() {\n const body = this.source.body;\n switch (body._tag) {\n case \"Empty\":\n {\n return Stream.empty;\n }\n case \"Uint8Array\":\n {\n return Stream.succeed(body.body);\n }\n case \"Stream\":\n {\n return Stream.mapError(body.stream, cause => requestParseError(this, undefined, cause));\n }\n case \"FormData\":\n {\n return streamFromReadable(this, new Response(body.formData).body);\n }\n case \"Raw\":\n {\n return rawBodyStream(this, body.body);\n }\n }\n }\n bytesEffect;\n get bytes() {\n if (this.bytesEffect) {\n return this.bytesEffect;\n }\n const body = this.source.body;\n let effect;\n switch (body._tag) {\n case \"Empty\":\n {\n effect = Effect.succeed(new Uint8Array(0));\n break;\n }\n case \"Uint8Array\":\n {\n effect = Effect.succeed(body.body);\n break;\n }\n case \"FormData\":\n {\n effect = bytesFromBodyInit(this, body.formData);\n break;\n }\n case \"Stream\":\n {\n effect = Stream.mkUint8Array(this.stream);\n break;\n }\n case \"Raw\":\n {\n effect = rawBodyBytes(this, body.body);\n break;\n }\n }\n this.bytesEffect = Effect.runSync(Effect.cached(effect));\n return this.bytesEffect;\n }\n get text() {\n return Effect.map(this.bytes, bytes => textDecoder.decode(bytes));\n }\n get json() {\n return Effect.flatMap(this.text, text => Effect.try({\n try: () => text === \"\" ? null : JSON.parse(text),\n catch: cause => requestParseError(this, undefined, cause)\n }));\n }\n get urlParamsBody() {\n return Effect.flatMap(this.text, _ => Effect.try({\n try: () => UrlParams.fromInput(new URLSearchParams(_)),\n catch: cause => requestParseError(this, undefined, cause)\n }));\n }\n multipartEffect;\n get multipart() {\n if (this.multipartEffect) {\n return this.multipartEffect;\n }\n this.multipartEffect = Effect.runSync(Effect.cached(Multipart.toPersisted(this.multipartStream)));\n return this.multipartEffect;\n }\n get multipartStream() {\n const formData = this.source.body._tag === \"FormData\" && this.source.body.formData;\n if (formData) {\n return Stream.fromIterable(formDataToParts(formData));\n }\n return Stream.pipeThroughChannel(Stream.mapError(this.stream, cause => Multipart.MultipartError.fromReason(\"InternalError\", cause)), Multipart.makeChannel(this.headers));\n }\n get arrayBuffer() {\n return Effect.map(this.bytes, bytes => bytes.slice().buffer);\n }\n get upgrade() {\n return Effect.fail(requestParseError(this, \"Not an upgradeable ServerRequest\"));\n }\n}\nconst getFormDataBody = request => {\n if (!HttpClientRequest.isHttpClientRequest(request.source)) {\n return undefined;\n }\n const body = request.source.body;\n if (body._tag === \"FormData\") {\n return body.formData;\n }\n if (body._tag === \"Raw\" && isFormData(body.body)) {\n return body.body;\n }\n return undefined;\n};\nconst rawBodyStream = (request, body) => {\n if (body instanceof Request) {\n return streamFromReadable(request, body.body);\n }\n if (isFormData(body)) {\n return streamFromReadable(request, new Response(body).body);\n }\n if (isReadableStream(body)) {\n return streamFromReadable(request, body);\n }\n return Stream.fail(requestParseError(request, \"Unsupported body type\"));\n};\nconst rawBodyBytes = (request, body) => {\n if (body instanceof Blob) {\n return bytesFromBodyInit(request, body);\n }\n if (body instanceof Request) {\n return Effect.tryPromise({\n try: () => body.arrayBuffer().then(buffer => new Uint8Array(buffer)),\n catch: cause => requestParseError(request, undefined, cause)\n });\n }\n return Effect.fail(requestParseError(request, \"Unsupported body type\"));\n};\nconst bytesFromBodyInit = (request, body) => Effect.tryPromise({\n try: () => new Response(body).arrayBuffer().then(buffer => new Uint8Array(buffer)),\n catch: cause => requestParseError(request, undefined, cause)\n});\nconst streamFromReadable = (request, body) => body ? Stream.fromReadableStream({\n evaluate: () => body,\n onError: cause => requestParseError(request, undefined, cause)\n}) : Stream.empty;\nconst requestParseError = (request, description, cause) => new HttpServerError({\n reason: new RequestParseError({\n request,\n ...(description === undefined ? undefined : {\n description\n }),\n ...(cause === undefined ? undefined : {\n cause\n })\n })\n});\nconst formDataToParts = formData => {\n const parts = [];\n for (const [key, value] of formData.entries()) {\n parts.push(typeof value === \"string\" ? new MultipartFieldPart(key, value) : new MultipartFilePart(key, value));\n }\n return parts;\n};\nclass MultipartFieldPart extends Inspectable.Class {\n [Multipart.TypeId];\n _tag = \"Field\";\n contentType = \"text/plain\";\n key;\n value;\n constructor(key, value) {\n super();\n this[Multipart.TypeId] = Multipart.TypeId;\n this.key = key;\n this.value = value;\n }\n toJSON() {\n return {\n _id: \"@effect/platform/Multipart/Part\",\n _tag: \"Field\",\n key: this.key,\n contentType: this.contentType,\n value: this.value\n };\n }\n}\nclass MultipartFilePart extends Inspectable.Class {\n [Multipart.TypeId];\n _tag = \"File\";\n key;\n name;\n contentType;\n content;\n contentEffect;\n constructor(key, file) {\n super();\n this[Multipart.TypeId] = Multipart.TypeId;\n this.key = key;\n this.name = file.name;\n this.contentType = file.type;\n this.content = Stream.fromReadableStream({\n evaluate: () => file.stream(),\n onError: cause => Multipart.MultipartError.fromReason(\"InternalError\", cause)\n });\n this.contentEffect = Effect.tryPromise({\n try: () => file.arrayBuffer().then(buffer => new Uint8Array(buffer)),\n catch: cause => Multipart.MultipartError.fromReason(\"InternalError\", cause)\n });\n }\n toJSON() {\n return {\n _id: \"@effect/platform/Multipart/Part\",\n _tag: \"File\",\n key: this.key,\n name: this.name,\n contentType: this.contentType\n };\n }\n}\nconst isReadableStream = u => typeof ReadableStream !== \"undefined\" && u instanceof ReadableStream;\nconst isFormData = u => typeof FormData !== \"undefined\" && u instanceof FormData;\nconst textDecoder = /*#__PURE__*/new TextDecoder();\n/**\n * Attempts to construct an absolute `URL` for a server request safely.\n *\n * **Details**\n *\n * The host comes from the `host` header, defaulting to `localhost`, and the\n * protocol is `https` only when `x-forwarded-proto` is `https`; invalid URLs\n * return `Option.none`.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toURL = self => {\n const host = self.headers.host ?? \"localhost\";\n const protocol = self.headers[\"x-forwarded-proto\"] === \"https\" ? \"https\" : \"http\";\n try {\n return Option.some(new URL(self.url, `${protocol}://${host}`));\n } catch {\n return Option.none();\n }\n};\n/**\n * Converts an `HttpServerRequest` safely to a Web `Request` as a `Result`.\n *\n * **Details**\n *\n * If the source is already a Web `Request`, it is returned unchanged. Otherwise\n * an absolute URL is derived from the request; invalid URLs fail with a\n * `RequestParseError`.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toWebResult = (self, options) => {\n if (self.source instanceof Request) {\n return Result.succeed(self.source);\n }\n const url = toURL(self);\n if (Option.isNone(url)) {\n return Result.fail(new RequestParseError({\n request: self,\n description: \"Invalid URL\"\n }));\n }\n const requestInit = {\n method: self.method,\n headers: self.headers\n };\n if (options?.signal) {\n requestInit.signal = options.signal;\n }\n if (hasBody(self.method)) {\n requestInit.body = Stream.toReadableStreamWith(self.stream, options?.context ?? Context.empty());\n requestInit.duplex = \"half\";\n }\n return Result.succeed(new Request(url.value, requestInit));\n};\n/**\n * Converts an `HttpServerRequest` to a Web `Request` in `Effect`.\n *\n * **Details**\n *\n * The current context is used when streaming the request body into the Web\n * request.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toWeb = (self, options) => Effect.contextWith(context => Effect.fromResult(toWebResult(self, {\n context,\n signal: options?.signal\n})));\n//# sourceMappingURL=HttpServerRequest.js.map","import * as Effect from \"../../../Effect.js\";\n/** @internal */\nexport const requestPreResponseHandlers = /*#__PURE__*/new WeakMap();\n/** @internal */\nexport const appendPreResponseHandlerUnsafe = (request, handler) => {\n const prev = requestPreResponseHandlers.get(request.source);\n const next = prev ? (request, response) => Effect.flatMap(prev(request, response), response => handler(request, response)) : handler;\n requestPreResponseHandlers.set(request.source, next);\n};\n//# sourceMappingURL=preResponseHandler.js.map","/**\n * Wraps HTTP server apps with request and response behavior.\n *\n * A middleware is a function from one HTTP server app effect to another. The app\n * runs with the current `HttpServerRequest` in its context, so middleware can\n * inspect or rewrite the request, provide request-scoped services, attach hooks\n * before the response is sent, or observe the app exit. This module includes\n * middleware for response logging, server tracing, forwarded proxy headers,\n * parsed search parameters, and CORS response headers.\n *\n * @since 4.0.0\n */\nimport { Clock } from \"../../Clock.js\";\nimport * as Context from \"../../Context.js\";\nimport * as Effect from \"../../Effect.js\";\nimport * as Exit from \"../../Exit.js\";\nimport { constant, constFalse } from \"../../Function.js\";\nimport * as internalEffect from \"../../internal/effect.js\";\nimport * as Layer from \"../../Layer.js\";\nimport * as Option from \"../../Option.js\";\nimport { TracerEnabled } from \"../../References.js\";\nimport { ParentSpan } from \"../../Tracer.js\";\nimport * as Headers from \"./Headers.js\";\nimport { causeResponseStripped } from \"./HttpServerError.js\";\nimport { HttpServerRequest } from \"./HttpServerRequest.js\";\nimport * as Request from \"./HttpServerRequest.js\";\nimport * as Response from \"./HttpServerResponse.js\";\nimport * as TraceContext from \"./HttpTraceContext.js\";\nimport { appendPreResponseHandlerUnsafe } from \"./internal/preResponseHandler.js\";\n/**\n * Defines an `HttpMiddleware` while preserving its precise type.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = middleware => middleware;\nconst loggerDisabledRequests = /*#__PURE__*/new WeakSet();\nconst stripSearchAndHash = url => {\n const queryIndex = url.indexOf(\"?\");\n const hashIndex = url.indexOf(\"#\");\n if (queryIndex === -1) {\n return hashIndex === -1 ? url : url.slice(0, hashIndex);\n }\n if (hashIndex === -1) {\n return url.slice(0, queryIndex);\n }\n return url.slice(0, Math.min(queryIndex, hashIndex));\n};\n/**\n * Runs an effect with HTTP response logging disabled for the current server request.\n *\n * @category Logger\n * @since 4.0.0\n */\nexport const withLoggerDisabled = self => Effect.withFiber(fiber => {\n const request = Context.getUnsafe(fiber.context, HttpServerRequest);\n loggerDisabledRequests.add(request.source);\n return self;\n});\n/**\n * Context reference for a predicate that disables server-side tracing for matching requests.\n *\n * @category Tracer\n * @since 4.0.0\n */\nexport const TracerDisabledWhen = /*#__PURE__*/Context.Reference(\"effect/http/HttpMiddleware/TracerDisabledWhen\", {\n defaultValue: () => constFalse\n});\n/**\n * Creates a layer that disables server-side tracing for requests whose URL exactly matches one of the supplied URLs.\n *\n * @category Tracer\n * @since 4.0.0\n */\nexport const layerTracerDisabledForUrls = urls => Layer.succeed(TracerDisabledWhen)(req => urls.includes(req.url));\n/**\n * Context reference for generating server span names from HTTP server requests.\n *\n * @category Tracer\n * @since 4.0.0\n */\nexport const SpanNameGenerator = /*#__PURE__*/Context.Reference(\"@effect/platform/HttpMiddleware/SpanNameGenerator\", {\n defaultValue: () => request => `http.server ${request.method}`\n});\n/**\n * Middleware that logs sent HTTP responses with request method, request URL, and response status annotations.\n *\n * @category Logger\n * @since 4.0.0\n */\nexport const logger = /*#__PURE__*/make(httpApp => Effect.withFiber(fiber => {\n const request = Context.getUnsafe(fiber.context, HttpServerRequest);\n const path = stripSearchAndHash(request.url);\n return Effect.withLogSpan(Effect.flatMap(Effect.exit(httpApp), exit => {\n if (loggerDisabledRequests.has(request.source)) {\n return exit;\n } else if (exit._tag === \"Failure\") {\n const [response, cause] = causeResponseStripped(exit.cause);\n return Effect.andThen(Effect.annotateLogs(Effect.log(Option.getOrElse(cause, () => \"Sent HTTP Response\")), {\n \"http.method\": request.method,\n \"http.url\": path,\n \"http.status\": response.status\n }), exit);\n }\n return Effect.andThen(Effect.annotateLogs(Effect.log(\"Sent HTTP response\"), {\n \"http.method\": request.method,\n \"http.url\": path,\n \"http.status\": exit.value.status\n }), exit);\n }), \"http.span\");\n}));\n/**\n * Middleware that creates a server trace span for each request and records request and response HTTP attributes.\n *\n * @category Tracer\n * @since 4.0.0\n */\nexport const tracer = /*#__PURE__*/make(httpApp => Effect.withFiber(fiber => {\n const request = Context.getUnsafe(fiber.context, HttpServerRequest);\n const disabled = !fiber.getRef(TracerEnabled) || fiber.getRef(TracerDisabledWhen)(request);\n if (disabled) {\n return httpApp;\n }\n const nameGenerator = fiber.getRef(SpanNameGenerator);\n const span = internalEffect.makeSpanUnsafe(fiber, nameGenerator(request), {\n parent: Option.getOrUndefined(TraceContext.fromHeaders(request.headers)),\n kind: \"server\"\n });\n const prevServices = fiber.context;\n fiber.setContext(Context.add(fiber.context, ParentSpan, span));\n return Effect.onExitPrimitive(httpApp, exit => {\n fiber.setContext(prevServices);\n const endTime = fiber.getRef(Clock).currentTimeNanosUnsafe();\n fiber.currentDispatcher.scheduleTask(() => {\n const url = Request.toURL(request);\n if (Option.isSome(url) && (url.value.username !== \"\" || url.value.password !== \"\")) {\n url.value.username = \"REDACTED\";\n url.value.password = \"REDACTED\";\n }\n const redactedHeaderNames = fiber.getRef(Headers.CurrentRedactedNames);\n const requestHeaders = Headers.redact(request.headers, redactedHeaderNames);\n span.attribute(\"http.request.method\", request.method);\n if (Option.isSome(url)) {\n span.attribute(\"url.full\", url.value.toString());\n span.attribute(\"url.path\", url.value.pathname);\n const query = url.value.search.slice(1);\n if (query !== \"\") {\n span.attribute(\"url.query\", url.value.search.slice(1));\n }\n span.attribute(\"url.scheme\", url.value.protocol.slice(0, -1));\n }\n if (request.headers[\"user-agent\"] !== undefined) {\n span.attribute(\"user_agent.original\", request.headers[\"user-agent\"]);\n }\n for (const name in requestHeaders) {\n span.attribute(`http.request.header.${name}`, String(requestHeaders[name]));\n }\n if (Option.isSome(request.remoteAddress)) {\n span.attribute(\"client.address\", request.remoteAddress.value);\n }\n let response;\n let spanExit = exit;\n if (Exit.isFailure(exit)) {\n const [failureResponse, cause] = causeResponseStripped(exit.cause);\n response = failureResponse;\n spanExit = Option.isSome(cause) ? Exit.failCause(cause.value) : Exit.succeed(response);\n } else {\n response = exit.value;\n }\n span.attribute(\"http.response.status_code\", response.status);\n const responseHeaders = Headers.redact(response.headers, redactedHeaderNames);\n for (const name in responseHeaders) {\n span.attribute(`http.response.header.${name}`, String(responseHeaders[name]));\n }\n span.end(endTime, spanExit);\n }, 0);\n return undefined;\n }, true);\n}));\n/**\n * Middleware that trusts `X-Forwarded-Host` and `X-Forwarded-For`, updating the request host header and remote address.\n *\n * @category Proxying\n * @since 4.0.0\n */\nexport const xForwardedHeaders = /*#__PURE__*/make(httpApp => Effect.updateService(httpApp, HttpServerRequest, request => request.headers[\"x-forwarded-host\"] ? request.modify({\n headers: Headers.set(request.headers, \"host\", request.headers[\"x-forwarded-host\"]),\n remoteAddress: Option.fromNullishOr(request.headers[\"x-forwarded-for\"]?.split(\",\")[0].trim())\n}) : request));\n/**\n * Middleware that parses the current request URL's search parameters and provides them as `ParsedSearchParams`.\n *\n * @category search params\n * @since 4.0.0\n */\nexport const searchParamsParser = httpApp => Effect.withFiber(fiber => {\n const services = fiber.context;\n const request = Context.getUnsafe(services, HttpServerRequest);\n const params = Request.searchParamsFromURL(new URL(request.originalUrl));\n return Effect.provideService(httpApp, Request.ParsedSearchParams, params);\n});\n/**\n * Middleware that handles CORS preflight requests and adds configured CORS headers to HTTP responses.\n *\n * @category CORS\n * @since 4.0.0\n */\nexport const cors = options => {\n const opts = {\n allowedOrigins: options?.allowedOrigins ?? [],\n allowedMethods: options?.allowedMethods ?? [\"GET\", \"HEAD\", \"PUT\", \"PATCH\", \"POST\", \"DELETE\"],\n allowedHeaders: options?.allowedHeaders ?? [],\n exposedHeaders: options?.exposedHeaders ?? [],\n credentials: options?.credentials ?? false,\n maxAge: options?.maxAge\n };\n const isAllowedOrigin = typeof opts.allowedOrigins === \"function\" ? opts.allowedOrigins : origin => opts.allowedOrigins.includes(origin);\n const allowOrigin = typeof opts.allowedOrigins === \"function\" || opts.allowedOrigins.length > 1 ? originHeader => {\n if (!isAllowedOrigin(originHeader)) return undefined;\n return {\n \"access-control-allow-origin\": originHeader,\n vary: \"Origin\"\n };\n } : opts.allowedOrigins.length === 0 ? constant({\n \"access-control-allow-origin\": \"*\"\n }) : constant({\n \"access-control-allow-origin\": opts.allowedOrigins[0],\n vary: \"Origin\"\n });\n const allowMethods = opts.allowedMethods.length > 0 ? {\n \"access-control-allow-methods\": opts.allowedMethods.join(\", \")\n } : undefined;\n const allowCredentials = opts.credentials ? {\n \"access-control-allow-credentials\": \"true\"\n } : undefined;\n const allowHeaders = accessControlRequestHeaders => {\n if (opts.allowedHeaders.length === 0 && accessControlRequestHeaders) {\n return {\n vary: \"Access-Control-Request-Headers\",\n \"access-control-allow-headers\": accessControlRequestHeaders\n };\n }\n if (opts.allowedHeaders) {\n return {\n \"access-control-allow-headers\": opts.allowedHeaders.join(\",\")\n };\n }\n return undefined;\n };\n const exposeHeaders = opts.exposedHeaders.length > 0 ? {\n \"access-control-expose-headers\": opts.exposedHeaders.join(\",\")\n } : undefined;\n const maxAge = opts.maxAge ? {\n \"access-control-max-age\": opts.maxAge.toString()\n } : undefined;\n const headersFromRequest = request => {\n const origin = request.headers[\"origin\"];\n return Headers.fromRecordUnsafe({\n ...allowOrigin(origin),\n ...allowCredentials,\n ...exposeHeaders\n });\n };\n const headersFromRequestOptions = request => {\n const origin = request.headers[\"origin\"];\n const accessControlRequestHeaders = request.headers[\"access-control-request-headers\"];\n return Headers.fromRecordUnsafe({\n ...allowOrigin(origin),\n ...allowCredentials,\n ...exposeHeaders,\n ...allowMethods,\n ...allowHeaders(accessControlRequestHeaders),\n ...maxAge\n });\n };\n const preResponseHandler = (request, response) => Effect.succeed(Response.setHeaders(response, headersFromRequest(request)));\n return httpApp => Effect.withFiber(fiber => {\n const request = Context.getUnsafe(fiber.context, HttpServerRequest);\n if (request.method === \"OPTIONS\") {\n return Effect.succeed(Response.empty({\n status: 204,\n headers: headersFromRequestOptions(request)\n }));\n }\n appendPreResponseHandlerUnsafe(request, preResponseHandler);\n return httpApp;\n });\n};\n//# sourceMappingURL=HttpMiddleware.js.map","import * as Context from \"../../Context.js\";\nimport * as Effect from \"../../Effect.js\";\nimport * as Exit from \"../../Exit.js\";\nimport * as Fiber from \"../../Fiber.js\";\nimport { dual } from \"../../Function.js\";\nimport { reportCauseUnsafe } from \"../../internal/effect.js\";\nimport * as Layer from \"../../Layer.js\";\nimport * as Scope from \"../../Scope.js\";\nimport * as Stream from \"../../Stream.js\";\nimport * as HttpBody from \"./HttpBody.js\";\nimport { tracer } from \"./HttpMiddleware.js\";\nimport { causeResponse, ClientAbort, HttpServerError, InternalError } from \"./HttpServerError.js\";\nimport { HttpServerRequest } from \"./HttpServerRequest.js\";\nimport * as Request from \"./HttpServerRequest.js\";\nimport * as Response from \"./HttpServerResponse.js\";\nimport { appendPreResponseHandlerUnsafe, requestPreResponseHandlers } from \"./internal/preResponseHandler.js\";\n/**\n * Runs an HTTP server effect, sends the produced response with the supplied handler, and converts failures into HTTP responses.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const toHandled = (self, handleResponse, middleware) => {\n const handleCause = cause => Effect.flatMapEager(causeResponse(cause), ([response, cause]) => {\n const fiber = Fiber.getCurrent();\n reportCauseUnsafe(fiber, cause);\n const request = Context.getUnsafe(fiber.context, HttpServerRequest);\n const handler = requestPreResponseHandlers.get(request.source);\n const cont = cause.reasons.length === 0 ? Effect.succeed(response) : Effect.failCause(cause);\n if (handler === undefined) {\n ;\n request[handledSymbol] = true;\n return Effect.flatMapEager(handleResponse(request, response), () => cont);\n }\n return Effect.flatMapEager(Effect.flatMapEager(handler(request, response), response => {\n ;\n request[handledSymbol] = true;\n return handleResponse(request, response);\n }), () => cont);\n });\n const responded = Effect.matchCauseEffect(self, {\n onSuccess: response => {\n const fiber = Fiber.getCurrent();\n const request = Context.getUnsafe(fiber.context, HttpServerRequest);\n const handler = requestPreResponseHandlers.get(request.source);\n if (handler === undefined) {\n ;\n request[handledSymbol] = true;\n return Effect.mapEager(handleResponse(request, response), () => response);\n }\n return Effect.flatMapEager(handler(request, response), sentResponse => {\n ;\n request[handledSymbol] = true;\n return Effect.mapEager(handleResponse(request, sentResponse), () => response);\n });\n },\n onFailure: handleCause\n });\n const withMiddleware = middleware === undefined ? tracer(responded) : Effect.matchCauseEffect(tracer(middleware(responded)), {\n onFailure(cause) {\n const fiber = Fiber.getCurrent();\n reportCauseUnsafe(fiber, cause);\n const request = Context.getUnsafe(fiber.context, HttpServerRequest);\n if (handledSymbol in request) return Effect.void;\n return Effect.matchCauseEffectEager(causeResponse(cause), {\n onFailure(_) {\n return handleResponse(request, Response.empty({\n status: 500\n }));\n },\n onSuccess([response]) {\n return handleResponse(request, response);\n }\n });\n },\n onSuccess(response) {\n const fiber = Fiber.getCurrent();\n const request = Context.getUnsafe(fiber.context, Request.HttpServerRequest);\n return handledSymbol in request ? Effect.void : handleResponse(request, response);\n }\n });\n return Effect.uninterruptible(scoped(withMiddleware));\n};\nconst handledSymbol = /*#__PURE__*/Symbol.for(\"effect/http/HttpEffect/handled\");\n/**\n * Disables automatic closing for an HTTP request scope.\n *\n * **Gotchas**\n *\n * Use only when another owner will close the scope; otherwise resources attached\n * to the request scope can leak.\n *\n * @category resource management\n * @since 4.0.0\n */\nexport const scopeDisableClose = scope => {\n ;\n scope[scopeEjected] = true;\n};\n/**\n * Returns a streaming server response that closes the request scope when the body stream exits.\n *\n * @category resource management\n * @since 4.0.0\n */\nexport const scopeTransferToStream = response => {\n if (response.body._tag !== \"Stream\") {\n return response;\n }\n const fiber = Fiber.getCurrent();\n const scope = Context.getUnsafe(fiber.context, Scope.Scope);\n scopeDisableClose(scope);\n return Response.setBody(response, HttpBody.stream(Stream.onExit(response.body.stream, exit => Scope.close(scope, exit)), response.body.contentType, response.body.contentLength));\n};\nconst scopeEjected = /*#__PURE__*/Symbol.for(\"effect/http/HttpEffect/scopeEjected\");\nconst scoped = effect => Effect.withFiber(fiber => {\n const scope = Scope.makeUnsafe();\n const prevServices = fiber.context;\n fiber.setContext(Context.add(fiber.context, Scope.Scope, scope));\n return Effect.onExitPrimitive(effect, exit => {\n fiber.setContext(prevServices);\n if (scopeEjected in scope) return undefined;\n return Scope.closeUnsafe(scope, exit);\n }, true);\n});\n/**\n * Registers an additional pre-response handler for the current HTTP server request.\n *\n * @category fiber refs\n * @since 4.0.0\n */\nexport const appendPreResponseHandler = handler => HttpServerRequest.use(request => {\n appendPreResponseHandlerUnsafe(request, handler);\n return Effect.void;\n});\nexport {\n/**\n * Registers a pre-response handler for the supplied HTTP server request.\n *\n * @category fiber refs\n * @since 4.0.0\n */\nappendPreResponseHandlerUnsafe };\n/**\n * Runs an effect after registering a pre-response handler for the current HTTP server request.\n *\n * @category fiber refs\n * @since 4.0.0\n */\nexport const withPreResponseHandler = /*#__PURE__*/dual(2, (self, handler) => HttpServerRequest.use(request => {\n appendPreResponseHandlerUnsafe(request, handler);\n return self;\n}));\n/**\n * Converts an HTTP server effect into a Web `Request` handler using the supplied base context and optional middleware.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toWebHandlerWith = context => (self, middleware) => {\n const resolveSymbol = Symbol.for(\"@effect/platform/HttpApp/resolve\");\n const httpApp = toHandled(self, (request, response) => {\n response = scopeTransferToStream(response);\n request[resolveSymbol](Response.toWeb(response, {\n withoutBody: request.method === \"HEAD\",\n context\n }));\n return Effect.void;\n }, middleware);\n return (request, reqContext) => new Promise(resolve => {\n const contextMap = new Map(context.mapUnsafe);\n if (Context.isContext(reqContext)) {\n for (const [key, value] of reqContext.mapUnsafe) {\n contextMap.set(key, value);\n }\n }\n const httpServerRequest = Request.fromWeb(request);\n contextMap.set(HttpServerRequest.key, httpServerRequest);\n httpServerRequest[resolveSymbol] = resolve;\n const fiber = Effect.runForkWith(Context.makeUnsafe(contextMap))(httpApp);\n request.signal?.addEventListener(\"abort\", () => {\n fiber.interruptUnsafe(undefined, ClientAbort.annotation);\n }, {\n once: true\n });\n });\n};\n/**\n * Converts an HTTP server effect into a Web `Request` handler using an empty base context.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toWebHandler = /*#__PURE__*/toWebHandlerWith(/*#__PURE__*/Context.empty());\n/**\n * Builds a Web `Request` handler from a layer and handler factory, returning the handler with a `dispose` function for the layer scope.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toWebHandlerLayerWith = (layer, options) => {\n const scope = Scope.makeUnsafe();\n const dispose = () => Effect.runPromise(Scope.close(scope, Exit.void));\n let handlerCache;\n let handlerPromise;\n function handler(request, context) {\n if (handlerCache) {\n return handlerCache(request, context);\n }\n handlerPromise ??= Effect.runPromise(Effect.gen(function* () {\n const context = yield* options.memoMap ? Layer.buildWithMemoMap(layer, options.memoMap, scope) : Layer.buildWithScope(layer, scope);\n return handlerCache = toWebHandlerWith(context)(yield* options.toHandler(context), options.middleware);\n }));\n return handlerPromise.then(f => f(request, context));\n }\n return {\n dispose,\n handler: handler\n };\n};\n/**\n * Builds a Web `Request` handler for an HTTP server effect using a layer to provide its services, returning the handler with a `dispose` function.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toWebHandlerLayer = (self, layer, options) => toWebHandlerLayerWith(layer, {\n ...options,\n toHandler: () => Effect.succeed(self)\n});\n/**\n * Adapts a Web `Request` handler into an HTTP server effect for the current `HttpServerRequest`.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const fromWebHandler = handler => Effect.callback((resume, signal) => {\n const fiber = Fiber.getCurrent();\n const request = Context.getUnsafe(fiber.context, HttpServerRequest);\n const requestResult = Request.toWebResult(request, {\n signal,\n context: fiber.context\n });\n if (requestResult._tag === \"Failure\") {\n return resume(Effect.fail(new HttpServerError({\n reason: requestResult.failure\n })));\n }\n handler(requestResult.success).then(response => resume(Effect.succeed(Response.fromWeb(response))), cause => resume(Effect.fail(new HttpServerError({\n reason: new InternalError({\n cause,\n request,\n description: \"HttpApp.fromWebHandler: Error in handler\"\n })\n }))));\n});\n//# sourceMappingURL=HttpEffect.js.map","/**\n * HTTP entity tag values and metadata-based generator layers.\n *\n * ETags are validators for a specific representation of a resource. Servers put\n * them in `ETag` response headers so clients and intermediaries can revalidate\n * cached content with `If-None-Match`, or protect writes with preconditions such\n * as `If-Match`.\n *\n * @since 4.0.0\n */\nimport * as Context from \"../../Context.js\";\nimport * as Effect from \"../../Effect.js\";\nimport * as Layer from \"../../Layer.js\";\nimport * as Option from \"../../Option.js\";\n/**\n * Formats an `Etag` as an HTTP header value, including quotes and the `W/` prefix for weak tags.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toString = self => {\n switch (self._tag) {\n case \"Weak\":\n return `W/\"${self.value}\"`;\n case \"Strong\":\n return `\"${self.value}\"`;\n }\n};\n/**\n * Service for generating ETags from filesystem file information or Web `File`-like metadata.\n *\n * @category models\n * @since 4.0.0\n */\nexport class Generator extends /*#__PURE__*/Context.Service()(\"effect/http/Etag/Generator\") {}\nconst fromFileInfo = info => {\n const mtime = Option.match(info.mtime, {\n onNone: () => \"0\",\n onSome: mtime => mtime.getTime().toString(16)\n });\n return `${info.size.toString(16)}-${mtime}`;\n};\nconst fromFileWeb = file => {\n return `${file.size.toString(16)}-${file.lastModified.toString(16)}`;\n};\n/**\n * Layer that provides a `Generator` which produces strong ETags from file size\n * and modification time metadata.\n *\n * **When to use**\n *\n * Use when you need the `Generator` service to produce strong ETags and file\n * size plus modification time reliably change for every byte-level change.\n *\n * **Gotchas**\n *\n * This layer marks metadata-derived tags as strong. If the underlying storage\n * can update file contents without changing the recorded size or modification\n * time, those tags can stop representing byte-for-byte identity.\n *\n * @see {@link layerWeak} for weak metadata-derived ETags when byte-for-byte identity is not required\n * @see {@link Generator} for the service provided by this layer\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layer = /*#__PURE__*/Layer.succeed(Generator)({\n fromFileInfo(info) {\n return Effect.sync(() => ({\n _tag: \"Strong\",\n value: fromFileInfo(info)\n }));\n },\n fromFileWeb(file) {\n return Effect.sync(() => ({\n _tag: \"Strong\",\n value: fromFileWeb(file)\n }));\n }\n});\n/**\n * Layer that provides a `Generator` which produces weak ETags from file size and modification time metadata.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerWeak = /*#__PURE__*/Layer.succeed(Generator)({\n fromFileInfo(info) {\n return Effect.sync(() => ({\n _tag: \"Weak\",\n value: fromFileInfo(info)\n }));\n },\n fromFileWeb(file) {\n return Effect.sync(() => ({\n _tag: \"Weak\",\n value: fromFileWeb(file)\n }));\n }\n});\n//# sourceMappingURL=Etag.js.map","/**\n * Platform-specific support for serving files as HTTP server responses.\n *\n * `HttpPlatform` is the boundary between the portable HTTP response model and\n * the runtime that knows how to stream bytes from the host platform. Server\n * code uses this service when it needs to return local files, static assets,\n * downloads, byte ranges, or Web `File`-like values without constructing the\n * response body by hand.\n *\n * @since 4.0.0\n */\nimport * as Context from \"../../Context.js\";\nimport * as Effect from \"../../Effect.js\";\nimport * as FileSystem from \"../../FileSystem.js\";\nimport { identity } from \"../../Function.js\";\nimport * as Layer from \"../../Layer.js\";\nimport * as Option from \"../../Option.js\";\nimport * as Stream from \"../../Stream.js\";\nimport * as Etag from \"./Etag.js\";\nimport * as Headers from \"./Headers.js\";\nimport * as Response from \"./HttpServerResponse.js\";\n/**\n * Service for platform-specific HTTP response helpers, including file-backed server responses.\n *\n * @category services\n * @since 4.0.0\n */\nexport class HttpPlatform extends /*#__PURE__*/Context.Service()(\"effect/http/HttpPlatform\") {}\n/**\n * Creates an `HttpPlatform` service from platform-specific file response constructors, using `FileSystem` and `Etag.Generator`.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = /*#__PURE__*/Effect.fnUntraced(function* (impl) {\n const fs = yield* FileSystem.FileSystem;\n const etagGen = yield* Etag.Generator;\n return HttpPlatform.of({\n fileResponse: Effect.fnUntraced(function* (path, options) {\n const info = yield* fs.stat(path);\n const etag = yield* etagGen.fromFileInfo(info);\n const start = Number(options?.offset ?? 0);\n const end = options?.bytesToRead !== undefined ? start + Number(options.bytesToRead) : undefined;\n const headers = Headers.set(options?.headers ? Headers.fromInput(options.headers) : Headers.empty, \"etag\", Etag.toString(etag));\n if (Option.isSome(info.mtime)) {\n ;\n headers[\"last-modified\"] = info.mtime.value.toUTCString();\n }\n const contentLength = end !== undefined ? end - start : Number(info.size) - start;\n return impl.fileResponse(path, options?.status ?? 200, options?.statusText, headers, start, end, contentLength);\n }),\n fileWebResponse(file, options) {\n return Effect.map(etagGen.fromFileWeb(file), etag => {\n const headers = Headers.merge(options?.headers ? Headers.fromInput(options.headers) : Headers.empty, Headers.fromRecordUnsafe({\n etag: Etag.toString(etag),\n \"last-modified\": new Date(file.lastModified).toUTCString()\n }));\n return impl.fileWebResponse(file, options?.status ?? 200, options?.statusText, headers, options);\n });\n }\n });\n});\n/**\n * Provides the default `HttpPlatform` implementation for serving file paths and\n * `File`-like values as streamed HTTP responses.\n *\n * **Details**\n *\n * The layer uses the `FileSystem` and weak ETag services to add file metadata\n * headers such as `etag` and `last-modified`.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layer = /*#__PURE__*/Layer.effect(HttpPlatform)(Effect.flatMap(FileSystem.FileSystem, fs => make({\n fileResponse(path, status, statusText, headers, start, end, contentLength) {\n return Response.stream(fs.stream(path, {\n offset: start,\n bytesToRead: end !== undefined ? end - start : undefined\n }), {\n contentLength,\n headers,\n status,\n statusText\n });\n },\n fileWebResponse(file, status, statusText, headers, _options) {\n return Response.stream(Stream.fromReadableStream({\n evaluate: () => file.stream(),\n onError: identity\n }), {\n headers,\n status,\n statusText\n });\n }\n}))).pipe(/*#__PURE__*/Layer.provide(Etag.layerWeak));\n//# sourceMappingURL=HttpPlatform.js.map","/**\n * Service for serving Effect HTTP responses on a concrete HTTP server.\n *\n * Platform adapters provide `HttpServer`, and routers or applications consume\n * it to run an `HttpServerResponse` effect for each incoming request. The\n * service exposes the listening address, while this module also includes helpers\n * for address formatting, server logging, and clients that target the current\n * server in tests.\n *\n * @since 4.0.0\n */\nimport * as Context from \"../../Context.js\";\nimport * as Effect from \"../../Effect.js\";\nimport * as FileSystem from \"../../FileSystem.js\";\nimport { dual } from \"../../Function.js\";\nimport * as Layer from \"../../Layer.js\";\nimport * as Path from \"../../Path.js\";\nimport * as Etag from \"./Etag.js\";\nimport * as HttpClient from \"./HttpClient.js\";\nimport * as ClientRequest from \"./HttpClientRequest.js\";\nimport * as HttpPlatform from \"./HttpPlatform.js\";\n/**\n * Service tag for an HTTP server runtime.\n *\n * **Details**\n *\n * The service can serve an HTTP response effect and exposes the address where the\n * server is listening.\n *\n * @category models\n * @since 4.0.0\n */\nexport class HttpServer extends /*#__PURE__*/Context.Service()(\"effect/http/HttpServer\") {}\n/**\n * Constructs an `HttpServer` service from a serving implementation and listening\n * address.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = options => options;\n/**\n * Creates a layer that starts serving an HTTP response effect with the current\n * `HttpServer`.\n *\n * **Details**\n *\n * The request service is supplied by the server for each request; the returned\n * layer still requires the server, a scope, and any non-request dependencies of\n * the response effect or middleware.\n *\n * @category accessors\n * @since 4.0.0\n */\nexport const serve = /*#__PURE__*/dual(args => Effect.isEffect(args[0]), (effect, middleware) => Layer.effectDiscard(HttpServer.use(server => server.serve(effect, middleware))));\n/**\n * Effect that starts serving an HTTP response effect with the current\n * `HttpServer`.\n *\n * **Details**\n *\n * The request service is supplied by the server for each request; the effect\n * requires a scope and any non-request dependencies of the response effect or\n * middleware.\n *\n * @category accessors\n * @since 4.0.0\n */\nexport const serveEffect = /*#__PURE__*/dual(args => Effect.isEffect(args[0]), (effect, middleware) => HttpServer.use(server => server.serve(effect, middleware)));\n/**\n * Formats a server address as a display string.\n *\n * **Details**\n *\n * TCP addresses are formatted as `http://host:port`; Unix socket addresses are\n * formatted as `unix://path`.\n *\n * @category address\n * @since 4.0.0\n */\nexport const formatAddress = address => {\n switch (address._tag) {\n case \"UnixAddress\":\n return `unix://${address.path}`;\n case \"TcpAddress\":\n return `http://${address.hostname}:${address.port}`;\n }\n};\n/**\n * Reads the current server address, formats it with `formatAddress`, and passes\n * the formatted address to the supplied effectful function.\n *\n * @category address\n * @since 4.0.0\n */\nexport const addressFormattedWith = f => Effect.flatMap(HttpServer, server => f(formatAddress(server.address)));\n/**\n * Logs the formatted address of the current HTTP server.\n *\n * @category address\n * @since 4.0.0\n */\nexport const logAddress = /*#__PURE__*/addressFormattedWith(_ => Effect.log(`Listening on ${_}`));\n/**\n * Adds address logging to a layer that provides an `HttpServer`.\n *\n * @category address\n * @since 4.0.0\n */\nexport const withLogAddress = layer => Layer.effectDiscard(logAddress).pipe(Layer.provideMerge(layer));\n/**\n * Builds an `HttpClient` that sends requests to the current test HTTP server.\n *\n * **Details**\n *\n * For TCP servers, requests are prefixed with the server URL and `0.0.0.0` is\n * rewritten to `127.0.0.1`.\n *\n * **Gotchas**\n *\n * Unix socket addresses are not supported.\n *\n * @category testing\n * @since 4.0.0\n */\nexport const makeTestClient = /*#__PURE__*/Effect.gen(function* () {\n const server = yield* HttpServer;\n const client = yield* HttpClient.HttpClient;\n const address = server.address;\n if (address._tag === \"UnixAddress\") {\n return yield* Effect.die(new Error(\"HttpServer.layerTestClient: UnixAddress not supported\"));\n }\n const host = address.hostname === \"0.0.0.0\" ? \"127.0.0.1\" : address.hostname;\n const url = `http://${host}:${address.port}`;\n return HttpClient.mapRequest(client, ClientRequest.prependUrl(url));\n});\n/**\n * Layer that provides the test `HttpClient` created by `makeTestClient`.\n *\n * @category testing\n * @since 4.0.0\n */\nexport const layerTestClient = /*#__PURE__*/Layer.effect(HttpClient.HttpClient)(makeTestClient);\n/**\n * Layer that provides the platform services commonly needed by HTTP\n * server tests.\n *\n * **Details**\n *\n * It includes `HttpPlatform`, `Path`, a weak ETag generator, and a no-op\n * `FileSystem`.\n *\n * @category testing\n * @since 4.0.0\n */\nexport const layerServices = /*#__PURE__*/Layer.mergeAll(HttpPlatform.layer, Path.layer, Etag.layerWeak).pipe(/*#__PURE__*/Layer.provideMerge(/*#__PURE__*/FileSystem.layerNoop({})));\n//# sourceMappingURL=HttpServer.js.map","/**\n * Builds server-side routers for Effect HTTP applications.\n *\n * `HttpRouter` collects routes and middleware while an application layer is\n * being built. Once the router is complete, it handles each\n * `HttpServerRequest` by finding a matching route and producing an\n * `HttpServerResponse`. The module also includes helpers for route definitions,\n * prefixes, parameters, request decoding, CORS, and running the router.\n *\n * @since 4.0.0\n */\nimport * as Arr from \"../../Array.js\";\nimport * as Context from \"../../Context.js\";\nimport * as Effect from \"../../Effect.js\";\nimport { compose, dual, identity } from \"../../Function.js\";\nimport * as Layer from \"../../Layer.js\";\nimport * as Option from \"../../Option.js\";\nimport * as Schema from \"../../Schema.js\";\nimport * as Scope from \"../../Scope.js\";\nimport * as Tracer from \"../../Tracer.js\";\nimport * as FindMyWay from \"./FindMyWay.js\";\nimport * as HttpEffect from \"./HttpEffect.js\";\nimport * as HttpMiddleware from \"./HttpMiddleware.js\";\nimport * as HttpServer from \"./HttpServer.js\";\nimport * as HttpServerError from \"./HttpServerError.js\";\nimport * as HttpServerRequest from \"./HttpServerRequest.js\";\nimport * as HttpServerResponse from \"./HttpServerResponse.js\";\nconst TypeId = \"~effect/http/HttpRouter\";\n/**\n * Service tag for the HTTP router used while constructing an HTTP application.\n * Route and middleware layers require this service to register themselves with\n * the router.\n *\n * @category HttpRouter\n * @since 4.0.0\n */\nexport const HttpRouter = /*#__PURE__*/Context.Service(\"effect/http/HttpRouter\");\n/**\n * Constructs an empty `HttpRouter` service.\n *\n * **Details**\n *\n * The returned router accepts route and middleware registrations and later routes\n * the current `HttpServerRequest` to the matching `HttpServerResponse`.\n *\n * @category HttpRouter\n * @since 4.0.0\n */\nexport const make = /*#__PURE__*/Effect.gen(function* () {\n const router = FindMyWay.make(yield* RouterConfig);\n const middleware = new Set();\n const addAll = routes => Effect.contextWith(context => {\n const middleware = getMiddleware(context);\n const applyMiddleware = effect => {\n for (let i = 0; i < middleware.length; i++) {\n effect = middleware[i](effect);\n }\n return effect;\n };\n for (let i = 0; i < routes.length; i++) {\n const route = middleware.length === 0 ? routes[i] : makeRoute({\n ...routes[i],\n handler: applyMiddleware(routes[i].handler)\n });\n if (route.method === \"*\") {\n if (route.path.endsWith(\"/*\")) {\n router.all(route.path, route);\n router.all(route.path.slice(0, -2), route);\n } else {\n router.all(route.path, route);\n }\n } else {\n if (route.path.endsWith(\"/*\")) {\n router.on(route.method, route.path, route);\n router.on(route.method, route.path.slice(0, -2), route);\n } else {\n router.on(route.method, route.path, route);\n }\n }\n }\n return Effect.void;\n });\n return HttpRouter.of({\n [TypeId]: TypeId,\n prefixed(prefix) {\n return HttpRouter.of({\n ...this,\n prefixed: newPrefix => this.prefixed(prefixPath(prefix, newPrefix)),\n addAll: routes => addAll(routes.map(prefixRoute(prefix))),\n add: (method, path, handler, options) => addAll([makeRoute({\n method,\n path: prefixPath(path, prefix),\n handler: HttpServerResponse.isHttpServerResponse(handler) ? Effect.succeed(handler) : Effect.isEffect(handler) ? handler : Effect.flatMap(HttpServerRequest.HttpServerRequest, handler),\n uninterruptible: options?.uninterruptible ?? false,\n prefix\n })])\n });\n },\n addAll,\n add: (method, path, handler, options) => addAll([route(method, path, handler, options)]),\n addGlobalMiddleware: middleware_ => Effect.sync(() => {\n middleware.add(middleware_);\n }),\n asHttpEffect() {\n let handler = Effect.withFiber(fiber => {\n const contextMap = new Map(fiber.context.mapUnsafe);\n const request = contextMap.get(HttpServerRequest.HttpServerRequest.key);\n let result = router.find(request.method, request.url);\n if (result === undefined && request.method === \"HEAD\") {\n result = router.find(\"GET\", request.url);\n }\n if (result === undefined) {\n return Effect.fail(new HttpServerError.HttpServerError({\n reason: new HttpServerError.RouteNotFound({\n request\n })\n }));\n }\n const route = result.handler;\n if (Option.isSome(route.prefix)) {\n contextMap.set(HttpServerRequest.HttpServerRequest.key, sliceRequestUrl(request, route.prefix.value));\n }\n contextMap.set(HttpServerRequest.ParsedSearchParams.key, result.searchParams);\n contextMap.set(RouteContext.key, {\n route,\n params: result.params\n });\n const span = contextMap.get(Tracer.ParentSpan.key);\n if (span && span._tag === \"Span\") {\n span.attribute(\"http.route\", route.path);\n }\n return Effect.provideContext(route.uninterruptible ? route.handler : Effect.interruptible(route.handler), Context.makeUnsafe(contextMap));\n });\n if (middleware.size === 0) return handler;\n for (const fn of Arr.reverse(middleware)) {\n handler = fn(handler);\n }\n return handler;\n }\n });\n});\nfunction sliceRequestUrl(request, prefix) {\n const prefexLen = prefix.length;\n return request.modify({\n url: request.url.length <= prefexLen ? \"/\" : request.url.slice(prefexLen)\n });\n}\n/**\n * Context reference for low-level router configuration.\n *\n * **Details**\n *\n * The value is passed to the route matcher when an `HttpRouter` is created and\n * defaults to an empty configuration.\n *\n * @category configuration\n * @since 4.0.0\n */\nexport const RouterConfig = /*#__PURE__*/Context.Reference(\"effect/http/HttpRouter/RouterConfig\", {\n defaultValue: () => ({})\n});\n/**\n * Service for the matched HTTP route in the current request.\n *\n * **When to use**\n *\n * Use to read captured path parameters and route metadata while handling a\n * request matched by the router.\n *\n * **Details**\n *\n * It provides the route definition and the path parameters captured by the route\n * matcher.\n *\n * @category services\n * @since 4.0.0\n */\nexport class RouteContext extends /*#__PURE__*/Context.Service()(\"effect/http/HttpRouter/RouteContext\") {}\n/**\n * Effect that returns the path parameters captured for the current matched route.\n *\n * @category getters\n * @since 4.0.0\n */\nexport const params = /*#__PURE__*/Effect.map(RouteContext, _ => _.params);\n/**\n * Decodes a schema from the current request and its JSON body.\n *\n * **Details**\n *\n * The input passed to the schema includes the request method, URL, headers,\n * cookies, path parameters, search parameters, and parsed JSON body. The effect\n * fails if the body cannot be parsed or the schema decode fails.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const schemaJson = (schema, options) => {\n const parse = Schema.decodeUnknownEffect(schema);\n return Effect.contextWith(context => {\n const request = Context.get(context, HttpServerRequest.HttpServerRequest);\n const searchParams = Context.get(context, HttpServerRequest.ParsedSearchParams);\n const routeContext = Context.get(context, RouteContext);\n return Effect.flatMap(request.json, body => parse({\n method: request.method,\n url: request.url,\n headers: request.headers,\n cookies: request.cookies,\n pathParams: routeContext.params,\n searchParams,\n body\n }, options));\n });\n};\n/**\n * Decodes a schema from the current request without reading the request body.\n *\n * **Details**\n *\n * The input passed to the schema includes the request method, URL, headers,\n * cookies, path parameters, and search parameters.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const schemaNoBody = (schema, options) => {\n const parse = Schema.decodeUnknownEffect(schema);\n return Effect.contextWith(context => {\n const request = Context.get(context, HttpServerRequest.HttpServerRequest);\n const searchParams = Context.get(context, HttpServerRequest.ParsedSearchParams);\n const routeContext = Context.get(context, RouteContext);\n return parse({\n method: request.method,\n url: request.url,\n headers: request.headers,\n cookies: request.cookies,\n pathParams: routeContext.params,\n searchParams\n }, options);\n });\n};\n/**\n * Decodes a schema from the current route path parameters and search parameters.\n *\n * **Details**\n *\n * When the same key appears in both sources, the path parameter value is used.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const schemaParams = (schema, options) => {\n const parse = Schema.decodeUnknownEffect(schema);\n return Effect.contextWith(context => {\n const searchParams = Context.get(context, HttpServerRequest.ParsedSearchParams);\n const routeContext = Context.get(context, RouteContext);\n return parse({\n ...searchParams,\n ...routeContext.params\n }, options);\n });\n};\n/**\n * Decodes a schema from the path parameters captured for the current matched\n * route.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const schemaPathParams = (schema, options) => {\n const parse = Schema.decodeUnknownEffect(schema);\n return Effect.flatMap(params, _ => parse(_, options));\n};\n/**\n * Creates a layer that accesses the current `HttpRouter` service and runs the\n * supplied effect.\n *\n * **When to use**\n *\n * Use when you need to register routes or middleware with the router during layer\n * construction.\n *\n * **Example** (Registering routes during layer construction)\n *\n * ```ts\n * import { Effect, Layer } from \"effect\"\n * import { HttpRouter } from \"effect/unstable/http\"\n *\n * const MyRoute = Layer.effectDiscard(Effect.gen(function*() {\n * const router = yield* HttpRouter.HttpRouter\n *\n * // then use `yield* router.add(...)` to add a route\n * }))\n * ```\n *\n * @category HttpRouter\n * @since 4.0.0\n */\nexport const use = f => Layer.effectDiscard(Effect.flatMap(HttpRouter, f));\n/**\n * Create a layer that adds a single route to the HTTP router.\n *\n * **Example** (Adding a GET route)\n *\n * ```ts\n * import { Effect } from \"effect\"\n * import { HttpRouter, HttpServerResponse } from \"effect/unstable/http\"\n *\n * const Route = HttpRouter.add(\n * \"GET\",\n * \"/hello\",\n * Effect.succeed(HttpServerResponse.text(\"Hello, World!\"))\n * )\n * ```\n *\n * @category HttpRouter\n * @since 4.0.0\n */\nexport const add = (method, path, handler, options) => use(router => router.add(method, path, handler, options));\n/**\n * Create a layer that adds multiple routes to the HTTP router.\n *\n * **Example** (Adding multiple routes)\n *\n * ```ts\n * import { Effect } from \"effect\"\n * import { HttpRouter, HttpServerResponse } from \"effect/unstable/http\"\n *\n * const Routes = HttpRouter.addAll([\n * HttpRouter.route(\n * \"GET\",\n * \"/hello\",\n * Effect.succeed(HttpServerResponse.text(\"Hello, World!\"))\n * )\n * ])\n * ```\n *\n * @category HttpRouter\n * @since 4.0.0\n */\nexport const addAll = (routes, options) => Layer.effectDiscard(Effect.gen(function* () {\n const toAdd = Effect.isEffect(routes) ? yield* routes : routes;\n let router = yield* HttpRouter;\n if (options?.prefix) {\n router = router.prefixed(options.prefix);\n }\n yield* router.addAll(toAdd);\n}));\n/**\n * Layer that provides a newly constructed `HttpRouter`.\n *\n * @category HttpRouter\n * @since 4.0.0\n */\nexport const layer = /*#__PURE__*/Layer.effect(HttpRouter)(make);\n/**\n * Builds an application layer with a router and returns the router as an HTTP\n * handler effect.\n *\n * **Details**\n *\n * The returned effect handles the current `HttpServerRequest` in the current\n * `Scope`; route request markers are converted into the ordinary requirements of\n * the returned handler.\n *\n * @category HttpRouter\n * @since 4.0.0\n */\nexport const toHttpEffect = appLayer => Effect.gen(function* () {\n const context = yield* Layer.build(Layer.provideMerge(appLayer, layer));\n const router = Context.get(context, HttpRouter);\n // @effect-diagnostics effect/returnEffectInGen:off\n return router.asHttpEffect();\n});\nconst RouteTypeId = \"~effect/http/HttpRouter/Route\";\nconst makeRoute = options => ({\n ...options,\n uninterruptible: options.uninterruptible ?? false,\n prefix: typeof options.prefix === \"string\" ? Option.some(options.prefix) : options.prefix ?? Option.none(),\n [RouteTypeId]: RouteTypeId\n});\n/**\n * Constructs a `Route` from an HTTP method, path, and handler.\n *\n * **Details**\n *\n * The handler may be a static response, an effect that produces a response, or a\n * function from the current request to a response effect. Set `uninterruptible` to\n * prevent the route handler from being made interruptible while it runs.\n *\n * @category Route\n * @since 4.0.0\n */\nexport const route = (method, path, handler, options) => makeRoute({\n ...options,\n method,\n path,\n handler: HttpServerResponse.isHttpServerResponse(handler) ? Effect.succeed(handler) : Effect.isEffect(handler) ? handler : Effect.flatMap(HttpServerRequest.HttpServerRequest, handler),\n uninterruptible: options?.uninterruptible ?? false\n});\nconst removeTrailingSlash = path => path.endsWith(\"/\") ? path.slice(0, -1) : path;\n/**\n * Adds a path prefix to a route path.\n *\n * **Details**\n *\n * Trailing slashes are removed from the prefix; `/` becomes the prefix itself and\n * `*` becomes a wildcard route under the prefix.\n *\n * @category PathInput\n * @since 4.0.0\n */\nexport const prefixPath = /*#__PURE__*/dual(2, (self, prefix) => {\n prefix = removeTrailingSlash(prefix);\n if (self === \"*\") return `${prefix}/*`;else if (self === \"/\") return prefix;\n return prefix + self;\n});\n/**\n * Returns a copy of a route with its path prefixed.\n *\n * **Details**\n *\n * The prefix is also tracked on the route so that, when the route handles a\n * request, the matched prefix can be removed from the request URL seen by the\n * handler.\n *\n * @category Route\n * @since 4.0.0\n */\nexport const prefixRoute = /*#__PURE__*/dual(2, (self, prefix) => makeRoute({\n ...self,\n path: prefixPath(self.path, prefix),\n prefix: Option.match(self.prefix, {\n onNone: () => prefix,\n onSome: existingPrefix => prefixPath(existingPrefix, prefix)\n })\n}));\nconst MiddlewareTypeId = \"~effect/http/HttpRouter/Middleware\";\n/**\n * Create a middleware layer that can be used to modify requests and responses.\n *\n * **Details**\n *\n * By default, the middleware only affects the routes that it is provided to.\n *\n * If you want to create a middleware that applies globally to all routes, pass\n * the `global` option as `true`.\n *\n * **Example** (Applying route and global middleware)\n *\n * ```ts\n * import { Context, Effect, Layer } from \"effect\"\n * import { HttpMiddleware, HttpRouter, HttpServerResponse } from \"effect/unstable/http\"\n *\n * // Here we are defining a CORS middleware\n * const CorsMiddleware = HttpRouter.middleware(HttpMiddleware.cors()).layer\n * // You can also use HttpRouter.cors() to create a CORS middleware\n *\n * class CurrentSession extends Context.Service<CurrentSession, {\n * readonly token: string\n * }>()(\"CurrentSession\") {}\n *\n * // You can create middleware that provides a service to the HTTP requests.\n * const SessionMiddleware = HttpRouter.middleware<{\n * provides: CurrentSession\n * }>()(\n * Effect.gen(function*() {\n * yield* Effect.log(\"SessionMiddleware initialized\")\n *\n * return (httpEffect) =>\n * Effect.provideService(httpEffect, CurrentSession, {\n * token: \"dummy-token\"\n * })\n * })\n * ).layer\n *\n * Effect.gen(function*() {\n * const router = yield* HttpRouter.HttpRouter\n * yield* router.add(\n * \"GET\",\n * \"/hello\",\n * Effect.gen(function*() {\n * // Requests can now access the current session\n * const session = yield* CurrentSession\n * return HttpServerResponse.text(\n * `Hello, World! Your token is ${session.token}`\n * )\n * })\n * )\n * }).pipe(\n * Layer.effectDiscard,\n * // Provide the SessionMiddleware & CorsMiddleware to some routes\n * Layer.provide([SessionMiddleware, CorsMiddleware])\n * )\n * ```\n *\n * @category middleware\n * @since 4.0.0\n */\nexport const middleware = function () {\n if (arguments.length === 0) {\n return makeMiddleware;\n }\n return makeMiddleware(arguments[0], arguments[1]);\n};\nconst makeMiddleware = (middleware, options) => options?.global ? Layer.effectDiscard(Effect.gen(function* () {\n const router = yield* HttpRouter;\n const fn = Effect.isEffect(middleware) ? yield* middleware : middleware;\n yield* router.addGlobalMiddleware(fn);\n})) : new MiddlewareImpl(Effect.isEffect(middleware) ? Layer.effectContext(Effect.map(middleware, fn => Context.makeUnsafe(new Map([[fnContextKey, fn]])))) : Layer.succeedContext(Context.makeUnsafe(new Map([[fnContextKey, middleware]]))));\nlet middlewareId = 0;\nconst fnContextKey = \"effect/http/HttpRouter/MiddlewareFn\";\nclass MiddlewareImpl {\n [MiddlewareTypeId] = {};\n layerFn;\n dependencies;\n constructor(layerFn, dependencies) {\n this.layerFn = layerFn;\n this.dependencies = dependencies;\n const contextKey = `effect/http/HttpRouter/Middleware-${++middlewareId}`;\n this.layer = Layer.effectContext(Effect.gen({\n self: this\n }, function* () {\n const context = yield* Effect.context();\n const stack = [context.mapUnsafe.get(fnContextKey)];\n if (this.dependencies) {\n const memoMap = yield* Layer.CurrentMemoMap;\n const scope = Context.get(context, Scope.Scope);\n const depsContext = yield* Layer.buildWithMemoMap(this.dependencies, memoMap, scope);\n stack.push(...getMiddleware(depsContext));\n }\n return Context.makeUnsafe(new Map([[contextKey, stack]]));\n })).pipe(Layer.provide(this.layerFn));\n }\n layer;\n combine(other) {\n return new MiddlewareImpl(this.layerFn, this.dependencies ? Layer.provideMerge(this.dependencies, other.layer) : other.layer);\n }\n}\nconst middlewareCache = /*#__PURE__*/new WeakMap();\nconst getMiddleware = context => {\n let arr = middlewareCache.get(context);\n if (arr) return arr;\n const topLevel = Arr.empty();\n let maxLength = 0;\n for (const [key, value] of context.mapUnsafe) {\n if (key.startsWith(\"effect/http/HttpRouter/Middleware-\")) {\n topLevel.push(value);\n if (value.length > maxLength) {\n maxLength = value.length;\n }\n }\n }\n if (topLevel.length === 0) {\n arr = [];\n } else {\n const middleware = new Set();\n for (let i = maxLength - 1; i >= 0; i--) {\n for (const arr of topLevel) {\n if (i < arr.length) {\n middleware.add(arr[i]);\n }\n }\n }\n arr = Arr.fromIterable(middleware).reverse();\n }\n middlewareCache.set(context, arr);\n return arr;\n};\n/**\n * Middleware that applies CORS headers to the HTTP response.\n *\n * @category middleware\n * @since 4.0.0\n */\nexport const cors = options => middleware(HttpMiddleware.cors(options), {\n global: true\n});\n/**\n * Middleware that disables the logger for some routes.\n *\n * **Example** (Disabling route logging)\n *\n * ```ts\n * import { Effect, Layer } from \"effect\"\n * import { HttpRouter, HttpServerResponse } from \"effect/unstable/http\"\n *\n * const Route = HttpRouter.add(\n * \"GET\",\n * \"/hello\",\n * Effect.succeed(HttpServerResponse.text(\"Hello, World!\"))\n * ).pipe(\n * // disable the logger for this route\n * Layer.provide(HttpRouter.disableLogger)\n * )\n * ```\n *\n * @category middleware\n * @since 4.0.0\n */\nexport const disableLogger = /*#__PURE__*/middleware(HttpMiddleware.withLoggerDisabled).layer;\n/**\n * Provides request-level dependencies to some routes.\n *\n * @category middleware\n * @since 4.0.0\n */\nexport const provideRequest = layer => self => Layer.provide(self, middleware()(Effect.gen(function* () {\n const services = yield* Layer.build(layer);\n return effect => Effect.provideContext(effect, services);\n})).layer);\n/**\n * Runs the provided application layer as an HTTP server.\n *\n * @category server\n * @since 4.0.0\n */\nexport const serve = (appLayer, options) => {\n let middleware = options?.middleware;\n if (options?.disableLogger !== true) {\n middleware = middleware ? compose(middleware, HttpMiddleware.logger) : HttpMiddleware.logger;\n }\n const RouterLayer = options?.routerConfig ? Layer.provide(layer, Layer.succeed(RouterConfig)(options.routerConfig)) : layer;\n return Effect.gen(function* () {\n const router = yield* HttpRouter;\n const handler = router.asHttpEffect();\n return middleware ? HttpServer.serve(handler, middleware) : HttpServer.serve(handler);\n }).pipe(Layer.unwrap, Layer.provideMerge(appLayer), Layer.provide(RouterLayer), options?.disableListenLog ? identity : HttpServer.withLogAddress);\n};\n/**\n * Builds a Fetch-compatible request handler from an HTTP router application\n * layer.\n *\n * **Details**\n *\n * The result contains a `handler` function that converts Web `Request` values to\n * Web `Response` values and a `dispose` function for releasing the layer\n * resources.\n *\n * @category server\n * @since 4.0.0\n */\nexport const toWebHandler = (appLayer, options) => {\n let middleware = options?.middleware;\n if (options?.disableLogger !== true) {\n middleware = middleware ? compose(middleware, HttpMiddleware.logger) : HttpMiddleware.logger;\n }\n const RouterLayer = options?.routerConfig ? Layer.provide(layer, Layer.succeed(RouterConfig)(options.routerConfig)) : layer;\n return HttpEffect.toWebHandlerLayerWith(Layer.provideMerge(appLayer, RouterLayer), {\n toHandler: s => Effect.succeed(Context.get(s, HttpRouter).asHttpEffect()),\n middleware,\n memoMap: options?.memoMap\n });\n};\n//# sourceMappingURL=HttpRouter.js.map","/**\n * Marks encoded worker message fields that should move through `postMessage` as\n * transfer-list entries.\n *\n * Worker messages still pass through schema encoding and structured clone, but\n * schemas wrapped with `schema` can also report backing resources such as\n * `ArrayBuffer`, `ImageData.data.buffer`, or `MessagePort` to a `Collector`.\n * Worker platforms then pass the collected values as the transfer list for the\n * same `postMessage` call, avoiding copies for large payloads and ports.\n *\n * @since 4.0.0\n */\nimport * as Context from \"../../Context.js\";\nimport * as Effect from \"../../Effect.js\";\nimport { dual } from \"../../Function.js\";\nimport * as Schema from \"../../Schema.js\";\nimport * as SchemaGetter from \"../../SchemaGetter.js\";\n/**\n * Service for collecting `Transferable` objects while encoding worker messages\n * so they can be passed to `postMessage` transfer lists.\n *\n * @category models\n * @since 4.0.0\n */\nexport class Collector extends /*#__PURE__*/Context.Service()(\"effect/workers/Transferable/Collector\") {}\n/**\n * Creates a mutable `Collector` service directly, exposing unsafe synchronous\n * methods for reading, adding, and clearing collected transferables.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const makeCollectorUnsafe = () => {\n let tranferables = [];\n const unsafeAddAll = transfers => {\n tranferables.push(...transfers);\n };\n const unsafeRead = () => tranferables;\n const unsafeClear = () => {\n const prev = tranferables;\n tranferables = [];\n return prev;\n };\n return Collector.of({\n addAllUnsafe: unsafeAddAll,\n addAll: transferables => Effect.sync(() => unsafeAddAll(transferables)),\n readUnsafe: unsafeRead,\n read: Effect.sync(unsafeRead),\n clearUnsafe: unsafeClear,\n clear: Effect.sync(unsafeClear)\n });\n};\n/**\n * Effect that creates a fresh `Collector` service for accumulating\n * transferables.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const makeCollector = /*#__PURE__*/Effect.sync(makeCollectorUnsafe);\n/**\n * Adds transferables to the current `Collector` when one is present in the\n * context, and does nothing otherwise.\n *\n * @category accessors\n * @since 4.0.0\n */\nexport const addAll = tranferables => Effect.contextWith(services => {\n const collector = Context.getOrUndefined(services, Collector);\n if (!collector) return Effect.void;\n collector.addAllUnsafe(tranferables);\n return Effect.void;\n});\n/**\n * Creates a schema getter that records transferables derived from a value in\n * the current `Collector` while passing the value through unchanged.\n *\n * @category getters\n * @since 4.0.0\n */\nexport const getterAddAll = f => SchemaGetter.transformOrFail(e => Effect.contextWith(services => {\n const collector = Context.getOrUndefined(services, Collector);\n if (!collector) return Effect.succeed(e);\n collector.addAllUnsafe(f(e));\n return Effect.succeed(e);\n}));\n/**\n * Wraps a schema so encoding records transferables selected from the encoded\n * value, enabling worker messages to populate a `postMessage` transfer list.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const schema = /*#__PURE__*/dual(2, (self, f) => self.annotate({\n toCodecJson: () => passthroughLink\n}).pipe(Schema.decode({\n decode: SchemaGetter.passthrough(),\n encode: getterAddAll(f)\n})));\nconst passthroughLink = /*#__PURE__*/Schema.link()(Schema.Any, {\n decode: /*#__PURE__*/SchemaGetter.passthrough(),\n encode: /*#__PURE__*/SchemaGetter.passthrough()\n});\n/**\n * Schema for transferring `ImageData` values with their pixel data buffer.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const ImageData = /*#__PURE__*/schema(Schema.Any, _ => [_.data.buffer]);\n/**\n * Schema for transferring `MessagePort` values as transferable objects.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const MessagePort = /*#__PURE__*/schema(Schema.Any, _ => [_]);\n/**\n * Schema for transferring `Uint8Array` values with their backing buffer.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const Uint8Array = /*#__PURE__*/schema(Schema.Uint8Array, _ => [_.buffer]);\n//# sourceMappingURL=Transferable.js.map","/**\n * RPC schema markers and interruption annotations.\n *\n * This module contains the small pieces of schema metadata that the RPC\n * declaration, client, server, cluster, and reactivity layers share. It marks\n * streamed responses and annotates interruptions that came from a remote client\n * closing or cancelling a request.\n *\n * @since 4.0.0\n */\nimport * as Cause from \"../../Cause.js\";\nimport * as Context from \"../../Context.js\";\nimport { constUndefined } from \"../../Function.js\";\nimport * as Option from \"../../Option.js\";\nimport * as Predicate from \"../../Predicate.js\";\nimport * as Schema from \"../../Schema.js\";\nimport * as Stream_ from \"../../Stream.js\";\nconst StreamSchemaTypeId = \"~effect/rpc/RpcSchema/StreamSchema\";\n/**\n * Returns `true` when a schema is an RPC stream schema created by\n * `RpcSchema.Stream`.\n *\n * @category streams\n * @since 4.0.0\n */\nexport function isStreamSchema(schema) {\n return Predicate.hasProperty(schema, StreamSchemaTypeId);\n}\n/** @internal */\nexport function getStreamSchemas(schema) {\n return isStreamSchema(schema) ? Option.some({\n success: schema.success,\n error: schema.error\n }) : Option.none();\n}\nconst schema = /*#__PURE__*/Schema.declare(Stream_.isStream);\n/**\n * Creates an RPC stream schema from a stream element success schema and stream\n * error schema.\n *\n * @category streams\n * @since 4.0.0\n */\nexport function Stream(success, error) {\n return Schema.make(schema.ast, {\n [StreamSchemaTypeId]: StreamSchemaTypeId,\n success,\n error\n });\n}\n/**\n * Annotation that marks interruptions that originate from an RPC client\n * abort.\n *\n * @category Cause annotations\n * @since 4.0.0\n */\nexport class ClientAbort extends /*#__PURE__*/Context.Service()(\"effect/rpc/RpcSchema/ClientAbort\") {\n static annotation = /*#__PURE__*/this.context(true).pipe(/*#__PURE__*/Context.add(Cause.StackTrace, {\n name: \"ClientAbort\",\n stack: constUndefined,\n parent: undefined\n }));\n}\n//# sourceMappingURL=RpcSchema.js.map","import * as Context from \"../../Context.js\";\nimport * as Option from \"../../Option.js\";\nimport { pipeArguments } from \"../../Pipeable.js\";\nimport * as Predicate from \"../../Predicate.js\";\nimport * as PrimaryKey from \"../../PrimaryKey.js\";\nimport * as Schema from \"../../Schema.js\";\nimport * as RpcSchema from \"./RpcSchema.js\";\nconst TypeId = \"~effect/rpc/Rpc\";\n/**\n * Returns `true` when the value is an `Rpc` definition.\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isRpc = u => Predicate.hasProperty(u, TypeId);\n/**\n * Represents server-side metadata for the client associated with an RPC request.\n *\n * **When to use**\n *\n * Use to inspect or annotate the connected client while handling an RPC request\n * on the server.\n *\n * **Details**\n *\n * It stores the client id and request annotations that handlers can read or\n * extend.\n *\n * @category models\n * @since 4.0.0\n */\nexport class ServerClient {\n id;\n annotations;\n constructor(id) {\n this.id = id;\n this.annotations = Context.empty();\n }\n annotate(tag, value) {\n this.annotations = Context.add(this.annotations, tag, value);\n return this;\n }\n}\nconst Proto = {\n [TypeId]: TypeId,\n pipe() {\n return pipeArguments(this, arguments);\n },\n setSuccess(successSchema) {\n return makeProto({\n _tag: this._tag,\n payloadSchema: this.payloadSchema,\n successSchema,\n errorSchema: this.errorSchema,\n defectSchema: this.defectSchema,\n annotations: this.annotations,\n middlewares: this.middlewares\n });\n },\n setError(errorSchema) {\n return makeProto({\n _tag: this._tag,\n payloadSchema: this.payloadSchema,\n successSchema: this.successSchema,\n errorSchema,\n defectSchema: this.defectSchema,\n annotations: this.annotations,\n middlewares: this.middlewares\n });\n },\n setPayload(payloadSchema) {\n return makeProto({\n _tag: this._tag,\n payloadSchema: Schema.isSchema(payloadSchema) ? payloadSchema : Schema.Struct(payloadSchema),\n successSchema: this.successSchema,\n errorSchema: this.errorSchema,\n defectSchema: this.defectSchema,\n annotations: this.annotations,\n middlewares: this.middlewares\n });\n },\n middleware(middleware) {\n return makeProto({\n _tag: this._tag,\n payloadSchema: this.payloadSchema,\n successSchema: this.successSchema,\n errorSchema: this.errorSchema,\n defectSchema: this.defectSchema,\n annotations: this.annotations,\n middlewares: new Set([...this.middlewares, middleware])\n });\n },\n prefix(prefix) {\n return makeProto({\n _tag: `${prefix}${this._tag}`,\n payloadSchema: this.payloadSchema,\n successSchema: this.successSchema,\n errorSchema: this.errorSchema,\n defectSchema: this.defectSchema,\n annotations: this.annotations,\n middlewares: this.middlewares\n });\n },\n annotate(tag, value) {\n return makeProto({\n _tag: this._tag,\n payloadSchema: this.payloadSchema,\n successSchema: this.successSchema,\n errorSchema: this.errorSchema,\n defectSchema: this.defectSchema,\n middlewares: this.middlewares,\n annotations: Context.add(this.annotations, tag, value)\n });\n },\n annotateMerge(context) {\n return makeProto({\n _tag: this._tag,\n payloadSchema: this.payloadSchema,\n successSchema: this.successSchema,\n errorSchema: this.errorSchema,\n defectSchema: this.defectSchema,\n middlewares: this.middlewares,\n annotations: Context.merge(this.annotations, context)\n });\n }\n};\nconst makeProto = options => {\n function Rpc() {}\n Object.setPrototypeOf(Rpc, Proto);\n Object.assign(Rpc, options);\n Rpc.key = `effect/rpc/Rpc/${options._tag}`;\n return Rpc;\n};\n/**\n * Creates an RPC definition with the supplied tag and optional schemas.\n *\n * **Details**\n *\n * Payload options can be either a schema or struct fields. `stream: true` wraps\n * the success and error schemas in a stream schema and sets the normal error\n * schema to `Schema.Never`. `primaryKey` creates a payload class with a\n * primary key derived from the payload value.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = (tag, options) => {\n const successSchema = options?.success ?? Schema.Void;\n const errorSchema = options?.error ?? Schema.Never;\n const defectSchema = options?.defect ?? Schema.Defect();\n let payloadSchema;\n if (options?.primaryKey) {\n payloadSchema = class Payload extends Schema.Class(`effect/rpc/Rpc/${tag}`)(options.payload) {\n [PrimaryKey.symbol]() {\n return options.primaryKey(this);\n }\n };\n } else {\n payloadSchema = Schema.isSchema(options?.payload) ? options?.payload : options?.payload ? Schema.Struct(options?.payload) : Schema.Void;\n }\n return makeProto({\n _tag: tag,\n payloadSchema,\n successSchema: options?.stream ? RpcSchema.Stream(successSchema, errorSchema) : successSchema,\n errorSchema: options?.stream ? Schema.Never : errorSchema,\n defectSchema,\n annotations: Context.empty(),\n middlewares: new Set()\n });\n};\n/**\n * Creates a custom `Rpc` constructor that can transform the output schemas.\n *\n * **Example** (Defining a paginated RPC constructor)\n *\n * ```ts\n * import { Schema } from \"effect\"\n * import { Rpc } from \"effect/unstable/rpc\"\n *\n * // Create a custom Rpc wrapper definition by transforming the success and error\n * // schemas.\n * export interface RpcWithPagination extends Rpc.Custom {\n * readonly out: Rpc.Custom.Out<\n * Paginated<this[\"success\"]>,\n * this[\"error\"]\n * >\n * }\n *\n * // The type definition for the transformed success schema.\n * export interface Paginated<S extends Schema.Constraint> extends\n * Schema.Struct<{\n * readonly offset: Schema.Number\n * readonly total: Schema.Number\n * readonly results: Schema.$Array<S>\n * }>\n * {}\n *\n * // You can then implement the schema transformation using `Rpc.custom`\n * export const makePaginated = Rpc.custom<RpcWithPagination>((schemas) => ({\n * ...schemas,\n * success: Schema.Struct({\n * offset: Schema.Number,\n * total: Schema.Number,\n * results: Schema.Array(schemas.success)\n * })\n * }))\n *\n * // You can then use the custom constructor in the same way `Rpc.make` is used.\n * export const listAllRpc = makePaginated(\"listAll\", {\n * success: Schema.String\n * })\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const custom = f => (tag, options) => {\n const success = options?.success ?? Schema.Void;\n const error = options?.error ?? Schema.Never;\n const defect = options?.defect ?? Schema.Defect();\n const out = f({\n success,\n error,\n defect\n });\n return make(tag, {\n ...out,\n primaryKey: options?.primaryKey,\n payload: options?.payload,\n stream: options?.stream\n });\n};\nconst exitSchemaCache = /*#__PURE__*/new WeakMap();\n/**\n * Builds the `Schema.Exit` used to encode and decode RPC results.\n *\n * **Details**\n *\n * The failure side includes the RPC error schema, middleware error schemas, and\n * stream error schema for streaming RPCs. Streaming RPCs use `Schema.Void` for\n * the exit success value. The schema is cached per RPC definition.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const exitSchema = self => {\n if (exitSchemaCache.has(self)) {\n return exitSchemaCache.get(self);\n }\n const rpc = self;\n const failures = new Set([rpc.errorSchema]);\n const streamSchemas = RpcSchema.getStreamSchemas(rpc.successSchema);\n if (Option.isSome(streamSchemas)) {\n failures.add(streamSchemas.value.error);\n }\n for (const middleware of rpc.middlewares) {\n failures.add(middleware.error);\n }\n const schema = Schema.Exit(Option.isSome(streamSchemas) ? Schema.Void : rpc.successSchema, Schema.Union([...failures]), rpc.defectSchema);\n exitSchemaCache.set(self, schema);\n return schema;\n};\nconst WrapperTypeId = \"~effect/rpc/Rpc/Wrapper\";\n/**\n * Returns `true` when the value is an RPC `Wrapper`.\n *\n * @category wrapping\n * @since 4.0.0\n */\nexport const isWrapper = u => WrapperTypeId in u;\n/**\n * Wraps a handler result with RPC server execution options.\n *\n * **Details**\n *\n * When the value is already wrapped, unspecified options are inherited from the\n * existing wrapper.\n *\n * @category wrapping\n * @since 4.0.0\n */\nexport const wrap = options => value => isWrapper(value) ? {\n [WrapperTypeId]: WrapperTypeId,\n value: value.value,\n fork: options.fork ?? value.fork,\n uninterruptible: options.uninterruptible ?? value.uninterruptible\n} : {\n [WrapperTypeId]: WrapperTypeId,\n value,\n fork: options.fork ?? false,\n uninterruptible: options.uninterruptible ?? false\n};\n/**\n * Returns the wrapped response value when the input is an RPC `Wrapper`, or the\n * input itself when it is already unwrapped.\n *\n * @category wrapping\n * @since 4.0.0\n */\nexport const unwrap = value => isWrapper(value) ? value.value : value;\n/**\n * Maps the value inside an RPC wrapper, preserving wrapper options such as\n * `fork` and `uninterruptible`; unwrapped values are mapped directly.\n *\n * @category wrapping\n * @since 4.0.0\n */\nexport const wrapMap = (self, f) => {\n if (isWrapper(self)) {\n return wrap(self)(f(self.value));\n }\n return f(self);\n};\n/**\n * Wraps a response Effect or Stream so the RPC server executes it concurrently\n * regardless of the server concurrency setting.\n *\n * @category wrapping\n * @since 4.0.0\n */\nexport const fork = /*#__PURE__*/wrap({\n fork: true\n});\n/**\n * Wraps a response Effect or Stream so the RPC server runs it in an uninterruptible region.\n *\n * @category wrapping\n * @since 4.0.0\n */\nexport const uninterruptible = /*#__PURE__*/wrap({\n uninterruptible: true\n});\n//# sourceMappingURL=Rpc.js.map","import * as Schema from \"../../Schema.js\";\n/**\n * Converts a bigint or string request id into the branded `RequestId` type.\n *\n * @category request\n * @since 4.0.0\n */\nexport const RequestId = id => id;\n/**\n * Represents the reusable `Eof` message value.\n *\n * @category request\n * @since 4.0.0\n */\nexport const constEof = {\n _tag: \"Eof\"\n};\n/**\n * Represents the reusable `Ping` message value.\n *\n * @category request\n * @since 4.0.0\n */\nexport const constPing = {\n _tag: \"Ping\"\n};\n/**\n * The brand identifier used by the `ResponseId` type.\n *\n * @category type IDs\n * @since 4.0.0\n */\nexport const ResponseIdTypeId = \"~effect//rpc/RpcServer/ResponseId\";\nconst encodeDefect = /*#__PURE__*/Schema.encodeSync(/*#__PURE__*/Schema.Defect());\n/**\n * Creates an encoded terminal response for a request whose exit is a defect\n * encoded with `Schema.Defect()`.\n *\n * @category response\n * @since 4.0.0\n */\nexport const ResponseExitDieEncoded = options => ({\n _tag: \"Exit\",\n requestId: options.requestId,\n exit: {\n _tag: \"Failure\",\n cause: [{\n _tag: \"Die\",\n defect: encodeDefect(options.defect)\n }]\n }\n});\n/**\n * Creates a transport-encoded defect response by encoding the input with\n * `Schema.Defect()`.\n *\n * @category response\n * @since 4.0.0\n */\nexport const ResponseDefectEncoded = input => ({\n _tag: \"Defect\",\n defect: encodeDefect(input)\n});\n/**\n * Represents the reusable `Pong` message value.\n *\n * @category response\n * @since 4.0.0\n */\nexport const constPong = {\n _tag: \"Pong\"\n};\n/**\n * Checks if the response type is terminal.\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isTerminalResponse = response => {\n switch (response._tag) {\n case \"Exit\":\n case \"Defect\":\n case \"ClientProtocolError\":\n {\n return true;\n }\n default:\n {\n return false;\n }\n }\n};\n//# sourceMappingURL=RpcMessage.js.map","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}","/**\n * Serializes RPC protocol messages for transports.\n *\n * `RpcSerialization` is the boundary between `RpcMessage` envelopes and the\n * bytes or strings carried by a transport. This module provides built-in\n * serializers for JSON, newline-delimited JSON, JSON-RPC 2.0, and MessagePack,\n * including framed formats that can decode multiple messages from streaming\n * chunks.\n *\n * @since 4.0.0\n */\nimport * as Msgpackr from \"msgpackr\";\nimport * as Context from \"../../Context.js\";\nimport * as Layer from \"../../Layer.js\";\nimport * as Predicate from \"../../Predicate.js\";\nimport { hasProperty } from \"../../Predicate.js\";\n/**\n * Service that describes how RPC protocol messages are encoded and decoded,\n * including the content type and whether the serialization format provides\n * message framing.\n *\n * **When to use**\n *\n * Use to provide the serialization boundary shared by RPC clients and servers\n * for a chosen wire format.\n *\n * @category serialization\n * @since 4.0.0\n */\nexport class RpcSerialization extends /*#__PURE__*/Context.Service()(\"effect/rpc/RpcSerialization\") {}\n/**\n * JSON RPC serialization for whole message payloads. It does not include\n * message framing, so it is intended for transports that frame responses\n * themselves.\n *\n * @category serialization\n * @since 4.0.0\n */\nexport const json = /*#__PURE__*/RpcSerialization.of({\n contentType: \"application/json\",\n includesFraming: false,\n makeUnsafe: () => {\n const decoder = new TextDecoder();\n return {\n decode: bytes => {\n const decoded = JSON.parse(typeof bytes === \"string\" ? bytes : decoder.decode(bytes));\n return Array.isArray(decoded) ? decoded : [decoded];\n },\n encode: response => JSON.stringify(response)\n };\n }\n});\n/**\n * Serializes RPC protocol messages as newline-delimited JSON, framing each message\n * with a trailing newline.\n *\n * @category serialization\n * @since 4.0.0\n */\nexport const ndjson = /*#__PURE__*/RpcSerialization.of({\n contentType: \"application/ndjson\",\n includesFraming: true,\n makeUnsafe: () => {\n const decoder = new TextDecoder();\n let buffer = \"\";\n return {\n decode: bytes => {\n buffer += typeof bytes === \"string\" ? bytes : decoder.decode(bytes);\n let position = 0;\n let nlIndex = buffer.indexOf(\"\\n\", position);\n const items = [];\n while (nlIndex !== -1) {\n const item = JSON.parse(buffer.slice(position, nlIndex));\n items.push(item);\n position = nlIndex + 1;\n nlIndex = buffer.indexOf(\"\\n\", position);\n }\n buffer = buffer.slice(position);\n return items;\n },\n encode: response => {\n if (Array.isArray(response)) {\n if (response.length === 0) return undefined;\n let data = \"\";\n for (let i = 0; i < response.length; i++) {\n data += JSON.stringify(response[i]) + \"\\n\";\n }\n return data;\n }\n return JSON.stringify(response) + \"\\n\";\n }\n };\n }\n});\n/**\n * Creates a JSON-RPC 2.0 serialization for RPC protocol messages without\n * additional message framing.\n *\n * @category serialization\n * @since 4.0.0\n */\nexport const jsonRpc = options => RpcSerialization.of({\n contentType: options?.contentType ?? \"application/json\",\n includesFraming: false,\n makeUnsafe: () => {\n const decoder = new TextDecoder();\n const batches = new Map();\n return {\n decode: bytes => {\n const decoded = JSON.parse(typeof bytes === \"string\" ? bytes : decoder.decode(bytes));\n return decodeJsonRpcRaw(decoded, batches);\n },\n encode: response => {\n const encoded = encodeJsonRpcResponse(response, batches);\n return encoded && JSON.stringify(encoded);\n }\n };\n }\n});\n/**\n * Creates a newline-delimited JSON-RPC 2.0 serialization for RPC protocol\n * messages.\n *\n * @category serialization\n * @since 4.0.0\n */\nexport const ndJsonRpc = options => RpcSerialization.of({\n contentType: options?.contentType ?? \"application/json-rpc\",\n includesFraming: true,\n makeUnsafe: () => {\n const parser = ndjson.makeUnsafe();\n const batches = new Map();\n return {\n decode: bytes => {\n const frames = parser.decode(bytes);\n if (frames.length === 0) return [];\n const messages = [];\n for (let i = 0; i < frames.length; i++) {\n const frame = frames[i];\n messages.push(...decodeJsonRpcRaw(frame, batches));\n }\n return messages;\n },\n encode: response => {\n const encoded = encodeJsonRpcResponse(response, batches);\n return encoded && parser.encode(encoded);\n }\n };\n }\n});\nfunction decodeJsonRpcRaw(decoded, batches) {\n if (Array.isArray(decoded)) {\n const batch = {\n size: 0,\n responses: new Map()\n };\n const messages = [];\n for (let i = 0; i < decoded.length; i++) {\n const message = decodeJsonRpcMessage(decoded[i]);\n messages.push(message);\n if (message._tag === \"Request\") {\n batch.size++;\n batches.set(message.id, batch);\n }\n }\n return messages;\n }\n return [decodeJsonRpcMessage(decoded)];\n}\nfunction decodeJsonRpcMessage(decoded) {\n if (\"method\" in decoded) {\n if (Predicate.isNullish(decoded.id) && decoded.method.startsWith(\"@effect/rpc/\")) {\n const tag = decoded.method.slice(\"@effect/rpc/\".length);\n const requestId = decoded.params?.requestId;\n return requestId ? {\n _tag: tag,\n requestId\n } : {\n _tag: tag\n };\n }\n return {\n _tag: \"Request\",\n id: decoded.id ?? \"\",\n tag: decoded.method,\n payload: decoded.params ?? null,\n headers: decoded.headers ?? [],\n ...(decoded.spanId ? {\n traceId: decoded.traceId,\n spanId: decoded.spanId,\n sampled: decoded.sampled\n } : {})\n };\n } else if (decoded.error && decoded.error._tag === \"Defect\") {\n return {\n _tag: \"Defect\",\n defect: decoded.error.data\n };\n } else if (decoded.chunk === true) {\n return {\n _tag: \"Chunk\",\n requestId: decoded.id ?? \"\",\n values: decoded.result\n };\n }\n return {\n _tag: \"Exit\",\n requestId: decoded.id ?? \"\",\n exit: decoded.error != null ? {\n _tag: \"Failure\",\n cause: decoded.error._tag === \"Cause\" ? decoded.error.data : [{\n _tag: \"Die\",\n defect: decoded.error\n }]\n } : {\n _tag: \"Success\",\n value: decoded.result\n }\n };\n}\nfunction encodeJsonRpcRaw(response, batches) {\n if (!(\"requestId\" in response)) {\n return encodeJsonRpcMessage(response);\n }\n const batch = batches.get(response.requestId);\n if (batch) {\n batches.delete(response.requestId);\n batch.responses.set(response.requestId, response);\n if (batch.size === batch.responses.size) {\n return Array.from(batch.responses.values(), encodeJsonRpcMessage);\n }\n return undefined;\n }\n return encodeJsonRpcMessage(response);\n}\nfunction encodeJsonRpcResponse(response, batches) {\n if (Array.isArray(response) === false) {\n return encodeJsonRpcRaw(response, batches);\n }\n if (response.length === 0) {\n return undefined;\n }\n const encoded = [];\n for (let i = 0; i < response.length; i++) {\n const current = encodeJsonRpcRaw(response[i], batches);\n if (current !== undefined) {\n encoded.push(current);\n }\n }\n if (encoded.length === 0) {\n return undefined;\n }\n if (encoded.length === 1) {\n return encoded[0];\n }\n const messages = [];\n for (let i = 0; i < encoded.length; i++) {\n const current = encoded[i];\n if (Array.isArray(current)) {\n messages.push(...current);\n } else {\n messages.push(current);\n }\n }\n return messages;\n}\nfunction encodeJsonRpcMessage(response) {\n switch (response._tag) {\n case \"Request\":\n return {\n jsonrpc: \"2.0\",\n method: response.tag,\n params: response.payload,\n id: response.id,\n headers: response.headers,\n traceId: response.traceId,\n spanId: response.spanId,\n sampled: response.sampled\n };\n case \"Ping\":\n case \"Pong\":\n case \"Interrupt\":\n case \"Ack\":\n case \"Eof\":\n return {\n jsonrpc: \"2.0\",\n method: `@effect/rpc/${response._tag}`,\n params: \"requestId\" in response ? {\n requestId: response.requestId\n } : undefined\n };\n case \"Chunk\":\n return {\n jsonrpc: \"2.0\",\n chunk: true,\n id: response.requestId,\n result: response.values\n };\n case \"Exit\":\n {\n if (response.exit._tag === \"Success\") {\n return {\n jsonrpc: \"2.0\",\n id: response.requestId ?? undefined,\n result: response.exit.value\n };\n }\n const error = response.exit.cause.find(failure => failure._tag === \"Fail\");\n return {\n jsonrpc: \"2.0\",\n id: response.requestId ?? undefined,\n error: response.exit._tag === \"Failure\" ? {\n _tag: \"Cause\",\n code: error && Predicate.hasProperty(error, \"code\") ? Number(error.code) : 0,\n message: error && hasProperty(error, \"message\") ? error.message : JSON.stringify(response.exit.cause),\n data: response.exit.cause\n } : undefined\n };\n }\n case \"Defect\":\n return {\n jsonrpc: \"2.0\",\n id: jsonRpcInternalError,\n error: {\n _tag: \"Defect\",\n code: 1,\n message: \"A defect occurred\",\n data: response.defect\n }\n };\n case \"ClientProtocolError\":\n return {};\n }\n}\nconst jsonRpcInternalError = -32603;\n/**\n * Create a MessagePack serialization with custom msgpackr options.\n *\n * @category serialization\n * @since 4.0.0\n */\nexport const makeMsgPack = options => RpcSerialization.of({\n contentType: \"application/msgpack\",\n includesFraming: true,\n makeUnsafe: () => {\n const unpackr = new Msgpackr.Unpackr(options);\n const packr = new Msgpackr.Packr(options);\n const encoder = new TextEncoder();\n let incomplete = undefined;\n return {\n decode(bytes) {\n let buf = typeof bytes === \"string\" ? encoder.encode(bytes) : bytes;\n if (incomplete !== undefined) {\n const prev = buf;\n bytes = new Uint8Array(incomplete.length + buf.length);\n bytes.set(incomplete);\n bytes.set(prev, incomplete.length);\n buf = bytes;\n incomplete = undefined;\n }\n try {\n return unpackr.unpackMultiple(buf);\n } catch (error_) {\n const error = error_;\n if (error.incomplete) {\n incomplete = buf.subarray(error.lastPosition);\n return error.values ?? [];\n }\n throw error_;\n }\n },\n encode: response => packr.pack(response)\n };\n }\n});\n/**\n * Default MessagePack RPC serialization using record support and built-in\n * message framing.\n *\n * @category serialization\n * @since 4.0.0\n */\nexport const msgPack = /*#__PURE__*/makeMsgPack({\n useRecords: true\n});\n/**\n * RPC serialization layer that uses JSON for serialization.\n *\n * **When to use**\n *\n * Use when you have a transport protocol that already provides message framing.\n *\n * @see {@link layerNdjson} for transports that need newline-delimited framing\n *\n * @category serialization\n * @since 4.0.0\n */\nexport const layerJson = /*#__PURE__*/Layer.succeed(RpcSerialization)(json);\n/**\n * RPC serialization layer that uses NDJSON for serialization.\n *\n * **When to use**\n *\n * Use when you have a transport protocol that does not provide message framing.\n *\n * @see {@link layerJson} for transports that already provide message framing\n *\n * @category serialization\n * @since 4.0.0\n */\nexport const layerNdjson = /*#__PURE__*/Layer.succeed(RpcSerialization)(ndjson);\n/**\n * RPC serialization layer that uses JSON-RPC for serialization.\n *\n * @category serialization\n * @since 4.0.0\n */\nexport const layerJsonRpc = options => Layer.succeed(RpcSerialization)(jsonRpc(options));\n/**\n * RPC serialization layer that uses newline-delimited JSON-RPC for\n * serialization.\n *\n * @category serialization\n * @since 4.0.0\n */\nexport const layerNdJsonRpc = options => Layer.succeed(RpcSerialization)(ndJsonRpc(options));\n/**\n * RPC serialization layer that uses MessagePack for serialization.\n *\n * **Details**\n *\n * MessagePack has a more compact binary format compared to JSON and NDJSON. It\n * also has better support for binary data.\n *\n * @category serialization\n * @since 4.0.0\n */\nexport const layerMsgPack = /*#__PURE__*/Layer.succeed(RpcSerialization)(msgPack);\n//# sourceMappingURL=RpcSerialization.js.map","import * as Effect from \"../../Effect.js\";\nimport * as Semaphore from \"../../Semaphore.js\";\n/**\n * Builds a service with a `run` method that buffers writes until `run` installs\n * a writer, replays buffered writes with their original contexts, and restores\n * the previous writer when the run ends.\n *\n * @category services\n * @since 4.0.0\n */\nexport const withRun = () => f => Effect.suspend(() => {\n const semaphore = Semaphore.makeUnsafe(1);\n let buffer = [];\n let write = (...args) => Effect.contextWith(context => {\n buffer.push([args, context]);\n return Effect.void;\n });\n return Effect.map(f((...args) => write(...args)), a => ({\n ...a,\n run(f) {\n return semaphore.withPermits(1)(Effect.gen(function* () {\n const prev = write;\n write = f;\n for (const [args, context] of buffer) {\n yield* Effect.provideContext(Effect.suspend(() => f(...args)), context);\n }\n buffer = [];\n return yield* Effect.onExit(Effect.never, () => {\n write = prev;\n return Effect.void;\n });\n }));\n }\n }));\n});\n/**\n * Builds an RPC client protocol service that tracks active client IDs and\n * buffers server responses per client until that client's `run` handler is\n * installed.\n *\n * @category services\n * @since 4.0.0\n */\nexport const withRunClient = f => Effect.suspend(() => {\n const clientIds = new Set();\n const clientBuffers = new Map();\n const clientWrites = new Map();\n let write = (clientId, data) => Effect.contextWith(context => {\n let buffer = clientBuffers.get(clientId);\n if (!buffer) {\n buffer = [];\n clientBuffers.set(clientId, buffer);\n }\n buffer.push([data, context]);\n return Effect.void;\n });\n return Effect.map(f((clientId, data) => {\n const clientWrite = clientWrites.get(clientId);\n if (clientWrite) {\n return clientWrite(data);\n }\n return write(clientId, data);\n }, clientIds), a => ({\n ...a,\n run(clientId, f) {\n return Effect.gen(function* () {\n clientIds.add(clientId);\n clientWrites.set(clientId, f);\n const buffer = clientBuffers.get(clientId);\n if (buffer) {\n clientBuffers.delete(clientId);\n for (const [args, context] of buffer) {\n yield* Effect.provideContext(Effect.suspend(() => f(args)), context);\n }\n }\n return yield* Effect.onExit(Effect.never, () => {\n clientIds.delete(clientId);\n clientWrites.delete(clientId);\n return Effect.void;\n });\n });\n }\n }));\n});\n//# sourceMappingURL=Utils.js.map","import * as Cause from \"../../Cause.js\";\nimport * as Context from \"../../Context.js\";\nimport * as Effect from \"../../Effect.js\";\nimport * as Exit from \"../../Exit.js\";\nimport * as Fiber from \"../../Fiber.js\";\nimport { constVoid, dual, flow, identity } from \"../../Function.js\";\nimport * as Latch from \"../../Latch.js\";\nimport * as Layer from \"../../Layer.js\";\nimport * as Option from \"../../Option.js\";\nimport * as Pool from \"../../Pool.js\";\nimport * as Queue from \"../../Queue.js\";\nimport * as Result from \"../../Result.js\";\nimport * as Schedule from \"../../Schedule.js\";\nimport * as Schema from \"../../Schema.js\";\nimport * as Scope from \"../../Scope.js\";\nimport * as Stream from \"../../Stream.js\";\nimport * as Headers from \"../http/Headers.js\";\nimport * as HttpBody from \"../http/HttpBody.js\";\nimport * as HttpClient from \"../http/HttpClient.js\";\nimport { HttpClientErrorSchema } from \"../http/HttpClientError.js\";\nimport * as HttpClientRequest from \"../http/HttpClientRequest.js\";\nimport * as Socket from \"../socket/Socket.js\";\nimport * as Transferable from \"../workers/Transferable.js\";\nimport * as Worker from \"../workers/Worker.js\";\nimport * as Rpc from \"./Rpc.js\";\nimport { RpcClientDefect, RpcClientError } from \"./RpcClientError.js\";\nimport { constPing, isTerminalResponse, RequestId } from \"./RpcMessage.js\";\nimport * as RpcSchema from \"./RpcSchema.js\";\nimport * as RpcSerialization from \"./RpcSerialization.js\";\nimport * as RpcWorker from \"./RpcWorker.js\";\nimport { withRunClient } from \"./Utils.js\";\nlet requestIdCounter = 0;\n/**\n * Creates an RPC client for an already-decoded message channel, returning the\n * client API together with a `write` function for delivering server messages\n * back to the client.\n *\n * @category client\n * @since 4.0.0\n */\nexport const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (group, options) {\n const spanPrefix = options?.spanPrefix ?? \"RpcClient\";\n const supportsAck = options?.supportsAck ?? true;\n const disableTracing = options?.disableTracing ?? false;\n const generateRequestId = options?.generateRequestId ?? (() => requestIdCounter++);\n const services = yield* Effect.context();\n const scope = Context.get(services, Scope.Scope);\n const entries = new Map();\n let isShutdown = false;\n yield* Scope.addFinalizer(scope, Effect.withFiber(parent => {\n isShutdown = true;\n return clearEntries(Exit.interrupt(parent.id));\n }));\n const clearEntries = Effect.fnUntraced(function* (exit) {\n for (const [id, entry] of entries) {\n entries.delete(id);\n if (entry._tag === \"Queue\") {\n yield* exit._tag === \"Success\" ? Queue.end(entry.queue) : Queue.failCause(entry.queue, exit.cause);\n } else {\n entry.resume(exit);\n }\n }\n });\n const onRequest = rpc => {\n const isStream = RpcSchema.isStreamSchema(rpc.successSchema);\n const middleware = getRpcClientMiddleware(rpc);\n return (payload, opts) => {\n const headers = opts?.headers ? Headers.fromInput(opts.headers) : Headers.empty;\n const context = opts?.context ?? Context.empty();\n if (!isStream) {\n const onRequest = span => onEffectRequest(rpc, middleware, span, rpc.payloadSchema.make(payload), headers, context, opts?.discard ?? false);\n return disableTracing ? onRequest(undefined) : Effect.useSpan(`${spanPrefix}.${rpc._tag}`, {\n attributes: options.spanAttributes\n }, onRequest);\n }\n const queue = onStreamRequest(rpc, middleware, rpc.payloadSchema.make(payload), headers, opts?.streamBufferSize ?? 16, context);\n if (opts?.asQueue) return queue;\n return Stream.unwrap(Effect.map(queue, Stream.fromQueue));\n };\n };\n const onEffectRequest = (rpc, middleware, span, payload, headers, context, discard) => Effect.withFiber(parentFiber => {\n if (isShutdown) {\n return Effect.interrupt;\n }\n const id = generateRequestId();\n const send = middleware(message => options.onFromClient({\n message,\n context,\n discard\n }), {\n _tag: \"Request\",\n id,\n tag: rpc._tag,\n payload,\n ...(span ? {\n traceId: span.traceId,\n spanId: span.spanId,\n sampled: span.sampled\n } : {}),\n headers: Headers.merge(parentFiber.getRef(CurrentHeaders), headers)\n });\n if (discard) {\n return send;\n }\n let fiber;\n return Effect.onInterrupt(Effect.callback(resume => {\n const entry = {\n _tag: \"Effect\",\n rpc,\n context,\n resume(exit) {\n resume(exit);\n if (fiber && !fiber.pollUnsafe()) {\n parentFiber.currentDispatcher.scheduleTask(() => {\n fiber.interruptUnsafe(parentFiber.id);\n }, 0);\n }\n }\n };\n entries.set(id, entry);\n fiber = send.pipe(span ? Effect.withParentSpan(span, {\n captureStackTrace: false\n }) : identity, Effect.runForkWith(parentFiber.context));\n fiber.addObserver(exit => {\n if (exit._tag === \"Failure\") {\n return resume(exit);\n }\n });\n }), interruptors => {\n entries.delete(id);\n return Effect.andThen(Fiber.interrupt(fiber), sendInterrupt(id, Array.from(interruptors), context));\n });\n });\n const onStreamRequest = Effect.fnUntraced(function* (rpc, middleware, payload, headers, streamBufferSize, context) {\n if (isShutdown) {\n return yield* Effect.interrupt;\n }\n const span = disableTracing ? undefined : yield* Effect.makeSpanScoped(`${spanPrefix}.${rpc._tag}`, {\n attributes: options.spanAttributes\n });\n const fiber = Fiber.getCurrent();\n const id = generateRequestId();\n const scope = Context.getUnsafe(fiber.context, Scope.Scope);\n yield* Scope.addFinalizerExit(scope, exit => {\n if (!entries.has(id)) return Effect.void;\n entries.delete(id);\n return sendInterrupt(id, Exit.isFailure(exit) ? Array.from(Cause.interruptors(exit.cause)) : [], context);\n });\n const queue = yield* Queue.bounded(streamBufferSize);\n entries.set(id, {\n _tag: \"Queue\",\n rpc,\n queue,\n scope,\n context\n });\n yield* middleware(message => options.onFromClient({\n message,\n context,\n discard: false\n }), {\n _tag: \"Request\",\n id,\n tag: rpc._tag,\n payload,\n ...(span ? {\n traceId: span.traceId,\n spanId: span.spanId,\n sampled: span.sampled\n } : {}),\n headers: Headers.merge(fiber.getRef(CurrentHeaders), headers)\n }).pipe(span ? Effect.withParentSpan(span, {\n captureStackTrace: false\n }) : identity, Effect.catchCause(error => Queue.failCause(queue, error)), Effect.interruptible, Effect.forkIn(scope, {\n startImmediately: true\n }));\n return queue;\n });\n const getRpcClientMiddleware = rpc => {\n const middlewares = [];\n for (const tag of rpc.middlewares.values()) {\n const middleware = services.mapUnsafe.get(`${tag.key}/Client`);\n if (!middleware) continue;\n middlewares.push(middleware);\n }\n if (middlewares.length === 0) {\n return (send, request) => send(request);\n }\n return function loop(send, request, index = middlewares.length - 1) {\n if (index === -1) {\n return send(request);\n }\n return middlewares[index]({\n rpc,\n request,\n next(request) {\n return loop(send, request, index - 1);\n }\n });\n };\n };\n const sendInterrupt = (requestId, interruptors, context) => Effect.callback(resume => {\n const parentFiber = Fiber.getCurrent();\n const fiber = options.onFromClient({\n message: {\n _tag: \"Interrupt\",\n requestId,\n interruptors\n },\n context,\n discard: false\n }).pipe(Effect.timeout(1000), Effect.runForkWith(parentFiber.context));\n fiber.addObserver(() => {\n resume(Effect.void);\n });\n });\n const write = message => {\n switch (message._tag) {\n case \"Chunk\":\n {\n const requestId = message.requestId;\n const entry = entries.get(requestId);\n if (!entry || entry._tag !== \"Queue\") return Effect.void;\n return Queue.offerAll(entry.queue, message.values).pipe(supportsAck ? Effect.flatMap(() => options.onFromClient({\n message: {\n _tag: \"Ack\",\n requestId: message.requestId\n },\n context: entry.context,\n discard: false\n })) : identity, Effect.catchCause(cause => Queue.failCause(entry.queue, cause)));\n }\n case \"Exit\":\n {\n const requestId = message.requestId;\n const entry = entries.get(requestId);\n if (!entry) return Effect.void;\n entries.delete(requestId);\n if (entry._tag === \"Effect\") {\n entry.resume(message.exit);\n return Effect.void;\n }\n return message.exit._tag === \"Success\" ? Queue.end(entry.queue) : Queue.failCause(entry.queue, message.exit.cause);\n }\n case \"Defect\":\n {\n return clearEntries(Exit.die(message.defect));\n }\n case \"ClientEnd\":\n {\n return Effect.void;\n }\n }\n };\n let client;\n if (options.flatten) {\n const fns = new Map();\n client = function client(tag, payload, options) {\n let fn = fns.get(tag);\n if (!fn) {\n fn = onRequest(group.requests.get(tag));\n fns.set(tag, fn);\n }\n return fn(payload, options);\n };\n } else {\n client = {};\n group.requests.forEach(rpc => {\n client[rpc._tag] = onRequest(rpc);\n });\n }\n return {\n client,\n write\n };\n});\nlet clientIdCounter = 0;\n/**\n * Creates a schema-aware RPC client for a group using the current client\n * `Protocol`, encoding requests and decoding server responses.\n *\n * @category client\n * @since 4.0.0\n */\nexport const make = /*#__PURE__*/Effect.fnUntraced(function* (group, options) {\n const clientId = clientIdCounter++;\n const {\n run,\n send,\n supportsAck,\n supportsTransferables\n } = yield* Protocol;\n const entries = new Map();\n const {\n client,\n write\n } = yield* makeNoSerialization(group, {\n ...options,\n supportsAck,\n onFromClient({\n message\n }) {\n switch (message._tag) {\n case \"Request\":\n {\n const rpc = group.requests.get(message.tag);\n const collector = supportsTransferables ? Transferable.makeCollectorUnsafe() : undefined;\n const fiber = Fiber.getCurrent();\n const entry = {\n rpc,\n context: collector ? Context.add(fiber.context, Transferable.Collector, collector) : fiber.context,\n schemas: rpcSchemas(rpc)\n };\n entries.set(message.id, entry);\n return entry.schemas.encodePayload(message.payload).pipe(Effect.provideContext(entry.context), Effect.orDie, Effect.flatMap(payload => send(clientId, {\n ...message,\n id: message.id,\n payload,\n headers: Object.entries(message.headers)\n }, collector && collector.readUnsafe())));\n }\n case \"Ack\":\n {\n const entry = entries.get(message.requestId);\n if (!entry) return Effect.void;\n return send(clientId, {\n _tag: \"Ack\",\n requestId: message.requestId\n });\n }\n case \"Interrupt\":\n {\n const entry = entries.get(message.requestId);\n if (!entry) return Effect.void;\n entries.delete(message.requestId);\n return send(clientId, {\n _tag: \"Interrupt\",\n requestId: message.requestId\n });\n }\n case \"Eof\":\n {\n return Effect.void;\n }\n }\n }\n });\n yield* run(clientId, message => {\n switch (message._tag) {\n case \"Chunk\":\n {\n const requestId = RequestId(message.requestId);\n const entry = entries.get(requestId);\n if (!entry || Option.isNone(entry.schemas.decodeChunk)) return Effect.void;\n return entry.schemas.decodeChunk.value(message.values).pipe(Effect.provideContext(entry.context), Effect.orDie, Effect.flatMap(chunk => write({\n _tag: \"Chunk\",\n clientId: 0,\n requestId: RequestId(message.requestId),\n values: chunk\n })), Effect.onError(cause => write({\n _tag: \"Exit\",\n clientId: 0,\n requestId: RequestId(message.requestId),\n exit: Exit.failCause(cause)\n })));\n }\n case \"Exit\":\n {\n const requestId = RequestId(message.requestId);\n const entry = entries.get(requestId);\n if (!entry) return Effect.void;\n entries.delete(requestId);\n return entry.schemas.decodeExit(message.exit).pipe(Effect.provideContext(entry.context), Effect.orDie, Effect.matchCauseEffect({\n onSuccess: exit => write({\n _tag: \"Exit\",\n clientId: 0,\n requestId,\n exit\n }),\n onFailure: cause => write({\n _tag: \"Exit\",\n clientId: 0,\n requestId,\n exit: Exit.failCause(cause)\n })\n }));\n }\n case \"Defect\":\n {\n return write({\n _tag: \"Defect\",\n clientId: 0,\n defect: decodeDefect(message.defect)\n });\n }\n case \"ClientProtocolError\":\n {\n const exit = Exit.fail(message.error);\n return Effect.forEach(entries.keys(), requestId => write({\n _tag: \"Exit\",\n clientId: 0,\n requestId,\n exit: exit\n }));\n }\n default:\n {\n return Effect.void;\n }\n }\n }).pipe(Effect.catchCause(Effect.logError), Effect.interruptible, Effect.forkScoped);\n return client;\n});\nconst rpcSchemasCache = /*#__PURE__*/new WeakMap();\nconst rpcSchemas = rpc => {\n let entry = rpcSchemasCache.get(rpc);\n if (entry !== undefined) {\n return entry;\n }\n const streamSchemas = RpcSchema.getStreamSchemas(rpc.successSchema);\n entry = {\n decodeChunk: Option.map(streamSchemas, streamSchemas => Schema.decodeUnknownEffect(Schema.toCodecJson(Schema.NonEmptyArray(streamSchemas.success)))),\n encodePayload: Schema.encodeEffect(Schema.toCodecJson(rpc.payloadSchema)),\n decodeExit: Schema.decodeUnknownEffect(Schema.toCodecJson(Rpc.exitSchema(rpc)))\n };\n rpcSchemasCache.set(rpc, entry);\n return entry;\n};\n/**\n * Fiber reference containing headers that are merged into outgoing RPC\n * client requests.\n *\n * **When to use**\n *\n * Use to set request headers that should be automatically merged into outgoing\n * RPC client messages.\n *\n * @category headers\n * @since 4.0.0\n */\nexport const CurrentHeaders = /*#__PURE__*/Context.Reference(\"effect/rpc/RpcClient/CurrentHeaders\", {\n defaultValue: () => Headers.empty\n});\n/**\n * Runs an effect with additional RPC client headers, merging them with the\n * current `CurrentHeaders` value for outgoing requests.\n *\n * @category headers\n * @since 4.0.0\n */\nexport const withHeaders = /*#__PURE__*/dual(2, (effect, headers) => Effect.updateService(effect, CurrentHeaders, Headers.merge(Headers.fromInput(headers))));\n/**\n * Defines the service interface for an RPC client transport, responsible for running the\n * receive loop and sending encoded client messages.\n *\n * **When to use**\n *\n * Use to provide the transport boundary for RPC clients over HTTP, WebSocket,\n * workers, sockets, or custom protocols.\n *\n * @category protocols\n * @since 4.0.0\n */\nexport class Protocol extends /*#__PURE__*/Context.Service()(\"effect/rpc/RpcClient/Protocol\") {\n /**\n * Creates a client protocol service from the supplied RPC request runner.\n *\n * @since 4.0.0\n */\n static make = withRunClient;\n}\n/**\n * Creates a client `Protocol` that sends each RPC request through the supplied\n * `HttpClient` and decodes responses with the current `RpcSerialization`.\n *\n * @category protocols\n * @since 4.0.0\n */\nexport const makeProtocolHttp = client => Protocol.make(Effect.fnUntraced(function* (writeResponse) {\n const serialization = yield* RpcSerialization.RpcSerialization;\n const isFramed = serialization.includesFraming;\n const httpClientError = cause => new RpcClientError({\n reason: HttpClientErrorSchema.fromHttpClientError(cause)\n });\n const protocolDefect = (message, cause) => new RpcClientError({\n reason: new RpcClientDefect({\n message,\n cause\n })\n });\n const emptyResponseError = request => protocolDefect(\"Received empty HTTP response from RPC server\", request);\n const incompleteResponseError = request => protocolDefect(\"HTTP response ended before RPC request completed\", request);\n const send = Effect.fnUntraced(function* (clientId, request) {\n if (request._tag !== \"Request\") {\n return;\n }\n const parser = serialization.makeUnsafe();\n const encoded = parser.encode(request);\n const body = typeof encoded === \"string\" ? HttpBody.text(encoded, serialization.contentType) : HttpBody.uint8Array(encoded, serialization.contentType);\n const response = yield* client.post(\"\", {\n body\n }).pipe(Effect.mapError(httpClientError));\n if (!isFramed) {\n const text = yield* response.text.pipe(Effect.mapError(httpClientError));\n const responses = yield* Effect.try({\n try: () => parser.decode(text),\n catch: cause => protocolDefect(\"Error decoding HTTP response\", cause)\n });\n if (!Array.isArray(responses)) {\n return yield* protocolDefect(\"Expected an array of responses\", responses);\n }\n if (responses.length === 0) {\n return yield* emptyResponseError(request);\n }\n let completed = false;\n let i = 0;\n yield* Effect.whileLoop({\n while: () => i < responses.length,\n body: () => {\n const response = responses[i++];\n if (isTerminalResponse(response)) {\n completed = true;\n }\n return writeResponse(clientId, response);\n },\n step: constVoid\n });\n if (!completed) {\n return yield* incompleteResponseError(request);\n }\n return;\n }\n let hasResponse = false;\n let completed = false;\n yield* Stream.runForEachArray(response.stream, chunk => Effect.try({\n try: () => chunk.flatMap(parser.decode),\n catch: cause => protocolDefect(\"Error decoding HTTP response\", cause)\n }).pipe(Effect.flatMap(responses => {\n if (responses.length === 0) return Effect.void;\n hasResponse = true;\n let i = 0;\n return Effect.whileLoop({\n while: () => i < responses.length,\n body: () => {\n const response = responses[i++];\n if (isTerminalResponse(response)) {\n completed = true;\n }\n return writeResponse(clientId, response);\n },\n step: constVoid\n });\n }))).pipe(Effect.mapError(cause => cause instanceof RpcClientError ? cause : httpClientError(cause)));\n if (!hasResponse) {\n return yield* emptyResponseError(request);\n } else if (!completed) {\n return yield* incompleteResponseError(request);\n }\n });\n return {\n send,\n supportsAck: false,\n supportsTransferables: false\n };\n}));\n/**\n * Provides a client `Protocol` backed by `HttpClient`, targeting the configured\n * URL and optionally transforming the client before use.\n *\n * @category protocols\n * @since 4.0.0\n */\nexport const layerProtocolHttp = options => Layer.effect(Protocol)(Effect.flatMap(HttpClient.HttpClient, client => {\n client = HttpClient.mapRequest(client, HttpClientRequest.prependUrl(options.url));\n return makeProtocolHttp(options.transformClient ? options.transformClient(client) : client);\n}));\n/**\n * Creates a client `Protocol` over the current `Socket`, using the current\n * `RpcSerialization`, connection hooks, ping timeouts, and the configured retry\n * policy.\n *\n * @category protocols\n * @since 4.0.0\n */\nexport const makeProtocolSocket = options => Protocol.make(Effect.fnUntraced(function* (writeResponse, clientIds) {\n const socket = yield* Socket.Socket;\n const serialization = yield* RpcSerialization.RpcSerialization;\n const hooks = yield* Effect.serviceOption(ConnectionHooks);\n const requestClientMap = new Map();\n const write = yield* socket.writer;\n let parser = serialization.makeUnsafe();\n const pinger = yield* makePinger(write(parser.encode(constPing)));\n let currentError;\n const onOpen = Effect.suspend(() => {\n currentError = undefined;\n return Option.isSome(hooks) ? hooks.value.onConnect : Effect.void;\n });\n const broadcast = response => Effect.forEach(clientIds, clientId => writeResponse(clientId, response));\n yield* Effect.suspend(() => {\n parser = serialization.makeUnsafe();\n pinger.reset();\n return socket.runRaw(message => {\n try {\n const responses = parser.decode(message);\n if (responses.length === 0) return;\n let i = 0;\n return Effect.whileLoop({\n while: () => i < responses.length,\n body: () => {\n const response = responses[i++];\n if (response._tag === \"Pong\") {\n pinger.onPong();\n return Effect.void;\n }\n if (\"requestId\" in response) {\n const clientId = requestClientMap.get(response.requestId);\n if (clientId !== undefined) {\n if (response._tag === \"Exit\") {\n requestClientMap.delete(response.requestId);\n }\n return writeResponse(clientId, response);\n }\n }\n return broadcast(response);\n },\n step: constVoid\n });\n } catch (defect) {\n return broadcast({\n _tag: \"ClientProtocolError\",\n error: new RpcClientError({\n reason: new RpcClientDefect({\n message: \"Error decoding message\",\n cause: defect\n })\n })\n });\n }\n }, {\n onOpen\n }).pipe(Effect.raceFirst(Effect.flatMap(pinger.timeout, () => Effect.fail(new Socket.SocketError({\n reason: new Socket.SocketOpenError({\n kind: \"Timeout\",\n cause: new Error(\"ping timeout\")\n })\n })))));\n }).pipe(Effect.flatMap(() => Effect.fail(new Socket.SocketError({\n reason: new Socket.SocketCloseError({\n code: 1000\n })\n }))), Option.isSome(hooks) ? Effect.ensuring(hooks.value.onDisconnect) : identity, Effect.tapCause(cause => {\n const error = Cause.findError(cause);\n const hasError = Result.isSuccess(error);\n if (options?.retryTransientErrors && hasError && error.success.reason._tag === \"SocketOpenError\") {\n return Effect.void;\n }\n currentError = new RpcClientError({\n reason: hasError ? error.success.reason : new RpcClientDefect({\n message: \"Unknown socket error\",\n cause: Cause.squash(cause)\n })\n });\n return broadcast({\n _tag: \"ClientProtocolError\",\n error: currentError\n });\n }), Effect.retry(options?.retryPolicy ?? defaultRetryPolicy), Effect.annotateLogs({\n module: \"RpcClient\",\n method: \"makeProtocolSocket\"\n }), Effect.forkScoped);\n return {\n send(clientId, request) {\n if (currentError) {\n return Effect.fail(currentError);\n }\n if (request._tag === \"Request\") {\n requestClientMap.set(request.id, clientId);\n }\n const encoded = parser.encode(request);\n if (encoded === undefined) return Effect.void;\n return Effect.orDie(write(encoded));\n },\n supportsAck: true,\n supportsTransferables: false\n };\n}));\nconst defaultRetryPolicy = /*#__PURE__*/Schedule.min([/*#__PURE__*/Schedule.exponential(500, 1.5), /*#__PURE__*/Schedule.spaced(5000)]);\nconst makePinger = /*#__PURE__*/Effect.fnUntraced(function* (writePing) {\n let recievedPong = true;\n const latch = Latch.makeUnsafe();\n const reset = () => {\n recievedPong = true;\n latch.closeUnsafe();\n };\n const onPong = () => {\n recievedPong = true;\n };\n yield* Effect.suspend(() => {\n if (!recievedPong) return latch.open;\n recievedPong = false;\n return writePing;\n }).pipe(Effect.delay(\"5 seconds\"), Effect.ignore, Effect.forever, Effect.interruptible, Effect.forkScoped);\n return {\n timeout: latch.await,\n reset,\n onPong\n };\n});\n/**\n * Provides a client `Protocol` backed by the current `Socket` and\n * `RpcSerialization` services.\n *\n * @category protocols\n * @since 4.0.0\n */\nexport const layerProtocolSocket = options => Layer.effect(Protocol)(makeProtocolSocket(options));\n/**\n * Creates a client `Protocol` backed by a pool of workers, routing RPC requests\n * to workers and supporting transferable values when the platform does.\n *\n * @category protocols\n * @since 4.0.0\n */\nexport const makeProtocolWorker = options => Protocol.make(Effect.fnUntraced(function* (writeResponse, clientIds) {\n const worker = yield* Worker.WorkerPlatform;\n const scope = yield* Effect.scope;\n let workerId = 0;\n const initialMessage = yield* Effect.serviceOption(RpcWorker.InitialMessage);\n const hooks = yield* Effect.serviceOption(ConnectionHooks);\n const entries = new Map();\n const broadcast = response => Effect.forEach(clientIds, clientId => writeResponse(clientId, response));\n const acquire = Effect.gen(function* () {\n const id = workerId++;\n const backing = yield* worker.spawn(id);\n yield* backing.run(response => {\n if (response._tag === \"Exit\") {\n const entry = entries.get(response.requestId);\n if (entry) {\n entries.delete(response.requestId);\n entry.latch.openUnsafe();\n return writeResponse(entry.clientId, response);\n }\n } else if (response._tag === \"Defect\") {\n for (const [requestId, entry] of entries) {\n entries.delete(requestId);\n entry.latch.openUnsafe();\n }\n return broadcast(response);\n } else if (\"requestId\" in response) {\n const entry = entries.get(response.requestId);\n if (entry) {\n return writeResponse(entry.clientId, response);\n }\n }\n return broadcast(response);\n }, {\n onSpawn: Option.isSome(initialMessage) ? Effect.flatMap(initialMessage.value, ([value, transfers]) => Effect.orDie(backing.send({\n _tag: \"InitialMessage\",\n value\n }, transfers))) : undefined\n }).pipe(Effect.tapCause(cause => {\n const error = Cause.findError(cause);\n return broadcast({\n _tag: \"ClientProtocolError\",\n error: new RpcClientError({\n reason: Result.isSuccess(error) ? error.success.reason : new RpcClientDefect({\n message: \"Error in worker\",\n cause: Cause.squash(cause)\n })\n })\n });\n }), Effect.retry(Schedule.spaced(1000)), Effect.annotateLogs({\n module: \"RpcClient\",\n method: \"makeProtocolWorker\"\n }), Effect.interruptible, Effect.forkScoped);\n return backing;\n });\n const pool = \"minSize\" in options ? yield* Pool.makeWithTTL({\n acquire,\n min: options.minSize,\n max: options.maxSize,\n concurrency: options.concurrency,\n targetUtilization: options.targetUtilization,\n timeToLive: options.timeToLive\n }) : yield* Pool.make({\n acquire,\n size: options.size,\n concurrency: options.concurrency,\n targetUtilization: options.targetUtilization\n });\n yield* Scope.addFinalizer(scope, Effect.sync(() => {\n for (const entry of entries.values()) {\n entry.latch.openUnsafe();\n }\n entries.clear();\n }));\n const send = (clientId, request, transferables) => {\n switch (request._tag) {\n case \"Request\":\n {\n return Pool.get(pool).pipe(Effect.flatMap(worker => {\n const latch = Latch.makeUnsafe(false);\n entries.set(request.id, {\n clientId,\n worker,\n latch\n });\n return Effect.flatMap(worker.send(request, transferables), () => latch.await);\n }), Effect.scoped, Effect.orDie);\n }\n case \"Interrupt\":\n {\n const entry = entries.get(request.requestId);\n if (!entry) return Effect.void;\n entries.delete(request.requestId);\n entry.latch.openUnsafe();\n return Effect.orDie(entry.worker.send(request));\n }\n case \"Ack\":\n {\n const entry = entries.get(request.requestId);\n if (!entry) return Effect.void;\n return Effect.orDie(entry.worker.send(request));\n }\n }\n return Effect.void;\n };\n yield* Effect.scoped(Pool.get(pool));\n if (Option.isSome(hooks)) yield* hooks.value.onConnect;\n return {\n send,\n supportsAck: true,\n supportsTransferables: true\n };\n}));\n/**\n * Provides a client `Protocol` backed by a worker pool using the current worker\n * platform and spawner services.\n *\n * @category protocols\n * @since 4.0.0\n */\nexport const layerProtocolWorker = /*#__PURE__*/flow(makeProtocolWorker, /*#__PURE__*/Layer.effect(Protocol));\n/**\n * Represents optional client protocol hooks that run when a transport connects\n * and disconnects.\n *\n * **When to use**\n *\n * Use to run setup or cleanup effects when an RPC client transport opens or\n * closes.\n *\n * @category connection hooks\n * @since 4.0.0\n */\nexport class ConnectionHooks extends /*#__PURE__*/Context.Service()(\"effect/rpc/RpcClient/ConnectionHooks\") {}\n// internal\nconst decodeDefect = /*#__PURE__*/Schema.decodeSync(/*#__PURE__*/Schema.Defect());\n//# sourceMappingURL=RpcClient.js.map","import * as Cause from \"../../Cause.js\";\nimport * as Context from \"../../Context.js\";\nimport * as Deferred from \"../../Deferred.js\";\nimport * as Effect from \"../../Effect.js\";\nimport * as Exit from \"../../Exit.js\";\nimport * as Fiber from \"../../Fiber.js\";\nimport { constant, constTrue, constVoid, identity } from \"../../Function.js\";\nimport { reportCauseUnsafe } from \"../../internal/effect.js\";\nimport * as Latch from \"../../Latch.js\";\nimport * as Layer from \"../../Layer.js\";\nimport * as Option from \"../../Option.js\";\nimport * as Predicate from \"../../Predicate.js\";\nimport * as Pull from \"../../Pull.js\";\nimport * as Queue from \"../../Queue.js\";\nimport * as Schedule from \"../../Schedule.js\";\nimport * as Schema from \"../../Schema.js\";\nimport * as Scope from \"../../Scope.js\";\nimport * as Semaphore from \"../../Semaphore.js\";\nimport { Stdio } from \"../../Stdio.js\";\nimport * as Stream from \"../../Stream.js\";\nimport * as Tracer from \"../../Tracer.js\";\nimport * as Headers from \"../http/Headers.js\";\nimport * as HttpRouter from \"../http/HttpRouter.js\";\nimport * as HttpServerRequest from \"../http/HttpServerRequest.js\";\nimport * as HttpServerResponse from \"../http/HttpServerResponse.js\";\nimport * as SocketServer from \"../socket/SocketServer.js\";\nimport * as Transferable from \"../workers/Transferable.js\";\nimport * as WorkerRunner from \"../workers/WorkerRunner.js\";\nimport * as Rpc from \"./Rpc.js\";\nimport { constEof, constPong, RequestId, ResponseDefectEncoded } from \"./RpcMessage.js\";\nimport * as RpcSchema from \"./RpcSchema.js\";\nimport * as RpcSerialization from \"./RpcSerialization.js\";\nimport { withRun } from \"./Utils.js\";\n/**\n * Creates an RPC server for an already-decoded message channel, running\n * handlers for a group and sending decoded server responses through\n * `onFromServer`.\n *\n * @category server\n * @since 4.0.0\n */\nexport const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (group, options) {\n const enableTracing = options.disableTracing !== true;\n const enableSpanPropagation = options.disableSpanPropagation !== true;\n const supportsAck = options.disableClientAcks !== true;\n const spanPrefix = options.spanPrefix ?? \"RpcServer\";\n const concurrency = options.concurrency ?? \"unbounded\";\n const disableFatalDefects = options.disableFatalDefects ?? false;\n const services = yield* Effect.context();\n const scope = Context.get(services, Scope.Scope);\n const trackFiber = Fiber.runIn(Scope.forkUnsafe(scope, \"parallel\"));\n const concurrencySemaphore = concurrency === \"unbounded\" ? undefined : yield* Semaphore.make(concurrency);\n const clients = new Map();\n let isShutdown = false;\n const shutdownLatch = Latch.makeUnsafe(false);\n yield* Scope.addFinalizer(scope, Effect.withFiber(parent => {\n isShutdown = true;\n for (const client of clients.values()) {\n client.ended = true;\n if (client.fibers.size === 0) {\n trackFiber(Effect.runForkWith(services)(endClient(client)));\n continue;\n }\n for (const fiber of client.fibers.values()) {\n fiber.interruptUnsafe(parent.id);\n }\n }\n if (clients.size === 0) {\n return Effect.void;\n }\n return shutdownLatch.await;\n }));\n const disconnect = clientId => Effect.withFiber(parent => {\n const client = clients.get(clientId);\n if (!client) return Effect.void;\n for (const fiber of client.fibers.values()) {\n fiber.interruptUnsafe(parent.id);\n }\n clients.delete(clientId);\n return Effect.void;\n });\n const write = (clientId, message) => Effect.catchDefect(Effect.withFiber(requestFiber => {\n if (isShutdown) return Effect.interrupt;\n let client = clients.get(clientId);\n if (!client) {\n client = {\n id: clientId,\n latches: new Map(),\n fibers: new Map(),\n ended: false,\n serverClient: new Rpc.ServerClient(clientId)\n };\n clients.set(clientId, client);\n } else if (client.ended) {\n return Effect.interrupt;\n }\n switch (message._tag) {\n case \"Request\":\n {\n return handleRequest(requestFiber, client, message);\n }\n case \"Ack\":\n {\n const latch = client.latches.get(message.requestId);\n return latch ? latch.open : Effect.void;\n }\n case \"Interrupt\":\n {\n const fiber = client.fibers.get(message.requestId);\n if (fiber) {\n fiber.interruptUnsafe(requestFiber.id, RpcSchema.ClientAbort.annotation);\n return Effect.void;\n }\n return options.onFromServer({\n _tag: \"Exit\",\n clientId,\n requestId: message.requestId,\n exit: Exit.interrupt()\n });\n }\n case \"Eof\":\n {\n client.ended = true;\n if (client.fibers.size > 0) return Effect.void;\n return endClient(client);\n }\n default:\n {\n return sendDefect(client, `Unknown request tag: ${message._tag}`);\n }\n }\n }), defect => sendDefect(clients.get(clientId), defect));\n const endClient = client => {\n clients.delete(client.id);\n const write = options.onFromServer({\n _tag: \"ClientEnd\",\n clientId: client.id\n });\n if (isShutdown && clients.size === 0) {\n return Effect.andThen(write, shutdownLatch.open);\n }\n return write;\n };\n const handleRequest = (requestFiber, client, request) => {\n if (client.fibers.has(request.id)) {\n return Effect.interrupt;\n }\n const rpc = group.requests.get(request.tag);\n const entry = services.mapUnsafe.get(rpc?.key);\n if (!rpc || !entry) {\n const write = Effect.catchDefect(options.onFromServer({\n _tag: \"Exit\",\n clientId: client.id,\n requestId: request.id,\n exit: Exit.die(`Unknown request tag: ${request.tag}`)\n }), defect => sendDefect(client, defect));\n if (!client.ended || client.fibers.size > 0) return write;\n return Effect.ensuring(write, endClient(client));\n }\n const isStream = RpcSchema.isStreamSchema(rpc.successSchema);\n const metadata = {\n rpc,\n client: client.serverClient,\n requestId: request.id,\n headers: request.headers,\n payload: request.payload\n };\n const result = entry.handler(request.payload, metadata);\n // if the handler requested forking, then we skip the concurrency control\n const isWrapper = Rpc.isWrapper(result);\n const isFork = isWrapper && result.fork;\n const isUninterruptible = isWrapper && result.uninterruptible;\n // unwrap the fork data type\n const streamOrEffect = isWrapper ? result.value : result;\n const handler = isStream ? streamEffect(client, request, streamOrEffect) : streamOrEffect;\n const withMiddleware = rpc.middlewares.size > 0 ? applyMiddleware(services, handler, metadata) : handler;\n let responded = false;\n const scope = Scope.makeUnsafe();\n let deferred = undefined;\n let effect = Effect.onExit(withMiddleware, exit => {\n responded = true;\n let write;\n if (exit._tag === \"Success\") {\n if (Deferred.isDeferred(exit.value)) {\n deferred = exit.value;\n write = Effect.void;\n } else {\n write = options.onFromServer({\n _tag: \"Exit\",\n clientId: client.id,\n requestId: request.id,\n exit: exit\n });\n }\n } else if (!disableFatalDefects && Cause.hasDies(exit.cause) && !Cause.hasInterrupts(exit.cause)) {\n write = sendDefect(client, Cause.squash(exit.cause));\n } else {\n write = options.onFromServer({\n _tag: \"Exit\",\n clientId: client.id,\n requestId: request.id,\n exit: exit\n });\n }\n const close = Scope.closeUnsafe(scope, exit);\n if (exit._tag === \"Failure\") {\n reportCauseUnsafe(Fiber.getCurrent(), exit.cause);\n }\n return close ? Effect.ensuring(write, close) : write;\n });\n if (enableTracing) {\n const parentSpan = requestFiber.context.mapUnsafe.get(Tracer.ParentSpan.key);\n effect = Effect.withSpan(effect, `${spanPrefix}.${request.tag}`, {\n captureStackTrace: false,\n attributes: options.spanAttributes,\n parent: enableSpanPropagation && request.spanId ? Tracer.externalSpan({\n traceId: request.traceId,\n spanId: request.spanId,\n sampled: request.sampled\n }) : undefined,\n links: enableSpanPropagation && parentSpan ? [{\n span: parentSpan,\n attributes: {}\n }] : undefined\n });\n }\n if (!isFork && concurrencySemaphore) {\n effect = concurrencySemaphore.withPermit(effect);\n }\n const context = new Map(entry.context.mapUnsafe);\n requestFiber.context.mapUnsafe.forEach((value, key) => context.set(key, value));\n context.set(Scope.Scope.key, scope);\n const runFork = Effect.runForkWith(Context.makeUnsafe(context));\n const fiber = trackFiber(runFork(effect, isUninterruptible ? {\n uninterruptible: true\n } : undefined));\n client.fibers.set(request.id, fiber);\n fiber.addObserver(function onExit(exit) {\n if (deferred) {\n const fiber = trackFiber(runFork(Effect.onExit(Deferred.await(deferred), exit => options.onFromServer({\n _tag: \"Exit\",\n clientId: client.id,\n requestId: request.id,\n exit: exit\n }))));\n client.fibers.set(request.id, fiber);\n deferred = undefined;\n fiber.addObserver(onExit);\n return;\n }\n if (!responded && exit._tag === \"Failure\") {\n trackFiber(runFork(options.onFromServer({\n _tag: \"Exit\",\n clientId: client.id,\n requestId: request.id,\n exit: Exit.interrupt()\n })));\n }\n client.fibers.delete(request.id);\n client.latches.delete(request.id);\n if (client.ended && client.fibers.size === 0) {\n trackFiber(runFork(endClient(client)));\n }\n });\n return Effect.void;\n };\n const streamEffect = (client, request, stream) => {\n let latch = client.latches.get(request.id);\n if (supportsAck && !latch) {\n latch = Latch.makeUnsafe(false);\n client.latches.set(request.id, latch);\n }\n if (Effect.isEffect(stream)) {\n return stream.pipe(Effect.flatMap(queue => Effect.whileLoop({\n while: constTrue,\n body: constant(Effect.flatMap(Queue.takeAll(queue), values => {\n const write = options.onFromServer({\n _tag: \"Chunk\",\n clientId: client.id,\n requestId: request.id,\n values\n });\n if (!latch) return write;\n latch.closeUnsafe();\n return Effect.flatMap(write, () => latch.await);\n })),\n step: constVoid\n })), Pull.catchDone(() => Effect.void), Effect.scoped);\n }\n return Stream.runForEachArray(stream, values => {\n const write = options.onFromServer({\n _tag: \"Chunk\",\n clientId: client.id,\n requestId: request.id,\n values\n });\n if (!latch) return write;\n latch.closeUnsafe();\n return Effect.andThen(write, latch.await);\n });\n };\n const sendDefect = (client, defect) => Effect.suspend(() => {\n const shouldEnd = client.ended && client.fibers.size === 0;\n const write = options.onFromServer({\n _tag: \"Defect\",\n clientId: client.id,\n defect\n });\n if (!shouldEnd) return write;\n return Effect.andThen(write, endClient(client));\n });\n return identity({\n write,\n disconnect\n });\n});\nconst applyMiddleware = (context, handler, options) => {\n for (const service of options.rpc.middlewares) {\n const middleware = Context.getUnsafe(context, service);\n handler = middleware(handler, options);\n }\n return handler;\n};\n/**\n * Runs an RPC server for a group using the current server `Protocol`, decoding\n * requests, invoking handlers, encoding responses, and managing in-flight\n * request lifetime.\n *\n * @category server\n * @since 4.0.0\n */\nexport const make = /*#__PURE__*/Effect.fnUntraced(function* (group, options) {\n const {\n disconnects,\n end,\n run,\n send,\n supportsAck,\n supportsSpanPropagation,\n supportsTransferables\n } = yield* Protocol;\n const services = yield* Effect.context();\n const scope = yield* Scope.make();\n const server = yield* makeNoSerialization(group, {\n ...options,\n disableClientAcks: !supportsAck,\n disableSpanPropagation: !supportsSpanPropagation,\n onFromServer(response) {\n const client = clients.get(response.clientId);\n if (!client) return Effect.void;\n switch (response._tag) {\n case \"Chunk\":\n {\n const schemas = client.schemas.get(response.requestId);\n if (!schemas) return Effect.void;\n return handleEncode(client, response.requestId, schemas.encodeDefect, schemas.collector, Effect.provideContext(schemas.encodeChunk(response.values), schemas.context), values => ({\n _tag: \"Chunk\",\n requestId: response.requestId,\n values\n }));\n }\n case \"Exit\":\n {\n const schemas = client.schemas.get(response.requestId);\n if (!schemas) return Effect.void;\n client.schemas.delete(response.requestId);\n return handleEncode(client, response.requestId, schemas.encodeDefect, schemas.collector, Effect.provideContext(schemas.encodeExit(response.exit), schemas.context), exit => ({\n _tag: \"Exit\",\n requestId: response.requestId,\n exit\n }));\n }\n case \"Defect\":\n {\n return sendDefect(client, response.defect);\n }\n case \"ClientEnd\":\n {\n clients.delete(response.clientId);\n return end(response.clientId);\n }\n }\n }\n }).pipe(Scope.provide(scope));\n // handle disconnects\n yield* Effect.forkChild(Effect.whileLoop({\n while: constTrue,\n body: constant(Effect.flatMap(Queue.take(disconnects), clientId => {\n clients.delete(clientId);\n return server.disconnect(clientId);\n })),\n step: constVoid\n }));\n const schemasCache = new WeakMap();\n const getSchemas = rpc => {\n let schemas = schemasCache.get(rpc);\n if (!schemas) {\n const entry = services.mapUnsafe.get(rpc.key);\n const streamSchemas = RpcSchema.getStreamSchemas(rpc.successSchema);\n schemas = {\n decode: Schema.decodeUnknownEffect(Schema.toCodecJson(rpc.payloadSchema)),\n encodeChunk: Schema.encodeUnknownEffect(Schema.toCodecJson(Schema.Array(Option.isSome(streamSchemas) ? streamSchemas.value.success : Schema.Any))),\n encodeExit: Schema.encodeUnknownEffect(Schema.toCodecJson(Rpc.exitSchema(rpc))),\n encodeDefect: Schema.encodeUnknownEffect(Schema.toCodecJson(rpc.defectSchema)),\n context: entry.context\n };\n schemasCache.set(rpc, schemas);\n }\n return schemas;\n };\n const clients = new Map();\n const handleEncode = (client, requestId, encodeDefect, collector, effect, onSuccess) => (collector ? Effect.provideService(effect, Transferable.Collector, collector) : effect).pipe(Effect.flatMap(a => send(client.id, onSuccess(a), collector && collector.clearUnsafe())), Effect.catchCause(cause => {\n client.schemas.delete(requestId);\n const defect = Cause.squash(Cause.map(cause, e => e.issue.toString()));\n return Effect.andThen(sendRequestDefect(client, requestId, encodeDefect, defect), server.write(client.id, {\n _tag: \"Interrupt\",\n requestId,\n interruptors: []\n }));\n }));\n const sendRequestDefect = (client, requestId, encodeDefect, defect) => Effect.catchCause(Effect.flatMap(encodeDefect(defect), encodedDefect => send(client.id, {\n _tag: \"Exit\",\n requestId,\n exit: {\n _tag: \"Failure\",\n cause: [{\n _tag: \"Die\",\n defect: encodedDefect\n }]\n }\n })), cause => sendDefect(client, Cause.squash(cause)));\n const sendDefect = (client, defect) => Effect.catchCause(send(client.id, ResponseDefectEncoded(defect)), cause => Effect.annotateLogs(Effect.logDebug(cause), {\n module: \"RpcServer\",\n method: \"sendDefect\"\n }));\n // main server loop\n return yield* run((clientId, request) => {\n let client = clients.get(clientId);\n if (!client) {\n client = {\n id: clientId,\n schemas: new Map()\n };\n clients.set(clientId, client);\n }\n switch (request._tag) {\n case \"Request\":\n {\n const tag = Predicate.hasProperty(request, \"tag\") ? request.tag : \"\";\n let requestId;\n switch (typeof request.id) {\n case \"number\":\n case \"string\":\n {\n requestId = RequestId(request.id);\n break;\n }\n default:\n {\n return sendDefect(client, `Invalid request id: ${request.id}`);\n }\n }\n const rpc = group.requests.get(tag);\n if (!rpc) {\n return sendRequestDefect(client, requestId, defect => Effect.succeed(defect), `Unknown request tag: ${tag}`);\n }\n const schemas = getSchemas(rpc);\n return Effect.matchEffect(Effect.provideContext(schemas.decode(request.payload), schemas.context), {\n onFailure: error => sendRequestDefect(client, requestId, schemas.encodeDefect, error.issue.toString()),\n onSuccess: payload => {\n client.schemas.set(requestId, supportsTransferables ? {\n ...schemas,\n collector: Transferable.makeCollectorUnsafe()\n } : schemas);\n return server.write(clientId, {\n ...request,\n id: requestId,\n payload,\n headers: Headers.fromInput(request.headers)\n });\n }\n });\n }\n case \"Ping\":\n {\n return Effect.catchCause(send(client.id, constPong), cause => sendDefect(client, Cause.squash(cause)));\n }\n case \"Eof\":\n {\n return server.write(clientId, request);\n }\n case \"Ack\":\n {\n return server.write(clientId, {\n ...request,\n requestId: RequestId(request.requestId)\n });\n }\n case \"Interrupt\":\n {\n return server.write(clientId, {\n ...request,\n requestId: RequestId(request.requestId),\n interruptors: []\n });\n }\n default:\n {\n return sendDefect(client, `Unknown request tag: ${request._tag}`);\n }\n }\n }).pipe(Effect.tapCause(cause => Effect.logFatal(\"BUG: RpcServer protocol crashed\", cause)), Effect.onExit(exit => Scope.close(scope, exit)));\n});\n/**\n * Provides a scoped layer that starts an RPC server for a group using the\n * current server `Protocol`.\n *\n * @category server\n * @since 4.0.0\n */\nexport const layer = (group, options) => Layer.effectDiscard(Effect.forkScoped(make(group, options)));\n/**\n * Creates a RPC server that registers a HTTP route with a `HttpRouter`.\n *\n * **Details**\n *\n * Defaults to using websockets for communication, but can be configured to use\n * HTTP.\n *\n * @category protocols\n * @since 4.0.0\n */\nexport const layerHttp = options => layer(options.group, options).pipe(Layer.provide(options.protocol === \"http\" ? layerProtocolHttp(options) : layerProtocolWebsocket(options)));\n/**\n * Defines the service interface for an RPC server transport, responsible for receiving\n * encoded client messages, sending encoded responses, tracking clients, and\n * declaring transport capabilities.\n *\n * **When to use**\n *\n * Use to provide the transport boundary for RPC servers over HTTP, WebSocket,\n * workers, sockets, or custom protocols.\n *\n * @category protocols\n * @since 4.0.0\n */\nexport class Protocol extends /*#__PURE__*/Context.Service()(\"effect/rpc/RpcServer/Protocol\") {\n /**\n * Creates a server protocol service from the supplied RPC implementation.\n *\n * @since 4.0.0\n */\n static make = /*#__PURE__*/withRun();\n}\n/**\n * Creates a server `Protocol` backed by the current `SocketServer`, accepting\n * socket connections and routing decoded RPC messages.\n *\n * @category protocols\n * @since 4.0.0\n */\nexport const makeProtocolSocketServer = /*#__PURE__*/Effect.gen(function* () {\n const server = yield* SocketServer.SocketServer;\n const {\n onSocket,\n protocol\n } = yield* makeSocketProtocol;\n yield* Effect.forkScoped(server.run(Effect.fnUntraced(onSocket, Effect.scoped)));\n return protocol;\n});\n/**\n * RPC protocol that uses `SocketServer` for communication.\n *\n * @category protocols\n * @since 4.0.0\n */\nexport const layerProtocolSocketServer = /*#__PURE__*/Layer.effect(Protocol)(makeProtocolSocketServer);\n/**\n * Creates a websocket server `Protocol` together with an HTTP effect that\n * upgrades the current request to a websocket and attaches it to the protocol.\n *\n * @category protocols\n * @since 4.0.0\n */\nexport const makeProtocolWithHttpEffectWebsocket = /*#__PURE__*/Effect.gen(function* () {\n const {\n onSocket,\n protocol\n } = yield* makeSocketProtocol;\n const httpEffect = Effect.gen(function* () {\n const request = yield* HttpServerRequest.HttpServerRequest;\n const socket = yield* Effect.orDie(request.upgrade);\n yield* onSocket(socket, Object.entries(request.headers));\n return HttpServerResponse.empty();\n });\n return {\n protocol,\n httpEffect\n };\n});\n/**\n * Creates a websocket server `Protocol` and registers its upgrade handler as a\n * GET route on the current `HttpRouter`.\n *\n * @category protocols\n * @since 4.0.0\n */\nexport const makeProtocolWebsocket = /*#__PURE__*/Effect.fnUntraced(function* (options) {\n const {\n httpEffect,\n protocol\n } = yield* makeProtocolWithHttpEffectWebsocket;\n const router = yield* HttpRouter.HttpRouter;\n yield* router.add(\"GET\", options.path, httpEffect);\n return protocol;\n});\n/**\n * RPC protocol that uses WebSockets for communication.\n *\n * @category protocols\n * @since 4.0.0\n */\nexport const layerProtocolWebsocket = options => {\n return Layer.effect(Protocol)(makeProtocolWebsocket(options));\n};\n/**\n * Creates an HTTP request/response server `Protocol` together with an HTTP\n * effect that decodes the current request and streams or returns encoded RPC\n * responses.\n *\n * @category protocols\n * @since 4.0.0\n */\nexport const makeProtocolWithHttpEffect = /*#__PURE__*/Effect.gen(function* () {\n const serialization = yield* RpcSerialization.RpcSerialization;\n const includesFraming = serialization.includesFraming;\n const isBinary = !serialization.contentType.includes(\"json\");\n const disconnects = yield* Queue.make();\n let writeRequest;\n let clientId = 0;\n const clients = new Map();\n const clientIds = new Set();\n const encoder = new TextEncoder();\n const httpEffect = Effect.gen(function* () {\n const fiber = Fiber.getCurrent();\n const request = Context.getUnsafe(fiber.context, HttpServerRequest.HttpServerRequest);\n const scope = Context.getUnsafe(fiber.context, Scope.Scope);\n const requestHeaders = Object.entries(request.headers);\n const data = yield* Effect.orDie(isBinary ? Effect.map(request.arrayBuffer, buf => new Uint8Array(buf)) : request.text);\n const id = clientId++;\n const queue = yield* Queue.make();\n const parser = serialization.makeUnsafe();\n const requestIds = [];\n const offer = data => typeof data === \"string\" ? Queue.offer(queue, encoder.encode(data)) : Queue.offer(queue, data);\n const client = {\n write: !includesFraming ? response => Queue.offer(queue, response) : response => {\n try {\n const encoded = parser.encode(response);\n if (encoded === undefined) return Effect.void;\n return offer(encoded);\n } catch (cause) {\n return offer(parser.encode(ResponseDefectEncoded(cause)));\n }\n },\n end: Queue.end(queue)\n };\n yield* Scope.addFinalizerExit(scope, () => {\n clients.delete(id);\n clientIds.delete(id);\n Queue.offerUnsafe(disconnects, id);\n if (queue.state._tag === \"Done\") return Effect.void;\n return Effect.forEach(requestIds, requestId => writeRequest(id, {\n _tag: \"Interrupt\",\n requestId\n }), {\n discard: true\n });\n });\n clients.set(id, client);\n clientIds.add(id);\n // @effect-diagnostics-next-line tryCatchInEffectGen:off\n try {\n const decoded = parser.decode(data);\n for (let i = 0; i < decoded.length; i++) {\n const message = decoded[i];\n if (message._tag === \"Request\") {\n requestIds.push(RequestId(message.id));\n message.headers = requestHeaders.concat(message.headers);\n }\n yield* writeRequest(id, message);\n }\n } catch (cause) {\n yield* client.write(ResponseDefectEncoded(cause));\n }\n yield* writeRequest(id, constEof);\n if (!includesFraming) {\n const responses = yield* Queue.collect(queue);\n return HttpServerResponse.text(parser.encode(responses), {\n contentType: serialization.contentType\n });\n }\n const initialChunk = yield* Queue.takeAll(queue);\n if (queue.state._tag === \"Done\") {\n return HttpServerResponse.uint8Array(mergeUint8Arrays(initialChunk), {\n contentType: serialization.contentType\n });\n }\n return HttpServerResponse.stream(Stream.fromArray(initialChunk).pipe(Stream.concat(Stream.fromQueue(queue))), {\n contentType: serialization.contentType\n });\n });\n const protocol = yield* Protocol.make(writeRequest_ => {\n writeRequest = writeRequest_;\n return Effect.succeed({\n disconnects,\n send(clientId, response) {\n const client = clients.get(clientId);\n if (!client) return Effect.void;\n return client.write(response);\n },\n end(clientId) {\n const client = clients.get(clientId);\n if (!client) return Effect.void;\n return client.end;\n },\n clientIds: Effect.sync(() => clientIds),\n initialMessage: Effect.succeedNone,\n supportsAck: false,\n supportsTransferables: false,\n supportsSpanPropagation: false\n });\n });\n return {\n protocol,\n httpEffect\n };\n});\nconst mergeUint8Arrays = arrays => {\n if (arrays.length === 0) return new Uint8Array(0);\n if (arrays.length === 1) return arrays[0];\n const length = arrays.reduce((acc, arr) => acc + arr.length, 0);\n const result = new Uint8Array(length);\n let offset = 0;\n for (const arr of arrays) {\n result.set(arr, offset);\n offset += arr.length;\n }\n return result;\n};\n/**\n * Creates an HTTP server `Protocol` and registers its request handler as a POST\n * route on the current `HttpRouter`.\n *\n * @category protocols\n * @since 4.0.0\n */\nexport const makeProtocolHttp = /*#__PURE__*/Effect.fnUntraced(function* (options) {\n const {\n httpEffect,\n protocol\n } = yield* makeProtocolWithHttpEffect;\n const router = yield* HttpRouter.HttpRouter;\n yield* router.add(\"POST\", options.path, httpEffect);\n return protocol;\n});\n/**\n * Provides a server `Protocol` that uses HTTP POST requests for RPC\n * communication.\n *\n * @category protocols\n * @since 4.0.0\n */\nexport const layerProtocolHttp = options => {\n return Layer.effect(Protocol)(makeProtocolHttp(options));\n};\n/**\n * Starts an RPC server for a group and returns the HTTP request/response effect\n * that serves the non-websocket HTTP RPC protocol.\n *\n * @category http app\n * @since 4.0.0\n */\nexport const toHttpEffect = /*#__PURE__*/Effect.fnUntraced(function* (group, options) {\n const {\n httpEffect,\n protocol\n } = yield* makeProtocolWithHttpEffect;\n yield* make(group, options).pipe(Effect.provideService(Protocol, protocol), Effect.forkScoped);\n // @effect-diagnostics-next-line returnEffectInGen:off\n return httpEffect;\n});\n/**\n * Starts an RPC server for a group and returns the HTTP effect that upgrades\n * requests to the websocket RPC protocol.\n *\n * @category http app\n * @since 4.0.0\n */\nexport const toHttpEffectWebsocket = /*#__PURE__*/Effect.fnUntraced(function* (group, options) {\n const {\n httpEffect,\n protocol\n } = yield* makeProtocolWithHttpEffectWebsocket;\n yield* make(group, options).pipe(Effect.provideService(Protocol, protocol), Effect.forkScoped);\n // @effect-diagnostics-next-line returnEffectInGen:off\n return httpEffect;\n});\n/**\n * Creates a server `Protocol` that reads RPC messages from `Stdio.stdin` and\n * writes encoded responses to `Stdio.stdout`.\n *\n * @category protocols\n * @since 4.0.0\n */\nexport const makeProtocolStdio = /*#__PURE__*/Effect.gen(function* () {\n const stdio = yield* Stdio;\n const fiber = Fiber.getCurrent();\n const serialization = yield* RpcSerialization.RpcSerialization;\n return yield* Protocol.make(Effect.fnUntraced(function* (writeRequest) {\n const queue = yield* Queue.make();\n const parser = serialization.makeUnsafe();\n yield* stdio.stdin.pipe(Stream.runForEach(data => {\n const decoded = parser.decode(data);\n if (decoded.length === 0) return Effect.void;\n let i = 0;\n return Effect.whileLoop({\n while: () => i < decoded.length,\n body: () => writeRequest(0, decoded[i++]),\n step: constVoid\n });\n }), Effect.sandbox, Effect.tapError(Effect.logError), Effect.retry(Schedule.spaced(500)), Effect.ensuring(Effect.forkDetach(Fiber.interrupt(fiber), {\n startImmediately: true\n })), Effect.forkScoped);\n yield* Stream.fromQueue(queue).pipe(Stream.run(stdio.stdout()), Effect.retry(Schedule.spaced(500)), Effect.forkScoped);\n return {\n disconnects: yield* Queue.make(),\n send(_clientId, response) {\n const responseEncoded = parser.encode(response);\n if (responseEncoded === undefined) {\n return Effect.void;\n }\n return Queue.offer(queue, responseEncoded);\n },\n end(_clientId) {\n return Queue.end(queue);\n },\n clientIds: Effect.succeed(new Set([0])),\n initialMessage: Effect.succeedNone,\n supportsAck: true,\n supportsTransferables: false,\n supportsSpanPropagation: true\n };\n }));\n});\n/**\n * Provides a server `Protocol` that reads RPC messages from `Stdio.stdin` and\n * writes encoded responses to `Stdio.stdout`.\n *\n * @category protocols\n * @since 4.0.0\n */\nexport const layerProtocolStdio = /*#__PURE__*/Layer.effect(Protocol, makeProtocolStdio);\n/**\n * Creates a server `Protocol` backed by `WorkerRunnerPlatform`, routing worker\n * messages to the RPC server and server responses back to workers.\n *\n * @category protocols\n * @since 4.0.0\n */\nexport const makeProtocolWorkerRunner = /*#__PURE__*/Protocol.make(/*#__PURE__*/Effect.fnUntraced(function* (writeRequest) {\n const fiber = Fiber.getCurrent();\n const runner = yield* WorkerRunner.WorkerRunnerPlatform;\n const backing = yield* runner.start();\n const initialMessage = yield* Deferred.make();\n const clientIds = new Set();\n const disconnects = yield* Queue.make();\n yield* backing.run((clientId, message) => {\n clientIds.add(clientId);\n if (message._tag === \"InitialMessage\") {\n return Deferred.succeed(initialMessage, message.value);\n }\n return writeRequest(clientId, message);\n }).pipe(Effect.tapCause(Effect.logError), Effect.onExit(() => Effect.sync(() => {\n fiber.currentDispatcher.scheduleTask(() => fiber.interruptUnsafe(fiber.id), 0);\n })), Effect.forkScoped);\n if (backing.disconnects) {\n yield* Queue.take(backing.disconnects).pipe(Effect.tap(clientId => {\n clientIds.delete(clientId);\n return Queue.offer(disconnects, clientId);\n }), Effect.forkScoped);\n }\n return {\n disconnects,\n send: backing.send,\n end(_clientId) {\n return Effect.void;\n },\n clientIds: Effect.sync(() => clientIds),\n initialMessage: Effect.asSome(Deferred.await(initialMessage)),\n supportsAck: true,\n supportsTransferables: true,\n supportsSpanPropagation: true\n };\n}));\n/**\n * Provides a server `Protocol` backed by the current `WorkerRunnerPlatform`.\n *\n * @category protocols\n * @since 4.0.0\n */\nexport const layerProtocolWorkerRunner = /*#__PURE__*/Layer.effect(Protocol)(makeProtocolWorkerRunner);\n// internal\nconst makeSocketProtocol = /*#__PURE__*/Effect.gen(function* () {\n const serialization = yield* RpcSerialization.RpcSerialization;\n const disconnects = yield* Queue.make();\n let clientId = 0;\n const clients = new Map();\n const clientIds = new Set();\n let writeRequest;\n const onSocket = function* (socket, headers) {\n const scope = yield* Effect.scope;\n const parser = serialization.makeUnsafe();\n const id = clientId++;\n yield* Scope.addFinalizerExit(scope, () => {\n clients.delete(id);\n clientIds.delete(id);\n return Queue.offer(disconnects, id);\n });\n const writeRaw = yield* socket.writer;\n const write = response => {\n try {\n const encoded = parser.encode(response);\n if (encoded === undefined) {\n return Effect.void;\n }\n return Effect.orDie(writeRaw(encoded));\n } catch (cause) {\n return Effect.orDie(writeRaw(parser.encode(ResponseDefectEncoded(cause))));\n }\n };\n clients.set(id, {\n write\n });\n clientIds.add(id);\n yield* socket.runRaw(data => {\n try {\n const decoded = parser.decode(data);\n if (decoded.length === 0) return Effect.void;\n let i = 0;\n return Effect.whileLoop({\n while: () => i < decoded.length,\n body() {\n const message = decoded[i++];\n if (message._tag === \"Request\" && headers) {\n ;\n message.headers = headers.concat(message.headers);\n }\n return writeRequest(id, message);\n },\n step: constVoid\n });\n } catch (cause) {\n return writeRaw(parser.encode(ResponseDefectEncoded(cause)));\n }\n }).pipe(Effect.catchReason(\"SocketError\", \"SocketCloseError\", _ => Effect.void), Effect.orDie);\n };\n const protocol = yield* Protocol.make(writeRequest_ => {\n writeRequest = writeRequest_;\n return Effect.succeed({\n disconnects,\n send: (clientId, response) => {\n const client = clients.get(clientId);\n if (!client) return Effect.void;\n return Effect.orDie(client.write(response));\n },\n end(_clientId) {\n return Effect.void;\n },\n clientIds: Effect.sync(() => clientIds),\n initialMessage: Effect.succeedNone,\n supportsAck: true,\n supportsTransferables: false,\n supportsSpanPropagation: true\n });\n });\n return {\n protocol,\n onSocket\n };\n});\n//# sourceMappingURL=RpcServer.js.map","import * as Context from \"../../Context.js\";\nimport * as Effect from \"../../Effect.js\";\nimport { identity } from \"../../Function.js\";\nimport * as Layer from \"../../Layer.js\";\nimport * as Stream from \"../../Stream.js\";\nimport * as Rpc from \"./Rpc.js\";\nconst TypeId = \"~effect/rpc/RpcGroup\";\nconst RpcGroupProto = {\n add(...rpcs) {\n const requests = new Map(this.requests);\n for (const rpc of rpcs) {\n requests.set(rpc._tag, rpc);\n }\n return makeProto({\n requests,\n annotations: this.annotations\n });\n },\n merge(...groups) {\n const requests = new Map(this.requests);\n const annotations = new Map(this.annotations.mapUnsafe);\n for (const group of groups) {\n for (const [tag, rpc] of group.requests) {\n requests.set(tag, rpc);\n }\n for (const [key, value] of group.annotations.mapUnsafe) {\n annotations.set(key, value);\n }\n }\n return makeProto({\n requests,\n annotations: Context.makeUnsafe(annotations)\n });\n },\n omit(...tags) {\n const requests = new Map(this.requests);\n for (const tag of tags) {\n requests.delete(tag);\n }\n return makeProto({\n requests,\n annotations: this.annotations\n });\n },\n middleware(middleware) {\n const requests = new Map();\n for (const [tag, rpc] of this.requests) {\n requests.set(tag, rpc.middleware(middleware));\n }\n return makeProto({\n requests,\n annotations: this.annotations\n });\n },\n toHandlers(build) {\n // oxlint-disable-next-line no-this-alias\n const self = this;\n return Effect.gen(function* () {\n const services = yield* Effect.context();\n const handlers = Effect.isEffect(build) ? yield* build : build;\n const contextMap = new Map();\n self.requests.forEach((rpc, tag) => {\n contextMap.set(rpc.key, {\n tag: rpc._tag,\n handler: handlers[tag],\n context: services\n });\n });\n return Context.makeUnsafe(contextMap);\n });\n },\n prefix(prefix) {\n const requests = new Map();\n for (const rpc of this.requests.values()) {\n const newRpc = rpc.prefix(prefix);\n requests.set(newRpc._tag, newRpc);\n }\n return makeProto({\n requests,\n annotations: this.annotations\n });\n },\n toLayer(build) {\n return Layer.effectContext(this.toHandlers(build));\n },\n of: identity,\n toLayerHandler(service, build) {\n // oxlint-disable-next-line no-this-alias\n const self = this;\n return Layer.effectContext(Effect.gen(function* () {\n const services = yield* Effect.context();\n const handler = Effect.isEffect(build) ? yield* build : build;\n const contextMap = new Map();\n const rpc = self.requests.get(service);\n contextMap.set(rpc.key, {\n handler,\n context: services\n });\n return Context.makeUnsafe(contextMap);\n }));\n },\n accessHandler(service) {\n return Effect.contextWith(parentContext => {\n const rpc = this.requests.get(service);\n const {\n handler,\n context\n } = parentContext.mapUnsafe.get(rpc.key);\n return Effect.succeed((payload, options) => {\n options.rpc = rpc;\n const result = handler(payload, options);\n const effectOrStream = Rpc.isWrapper(result) ? result.value : result;\n return Effect.isEffect(effectOrStream) ? Effect.provide(effectOrStream, context) : Stream.provideContext(effectOrStream, context);\n });\n });\n },\n annotate(service, value) {\n return makeProto({\n requests: this.requests,\n annotations: Context.add(this.annotations, service, value)\n });\n },\n annotateRpcs(service, value) {\n return this.annotateRpcsMerge(Context.make(service, value));\n },\n annotateMerge(context) {\n return makeProto({\n requests: this.requests,\n annotations: Context.merge(this.annotations, context)\n });\n },\n annotateRpcsMerge(context) {\n const requests = new Map();\n for (const [tag, rpc] of this.requests) {\n requests.set(tag, rpc.annotateMerge(Context.merge(context, rpc.annotations)));\n }\n return makeProto({\n requests,\n annotations: this.annotations\n });\n }\n};\nconst makeProto = options => Object.assign(function () {}, RpcGroupProto, {\n requests: options.requests,\n annotations: options.annotations\n});\n/**\n * Creates an `RpcGroup` from one or more RPC definitions.\n *\n * @category groups\n * @since 4.0.0\n */\nexport const make = (...rpcs) => makeProto({\n requests: new Map(rpcs.map(rpc => [rpc._tag, rpc])),\n annotations: Context.empty()\n});\n//# sourceMappingURL=RpcGroup.js.map","'use strict';\n\nconst BINARY_TYPES = ['nodebuffer', 'arraybuffer', 'fragments'];\nconst hasBlob = typeof Blob !== 'undefined';\n\nif (hasBlob) BINARY_TYPES.push('blob');\n\nmodule.exports = {\n BINARY_TYPES,\n CLOSE_TIMEOUT: 30000,\n EMPTY_BUFFER: Buffer.alloc(0),\n GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11',\n hasBlob,\n kForOnEventAttribute: Symbol('kIsForOnEventAttribute'),\n kListener: Symbol('kListener'),\n kStatusCode: Symbol('status-code'),\n kWebSocket: Symbol('websocket'),\n NOOP: () => {}\n};\n","export default {};\nthrow new Error(`Could not resolve \"bufferutil\" imported by \"ws\". Is it installed?`)","'use strict';\n\nconst { EMPTY_BUFFER } = require('./constants');\n\nconst FastBuffer = Buffer[Symbol.species];\n\n/**\n * Merges an array of buffers into a new buffer.\n *\n * @param {Buffer[]} list The array of buffers to concat\n * @param {Number} totalLength The total length of buffers in the list\n * @return {Buffer} The resulting buffer\n * @public\n */\nfunction concat(list, totalLength) {\n if (list.length === 0) return EMPTY_BUFFER;\n if (list.length === 1) return list[0];\n\n const target = Buffer.allocUnsafe(totalLength);\n let offset = 0;\n\n for (let i = 0; i < list.length; i++) {\n const buf = list[i];\n target.set(buf, offset);\n offset += buf.length;\n }\n\n if (offset < totalLength) {\n return new FastBuffer(target.buffer, target.byteOffset, offset);\n }\n\n return target;\n}\n\n/**\n * Masks a buffer using the given mask.\n *\n * @param {Buffer} source The buffer to mask\n * @param {Buffer} mask The mask to use\n * @param {Buffer} output The buffer where to store the result\n * @param {Number} offset The offset at which to start writing\n * @param {Number} length The number of bytes to mask.\n * @public\n */\nfunction _mask(source, mask, output, offset, length) {\n for (let i = 0; i < length; i++) {\n output[offset + i] = source[i] ^ mask[i & 3];\n }\n}\n\n/**\n * Unmasks a buffer using the given mask.\n *\n * @param {Buffer} buffer The buffer to unmask\n * @param {Buffer} mask The mask to use\n * @public\n */\nfunction _unmask(buffer, mask) {\n for (let i = 0; i < buffer.length; i++) {\n buffer[i] ^= mask[i & 3];\n }\n}\n\n/**\n * Converts a buffer to an `ArrayBuffer`.\n *\n * @param {Buffer} buf The buffer to convert\n * @return {ArrayBuffer} Converted buffer\n * @public\n */\nfunction toArrayBuffer(buf) {\n if (buf.length === buf.buffer.byteLength) {\n return buf.buffer;\n }\n\n return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);\n}\n\n/**\n * Converts `data` to a `Buffer`.\n *\n * @param {*} data The data to convert\n * @return {Buffer} The buffer\n * @throws {TypeError}\n * @public\n */\nfunction toBuffer(data) {\n toBuffer.readOnly = true;\n\n if (Buffer.isBuffer(data)) return data;\n\n let buf;\n\n if (data instanceof ArrayBuffer) {\n buf = new FastBuffer(data);\n } else if (ArrayBuffer.isView(data)) {\n buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);\n } else {\n buf = Buffer.from(data);\n toBuffer.readOnly = false;\n }\n\n return buf;\n}\n\nmodule.exports = {\n concat,\n mask: _mask,\n toArrayBuffer,\n toBuffer,\n unmask: _unmask\n};\n\n/* istanbul ignore else */\nif (!process.env.WS_NO_BUFFER_UTIL) {\n try {\n const bufferUtil = require('bufferutil');\n\n module.exports.mask = function (source, mask, output, offset, length) {\n if (length < 48) _mask(source, mask, output, offset, length);\n else bufferUtil.mask(source, mask, output, offset, length);\n };\n\n module.exports.unmask = function (buffer, mask) {\n if (buffer.length < 32) _unmask(buffer, mask);\n else bufferUtil.unmask(buffer, mask);\n };\n } catch (e) {\n // Continue regardless of the error.\n }\n}\n","'use strict';\n\nconst kDone = Symbol('kDone');\nconst kRun = Symbol('kRun');\n\n/**\n * A very simple job queue with adjustable concurrency. Adapted from\n * https://github.com/STRML/async-limiter\n */\nclass Limiter {\n /**\n * Creates a new `Limiter`.\n *\n * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed\n * to run concurrently\n */\n constructor(concurrency) {\n this[kDone] = () => {\n this.pending--;\n this[kRun]();\n };\n this.concurrency = concurrency || Infinity;\n this.jobs = [];\n this.pending = 0;\n }\n\n /**\n * Adds a job to the queue.\n *\n * @param {Function} job The job to run\n * @public\n */\n add(job) {\n this.jobs.push(job);\n this[kRun]();\n }\n\n /**\n * Removes a job from the queue and runs it if possible.\n *\n * @private\n */\n [kRun]() {\n if (this.pending === this.concurrency) return;\n\n if (this.jobs.length) {\n const job = this.jobs.shift();\n\n this.pending++;\n job(this[kDone]);\n }\n }\n}\n\nmodule.exports = Limiter;\n","'use strict';\n\nconst zlib = require('zlib');\n\nconst bufferUtil = require('./buffer-util');\nconst Limiter = require('./limiter');\nconst { kStatusCode } = require('./constants');\n\nconst FastBuffer = Buffer[Symbol.species];\nconst TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]);\nconst kPerMessageDeflate = Symbol('permessage-deflate');\nconst kTotalLength = Symbol('total-length');\nconst kCallback = Symbol('callback');\nconst kBuffers = Symbol('buffers');\nconst kError = Symbol('error');\n\n//\n// We limit zlib concurrency, which prevents severe memory fragmentation\n// as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913\n// and https://github.com/websockets/ws/issues/1202\n//\n// Intentionally global; it's the global thread pool that's an issue.\n//\nlet zlibLimiter;\n\n/**\n * permessage-deflate implementation.\n */\nclass PerMessageDeflate {\n /**\n * Creates a PerMessageDeflate instance.\n *\n * @param {Object} [options] Configuration options\n * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support\n * for, or request, a custom client window size\n * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/\n * acknowledge disabling of client context takeover\n * @param {Number} [options.concurrencyLimit=10] The number of concurrent\n * calls to zlib\n * @param {Boolean} [options.isServer=false] Create the instance in either\n * server or client mode\n * @param {Number} [options.maxPayload=0] The maximum allowed message length\n * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the\n * use of a custom server window size\n * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept\n * disabling of server context takeover\n * @param {Number} [options.threshold=1024] Size (in bytes) below which\n * messages should not be compressed if context takeover is disabled\n * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on\n * deflate\n * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on\n * inflate\n */\n constructor(options) {\n this._options = options || {};\n this._threshold =\n this._options.threshold !== undefined ? this._options.threshold : 1024;\n this._maxPayload = this._options.maxPayload | 0;\n this._isServer = !!this._options.isServer;\n this._deflate = null;\n this._inflate = null;\n\n this.params = null;\n\n if (!zlibLimiter) {\n const concurrency =\n this._options.concurrencyLimit !== undefined\n ? this._options.concurrencyLimit\n : 10;\n zlibLimiter = new Limiter(concurrency);\n }\n }\n\n /**\n * @type {String}\n */\n static get extensionName() {\n return 'permessage-deflate';\n }\n\n /**\n * Create an extension negotiation offer.\n *\n * @return {Object} Extension parameters\n * @public\n */\n offer() {\n const params = {};\n\n if (this._options.serverNoContextTakeover) {\n params.server_no_context_takeover = true;\n }\n if (this._options.clientNoContextTakeover) {\n params.client_no_context_takeover = true;\n }\n if (this._options.serverMaxWindowBits) {\n params.server_max_window_bits = this._options.serverMaxWindowBits;\n }\n if (this._options.clientMaxWindowBits) {\n params.client_max_window_bits = this._options.clientMaxWindowBits;\n } else if (this._options.clientMaxWindowBits == null) {\n params.client_max_window_bits = true;\n }\n\n return params;\n }\n\n /**\n * Accept an extension negotiation offer/response.\n *\n * @param {Array} configurations The extension negotiation offers/reponse\n * @return {Object} Accepted configuration\n * @public\n */\n accept(configurations) {\n configurations = this.normalizeParams(configurations);\n\n this.params = this._isServer\n ? this.acceptAsServer(configurations)\n : this.acceptAsClient(configurations);\n\n return this.params;\n }\n\n /**\n * Releases all resources used by the extension.\n *\n * @public\n */\n cleanup() {\n if (this._inflate) {\n this._inflate.close();\n this._inflate = null;\n }\n\n if (this._deflate) {\n const callback = this._deflate[kCallback];\n\n this._deflate.close();\n this._deflate = null;\n\n if (callback) {\n callback(\n new Error(\n 'The deflate stream was closed while data was being processed'\n )\n );\n }\n }\n }\n\n /**\n * Accept an extension negotiation offer.\n *\n * @param {Array} offers The extension negotiation offers\n * @return {Object} Accepted configuration\n * @private\n */\n acceptAsServer(offers) {\n const opts = this._options;\n const accepted = offers.find((params) => {\n if (\n (opts.serverNoContextTakeover === false &&\n params.server_no_context_takeover) ||\n (params.server_max_window_bits &&\n (opts.serverMaxWindowBits === false ||\n (typeof opts.serverMaxWindowBits === 'number' &&\n opts.serverMaxWindowBits > params.server_max_window_bits))) ||\n (typeof opts.clientMaxWindowBits === 'number' &&\n !params.client_max_window_bits)\n ) {\n return false;\n }\n\n return true;\n });\n\n if (!accepted) {\n throw new Error('None of the extension offers can be accepted');\n }\n\n if (opts.serverNoContextTakeover) {\n accepted.server_no_context_takeover = true;\n }\n if (opts.clientNoContextTakeover) {\n accepted.client_no_context_takeover = true;\n }\n if (typeof opts.serverMaxWindowBits === 'number') {\n accepted.server_max_window_bits = opts.serverMaxWindowBits;\n }\n if (typeof opts.clientMaxWindowBits === 'number') {\n accepted.client_max_window_bits = opts.clientMaxWindowBits;\n } else if (\n accepted.client_max_window_bits === true ||\n opts.clientMaxWindowBits === false\n ) {\n delete accepted.client_max_window_bits;\n }\n\n return accepted;\n }\n\n /**\n * Accept the extension negotiation response.\n *\n * @param {Array} response The extension negotiation response\n * @return {Object} Accepted configuration\n * @private\n */\n acceptAsClient(response) {\n const params = response[0];\n\n if (\n this._options.clientNoContextTakeover === false &&\n params.client_no_context_takeover\n ) {\n throw new Error('Unexpected parameter \"client_no_context_takeover\"');\n }\n\n if (!params.client_max_window_bits) {\n if (typeof this._options.clientMaxWindowBits === 'number') {\n params.client_max_window_bits = this._options.clientMaxWindowBits;\n }\n } else if (\n this._options.clientMaxWindowBits === false ||\n (typeof this._options.clientMaxWindowBits === 'number' &&\n params.client_max_window_bits > this._options.clientMaxWindowBits)\n ) {\n throw new Error(\n 'Unexpected or invalid parameter \"client_max_window_bits\"'\n );\n }\n\n return params;\n }\n\n /**\n * Normalize parameters.\n *\n * @param {Array} configurations The extension negotiation offers/reponse\n * @return {Array} The offers/response with normalized parameters\n * @private\n */\n normalizeParams(configurations) {\n configurations.forEach((params) => {\n Object.keys(params).forEach((key) => {\n let value = params[key];\n\n if (value.length > 1) {\n throw new Error(`Parameter \"${key}\" must have only a single value`);\n }\n\n value = value[0];\n\n if (key === 'client_max_window_bits') {\n if (value !== true) {\n const num = +value;\n if (!Number.isInteger(num) || num < 8 || num > 15) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n value = num;\n } else if (!this._isServer) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n } else if (key === 'server_max_window_bits') {\n const num = +value;\n if (!Number.isInteger(num) || num < 8 || num > 15) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n value = num;\n } else if (\n key === 'client_no_context_takeover' ||\n key === 'server_no_context_takeover'\n ) {\n if (value !== true) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n } else {\n throw new Error(`Unknown parameter \"${key}\"`);\n }\n\n params[key] = value;\n });\n });\n\n return configurations;\n }\n\n /**\n * Decompress data. Concurrency limited.\n *\n * @param {Buffer} data Compressed data\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @public\n */\n decompress(data, fin, callback) {\n zlibLimiter.add((done) => {\n this._decompress(data, fin, (err, result) => {\n done();\n callback(err, result);\n });\n });\n }\n\n /**\n * Compress data. Concurrency limited.\n *\n * @param {(Buffer|String)} data Data to compress\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @public\n */\n compress(data, fin, callback) {\n zlibLimiter.add((done) => {\n this._compress(data, fin, (err, result) => {\n done();\n callback(err, result);\n });\n });\n }\n\n /**\n * Decompress data.\n *\n * @param {Buffer} data Compressed data\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @private\n */\n _decompress(data, fin, callback) {\n const endpoint = this._isServer ? 'client' : 'server';\n\n if (!this._inflate) {\n const key = `${endpoint}_max_window_bits`;\n const windowBits =\n typeof this.params[key] !== 'number'\n ? zlib.Z_DEFAULT_WINDOWBITS\n : this.params[key];\n\n this._inflate = zlib.createInflateRaw({\n ...this._options.zlibInflateOptions,\n windowBits\n });\n this._inflate[kPerMessageDeflate] = this;\n this._inflate[kTotalLength] = 0;\n this._inflate[kBuffers] = [];\n this._inflate.on('error', inflateOnError);\n this._inflate.on('data', inflateOnData);\n }\n\n this._inflate[kCallback] = callback;\n\n this._inflate.write(data);\n if (fin) this._inflate.write(TRAILER);\n\n this._inflate.flush(() => {\n const err = this._inflate[kError];\n\n if (err) {\n this._inflate.close();\n this._inflate = null;\n callback(err);\n return;\n }\n\n const data = bufferUtil.concat(\n this._inflate[kBuffers],\n this._inflate[kTotalLength]\n );\n\n if (this._inflate._readableState.endEmitted) {\n this._inflate.close();\n this._inflate = null;\n } else {\n this._inflate[kTotalLength] = 0;\n this._inflate[kBuffers] = [];\n\n if (fin && this.params[`${endpoint}_no_context_takeover`]) {\n this._inflate.reset();\n }\n }\n\n callback(null, data);\n });\n }\n\n /**\n * Compress data.\n *\n * @param {(Buffer|String)} data Data to compress\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @private\n */\n _compress(data, fin, callback) {\n const endpoint = this._isServer ? 'server' : 'client';\n\n if (!this._deflate) {\n const key = `${endpoint}_max_window_bits`;\n const windowBits =\n typeof this.params[key] !== 'number'\n ? zlib.Z_DEFAULT_WINDOWBITS\n : this.params[key];\n\n this._deflate = zlib.createDeflateRaw({\n ...this._options.zlibDeflateOptions,\n windowBits\n });\n\n this._deflate[kTotalLength] = 0;\n this._deflate[kBuffers] = [];\n\n this._deflate.on('data', deflateOnData);\n }\n\n this._deflate[kCallback] = callback;\n\n this._deflate.write(data);\n this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {\n if (!this._deflate) {\n //\n // The deflate stream was closed while data was being processed.\n //\n return;\n }\n\n let data = bufferUtil.concat(\n this._deflate[kBuffers],\n this._deflate[kTotalLength]\n );\n\n if (fin) {\n data = new FastBuffer(data.buffer, data.byteOffset, data.length - 4);\n }\n\n //\n // Ensure that the callback will not be called again in\n // `PerMessageDeflate#cleanup()`.\n //\n this._deflate[kCallback] = null;\n\n this._deflate[kTotalLength] = 0;\n this._deflate[kBuffers] = [];\n\n if (fin && this.params[`${endpoint}_no_context_takeover`]) {\n this._deflate.reset();\n }\n\n callback(null, data);\n });\n }\n}\n\nmodule.exports = PerMessageDeflate;\n\n/**\n * The listener of the `zlib.DeflateRaw` stream `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction deflateOnData(chunk) {\n this[kBuffers].push(chunk);\n this[kTotalLength] += chunk.length;\n}\n\n/**\n * The listener of the `zlib.InflateRaw` stream `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction inflateOnData(chunk) {\n this[kTotalLength] += chunk.length;\n\n if (\n this[kPerMessageDeflate]._maxPayload < 1 ||\n this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload\n ) {\n this[kBuffers].push(chunk);\n return;\n }\n\n this[kError] = new RangeError('Max payload size exceeded');\n this[kError].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH';\n this[kError][kStatusCode] = 1009;\n this.removeListener('data', inflateOnData);\n\n //\n // The choice to employ `zlib.reset()` over `zlib.close()` is dictated by the\n // fact that in Node.js versions prior to 13.10.0, the callback for\n // `zlib.flush()` is not called if `zlib.close()` is used. Utilizing\n // `zlib.reset()` ensures that either the callback is invoked or an error is\n // emitted.\n //\n this.reset();\n}\n\n/**\n * The listener of the `zlib.InflateRaw` stream `'error'` event.\n *\n * @param {Error} err The emitted error\n * @private\n */\nfunction inflateOnError(err) {\n //\n // There is no need to call `Zlib#close()` as the handle is automatically\n // closed when an error is emitted.\n //\n this[kPerMessageDeflate]._inflate = null;\n\n if (this[kError]) {\n this[kCallback](this[kError]);\n return;\n }\n\n err[kStatusCode] = 1007;\n this[kCallback](err);\n}\n","export default {};\nthrow new Error(`Could not resolve \"utf-8-validate\" imported by \"ws\". Is it installed?`)","'use strict';\n\nconst { isUtf8 } = require('buffer');\n\nconst { hasBlob } = require('./constants');\n\n//\n// Allowed token characters:\n//\n// '!', '#', '$', '%', '&', ''', '*', '+', '-',\n// '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~'\n//\n// tokenChars[32] === 0 // ' '\n// tokenChars[33] === 1 // '!'\n// tokenChars[34] === 0 // '\"'\n// ...\n//\n// prettier-ignore\nconst tokenChars = [\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31\n 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63\n 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127\n];\n\n/**\n * Checks if a status code is allowed in a close frame.\n *\n * @param {Number} code The status code\n * @return {Boolean} `true` if the status code is valid, else `false`\n * @public\n */\nfunction isValidStatusCode(code) {\n return (\n (code >= 1000 &&\n code <= 1014 &&\n code !== 1004 &&\n code !== 1005 &&\n code !== 1006) ||\n (code >= 3000 && code <= 4999)\n );\n}\n\n/**\n * Checks if a given buffer contains only correct UTF-8.\n * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by\n * Markus Kuhn.\n *\n * @param {Buffer} buf The buffer to check\n * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`\n * @public\n */\nfunction _isValidUTF8(buf) {\n const len = buf.length;\n let i = 0;\n\n while (i < len) {\n if ((buf[i] & 0x80) === 0) {\n // 0xxxxxxx\n i++;\n } else if ((buf[i] & 0xe0) === 0xc0) {\n // 110xxxxx 10xxxxxx\n if (\n i + 1 === len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i] & 0xfe) === 0xc0 // Overlong\n ) {\n return false;\n }\n\n i += 2;\n } else if ((buf[i] & 0xf0) === 0xe0) {\n // 1110xxxx 10xxxxxx 10xxxxxx\n if (\n i + 2 >= len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i + 2] & 0xc0) !== 0x80 ||\n (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong\n (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF)\n ) {\n return false;\n }\n\n i += 3;\n } else if ((buf[i] & 0xf8) === 0xf0) {\n // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\n if (\n i + 3 >= len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i + 2] & 0xc0) !== 0x80 ||\n (buf[i + 3] & 0xc0) !== 0x80 ||\n (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong\n (buf[i] === 0xf4 && buf[i + 1] > 0x8f) ||\n buf[i] > 0xf4 // > U+10FFFF\n ) {\n return false;\n }\n\n i += 4;\n } else {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Determines whether a value is a `Blob`.\n *\n * @param {*} value The value to be tested\n * @return {Boolean} `true` if `value` is a `Blob`, else `false`\n * @private\n */\nfunction isBlob(value) {\n return (\n hasBlob &&\n typeof value === 'object' &&\n typeof value.arrayBuffer === 'function' &&\n typeof value.type === 'string' &&\n typeof value.stream === 'function' &&\n (value[Symbol.toStringTag] === 'Blob' ||\n value[Symbol.toStringTag] === 'File')\n );\n}\n\nmodule.exports = {\n isBlob,\n isValidStatusCode,\n isValidUTF8: _isValidUTF8,\n tokenChars\n};\n\nif (isUtf8) {\n module.exports.isValidUTF8 = function (buf) {\n return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);\n };\n} /* istanbul ignore else */ else if (!process.env.WS_NO_UTF_8_VALIDATE) {\n try {\n const isValidUTF8 = require('utf-8-validate');\n\n module.exports.isValidUTF8 = function (buf) {\n return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);\n };\n } catch (e) {\n // Continue regardless of the error.\n }\n}\n","'use strict';\n\nconst { Writable } = require('stream');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst {\n BINARY_TYPES,\n EMPTY_BUFFER,\n kStatusCode,\n kWebSocket\n} = require('./constants');\nconst { concat, toArrayBuffer, unmask } = require('./buffer-util');\nconst { isValidStatusCode, isValidUTF8 } = require('./validation');\n\nconst FastBuffer = Buffer[Symbol.species];\n\nconst GET_INFO = 0;\nconst GET_PAYLOAD_LENGTH_16 = 1;\nconst GET_PAYLOAD_LENGTH_64 = 2;\nconst GET_MASK = 3;\nconst GET_DATA = 4;\nconst INFLATING = 5;\nconst DEFER_EVENT = 6;\n\n/**\n * HyBi Receiver implementation.\n *\n * @extends Writable\n */\nclass Receiver extends Writable {\n /**\n * Creates a Receiver instance.\n *\n * @param {Object} [options] Options object\n * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether\n * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n * multiple times in the same tick\n * @param {String} [options.binaryType=nodebuffer] The type for binary data\n * @param {Object} [options.extensions] An object containing the negotiated\n * extensions\n * @param {Boolean} [options.isServer=false] Specifies whether to operate in\n * client or server mode\n * @param {Number} [options.maxBufferedChunks=0] The maximum number of\n * buffered data chunks\n * @param {Number} [options.maxFragments=0] The maximum number of message\n * fragments\n * @param {Number} [options.maxPayload=0] The maximum allowed message length\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n */\n constructor(options = {}) {\n super();\n\n this._allowSynchronousEvents =\n options.allowSynchronousEvents !== undefined\n ? options.allowSynchronousEvents\n : true;\n this._binaryType = options.binaryType || BINARY_TYPES[0];\n this._extensions = options.extensions || {};\n this._isServer = !!options.isServer;\n this._maxBufferedChunks = options.maxBufferedChunks | 0;\n this._maxFragments = options.maxFragments | 0;\n this._maxPayload = options.maxPayload | 0;\n this._skipUTF8Validation = !!options.skipUTF8Validation;\n this[kWebSocket] = undefined;\n\n this._bufferedBytes = 0;\n this._buffers = [];\n\n this._compressed = false;\n this._payloadLength = 0;\n this._mask = undefined;\n this._fragmented = 0;\n this._masked = false;\n this._fin = false;\n this._opcode = 0;\n\n this._totalPayloadLength = 0;\n this._messageLength = 0;\n this._fragments = [];\n\n this._errored = false;\n this._loop = false;\n this._state = GET_INFO;\n }\n\n /**\n * Implements `Writable.prototype._write()`.\n *\n * @param {Buffer} chunk The chunk of data to write\n * @param {String} encoding The character encoding of `chunk`\n * @param {Function} cb Callback\n * @private\n */\n _write(chunk, encoding, cb) {\n if (this._opcode === 0x08 && this._state == GET_INFO) return cb();\n\n if (\n this._maxBufferedChunks > 0 &&\n this._buffers.length >= this._maxBufferedChunks\n ) {\n cb(\n this.createError(\n RangeError,\n 'Too many buffered chunks',\n false,\n 1008,\n 'WS_ERR_TOO_MANY_BUFFERED_PARTS'\n )\n );\n return;\n }\n\n this._bufferedBytes += chunk.length;\n this._buffers.push(chunk);\n this.startLoop(cb);\n }\n\n /**\n * Consumes `n` bytes from the buffered data.\n *\n * @param {Number} n The number of bytes to consume\n * @return {Buffer} The consumed bytes\n * @private\n */\n consume(n) {\n this._bufferedBytes -= n;\n\n if (n === this._buffers[0].length) return this._buffers.shift();\n\n if (n < this._buffers[0].length) {\n const buf = this._buffers[0];\n this._buffers[0] = new FastBuffer(\n buf.buffer,\n buf.byteOffset + n,\n buf.length - n\n );\n\n return new FastBuffer(buf.buffer, buf.byteOffset, n);\n }\n\n const dst = Buffer.allocUnsafe(n);\n\n do {\n const buf = this._buffers[0];\n const offset = dst.length - n;\n\n if (n >= buf.length) {\n dst.set(this._buffers.shift(), offset);\n } else {\n dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);\n this._buffers[0] = new FastBuffer(\n buf.buffer,\n buf.byteOffset + n,\n buf.length - n\n );\n }\n\n n -= buf.length;\n } while (n > 0);\n\n return dst;\n }\n\n /**\n * Starts the parsing loop.\n *\n * @param {Function} cb Callback\n * @private\n */\n startLoop(cb) {\n this._loop = true;\n\n do {\n switch (this._state) {\n case GET_INFO:\n this.getInfo(cb);\n break;\n case GET_PAYLOAD_LENGTH_16:\n this.getPayloadLength16(cb);\n break;\n case GET_PAYLOAD_LENGTH_64:\n this.getPayloadLength64(cb);\n break;\n case GET_MASK:\n this.getMask();\n break;\n case GET_DATA:\n this.getData(cb);\n break;\n case INFLATING:\n case DEFER_EVENT:\n this._loop = false;\n return;\n }\n } while (this._loop);\n\n if (!this._errored) cb();\n }\n\n /**\n * Reads the first two bytes of a frame.\n *\n * @param {Function} cb Callback\n * @private\n */\n getInfo(cb) {\n if (this._bufferedBytes < 2) {\n this._loop = false;\n return;\n }\n\n const buf = this.consume(2);\n\n if ((buf[0] & 0x30) !== 0x00) {\n const error = this.createError(\n RangeError,\n 'RSV2 and RSV3 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_2_3'\n );\n\n cb(error);\n return;\n }\n\n const compressed = (buf[0] & 0x40) === 0x40;\n\n if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {\n const error = this.createError(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n\n cb(error);\n return;\n }\n\n this._fin = (buf[0] & 0x80) === 0x80;\n this._opcode = buf[0] & 0x0f;\n this._payloadLength = buf[1] & 0x7f;\n\n if (this._opcode === 0x00) {\n if (compressed) {\n const error = this.createError(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n\n cb(error);\n return;\n }\n\n if (!this._fragmented) {\n const error = this.createError(\n RangeError,\n 'invalid opcode 0',\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n\n cb(error);\n return;\n }\n\n this._opcode = this._fragmented;\n } else if (this._opcode === 0x01 || this._opcode === 0x02) {\n if (this._fragmented) {\n const error = this.createError(\n RangeError,\n `invalid opcode ${this._opcode}`,\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n\n cb(error);\n return;\n }\n\n this._compressed = compressed;\n } else if (this._opcode > 0x07 && this._opcode < 0x0b) {\n if (!this._fin) {\n const error = this.createError(\n RangeError,\n 'FIN must be set',\n true,\n 1002,\n 'WS_ERR_EXPECTED_FIN'\n );\n\n cb(error);\n return;\n }\n\n if (compressed) {\n const error = this.createError(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n\n cb(error);\n return;\n }\n\n if (\n this._payloadLength > 0x7d ||\n (this._opcode === 0x08 && this._payloadLength === 1)\n ) {\n const error = this.createError(\n RangeError,\n `invalid payload length ${this._payloadLength}`,\n true,\n 1002,\n 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH'\n );\n\n cb(error);\n return;\n }\n } else {\n const error = this.createError(\n RangeError,\n `invalid opcode ${this._opcode}`,\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n\n cb(error);\n return;\n }\n\n if (!this._fin && !this._fragmented) this._fragmented = this._opcode;\n this._masked = (buf[1] & 0x80) === 0x80;\n\n if (this._isServer) {\n if (!this._masked) {\n const error = this.createError(\n RangeError,\n 'MASK must be set',\n true,\n 1002,\n 'WS_ERR_EXPECTED_MASK'\n );\n\n cb(error);\n return;\n }\n } else if (this._masked) {\n const error = this.createError(\n RangeError,\n 'MASK must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_MASK'\n );\n\n cb(error);\n return;\n }\n\n if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;\n else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;\n else this.haveLength(cb);\n }\n\n /**\n * Gets extended payload length (7+16).\n *\n * @param {Function} cb Callback\n * @private\n */\n getPayloadLength16(cb) {\n if (this._bufferedBytes < 2) {\n this._loop = false;\n return;\n }\n\n this._payloadLength = this.consume(2).readUInt16BE(0);\n this.haveLength(cb);\n }\n\n /**\n * Gets extended payload length (7+64).\n *\n * @param {Function} cb Callback\n * @private\n */\n getPayloadLength64(cb) {\n if (this._bufferedBytes < 8) {\n this._loop = false;\n return;\n }\n\n const buf = this.consume(8);\n const num = buf.readUInt32BE(0);\n\n //\n // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned\n // if payload length is greater than this number.\n //\n if (num > Math.pow(2, 53 - 32) - 1) {\n const error = this.createError(\n RangeError,\n 'Unsupported WebSocket frame: payload length > 2^53 - 1',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH'\n );\n\n cb(error);\n return;\n }\n\n this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);\n this.haveLength(cb);\n }\n\n /**\n * Payload length has been read.\n *\n * @param {Function} cb Callback\n * @private\n */\n haveLength(cb) {\n if (this._payloadLength && this._opcode < 0x08) {\n this._totalPayloadLength += this._payloadLength;\n if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {\n const error = this.createError(\n RangeError,\n 'Max payload size exceeded',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'\n );\n\n cb(error);\n return;\n }\n }\n\n if (this._masked) this._state = GET_MASK;\n else this._state = GET_DATA;\n }\n\n /**\n * Reads mask bytes.\n *\n * @private\n */\n getMask() {\n if (this._bufferedBytes < 4) {\n this._loop = false;\n return;\n }\n\n this._mask = this.consume(4);\n this._state = GET_DATA;\n }\n\n /**\n * Reads data bytes.\n *\n * @param {Function} cb Callback\n * @private\n */\n getData(cb) {\n let data = EMPTY_BUFFER;\n\n if (this._payloadLength) {\n if (this._bufferedBytes < this._payloadLength) {\n this._loop = false;\n return;\n }\n\n data = this.consume(this._payloadLength);\n\n if (\n this._masked &&\n (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0\n ) {\n unmask(data, this._mask);\n }\n }\n\n if (this._opcode > 0x07) {\n this.controlMessage(data, cb);\n return;\n }\n\n if (this._compressed) {\n this._state = INFLATING;\n this.decompress(data, cb);\n return;\n }\n\n if (data.length) {\n if (\n this._maxFragments > 0 &&\n this._fragments.length >= this._maxFragments\n ) {\n const error = this.createError(\n RangeError,\n 'Too many message fragments',\n false,\n 1008,\n 'WS_ERR_TOO_MANY_BUFFERED_PARTS'\n );\n\n cb(error);\n return;\n }\n\n //\n // This message is not compressed so its length is the sum of the payload\n // length of all fragments.\n //\n this._messageLength = this._totalPayloadLength;\n this._fragments.push(data);\n }\n\n this.dataMessage(cb);\n }\n\n /**\n * Decompresses data.\n *\n * @param {Buffer} data Compressed data\n * @param {Function} cb Callback\n * @private\n */\n decompress(data, cb) {\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n\n perMessageDeflate.decompress(data, this._fin, (err, buf) => {\n if (err) return cb(err);\n\n if (buf.length) {\n this._messageLength += buf.length;\n if (this._messageLength > this._maxPayload && this._maxPayload > 0) {\n const error = this.createError(\n RangeError,\n 'Max payload size exceeded',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'\n );\n\n cb(error);\n return;\n }\n\n if (\n this._maxFragments > 0 &&\n this._fragments.length >= this._maxFragments\n ) {\n const error = this.createError(\n RangeError,\n 'Too many message fragments',\n false,\n 1008,\n 'WS_ERR_TOO_MANY_BUFFERED_PARTS'\n );\n\n cb(error);\n return;\n }\n\n this._fragments.push(buf);\n }\n\n this.dataMessage(cb);\n if (this._state === GET_INFO) this.startLoop(cb);\n });\n }\n\n /**\n * Handles a data message.\n *\n * @param {Function} cb Callback\n * @private\n */\n dataMessage(cb) {\n if (!this._fin) {\n this._state = GET_INFO;\n return;\n }\n\n const messageLength = this._messageLength;\n const fragments = this._fragments;\n\n this._totalPayloadLength = 0;\n this._messageLength = 0;\n this._fragmented = 0;\n this._fragments = [];\n\n if (this._opcode === 2) {\n let data;\n\n if (this._binaryType === 'nodebuffer') {\n data = concat(fragments, messageLength);\n } else if (this._binaryType === 'arraybuffer') {\n data = toArrayBuffer(concat(fragments, messageLength));\n } else if (this._binaryType === 'blob') {\n data = new Blob(fragments);\n } else {\n data = fragments;\n }\n\n if (this._allowSynchronousEvents) {\n this.emit('message', data, true);\n this._state = GET_INFO;\n } else {\n this._state = DEFER_EVENT;\n setImmediate(() => {\n this.emit('message', data, true);\n this._state = GET_INFO;\n this.startLoop(cb);\n });\n }\n } else {\n const buf = concat(fragments, messageLength);\n\n if (!this._skipUTF8Validation && !isValidUTF8(buf)) {\n const error = this.createError(\n Error,\n 'invalid UTF-8 sequence',\n true,\n 1007,\n 'WS_ERR_INVALID_UTF8'\n );\n\n cb(error);\n return;\n }\n\n if (this._state === INFLATING || this._allowSynchronousEvents) {\n this.emit('message', buf, false);\n this._state = GET_INFO;\n } else {\n this._state = DEFER_EVENT;\n setImmediate(() => {\n this.emit('message', buf, false);\n this._state = GET_INFO;\n this.startLoop(cb);\n });\n }\n }\n }\n\n /**\n * Handles a control message.\n *\n * @param {Buffer} data Data to handle\n * @return {(Error|RangeError|undefined)} A possible error\n * @private\n */\n controlMessage(data, cb) {\n if (this._opcode === 0x08) {\n if (data.length === 0) {\n this._loop = false;\n this.emit('conclude', 1005, EMPTY_BUFFER);\n this.end();\n } else {\n const code = data.readUInt16BE(0);\n\n if (!isValidStatusCode(code)) {\n const error = this.createError(\n RangeError,\n `invalid status code ${code}`,\n true,\n 1002,\n 'WS_ERR_INVALID_CLOSE_CODE'\n );\n\n cb(error);\n return;\n }\n\n const buf = new FastBuffer(\n data.buffer,\n data.byteOffset + 2,\n data.length - 2\n );\n\n if (!this._skipUTF8Validation && !isValidUTF8(buf)) {\n const error = this.createError(\n Error,\n 'invalid UTF-8 sequence',\n true,\n 1007,\n 'WS_ERR_INVALID_UTF8'\n );\n\n cb(error);\n return;\n }\n\n this._loop = false;\n this.emit('conclude', code, buf);\n this.end();\n }\n\n this._state = GET_INFO;\n return;\n }\n\n if (this._allowSynchronousEvents) {\n this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);\n this._state = GET_INFO;\n } else {\n this._state = DEFER_EVENT;\n setImmediate(() => {\n this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);\n this._state = GET_INFO;\n this.startLoop(cb);\n });\n }\n }\n\n /**\n * Builds an error object.\n *\n * @param {function(new:Error|RangeError)} ErrorCtor The error constructor\n * @param {String} message The error message\n * @param {Boolean} prefix Specifies whether or not to add a default prefix to\n * `message`\n * @param {Number} statusCode The status code\n * @param {String} errorCode The exposed error code\n * @return {(Error|RangeError)} The error\n * @private\n */\n createError(ErrorCtor, message, prefix, statusCode, errorCode) {\n this._loop = false;\n this._errored = true;\n\n const err = new ErrorCtor(\n prefix ? `Invalid WebSocket frame: ${message}` : message\n );\n\n Error.captureStackTrace(err, this.createError);\n err.code = errorCode;\n err[kStatusCode] = statusCode;\n return err;\n }\n}\n\nmodule.exports = Receiver;\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex\" }] */\n\n'use strict';\n\nconst { Duplex } = require('stream');\nconst { randomFillSync } = require('crypto');\nconst {\n types: { isUint8Array }\n} = require('util');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst { EMPTY_BUFFER, kWebSocket, NOOP } = require('./constants');\nconst { isBlob, isValidStatusCode } = require('./validation');\nconst { mask: applyMask, toBuffer } = require('./buffer-util');\n\nconst kByteLength = Symbol('kByteLength');\nconst maskBuffer = Buffer.alloc(4);\nconst RANDOM_POOL_SIZE = 8 * 1024;\nlet randomPool;\nlet randomPoolPointer = RANDOM_POOL_SIZE;\n\nconst DEFAULT = 0;\nconst DEFLATING = 1;\nconst GET_BLOB_DATA = 2;\n\n/**\n * HyBi Sender implementation.\n */\nclass Sender {\n /**\n * Creates a Sender instance.\n *\n * @param {Duplex} socket The connection socket\n * @param {Object} [extensions] An object containing the negotiated extensions\n * @param {Function} [generateMask] The function used to generate the masking\n * key\n */\n constructor(socket, extensions, generateMask) {\n this._extensions = extensions || {};\n\n if (generateMask) {\n this._generateMask = generateMask;\n this._maskBuffer = Buffer.alloc(4);\n }\n\n this._socket = socket;\n\n this._firstFragment = true;\n this._compress = false;\n\n this._bufferedBytes = 0;\n this._queue = [];\n this._state = DEFAULT;\n this.onerror = NOOP;\n this[kWebSocket] = undefined;\n }\n\n /**\n * Frames a piece of data according to the HyBi WebSocket protocol.\n *\n * @param {(Buffer|String)} data The data to frame\n * @param {Object} options Options object\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n * key\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @return {(Buffer|String)[]} The framed data\n * @public\n */\n static frame(data, options) {\n let mask;\n let merge = false;\n let offset = 2;\n let skipMasking = false;\n\n if (options.mask) {\n mask = options.maskBuffer || maskBuffer;\n\n if (options.generateMask) {\n options.generateMask(mask);\n } else {\n if (randomPoolPointer === RANDOM_POOL_SIZE) {\n /* istanbul ignore else */\n if (randomPool === undefined) {\n //\n // This is lazily initialized because server-sent frames must not\n // be masked so it may never be used.\n //\n randomPool = Buffer.alloc(RANDOM_POOL_SIZE);\n }\n\n randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);\n randomPoolPointer = 0;\n }\n\n mask[0] = randomPool[randomPoolPointer++];\n mask[1] = randomPool[randomPoolPointer++];\n mask[2] = randomPool[randomPoolPointer++];\n mask[3] = randomPool[randomPoolPointer++];\n }\n\n skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;\n offset = 6;\n }\n\n let dataLength;\n\n if (typeof data === 'string') {\n if (\n (!options.mask || skipMasking) &&\n options[kByteLength] !== undefined\n ) {\n dataLength = options[kByteLength];\n } else {\n data = Buffer.from(data);\n dataLength = data.length;\n }\n } else {\n dataLength = data.length;\n merge = options.mask && options.readOnly && !skipMasking;\n }\n\n let payloadLength = dataLength;\n\n if (dataLength >= 65536) {\n offset += 8;\n payloadLength = 127;\n } else if (dataLength > 125) {\n offset += 2;\n payloadLength = 126;\n }\n\n const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);\n\n target[0] = options.fin ? options.opcode | 0x80 : options.opcode;\n if (options.rsv1) target[0] |= 0x40;\n\n target[1] = payloadLength;\n\n if (payloadLength === 126) {\n target.writeUInt16BE(dataLength, 2);\n } else if (payloadLength === 127) {\n target[2] = target[3] = 0;\n target.writeUIntBE(dataLength, 4, 6);\n }\n\n if (!options.mask) return [target, data];\n\n target[1] |= 0x80;\n target[offset - 4] = mask[0];\n target[offset - 3] = mask[1];\n target[offset - 2] = mask[2];\n target[offset - 1] = mask[3];\n\n if (skipMasking) return [target, data];\n\n if (merge) {\n applyMask(data, mask, target, offset, dataLength);\n return [target];\n }\n\n applyMask(data, mask, data, 0, dataLength);\n return [target, data];\n }\n\n /**\n * Sends a close message to the other peer.\n *\n * @param {Number} [code] The status code component of the body\n * @param {(String|Buffer)} [data] The message component of the body\n * @param {Boolean} [mask=false] Specifies whether or not to mask the message\n * @param {Function} [cb] Callback\n * @public\n */\n close(code, data, mask, cb) {\n let buf;\n\n if (code === undefined) {\n buf = EMPTY_BUFFER;\n } else if (typeof code !== 'number' || !isValidStatusCode(code)) {\n throw new TypeError('First argument must be a valid error code number');\n } else if (data === undefined || !data.length) {\n buf = Buffer.allocUnsafe(2);\n buf.writeUInt16BE(code, 0);\n } else {\n const length = Buffer.byteLength(data);\n\n if (length > 123) {\n throw new RangeError('The message must not be greater than 123 bytes');\n }\n\n buf = Buffer.allocUnsafe(2 + length);\n buf.writeUInt16BE(code, 0);\n\n if (typeof data === 'string') {\n buf.write(data, 2);\n } else if (isUint8Array(data)) {\n buf.set(data, 2);\n } else {\n throw new TypeError('Second argument must be a string or a Uint8Array');\n }\n }\n\n const options = {\n [kByteLength]: buf.length,\n fin: true,\n generateMask: this._generateMask,\n mask,\n maskBuffer: this._maskBuffer,\n opcode: 0x08,\n readOnly: false,\n rsv1: false\n };\n\n if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, buf, false, options, cb]);\n } else {\n this.sendFrame(Sender.frame(buf, options), cb);\n }\n }\n\n /**\n * Sends a ping message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Boolean} [mask=false] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback\n * @public\n */\n ping(data, mask, cb) {\n let byteLength;\n let readOnly;\n\n if (typeof data === 'string') {\n byteLength = Buffer.byteLength(data);\n readOnly = false;\n } else if (isBlob(data)) {\n byteLength = data.size;\n readOnly = false;\n } else {\n data = toBuffer(data);\n byteLength = data.length;\n readOnly = toBuffer.readOnly;\n }\n\n if (byteLength > 125) {\n throw new RangeError('The data size must not be greater than 125 bytes');\n }\n\n const options = {\n [kByteLength]: byteLength,\n fin: true,\n generateMask: this._generateMask,\n mask,\n maskBuffer: this._maskBuffer,\n opcode: 0x09,\n readOnly,\n rsv1: false\n };\n\n if (isBlob(data)) {\n if (this._state !== DEFAULT) {\n this.enqueue([this.getBlobData, data, false, options, cb]);\n } else {\n this.getBlobData(data, false, options, cb);\n }\n } else if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, data, false, options, cb]);\n } else {\n this.sendFrame(Sender.frame(data, options), cb);\n }\n }\n\n /**\n * Sends a pong message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Boolean} [mask=false] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback\n * @public\n */\n pong(data, mask, cb) {\n let byteLength;\n let readOnly;\n\n if (typeof data === 'string') {\n byteLength = Buffer.byteLength(data);\n readOnly = false;\n } else if (isBlob(data)) {\n byteLength = data.size;\n readOnly = false;\n } else {\n data = toBuffer(data);\n byteLength = data.length;\n readOnly = toBuffer.readOnly;\n }\n\n if (byteLength > 125) {\n throw new RangeError('The data size must not be greater than 125 bytes');\n }\n\n const options = {\n [kByteLength]: byteLength,\n fin: true,\n generateMask: this._generateMask,\n mask,\n maskBuffer: this._maskBuffer,\n opcode: 0x0a,\n readOnly,\n rsv1: false\n };\n\n if (isBlob(data)) {\n if (this._state !== DEFAULT) {\n this.enqueue([this.getBlobData, data, false, options, cb]);\n } else {\n this.getBlobData(data, false, options, cb);\n }\n } else if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, data, false, options, cb]);\n } else {\n this.sendFrame(Sender.frame(data, options), cb);\n }\n }\n\n /**\n * Sends a data message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Object} options Options object\n * @param {Boolean} [options.binary=false] Specifies whether `data` is binary\n * or text\n * @param {Boolean} [options.compress=false] Specifies whether or not to\n * compress `data`\n * @param {Boolean} [options.fin=false] Specifies whether the fragment is the\n * last one\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Function} [cb] Callback\n * @public\n */\n send(data, options, cb) {\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n let opcode = options.binary ? 2 : 1;\n let rsv1 = options.compress;\n\n let byteLength;\n let readOnly;\n\n if (typeof data === 'string') {\n byteLength = Buffer.byteLength(data);\n readOnly = false;\n } else if (isBlob(data)) {\n byteLength = data.size;\n readOnly = false;\n } else {\n data = toBuffer(data);\n byteLength = data.length;\n readOnly = toBuffer.readOnly;\n }\n\n if (this._firstFragment) {\n this._firstFragment = false;\n if (\n rsv1 &&\n perMessageDeflate &&\n perMessageDeflate.params[\n perMessageDeflate._isServer\n ? 'server_no_context_takeover'\n : 'client_no_context_takeover'\n ]\n ) {\n rsv1 = byteLength >= perMessageDeflate._threshold;\n }\n this._compress = rsv1;\n } else {\n rsv1 = false;\n opcode = 0;\n }\n\n if (options.fin) this._firstFragment = true;\n\n const opts = {\n [kByteLength]: byteLength,\n fin: options.fin,\n generateMask: this._generateMask,\n mask: options.mask,\n maskBuffer: this._maskBuffer,\n opcode,\n readOnly,\n rsv1\n };\n\n if (isBlob(data)) {\n if (this._state !== DEFAULT) {\n this.enqueue([this.getBlobData, data, this._compress, opts, cb]);\n } else {\n this.getBlobData(data, this._compress, opts, cb);\n }\n } else if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, data, this._compress, opts, cb]);\n } else {\n this.dispatch(data, this._compress, opts, cb);\n }\n }\n\n /**\n * Gets the contents of a blob as binary data.\n *\n * @param {Blob} blob The blob\n * @param {Boolean} [compress=false] Specifies whether or not to compress\n * the data\n * @param {Object} options Options object\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n * key\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @param {Function} [cb] Callback\n * @private\n */\n getBlobData(blob, compress, options, cb) {\n this._bufferedBytes += options[kByteLength];\n this._state = GET_BLOB_DATA;\n\n blob\n .arrayBuffer()\n .then((arrayBuffer) => {\n if (this._socket.destroyed) {\n const err = new Error(\n 'The socket was closed while the blob was being read'\n );\n\n //\n // `callCallbacks` is called in the next tick to ensure that errors\n // that might be thrown in the callbacks behave like errors thrown\n // outside the promise chain.\n //\n process.nextTick(callCallbacks, this, err, cb);\n return;\n }\n\n this._bufferedBytes -= options[kByteLength];\n const data = toBuffer(arrayBuffer);\n\n if (!compress) {\n this._state = DEFAULT;\n this.sendFrame(Sender.frame(data, options), cb);\n this.dequeue();\n } else {\n this.dispatch(data, compress, options, cb);\n }\n })\n .catch((err) => {\n //\n // `onError` is called in the next tick for the same reason that\n // `callCallbacks` above is.\n //\n process.nextTick(onError, this, err, cb);\n });\n }\n\n /**\n * Dispatches a message.\n *\n * @param {(Buffer|String)} data The message to send\n * @param {Boolean} [compress=false] Specifies whether or not to compress\n * `data`\n * @param {Object} options Options object\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n * key\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @param {Function} [cb] Callback\n * @private\n */\n dispatch(data, compress, options, cb) {\n if (!compress) {\n this.sendFrame(Sender.frame(data, options), cb);\n return;\n }\n\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n\n this._bufferedBytes += options[kByteLength];\n this._state = DEFLATING;\n perMessageDeflate.compress(data, options.fin, (_, buf) => {\n if (this._socket.destroyed) {\n const err = new Error(\n 'The socket was closed while data was being compressed'\n );\n\n callCallbacks(this, err, cb);\n return;\n }\n\n this._bufferedBytes -= options[kByteLength];\n this._state = DEFAULT;\n options.readOnly = false;\n this.sendFrame(Sender.frame(buf, options), cb);\n this.dequeue();\n });\n }\n\n /**\n * Executes queued send operations.\n *\n * @private\n */\n dequeue() {\n while (this._state === DEFAULT && this._queue.length) {\n const params = this._queue.shift();\n\n this._bufferedBytes -= params[3][kByteLength];\n Reflect.apply(params[0], this, params.slice(1));\n }\n }\n\n /**\n * Enqueues a send operation.\n *\n * @param {Array} params Send operation parameters.\n * @private\n */\n enqueue(params) {\n this._bufferedBytes += params[3][kByteLength];\n this._queue.push(params);\n }\n\n /**\n * Sends a frame.\n *\n * @param {(Buffer | String)[]} list The frame to send\n * @param {Function} [cb] Callback\n * @private\n */\n sendFrame(list, cb) {\n if (list.length === 2) {\n this._socket.cork();\n this._socket.write(list[0]);\n this._socket.write(list[1], cb);\n this._socket.uncork();\n } else {\n this._socket.write(list[0], cb);\n }\n }\n}\n\nmodule.exports = Sender;\n\n/**\n * Calls queued callbacks with an error.\n *\n * @param {Sender} sender The `Sender` instance\n * @param {Error} err The error to call the callbacks with\n * @param {Function} [cb] The first callback\n * @private\n */\nfunction callCallbacks(sender, err, cb) {\n if (typeof cb === 'function') cb(err);\n\n for (let i = 0; i < sender._queue.length; i++) {\n const params = sender._queue[i];\n const callback = params[params.length - 1];\n\n if (typeof callback === 'function') callback(err);\n }\n}\n\n/**\n * Handles a `Sender` error.\n *\n * @param {Sender} sender The `Sender` instance\n * @param {Error} err The error\n * @param {Function} [cb] The first pending callback\n * @private\n */\nfunction onError(sender, err, cb) {\n callCallbacks(sender, err, cb);\n sender.onerror(err);\n}\n","'use strict';\n\nconst { kForOnEventAttribute, kListener } = require('./constants');\n\nconst kCode = Symbol('kCode');\nconst kData = Symbol('kData');\nconst kError = Symbol('kError');\nconst kMessage = Symbol('kMessage');\nconst kReason = Symbol('kReason');\nconst kTarget = Symbol('kTarget');\nconst kType = Symbol('kType');\nconst kWasClean = Symbol('kWasClean');\n\n/**\n * Class representing an event.\n */\nclass Event {\n /**\n * Create a new `Event`.\n *\n * @param {String} type The name of the event\n * @throws {TypeError} If the `type` argument is not specified\n */\n constructor(type) {\n this[kTarget] = null;\n this[kType] = type;\n }\n\n /**\n * @type {*}\n */\n get target() {\n return this[kTarget];\n }\n\n /**\n * @type {String}\n */\n get type() {\n return this[kType];\n }\n}\n\nObject.defineProperty(Event.prototype, 'target', { enumerable: true });\nObject.defineProperty(Event.prototype, 'type', { enumerable: true });\n\n/**\n * Class representing a close event.\n *\n * @extends Event\n */\nclass CloseEvent extends Event {\n /**\n * Create a new `CloseEvent`.\n *\n * @param {String} type The name of the event\n * @param {Object} [options] A dictionary object that allows for setting\n * attributes via object members of the same name\n * @param {Number} [options.code=0] The status code explaining why the\n * connection was closed\n * @param {String} [options.reason=''] A human-readable string explaining why\n * the connection was closed\n * @param {Boolean} [options.wasClean=false] Indicates whether or not the\n * connection was cleanly closed\n */\n constructor(type, options = {}) {\n super(type);\n\n this[kCode] = options.code === undefined ? 0 : options.code;\n this[kReason] = options.reason === undefined ? '' : options.reason;\n this[kWasClean] = options.wasClean === undefined ? false : options.wasClean;\n }\n\n /**\n * @type {Number}\n */\n get code() {\n return this[kCode];\n }\n\n /**\n * @type {String}\n */\n get reason() {\n return this[kReason];\n }\n\n /**\n * @type {Boolean}\n */\n get wasClean() {\n return this[kWasClean];\n }\n}\n\nObject.defineProperty(CloseEvent.prototype, 'code', { enumerable: true });\nObject.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true });\nObject.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true });\n\n/**\n * Class representing an error event.\n *\n * @extends Event\n */\nclass ErrorEvent extends Event {\n /**\n * Create a new `ErrorEvent`.\n *\n * @param {String} type The name of the event\n * @param {Object} [options] A dictionary object that allows for setting\n * attributes via object members of the same name\n * @param {*} [options.error=null] The error that generated this event\n * @param {String} [options.message=''] The error message\n */\n constructor(type, options = {}) {\n super(type);\n\n this[kError] = options.error === undefined ? null : options.error;\n this[kMessage] = options.message === undefined ? '' : options.message;\n }\n\n /**\n * @type {*}\n */\n get error() {\n return this[kError];\n }\n\n /**\n * @type {String}\n */\n get message() {\n return this[kMessage];\n }\n}\n\nObject.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true });\nObject.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true });\n\n/**\n * Class representing a message event.\n *\n * @extends Event\n */\nclass MessageEvent extends Event {\n /**\n * Create a new `MessageEvent`.\n *\n * @param {String} type The name of the event\n * @param {Object} [options] A dictionary object that allows for setting\n * attributes via object members of the same name\n * @param {*} [options.data=null] The message content\n */\n constructor(type, options = {}) {\n super(type);\n\n this[kData] = options.data === undefined ? null : options.data;\n }\n\n /**\n * @type {*}\n */\n get data() {\n return this[kData];\n }\n}\n\nObject.defineProperty(MessageEvent.prototype, 'data', { enumerable: true });\n\n/**\n * This provides methods for emulating the `EventTarget` interface. It's not\n * meant to be used directly.\n *\n * @mixin\n */\nconst EventTarget = {\n /**\n * Register an event listener.\n *\n * @param {String} type A string representing the event type to listen for\n * @param {(Function|Object)} handler The listener to add\n * @param {Object} [options] An options object specifies characteristics about\n * the event listener\n * @param {Boolean} [options.once=false] A `Boolean` indicating that the\n * listener should be invoked at most once after being added. If `true`,\n * the listener would be automatically removed when invoked.\n * @public\n */\n addEventListener(type, handler, options = {}) {\n for (const listener of this.listeners(type)) {\n if (\n !options[kForOnEventAttribute] &&\n listener[kListener] === handler &&\n !listener[kForOnEventAttribute]\n ) {\n return;\n }\n }\n\n let wrapper;\n\n if (type === 'message') {\n wrapper = function onMessage(data, isBinary) {\n const event = new MessageEvent('message', {\n data: isBinary ? data : data.toString()\n });\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else if (type === 'close') {\n wrapper = function onClose(code, message) {\n const event = new CloseEvent('close', {\n code,\n reason: message.toString(),\n wasClean: this._closeFrameReceived && this._closeFrameSent\n });\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else if (type === 'error') {\n wrapper = function onError(error) {\n const event = new ErrorEvent('error', {\n error,\n message: error.message\n });\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else if (type === 'open') {\n wrapper = function onOpen() {\n const event = new Event('open');\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else {\n return;\n }\n\n wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];\n wrapper[kListener] = handler;\n\n if (options.once) {\n this.once(type, wrapper);\n } else {\n this.on(type, wrapper);\n }\n },\n\n /**\n * Remove an event listener.\n *\n * @param {String} type A string representing the event type to remove\n * @param {(Function|Object)} handler The listener to remove\n * @public\n */\n removeEventListener(type, handler) {\n for (const listener of this.listeners(type)) {\n if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {\n this.removeListener(type, listener);\n break;\n }\n }\n }\n};\n\nmodule.exports = {\n CloseEvent,\n ErrorEvent,\n Event,\n EventTarget,\n MessageEvent\n};\n\n/**\n * Call an event listener\n *\n * @param {(Function|Object)} listener The listener to call\n * @param {*} thisArg The value to use as `this`` when calling the listener\n * @param {Event} event The event to pass to the listener\n * @private\n */\nfunction callListener(listener, thisArg, event) {\n if (typeof listener === 'object' && listener.handleEvent) {\n listener.handleEvent.call(listener, event);\n } else {\n listener.call(thisArg, event);\n }\n}\n","'use strict';\n\nconst { tokenChars } = require('./validation');\n\n/**\n * Adds an offer to the map of extension offers or a parameter to the map of\n * parameters.\n *\n * @param {Object} dest The map of extension offers or parameters\n * @param {String} name The extension or parameter name\n * @param {(Object|Boolean|String)} elem The extension parameters or the\n * parameter value\n * @private\n */\nfunction push(dest, name, elem) {\n if (dest[name] === undefined) dest[name] = [elem];\n else dest[name].push(elem);\n}\n\n/**\n * Parses the `Sec-WebSocket-Extensions` header into an object.\n *\n * @param {String} header The field value of the header\n * @return {Object} The parsed object\n * @public\n */\nfunction parse(header) {\n const offers = Object.create(null);\n let params = Object.create(null);\n let mustUnescape = false;\n let isEscaping = false;\n let inQuotes = false;\n let extensionName;\n let paramName;\n let start = -1;\n let code = -1;\n let end = -1;\n let i = 0;\n\n for (; i < header.length; i++) {\n code = header.charCodeAt(i);\n\n if (extensionName === undefined) {\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (\n i !== 0 &&\n (code === 0x20 /* ' ' */ || code === 0x09) /* '\\t' */\n ) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n const name = header.slice(start, end);\n if (code === 0x2c) {\n push(offers, name, params);\n params = Object.create(null);\n } else {\n extensionName = name;\n }\n\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else if (paramName === undefined) {\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (code === 0x20 || code === 0x09) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x3b || code === 0x2c) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n push(params, header.slice(start, end), true);\n if (code === 0x2c) {\n push(offers, extensionName, params);\n params = Object.create(null);\n extensionName = undefined;\n }\n\n start = end = -1;\n } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) {\n paramName = header.slice(start, i);\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else {\n //\n // The value of a quoted-string after unescaping must conform to the\n // token ABNF, so only token characters are valid.\n // Ref: https://tools.ietf.org/html/rfc6455#section-9.1\n //\n if (isEscaping) {\n if (tokenChars[code] !== 1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n if (start === -1) start = i;\n else if (!mustUnescape) mustUnescape = true;\n isEscaping = false;\n } else if (inQuotes) {\n if (tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (code === 0x22 /* '\"' */ && start !== -1) {\n inQuotes = false;\n end = i;\n } else if (code === 0x5c /* '\\' */) {\n isEscaping = true;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) {\n inQuotes = true;\n } else if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (start !== -1 && (code === 0x20 || code === 0x09)) {\n if (end === -1) end = i;\n } else if (code === 0x3b || code === 0x2c) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n let value = header.slice(start, end);\n if (mustUnescape) {\n value = value.replace(/\\\\/g, '');\n mustUnescape = false;\n }\n push(params, paramName, value);\n if (code === 0x2c) {\n push(offers, extensionName, params);\n params = Object.create(null);\n extensionName = undefined;\n }\n\n paramName = undefined;\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n }\n }\n\n if (start === -1 || inQuotes || code === 0x20 || code === 0x09) {\n throw new SyntaxError('Unexpected end of input');\n }\n\n if (end === -1) end = i;\n const token = header.slice(start, end);\n if (extensionName === undefined) {\n push(offers, token, params);\n } else {\n if (paramName === undefined) {\n push(params, token, true);\n } else if (mustUnescape) {\n push(params, paramName, token.replace(/\\\\/g, ''));\n } else {\n push(params, paramName, token);\n }\n push(offers, extensionName, params);\n }\n\n return offers;\n}\n\n/**\n * Builds the `Sec-WebSocket-Extensions` header field value.\n *\n * @param {Object} extensions The map of extensions and parameters to format\n * @return {String} A string representing the given object\n * @public\n */\nfunction format(extensions) {\n return Object.keys(extensions)\n .map((extension) => {\n let configurations = extensions[extension];\n if (!Array.isArray(configurations)) configurations = [configurations];\n return configurations\n .map((params) => {\n return [extension]\n .concat(\n Object.keys(params).map((k) => {\n let values = params[k];\n if (!Array.isArray(values)) values = [values];\n return values\n .map((v) => (v === true ? k : `${k}=${v}`))\n .join('; ');\n })\n )\n .join('; ');\n })\n .join(', ');\n })\n .join(', ');\n}\n\nmodule.exports = { format, parse };\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex|Readable$\", \"caughtErrors\": \"none\" }] */\n\n'use strict';\n\nconst EventEmitter = require('events');\nconst https = require('https');\nconst http = require('http');\nconst net = require('net');\nconst tls = require('tls');\nconst { randomBytes, createHash } = require('crypto');\nconst { Duplex, Readable } = require('stream');\nconst { URL } = require('url');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst Receiver = require('./receiver');\nconst Sender = require('./sender');\nconst { isBlob } = require('./validation');\n\nconst {\n BINARY_TYPES,\n CLOSE_TIMEOUT,\n EMPTY_BUFFER,\n GUID,\n kForOnEventAttribute,\n kListener,\n kStatusCode,\n kWebSocket,\n NOOP\n} = require('./constants');\nconst {\n EventTarget: { addEventListener, removeEventListener }\n} = require('./event-target');\nconst { format, parse } = require('./extension');\nconst { toBuffer } = require('./buffer-util');\n\nconst kAborted = Symbol('kAborted');\nconst protocolVersions = [8, 13];\nconst readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];\nconst subprotocolRegex = /^[!#$%&'*+\\-.0-9A-Z^_`|a-z~]+$/;\n\n/**\n * Class representing a WebSocket.\n *\n * @extends EventEmitter\n */\nclass WebSocket extends EventEmitter {\n /**\n * Create a new `WebSocket`.\n *\n * @param {(String|URL)} address The URL to which to connect\n * @param {(String|String[])} [protocols] The subprotocols\n * @param {Object} [options] Connection options\n */\n constructor(address, protocols, options) {\n super();\n\n this._binaryType = BINARY_TYPES[0];\n this._closeCode = 1006;\n this._closeFrameReceived = false;\n this._closeFrameSent = false;\n this._closeMessage = EMPTY_BUFFER;\n this._closeTimer = null;\n this._errorEmitted = false;\n this._extensions = {};\n this._paused = false;\n this._protocol = '';\n this._readyState = WebSocket.CONNECTING;\n this._receiver = null;\n this._sender = null;\n this._socket = null;\n\n if (address !== null) {\n this._bufferedAmount = 0;\n this._isServer = false;\n this._redirects = 0;\n\n if (protocols === undefined) {\n protocols = [];\n } else if (!Array.isArray(protocols)) {\n if (typeof protocols === 'object' && protocols !== null) {\n options = protocols;\n protocols = [];\n } else {\n protocols = [protocols];\n }\n }\n\n initAsClient(this, address, protocols, options);\n } else {\n this._autoPong = options.autoPong;\n this._closeTimeout = options.closeTimeout;\n this._isServer = true;\n }\n }\n\n /**\n * For historical reasons, the custom \"nodebuffer\" type is used by the default\n * instead of \"blob\".\n *\n * @type {String}\n */\n get binaryType() {\n return this._binaryType;\n }\n\n set binaryType(type) {\n if (!BINARY_TYPES.includes(type)) return;\n\n this._binaryType = type;\n\n //\n // Allow to change `binaryType` on the fly.\n //\n if (this._receiver) this._receiver._binaryType = type;\n }\n\n /**\n * @type {Number}\n */\n get bufferedAmount() {\n if (!this._socket) return this._bufferedAmount;\n\n return this._socket._writableState.length + this._sender._bufferedBytes;\n }\n\n /**\n * @type {String}\n */\n get extensions() {\n return Object.keys(this._extensions).join();\n }\n\n /**\n * @type {Boolean}\n */\n get isPaused() {\n return this._paused;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onclose() {\n return null;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onerror() {\n return null;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onopen() {\n return null;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onmessage() {\n return null;\n }\n\n /**\n * @type {String}\n */\n get protocol() {\n return this._protocol;\n }\n\n /**\n * @type {Number}\n */\n get readyState() {\n return this._readyState;\n }\n\n /**\n * @type {String}\n */\n get url() {\n return this._url;\n }\n\n /**\n * Set up the socket and the internal resources.\n *\n * @param {Duplex} socket The network socket between the server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Object} options Options object\n * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether\n * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n * multiple times in the same tick\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Number} [options.maxBufferedChunks=0] The maximum number of\n * buffered data chunks\n * @param {Number} [options.maxFragments=0] The maximum number of message\n * fragments\n * @param {Number} [options.maxPayload=0] The maximum allowed message size\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n * @private\n */\n setSocket(socket, head, options) {\n const receiver = new Receiver({\n allowSynchronousEvents: options.allowSynchronousEvents,\n binaryType: this.binaryType,\n extensions: this._extensions,\n isServer: this._isServer,\n maxBufferedChunks: options.maxBufferedChunks,\n maxFragments: options.maxFragments,\n maxPayload: options.maxPayload,\n skipUTF8Validation: options.skipUTF8Validation\n });\n\n const sender = new Sender(socket, this._extensions, options.generateMask);\n\n this._receiver = receiver;\n this._sender = sender;\n this._socket = socket;\n\n receiver[kWebSocket] = this;\n sender[kWebSocket] = this;\n socket[kWebSocket] = this;\n\n receiver.on('conclude', receiverOnConclude);\n receiver.on('drain', receiverOnDrain);\n receiver.on('error', receiverOnError);\n receiver.on('message', receiverOnMessage);\n receiver.on('ping', receiverOnPing);\n receiver.on('pong', receiverOnPong);\n\n sender.onerror = senderOnError;\n\n //\n // These methods may not be available if `socket` is just a `Duplex`.\n //\n if (socket.setTimeout) socket.setTimeout(0);\n if (socket.setNoDelay) socket.setNoDelay();\n\n if (head.length > 0) socket.unshift(head);\n\n socket.on('close', socketOnClose);\n socket.on('data', socketOnData);\n socket.on('end', socketOnEnd);\n socket.on('error', socketOnError);\n\n this._readyState = WebSocket.OPEN;\n this.emit('open');\n }\n\n /**\n * Emit the `'close'` event.\n *\n * @private\n */\n emitClose() {\n if (!this._socket) {\n this._readyState = WebSocket.CLOSED;\n this.emit('close', this._closeCode, this._closeMessage);\n return;\n }\n\n if (this._extensions[PerMessageDeflate.extensionName]) {\n this._extensions[PerMessageDeflate.extensionName].cleanup();\n }\n\n this._receiver.removeAllListeners();\n this._readyState = WebSocket.CLOSED;\n this.emit('close', this._closeCode, this._closeMessage);\n }\n\n /**\n * Start a closing handshake.\n *\n * +----------+ +-----------+ +----------+\n * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -\n * | +----------+ +-----------+ +----------+ |\n * +----------+ +-----------+ |\n * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING\n * +----------+ +-----------+ |\n * | | | +---+ |\n * +------------------------+-->|fin| - - - -\n * | +---+ | +---+\n * - - - - -|fin|<---------------------+\n * +---+\n *\n * @param {Number} [code] Status code explaining why the connection is closing\n * @param {(String|Buffer)} [data] The reason why the connection is\n * closing\n * @public\n */\n close(code, data) {\n if (this.readyState === WebSocket.CLOSED) return;\n if (this.readyState === WebSocket.CONNECTING) {\n const msg = 'WebSocket was closed before the connection was established';\n abortHandshake(this, this._req, msg);\n return;\n }\n\n if (this.readyState === WebSocket.CLOSING) {\n if (\n this._closeFrameSent &&\n (this._closeFrameReceived || this._receiver._writableState.errorEmitted)\n ) {\n this._socket.end();\n }\n\n return;\n }\n\n this._readyState = WebSocket.CLOSING;\n this._sender.close(code, data, !this._isServer, (err) => {\n //\n // This error is handled by the `'error'` listener on the socket. We only\n // want to know if the close frame has been sent here.\n //\n if (err) return;\n\n this._closeFrameSent = true;\n\n if (\n this._closeFrameReceived ||\n this._receiver._writableState.errorEmitted\n ) {\n this._socket.end();\n }\n });\n\n setCloseTimer(this);\n }\n\n /**\n * Pause the socket.\n *\n * @public\n */\n pause() {\n if (\n this.readyState === WebSocket.CONNECTING ||\n this.readyState === WebSocket.CLOSED\n ) {\n return;\n }\n\n this._paused = true;\n this._socket.pause();\n }\n\n /**\n * Send a ping.\n *\n * @param {*} [data] The data to send\n * @param {Boolean} [mask] Indicates whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when the ping is sent\n * @public\n */\n ping(data, mask, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof data === 'function') {\n cb = data;\n data = mask = undefined;\n } else if (typeof mask === 'function') {\n cb = mask;\n mask = undefined;\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n if (mask === undefined) mask = !this._isServer;\n this._sender.ping(data || EMPTY_BUFFER, mask, cb);\n }\n\n /**\n * Send a pong.\n *\n * @param {*} [data] The data to send\n * @param {Boolean} [mask] Indicates whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when the pong is sent\n * @public\n */\n pong(data, mask, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof data === 'function') {\n cb = data;\n data = mask = undefined;\n } else if (typeof mask === 'function') {\n cb = mask;\n mask = undefined;\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n if (mask === undefined) mask = !this._isServer;\n this._sender.pong(data || EMPTY_BUFFER, mask, cb);\n }\n\n /**\n * Resume the socket.\n *\n * @public\n */\n resume() {\n if (\n this.readyState === WebSocket.CONNECTING ||\n this.readyState === WebSocket.CLOSED\n ) {\n return;\n }\n\n this._paused = false;\n if (!this._receiver._writableState.needDrain) this._socket.resume();\n }\n\n /**\n * Send a data message.\n *\n * @param {*} data The message to send\n * @param {Object} [options] Options object\n * @param {Boolean} [options.binary] Specifies whether `data` is binary or\n * text\n * @param {Boolean} [options.compress] Specifies whether or not to compress\n * `data`\n * @param {Boolean} [options.fin=true] Specifies whether the fragment is the\n * last one\n * @param {Boolean} [options.mask] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when data is written out\n * @public\n */\n send(data, options, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof options === 'function') {\n cb = options;\n options = {};\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n const opts = {\n binary: typeof data !== 'string',\n mask: !this._isServer,\n compress: true,\n fin: true,\n ...options\n };\n\n if (!this._extensions[PerMessageDeflate.extensionName]) {\n opts.compress = false;\n }\n\n this._sender.send(data || EMPTY_BUFFER, opts, cb);\n }\n\n /**\n * Forcibly close the connection.\n *\n * @public\n */\n terminate() {\n if (this.readyState === WebSocket.CLOSED) return;\n if (this.readyState === WebSocket.CONNECTING) {\n const msg = 'WebSocket was closed before the connection was established';\n abortHandshake(this, this._req, msg);\n return;\n }\n\n if (this._socket) {\n this._readyState = WebSocket.CLOSING;\n this._socket.destroy();\n }\n }\n}\n\n/**\n * @constant {Number} CONNECTING\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CONNECTING', {\n enumerable: true,\n value: readyStates.indexOf('CONNECTING')\n});\n\n/**\n * @constant {Number} CONNECTING\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CONNECTING', {\n enumerable: true,\n value: readyStates.indexOf('CONNECTING')\n});\n\n/**\n * @constant {Number} OPEN\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'OPEN', {\n enumerable: true,\n value: readyStates.indexOf('OPEN')\n});\n\n/**\n * @constant {Number} OPEN\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'OPEN', {\n enumerable: true,\n value: readyStates.indexOf('OPEN')\n});\n\n/**\n * @constant {Number} CLOSING\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CLOSING', {\n enumerable: true,\n value: readyStates.indexOf('CLOSING')\n});\n\n/**\n * @constant {Number} CLOSING\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CLOSING', {\n enumerable: true,\n value: readyStates.indexOf('CLOSING')\n});\n\n/**\n * @constant {Number} CLOSED\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CLOSED', {\n enumerable: true,\n value: readyStates.indexOf('CLOSED')\n});\n\n/**\n * @constant {Number} CLOSED\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CLOSED', {\n enumerable: true,\n value: readyStates.indexOf('CLOSED')\n});\n\n[\n 'binaryType',\n 'bufferedAmount',\n 'extensions',\n 'isPaused',\n 'protocol',\n 'readyState',\n 'url'\n].forEach((property) => {\n Object.defineProperty(WebSocket.prototype, property, { enumerable: true });\n});\n\n//\n// Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes.\n// See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface\n//\n['open', 'error', 'close', 'message'].forEach((method) => {\n Object.defineProperty(WebSocket.prototype, `on${method}`, {\n enumerable: true,\n get() {\n for (const listener of this.listeners(method)) {\n if (listener[kForOnEventAttribute]) return listener[kListener];\n }\n\n return null;\n },\n set(handler) {\n for (const listener of this.listeners(method)) {\n if (listener[kForOnEventAttribute]) {\n this.removeListener(method, listener);\n break;\n }\n }\n\n if (typeof handler !== 'function') return;\n\n this.addEventListener(method, handler, {\n [kForOnEventAttribute]: true\n });\n }\n });\n});\n\nWebSocket.prototype.addEventListener = addEventListener;\nWebSocket.prototype.removeEventListener = removeEventListener;\n\nmodule.exports = WebSocket;\n\n/**\n * Initialize a WebSocket client.\n *\n * @param {WebSocket} websocket The client to initialize\n * @param {(String|URL)} address The URL to which to connect\n * @param {Array} protocols The subprotocols\n * @param {Object} [options] Connection options\n * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether any\n * of the `'message'`, `'ping'`, and `'pong'` events can be emitted multiple\n * times in the same tick\n * @param {Boolean} [options.autoPong=true] Specifies whether or not to\n * automatically send a pong in response to a ping\n * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to wait\n * for the closing handshake to finish after `websocket.close()` is called\n * @param {Function} [options.finishRequest] A function which can be used to\n * customize the headers of each http request before it is sent\n * @param {Boolean} [options.followRedirects=false] Whether or not to follow\n * redirects\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the\n * handshake request\n * @param {Number} [options.maxBufferedChunks=1048576] The maximum number of\n * buffered data chunks\n * @param {Number} [options.maxFragments=131072] The maximum number of message\n * fragments\n * @param {Number} [options.maxPayload=104857600] The maximum allowed message\n * size\n * @param {Number} [options.maxRedirects=10] The maximum number of redirects\n * allowed\n * @param {String} [options.origin] Value of the `Origin` or\n * `Sec-WebSocket-Origin` header\n * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable\n * permessage-deflate\n * @param {Number} [options.protocolVersion=13] Value of the\n * `Sec-WebSocket-Version` header\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n * @private\n */\nfunction initAsClient(websocket, address, protocols, options) {\n const opts = {\n allowSynchronousEvents: true,\n autoPong: true,\n closeTimeout: CLOSE_TIMEOUT,\n protocolVersion: protocolVersions[1],\n maxBufferedChunks: 1024 * 1024,\n maxFragments: 128 * 1024,\n maxPayload: 100 * 1024 * 1024,\n skipUTF8Validation: false,\n perMessageDeflate: true,\n followRedirects: false,\n maxRedirects: 10,\n ...options,\n socketPath: undefined,\n hostname: undefined,\n protocol: undefined,\n timeout: undefined,\n method: 'GET',\n host: undefined,\n path: undefined,\n port: undefined\n };\n\n websocket._autoPong = opts.autoPong;\n websocket._closeTimeout = opts.closeTimeout;\n\n if (!protocolVersions.includes(opts.protocolVersion)) {\n throw new RangeError(\n `Unsupported protocol version: ${opts.protocolVersion} ` +\n `(supported versions: ${protocolVersions.join(', ')})`\n );\n }\n\n let parsedUrl;\n\n if (address instanceof URL) {\n parsedUrl = address;\n } else {\n try {\n parsedUrl = new URL(address);\n } catch {\n throw new SyntaxError(`Invalid URL: ${address}`);\n }\n }\n\n if (parsedUrl.protocol === 'http:') {\n parsedUrl.protocol = 'ws:';\n } else if (parsedUrl.protocol === 'https:') {\n parsedUrl.protocol = 'wss:';\n }\n\n websocket._url = parsedUrl.href;\n\n const isSecure = parsedUrl.protocol === 'wss:';\n const isIpcUrl = parsedUrl.protocol === 'ws+unix:';\n let invalidUrlMessage;\n\n if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) {\n invalidUrlMessage =\n 'The URL\\'s protocol must be one of \"ws:\", \"wss:\", ' +\n '\"http:\", \"https:\", or \"ws+unix:\"';\n } else if (isIpcUrl && !parsedUrl.pathname) {\n invalidUrlMessage = \"The URL's pathname is empty\";\n } else if (parsedUrl.hash) {\n invalidUrlMessage = 'The URL contains a fragment identifier';\n }\n\n if (invalidUrlMessage) {\n const err = new SyntaxError(invalidUrlMessage);\n\n if (websocket._redirects === 0) {\n throw err;\n } else {\n emitErrorAndClose(websocket, err);\n return;\n }\n }\n\n const defaultPort = isSecure ? 443 : 80;\n const key = randomBytes(16).toString('base64');\n const request = isSecure ? https.request : http.request;\n const protocolSet = new Set();\n let perMessageDeflate;\n\n opts.createConnection =\n opts.createConnection || (isSecure ? tlsConnect : netConnect);\n opts.defaultPort = opts.defaultPort || defaultPort;\n opts.port = parsedUrl.port || defaultPort;\n opts.host = parsedUrl.hostname.startsWith('[')\n ? parsedUrl.hostname.slice(1, -1)\n : parsedUrl.hostname;\n opts.headers = {\n ...opts.headers,\n 'Sec-WebSocket-Version': opts.protocolVersion,\n 'Sec-WebSocket-Key': key,\n Connection: 'Upgrade',\n Upgrade: 'websocket'\n };\n opts.path = parsedUrl.pathname + parsedUrl.search;\n opts.timeout = opts.handshakeTimeout;\n\n if (opts.perMessageDeflate) {\n perMessageDeflate = new PerMessageDeflate({\n ...opts.perMessageDeflate,\n isServer: false,\n maxPayload: opts.maxPayload\n });\n opts.headers['Sec-WebSocket-Extensions'] = format({\n [PerMessageDeflate.extensionName]: perMessageDeflate.offer()\n });\n }\n if (protocols.length) {\n for (const protocol of protocols) {\n if (\n typeof protocol !== 'string' ||\n !subprotocolRegex.test(protocol) ||\n protocolSet.has(protocol)\n ) {\n throw new SyntaxError(\n 'An invalid or duplicated subprotocol was specified'\n );\n }\n\n protocolSet.add(protocol);\n }\n\n opts.headers['Sec-WebSocket-Protocol'] = protocols.join(',');\n }\n if (opts.origin) {\n if (opts.protocolVersion < 13) {\n opts.headers['Sec-WebSocket-Origin'] = opts.origin;\n } else {\n opts.headers.Origin = opts.origin;\n }\n }\n if (parsedUrl.username || parsedUrl.password) {\n opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;\n }\n\n if (isIpcUrl) {\n const parts = opts.path.split(':');\n\n opts.socketPath = parts[0];\n opts.path = parts[1];\n }\n\n let req;\n\n if (opts.followRedirects) {\n if (websocket._redirects === 0) {\n websocket._originalIpc = isIpcUrl;\n websocket._originalSecure = isSecure;\n websocket._originalHostOrSocketPath = isIpcUrl\n ? opts.socketPath\n : parsedUrl.host;\n\n const headers = options && options.headers;\n\n //\n // Shallow copy the user provided options so that headers can be changed\n // without mutating the original object.\n //\n options = { ...options, headers: {} };\n\n if (headers) {\n for (const [key, value] of Object.entries(headers)) {\n options.headers[key.toLowerCase()] = value;\n }\n }\n } else if (websocket.listenerCount('redirect') === 0) {\n const isSameHost = isIpcUrl\n ? websocket._originalIpc\n ? opts.socketPath === websocket._originalHostOrSocketPath\n : false\n : websocket._originalIpc\n ? false\n : parsedUrl.host === websocket._originalHostOrSocketPath;\n\n if (!isSameHost || (websocket._originalSecure && !isSecure)) {\n //\n // Match curl 7.77.0 behavior and drop the following headers. These\n // headers are also dropped when following a redirect to a subdomain.\n //\n delete opts.headers.authorization;\n delete opts.headers.cookie;\n\n if (!isSameHost) delete opts.headers.host;\n\n opts.auth = undefined;\n }\n }\n\n //\n // Match curl 7.77.0 behavior and make the first `Authorization` header win.\n // If the `Authorization` header is set, then there is nothing to do as it\n // will take precedence.\n //\n if (opts.auth && !options.headers.authorization) {\n options.headers.authorization =\n 'Basic ' + Buffer.from(opts.auth).toString('base64');\n }\n\n req = websocket._req = request(opts);\n\n if (websocket._redirects) {\n //\n // Unlike what is done for the `'upgrade'` event, no early exit is\n // triggered here if the user calls `websocket.close()` or\n // `websocket.terminate()` from a listener of the `'redirect'` event. This\n // is because the user can also call `request.destroy()` with an error\n // before calling `websocket.close()` or `websocket.terminate()` and this\n // would result in an error being emitted on the `request` object with no\n // `'error'` event listeners attached.\n //\n websocket.emit('redirect', websocket.url, req);\n }\n } else {\n req = websocket._req = request(opts);\n }\n\n if (opts.timeout) {\n req.on('timeout', () => {\n abortHandshake(websocket, req, 'Opening handshake has timed out');\n });\n }\n\n req.on('error', (err) => {\n if (req === null || req[kAborted]) return;\n\n req = websocket._req = null;\n emitErrorAndClose(websocket, err);\n });\n\n req.on('response', (res) => {\n const location = res.headers.location;\n const statusCode = res.statusCode;\n\n if (\n location &&\n opts.followRedirects &&\n statusCode >= 300 &&\n statusCode < 400\n ) {\n if (++websocket._redirects > opts.maxRedirects) {\n abortHandshake(websocket, req, 'Maximum redirects exceeded');\n return;\n }\n\n req.abort();\n\n let addr;\n\n try {\n addr = new URL(location, address);\n } catch (e) {\n const err = new SyntaxError(`Invalid URL: ${location}`);\n emitErrorAndClose(websocket, err);\n return;\n }\n\n initAsClient(websocket, addr, protocols, options);\n } else if (!websocket.emit('unexpected-response', req, res)) {\n abortHandshake(\n websocket,\n req,\n `Unexpected server response: ${res.statusCode}`\n );\n }\n });\n\n req.on('upgrade', (res, socket, head) => {\n websocket.emit('upgrade', res);\n\n //\n // The user may have closed the connection from a listener of the\n // `'upgrade'` event.\n //\n if (websocket.readyState !== WebSocket.CONNECTING) return;\n\n req = websocket._req = null;\n\n const upgrade = res.headers.upgrade;\n\n if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {\n abortHandshake(websocket, socket, 'Invalid Upgrade header');\n return;\n }\n\n const digest = createHash('sha1')\n .update(key + GUID)\n .digest('base64');\n\n if (res.headers['sec-websocket-accept'] !== digest) {\n abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header');\n return;\n }\n\n const serverProt = res.headers['sec-websocket-protocol'];\n let protError;\n\n if (serverProt !== undefined) {\n if (!protocolSet.size) {\n protError = 'Server sent a subprotocol but none was requested';\n } else if (!protocolSet.has(serverProt)) {\n protError = 'Server sent an invalid subprotocol';\n }\n } else if (protocolSet.size) {\n protError = 'Server sent no subprotocol';\n }\n\n if (protError) {\n abortHandshake(websocket, socket, protError);\n return;\n }\n\n if (serverProt) websocket._protocol = serverProt;\n\n const secWebSocketExtensions = res.headers['sec-websocket-extensions'];\n\n if (secWebSocketExtensions !== undefined) {\n if (!perMessageDeflate) {\n const message =\n 'Server sent a Sec-WebSocket-Extensions header but no extension ' +\n 'was requested';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n let extensions;\n\n try {\n extensions = parse(secWebSocketExtensions);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Extensions header';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n const extensionNames = Object.keys(extensions);\n\n if (\n extensionNames.length !== 1 ||\n extensionNames[0] !== PerMessageDeflate.extensionName\n ) {\n const message = 'Server indicated an extension that was not requested';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n try {\n perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Extensions header';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n websocket._extensions[PerMessageDeflate.extensionName] =\n perMessageDeflate;\n }\n\n websocket.setSocket(socket, head, {\n allowSynchronousEvents: opts.allowSynchronousEvents,\n generateMask: opts.generateMask,\n maxBufferedChunks: opts.maxBufferedChunks,\n maxFragments: opts.maxFragments,\n maxPayload: opts.maxPayload,\n skipUTF8Validation: opts.skipUTF8Validation\n });\n });\n\n if (opts.finishRequest) {\n opts.finishRequest(req, websocket);\n } else {\n req.end();\n }\n}\n\n/**\n * Emit the `'error'` and `'close'` events.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {Error} The error to emit\n * @private\n */\nfunction emitErrorAndClose(websocket, err) {\n websocket._readyState = WebSocket.CLOSING;\n //\n // The following assignment is practically useless and is done only for\n // consistency.\n //\n websocket._errorEmitted = true;\n websocket.emit('error', err);\n websocket.emitClose();\n}\n\n/**\n * Create a `net.Socket` and initiate a connection.\n *\n * @param {Object} options Connection options\n * @return {net.Socket} The newly created socket used to start the connection\n * @private\n */\nfunction netConnect(options) {\n options.path = options.socketPath;\n return net.connect(options);\n}\n\n/**\n * Create a `tls.TLSSocket` and initiate a connection.\n *\n * @param {Object} options Connection options\n * @return {tls.TLSSocket} The newly created socket used to start the connection\n * @private\n */\nfunction tlsConnect(options) {\n options.path = undefined;\n\n if (!options.servername && options.servername !== '') {\n options.servername = net.isIP(options.host) ? '' : options.host;\n }\n\n return tls.connect(options);\n}\n\n/**\n * Abort the handshake and emit an error.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to\n * abort or the socket to destroy\n * @param {String} message The error message\n * @private\n */\nfunction abortHandshake(websocket, stream, message) {\n websocket._readyState = WebSocket.CLOSING;\n\n const err = new Error(message);\n Error.captureStackTrace(err, abortHandshake);\n\n if (stream.setHeader) {\n stream[kAborted] = true;\n stream.abort();\n\n if (stream.socket && !stream.socket.destroyed) {\n //\n // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if\n // called after the request completed. See\n // https://github.com/websockets/ws/issues/1869.\n //\n stream.socket.destroy();\n }\n\n process.nextTick(emitErrorAndClose, websocket, err);\n } else {\n stream.destroy(err);\n stream.once('error', websocket.emit.bind(websocket, 'error'));\n stream.once('close', websocket.emitClose.bind(websocket));\n }\n}\n\n/**\n * Handle cases where the `ping()`, `pong()`, or `send()` methods are called\n * when the `readyState` attribute is `CLOSING` or `CLOSED`.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {*} [data] The data to send\n * @param {Function} [cb] Callback\n * @private\n */\nfunction sendAfterClose(websocket, data, cb) {\n if (data) {\n const length = isBlob(data) ? data.size : toBuffer(data).length;\n\n //\n // The `_bufferedAmount` property is used only when the peer is a client and\n // the opening handshake fails. Under these circumstances, in fact, the\n // `setSocket()` method is not called, so the `_socket` and `_sender`\n // properties are set to `null`.\n //\n if (websocket._socket) websocket._sender._bufferedBytes += length;\n else websocket._bufferedAmount += length;\n }\n\n if (cb) {\n const err = new Error(\n `WebSocket is not open: readyState ${websocket.readyState} ` +\n `(${readyStates[websocket.readyState]})`\n );\n process.nextTick(cb, err);\n }\n}\n\n/**\n * The listener of the `Receiver` `'conclude'` event.\n *\n * @param {Number} code The status code\n * @param {Buffer} reason The reason for closing\n * @private\n */\nfunction receiverOnConclude(code, reason) {\n const websocket = this[kWebSocket];\n\n websocket._closeFrameReceived = true;\n websocket._closeMessage = reason;\n websocket._closeCode = code;\n\n if (websocket._socket[kWebSocket] === undefined) return;\n\n websocket._socket.removeListener('data', socketOnData);\n process.nextTick(resume, websocket._socket);\n\n if (code === 1005) websocket.close();\n else websocket.close(code, reason);\n}\n\n/**\n * The listener of the `Receiver` `'drain'` event.\n *\n * @private\n */\nfunction receiverOnDrain() {\n const websocket = this[kWebSocket];\n\n if (!websocket.isPaused) websocket._socket.resume();\n}\n\n/**\n * The listener of the `Receiver` `'error'` event.\n *\n * @param {(RangeError|Error)} err The emitted error\n * @private\n */\nfunction receiverOnError(err) {\n const websocket = this[kWebSocket];\n\n if (websocket._socket[kWebSocket] !== undefined) {\n websocket._socket.removeListener('data', socketOnData);\n\n //\n // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See\n // https://github.com/websockets/ws/issues/1940.\n //\n process.nextTick(resume, websocket._socket);\n\n websocket.close(err[kStatusCode]);\n }\n\n if (!websocket._errorEmitted) {\n websocket._errorEmitted = true;\n websocket.emit('error', err);\n }\n}\n\n/**\n * The listener of the `Receiver` `'finish'` event.\n *\n * @private\n */\nfunction receiverOnFinish() {\n this[kWebSocket].emitClose();\n}\n\n/**\n * The listener of the `Receiver` `'message'` event.\n *\n * @param {Buffer|ArrayBuffer|Buffer[])} data The message\n * @param {Boolean} isBinary Specifies whether the message is binary or not\n * @private\n */\nfunction receiverOnMessage(data, isBinary) {\n this[kWebSocket].emit('message', data, isBinary);\n}\n\n/**\n * The listener of the `Receiver` `'ping'` event.\n *\n * @param {Buffer} data The data included in the ping frame\n * @private\n */\nfunction receiverOnPing(data) {\n const websocket = this[kWebSocket];\n\n if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);\n websocket.emit('ping', data);\n}\n\n/**\n * The listener of the `Receiver` `'pong'` event.\n *\n * @param {Buffer} data The data included in the pong frame\n * @private\n */\nfunction receiverOnPong(data) {\n this[kWebSocket].emit('pong', data);\n}\n\n/**\n * Resume a readable stream\n *\n * @param {Readable} stream The readable stream\n * @private\n */\nfunction resume(stream) {\n stream.resume();\n}\n\n/**\n * The `Sender` error event handler.\n *\n * @param {Error} The error\n * @private\n */\nfunction senderOnError(err) {\n const websocket = this[kWebSocket];\n\n if (websocket.readyState === WebSocket.CLOSED) return;\n if (websocket.readyState === WebSocket.OPEN) {\n websocket._readyState = WebSocket.CLOSING;\n setCloseTimer(websocket);\n }\n\n //\n // `socket.end()` is used instead of `socket.destroy()` to allow the other\n // peer to finish sending queued data. There is no need to set a timer here\n // because `CLOSING` means that it is already set or not needed.\n //\n this._socket.end();\n\n if (!websocket._errorEmitted) {\n websocket._errorEmitted = true;\n websocket.emit('error', err);\n }\n}\n\n/**\n * Set a timer to destroy the underlying raw socket of a WebSocket.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @private\n */\nfunction setCloseTimer(websocket) {\n websocket._closeTimer = setTimeout(\n websocket._socket.destroy.bind(websocket._socket),\n websocket._closeTimeout\n );\n}\n\n/**\n * The listener of the socket `'close'` event.\n *\n * @private\n */\nfunction socketOnClose() {\n const websocket = this[kWebSocket];\n\n this.removeListener('close', socketOnClose);\n this.removeListener('data', socketOnData);\n this.removeListener('end', socketOnEnd);\n\n websocket._readyState = WebSocket.CLOSING;\n\n //\n // The close frame might not have been received or the `'end'` event emitted,\n // for example, if the socket was destroyed due to an error. Ensure that the\n // `receiver` stream is closed after writing any remaining buffered data to\n // it. If the readable side of the socket is in flowing mode then there is no\n // buffered data as everything has been already written. If instead, the\n // socket is paused, any possible buffered data will be read as a single\n // chunk.\n //\n if (\n !this._readableState.endEmitted &&\n !websocket._closeFrameReceived &&\n !websocket._receiver._writableState.errorEmitted &&\n this._readableState.length !== 0\n ) {\n const chunk = this.read(this._readableState.length);\n\n websocket._receiver.write(chunk);\n }\n\n websocket._receiver.end();\n\n this[kWebSocket] = undefined;\n\n clearTimeout(websocket._closeTimer);\n\n if (\n websocket._receiver._writableState.finished ||\n websocket._receiver._writableState.errorEmitted\n ) {\n websocket.emitClose();\n } else {\n websocket._receiver.on('error', receiverOnFinish);\n websocket._receiver.on('finish', receiverOnFinish);\n }\n}\n\n/**\n * The listener of the socket `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction socketOnData(chunk) {\n if (!this[kWebSocket]._receiver.write(chunk)) {\n this.pause();\n }\n}\n\n/**\n * The listener of the socket `'end'` event.\n *\n * @private\n */\nfunction socketOnEnd() {\n const websocket = this[kWebSocket];\n\n websocket._readyState = WebSocket.CLOSING;\n websocket._receiver.end();\n this.end();\n}\n\n/**\n * The listener of the socket `'error'` event.\n *\n * @private\n */\nfunction socketOnError() {\n const websocket = this[kWebSocket];\n\n this.removeListener('error', socketOnError);\n this.on('error', NOOP);\n\n if (websocket) {\n websocket._readyState = WebSocket.CLOSING;\n this.destroy();\n }\n}\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^WebSocket$\" }] */\n'use strict';\n\nconst WebSocket = require('./websocket');\nconst { Duplex } = require('stream');\n\n/**\n * Emits the `'close'` event on a stream.\n *\n * @param {Duplex} stream The stream.\n * @private\n */\nfunction emitClose(stream) {\n stream.emit('close');\n}\n\n/**\n * The listener of the `'end'` event.\n *\n * @private\n */\nfunction duplexOnEnd() {\n if (!this.destroyed && this._writableState.finished) {\n this.destroy();\n }\n}\n\n/**\n * The listener of the `'error'` event.\n *\n * @param {Error} err The error\n * @private\n */\nfunction duplexOnError(err) {\n this.removeListener('error', duplexOnError);\n this.destroy();\n if (this.listenerCount('error') === 0) {\n // Do not suppress the throwing behavior.\n this.emit('error', err);\n }\n}\n\n/**\n * Wraps a `WebSocket` in a duplex stream.\n *\n * @param {WebSocket} ws The `WebSocket` to wrap\n * @param {Object} [options] The options for the `Duplex` constructor\n * @return {Duplex} The duplex stream\n * @public\n */\nfunction createWebSocketStream(ws, options) {\n let terminateOnDestroy = true;\n\n const duplex = new Duplex({\n ...options,\n autoDestroy: false,\n emitClose: false,\n objectMode: false,\n writableObjectMode: false\n });\n\n ws.on('message', function message(msg, isBinary) {\n const data =\n !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;\n\n if (!duplex.push(data)) ws.pause();\n });\n\n ws.once('error', function error(err) {\n if (duplex.destroyed) return;\n\n // Prevent `ws.terminate()` from being called by `duplex._destroy()`.\n //\n // - If the `'error'` event is emitted before the `'open'` event, then\n // `ws.terminate()` is a noop as no socket is assigned.\n // - Otherwise, the error is re-emitted by the listener of the `'error'`\n // event of the `Receiver` object. The listener already closes the\n // connection by calling `ws.close()`. This allows a close frame to be\n // sent to the other peer. If `ws.terminate()` is called right after this,\n // then the close frame might not be sent.\n terminateOnDestroy = false;\n duplex.destroy(err);\n });\n\n ws.once('close', function close() {\n if (duplex.destroyed) return;\n\n duplex.push(null);\n });\n\n duplex._destroy = function (err, callback) {\n if (ws.readyState === ws.CLOSED) {\n callback(err);\n process.nextTick(emitClose, duplex);\n return;\n }\n\n let called = false;\n\n ws.once('error', function error(err) {\n called = true;\n callback(err);\n });\n\n ws.once('close', function close() {\n if (!called) callback(err);\n process.nextTick(emitClose, duplex);\n });\n\n if (terminateOnDestroy) ws.terminate();\n };\n\n duplex._final = function (callback) {\n if (ws.readyState === ws.CONNECTING) {\n ws.once('open', function open() {\n duplex._final(callback);\n });\n return;\n }\n\n // If the value of the `_socket` property is `null` it means that `ws` is a\n // client websocket and the handshake failed. In fact, when this happens, a\n // socket is never assigned to the websocket. Wait for the `'error'` event\n // that will be emitted by the websocket.\n if (ws._socket === null) return;\n\n if (ws._socket._writableState.finished) {\n callback();\n if (duplex._readableState.endEmitted) duplex.destroy();\n } else {\n ws._socket.once('finish', function finish() {\n // `duplex` is not destroyed here because the `'end'` event will be\n // emitted on `duplex` after this `'finish'` event. The EOF signaling\n // `null` chunk is, in fact, pushed when the websocket emits `'close'`.\n callback();\n });\n ws.close();\n }\n };\n\n duplex._read = function () {\n if (ws.isPaused) ws.resume();\n };\n\n duplex._write = function (chunk, encoding, callback) {\n if (ws.readyState === ws.CONNECTING) {\n ws.once('open', function open() {\n duplex._write(chunk, encoding, callback);\n });\n return;\n }\n\n ws.send(chunk, callback);\n };\n\n duplex.on('end', duplexOnEnd);\n duplex.on('error', duplexOnError);\n return duplex;\n}\n\nmodule.exports = createWebSocketStream;\n","'use strict';\n\nconst { tokenChars } = require('./validation');\n\n/**\n * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names.\n *\n * @param {String} header The field value of the header\n * @return {Set} The subprotocol names\n * @public\n */\nfunction parse(header) {\n const protocols = new Set();\n let start = -1;\n let end = -1;\n let i = 0;\n\n for (i; i < header.length; i++) {\n const code = header.charCodeAt(i);\n\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (\n i !== 0 &&\n (code === 0x20 /* ' ' */ || code === 0x09) /* '\\t' */\n ) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x2c /* ',' */) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n\n const protocol = header.slice(start, end);\n\n if (protocols.has(protocol)) {\n throw new SyntaxError(`The \"${protocol}\" subprotocol is duplicated`);\n }\n\n protocols.add(protocol);\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n }\n\n if (start === -1 || end !== -1) {\n throw new SyntaxError('Unexpected end of input');\n }\n\n const protocol = header.slice(start, i);\n\n if (protocols.has(protocol)) {\n throw new SyntaxError(`The \"${protocol}\" subprotocol is duplicated`);\n }\n\n protocols.add(protocol);\n return protocols;\n}\n\nmodule.exports = { parse };\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex$\", \"caughtErrors\": \"none\" }] */\n\n'use strict';\n\nconst EventEmitter = require('events');\nconst http = require('http');\nconst { Duplex } = require('stream');\nconst { createHash } = require('crypto');\n\nconst extension = require('./extension');\nconst PerMessageDeflate = require('./permessage-deflate');\nconst subprotocol = require('./subprotocol');\nconst WebSocket = require('./websocket');\nconst { CLOSE_TIMEOUT, GUID, kWebSocket } = require('./constants');\n\nconst keyRegex = /^[+/0-9A-Za-z]{22}==$/;\n\nconst RUNNING = 0;\nconst CLOSING = 1;\nconst CLOSED = 2;\n\n/**\n * Class representing a WebSocket server.\n *\n * @extends EventEmitter\n */\nclass WebSocketServer extends EventEmitter {\n /**\n * Create a `WebSocketServer` instance.\n *\n * @param {Object} options Configuration options\n * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether\n * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n * multiple times in the same tick\n * @param {Boolean} [options.autoPong=true] Specifies whether or not to\n * automatically send a pong in response to a ping\n * @param {Number} [options.backlog=511] The maximum length of the queue of\n * pending connections\n * @param {Boolean} [options.clientTracking=true] Specifies whether or not to\n * track clients\n * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to\n * wait for the closing handshake to finish after `websocket.close()` is\n * called\n * @param {Function} [options.handleProtocols] A hook to handle protocols\n * @param {String} [options.host] The hostname where to bind the server\n * @param {Number} [options.maxBufferedChunks=1048576] The maximum number of\n * buffered data chunks\n * @param {Number} [options.maxFragments=131072] The maximum number of message\n * fragments\n * @param {Number} [options.maxPayload=104857600] The maximum allowed message\n * size\n * @param {Boolean} [options.noServer=false] Enable no server mode\n * @param {String} [options.path] Accept only connections matching this path\n * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable\n * permessage-deflate\n * @param {Number} [options.port] The port where to bind the server\n * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S\n * server to use\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n * @param {Function} [options.verifyClient] A hook to reject connections\n * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`\n * class to use. It must be the `WebSocket` class or class that extends it\n * @param {Function} [callback] A listener for the `listening` event\n */\n constructor(options, callback) {\n super();\n\n options = {\n allowSynchronousEvents: true,\n autoPong: true,\n maxBufferedChunks: 1024 * 1024,\n maxFragments: 128 * 1024,\n maxPayload: 100 * 1024 * 1024,\n skipUTF8Validation: false,\n perMessageDeflate: false,\n handleProtocols: null,\n clientTracking: true,\n closeTimeout: CLOSE_TIMEOUT,\n verifyClient: null,\n noServer: false,\n backlog: null, // use default (511 as implemented in net.js)\n server: null,\n host: null,\n path: null,\n port: null,\n WebSocket,\n ...options\n };\n\n if (\n (options.port == null && !options.server && !options.noServer) ||\n (options.port != null && (options.server || options.noServer)) ||\n (options.server && options.noServer)\n ) {\n throw new TypeError(\n 'One and only one of the \"port\", \"server\", or \"noServer\" options ' +\n 'must be specified'\n );\n }\n\n if (options.port != null) {\n this._server = http.createServer((req, res) => {\n const body = http.STATUS_CODES[426];\n\n res.writeHead(426, {\n 'Content-Length': body.length,\n 'Content-Type': 'text/plain'\n });\n res.end(body);\n });\n this._server.listen(\n options.port,\n options.host,\n options.backlog,\n callback\n );\n } else if (options.server) {\n this._server = options.server;\n }\n\n if (this._server) {\n const emitConnection = this.emit.bind(this, 'connection');\n\n this._removeListeners = addListeners(this._server, {\n listening: this.emit.bind(this, 'listening'),\n error: this.emit.bind(this, 'error'),\n upgrade: (req, socket, head) => {\n this.handleUpgrade(req, socket, head, emitConnection);\n }\n });\n }\n\n if (options.perMessageDeflate === true) options.perMessageDeflate = {};\n if (options.clientTracking) {\n this.clients = new Set();\n this._shouldEmitClose = false;\n }\n\n this.options = options;\n this._state = RUNNING;\n }\n\n /**\n * Returns the bound address, the address family name, and port of the server\n * as reported by the operating system if listening on an IP socket.\n * If the server is listening on a pipe or UNIX domain socket, the name is\n * returned as a string.\n *\n * @return {(Object|String|null)} The address of the server\n * @public\n */\n address() {\n if (this.options.noServer) {\n throw new Error('The server is operating in \"noServer\" mode');\n }\n\n if (!this._server) return null;\n return this._server.address();\n }\n\n /**\n * Stop the server from accepting new connections and emit the `'close'` event\n * when all existing connections are closed.\n *\n * @param {Function} [cb] A one-time listener for the `'close'` event\n * @public\n */\n close(cb) {\n if (this._state === CLOSED) {\n if (cb) {\n this.once('close', () => {\n cb(new Error('The server is not running'));\n });\n }\n\n process.nextTick(emitClose, this);\n return;\n }\n\n if (cb) this.once('close', cb);\n\n if (this._state === CLOSING) return;\n this._state = CLOSING;\n\n if (this.options.noServer || this.options.server) {\n if (this._server) {\n this._removeListeners();\n this._removeListeners = this._server = null;\n }\n\n if (this.clients) {\n if (!this.clients.size) {\n process.nextTick(emitClose, this);\n } else {\n this._shouldEmitClose = true;\n }\n } else {\n process.nextTick(emitClose, this);\n }\n } else {\n const server = this._server;\n\n this._removeListeners();\n this._removeListeners = this._server = null;\n\n //\n // The HTTP/S server was created internally. Close it, and rely on its\n // `'close'` event.\n //\n server.close(() => {\n emitClose(this);\n });\n }\n }\n\n /**\n * See if a given request should be handled by this server instance.\n *\n * @param {http.IncomingMessage} req Request object to inspect\n * @return {Boolean} `true` if the request is valid, else `false`\n * @public\n */\n shouldHandle(req) {\n if (this.options.path) {\n const index = req.url.indexOf('?');\n const pathname = index !== -1 ? req.url.slice(0, index) : req.url;\n\n if (pathname !== this.options.path) return false;\n }\n\n return true;\n }\n\n /**\n * Handle a HTTP Upgrade request.\n *\n * @param {http.IncomingMessage} req The request object\n * @param {Duplex} socket The network socket between the server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Function} cb Callback\n * @public\n */\n handleUpgrade(req, socket, head, cb) {\n socket.on('error', socketOnError);\n\n const key = req.headers['sec-websocket-key'];\n const upgrade = req.headers.upgrade;\n const version = +req.headers['sec-websocket-version'];\n\n if (req.method !== 'GET') {\n const message = 'Invalid HTTP method';\n abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);\n return;\n }\n\n if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {\n const message = 'Invalid Upgrade header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n\n if (key === undefined || !keyRegex.test(key)) {\n const message = 'Missing or invalid Sec-WebSocket-Key header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n\n if (version !== 13 && version !== 8) {\n const message = 'Missing or invalid Sec-WebSocket-Version header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {\n 'Sec-WebSocket-Version': '13, 8'\n });\n return;\n }\n\n if (!this.shouldHandle(req)) {\n abortHandshake(socket, 400);\n return;\n }\n\n const secWebSocketProtocol = req.headers['sec-websocket-protocol'];\n let protocols = new Set();\n\n if (secWebSocketProtocol !== undefined) {\n try {\n protocols = subprotocol.parse(secWebSocketProtocol);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Protocol header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n }\n\n const secWebSocketExtensions = req.headers['sec-websocket-extensions'];\n const extensions = {};\n\n if (\n this.options.perMessageDeflate &&\n secWebSocketExtensions !== undefined\n ) {\n const perMessageDeflate = new PerMessageDeflate({\n ...this.options.perMessageDeflate,\n isServer: true,\n maxPayload: this.options.maxPayload\n });\n\n try {\n const offers = extension.parse(secWebSocketExtensions);\n\n if (offers[PerMessageDeflate.extensionName]) {\n perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);\n extensions[PerMessageDeflate.extensionName] = perMessageDeflate;\n }\n } catch (err) {\n const message =\n 'Invalid or unacceptable Sec-WebSocket-Extensions header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n }\n\n //\n // Optionally call external client verification handler.\n //\n if (this.options.verifyClient) {\n const info = {\n origin:\n req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],\n secure: !!(req.socket.authorized || req.socket.encrypted),\n req\n };\n\n if (this.options.verifyClient.length === 2) {\n this.options.verifyClient(info, (verified, code, message, headers) => {\n if (!verified) {\n return abortHandshake(socket, code || 401, message, headers);\n }\n\n this.completeUpgrade(\n extensions,\n key,\n protocols,\n req,\n socket,\n head,\n cb\n );\n });\n return;\n }\n\n if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);\n }\n\n this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);\n }\n\n /**\n * Upgrade the connection to WebSocket.\n *\n * @param {Object} extensions The accepted extensions\n * @param {String} key The value of the `Sec-WebSocket-Key` header\n * @param {Set} protocols The subprotocols\n * @param {http.IncomingMessage} req The request object\n * @param {Duplex} socket The network socket between the server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Function} cb Callback\n * @throws {Error} If called more than once with the same socket\n * @private\n */\n completeUpgrade(extensions, key, protocols, req, socket, head, cb) {\n //\n // Destroy the socket if the client has already sent a FIN packet.\n //\n if (!socket.readable || !socket.writable) return socket.destroy();\n\n if (socket[kWebSocket]) {\n throw new Error(\n 'server.handleUpgrade() was called more than once with the same ' +\n 'socket, possibly due to a misconfiguration'\n );\n }\n\n if (this._state > RUNNING) return abortHandshake(socket, 503);\n\n const digest = createHash('sha1')\n .update(key + GUID)\n .digest('base64');\n\n const headers = [\n 'HTTP/1.1 101 Switching Protocols',\n 'Upgrade: websocket',\n 'Connection: Upgrade',\n `Sec-WebSocket-Accept: ${digest}`\n ];\n\n const ws = new this.options.WebSocket(null, undefined, this.options);\n\n if (protocols.size) {\n //\n // Optionally call external protocol selection handler.\n //\n const protocol = this.options.handleProtocols\n ? this.options.handleProtocols(protocols, req)\n : protocols.values().next().value;\n\n if (protocol) {\n headers.push(`Sec-WebSocket-Protocol: ${protocol}`);\n ws._protocol = protocol;\n }\n }\n\n if (extensions[PerMessageDeflate.extensionName]) {\n const params = extensions[PerMessageDeflate.extensionName].params;\n const value = extension.format({\n [PerMessageDeflate.extensionName]: [params]\n });\n headers.push(`Sec-WebSocket-Extensions: ${value}`);\n ws._extensions = extensions;\n }\n\n //\n // Allow external modification/inspection of handshake headers.\n //\n this.emit('headers', headers, req);\n\n socket.write(headers.concat('\\r\\n').join('\\r\\n'));\n socket.removeListener('error', socketOnError);\n\n ws.setSocket(socket, head, {\n allowSynchronousEvents: this.options.allowSynchronousEvents,\n maxBufferedChunks: this.options.maxBufferedChunks,\n maxFragments: this.options.maxFragments,\n maxPayload: this.options.maxPayload,\n skipUTF8Validation: this.options.skipUTF8Validation\n });\n\n if (this.clients) {\n this.clients.add(ws);\n ws.on('close', () => {\n this.clients.delete(ws);\n\n if (this._shouldEmitClose && !this.clients.size) {\n process.nextTick(emitClose, this);\n }\n });\n }\n\n cb(ws, req);\n }\n}\n\nmodule.exports = WebSocketServer;\n\n/**\n * Add event listeners on an `EventEmitter` using a map of <event, listener>\n * pairs.\n *\n * @param {EventEmitter} server The event emitter\n * @param {Object.<String, Function>} map The listeners to add\n * @return {Function} A function that will remove the added listeners when\n * called\n * @private\n */\nfunction addListeners(server, map) {\n for (const event of Object.keys(map)) server.on(event, map[event]);\n\n return function removeListeners() {\n for (const event of Object.keys(map)) {\n server.removeListener(event, map[event]);\n }\n };\n}\n\n/**\n * Emit a `'close'` event on an `EventEmitter`.\n *\n * @param {EventEmitter} server The event emitter\n * @private\n */\nfunction emitClose(server) {\n server._state = CLOSED;\n server.emit('close');\n}\n\n/**\n * Handle socket errors.\n *\n * @private\n */\nfunction socketOnError() {\n this.destroy();\n}\n\n/**\n * Close the connection when preconditions are not fulfilled.\n *\n * @param {Duplex} socket The socket of the upgrade request\n * @param {Number} code The HTTP response status code\n * @param {String} [message] The HTTP response body\n * @param {Object} [headers] Additional HTTP response headers\n * @private\n */\nfunction abortHandshake(socket, code, message, headers) {\n //\n // The socket is writable unless the user destroyed or ended it before calling\n // `server.handleUpgrade()` or in the `verifyClient` function, which is a user\n // error. Handling this does not make much sense as the worst that can happen\n // is that some of the data written by the user might be discarded due to the\n // call to `socket.end()` below, which triggers an `'error'` event that in\n // turn causes the socket to be destroyed.\n //\n message = message || http.STATUS_CODES[code];\n headers = {\n Connection: 'close',\n 'Content-Type': 'text/html',\n 'Content-Length': Buffer.byteLength(message),\n ...headers\n };\n\n socket.once('finish', socket.destroy);\n\n socket.end(\n `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\\r\\n` +\n Object.keys(headers)\n .map((h) => `${h}: ${headers[h]}`)\n .join('\\r\\n') +\n '\\r\\n\\r\\n' +\n message\n );\n}\n\n/**\n * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least\n * one listener for it, otherwise call `abortHandshake()`.\n *\n * @param {WebSocketServer} server The WebSocket server\n * @param {http.IncomingMessage} req The request object\n * @param {Duplex} socket The socket of the upgrade request\n * @param {Number} code The HTTP response status code\n * @param {String} message The HTTP response body\n * @param {Object} [headers] The HTTP response headers\n * @private\n */\nfunction abortHandshakeOrEmitwsClientError(\n server,\n req,\n socket,\n code,\n message,\n headers\n) {\n if (server.listenerCount('wsClientError')) {\n const err = new Error(message);\n Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);\n\n server.emit('wsClientError', err, socket, req);\n } else {\n abortHandshake(socket, code, message, headers);\n }\n}\n","import createWebSocketStream from './lib/stream.js';\nimport extension from './lib/extension.js';\nimport PerMessageDeflate from './lib/permessage-deflate.js';\nimport Receiver from './lib/receiver.js';\nimport Sender from './lib/sender.js';\nimport subprotocol from './lib/subprotocol.js';\nimport WebSocket from './lib/websocket.js';\nimport WebSocketServer from './lib/websocket-server.js';\n\nexport {\n createWebSocketStream,\n extension,\n PerMessageDeflate,\n Receiver,\n Sender,\n subprotocol,\n WebSocket,\n WebSocketServer\n};\n\nexport default WebSocket;\n","/**\n * Adapter base for exposing Node `http.IncomingMessage` values as Effect HTTP\n * incoming messages.\n *\n * Server requests and Node client responses both arrive as Node readable\n * streams with raw header objects, socket metadata, and one-shot body\n * consumption. This module's `NodeHttpIncomingMessage` class keeps the original\n * Node message available while presenting Effect's `HttpIncomingMessage` shape:\n * typed headers, remote address lookup, stream access, and text, JSON,\n * URL-encoded, and array-buffer body readers.\n *\n * @since 4.0.0\n */\nimport * as Effect from \"effect/Effect\";\nimport * as Inspectable from \"effect/Inspectable\";\nimport * as Option from \"effect/Option\";\nimport * as Headers from \"effect/unstable/http/Headers\";\nimport * as IncomingMessage from \"effect/unstable/http/HttpIncomingMessage\";\nimport * as UrlParams from \"effect/unstable/http/UrlParams\";\nimport * as NodeStream from \"./NodeStream.js\";\n/**\n * Adapts a Node `IncomingMessage` to Effect HTTP incoming messages.\n *\n * **When to use**\n *\n * Use to implement Node HTTP request or response adapters that expose the\n * Effect HTTP incoming-message interface.\n *\n * **Details**\n *\n * The adapter exposes headers, remote address, stream access, and cached body\n * decoders. Subclasses provide the error mapping for unknown Node errors.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport class NodeHttpIncomingMessage extends Inspectable.Class {\n /**\n * Marks this value as an HTTP incoming message for runtime guards.\n *\n * @since 4.0.0\n */\n [IncomingMessage.TypeId];\n source;\n onError;\n remoteAddressOverride;\n constructor(source, onError, remoteAddressOverride) {\n super();\n this[IncomingMessage.TypeId] = IncomingMessage.TypeId;\n this.source = source;\n this.onError = onError;\n this.remoteAddressOverride = remoteAddressOverride;\n }\n get headers() {\n return Headers.fromInput(this.source.headers);\n }\n get remoteAddress() {\n return this.remoteAddressOverride ?? Option.fromNullishOr(this.source.socket.remoteAddress);\n }\n textEffect;\n get text() {\n if (this.textEffect) {\n return this.textEffect;\n }\n this.textEffect = Effect.runSync(Effect.cached(Effect.flatMap(IncomingMessage.MaxBodySize, maxBodySize => NodeStream.toString(() => this.source, {\n onError: this.onError,\n maxBytes: maxBodySize\n }))));\n this.arrayBufferEffect = Effect.map(this.textEffect, _ => new TextEncoder().encode(_).buffer);\n return this.textEffect;\n }\n get textUnsafe() {\n return Effect.runSync(this.text);\n }\n get json() {\n return Effect.flatMap(this.text, text => Effect.try({\n try: () => text === \"\" ? null : JSON.parse(text),\n catch: this.onError\n }));\n }\n get jsonUnsafe() {\n return Effect.runSync(this.json);\n }\n get urlParamsBody() {\n return Effect.flatMap(this.text, _ => Effect.try({\n try: () => UrlParams.fromInput(new URLSearchParams(_)),\n catch: this.onError\n }));\n }\n get stream() {\n return NodeStream.fromReadable({\n evaluate: () => this.source,\n onError: this.onError\n });\n }\n arrayBufferEffect;\n get arrayBuffer() {\n if (this.arrayBufferEffect) {\n return this.arrayBufferEffect;\n }\n this.arrayBufferEffect = Effect.withFiber(fiber => NodeStream.toArrayBuffer(() => this.source, {\n onError: this.onError,\n maxBytes: fiber.getRef(IncomingMessage.MaxBodySize)\n })).pipe(Effect.cached, Effect.runSync);\n this.textEffect = Effect.map(this.arrayBufferEffect, _ => new TextDecoder().decode(_));\n return this.arrayBufferEffect;\n }\n}\n//# sourceMappingURL=NodeHttpIncomingMessage.js.map","/**\n * Node.js implementation of the Effect HTTP platform service.\n *\n * This module connects the portable `HttpPlatform` file response helpers to\n * Node runtime primitives. It serves local files through Node readable streams,\n * supports byte ranges, converts Web `File` values to readable streams, and\n * fills in content type and content length headers when needed.\n *\n * @since 4.0.0\n */\nimport { pipe } from \"effect/Function\";\nimport * as Layer from \"effect/Layer\";\nimport * as EtagImpl from \"effect/unstable/http/Etag\";\nimport * as Headers from \"effect/unstable/http/Headers\";\nimport * as Platform from \"effect/unstable/http/HttpPlatform\";\nimport * as ServerResponse from \"effect/unstable/http/HttpServerResponse\";\nimport * as Fs from \"node:fs\";\nimport { Readable } from \"node:stream\";\nimport Mime from \"./Mime.js\";\nimport * as NodeFileSystem from \"./NodeFileSystem.js\";\n/**\n * Creates the Node `HttpPlatform`, serving file responses from Node readable\n * streams and adding MIME type and content-length headers when needed.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = /*#__PURE__*/Platform.make({\n fileResponse(path, status, statusText, headers, start, end, contentLength) {\n const stream = contentLength === 0 ? Readable.from([]) : Fs.createReadStream(path, {\n start,\n end: end === undefined ? undefined : end - 1\n });\n return ServerResponse.raw(stream, {\n headers: {\n ...headers,\n \"content-type\": headers[\"content-type\"] ?? Mime.getType(path) ?? \"application/octet-stream\",\n \"content-length\": contentLength.toString()\n },\n status,\n statusText\n });\n },\n fileWebResponse(file, status, statusText, headers, _options) {\n return ServerResponse.raw(Readable.fromWeb(file.stream()), {\n headers: Headers.merge(headers, Headers.fromRecordUnsafe({\n \"content-type\": headers[\"content-type\"] ?? Mime.getType(file.name) ?? \"application/octet-stream\",\n \"content-length\": file.size.toString()\n })),\n status,\n statusText\n });\n }\n});\n/**\n * Provides the Node `HttpPlatform` together with the filesystem and ETag\n * services it needs for file responses.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layer = /*#__PURE__*/pipe(/*#__PURE__*/Layer.effect(Platform.HttpPlatform)(make), /*#__PURE__*/Layer.provide(NodeFileSystem.layer), /*#__PURE__*/Layer.provide(EtagImpl.layer));\n//# sourceMappingURL=NodeHttpPlatform.js.map","import * as MP from \"./index.js\";\nimport { Duplex, Readable } from \"node:stream\";\nexport { decodeField } from \"./index.js\";\nexport class MultipastaStream extends Duplex {\n _parser;\n _canWrite = true;\n _writeCallback;\n constructor(config) {\n super({\n readableObjectMode: true\n });\n let currentError;\n let currentFile;\n this._parser = MP.make({\n ...config,\n onField: (info, value) => {\n if (currentError !== undefined) return;\n const field = {\n _tag: \"Field\",\n info,\n value\n };\n this.push(field);\n this.emit(\"field\", field);\n },\n onFile: info => {\n if (currentError !== undefined) return _ => {};\n const file = new FileStream(info, this);\n currentFile = file;\n this.push(file);\n this.emit(\"file\", file);\n return chunk => {\n this._canWrite = file.push(chunk);\n if (chunk === null && !this._canWrite) {\n currentFile = undefined;\n this._resume();\n }\n };\n },\n onError: error => {\n this.emit(\"error\", error);\n currentFile?.emit(\"error\", error);\n currentError = error;\n },\n onDone: () => {\n this.push(null);\n }\n });\n }\n _resume() {\n this._canWrite = true;\n if (this._writeCallback !== undefined) {\n const callback = this._writeCallback;\n this._writeCallback = undefined;\n callback();\n }\n }\n _read(_size) {}\n _write(chunk, encoding, callback) {\n this._parser.write(chunk instanceof Uint8Array ? chunk : Buffer.from(chunk, encoding));\n if (this._canWrite) {\n callback();\n } else {\n this._writeCallback = callback;\n }\n }\n _final(callback) {\n this._parser.end();\n callback();\n }\n}\nexport const make = config => new MultipastaStream(config);\nexport class FileStream extends Readable {\n info;\n _parent;\n _tag = \"File\";\n filename;\n constructor(info, _parent) {\n super();\n this.info = info;\n this._parent = _parent;\n this.filename = info.filename;\n }\n _read(_size) {\n if (this._parent._canWrite === false) {\n this._parent._resume();\n }\n }\n}\n//# sourceMappingURL=node.js.map","/**\n * Node.js multipart parsing for HTTP `multipart/form-data` request bodies.\n *\n * `NodeMultipart` adapts a Node `Readable` plus incoming HTTP headers into\n * Effect's shared multipart model. It can expose form parts as a stream or\n * collect a complete persisted form by writing file uploads to scoped temporary\n * files through the current `FileSystem` and `Path` services. `fileToReadable`\n * returns the underlying Node readable stream for file parts produced by this\n * parser.\n *\n * @since 4.0.0\n */\nimport * as Effect from \"effect/Effect\";\nimport * as Inspectable from \"effect/Inspectable\";\nimport * as Stream from \"effect/Stream\";\nimport * as Multipart from \"effect/unstable/http/Multipart\";\nimport * as MP from \"effect/unstable/http/Multipasta/Node\";\nimport * as NFS from \"node:fs\";\nimport * as NodeStreamP from \"node:stream/promises\";\nimport * as NodeStream from \"./NodeStream.js\";\n/**\n * Parses multipart data from a Node readable request body and headers into a\n * stream of `Multipart.Part` values, converting parser failures to\n * `MultipartError`.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const stream = (source, headers) => Multipart.makeConfig(headers).pipe(Effect.map(config => NodeStream.fromReadable({\n evaluate() {\n const parser = MP.make(config);\n source.pipe(parser);\n return parser;\n },\n onError: error => convertError(error)\n})), Stream.unwrap, Stream.map(convertPart));\n/**\n * Parses multipart data from a Node readable request body and persists file\n * parts using the current `FileSystem`, `Path`, and `Scope` services.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const persisted = (source, headers) => Multipart.toPersisted(stream(source, headers), (path, file) => Effect.tryPromise({\n try: signal => NodeStreamP.pipeline(file.file, NFS.createWriteStream(path), {\n signal\n }),\n catch: cause => Multipart.MultipartError.fromReason(\"InternalError\", cause)\n}));\n/**\n * Returns the underlying Node readable stream for a multipart file produced by\n * the Node multipart parser.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const fileToReadable = file => file.file;\n// -----------------------------------------------------------------------------\n// Internal\n// -----------------------------------------------------------------------------\nconst convertPart = part => part._tag === \"Field\" ? new FieldImpl(part.info, part.value) : new FileImpl(part);\nclass PartBase extends Inspectable.Class {\n [Multipart.TypeId];\n constructor() {\n super();\n this[Multipart.TypeId] = Multipart.TypeId;\n }\n}\nclass FieldImpl extends PartBase {\n _tag = \"Field\";\n key;\n contentType;\n value;\n constructor(info, value) {\n super();\n this.key = info.name;\n this.contentType = info.contentType;\n this.value = MP.decodeField(info, value);\n }\n toJSON() {\n return {\n _id: \"@effect/platform/Multipart/Part\",\n _tag: \"Field\",\n key: this.key,\n value: this.value,\n contentType: this.contentType\n };\n }\n}\nclass FileImpl extends PartBase {\n _tag = \"File\";\n key;\n name;\n contentType;\n content;\n contentEffect;\n file;\n constructor(file) {\n super();\n this.file = file;\n this.key = file.info.name;\n this.name = file.filename ?? file.info.name;\n this.contentType = file.info.contentType;\n this.content = NodeStream.fromReadable({\n evaluate: () => file,\n onError: cause => Multipart.MultipartError.fromReason(\"InternalError\", cause)\n });\n this.contentEffect = NodeStream.toUint8Array(() => file, {\n onError: cause => Multipart.MultipartError.fromReason(\"InternalError\", cause)\n });\n }\n toJSON() {\n return {\n _id: \"@effect/platform/Multipart/Part\",\n _tag: \"File\",\n key: this.key,\n name: this.name,\n contentType: this.contentType\n };\n }\n}\nfunction convertError(cause) {\n switch (cause._tag) {\n case \"ReachedLimit\":\n {\n switch (cause.limit) {\n case \"MaxParts\":\n {\n return Multipart.MultipartError.fromReason(\"TooManyParts\", cause);\n }\n case \"MaxFieldSize\":\n {\n return Multipart.MultipartError.fromReason(\"FieldTooLarge\", cause);\n }\n case \"MaxPartSize\":\n {\n return Multipart.MultipartError.fromReason(\"FileTooLarge\", cause);\n }\n case \"MaxTotalSize\":\n {\n return Multipart.MultipartError.fromReason(\"BodyTooLarge\", cause);\n }\n }\n }\n default:\n {\n return Multipart.MultipartError.fromReason(\"Parse\", cause);\n }\n }\n}\n//# sourceMappingURL=NodeMultipart.js.map","/**\n * Node.js implementation of the Effect `HttpServer`.\n *\n * This module adapts a supplied Node `http.Server` into Effect's\n * platform-independent HTTP server service. It starts the server with Node\n * `listen` options, converts `request` events into `HttpServerRequest` values,\n * writes `HttpServerResponse` bodies through Node's `ServerResponse`, and\n * handles `upgrade` events by exposing the upgraded socket through\n * `HttpServerRequest.upgrade`. It also exports request and upgrade handler\n * constructors plus layers for the server alone, HTTP support services, the\n * combined server, configurable options, and tests.\n *\n * @since 4.0.0\n */\nimport * as Cause from \"effect/Cause\";\nimport * as Config from \"effect/Config\";\nimport * as Context from \"effect/Context\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Fiber from \"effect/Fiber\";\nimport { flow } from \"effect/Function\";\nimport * as Latch from \"effect/Latch\";\nimport * as Layer from \"effect/Layer\";\nimport * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\nimport * as Cookies from \"effect/unstable/http/Cookies\";\nimport * as Etag from \"effect/unstable/http/Etag\";\nimport * as FetchHttpClient from \"effect/unstable/http/FetchHttpClient\";\nimport * as HttpEffect from \"effect/unstable/http/HttpEffect\";\nimport * as HttpIncomingMessage from \"effect/unstable/http/HttpIncomingMessage\";\nimport * as HttpServer from \"effect/unstable/http/HttpServer\";\nimport { causeResponse, ClientAbort, HttpServerError, RequestParseError, ResponseError, ServeError } from \"effect/unstable/http/HttpServerError\";\nimport * as Request from \"effect/unstable/http/HttpServerRequest\";\nimport { HttpServerRequest } from \"effect/unstable/http/HttpServerRequest\";\nimport * as Socket from \"effect/unstable/socket/Socket\";\nimport * as Http from \"node:http\";\nimport { Readable } from \"node:stream\";\nimport { pipeline } from \"node:stream/promises\";\nimport { NodeHttpIncomingMessage } from \"./NodeHttpIncomingMessage.js\";\nimport * as NodeHttpPlatform from \"./NodeHttpPlatform.js\";\nimport * as NodeMultipart from \"./NodeMultipart.js\";\nimport * as NodeServices from \"./NodeServices.js\";\nimport { NodeWS } from \"./NodeSocket.js\";\n/**\n * Creates a scoped `HttpServer` from a Node `http.Server`, starts listening\n * with the supplied options, registers request and upgrade handling, and closes\n * the server during scope finalization with optional graceful-shutdown control.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = /*#__PURE__*/Effect.fnUntraced(function* (evaluate, options) {\n const scope = yield* Effect.scope;\n const server = evaluate();\n const shutdown = yield* Effect.callback(resume => {\n if (!server.listening) {\n return resume(Effect.void);\n }\n server.close(error => {\n if (error) {\n resume(Effect.die(error));\n } else {\n resume(Effect.void);\n }\n });\n }).pipe(Effect.cached);\n const preemptiveShutdown = options.disablePreemptiveShutdown ? Effect.void : Effect.timeoutOrElse(shutdown, {\n duration: options.gracefulShutdownTimeout ?? Duration.seconds(20),\n orElse: () => Effect.void\n });\n yield* Scope.addFinalizer(scope, shutdown);\n yield* Effect.callback(resume => {\n function onError(cause) {\n resume(Effect.fail(new ServeError({\n cause\n })));\n }\n server.on(\"error\", onError);\n server.listen(options, () => {\n server.off(\"error\", onError);\n resume(Effect.void);\n });\n });\n const address = server.address();\n const wss = yield* Effect.acquireRelease(Effect.sync(() => new NodeWS.WebSocketServer({\n noServer: true\n })), wss => Effect.callback(resume => {\n wss.close(() => resume(Effect.void));\n })).pipe(Scope.provide(scope), Effect.cached);\n return HttpServer.make({\n address: typeof address === \"string\" ? {\n _tag: \"UnixAddress\",\n path: address\n } : {\n _tag: \"TcpAddress\",\n hostname: address.address === \"::\" ? \"0.0.0.0\" : address.address,\n port: address.port\n },\n serve: Effect.fnUntraced(function* (httpApp, middleware) {\n const serveScope = yield* Effect.scope;\n const scope = Scope.forkUnsafe(serveScope, \"parallel\");\n const handler = yield* makeHandler(httpApp, {\n middleware: middleware,\n scope\n });\n const upgradeHandler = yield* makeUpgradeHandler(wss, httpApp, {\n middleware: middleware,\n scope\n });\n yield* Scope.addFinalizerExit(serveScope, () => {\n server.off(\"request\", handler);\n server.off(\"upgrade\", upgradeHandler);\n return preemptiveShutdown;\n });\n server.on(\"request\", handler);\n server.on(\"upgrade\", upgradeHandler);\n })\n });\n});\n/**\n * Creates a Node `request` event handler for an Effect HTTP application,\n * injecting a `HttpServerRequest` and interrupting the request fiber if the\n * client closes the response before it finishes.\n *\n * @category handlers\n * @since 4.0.0\n */\nexport const makeHandler = (httpEffect, options) => {\n const handled = HttpEffect.toHandled(httpEffect, handleResponse, options.middleware);\n return Effect.withFiber(parent => {\n const services = parent.context;\n return Effect.succeed(function handler(nodeRequest, nodeResponse) {\n const map = new Map(services.mapUnsafe);\n map.set(HttpServerRequest.key, new ServerRequestImpl(nodeRequest, nodeResponse));\n const fiber = Fiber.runIn(Effect.runForkWith(Context.makeUnsafe(map))(handled), options.scope);\n nodeResponse.on(\"close\", () => {\n if (!nodeResponse.writableEnded) {\n fiber.interruptUnsafe(parent.id, ClientAbort.annotation);\n }\n });\n });\n });\n};\n/**\n * Creates a Node `upgrade` event handler for an Effect HTTP application,\n * exposing the upgraded WebSocket as the request's `upgrade` effect and\n * interrupting the request fiber when the socket closes early.\n *\n * @category handlers\n * @since 4.0.0\n */\nexport const makeUpgradeHandler = (lazyWss, httpEffect, options) => {\n const handledApp = HttpEffect.toHandled(httpEffect, handleResponse, options.middleware);\n return Effect.withFiber(parent => {\n const services = parent.context;\n return Effect.succeed(function handler(nodeRequest, socket, head) {\n let nodeResponse_ = undefined;\n const nodeResponse = () => {\n if (nodeResponse_ === undefined) {\n nodeResponse_ = new Http.ServerResponse(nodeRequest);\n nodeResponse_.assignSocket(socket);\n nodeResponse_.on(\"finish\", () => {\n socket.end();\n });\n }\n return nodeResponse_;\n };\n const upgradeEffect = Socket.fromWebSocket(Effect.flatMap(lazyWss, wss => Effect.acquireRelease(Effect.callback(resume => wss.handleUpgrade(nodeRequest, socket, head, ws => {\n resume(Effect.succeed(ws));\n })), ws => Effect.sync(() => ws.close()))));\n const map = new Map(services.mapUnsafe);\n map.set(HttpServerRequest.key, new ServerRequestImpl(nodeRequest, nodeResponse, upgradeEffect));\n const fiber = Fiber.runIn(Effect.runForkWith(Context.makeUnsafe(map))(handledApp), options.scope);\n socket.on(\"close\", () => {\n if (!socket.writableEnded) {\n fiber.interruptUnsafe(parent.id, ClientAbort.annotation);\n }\n });\n });\n });\n};\nclass ServerRequestImpl extends NodeHttpIncomingMessage {\n [Request.TypeId];\n response;\n upgradeEffect;\n url;\n headersOverride;\n constructor(source, response, upgradeEffect, url = source.url, headersOverride, remoteAddressOverride) {\n super(source, cause => new HttpServerError({\n reason: new RequestParseError({\n request: this,\n cause\n })\n }), remoteAddressOverride);\n this[Request.TypeId] = Request.TypeId;\n this.response = response;\n this.upgradeEffect = upgradeEffect;\n this.url = url;\n this.headersOverride = headersOverride;\n }\n cachedCookies;\n get cookies() {\n if (this.cachedCookies) {\n return this.cachedCookies;\n }\n return this.cachedCookies = Cookies.parseHeader(this.headers.cookie ?? \"\");\n }\n get resolvedResponse() {\n return typeof this.response === \"function\" ? this.response() : this.response;\n }\n modify(options) {\n return new ServerRequestImpl(this.source, this.response, this.upgradeEffect, options.url ?? this.url, options.headers ?? this.headersOverride, \"remoteAddress\" in options ? options.remoteAddress : this.remoteAddressOverride);\n }\n get originalUrl() {\n return this.source.url;\n }\n get method() {\n return this.source.method.toUpperCase();\n }\n get headers() {\n this.headersOverride ??= this.source.headers;\n return this.headersOverride;\n }\n multipartEffect;\n get multipart() {\n if (this.multipartEffect) {\n return this.multipartEffect;\n }\n this.multipartEffect = Effect.runSync(Effect.cached(NodeMultipart.persisted(this.source, this.source.headers)));\n return this.multipartEffect;\n }\n get multipartStream() {\n return NodeMultipart.stream(this.source, this.source.headers);\n }\n get upgrade() {\n return this.upgradeEffect ?? Effect.fail(new HttpServerError({\n reason: new RequestParseError({\n request: this,\n description: \"not an upgradeable ServerRequest\"\n })\n }));\n }\n toString() {\n return `ServerRequest(${this.method} ${this.url})`;\n }\n toJSON() {\n return HttpIncomingMessage.inspect(this, {\n _id: \"HttpServerRequest\",\n method: this.method,\n url: this.originalUrl\n });\n }\n}\n/**\n * Provides an `HttpServer` by creating and managing a scoped Node\n * `http.Server` with the supplied listen and shutdown options.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerServer = /*#__PURE__*/flow(make, /*#__PURE__*/Layer.effect(HttpServer.HttpServer));\n/**\n * Provides the Node HTTP support services used by `NodeHttpServer`, including\n * the HTTP platform, ETag generator, and core Node platform services.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerHttpServices = /*#__PURE__*/Layer.mergeAll(NodeHttpPlatform.layer, Etag.layerWeak, NodeServices.layer);\n/**\n * Provides a Node `HttpServer` together with the Node HTTP platform, ETag, and\n * core platform services required to serve requests.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layer = (evaluate, options) => Layer.mergeAll(layerServer(evaluate, options), layerHttpServices);\n/**\n * Provides a Node `HttpServer` together with the Node HTTP platform, ETag,\n * and core Node platform services, reading the listen and shutdown options from\n * a `Config` value.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerConfig = (evaluate, options) => Layer.mergeAll(Layer.effect(HttpServer.HttpServer)(Effect.flatMap(Config.unwrap(options), options => make(evaluate, options))), layerHttpServices);\n/**\n * Provides a test HTTP server listening on an ephemeral port together with a\n * Fetch-backed `HttpClient` configured for server integration tests.\n *\n * @category testing\n * @since 4.0.0\n */\nexport const layerTest = /*#__PURE__*/HttpServer.layerTestClient.pipe(/*#__PURE__*/Layer.provide(/*#__PURE__*/Layer.fresh(FetchHttpClient.layer).pipe(/*#__PURE__*/Layer.provide(/*#__PURE__*/Layer.succeed(FetchHttpClient.RequestInit)({\n keepalive: false\n})))), /*#__PURE__*/Layer.provideMerge(/*#__PURE__*/layer(Http.createServer, {\n port: 0\n})));\n// -----------------------------------------------------------------------------\n// Internal\n// -----------------------------------------------------------------------------\nconst handleResponse = (request, response) => {\n const nodeResponse = request.resolvedResponse;\n if (nodeResponse.writableEnded) {\n return Effect.void;\n }\n let headers = response.headers;\n if (!Cookies.isEmpty(response.cookies)) {\n headers = {\n ...headers\n };\n const toSet = Cookies.toSetCookieHeaders(response.cookies);\n if (headers[\"set-cookie\"] !== undefined) {\n toSet.push(headers[\"set-cookie\"]);\n }\n headers[\"set-cookie\"] = toSet;\n }\n if (request.method === \"HEAD\") {\n nodeResponse.writeHead(response.status, headers);\n return Effect.callback(resume => {\n nodeResponse.end(() => resume(Effect.void));\n });\n }\n const body = response.body;\n switch (body._tag) {\n case \"Empty\":\n {\n nodeResponse.writeHead(response.status, headers);\n nodeResponse.end();\n return Effect.void;\n }\n case \"Raw\":\n {\n nodeResponse.writeHead(response.status, headers);\n if (typeof body.body === \"object\" && body.body !== null && \"pipe\" in body.body && typeof body.body.pipe === \"function\") {\n return Effect.tryPromise({\n try: signal => pipeline(body.body, nodeResponse, {\n signal,\n end: true\n }),\n catch: cause => new HttpServerError({\n reason: new ResponseError({\n request,\n response,\n description: \"Error writing raw response\",\n cause\n })\n })\n }).pipe(Effect.interruptible, Effect.tapCause(handleCause(nodeResponse, response)));\n }\n return Effect.callback(resume => {\n nodeResponse.end(body.body, () => resume(Effect.void));\n });\n }\n case \"Uint8Array\":\n {\n nodeResponse.writeHead(response.status, headers);\n // If the body is less than 1MB, we skip the callback\n if (body.body.length < 1024 * 1024) {\n nodeResponse.end(body.body);\n return Effect.void;\n }\n return Effect.callback(resume => {\n nodeResponse.end(body.body, () => resume(Effect.void));\n });\n }\n case \"FormData\":\n {\n return Effect.suspend(() => {\n const r = new globalThis.Response(body.formData);\n nodeResponse.writeHead(response.status, {\n ...headers,\n ...Object.fromEntries(r.headers)\n });\n return Effect.callback((resume, signal) => {\n Readable.fromWeb(r.body, {\n signal\n }).pipe(nodeResponse).on(\"error\", cause => {\n resume(Effect.fail(new HttpServerError({\n reason: new ResponseError({\n request,\n response,\n description: \"Error writing FormData response\",\n cause\n })\n })));\n }).once(\"finish\", () => {\n resume(Effect.void);\n });\n }).pipe(Effect.interruptible, Effect.tapCause(handleCause(nodeResponse, response)));\n });\n }\n case \"Stream\":\n {\n nodeResponse.writeHead(response.status, headers);\n const drainLatch = Latch.makeUnsafe();\n nodeResponse.on(\"drain\", () => drainLatch.openUnsafe());\n return body.stream.pipe(Stream.orDie, Stream.runForEachArray(array => {\n let needDrain = false;\n for (let i = 0; i < array.length; i++) {\n const written = nodeResponse.write(array[i]);\n if (!written && !needDrain) {\n needDrain = true;\n drainLatch.closeUnsafe();\n } else if (written && needDrain) {\n needDrain = false;\n }\n }\n if (!needDrain) return Effect.void;\n return drainLatch.await;\n }), Effect.interruptible, Effect.matchCauseEffect({\n onSuccess: () => Effect.sync(() => nodeResponse.end()),\n onFailure: handleCause(nodeResponse, response)\n }));\n }\n }\n};\nconst handleCause = (nodeResponse, originalResponse) => originalCause => Effect.flatMap(causeResponse(originalCause), ([response, cause]) => {\n const headersSent = nodeResponse.headersSent;\n if (!headersSent) {\n nodeResponse.writeHead(response.status);\n }\n if (!nodeResponse.writableEnded) {\n nodeResponse.end();\n }\n return Effect.failCause(headersSent ? Cause.combine(originalCause, Cause.die(originalResponse)) : cause);\n});\n//# sourceMappingURL=NodeHttpServer.js.map","import * as Effect from \"../../Effect.js\";\nimport { identity } from \"../../Function.js\";\nimport * as Predicate from \"../../Predicate.js\";\nimport * as Schema from \"../../Schema.js\";\nimport * as SchemaTransformation from \"../../SchemaTransformation.js\";\nconst PartTypeId = \"~effect/ai/Content/Part\";\n// =============================================================================\n// All Parts\n// =============================================================================\n/**\n * Type guard to check if a value is a Response Part.\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isPart = u => Predicate.hasProperty(u, PartTypeId);\n/**\n * Creates a Schema for all response parts based on a toolkit.\n *\n * **Details**\n *\n * Generates a schema that includes all possible response parts, with tool call\n * and tool result parts dynamically created based on the provided toolkit.\n *\n * **Example** (Building a response parts schema)\n *\n * ```ts\n * import { Schema } from \"effect\"\n * import { Response, Tool, Toolkit } from \"effect/unstable/ai\"\n *\n * const myToolkit = Toolkit.make(\n * Tool.make(\"GetWeather\", {\n * parameters: Schema.Struct({ city: Schema.String }),\n * success: Schema.Struct({ temperature: Schema.Number })\n * })\n * )\n *\n * const allPartsSchema = Response.AllParts(myToolkit)\n * ```\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const AllParts = toolkit => {\n const toolCalls = [];\n const toolResults = [];\n for (const tool of Object.values(toolkit.tools)) {\n const toolCall = ToolCallPart(tool.name, tool.parametersSchema);\n const toolResult = ToolResultPart(tool.name, tool.successSchema, tool.failureSchema);\n toolCalls.push(toolCall);\n toolResults.push(toolResult);\n }\n return Schema.Union([TextPart, TextStartPart, TextDeltaPart, TextEndPart, ReasoningPart, ReasoningStartPart, ReasoningDeltaPart, ReasoningEndPart, ToolParamsStartPart, ToolParamsDeltaPart, ToolParamsEndPart, ToolApprovalRequestPart, FilePart, DocumentSourcePart, UrlSourcePart, ResponseMetadataPart, FinishPart, ErrorPart, ...toolCalls, ...toolResults]);\n};\n/**\n * Creates a Schema for non-streaming response parts based on a toolkit.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const Part = toolkit => {\n const toolCalls = [];\n const toolResults = [];\n for (const tool of Object.values(toolkit.tools)) {\n const toolCall = ToolCallPart(tool.name, tool.parametersSchema);\n const toolResult = ToolResultPart(tool.name, tool.successSchema, tool.failureSchema);\n toolCalls.push(toolCall);\n toolResults.push(toolResult);\n }\n return Schema.Union([TextPart, ReasoningPart, ToolApprovalRequestPart, FilePart, DocumentSourcePart, UrlSourcePart, ResponseMetadataPart, FinishPart, ...toolCalls, ...toolResults]);\n};\n/**\n * Creates a Schema for streaming response parts based on a toolkit.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const StreamPart = toolkit => {\n const toolCalls = [];\n const toolResults = [];\n for (const tool of Object.values(toolkit.tools)) {\n const toolCall = ToolCallPart(tool.name, tool.parametersSchema);\n const toolResult = ToolResultPart(tool.name, tool.successSchema, tool.failureSchema);\n toolCalls.push(toolCall);\n toolResults.push(toolResult);\n }\n return Schema.Union([TextStartPart, TextDeltaPart, TextEndPart, ReasoningStartPart, ReasoningDeltaPart, ReasoningEndPart, ToolParamsStartPart, ToolParamsDeltaPart, ToolParamsEndPart, ToolApprovalRequestPart, FilePart, DocumentSourcePart, UrlSourcePart, ResponseMetadataPart, FinishPart, ErrorPart, ...toolCalls, ...toolResults]);\n};\n// =============================================================================\n// Base Part\n// =============================================================================\n/**\n * Schema for provider-specific metadata attached to response parts,\n * represented as a record from provider-specific keys to JSON values or `null`.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const ProviderMetadata = /*#__PURE__*/Schema.Record(Schema.String, /*#__PURE__*/Schema.NullOr(Schema.Json));\nconst BasePart = /*#__PURE__*/Schema.Struct({\n [PartTypeId]: /*#__PURE__*/Schema.tag(PartTypeId).pipe(/*#__PURE__*/Schema.withDecodingDefaultKey(/*#__PURE__*/Effect.succeed(PartTypeId), {\n encodingStrategy: \"omit\"\n })),\n metadata: /*#__PURE__*/ProviderMetadata.pipe(/*#__PURE__*/Schema.withDecodingDefault(/*#__PURE__*/Effect.succeed({})))\n});\n/**\n * Creates a new response content part of the specified type.\n *\n * **Example** (Creating response content parts)\n *\n * ```ts\n * import { Response } from \"effect/unstable/ai\"\n *\n * const textPart = Response.makePart(\"text\", {\n * text: \"Hello, world!\"\n * })\n *\n * const toolCallPart = Response.makePart(\"tool-call\", {\n * id: \"call_123\",\n * name: \"get_weather\",\n * params: { city: \"San Francisco\" },\n * providerExecuted: false\n * })\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const makePart = (\n/**\n * The type of part to create.\n */\ntype,\n/**\n * Parameters specific to the part type being created.\n */\nparams) => ({\n ...params,\n [PartTypeId]: PartTypeId,\n type,\n metadata: params.metadata ?? {}\n});\n/**\n * Schema for validation and encoding of text parts.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const TextPart = /*#__PURE__*/Schema.Struct({\n ...BasePart.fields,\n type: Schema.tag(\"text\"),\n text: Schema.String\n}).annotate({\n identifier: \"TextPart\"\n});\n/**\n * Schema for validation and encoding of text start parts.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const TextStartPart = /*#__PURE__*/Schema.Struct({\n ...BasePart.fields,\n type: Schema.tag(\"text-start\"),\n id: Schema.String\n}).annotate({\n identifier: \"TextStartPart\"\n});\n/**\n * Schema for validation and encoding of text delta parts.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const TextDeltaPart = /*#__PURE__*/Schema.Struct({\n ...BasePart.fields,\n type: Schema.tag(\"text-delta\"),\n id: Schema.String,\n delta: Schema.String\n}).annotate({\n identifier: \"TextDeltaPart\"\n});\n/**\n * Schema for validation and encoding of text end parts.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const TextEndPart = /*#__PURE__*/Schema.Struct({\n ...BasePart.fields,\n type: Schema.tag(\"text-end\"),\n id: Schema.String\n}).annotate({\n identifier: \"TextEndPart\"\n});\n/**\n * Schema for validation and encoding of reasoning parts.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const ReasoningPart = /*#__PURE__*/Schema.Struct({\n ...BasePart.fields,\n type: Schema.tag(\"reasoning\"),\n text: Schema.String\n}).annotate({\n identifier: \"ReasoningPart\"\n});\n/**\n * Schema for validation and encoding of reasoning start parts.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const ReasoningStartPart = /*#__PURE__*/Schema.Struct({\n ...BasePart.fields,\n type: Schema.tag(\"reasoning-start\"),\n id: Schema.String\n}).annotate({\n identifier: \"ReasoningStartPart\"\n});\n/**\n * Schema for validation and encoding of reasoning delta parts.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const ReasoningDeltaPart = /*#__PURE__*/Schema.Struct({\n ...BasePart.fields,\n type: Schema.tag(\"reasoning-delta\"),\n id: Schema.String,\n delta: Schema.String\n}).annotate({\n identifier: \"ReasoningDeltaPart\"\n});\n/**\n * Schema for validation and encoding of reasoning end parts.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const ReasoningEndPart = /*#__PURE__*/Schema.Struct({\n ...BasePart.fields,\n type: Schema.tag(\"reasoning-end\"),\n id: Schema.String\n}).annotate({\n identifier: \"ReasoningEndPart\"\n});\n/**\n * Schema for validation and encoding of tool params start parts.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const ToolParamsStartPart = /*#__PURE__*/Schema.Struct({\n ...BasePart.fields,\n type: Schema.tag(\"tool-params-start\"),\n id: Schema.String,\n name: Schema.String,\n providerExecuted: Schema.Boolean.pipe(Schema.withDecodingDefaultKey(Effect.succeed(false)))\n}).annotate({\n identifier: \"ToolParamsStartPart\"\n});\n/**\n * Schema for validation and encoding of tool params delta parts.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const ToolParamsDeltaPart = /*#__PURE__*/Schema.Struct({\n ...BasePart.fields,\n type: Schema.tag(\"tool-params-delta\"),\n id: Schema.String,\n delta: Schema.String\n}).annotate({\n identifier: \"ToolParamsDeltaPart\"\n});\n/**\n * Schema for validation and encoding of tool params end parts.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const ToolParamsEndPart = /*#__PURE__*/Schema.Struct({\n ...BasePart.fields,\n type: Schema.tag(\"tool-params-end\"),\n id: Schema.String\n}).annotate({\n identifier: \"ToolParamsEndPart\"\n});\n/**\n * Creates a Schema for tool call parts with specific tool name and parameters.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const ToolCallPart = (name, params) => Schema.Struct({\n ...BasePart.fields,\n type: Schema.Literal(\"tool-call\"),\n id: Schema.String,\n name: Schema.Literal(name),\n params,\n providerExecuted: Schema.Boolean.pipe(Schema.withDecodingDefaultKey(Effect.succeed(false)))\n}).annotate({\n identifier: \"ToolCallPart\"\n});\n/**\n * Constructs a new tool call part.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const toolCallPart = params => makePart(\"tool-call\", params);\n/**\n * Creates a Schema for tool result parts with specific tool name and result type.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const ToolResultPart = (name, success, failure) => {\n const ResultSchema = Schema.Union([success, failure]);\n const Common = {\n id: Schema.String,\n type: Schema.Literal(\"tool-result\"),\n isFailure: Schema.Boolean,\n name: Schema.Literal(name)\n };\n const Decoded = Schema.Struct({\n ...Common,\n [PartTypeId]: Schema.Literal(PartTypeId),\n result: ResultSchema,\n providerExecuted: Schema.Boolean,\n metadata: ProviderMetadata,\n encodedResult: Schema.toEncoded(ResultSchema),\n preliminary: Schema.Boolean\n });\n const Encoded = Schema.Struct({\n ...Common,\n result: Schema.toEncoded(ResultSchema),\n providerExecuted: Schema.optional(Schema.Boolean),\n metadata: Schema.optional(ProviderMetadata),\n preliminary: Schema.optional(Schema.Boolean)\n });\n return Decoded.pipe(Schema.encodeTo(Encoded, SchemaTransformation.transform({\n decode: encoded => ({\n ...encoded,\n [PartTypeId]: PartTypeId,\n providerExecuted: encoded.providerExecuted ?? false,\n metadata: encoded.metadata ?? {},\n encodedResult: encoded.result,\n preliminary: encoded.preliminary ?? false\n }),\n encode: identity\n }))).annotate({\n identifier: `ToolResultPart(${name})`\n });\n};\n/**\n * Constructs a new tool result part.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const toolResultPart = params => makePart(\"tool-result\", params);\n/**\n * Schema for validation and encoding of tool approval request parts.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const ToolApprovalRequestPart = /*#__PURE__*/Schema.Struct({\n ...BasePart.fields,\n type: Schema.tag(\"tool-approval-request\"),\n approvalId: Schema.String,\n toolCallId: Schema.String\n}).annotate({\n identifier: \"ToolApprovalRequestPart\"\n});\n/**\n * Constructs a new tool approval request part.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const toolApprovalRequestPart = params => makePart(\"tool-approval-request\", params);\n/**\n * Schema for validation and encoding of file parts.\n *\n * **Details**\n *\n * Decoded `data` is a `Uint8Array`; encoded `data` is a base64 string through\n * `Schema.Uint8ArrayFromBase64`.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const FilePart = /*#__PURE__*/Schema.Struct({\n ...BasePart.fields,\n type: Schema.tag(\"file\"),\n mediaType: Schema.String,\n data: Schema.Uint8ArrayFromBase64\n}).annotate({\n identifier: \"FilePart\"\n});\n/**\n * Schema for validation and encoding of document source parts.\n *\n * **When to use**\n *\n * Use to validate or encode document source references returned as response\n * content parts.\n *\n * **Details**\n *\n * Validates `type: \"source\"`, `sourceType: \"document\"`, required `id`,\n * `mediaType`, and `title`, optional `fileName`, and the metadata fields\n * inherited from response parts.\n *\n * @see {@link UrlSourcePart} for URL source references\n * @see {@link DocumentSourcePartEncoded} for the encoded document source representation\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const DocumentSourcePart = /*#__PURE__*/Schema.Struct({\n ...BasePart.fields,\n type: Schema.tag(\"source\"),\n sourceType: Schema.tag(\"document\"),\n id: Schema.String,\n mediaType: Schema.String,\n title: Schema.String,\n fileName: Schema.optionalKey(Schema.String)\n}).annotate({\n identifier: \"DocumentSourcePart\"\n});\n/**\n * Schema for validation and encoding of url source parts.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const UrlSourcePart = /*#__PURE__*/Schema.Struct({\n ...BasePart.fields,\n type: Schema.tag(\"source\"),\n sourceType: Schema.tag(\"url\"),\n id: Schema.String,\n url: Schema.URLFromString,\n title: Schema.String\n}).annotate({\n identifier: \"UrlSourcePart\"\n});\n// =============================================================================\n// HTTP Details\n// =============================================================================\n/**\n * Schema for HTTP request details associated with an AI response.\n *\n * **Details**\n *\n * Captures comprehensive information about the HTTP request made to the\n * AI provider, enabling inspection of request metadata for debugging and\n * observability purposes.\n *\n * **Example** (Describing an HTTP request)\n *\n * ```ts\n * import type { Response } from \"effect/unstable/ai\"\n *\n * const requestDetails: typeof Response.HttpRequestDetails.Type = {\n * method: \"POST\",\n * url: \"https://api.openai.com/v1/responses\",\n * urlParams: [],\n * hash: undefined,\n * headers: { \"Content-Type\": \"application/json\" }\n * }\n * ```\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const HttpRequestDetails = /*#__PURE__*/Schema.Struct({\n method: Schema.Literals([\"GET\", \"POST\", \"PATCH\", \"PUT\", \"DELETE\", \"HEAD\", \"OPTIONS\", \"TRACE\"]),\n url: Schema.String,\n urlParams: Schema.Array(Schema.Tuple([Schema.String, Schema.String])),\n hash: Schema.UndefinedOr(Schema.String),\n headers: Schema.Record(Schema.String, Schema.Union([Schema.String, Schema.Redacted(Schema.String)]))\n}).annotate({\n identifier: \"HttpRequestDetails\"\n});\n/**\n * Schema for HTTP response details associated with an AI response.\n *\n * **Details**\n *\n * Captures essential information about the HTTP response received from\n * the AI provider, including status codes and headers for debugging and\n * observability purposes.\n *\n * **Example** (Describing an HTTP response)\n *\n * ```ts\n * import type { Response } from \"effect/unstable/ai\"\n *\n * const responseDetails: typeof Response.HttpResponseDetails.Type = {\n * status: 200,\n * headers: {\n * \"Content-Type\": \"application/json\",\n * \"X-Request-Id\": \"req_abc123\"\n * }\n * }\n * ```\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const HttpResponseDetails = /*#__PURE__*/Schema.Struct({\n status: Schema.Number,\n headers: Schema.Record(Schema.String, Schema.Union([Schema.String, Schema.Redacted(Schema.String)]))\n}).annotate({\n identifier: \"HttpResponseDetails\"\n});\n/**\n * Schema for validation and encoding of response metadata parts.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const ResponseMetadataPart = /*#__PURE__*/Schema.Struct({\n ...BasePart.fields,\n type: Schema.tag(\"response-metadata\"),\n id: Schema.UndefinedOr(Schema.String),\n modelId: Schema.UndefinedOr(Schema.String),\n timestamp: Schema.UndefinedOr(Schema.DateTimeUtcFromString),\n request: Schema.UndefinedOr(HttpRequestDetails)\n}).annotate({\n identifier: \"ResponseMetadataPart\"\n});\n// =============================================================================\n// Finish Part\n// =============================================================================\n/**\n * Represents the reason why a model finished generation of a response.\n *\n * **Details**\n *\n * Possible finish reasons:\n * - `\"stop\"`: The model generated a stop sequence.\n * - `\"length\"`: The model exceeded its token budget.\n * - `\"content-filter\"`: The model generated content which violated a content filter.\n * - `\"tool-calls\"`: The model triggered a tool call.\n * - `\"error\"`: The model encountered an error.\n * - `\"pause\"`: The model requested to pause execution.\n * - `\"other\"`: The model stopped for a reason not supported by this protocol.\n * - `\"unknown\"`: The model did not specify a finish reason.\n *\n * @category models\n * @since 4.0.0\n */\nexport const FinishReason = /*#__PURE__*/Schema.Literals([\"stop\", \"length\", \"content-filter\", \"tool-calls\", \"error\", \"pause\", \"other\", \"unknown\"]);\n/**\n * Represents usage information for a request to a large language model provider.\n *\n * **Details**\n *\n * If the model provider returns additional usage information than what is\n * specified here, you can generally find that information under the provider\n * metadata of the finish part of the response.\n *\n * @category models\n * @since 4.0.0\n */\nexport class Usage extends /*#__PURE__*/Schema.Class(\"effect/ai/AiResponse/Usage\")({\n /**\n * Information about input (i.e. prompt) token utilization.\n */\n inputTokens: /*#__PURE__*/Schema.Struct({\n /**\n * The number of non-cached input (i.e. prompt) tokens used.\n */\n uncached: /*#__PURE__*/Schema.UndefinedOr(Schema.Number),\n /**\n * The total of number of input (i.e. prompt) tokens used.\n */\n total: /*#__PURE__*/Schema.UndefinedOr(Schema.Number),\n /**\n * The number of cached input (i.e. prompt) tokens read.\n */\n cacheRead: /*#__PURE__*/Schema.UndefinedOr(Schema.Number),\n /**\n * The number of cached input (i.e. prompt) tokens written.\n */\n cacheWrite: /*#__PURE__*/Schema.UndefinedOr(Schema.Number)\n }),\n /**\n * Information about the output (i.e. response) tokens used.\n */\n outputTokens: /*#__PURE__*/Schema.Struct({\n /**\n * The total of number of output (i.e. response) tokens used.\n */\n total: /*#__PURE__*/Schema.UndefinedOr(Schema.Number),\n /**\n * The number of text tokens used.\n */\n text: /*#__PURE__*/Schema.UndefinedOr(Schema.Number),\n /**\n * The number of reasoning tokens used.\n */\n reasoning: /*#__PURE__*/Schema.UndefinedOr(Schema.Number)\n })\n}) {}\n/**\n * Schema for finish response parts.\n *\n * **Details**\n *\n * Validates `type: \"finish\"`, `reason` through `FinishReason`, `usage`\n * through `Usage`, and optional provider HTTP response details.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const FinishPart = /*#__PURE__*/Schema.Struct({\n ...BasePart.fields,\n type: Schema.tag(\"finish\"),\n reason: FinishReason,\n usage: Usage,\n response: Schema.UndefinedOr(HttpResponseDetails)\n}).annotate({\n identifier: \"FinishPart\"\n});\n/**\n * Schema for validation and encoding of error parts.\n *\n * **Details**\n *\n * Validates and encodes error parts with `type: \"error\"` and an `error` payload\n * kept as `unknown`.\n *\n * **Gotchas**\n *\n * The decoded `error` value is not guaranteed to be an `Error`; narrow it before\n * reading `Error`-specific fields.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const ErrorPart = /*#__PURE__*/Schema.Struct({\n ...BasePart.fields,\n type: Schema.tag(\"error\"),\n error: Schema.Unknown\n}).annotate({\n identifier: \"ErrorPart\"\n});\n//# sourceMappingURL=Response.js.map","/**\n * Defines shared errors for AI operations.\n *\n * `AiError` records where a failure happened and stores the detailed reason in a\n * `reason` field. Those reasons cover transport problems, provider responses,\n * rate limits, authentication, content policy failures, invalid requests,\n * invalid output, unsupported schemas, tool failures, invalid user input, and\n * unknown failures. This module also includes metadata schemas, guards,\n * constructors, and helpers for converting HTTP response information into AI\n * error reasons.\n *\n * @since 4.0.0\n */\nimport * as Duration from \"../../Duration.js\";\nimport * as Effect from \"../../Effect.js\";\nimport * as Option from \"../../Option.js\";\nimport * as Predicate from \"../../Predicate.js\";\nimport { redact } from \"../../Redactable.js\";\nimport * as Redacted from \"../../Redacted.js\";\nimport * as Schema from \"../../Schema.js\";\nimport { HttpRequestDetails, HttpResponseDetails } from \"./Response.js\";\nconst ReasonTypeId = \"~effect/unstable/ai/AiError/Reason\";\nconst providerMetadataWithDefaults = () => ProviderMetadata.pipe(Schema.withConstructorDefault(Effect.succeed({})), Schema.withDecodingDefault(Effect.succeed({})));\nconst redactHeaders = headers => {\n const redacted = redact(headers);\n const result = {};\n for (const key in redacted) {\n const value = redacted[key];\n result[key] = Redacted.isRedacted(value) ? value.toString() : value;\n }\n return result;\n};\n// =============================================================================\n// Http Request Error\n// =============================================================================\n/**\n * Error indicating a network-level failure before receiving a response.\n *\n * **Details**\n *\n * This error is raised when issues arise before receiving an HTTP response,\n * such as network connectivity problems, request encoding issues, or invalid\n * URLs.\n *\n * **Example** (Creating a network error)\n *\n * ```ts\n * import { AiError } from \"effect/unstable/ai\"\n *\n * const error = new AiError.NetworkError({\n * reason: \"TransportError\",\n * request: {\n * method: \"POST\",\n * url: \"https://api.openai.com/v1/completions\",\n * urlParams: [],\n * hash: undefined,\n * headers: { \"Content-Type\": \"application/json\" }\n * },\n * description: \"Connection timeout after 30 seconds\"\n * })\n *\n * console.log(error.isRetryable) // true\n * console.log(error.message)\n * // \"Transport: Connection timeout after 30 seconds (POST https://api.openai.com/v1/completions)\"\n * ```\n *\n * @category reason\n * @since 4.0.0\n */\nexport class NetworkError extends /*#__PURE__*/Schema.ErrorClass(\"effect/ai/AiError/NetworkError\")({\n _tag: /*#__PURE__*/Schema.tag(\"NetworkError\"),\n reason: /*#__PURE__*/Schema.Literals([\"TransportError\", \"EncodeError\", \"InvalidUrlError\"]),\n request: HttpRequestDetails,\n description: /*#__PURE__*/Schema.optional(Schema.String)\n}) {\n /**\n * Marks `NetworkError` as a semantic AI error reason for runtime guards.\n *\n * @since 4.0.0\n */\n [ReasonTypeId] = ReasonTypeId;\n /**\n * Transport errors are retryable; encoding and URL errors are not.\n *\n * @since 4.0.0\n */\n get isRetryable() {\n return this.reason === \"TransportError\";\n }\n /**\n * Creates a NetworkError from a platform HttpClientError.RequestError.\n *\n * **Example** (Creating a network error from a request error)\n *\n * ```ts\n * import { AiError } from \"effect/unstable/ai\"\n * import type { HttpClientError } from \"effect/unstable/http\"\n *\n * declare const platformError: HttpClientError.RequestError\n *\n * const aiError = AiError.NetworkError.fromRequestError(platformError)\n * ```\n *\n * @since 4.0.0\n */\n static fromRequestError(error) {\n return new NetworkError({\n description: error.description,\n reason: error._tag,\n request: {\n hash: Option.getOrUndefined(error.request.hash),\n headers: redactHeaders(error.request.headers),\n method: error.request.method,\n url: error.request.url,\n urlParams: Array.from(error.request.urlParams)\n }\n });\n }\n get message() {\n const methodAndUrl = `${this.request.method} ${this.request.url}`;\n let baseMessage = this.description ? `${this.reason}: ${this.description}` : `${this.reason}: A network error occurred.`;\n baseMessage += ` (${methodAndUrl})`;\n let suggestion = \"\";\n switch (this.reason) {\n case \"EncodeError\":\n {\n suggestion += \"Check that the request body data is properly formatted and matches the expected content type.\";\n break;\n }\n case \"InvalidUrlError\":\n {\n suggestion += \"Verify that the URL format is correct and that all required parameters have been provided.\";\n suggestion += \" Check for any special characters that may need encoding.\";\n break;\n }\n case \"TransportError\":\n {\n suggestion += \"Check your network connection and verify that the requested URL is accessible.\";\n break;\n }\n }\n baseMessage += `\\n\\n${suggestion}`;\n return baseMessage;\n }\n}\n// =============================================================================\n// Http Response Error\n// =============================================================================\n// =============================================================================\n// Supporting Schemas\n// =============================================================================\n/**\n * Schema for provider-specific metadata which can be attached to error reasons.\n *\n * **Details**\n *\n * Provider-specific metadata is namespaced by provider name. Each provider\n * value can contain arbitrary mutable JSON metadata or `null`.\n *\n * **Example** (Inspecting metadata shape)\n *\n * ```ts\n * const metadata = {\n * openai: {\n * errorCode: \"rate_limit_exceeded\",\n * requestId: \"req_123\"\n * },\n * anthropic: null\n * }\n * ```\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const ProviderMetadata = /*#__PURE__*/Schema.Record(Schema.String, /*#__PURE__*/Schema.NullOr(Schema.MutableJson));\n/**\n * Schema for token usage information from AI operations.\n *\n * **Details**\n *\n * Schema for optional provider-reported token counts for prompt tokens,\n * completion tokens, and total tokens.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const UsageInfo = /*#__PURE__*/Schema.Struct({\n promptTokens: Schema.optional(Schema.Number),\n completionTokens: Schema.optional(Schema.Number),\n totalTokens: Schema.optional(Schema.Number)\n}).annotate({\n identifier: \"UsageInfo\"\n});\n/**\n * Schema for the combined HTTP context used in error reporting.\n *\n * **When to use**\n *\n * Use to attach request details, optional response details, and optional body\n * text to AI provider errors.\n *\n * **Details**\n *\n * Includes the required request details plus optional response details and raw\n * response body.\n *\n * @see {@link HttpRequestDetails} for captured request details\n * @see {@link HttpResponseDetails} for captured response details\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const HttpContext = /*#__PURE__*/Schema.Struct({\n request: HttpRequestDetails,\n response: Schema.optional(HttpResponseDetails),\n body: Schema.optional(Schema.String)\n}).annotate({\n identifier: \"HttpContext\"\n});\n// =============================================================================\n// Reason Classes\n// =============================================================================\n/**\n * Error indicating the request was rate limited.\n *\n * **Details**\n *\n * Rate limit errors are always retryable. When `retryAfter` is provided,\n * callers should wait that duration before retrying.\n *\n * **Example** (Creating a rate limit error)\n *\n * ```ts\n * import { Duration } from \"effect\"\n * import { AiError } from \"effect/unstable/ai\"\n *\n * const rateLimitError = new AiError.RateLimitError({\n * retryAfter: Duration.seconds(60)\n * })\n *\n * console.log(rateLimitError.isRetryable) // true\n * console.log(rateLimitError.message) // \"Rate limit exceeded. Retry after 1 minute\"\n * ```\n *\n * @category reason\n * @since 4.0.0\n */\nexport class RateLimitError extends /*#__PURE__*/Schema.ErrorClass(\"effect/ai/AiError/RateLimitError\")({\n _tag: /*#__PURE__*/Schema.tag(\"RateLimitError\"),\n retryAfter: /*#__PURE__*/Schema.optional(Schema.Duration),\n metadata: /*#__PURE__*/providerMetadataWithDefaults(),\n http: /*#__PURE__*/Schema.optional(HttpContext)\n}) {\n /**\n * Marks `RateLimitError` as a semantic AI error reason for runtime guards.\n *\n * @since 4.0.0\n */\n [ReasonTypeId] = ReasonTypeId;\n /**\n * Rate limit errors are always retryable.\n *\n * @since 4.0.0\n */\n get isRetryable() {\n return true;\n }\n get message() {\n let msg = \"Rate limit exceeded\";\n if (this.retryAfter) msg += `. Retry after ${Duration.format(this.retryAfter)}`;\n return msg;\n }\n}\n/**\n * Error indicating account or billing limits have been reached.\n *\n * **Details**\n *\n * Quota exhausted errors are not retryable without user action.\n *\n * **Example** (Creating a quota exhausted error)\n *\n * ```ts\n * import { AiError } from \"effect/unstable/ai\"\n *\n * const quotaError = new AiError.QuotaExhaustedError({})\n *\n * console.log(quotaError.isRetryable) // false\n * console.log(quotaError.message)\n * // \"Quota exhausted. Check your account billing and usage limits.\"\n * ```\n *\n * @category reason\n * @since 4.0.0\n */\nexport class QuotaExhaustedError extends /*#__PURE__*/Schema.ErrorClass(\"effect/ai/AiError/QuotaExhaustedError\")({\n _tag: /*#__PURE__*/Schema.tag(\"QuotaExhaustedError\"),\n resetAt: /*#__PURE__*/Schema.optional(Schema.DateTimeUtc),\n metadata: /*#__PURE__*/providerMetadataWithDefaults(),\n http: /*#__PURE__*/Schema.optional(HttpContext)\n}) {\n /**\n * Marks `QuotaExhaustedError` as a semantic AI error reason for runtime guards.\n *\n * @since 4.0.0\n */\n [ReasonTypeId] = ReasonTypeId;\n /**\n * Quota exhausted errors require user action and are not retryable.\n *\n * @since 4.0.0\n */\n get isRetryable() {\n return false;\n }\n get message() {\n let msg = \"Quota exhausted\";\n if (this.resetAt) msg += `. Resets at ${this.resetAt}`;\n return `${msg}. Check your account billing and usage limits.`;\n }\n}\n/**\n * Error indicating authentication or authorization failure.\n *\n * **Details**\n *\n * Authentication errors are never retryable without credential changes.\n *\n * **Example** (Creating an authentication error)\n *\n * ```ts\n * import { AiError } from \"effect/unstable/ai\"\n *\n * const authError = new AiError.AuthenticationError({\n * kind: \"InvalidKey\"\n * })\n *\n * console.log(authError.isRetryable) // false\n * console.log(authError.message)\n * // \"InvalidKey: Verify your API key is correct\"\n * ```\n *\n * @category reason\n * @since 4.0.0\n */\nexport class AuthenticationError extends /*#__PURE__*/Schema.ErrorClass(\"effect/ai/AiError/AuthenticationError\")({\n _tag: /*#__PURE__*/Schema.tag(\"AuthenticationError\"),\n kind: /*#__PURE__*/Schema.Literals([\"InvalidKey\", \"ExpiredKey\", \"MissingKey\", \"InsufficientPermissions\", \"Unknown\"]),\n metadata: /*#__PURE__*/providerMetadataWithDefaults(),\n http: /*#__PURE__*/Schema.optional(HttpContext)\n}) {\n /**\n * Marks `AuthenticationError` as a semantic AI error reason for runtime guards.\n *\n * @since 4.0.0\n */\n [ReasonTypeId] = ReasonTypeId;\n /**\n * Authentication errors require credential changes and are not retryable.\n *\n * @since 4.0.0\n */\n get isRetryable() {\n return false;\n }\n get message() {\n const suggestions = {\n InvalidKey: \"Verify your API key is correct\",\n ExpiredKey: \"Your API key has expired. Generate a new one\",\n MissingKey: \"No API key provided. Set the appropriate environment variable\",\n InsufficientPermissions: \"Your API key lacks required permissions\",\n Unknown: \"Authentication failed. Check your credentials\"\n };\n return `${this.kind}: ${suggestions[this.kind]}`;\n }\n}\n/**\n * Error indicating content policy violation.\n *\n * **Details**\n *\n * Content policy errors are never retryable without content changes.\n *\n * **Example** (Creating a content policy error)\n *\n * ```ts\n * import { AiError } from \"effect/unstable/ai\"\n *\n * const policyError = new AiError.ContentPolicyError({\n * description: \"Input contains prohibited content\"\n * })\n *\n * console.log(policyError.isRetryable) // false\n * console.log(policyError.message)\n * // \"Content policy violation: Input contains prohibited content\"\n * ```\n *\n * @category reason\n * @since 4.0.0\n */\nexport class ContentPolicyError extends /*#__PURE__*/Schema.ErrorClass(\"effect/ai/AiError/ContentPolicyError\")({\n _tag: /*#__PURE__*/Schema.tag(\"ContentPolicyError\"),\n description: Schema.String,\n metadata: /*#__PURE__*/providerMetadataWithDefaults(),\n http: /*#__PURE__*/Schema.optional(HttpContext)\n}) {\n /**\n * Marks `ContentPolicyError` as a semantic AI error reason for runtime guards.\n *\n * @since 4.0.0\n */\n [ReasonTypeId] = ReasonTypeId;\n /**\n * Content policy errors require content changes and are not retryable.\n *\n * @since 4.0.0\n */\n get isRetryable() {\n return false;\n }\n get message() {\n return `Content policy violation: ${this.description}`;\n }\n}\n/**\n * Error indicating the request had invalid or malformed parameters.\n *\n * **Details**\n *\n * Invalid request errors require fixing the request and are not retryable.\n *\n * **Example** (Creating an invalid request error)\n *\n * ```ts\n * import { AiError } from \"effect/unstable/ai\"\n *\n * const invalidRequestError = new AiError.InvalidRequestError({\n * parameter: \"temperature\",\n * constraint: \"must be between 0 and 2\",\n * description: \"Temperature value 5 is out of range\"\n * })\n *\n * console.log(invalidRequestError.isRetryable) // false\n * console.log(invalidRequestError.message)\n * // \"Invalid request: parameter 'temperature' must be between 0 and 2. Temperature value 5 is out of range\"\n * ```\n *\n * @category reason\n * @since 4.0.0\n */\nexport class InvalidRequestError extends /*#__PURE__*/Schema.ErrorClass(\"effect/ai/AiError/InvalidRequestError\")({\n _tag: /*#__PURE__*/Schema.tag(\"InvalidRequestError\"),\n parameter: /*#__PURE__*/Schema.optional(Schema.String),\n constraint: /*#__PURE__*/Schema.optional(Schema.String),\n description: /*#__PURE__*/Schema.optional(Schema.String),\n metadata: /*#__PURE__*/providerMetadataWithDefaults(),\n http: /*#__PURE__*/Schema.optional(HttpContext)\n}) {\n /**\n * Marks `InvalidRequestError` as a semantic AI error reason for runtime guards.\n *\n * @since 4.0.0\n */\n [ReasonTypeId] = ReasonTypeId;\n /**\n * Invalid request errors require fixing the request and are not retryable.\n *\n * @since 4.0.0\n */\n get isRetryable() {\n return false;\n }\n get message() {\n let msg = \"Invalid request\";\n if (this.parameter) msg += `: parameter '${this.parameter}'`;\n if (this.constraint) msg += ` ${this.constraint}`;\n if (this.description) msg += `. ${this.description}`;\n return msg;\n }\n}\n/**\n * Error indicating the AI provider experienced an internal error.\n *\n * **Details**\n *\n * Internal provider errors are typically transient and are retryable.\n *\n * **Example** (Creating an internal provider error)\n *\n * ```ts\n * import { AiError } from \"effect/unstable/ai\"\n *\n * const providerError = new AiError.InternalProviderError({\n * description: \"Server encountered an unexpected error\"\n * })\n *\n * console.log(providerError.isRetryable) // true\n * console.log(providerError.message)\n * // \"Internal provider error: Server encountered an unexpected error\"\n * ```\n *\n * @category reason\n * @since 4.0.0\n */\nexport class InternalProviderError extends /*#__PURE__*/Schema.ErrorClass(\"effect/ai/AiError/InternalProviderError\")({\n _tag: /*#__PURE__*/Schema.tag(\"InternalProviderError\"),\n description: Schema.String,\n metadata: /*#__PURE__*/providerMetadataWithDefaults(),\n http: /*#__PURE__*/Schema.optional(HttpContext)\n}) {\n /**\n * Marks `InternalProviderError` as a semantic AI error reason for runtime guards.\n *\n * @since 4.0.0\n */\n [ReasonTypeId] = ReasonTypeId;\n /**\n * Internal provider errors are typically transient and are retryable.\n *\n * @since 4.0.0\n */\n get isRetryable() {\n return true;\n }\n get message() {\n return `Internal provider error: ${this.description}`;\n }\n}\n/**\n * Error indicating failure to parse or validate LLM output.\n *\n * **Details**\n *\n * Invalid output errors are retryable since LLM outputs are non-deterministic.\n *\n * **Example** (Creating an invalid output error)\n *\n * ```ts\n * import { AiError } from \"effect/unstable/ai\"\n *\n * const parseError = new AiError.InvalidOutputError({\n * description: \"Expected a string but received a number\"\n * })\n *\n * console.log(parseError.isRetryable) // true\n * console.log(parseError.message)\n * // \"Invalid output: Expected a string but received a number\"\n * ```\n *\n * @category reason\n * @since 4.0.0\n */\nexport class InvalidOutputError extends /*#__PURE__*/Schema.ErrorClass(\"effect/ai/AiError/InvalidOutputError\")({\n _tag: /*#__PURE__*/Schema.tag(\"InvalidOutputError\"),\n description: Schema.String,\n metadata: /*#__PURE__*/providerMetadataWithDefaults(),\n usage: /*#__PURE__*/Schema.optional(UsageInfo)\n}) {\n /**\n * Marks `InvalidOutputError` as a semantic AI error reason for runtime guards.\n *\n * @since 4.0.0\n */\n [ReasonTypeId] = ReasonTypeId;\n /**\n * Invalid output errors are retryable since LLM outputs are non-deterministic.\n *\n * @since 4.0.0\n */\n get isRetryable() {\n return true;\n }\n /**\n * Creates an InvalidOutputError from a Schema error.\n *\n * **Example** (Creating an invalid output error from a schema error)\n *\n * ```ts\n * import { Schema } from \"effect\"\n * import { AiError } from \"effect/unstable/ai\"\n *\n * declare const schemaError: Schema.SchemaError\n *\n * const parseError = AiError.InvalidOutputError.fromSchemaError(schemaError)\n * ```\n *\n * @since 4.0.0\n */\n static fromSchemaError(error) {\n return new InvalidOutputError({\n description: error.message\n });\n }\n get message() {\n return `Invalid output: ${this.description}`;\n }\n}\n/**\n * Error indicating the LLM generated text that does not conform to the\n * requested structured output schema.\n *\n * **Details**\n *\n * Structured output errors are retryable since LLM outputs are non-deterministic.\n *\n * **Example** (Creating a structured output error)\n *\n * ```ts\n * import { AiError } from \"effect/unstable/ai\"\n *\n * const error = new AiError.StructuredOutputError({\n * description: \"Expected a valid JSON object\",\n * responseText: \"{\\\"foo\\\":}\"\n * })\n *\n * console.log(error.isRetryable) // true\n * console.log(error.message)\n * // \"Structured output validation failed: Expected a valid JSON object\"\n * ```\n *\n * @category reason\n * @since 4.0.0\n */\nexport class StructuredOutputError extends /*#__PURE__*/Schema.ErrorClass(\"effect/ai/AiError/StructuredOutputError\")({\n _tag: /*#__PURE__*/Schema.tag(\"StructuredOutputError\"),\n description: Schema.String,\n responseText: Schema.String,\n metadata: /*#__PURE__*/providerMetadataWithDefaults(),\n usage: /*#__PURE__*/Schema.optional(UsageInfo)\n}) {\n /**\n * Marks `StructuredOutputError` as a semantic AI error reason for runtime guards.\n *\n * @since 4.0.0\n */\n [ReasonTypeId] = ReasonTypeId;\n /**\n * Structured output errors are retryable since LLM outputs are non-deterministic.\n *\n * @since 4.0.0\n */\n get isRetryable() {\n return true;\n }\n /**\n * Creates a StructuredOutputError from a Schema error.\n *\n * **Example** (Creating a structured output error from a schema error)\n *\n * ```ts\n * import { Schema } from \"effect\"\n * import { AiError } from \"effect/unstable/ai\"\n *\n * declare const schemaError: Schema.SchemaError\n * declare const rawText: string\n *\n * const parseError = AiError.StructuredOutputError.fromSchemaError(schemaError, rawText)\n * ```\n *\n * @since 4.0.0\n */\n static fromSchemaError(error, responseText) {\n return new StructuredOutputError({\n description: error.message,\n responseText\n });\n }\n get message() {\n return `Structured output validation failed: ${this.description}`;\n }\n}\n/**\n * Error indicating a codec transformer rejected a schema because it contains\n * unsupported constructs.\n *\n * **Details**\n *\n * Unsupported schema errors are not retryable because they indicate a\n * programmer error where the schema is incompatible with the provider.\n *\n * **Example** (Creating an unsupported schema error)\n *\n * ```ts\n * import { AiError } from \"effect/unstable/ai\"\n *\n * const error = new AiError.UnsupportedSchemaError({\n * description: \"Unions are not supported in Anthropic structured output\"\n * })\n *\n * console.log(error.isRetryable) // false\n * console.log(error.message)\n * // \"Unsupported schema: Unions are not supported in Anthropic structured output\"\n * ```\n *\n * @category reason\n * @since 4.0.0\n */\nexport class UnsupportedSchemaError extends /*#__PURE__*/Schema.ErrorClass(\"effect/ai/AiError/UnsupportedSchemaError\")({\n _tag: /*#__PURE__*/Schema.tag(\"UnsupportedSchemaError\"),\n description: Schema.String,\n metadata: /*#__PURE__*/providerMetadataWithDefaults()\n}) {\n /**\n * Marks `UnsupportedSchemaError` as a semantic AI error reason for runtime guards.\n *\n * @since 4.0.0\n */\n [ReasonTypeId] = ReasonTypeId;\n /**\n * Unsupported schema errors are not retryable because they indicate a programmer error.\n *\n * @since 4.0.0\n */\n get isRetryable() {\n return false;\n }\n get message() {\n return `Unsupported schema: ${this.description}`;\n }\n}\n/**\n * Error data for unknown or unexpected AI failures.\n *\n * **Details**\n *\n * Unknown errors are not retryable by default since the cause is unknown.\n *\n * **Example** (Creating an unknown error)\n *\n * ```ts\n * import { AiError } from \"effect/unstable/ai\"\n *\n * const unknownError = new AiError.UnknownError({\n * description: \"An unexpected error occurred\"\n * })\n *\n * console.log(unknownError.isRetryable) // false\n * console.log(unknownError.message)\n * // \"An unexpected error occurred\"\n * ```\n *\n * @category reason\n * @since 4.0.0\n */\nexport class UnknownError extends /*#__PURE__*/Schema.ErrorClass(\"effect/ai/AiError/UnknownError\")({\n _tag: /*#__PURE__*/Schema.tag(\"UnknownError\"),\n description: /*#__PURE__*/Schema.optional(Schema.String),\n metadata: /*#__PURE__*/providerMetadataWithDefaults(),\n http: /*#__PURE__*/Schema.optional(HttpContext)\n}) {\n /**\n * Marks `UnknownError` as a semantic AI error reason for runtime guards.\n *\n * @since 4.0.0\n */\n [ReasonTypeId] = ReasonTypeId;\n /**\n * Unknown errors are not retryable by default.\n *\n * @since 4.0.0\n */\n get isRetryable() {\n return false;\n }\n get message() {\n return this.description ?? \"Unknown error\";\n }\n}\n// =============================================================================\n// Tool Call Error Types\n// =============================================================================\n/**\n * Error indicating the model requested a tool that doesn't exist in the toolkit.\n *\n * **Details**\n *\n * This error is retryable because the model may self-correct when provided\n * with the list of available tools.\n *\n * **Example** (Creating a tool not found error)\n *\n * ```ts\n * import { AiError } from \"effect/unstable/ai\"\n *\n * const error = new AiError.ToolNotFoundError({\n * toolName: \"unknownTool\",\n * availableTools: [\"GetWeather\", \"GetTime\"]\n * })\n *\n * console.log(error.isRetryable) // true\n * console.log(error.message)\n * // \"Tool 'unknownTool' not found. Available tools: GetWeather, GetTime\"\n * ```\n *\n * @category reason\n * @since 4.0.0\n */\nexport class ToolNotFoundError extends /*#__PURE__*/Schema.ErrorClass(\"effect/ai/AiError/ToolNotFoundError\")({\n _tag: /*#__PURE__*/Schema.tag(\"ToolNotFoundError\"),\n toolName: Schema.String,\n availableTools: /*#__PURE__*/Schema.Array(Schema.String)\n}) {\n /**\n * Marks `ToolNotFoundError` as a semantic AI error reason for runtime guards.\n *\n * @since 4.0.0\n */\n [ReasonTypeId] = ReasonTypeId;\n /**\n * Tool not found errors are retryable because the model may self-correct.\n *\n * @since 4.0.0\n */\n get isRetryable() {\n return true;\n }\n get message() {\n const availableTools = this.availableTools.length > 0 ? this.availableTools.join(\", \") : \"none\";\n return `Tool '${this.toolName}' not found. Available tools: ${availableTools}`;\n }\n}\n/**\n * Error indicating the model's tool call parameters failed schema validation.\n *\n * **Details**\n *\n * This error is retryable because the model may correct its parameters\n * on subsequent attempts.\n *\n * **Example** (Creating a tool parameter validation error)\n *\n * ```ts\n * import { AiError } from \"effect/unstable/ai\"\n *\n * const error = new AiError.ToolParameterValidationError({\n * toolName: \"GetWeather\",\n * toolParams: { location: 123 },\n * description: \"Expected string, got number\"\n * })\n *\n * console.log(error.isRetryable) // true\n * console.log(error.message)\n * // \"Invalid parameters for tool 'GetWeather': Expected string, got number\"\n * ```\n *\n * @category reason\n * @since 4.0.0\n */\nexport class ToolParameterValidationError extends /*#__PURE__*/Schema.ErrorClass(\"effect/ai/AiError/ToolParameterValidationError\")({\n _tag: /*#__PURE__*/Schema.tag(\"ToolParameterValidationError\"),\n toolName: Schema.String,\n toolParams: Schema.Json,\n description: Schema.String\n}) {\n /**\n * Marks `ToolParameterValidationError` as a semantic AI error reason for runtime guards.\n *\n * @since 4.0.0\n */\n [ReasonTypeId] = ReasonTypeId;\n /**\n * Parameter validation errors are retryable because the model may correct parameters.\n *\n * @since 4.0.0\n */\n get isRetryable() {\n return true;\n }\n get message() {\n return `Invalid parameters for tool '${this.toolName}': ${this.description}`;\n }\n}\n/**\n * Error indicating the tool handler returned an invalid result that does not\n * match the tool's schema.\n *\n * **Details**\n *\n * This error is not retryable because invalid results indicate a bug in the\n * tool handler implementation.\n *\n * **Example** (Creating an invalid tool result error)\n *\n * ```ts\n * import { AiError } from \"effect/unstable/ai\"\n *\n * const error = new AiError.InvalidToolResultError({\n * toolName: \"GetWeather\",\n * description: \"Tool handler returned invalid result: missing 'temperature' field\"\n * })\n *\n * console.log(error.isRetryable) // false\n * console.log(error.message)\n * // \"Tool 'GetWeather' returned invalid result: missing 'temperature' field\"\n * ```\n *\n * @category reason\n * @since 4.0.0\n */\nexport class InvalidToolResultError extends /*#__PURE__*/Schema.ErrorClass(\"effect/ai/AiError/InvalidToolResultError\")({\n _tag: /*#__PURE__*/Schema.tag(\"InvalidToolResultError\"),\n toolName: Schema.String,\n description: Schema.String\n}) {\n /**\n * Marks `InvalidToolResultError` as a semantic AI error reason for runtime guards.\n *\n * @since 4.0.0\n */\n [ReasonTypeId] = ReasonTypeId;\n /**\n * Invalid tool result errors are not retryable because they indicate a bug in the handler.\n *\n * @since 4.0.0\n */\n get isRetryable() {\n return false;\n }\n get message() {\n return `Tool '${this.toolName}' returned invalid result: ${this.description}`;\n }\n}\n/**\n * Error indicating the tool result cannot be encoded for sending back to the model.\n *\n * **Details**\n *\n * This error is not retryable because encoding failures indicate a bug in the\n * tool schema definitions.\n *\n * **Example** (Creating a tool result encoding error)\n *\n * ```ts\n * import { AiError } from \"effect/unstable/ai\"\n *\n * const error = new AiError.ToolResultEncodingError({\n * toolName: \"GetWeather\",\n * toolResult: { temperature: 72n },\n * description: \"Cannot encode bigint values as JSON\"\n * })\n *\n * console.log(error.isRetryable) // false\n * console.log(error.message)\n * // \"Failed to encode result for tool 'GetWeather': Cannot encode bigint values as JSON\"\n * ```\n *\n * @category reason\n * @since 4.0.0\n */\nexport class ToolResultEncodingError extends /*#__PURE__*/Schema.ErrorClass(\"effect/ai/AiError/ToolResultEncodingError\")({\n _tag: /*#__PURE__*/Schema.tag(\"ToolResultEncodingError\"),\n toolName: Schema.String,\n toolResult: Schema.Unknown,\n description: Schema.String\n}) {\n /**\n * Marks `ToolResultEncodingError` as a semantic AI error reason for runtime guards.\n *\n * @since 4.0.0\n */\n [ReasonTypeId] = ReasonTypeId;\n /**\n * Encoding errors are not retryable because they indicate a code bug.\n *\n * @since 4.0.0\n */\n get isRetryable() {\n return false;\n }\n get message() {\n return `Failed to encode result for tool '${this.toolName}': ${this.description}`;\n }\n}\n/**\n * Error indicating a provider-defined tool was configured with invalid arguments.\n *\n * **Details**\n *\n * This error is not retryable because it indicates a programming error in the\n * tool configuration that must be fixed in code.\n *\n * **Example** (Creating a tool configuration error)\n *\n * ```ts\n * import { AiError } from \"effect/unstable/ai\"\n *\n * const error = new AiError.ToolConfigurationError({\n * toolName: \"OpenAiCodeInterpreter\",\n * description: \"Invalid container ID format\"\n * })\n *\n * console.log(error.isRetryable) // false\n * console.log(error.message)\n * // \"Invalid configuration for tool 'OpenAiCodeInterpreter': Invalid container ID format\"\n * ```\n *\n * @category reason\n * @since 4.0.0\n */\nexport class ToolConfigurationError extends /*#__PURE__*/Schema.ErrorClass(\"effect/ai/AiError/ToolConfigurationError\")({\n _tag: /*#__PURE__*/Schema.tag(\"ToolConfigurationError\"),\n toolName: Schema.String,\n description: Schema.String\n}) {\n /**\n * Marks `ToolConfigurationError` as a semantic AI error reason for runtime guards.\n *\n * @since 4.0.0\n */\n [ReasonTypeId] = ReasonTypeId;\n /**\n * Configuration errors are not retryable because they indicate a code bug.\n *\n * @since 4.0.0\n */\n get isRetryable() {\n return false;\n }\n get message() {\n return `Invalid configuration for tool '${this.toolName}': ${this.description}`;\n }\n}\n/**\n * Error indicating an operation requires a toolkit but none was provided.\n *\n * **Details**\n *\n * This error occurs when tool approval responses are present in the prompt\n * but no toolkit was provided to resolve them.\n *\n * **Example** (Creating a toolkit required error)\n *\n * ```ts\n * import { AiError } from \"effect/unstable/ai\"\n *\n * const error = new AiError.ToolkitRequiredError({\n * pendingApprovals: [\"GetWeather\", \"SendEmail\"]\n * })\n *\n * console.log(error.isRetryable) // false\n * console.log(error.message)\n * // \"Toolkit required to resolve pending tool approvals: GetWeather, SendEmail\"\n * ```\n *\n * @category reason\n * @since 4.0.0\n */\nexport class ToolkitRequiredError extends /*#__PURE__*/Schema.ErrorClass(\"effect/ai/AiError/ToolkitRequiredError\")({\n _tag: /*#__PURE__*/Schema.tag(\"ToolkitRequiredError\"),\n pendingApprovals: /*#__PURE__*/Schema.Array(Schema.String),\n description: /*#__PURE__*/Schema.optional(Schema.String)\n}) {\n /**\n * Marks `ToolkitRequiredError` as a semantic AI error reason for runtime guards.\n *\n * @since 4.0.0\n */\n [ReasonTypeId] = ReasonTypeId;\n /**\n * Toolkit required errors are not retryable without providing a toolkit.\n *\n * @since 4.0.0\n */\n get isRetryable() {\n return false;\n }\n get message() {\n const tools = this.pendingApprovals.join(\", \");\n return `Toolkit required to resolve pending tool approvals: ${tools}`;\n }\n}\n/**\n * Error indicating the user provided invalid input in their prompt.\n *\n * **Details**\n *\n * This error is raised when the prompt contains content that is structurally\n * valid but not supported by the provider (e.g., unsupported media types,\n * unsupported file formats, etc.).\n *\n * **Example** (Creating an invalid user input error)\n *\n * ```ts\n * import { AiError } from \"effect/unstable/ai\"\n *\n * const error = new AiError.InvalidUserInputError({\n * description: \"Unsupported media type 'video/mp4'. Supported types include images, application/pdf, text/plain\"\n * })\n *\n * console.log(error.isRetryable) // false\n * console.log(error.message)\n * // \"Invalid user input: Unsupported media type 'video/mp4'. Supported types include images, application/pdf, text/plain\"\n * ```\n *\n * @category reason\n * @since 4.0.0\n */\nexport class InvalidUserInputError extends /*#__PURE__*/Schema.ErrorClass(\"effect/ai/AiError/InvalidUserInputError\")({\n _tag: /*#__PURE__*/Schema.tag(\"InvalidUserInputError\"),\n description: Schema.String\n}) {\n /**\n * Marks `InvalidUserInputError` as a semantic AI error reason for runtime guards.\n *\n * @since 4.0.0\n */\n [ReasonTypeId] = ReasonTypeId;\n /**\n * Invalid user input errors require fixing the input and are not retryable.\n *\n * @since 4.0.0\n */\n get isRetryable() {\n return false;\n }\n get message() {\n return `Invalid user input: ${this.description}`;\n }\n}\n/**\n * Schema for validating and parsing AI error reasons.\n *\n * **When to use**\n *\n * Use when decoding or validating unknown AI error reason values with Schema.\n *\n * **Details**\n *\n * This runtime schema is the union of the concrete AI error reason classes.\n *\n * @see {@link isAiErrorReason} for checking an existing value without Schema decoding\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const AiErrorReason = /*#__PURE__*/Schema.Union([RateLimitError, QuotaExhaustedError, AuthenticationError, ContentPolicyError, InvalidRequestError, InternalProviderError, NetworkError, InvalidOutputError, StructuredOutputError, UnsupportedSchemaError, UnknownError, ToolNotFoundError, ToolParameterValidationError, InvalidToolResultError, ToolResultEncodingError, ToolConfigurationError, ToolkitRequiredError, InvalidUserInputError]);\n// =============================================================================\n// Top-Level AiError\n// =============================================================================\nconst TypeId = \"~effect/unstable/ai/AiError/AiError\";\n/**\n * Schema for the top-level AI error wrapper using the `reason` pattern.\n *\n * **When to use**\n *\n * Use when you need AI errors that can be handled by semantic reason with\n * `Effect.catchReason`.\n *\n * **Details**\n *\n * This error stores `module` and `method` context, the semantic `reason`, and\n * delegates `isRetryable` and `retryAfter` to the underlying reason.\n *\n * **Example** (Handling an AI error by tag)\n *\n * ```ts\n * import { Effect } from \"effect\"\n * import { AiError } from \"effect/unstable/ai\"\n *\n * declare const aiOperation: Effect.Effect<string, AiError.AiError>\n *\n * // Handle specific reason types\n * const handled = aiOperation.pipe(\n * Effect.catchTag(\"AiError\", (error) => {\n * if (error.reason._tag === \"RateLimitError\") {\n * return Effect.succeed(`Retry after ${error.retryAfter}`)\n * }\n * return Effect.fail(error)\n * })\n * )\n * ```\n *\n * @category schemas\n * @since 4.0.0\n */\nexport class AiError extends /*#__PURE__*/Schema.ErrorClass(\"effect/ai/AiError/AiError\")({\n _tag: /*#__PURE__*/Schema.tag(\"AiError\"),\n module: Schema.String,\n method: Schema.String,\n reason: AiErrorReason\n}) {\n [TypeId] = TypeId;\n cause = this.reason;\n /**\n * Delegates to the underlying reason's `isRetryable` getter.\n *\n * @since 4.0.0\n */\n get isRetryable() {\n return this.reason.isRetryable;\n }\n /**\n * Delegates to the underlying reason's `retryAfter` if present.\n *\n * @since 4.0.0\n */\n get retryAfter() {\n return \"retryAfter\" in this.reason ? this.reason.retryAfter : undefined;\n }\n get message() {\n return `${this.module}.${this.method}: ${this.reason.message}`;\n }\n}\n/**\n * Type guard to check if a value is an `AiError`.\n *\n * **Example** (Checking for an AI error)\n *\n * ```ts\n * import { AiError } from \"effect/unstable/ai\"\n *\n * const someError = new Error(\"generic error\")\n * const aiError = AiError.make({\n * module: \"Test\",\n * method: \"example\",\n * reason: new AiError.RateLimitError({})\n * })\n *\n * console.log(AiError.isAiError(someError)) // false\n * console.log(AiError.isAiError(aiError)) // true\n * ```\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isAiError = u => Predicate.hasProperty(u, TypeId);\n/**\n * Type guard to check if a value is an `AiErrorReason`.\n *\n * **Example** (Checking for an AI error reason)\n *\n * ```ts\n * import { AiError } from \"effect/unstable/ai\"\n *\n * const rateLimitError = new AiError.RateLimitError({})\n * const genericError = new Error(\"generic error\")\n *\n * console.log(AiError.isAiErrorReason(rateLimitError)) // true\n * console.log(AiError.isAiErrorReason(genericError)) // false\n * ```\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isAiErrorReason = u => Predicate.hasProperty(u, ReasonTypeId);\n/**\n * Creates an `AiError` with the given reason.\n *\n * **Example** (Creating an AI error)\n *\n * ```ts\n * import { Duration } from \"effect\"\n * import { AiError } from \"effect/unstable/ai\"\n *\n * const error = AiError.make({\n * module: \"OpenAI\",\n * method: \"completion\",\n * reason: new AiError.RateLimitError({\n * retryAfter: Duration.seconds(60)\n * })\n * })\n *\n * console.log(error.message)\n * // \"OpenAI.completion: Rate limit exceeded. Retry after 1 minute\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = params => new AiError(params);\n/**\n * Maps HTTP status codes to semantic error reasons.\n *\n * **When to use**\n *\n * Use as the base mapping when provider packages translate HTTP status codes into\n * provider-specific error reasons.\n *\n * **Example** (Mapping an HTTP status to a reason)\n *\n * ```ts\n * import { AiError } from \"effect/unstable/ai\"\n *\n * const reason = AiError.reasonFromHttpStatus({\n * status: 429,\n * body: { error: \"Rate limit exceeded\" }\n * })\n *\n * console.log(reason._tag) // \"RateLimitError\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const reasonFromHttpStatus = params => {\n const {\n status,\n http,\n metadata,\n description\n } = params;\n const common = {\n http,\n ...(metadata ? {\n metadata\n } : undefined),\n ...(description ? {\n description\n } : undefined)\n };\n switch (status) {\n case 400:\n return new InvalidRequestError(common);\n case 401:\n return new AuthenticationError({\n kind: \"InvalidKey\",\n ...common\n });\n case 403:\n return new AuthenticationError({\n kind: \"InsufficientPermissions\",\n ...common\n });\n case 429:\n return new RateLimitError(common);\n default:\n if (status >= 500) {\n return new InternalProviderError({\n description: \"Server error\",\n ...common\n });\n }\n return new UnknownError(common);\n }\n};\n//# sourceMappingURL=AiError.js.map","import * as Context from \"../../Context.js\";\nimport * as Effect from \"../../Effect.js\";\nimport * as Effectable from \"../../Effectable.js\";\nimport * as Fiber from \"../../Fiber.js\";\nimport { identity } from \"../../Function.js\";\nimport * as Layer from \"../../Layer.js\";\nimport * as Predicate from \"../../Predicate.js\";\nimport * as Queue from \"../../Queue.js\";\nimport * as Schema from \"../../Schema.js\";\nimport * as Stream from \"../../Stream.js\";\nimport * as AiError from \"./AiError.js\";\nconst TypeId = \"~effect/ai/Toolkit\";\nconst Proto = {\n ... /*#__PURE__*/Effectable.Prototype({\n label: \"Toolkit\",\n evaluate: /*#__PURE__*/Effect.fnUntraced(function* (parent) {\n const tools = this.tools;\n const services = parent.context;\n const schemasCache = new WeakMap();\n const getSchemas = tool => {\n let schemas = schemasCache.get(tool);\n if (Predicate.isUndefined(schemas)) {\n const handler = services.mapUnsafe.get(tool.id);\n const resultSchema = tool.failureMode === \"return\" ? Schema.Union([tool.successSchema, tool.failureSchema, AiError.AiError]) : tool.successSchema;\n const decodeParameters = Schema.isSchema(tool.parametersSchema) ? Schema.decodeUnknownEffect(tool.parametersSchema) : u => Effect.succeed(u);\n const decodeResult = Schema.decodeUnknownEffect(resultSchema);\n const encodeResult = Schema.encodeUnknownEffect(resultSchema);\n schemas = {\n context: handler.context,\n handler: handler.handler,\n decodeParameters,\n decodeResult,\n encodeResult\n };\n schemasCache.set(tool, schemas);\n }\n return schemas;\n };\n const handle = Effect.fnUntraced(function* (name, params) {\n const tool = tools[name];\n yield* Effect.annotateCurrentSpan({\n tool: name,\n parameters: params\n });\n // If the tool is not found, return an error\n if (Predicate.isUndefined(tool)) {\n return yield* AiError.make({\n module: \"Toolkit\",\n method: `${name}.handle`,\n reason: new AiError.ToolNotFoundError({\n toolName: name,\n availableTools: Object.keys(tools)\n })\n });\n }\n // Fetch cached schemas / handlers for the tool\n const schemas = getSchemas(tool);\n // Decode the tool call parameters which will be passed to the handler\n const decodedParams = yield* schemas.decodeParameters(params).pipe(Effect.mapError(cause => AiError.make({\n module: \"Toolkit\",\n method: `${name}.handle`,\n reason: new AiError.ToolParameterValidationError({\n toolName: name,\n toolParams: params,\n description: cause.message\n })\n })));\n // Setup the handler context\n const queue = yield* Queue.make();\n const context = {\n preliminary: result => Effect.asVoid(Queue.offer(queue, {\n result,\n isFailure: false,\n preliminary: true\n }))\n };\n const fiber = yield* schemas.handler(decodedParams, context).pipe(Effect.flatMap(result => Queue.offer(queue, {\n result,\n isFailure: false,\n preliminary: false\n })), Effect.updateContext(input => Context.merge(schemas.context, input)), Effect.matchCauseEffect({\n onFailure: cause => Queue.failCause(queue, cause),\n onSuccess: () => Queue.end(queue)\n }), Effect.forkChild);\n const encodeResult = result => schemas.encodeResult(result).pipe(Effect.mapError(cause => AiError.make({\n module: \"Toolkit\",\n method: `${name}.handle`,\n reason: new AiError.ToolResultEncodingError({\n toolName: name,\n toolResult: result,\n description: cause.message\n })\n })));\n const normalizeError = error => {\n // Schema errors indicate handler returned invalid data\n const normalizedError = Schema.isSchemaError(error) ? AiError.make({\n module: \"Toolkit\",\n method: `${name}.handle`,\n reason: new AiError.InvalidToolResultError({\n toolName: name,\n description: `Tool handler returned invalid result: ${error.message}`\n })\n }) : AiError.isAiErrorReason(error) ? AiError.make({\n module: \"Toolkit\",\n method: `${name}.handle`,\n reason: error\n }) : error;\n return normalizedError;\n };\n return Stream.fromQueue(queue).pipe(\n // If the tool handler failed, check the tool's failure mode to\n // determine how the result should be returned to the end user\n Stream.catch(error => {\n const normalizedError = normalizeError(error);\n return tool.failureMode === \"error\" ? Stream.fail(normalizedError) : Stream.succeed({\n result: normalizedError,\n isFailure: true,\n preliminary: false\n });\n }), Stream.mapEffect(Effect.fnUntraced(function* (output) {\n const encodedResult = yield* encodeResult(output.result);\n return {\n ...output,\n encodedResult\n };\n })), Stream.onEnd(Fiber.interrupt(fiber)));\n });\n return {\n tools,\n handle: handle\n };\n })\n }),\n [TypeId]: TypeId,\n of: identity,\n toHandlers(build) {\n return Effect.gen({\n self: this\n }, function* () {\n const services = yield* Effect.context();\n const handlers = Effect.isEffect(build) ? yield* build : build;\n const context = new Map();\n for (const [name, handler] of Object.entries(handlers)) {\n const tool = this.tools[name];\n context.set(tool.id, {\n name,\n handler,\n context: services\n });\n }\n return Context.makeUnsafe(context);\n });\n },\n toLayer(build) {\n return Layer.effectContext(this.toHandlers(build));\n },\n toJSON() {\n return {\n _id: \"effect/ai/Toolkit\",\n tools: Array.from(Object.values(this.tools)).map(tool => tool.name)\n };\n }\n};\nconst makeProto = tools => Object.assign(function () {}, Proto, {\n tools\n});\nconst resolveInput = (...tools) => {\n const output = {};\n for (const tool of tools) {\n output[tool.name] = tool;\n }\n return output;\n};\n/**\n * An empty toolkit with no tools.\n *\n * **When to use**\n *\n * Use when you need an empty starting point for building toolkits or a default\n * toolkit value that can be extended with `merge`.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const empty = /*#__PURE__*/makeProto({});\n/**\n * Creates a new toolkit from the specified tools.\n *\n * **Details**\n *\n * This is the primary constructor for creating toolkits. It accepts multiple\n * tools and organizes them into a toolkit that can be provided to AI language\n * models.\n *\n * **Example** (Creating a toolkit)\n *\n * ```ts\n * import { Schema } from \"effect\"\n * import { Tool, Toolkit } from \"effect/unstable/ai\"\n *\n * const GetCurrentTime = Tool.make(\"GetCurrentTime\", {\n * description: \"Get the current timestamp\",\n * success: Schema.Number\n * })\n *\n * const GetWeather = Tool.make(\"get_weather\", {\n * description: \"Get weather information\",\n * parameters: Schema.Struct({ location: Schema.String }),\n * success: Schema.Struct({\n * temperature: Schema.Number,\n * condition: Schema.String\n * })\n * })\n *\n * const toolkit = Toolkit.make(GetCurrentTime, GetWeather)\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = (...tools) => makeProto(resolveInput(...tools));\n/**\n * Merges multiple toolkits into a single toolkit.\n *\n * **Details**\n *\n * Combines all tools from the provided toolkits into one unified toolkit.\n * If there are naming conflicts, tools from later toolkits will override\n * tools from earlier ones.\n *\n * **Example** (Merging toolkits)\n *\n * ```ts\n * import { Schema } from \"effect\"\n * import { Tool, Toolkit } from \"effect/unstable/ai\"\n *\n * const mathToolkit = Toolkit.make(\n * Tool.make(\"add\", { success: Schema.Number }),\n * Tool.make(\"subtract\", { success: Schema.Number })\n * )\n *\n * const utilityToolkit = Toolkit.make(\n * Tool.make(\"get_time\", { success: Schema.Number }),\n * Tool.make(\"get_weather\", { success: Schema.String })\n * )\n *\n * const combined = Toolkit.merge(mathToolkit, utilityToolkit)\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const merge = (\n/**\n * The toolkits to merge together.\n */\n...toolkits) => {\n const tools = {};\n for (const toolkit of toolkits) {\n for (const [name, tool] of Object.entries(toolkit.tools)) {\n tools[name] = tool;\n }\n }\n return makeProto(tools);\n};\n//# sourceMappingURL=Toolkit.js.map","/**\n * Definitions and helpers for tools that AI models can request during a\n * workflow.\n *\n * A tool names an operation, describes the parameters it accepts, declares\n * successful and failed results, and can require approval before execution.\n * This module supports tools defined by the application, tools built into a\n * provider, and dynamic tools whose schema is known only at runtime. It also\n * includes the shared types and conversion helpers needed by language-model\n * requests, tool handlers, and provider integrations.\n *\n * @since 4.0.0\n */\nimport * as Context from \"../../Context.js\";\nimport { constFalse, constTrue, identity } from \"../../Function.js\";\nimport * as StackTraceLimit from \"../../internal/stackTraceLimit.js\";\nimport { pipeArguments } from \"../../Pipeable.js\";\nimport * as Predicate from \"../../Predicate.js\";\nimport * as Schema from \"../../Schema.js\";\nimport * as SchemaAST from \"../../SchemaAST.js\";\n// =============================================================================\n// Type Ids\n// =============================================================================\n/**\n * Runtime type identifier carried by Effect AI tool values.\n *\n * **Details**\n *\n * The tool type guards use this marker, together with more specific markers,\n * to distinguish user-defined, provider-defined, and dynamic tools.\n *\n * @category type IDs\n * @since 4.0.0\n */\nexport const TypeId = \"~effect/ai/Tool\";\n/**\n * Runtime type identifier carried by provider-defined tools.\n *\n * **Details**\n *\n * `isProviderDefined` uses this marker to distinguish tools that are built into\n * an AI provider from user-defined and dynamic tools.\n *\n * @category type IDs\n * @since 4.0.0\n */\nexport const ProviderDefinedTypeId = \"~effect/ai/Tool/ProviderDefined\";\n/**\n * Runtime type identifier carried by dynamic tools.\n *\n * **Details**\n *\n * `isDynamic` uses this marker to distinguish tools whose schema may be\n * provided at runtime from user-defined and provider-defined tools.\n *\n * @category type IDs\n * @since 4.0.0\n */\nexport const DynamicTypeId = \"~effect/ai/Tool/Dynamic\";\n// =============================================================================\n// Type Guards\n// =============================================================================\n/**\n * Type guard to check if a value is a user-defined tool.\n *\n * **Example** (Checking for user-defined tools)\n *\n * ```ts\n * import { Schema } from \"effect\"\n * import { Tool } from \"effect/unstable/ai\"\n *\n * const UserDefinedTool = Tool.make(\"Calculator\", {\n * description: \"Performs basic arithmetic operations\",\n * parameters: Schema.Struct({\n * operation: Schema.Literals([\"add\", \"subtract\", \"multiply\", \"divide\"]),\n * a: Schema.Number,\n * b: Schema.Number\n * }),\n * success: Schema.Number\n * })\n *\n * const ProviderDefinedTool = Tool.providerDefined({\n * id: \"openai.web_search\",\n * customName: \"OpenAiWebSearch\",\n * providerName: \"web_search\",\n * args: Schema.Struct({\n * query: Schema.String\n * }),\n * success: Schema.Struct({\n * results: Schema.Array(Schema.Struct({\n * title: Schema.String,\n * url: Schema.String,\n * snippet: Schema.String\n * }))\n * })\n * })\n *\n * console.log(Tool.isUserDefined(UserDefinedTool)) // true\n * console.log(Tool.isUserDefined(ProviderDefinedTool)) // false\n * ```\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isUserDefined = u => Predicate.hasProperty(u, TypeId) && !isProviderDefined(u) && !isDynamic(u);\n/**\n * Type guard to check if a value is a provider-defined tool.\n *\n * **Example** (Checking for provider-defined tools)\n *\n * ```ts\n * import { Schema } from \"effect\"\n * import { Tool } from \"effect/unstable/ai\"\n *\n * const UserDefinedTool = Tool.make(\"Calculator\", {\n * description: \"Performs basic arithmetic operations\",\n * parameters: Schema.Struct({\n * operation: Schema.Literals([\"add\", \"subtract\", \"multiply\", \"divide\"]),\n * a: Schema.Number,\n * b: Schema.Number\n * }),\n * success: Schema.Number\n * })\n *\n * const ProviderDefinedTool = Tool.providerDefined({\n * id: \"openai.web_search\",\n * customName: \"OpenAiWebSearch\",\n * providerName: \"web_search\",\n * args: Schema.Struct({\n * query: Schema.String\n * }),\n * success: Schema.Struct({\n * results: Schema.Array(Schema.Struct({\n * title: Schema.String,\n * url: Schema.String,\n * snippet: Schema.String\n * }))\n * })\n * })\n *\n * console.log(Tool.isProviderDefined(UserDefinedTool)) // false\n * console.log(Tool.isProviderDefined(ProviderDefinedTool)) // true\n * ```\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isProviderDefined = u => Predicate.hasProperty(u, ProviderDefinedTypeId);\n/**\n * Type guard to check if a value is a dynamic tool.\n *\n * **Example** (Checking for dynamic tools)\n *\n * ```ts\n * import { Schema } from \"effect\"\n * import { Tool } from \"effect/unstable/ai\"\n *\n * const DynamicTool = Tool.dynamic(\"DynamicTool\", {\n * parameters: { type: \"object\", properties: {} }\n * })\n *\n * const UserDefinedTool = Tool.make(\"Calculator\", {\n * parameters: Schema.Struct({ a: Schema.Number, b: Schema.Number }),\n * success: Schema.Number\n * })\n *\n * console.log(Tool.isDynamic(DynamicTool)) // true\n * console.log(Tool.isDynamic(UserDefinedTool)) // false\n * ```\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isDynamic = u => Predicate.hasProperty(u, DynamicTypeId);\n// =============================================================================\n// Constructors\n// =============================================================================\nconst Proto = {\n [TypeId]: {\n _Requirements: identity\n },\n pipe() {\n return pipeArguments(this, arguments);\n },\n addDependency() {\n return userDefinedProto({\n ...this\n });\n },\n setParameters(parametersSchema) {\n return userDefinedProto({\n ...this,\n parametersSchema\n });\n },\n setSuccess(successSchema) {\n return userDefinedProto({\n ...this,\n successSchema\n });\n },\n setFailure(failureSchema) {\n return userDefinedProto({\n ...this,\n failureSchema\n });\n },\n annotate(tag, value) {\n return userDefinedProto({\n ...this,\n annotations: Context.add(this.annotations, tag, value)\n });\n },\n annotateMerge(context) {\n return userDefinedProto({\n ...this,\n annotations: Context.merge(this.annotations, context)\n });\n }\n};\nconst ProviderDefinedProto = {\n ...Proto,\n [ProviderDefinedTypeId]: ProviderDefinedTypeId\n};\nconst DynamicProto = {\n ...Proto,\n [DynamicTypeId]: DynamicTypeId\n};\nconst userDefinedProto = options => {\n const self = Object.assign(Object.create(Proto), options);\n self.id = `effect/ai/Tool/${options.name}`;\n return self;\n};\nconst providerDefinedProto = options => Object.assign(Object.create(ProviderDefinedProto), {\n ...options\n});\nconst dynamicProto = options => {\n const self = Object.assign(Object.create(DynamicProto), options);\n self.id = `effect/ai/Tool/${options.name}`;\n return self;\n};\n/**\n * Creates a user-defined tool with the specified name and configuration.\n *\n * **Details**\n *\n * This is the primary constructor for creating custom tools that AI models\n * can call. The tool definition includes parameter validation, success/failure\n * schemas, and optional service dependencies.\n *\n * If a tool accepts no parameters but still needs an explicit empty object\n * schema, use {@link EmptyParams}.\n *\n * **Example** (Creating a tool without parameters)\n *\n * ```ts\n * import { Schema } from \"effect\"\n * import { Tool } from \"effect/unstable/ai\"\n *\n * // Simple tool with no parameters\n * const GetCurrentTime = Tool.make(\"GetCurrentTime\", {\n * description: \"Returns the current timestamp\",\n * success: Schema.Number\n * })\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = (name, options) => {\n const successSchema = options?.success ?? Schema.Void;\n const failureSchema = options?.failure ?? Schema.Never;\n return userDefinedProto({\n name,\n description: options?.description,\n parametersSchema: options?.parameters ?? EmptyParams,\n successSchema,\n failureSchema,\n failureMode: options?.failureMode ?? \"error\",\n annotations: Context.empty(),\n needsApproval: options?.needsApproval\n });\n};\n/**\n * Creates a dynamic tool that can accept either an Effect Schema or a raw\n * JSON Schema for its parameters.\n *\n * **When to use**\n *\n * Use when you do not know a tool schema at compile time, such as MCP tools\n * discovered at runtime or tools from external configurations.\n *\n * **Details**\n *\n * - When `parameters` is an Effect Schema: full type safety with validation\n * - When `parameters` is a JSON Schema: handler receives `unknown`, no validation\n *\n * **Example** (Creating a dynamic tool)\n *\n * ```ts\n * import { Schema } from \"effect\"\n * import { Tool } from \"effect/unstable/ai\"\n *\n * // With Effect Schema (typed parameters)\n * const Calculator = Tool.dynamic(\"Calculator\", {\n * parameters: Schema.Struct({\n * operation: Schema.Literals([\"add\", \"subtract\"]),\n * a: Schema.Number,\n * b: Schema.Number\n * }),\n * success: Schema.Number\n * })\n *\n * // With JSON Schema (untyped parameters)\n * const McpTool = Tool.dynamic(\"McpTool\", {\n * description: \"Tool from MCP server\",\n * parameters: {\n * type: \"object\",\n * properties: { query: { type: \"string\" } },\n * required: [\"query\"]\n * }\n * })\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const dynamic = (name, options) => {\n const successSchema = options?.success ?? Schema.Unknown;\n const failureSchema = options?.failure ?? Schema.Never;\n const rawParameters = options?.parameters ?? Schema.Unknown;\n const isEffectSchema = Schema.isSchema(rawParameters);\n const parametersSchema = isEffectSchema ? rawParameters : Schema.Unknown;\n const jsonSchema = isEffectSchema ? undefined : rawParameters;\n return dynamicProto({\n name,\n description: options?.description,\n parametersSchema,\n successSchema,\n failureSchema,\n failureMode: options?.failureMode ?? \"error\",\n annotations: Context.empty(),\n needsApproval: options?.needsApproval,\n jsonSchema\n });\n};\n/**\n * Creates a provider-defined tool which leverages functionality built into a\n * large language model provider (e.g. web search, code execution).\n *\n * **Details**\n *\n * These tools are executed by the large language model provider rather than\n * by your application. However, they can optionally require custom handlers\n * implemented in your application to process provider generated results.\n *\n * **Example** (Creating a provider-defined tool)\n *\n * ```ts\n * import { Schema } from \"effect\"\n * import { Tool } from \"effect/unstable/ai\"\n *\n * // Web search tool provided by OpenAI\n * const WebSearch = Tool.providerDefined({\n * id: \"openai.web_search\",\n * customName: \"OpenAiWebSearch\",\n * providerName: \"web_search\",\n * args: Schema.Struct({\n * query: Schema.String\n * }),\n * success: Schema.Struct({\n * results: Schema.Array(Schema.Struct({\n * title: Schema.String,\n * url: Schema.String,\n * content: Schema.String\n * }))\n * })\n * })\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const providerDefined = options => args => {\n const failureMode = Predicate.isNotUndefined(args) && \"failureMode\" in args ? args.failureMode : undefined;\n const successSchema = options?.success ?? Schema.Void;\n const failureSchema = options?.failure ?? Schema.Never;\n return providerDefinedProto({\n id: options.id,\n name: options.customName,\n providerName: options.providerName,\n args: args,\n argsSchema: options?.args ?? Schema.Void,\n requiresHandler: options.requiresHandler ?? false,\n parametersSchema: options?.parameters ?? Schema.Void,\n successSchema,\n failureSchema,\n failureMode: failureMode ?? \"error\"\n });\n};\n// =============================================================================\n// Utilities\n// =============================================================================\n/**\n * Maps between a provider-defined tool name and the name given to the tool by\n * the Effect AI SDK.\n *\n * **Details**\n *\n * The custom names used by the Effect AI SDK are to allow for toolkits which\n * contain tools from multiple different providers that would otherwise have\n * naming conflicts (i.e. `\"web_search\"`) to instead use custom names (i.e.\n * `\"OpenAiWebSearch\"`).\n *\n * @category models\n * @since 4.0.0\n */\nexport class NameMapper {\n #customToProvider = /*#__PURE__*/new Map();\n #providerToCustom = /*#__PURE__*/new Map();\n constructor(tools) {\n for (const tool of tools) {\n if (isProviderDefined(tool)) {\n this.#customToProvider.set(tool.name, tool.providerName);\n this.#providerToCustom.set(tool.providerName, tool.name);\n }\n }\n }\n /**\n * Returns a list of the user-specified tool names in the name mapper.\n */\n get customNames() {\n return Array.from(this.#customToProvider.keys());\n }\n /**\n * Returns a list of the provider-specified tool names in the name mapper.\n */\n get providerNames() {\n return Array.from(this.#providerToCustom.keys());\n }\n /**\n * Returns the user-specified tool name that corresponds with the provided\n * provider-specified tool name.\n *\n * **Details**\n *\n * If the provider-specified tool name was not registered with the name mapper,\n * then the provider-specified tool name is returned.\n */\n getCustomName(providerName) {\n return this.#providerToCustom.get(providerName) ?? providerName;\n }\n /**\n * Returns the provider-specified tool name that corresponds with the provided\n * user-specified tool name.\n *\n * **Details**\n *\n * If the user-specified tool name was not registered with the name mapper,\n * then the user-specified tool name is returned.\n */\n getProviderName(customName) {\n return this.#customToProvider.get(customName) ?? customName;\n }\n}\n/**\n * Extracts the description from a tool's metadata.\n *\n * **Details**\n *\n * Returns the tool's description if explicitly set, otherwise attempts to\n * extract it from the parameter schema's AST annotations.\n *\n * **Example** (Reading a tool description)\n *\n * ```ts\n * import { Tool } from \"effect/unstable/ai\"\n *\n * const myTool = Tool.make(\"example\", {\n * description: \"This is an example tool\"\n * })\n *\n * const description = Tool.getDescription(myTool)\n * console.log(description) // \"This is an example tool\"\n * ```\n *\n * @category getters\n * @since 4.0.0\n */\nexport const getDescription = tool => {\n if (tool.description !== undefined) {\n return tool.description;\n }\n if (Schema.isSchema(tool.parametersSchema)) {\n return SchemaAST.resolveDescription(tool.parametersSchema.ast);\n }\n return undefined;\n};\n/**\n * Generates a JSON Schema for a tool.\n *\n * **Details**\n *\n * This function creates a JSON Schema representation that can be used by\n * large language models to indicate the structure and type of the parameters\n * that a given tool call should receive.\n *\n * May accept an optional `CodecTransformer` which can be used to transform the\n * tool parameter schema so that the resultant JSON schema for the tool call\n * parameters are in a format that conforms to any provider-specific constraints.\n *\n * **Example** (Generating a tool JSON schema)\n *\n * ```ts\n * import { Schema } from \"effect\"\n * import { Tool } from \"effect/unstable/ai\"\n *\n * const weatherTool = Tool.make(\"get_weather\", {\n * parameters: Schema.Struct({\n * location: Schema.String,\n * units: Schema.Literals([\"celsius\", \"fahrenheit\"])\n * })\n * })\n *\n * const jsonSchema = Tool.getJsonSchema(weatherTool)\n * console.log(jsonSchema)\n * // {\n * // type: \"object\",\n * // properties: {\n * // location: { type: \"string\" },\n * // units: { type: \"string\", enum: [\"celsius\", \"fahrenheit\"] }\n * // },\n * // required: [\"location\", \"units\"]\n * // }\n * ```\n *\n * @category getters\n * @since 4.0.0\n */\nexport const getJsonSchema = (tool, options) => {\n if (isDynamic(tool) && tool.jsonSchema !== undefined) {\n return tool.jsonSchema;\n }\n return getJsonSchemaFromSchema(tool.parametersSchema, options);\n};\n/**\n * Generates a JSON Schema from an Effect `Schema`.\n *\n * **Details**\n *\n * If a `CodecTransformer` is supplied, the transformed schema's JSON Schema is\n * returned. Otherwise, the schema is converted with\n * `Schema.toJsonSchemaDocument` and any generated definitions are attached as\n * `$defs`.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const getJsonSchemaFromSchema = (schema, options) => {\n if (Predicate.isNotUndefined(options?.transformer)) {\n return options.transformer(schema).jsonSchema;\n }\n const document = Schema.toJsonSchemaDocument(schema);\n if (Object.keys(document.definitions).length > 0) {\n document.schema.$defs = document.definitions;\n }\n return document.schema;\n};\n// =============================================================================\n// Annotations\n// =============================================================================\n/**\n * Annotation for providing a human-readable title for tools.\n *\n * **Example** (Annotating a tool title)\n *\n * ```ts\n * import { Tool } from \"effect/unstable/ai\"\n *\n * const myTool = Tool.make(\"calculate_tip\")\n * .annotate(Tool.Title, \"Tip Calculator\")\n * ```\n *\n * @category annotations\n * @since 4.0.0\n */\nexport class Title extends /*#__PURE__*/Context.Service()(\"effect/ai/Tool/Title\") {}\n/**\n * Annotation for providing tool metadata for MCP.\n *\n * **Example** (Annotating MCP metadata)\n *\n * ```ts\n * import { Tool } from \"effect/unstable/ai\"\n *\n * const myCalculatorUi = Tool.make(\"calculator_ui\", {})\n * .annotate(Tool.Meta, { ui: { resourceUri: \"ui://example/calculator-ui\" } })\n * ```\n *\n * @category annotations\n * @since 4.0.0\n */\nexport class Meta extends /*#__PURE__*/Context.Service()(\"effect/ai/Tool/Meta\") {}\n/**\n * Annotation indicating whether a tool only reads data without making changes.\n *\n * **Details**\n *\n * This is emitted as the MCP `readOnlyHint`; unannotated tools default to\n * `false`.\n *\n * **Example** (Marking a tool as read-only)\n *\n * ```ts\n * import { Tool } from \"effect/unstable/ai\"\n *\n * const readOnlyTool = Tool.make(\"get_user_info\")\n * .annotate(Tool.Readonly, true)\n * ```\n *\n * @category annotations\n * @since 4.0.0\n */\nexport const Readonly = /*#__PURE__*/Context.Reference(\"effect/ai/Tool/Readonly\", {\n defaultValue: constFalse\n});\n/**\n * Annotation indicating whether a tool may perform destructive operations.\n *\n * **Details**\n *\n * This is emitted as the MCP `destructiveHint`; unannotated tools default to\n * `true`, so annotate safe tools with `false`.\n *\n * **Example** (Marking a tool as non-destructive)\n *\n * ```ts\n * import { Tool } from \"effect/unstable/ai\"\n *\n * const safeTool = Tool.make(\"search_database\")\n * .annotate(Tool.Destructive, false)\n * ```\n *\n * @category annotations\n * @since 4.0.0\n */\nexport const Destructive = /*#__PURE__*/Context.Reference(\"effect/ai/Tool/Destructive\", {\n defaultValue: constTrue\n});\n/**\n * Annotation indicating whether a tool can be called repeatedly with the same\n * parameters without changing the result beyond the first call.\n *\n * **Details**\n *\n * This is emitted as the MCP `idempotentHint`; unannotated tools default to\n * `false`.\n *\n * **Example** (Marking a tool as idempotent)\n *\n * ```ts\n * import { Tool } from \"effect/unstable/ai\"\n *\n * const idempotentTool = Tool.make(\"get_current_time\")\n * .annotate(Tool.Idempotent, true)\n * ```\n *\n * @category annotations\n * @since 4.0.0\n */\nexport const Idempotent = /*#__PURE__*/Context.Reference(\"effect/ai/Tool/Idempotent\", {\n defaultValue: constFalse\n});\n/**\n * Annotation indicating whether a tool may interact with arbitrary external\n * data or systems.\n *\n * **Details**\n *\n * This is emitted as the MCP `openWorldHint`; unannotated tools default to\n * `true`.\n *\n * **Example** (Disabling open-world access)\n *\n * ```ts\n * import { Tool } from \"effect/unstable/ai\"\n *\n * const restrictedTool = Tool.make(\"internal_operation\")\n * .annotate(Tool.OpenWorld, false)\n * ```\n *\n * @category annotations\n * @since 4.0.0\n */\nexport const OpenWorld = /*#__PURE__*/Context.Reference(\"effect/ai/Tool/OpenWorld\", {\n defaultValue: constTrue\n});\n/**\n * Annotation controlling whether strict JSON schema mode is enabled for a tool.\n *\n * **Details**\n *\n * When `true`, providers that support strict mode will send `strict: true` to\n * the model API (e.g. OpenAI's Structured Outputs).\n *\n * When `false`, strict mode is disabled and `strict: false` is sent.\n *\n * When `undefined` (default), the provider's global configuration determines\n * the behavior (e.g. `Config.strictJsonSchema` for OpenAI).\n *\n * **Example** (Disabling strict JSON schema mode)\n *\n * ```ts\n * import { Tool } from \"effect/unstable/ai\"\n *\n * const flexibleTool = Tool.make(\"search\")\n * .annotate(Tool.Strict, false)\n * ```\n *\n * @category annotations\n * @since 4.0.0\n */\nexport const Strict = /*#__PURE__*/Context.Reference(\"effect/ai/Tool/Strict\", {\n defaultValue: () => undefined\n});\n/**\n * Returns the strict mode setting for a tool, or `undefined` if not set.\n *\n * **When to use**\n *\n * Use to inspect the per-tool strict JSON Schema override attached through\n * `Tool.Strict`.\n *\n * **Gotchas**\n *\n * `undefined` means no per-tool override is set. It is distinct from `false`;\n * provider or global configuration determines the final behavior.\n *\n * @see {@link Strict} for the annotation read by this helper\n *\n * @category getters\n * @since 4.0.0\n */\nexport const getStrictMode = tool => Context.get(tool.annotations, Strict);\n// Licensed under BSD-3-Clause (below code only)\n// Code adapted from https://github.com/fastify/secure-json-parse/blob/783fcb1b5434709466759847cec974381939673a/index.js\n//\n// Copyright (c) Effectful Technologies, Inc (https://effectful.co)\n// Copyright (c) 2019 The Fastify Team\n// Copyright (c) 2019, Sideway Inc, and project contributors\n// All rights reserved.\n//\n// The complete list of contributors can be found at:\n// - https://github.com/hapijs/bourne/graphs/contributors\n// - https://github.com/fastify/secure-json-parse/graphs/contributors\n// - https://github.com/Effect-TS/effect/commits/main/packages/ai/ai/src/Tool.ts\n//\n// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n//\n// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n//\n// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n//\n// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\nconst suspectProtoRx = /\"__proto__\"\\s*:/;\nconst suspectConstructorRx = /\"constructor\"\\s*:/;\nfunction _parse(text) {\n // Parse normally\n const obj = JSON.parse(text);\n // Ignore null and non-objects\n if (obj === null || typeof obj !== \"object\") {\n return obj;\n }\n if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) {\n return obj;\n }\n // Scan result for proto keys\n return filter(obj);\n}\nfunction filter(obj) {\n let next = [obj];\n while (next.length) {\n const nodes = next;\n next = [];\n for (const node of nodes) {\n if (Object.prototype.hasOwnProperty.call(node, \"__proto__\")) {\n throw new SyntaxError(\"Object contains forbidden prototype property\");\n }\n if (Object.prototype.hasOwnProperty.call(node, \"constructor\") && Object.prototype.hasOwnProperty.call(node.constructor, \"prototype\")) {\n throw new SyntaxError(\"Object contains forbidden prototype property\");\n }\n for (const key in node) {\n const value = node[key];\n if (value && typeof value === \"object\") {\n next.push(value);\n }\n }\n }\n }\n return obj;\n}\n/**\n * Parses JSON text while rejecting prototype-pollution keys.\n *\n * **When to use**\n *\n * Use when you need a JSON parser that throws for invalid JSON or unsafe\n * object shapes.\n *\n * **Gotchas**\n *\n * Invalid JSON throws through `JSON.parse`. Parsed objects containing an own\n * `__proto__` property or a dangerous `constructor.prototype` shape throw a\n * `SyntaxError`.\n *\n * @category unsafe\n * @since 4.0.0\n */\nexport const unsafeSecureJsonParse = text => {\n // Performance optimization, see https://github.com/fastify/secure-json-parse/pull/90\n const prevLimit = StackTraceLimit.getStackTraceLimit();\n StackTraceLimit.setStackTraceLimit(0);\n try {\n return _parse(text);\n } finally {\n StackTraceLimit.setStackTraceLimit(prevLimit);\n }\n};\n/**\n * Schema for tools that accept no parameters.\n *\n * **When to use**\n *\n * Use when you need an explicit no-parameter `parameters` schema for a tool.\n *\n * **Details**\n *\n * This is `Schema.Record(Schema.String, Schema.Never)`, representing an empty\n * object parameter shape with no additional properties.\n *\n * @see {@link make} for the tool constructor that defaults omitted parameters to this schema\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const EmptyParams = /*#__PURE__*/Schema.Record(Schema.String, Schema.Never);\n/** @internal */\nexport function isEmptyParamsRecord(indexSignature) {\n return indexSignature.parameter === SchemaAST.string && SchemaAST.isNever(indexSignature.type);\n}\n//# sourceMappingURL=Tool.js.map","/**\n * Middleware services for the unstable RPC runtime.\n *\n * A middleware service wraps server handler execution and can also install a\n * client-side wrapper for generated clients. Its metadata records the services\n * provided to downstream handlers, the services required by the middleware\n * implementation, the schema for server-visible failures, the client-only error\n * type, and whether generated clients must require the matching client layer.\n *\n * @since 4.0.0\n */\nimport * as Context from \"../../Context.js\";\nimport * as Effect from \"../../Effect.js\";\nimport { getStackTraceLimit, setStackTraceLimit } from \"../../internal/stackTraceLimit.js\";\nimport * as Layer from \"../../Layer.js\";\nimport * as Schema from \"../../Schema.js\";\nimport { Scope } from \"../../Scope.js\";\n/**\n * The runtime type id used to attach and inspect RPC middleware metadata.\n *\n * @category type IDs\n * @since 4.0.0\n */\nexport const TypeId = \"~effect/rpc/RpcMiddleware\";\n/**\n * Creates a typed RPC middleware service class, with optional service\n * requirements, provided services, error schema, and client-side requirement\n * metadata.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const Service = () => (id, options) => {\n const Err = globalThis.Error;\n const limit = getStackTraceLimit();\n setStackTraceLimit(2);\n const creationError = new Err();\n setStackTraceLimit(limit);\n function ServiceClass() {}\n const ServiceClass_ = ServiceClass;\n Object.setPrototypeOf(ServiceClass, Object.getPrototypeOf(Context.Service(id)));\n ServiceClass.key = id;\n Object.defineProperty(ServiceClass, \"stack\", {\n get() {\n return creationError.stack;\n }\n });\n ServiceClass_[TypeId] = TypeId;\n ServiceClass_.error = options?.error ?? Schema.Never;\n ServiceClass_.requiredForClient = options?.requiredForClient ?? false;\n return ServiceClass;\n};\n/**\n * Provides the client-side implementation for an RPC middleware service,\n * capturing the layer's environment and merging it into each middleware\n * invocation.\n *\n * @category client\n * @since 4.0.0\n */\nexport const layerClient = (tag, service) => Layer.effectContext(Effect.gen(function* () {\n const services = (yield* Effect.context()).pipe(Context.omit(Scope));\n const middleware = Effect.isEffect(service) ? yield* service : service;\n return Context.makeUnsafe(new Map([[`${tag.key}/Client`, options => Effect.updateContext(middleware(options), requestContext => Context.merge(services, requestContext))]]));\n}));\n//# sourceMappingURL=RpcMiddleware.js.map","/**\n * Defines schemas for Model Context Protocol messages.\n *\n * MCP clients and servers use these schemas to describe the JSON-RPC requests,\n * notifications, results, and errors that can cross the protocol boundary. This\n * module focuses on message shapes: it defines the shared protocol data model,\n * groups related messages for the RPC layer, and provides helpers for optional\n * fields and parameter metadata. Transport and server behavior live in other\n * modules.\n *\n * @since 4.0.0\n */\nimport * as Context from \"../../Context.js\";\nimport * as Effect from \"../../Effect.js\";\nimport { constFalse, constTrue } from \"../../Function.js\";\nimport * as Option from \"../../Option.js\";\nimport * as Predicate from \"../../Predicate.js\";\nimport * as Schema from \"../../Schema.js\";\nimport * as SchemaGetter from \"../../SchemaGetter.js\";\nimport * as Rpc from \"../rpc/Rpc.js\";\nimport * as RpcGroup from \"../rpc/RpcGroup.js\";\nimport * as RpcMiddleware from \"../rpc/RpcMiddleware.js\";\n/**\n * Marks a struct field as optional and supplies `defaultValue` when the field\n * is absent.\n *\n * **Details**\n *\n * The default is used during decoding and as the constructor default for the\n * schema field.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const optionalWithDefault = (schema, defaultValue) => {\n const effect = Effect.sync(defaultValue);\n return Schema.optionalKey(schema).pipe(Schema.decode({\n decode: SchemaGetter.withDefault(effect),\n encode: SchemaGetter.passthrough()\n }), Schema.withConstructorDefault(effect));\n};\n/**\n * Creates an optional MCP struct-field schema from a required schema.\n *\n * **Details**\n *\n * The field may be absent, and explicit `undefined` values are omitted when\n * encoding.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const optional = schema => Schema.optionalKey(schema).pipe(Schema.decodeTo(Schema.optional(schema), {\n decode: SchemaGetter.passthrough(),\n encode: SchemaGetter.transformOptional(Option.flatMap(Option.fromUndefinedOr))\n}));\n// =============================================================================\n// Common\n// =============================================================================\n/**\n * Schema for JSON-RPC request identifiers, allowing string or number ids.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const RequestId = /*#__PURE__*/Schema.Union([Schema.String, Schema.Number]);\n/**\n * Schema for MCP progress tokens that associate progress notifications with the\n * original request.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const ProgressToken = /*#__PURE__*/Schema.Union([Schema.String, Schema.Number]);\n/**\n * Schema for optional MCP request metadata.\n *\n * **Details**\n *\n * Request metadata may include a progress token that asks the receiver to send\n * out-of-band progress notifications for the request.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport class RequestMeta extends /*#__PURE__*/Schema.Opaque()(/*#__PURE__*/Schema.Struct({\n _meta: /*#__PURE__*/optional(/*#__PURE__*/Schema.Struct({\n /**\n * If specified, the caller is requesting out-of-band progress notifications\n * for this request (as represented by notifications/progress). The value of\n * this parameter is an opaque token that will be attached to any subsequent\n * notifications. The receiver is not obligated to provide these\n * notifications.\n */\n progressToken: /*#__PURE__*/optional(ProgressToken)\n }))\n})) {}\n/**\n * Schema for optional MCP result metadata.\n *\n * **Details**\n *\n * The `_meta` field is reserved for protocol, extension, or implementation\n * metadata attached to a result.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport class ResultMeta extends /*#__PURE__*/Schema.Opaque()(/*#__PURE__*/Schema.Struct({\n /**\n * This result property is reserved by the protocol to allow clients and\n * servers to attach additional metadata to their responses.\n */\n _meta: /*#__PURE__*/optional(/*#__PURE__*/Schema.Record(Schema.String, Schema.Json))\n})) {}\n/**\n * Schema for optional MCP notification metadata.\n *\n * **Details**\n *\n * The `_meta` field is reserved for protocol, extension, or implementation\n * metadata attached to a notification.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport class NotificationMeta extends /*#__PURE__*/Schema.Opaque()(/*#__PURE__*/Schema.Struct({\n /**\n * This parameter name is reserved by MCP to allow clients and servers to\n * attach additional metadata to their notifications.\n */\n _meta: /*#__PURE__*/optional(/*#__PURE__*/Schema.Record(Schema.String, Schema.Json))\n})) {}\n/**\n * Schema for opaque cursor tokens used in pagination.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const Cursor = Schema.String;\n/**\n * Schema for MCP request metadata used by paginated requests.\n *\n * **Details**\n *\n * It includes the base request metadata fields plus an optional cursor\n * indicating where the server should continue listing results.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport class PaginatedRequestMeta extends /*#__PURE__*/Schema.Opaque()(/*#__PURE__*/Schema.Struct({\n ...RequestMeta.fields,\n /**\n * An opaque token representing the current pagination position.\n * If provided, the server should return results starting after this cursor.\n */\n cursor: /*#__PURE__*/optional(Cursor)\n})) {}\n/**\n * Schema for MCP result metadata returned by paginated operations.\n *\n * **Details**\n *\n * It includes the base result metadata fields plus an optional `nextCursor`,\n * which indicates that more results may be available.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport class PaginatedResultMeta extends /*#__PURE__*/Schema.Opaque()(/*#__PURE__*/Schema.Struct({\n ...ResultMeta.fields,\n /**\n * An opaque token representing the pagination position after the last returned result.\n * If present, there may be more results available.\n */\n nextCursor: /*#__PURE__*/optional(Cursor)\n})) {}\n/**\n * Schema for MCP conversation roles, allowing user and assistant.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const Role = /*#__PURE__*/Schema.Literals([\"user\", \"assistant\"]);\n/**\n * Schema for optional client-facing annotations on MCP objects.\n *\n * **When to use**\n *\n * Use to describe intended audience and priority metadata for objects shown or\n * processed by a client.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport class Annotations extends /*#__PURE__*/Schema.Opaque()(/*#__PURE__*/Schema.Struct({\n /**\n * Describes who the intended customer of this object or data is.\n *\n * It can include multiple entries to indicate content useful for multiple\n * audiences (e.g., `[\"user\", \"assistant\"]`).\n */\n audience: /*#__PURE__*/optional(/*#__PURE__*/Schema.Array(Role)),\n /**\n * Describes how important this data is for operating the server.\n *\n * A value of 1 means \"most important,\" and indicates that the data is\n * effectively required, while 0 means \"least important,\" and indicates that\n * the data is entirely optional.\n */\n priority: /*#__PURE__*/optional(/*#__PURE__*/Schema.Number.check(/*#__PURE__*/Schema.isBetween({\n minimum: 0,\n maximum: 1\n })))\n})) {}\n/**\n * Describes the name and version of an MCP implementation.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport class Implementation extends /*#__PURE__*/Schema.Opaque()(/*#__PURE__*/Schema.Struct({\n name: Schema.String,\n title: /*#__PURE__*/optional(Schema.String),\n version: Schema.String\n})) {}\n/**\n * Describes capabilities advertised by an MCP client.\n *\n * **When to use**\n *\n * Use to describe which optional MCP features a client supports during\n * initialization.\n *\n * **Details**\n *\n * Known capabilities are represented by this schema, but the capability set is\n * open and clients may define additional capabilities.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport class ClientCapabilities extends /*#__PURE__*/Schema.Class(\"@effect/ai/McpSchema/ClientCapabilities\")({\n /**\n * Experimental, non-standard capabilities that the client supports.\n */\n experimental: /*#__PURE__*/optional(/*#__PURE__*/Schema.Record(Schema.String, /*#__PURE__*/Schema.Struct({}))),\n /**\n * Optional extensions capabilities advertised by the client.\n * Keys are extension identifiers following <vendor-prefix>/<extension-name> (e.g. \"io.modelcontextprotocol/ui\").\n */\n extensions: /*#__PURE__*/optional(/*#__PURE__*/Schema.Record(/*#__PURE__*/Schema.TemplateLiteral([Schema.String, \"/\", Schema.String]), Schema.Json)),\n /**\n * Present if the client supports listing roots.\n */\n roots: /*#__PURE__*/optional(/*#__PURE__*/Schema.Struct({\n /**\n * Whether the client supports notifications for changes to the roots list.\n */\n listChanged: /*#__PURE__*/optional(Schema.Boolean)\n })),\n /**\n * Present if the client supports sampling from an LLM.\n */\n sampling: /*#__PURE__*/optional(/*#__PURE__*/Schema.Struct({})),\n /**\n * Present if the client supports elicitation from the server.\n */\n elicitation: /*#__PURE__*/optional(/*#__PURE__*/Schema.Struct({}))\n}) {}\n/**\n * Describes capabilities advertised by an MCP server.\n *\n * **When to use**\n *\n * Use to describe which optional MCP features a server supports during\n * initialization.\n *\n * **Details**\n *\n * Known capabilities are represented by this schema, but the capability set is\n * open and servers may define additional capabilities.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport class ServerCapabilities extends /*#__PURE__*/Schema.Opaque()(/*#__PURE__*/Schema.Struct({\n /**\n * Experimental, non-standard capabilities that the server supports.\n */\n experimental: /*#__PURE__*/optional(/*#__PURE__*/Schema.Record(Schema.String, /*#__PURE__*/Schema.Struct({}))),\n /**\n * Optional extensions capabilities advertised by the server.\n * Keys are extension identifiers following <vendor-prefix>/<extension-name> (e.g. \"io.modelcontextprotocol/ui\").\n */\n extensions: /*#__PURE__*/optional(/*#__PURE__*/Schema.Record(/*#__PURE__*/Schema.TemplateLiteral([Schema.String, \"/\", Schema.String]), Schema.Json)),\n /**\n * Present if the server supports sending log messages to the client.\n */\n logging: /*#__PURE__*/optional(/*#__PURE__*/Schema.Struct({})),\n /**\n * Present if the server supports argument autocompletion suggestions.\n */\n completions: /*#__PURE__*/optional(/*#__PURE__*/Schema.Struct({})),\n /**\n * Present if the server offers any prompt templates.\n */\n prompts: /*#__PURE__*/optional(/*#__PURE__*/Schema.Struct({\n /**\n * Whether this server supports notifications for changes to the prompt list.\n */\n listChanged: /*#__PURE__*/optional(Schema.Boolean)\n })),\n /**\n * Present if the server offers any resources to read.\n */\n resources: /*#__PURE__*/optional(/*#__PURE__*/Schema.Struct({\n /**\n * Whether this server supports subscribing to resource updates.\n */\n subscribe: /*#__PURE__*/optional(Schema.Boolean),\n /**\n * Whether this server supports notifications for changes to the resource list.\n */\n listChanged: /*#__PURE__*/optional(Schema.Boolean)\n })),\n /**\n * Present if the server offers any tools to call.\n */\n tools: /*#__PURE__*/optional(/*#__PURE__*/Schema.Struct({\n /**\n * Whether this server supports notifications for changes to the tool list.\n */\n listChanged: /*#__PURE__*/optional(Schema.Boolean)\n }))\n})) {}\n// =============================================================================\n// Errors\n// =============================================================================\n/**\n * Schema for MCP and JSON-RPC error objects.\n *\n * **Details**\n *\n * It contains the numeric error `code`, a concise `message`, and optional\n * sender-defined `data`.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport class McpErrorBase extends /*#__PURE__*/Schema.Class(\"@effect/ai/McpSchema/McpErrorBase\")({\n /**\n * The error type that occurred.\n */\n code: Schema.Number,\n /**\n * A short description of the error. The message SHOULD be limited to a\n * concise single sentence.\n */\n message: Schema.String,\n /**\n * Additional information about the error. The value of this member is\n * defined by the sender (e.g. detailed error information, nested errors etc.).\n */\n data: /*#__PURE__*/optional(Schema.Any)\n}) {}\n/**\n * Represents the JSON-RPC error code for requests that are not valid request objects.\n *\n * **When to use**\n *\n * Use when building an MCP/JSON-RPC error response for a syntactically parsed\n * request object that fails request-shape validation.\n *\n * @category constants\n * @since 4.0.0\n */\nexport const INVALID_REQUEST_ERROR_CODE = -32600;\n/**\n * Represents the JSON-RPC error code for requests whose method does not exist or is not\n * available.\n *\n * **When to use**\n *\n * Use when building an MCP/JSON-RPC error response for a request whose\n * `method` is unknown or unavailable.\n *\n * @category constants\n * @since 4.0.0\n */\nexport const METHOD_NOT_FOUND_ERROR_CODE = -32601;\n/**\n * Represents the JSON-RPC error code for invalid method parameters.\n *\n * **When to use**\n *\n * Use when building an MCP/JSON-RPC error response for decoded request\n * parameters that fail method-specific validation.\n *\n * @category constants\n * @since 4.0.0\n */\nexport const INVALID_PARAMS_ERROR_CODE = -32602;\n/**\n * Represents the JSON-RPC error code for internal server errors.\n *\n * **When to use**\n *\n * Use when building an MCP/JSON-RPC error response for an unexpected\n * server-side failure.\n *\n * @category constants\n * @since 4.0.0\n */\nexport const INTERNAL_ERROR_CODE = -32603;\n/**\n * Represents the JSON-RPC error code for invalid JSON that could not be parsed.\n *\n * **When to use**\n *\n * Use when building an MCP/JSON-RPC error response before a request object is\n * available because the JSON payload could not be parsed.\n *\n * @category constants\n * @since 4.0.0\n */\nexport const PARSE_ERROR_CODE = -32700;\n/**\n * Represents an MCP/JSON-RPC error for invalid JSON that could not be parsed.\n *\n * **When to use**\n *\n * Use to report a JSON parse failure before a valid JSON-RPC request object is\n * available.\n *\n * **Details**\n *\n * Uses the standard JSON-RPC parse error code `-32700`.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class ParseError extends /*#__PURE__*/Schema.ErrorClass(\"effect/ai/McpSchema/ParseError\")({\n ...McpErrorBase.fields,\n _tag: /*#__PURE__*/Schema.tag(\"ParseError\"),\n code: /*#__PURE__*/Schema.tag(PARSE_ERROR_CODE)\n}) {}\n/**\n * Represents an MCP/JSON-RPC error for a request object that is not valid.\n *\n * **When to use**\n *\n * Use to report a syntactically parsed JSON-RPC request that is not a valid\n * request object.\n *\n * **Details**\n *\n * Uses the standard JSON-RPC invalid request code `-32600`.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class InvalidRequest extends /*#__PURE__*/Schema.ErrorClass(\"effect/ai/McpSchema/InvalidRequest\")({\n ...McpErrorBase.fields,\n _tag: /*#__PURE__*/Schema.tag(\"InvalidRequest\"),\n code: /*#__PURE__*/Schema.tag(INVALID_REQUEST_ERROR_CODE)\n}) {}\n/**\n * Represents an MCP/JSON-RPC error for an unavailable method.\n *\n * **When to use**\n *\n * Use to report a JSON-RPC method that does not exist or is not available.\n *\n * **Details**\n *\n * Uses the standard JSON-RPC method-not-found code `-32601`.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class MethodNotFound extends /*#__PURE__*/Schema.ErrorClass(\"effect/ai/McpSchema/MethodNotFound\")({\n ...McpErrorBase.fields,\n _tag: /*#__PURE__*/Schema.tag(\"MethodNotFound\"),\n code: /*#__PURE__*/Schema.tag(METHOD_NOT_FOUND_ERROR_CODE)\n}) {}\n/**\n * Represents an MCP/JSON-RPC error for invalid method parameters.\n *\n * **When to use**\n *\n * Use to report a request whose method parameters do not match the method\n * schema.\n *\n * **Details**\n *\n * Uses the standard JSON-RPC invalid params code `-32602`.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class InvalidParams extends /*#__PURE__*/Schema.ErrorClass(\"effect/ai/McpSchema/InvalidParams\")({\n ...McpErrorBase.fields,\n _tag: /*#__PURE__*/Schema.tag(\"InvalidParams\"),\n code: /*#__PURE__*/Schema.tag(INVALID_PARAMS_ERROR_CODE)\n}) {}\n/**\n * Represents an MCP/JSON-RPC error for unexpected internal server failures.\n *\n * **When to use**\n *\n * Use to report an unexpected server-side failure while handling a valid\n * request.\n *\n * **Details**\n *\n * Uses the standard JSON-RPC internal error code `-32603` and includes\n * `InternalError.notImplemented` for unimplemented handlers.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class InternalError extends /*#__PURE__*/Schema.ErrorClass(\"effect/ai/McpSchema/InternalError\")({\n ...McpErrorBase.fields,\n _tag: /*#__PURE__*/Schema.tag(\"InternalError\"),\n code: /*#__PURE__*/Schema.tag(INTERNAL_ERROR_CODE)\n}) {\n static notImplemented = /*#__PURE__*/new InternalError({\n message: \"Not implemented\"\n });\n}\n/**\n * Schema for MCP protocol errors returned in JSON-RPC failure responses,\n * including standard protocol errors and custom `McpErrorBase` values.\n *\n * @category errors\n * @since 4.0.0\n */\nexport const McpError = /*#__PURE__*/Schema.Union([ParseError, InvalidRequest, MethodNotFound, InvalidParams, InternalError, McpErrorBase]);\n// =============================================================================\n// Ping\n// =============================================================================\n/**\n * Represents an MCP ping request used to check whether the peer is still alive.\n *\n * **When to use**\n *\n * Use to implement client or server liveness checks.\n *\n * **Details**\n *\n * The receiver should respond promptly; otherwise the sender may disconnect.\n *\n * @category ping\n * @since 4.0.0\n */\nexport class Ping extends /*#__PURE__*/Rpc.make(\"ping\", {\n success: /*#__PURE__*/Schema.Struct({}),\n error: McpError,\n payload: /*#__PURE__*/Schema.UndefinedOr(RequestMeta)\n}) {}\n// =============================================================================\n// Initialization\n// =============================================================================\n/**\n * Schema for the server's response to an initialize request from the client.\n *\n * @category initialization\n * @since 4.0.0\n */\nexport class InitializeResult extends /*#__PURE__*/Schema.Opaque()(/*#__PURE__*/Schema.Struct({\n ...ResultMeta.fields,\n /**\n * The version of the Model Context Protocol that the server wants to use.\n * This may not match the version that the client requested. If the client\n * cannot support this version, it MUST disconnect.\n */\n protocolVersion: Schema.String,\n capabilities: ServerCapabilities,\n serverInfo: Implementation,\n /**\n * Instructions describing how to use the server and its features.\n *\n * This can be used by clients to improve the LLM's understanding of available\n * tools, resources, etc. It can be thought of like a \"hint\" to the model.\n * For example, this information MAY be added to the system prompt.\n */\n instructions: /*#__PURE__*/optional(Schema.String)\n})) {}\n/**\n * Sent from the client to the server when it first connects, asking it to begin\n * initialization.\n *\n * @category initialization\n * @since 4.0.0\n */\nexport class Initialize extends /*#__PURE__*/Rpc.make(\"initialize\", {\n success: InitializeResult,\n error: McpError,\n payload: {\n ...RequestMeta.fields,\n /**\n * The latest version of the Model Context Protocol that the client\n * supports. The client MAY decide to support older versions as well.\n */\n protocolVersion: Schema.String,\n /**\n * Capabilities a client may support. Known capabilities are defined here,\n * in this schema, but this is not a closed set: any client can define its\n * own, additional capabilities.\n */\n capabilities: ClientCapabilities,\n /**\n * Describes the name and version of an MCP implementation.\n */\n clientInfo: Implementation\n }\n}) {}\n/**\n * Sent from the client to the server after initialization has finished.\n *\n * @category initialization\n * @since 4.0.0\n */\nexport class InitializedNotification extends /*#__PURE__*/Rpc.make(\"notifications/initialized\", {\n payload: /*#__PURE__*/Schema.UndefinedOr(NotificationMeta)\n}) {}\n// =============================================================================\n// Cancellation\n// =============================================================================\n/**\n * Sent from either peer to cancel a previously issued request in the same\n * direction.\n *\n * **Details**\n *\n * The payload identifies the request to cancel and may include a\n * human-readable reason.\n *\n * @category cancellation\n * @since 4.0.0\n */\nexport class CancelledNotification extends /*#__PURE__*/Rpc.make(\"notifications/cancelled\", {\n payload: {\n ...NotificationMeta.fields,\n /**\n * The ID of the request to cancel.\n *\n * This MUST correspond to the ID of a request previously issued in the\n * same direction.\n */\n requestId: RequestId,\n /**\n * An optional string describing the reason for the cancellation. This MAY\n * be logged or presented to the user.\n */\n reason: /*#__PURE__*/optional(Schema.String)\n }\n}) {}\n// =============================================================================\n// Progress\n// =============================================================================\n/**\n * Sent from either peer to report progress for a long-running request.\n *\n * @category progress\n * @since 4.0.0\n */\nexport class ProgressNotification extends /*#__PURE__*/Rpc.make(\"notifications/progress\", {\n payload: {\n ...NotificationMeta.fields,\n /**\n * The progress token which was given in the initial request, used to\n * associate this notification with the request that is proceeding.\n */\n progressToken: ProgressToken,\n /**\n * The progress thus far. This should increase every time progress is made,\n * even if the total is unknown.\n */\n progress: /*#__PURE__*/optional(Schema.Number),\n /**\n * Total number of items to process (or total progress required), if known.\n */\n total: /*#__PURE__*/optional(Schema.Number),\n /**\n * An optional message describing the current progress.\n */\n message: /*#__PURE__*/optional(Schema.String)\n }\n}) {}\n// =============================================================================\n// Resources\n// =============================================================================\n/**\n * Schema for a known resource that the server is capable of reading.\n *\n * @category resources\n * @since 4.0.0\n */\nexport class Resource extends /*#__PURE__*/Schema.Class(\"@effect/ai/McpSchema/Resource\")({\n /**\n * The URI of this resource.\n */\n uri: Schema.String,\n /**\n * A human-readable name for this resource.\n *\n * This can be used by clients to populate UI elements.\n */\n name: Schema.String,\n title: /*#__PURE__*/optional(Schema.String),\n /**\n * A description of what this resource represents.\n *\n * This can be used by clients to improve the LLM's understanding of available\n * resources. It can be thought of like a \"hint\" to the model.\n */\n description: /*#__PURE__*/optional(Schema.String),\n /**\n * The MIME type of this resource, if known.\n */\n mimeType: /*#__PURE__*/optional(Schema.String),\n /**\n * Optional annotations for the client.\n */\n annotations: /*#__PURE__*/optional(Annotations),\n /**\n * The size of the raw resource content, in bytes (i.e., before base64\n * encoding or any tokenization), if known.\n *\n * This can be used by Hosts to display file sizes and estimate context\n * window usage.\n */\n size: /*#__PURE__*/optional(Schema.Number),\n /**\n * Optional additional metadata for the client.\n *\n * This parameter name is reserved by MCP to allow clients and servers to\n * attach additional metadata to resources.\n */\n _meta: /*#__PURE__*/optional(/*#__PURE__*/Schema.Record(Schema.String, Schema.Json))\n}) {}\n/**\n * Schema for a template description of resources available on the server.\n *\n * @category resources\n * @since 4.0.0\n */\nexport class ResourceTemplate extends /*#__PURE__*/Schema.Class(\"@effect/ai/McpSchema/ResourceTemplate\")({\n /**\n * A URI template (according to RFC 6570) that can be used to construct\n * resource URIs.\n */\n uriTemplate: Schema.String,\n /**\n * A human-readable name for the type of resource this template refers to.\n *\n * This can be used by clients to populate UI elements.\n */\n name: Schema.String,\n title: /*#__PURE__*/optional(Schema.String),\n /**\n * A description of what this template is for.\n *\n * This can be used by clients to improve the LLM's understanding of available\n * resources. It can be thought of like a \"hint\" to the model.\n */\n description: /*#__PURE__*/optional(Schema.String),\n /**\n * The MIME type for all resources that match this template. This should only\n * be included if all resources matching this template have the same type.\n */\n mimeType: /*#__PURE__*/optional(Schema.String),\n /**\n * Optional annotations for the client.\n */\n annotations: /*#__PURE__*/optional(Annotations),\n /**\n * Optional additional metadata for the client.\n */\n _meta: /*#__PURE__*/optional(/*#__PURE__*/Schema.Record(Schema.String, Schema.Json))\n}) {}\n/**\n * Schema for the contents of a specific resource or sub-resource.\n *\n * @category resources\n * @since 4.0.0\n */\nexport class ResourceContents extends /*#__PURE__*/Schema.Opaque()(/*#__PURE__*/Schema.Struct({\n /**\n * The URI of this resource.\n */\n uri: Schema.String,\n /**\n * The MIME type of this resource, if known.\n */\n mimeType: /*#__PURE__*/optional(Schema.String),\n /**\n * Optional additional metadata for the client.\n */\n _meta: /*#__PURE__*/optional(/*#__PURE__*/Schema.Record(Schema.String, Schema.Json))\n})) {}\n/**\n * Schema for text resource contents represented as a string.\n *\n * @category resources\n * @since 4.0.0\n */\nexport class TextResourceContents extends /*#__PURE__*/Schema.Opaque()(/*#__PURE__*/Schema.Struct({\n ...ResourceContents.fields,\n /**\n * The text of the item. This must only be set if the item can actually be\n * represented as text (not binary data).\n */\n text: Schema.String\n})) {}\n/**\n * Schema for binary resource contents represented as a `Uint8Array`.\n *\n * @category resources\n * @since 4.0.0\n */\nexport class BlobResourceContents extends /*#__PURE__*/Schema.Opaque()(/*#__PURE__*/Schema.Struct({\n ...ResourceContents.fields,\n /**\n * The binary data of the item decoded from a base64-encoded string.\n */\n blob: Schema.Uint8Array\n})) {}\n/**\n * Schema for the server's response to a resources/list request from the client.\n *\n * @category resources\n * @since 4.0.0\n */\nexport class ListResourcesResult extends /*#__PURE__*/Schema.Class(\"@effect/ai/McpSchema/ListResourcesResult\")({\n ...PaginatedResultMeta.fields,\n resources: /*#__PURE__*/Schema.Array(Resource)\n}) {}\n/**\n * Sent from the client to request a list of resources the server has.\n *\n * @category resources\n * @since 4.0.0\n */\nexport class ListResources extends /*#__PURE__*/Rpc.make(\"resources/list\", {\n success: ListResourcesResult,\n error: McpError,\n payload: /*#__PURE__*/Schema.UndefinedOr(PaginatedRequestMeta)\n}) {}\n/**\n * Schema for the server's response to a resources/templates/list request from\n * the client.\n *\n * @category resources\n * @since 4.0.0\n */\nexport class ListResourceTemplatesResult extends /*#__PURE__*/Schema.Class(\"@effect/ai/McpSchema/ListResourceTemplatesResult\")({\n ...PaginatedResultMeta.fields,\n resourceTemplates: /*#__PURE__*/Schema.Array(ResourceTemplate)\n}) {}\n/**\n * Sent from the client to request a list of resource templates the server has.\n *\n * @category resources\n * @since 4.0.0\n */\nexport class ListResourceTemplates extends /*#__PURE__*/Rpc.make(\"resources/templates/list\", {\n success: ListResourceTemplatesResult,\n error: McpError,\n payload: /*#__PURE__*/Schema.UndefinedOr(PaginatedRequestMeta)\n}) {}\n/**\n * Schema for the server's response to a resources/read request from the client.\n *\n * @category resources\n * @since 4.0.0\n */\nexport class ReadResourceResult extends /*#__PURE__*/Schema.Opaque()(/*#__PURE__*/Schema.Struct({\n ...ResultMeta.fields,\n contents: /*#__PURE__*/Schema.Array(/*#__PURE__*/Schema.Union([TextResourceContents, BlobResourceContents]))\n})) {}\n/**\n * Sent from the client to the server, to read a specific resource URI.\n *\n * @category resources\n * @since 4.0.0\n */\nexport class ReadResource extends /*#__PURE__*/Rpc.make(\"resources/read\", {\n success: ReadResourceResult,\n error: McpError,\n payload: {\n ...RequestMeta.fields,\n /**\n * The URI of the resource to read. The URI can use any protocol; it is up\n * to the server how to interpret it.\n */\n uri: Schema.String\n }\n}) {}\n/**\n * Represents a notification that the server's resource list changed.\n *\n * **When to use**\n *\n * Use to notify clients that `resources/list` should be requested again.\n *\n * **Details**\n *\n * Servers may send this notification without a previous client subscription.\n *\n * @category resources\n * @since 4.0.0\n */\nexport class ResourceListChangedNotification extends /*#__PURE__*/Rpc.make(\"notifications/resources/list_changed\", {\n payload: /*#__PURE__*/Schema.UndefinedOr(NotificationMeta)\n}) {}\n/**\n * Sent from the client to request resources/updated notifications from the\n * server whenever a particular resource changes.\n *\n * @category resources\n * @since 4.0.0\n */\nexport class Subscribe extends /*#__PURE__*/Rpc.make(\"resources/subscribe\", {\n error: McpError,\n payload: {\n ...RequestMeta.fields,\n /**\n * The URI of the resource to subscribe to. The URI can use any protocol;\n * it is up to the server how to interpret it.\n */\n uri: Schema.String\n }\n}) {}\n/**\n * Sent from the client to request cancellation of resources/updated\n * notifications from the server. This should follow a previous\n * resources/subscribe request.\n *\n * @category resources\n * @since 4.0.0\n */\nexport class Unsubscribe extends /*#__PURE__*/Rpc.make(\"resources/unsubscribe\", {\n error: McpError,\n payload: {\n ...RequestMeta.fields,\n /**\n * The URI of the resource to subscribe to. The URI can use any protocol;\n * it is up to the server how to interpret it.\n */\n uri: Schema.String\n }\n}) {}\n/**\n * Sent from the server when a subscribed resource URI has changed.\n *\n * **Details**\n *\n * The URI may identify a sub-resource of the resource that the client\n * originally subscribed to.\n *\n * @category resources\n * @since 4.0.0\n */\nexport class ResourceUpdatedNotification extends /*#__PURE__*/Rpc.make(\"notifications/resources/updated\", {\n payload: {\n ...NotificationMeta.fields,\n /**\n * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.\n */\n uri: Schema.String\n }\n}) {}\n// =============================================================================\n// Prompts\n// =============================================================================\n/**\n * Describes an argument that a prompt can accept.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport class PromptArgument extends /*#__PURE__*/Schema.Opaque()(/*#__PURE__*/Schema.Struct({\n /**\n * The name of the argument.\n */\n name: Schema.String,\n title: /*#__PURE__*/optional(Schema.String),\n /**\n * A human-readable description of the argument.\n */\n description: /*#__PURE__*/optional(Schema.String),\n /**\n * Whether this argument must be provided.\n */\n required: /*#__PURE__*/optional(Schema.Boolean)\n})) {}\n/**\n * Represents a prompt or prompt template that the server offers.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport class Prompt extends /*#__PURE__*/Schema.Class(\"@effect/ai/McpSchema/Prompt\")({\n /**\n * The name of the prompt or prompt template.\n */\n name: Schema.String,\n title: /*#__PURE__*/optional(Schema.String),\n /**\n * An optional description of what this prompt provides\n */\n description: /*#__PURE__*/optional(Schema.String),\n /**\n * A list of arguments to use for templating the prompt.\n */\n arguments: /*#__PURE__*/optional(/*#__PURE__*/Schema.Array(PromptArgument))\n}) {}\n/**\n * Represents text content provided to or from an LLM.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport class TextContent extends /*#__PURE__*/Schema.Opaque()(/*#__PURE__*/Schema.Struct({\n type: /*#__PURE__*/Schema.tag(\"text\"),\n /**\n * The text content of the message.\n */\n text: Schema.String,\n /**\n * Optional annotations for the client.\n */\n annotations: /*#__PURE__*/optional(Annotations)\n})) {}\n/**\n * Represents image content provided to or from an LLM.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport class ImageContent extends /*#__PURE__*/Schema.Opaque()(/*#__PURE__*/Schema.Struct({\n type: /*#__PURE__*/Schema.tag(\"image\"),\n /**\n * The image data.\n */\n data: Schema.Uint8Array,\n /**\n * The MIME type of the image. Different providers may support different\n * image types.\n */\n mimeType: Schema.String,\n /**\n * Optional annotations for the client.\n */\n annotations: /*#__PURE__*/optional(Annotations)\n})) {}\n/**\n * Represents audio content provided to or from an LLM.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport class AudioContent extends /*#__PURE__*/Schema.Opaque()(/*#__PURE__*/Schema.Struct({\n type: /*#__PURE__*/Schema.tag(\"audio\"),\n /**\n * The audio data.\n */\n data: Schema.Uint8Array,\n /**\n * The MIME type of the audio. Different providers may support different\n * audio types.\n */\n mimeType: Schema.String,\n /**\n * Optional annotations for the client.\n */\n annotations: /*#__PURE__*/optional(Annotations)\n})) {}\n/**\n * Represents resource contents embedded into a prompt or tool call result.\n *\n * **Details**\n *\n * It is up to the client how best to render embedded resources for the benefit\n * of the LLM and/or the user.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport class EmbeddedResource extends /*#__PURE__*/Schema.Opaque()(/*#__PURE__*/Schema.Struct({\n type: /*#__PURE__*/Schema.tag(\"resource\"),\n resource: /*#__PURE__*/Schema.Union([TextResourceContents, BlobResourceContents]),\n /**\n * Optional annotations for the client.\n */\n annotations: /*#__PURE__*/optional(Annotations)\n})) {}\n/**\n * Represents a readable resource included in a prompt or tool call result.\n *\n * **Gotchas**\n *\n * Resource links returned by tools are not guaranteed to appear in the results\n * of `resources/list` requests.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport class ResourceLink extends /*#__PURE__*/Schema.Opaque()(/*#__PURE__*/Schema.Struct({\n ...Resource.fields,\n type: /*#__PURE__*/Schema.tag(\"resource_link\")\n})) {}\n/**\n * Schema for MCP content blocks that can appear in prompt messages or tool\n * results.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const ContentBlock = /*#__PURE__*/Schema.Union([TextContent, ImageContent, AudioContent, EmbeddedResource, ResourceLink]);\n/**\n * Describes a message returned as part of a prompt.\n *\n * **Details**\n *\n * This is similar to `SamplingMessage`, but also supports the embedding of\n * resources from the MCP server.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport class PromptMessage extends /*#__PURE__*/Schema.Opaque()(/*#__PURE__*/Schema.Struct({\n role: Role,\n content: ContentBlock\n})) {}\n/**\n * Represents the server response to a prompts/list request from the client.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport class ListPromptsResult extends /*#__PURE__*/Schema.Class(\"@effect/ai/McpSchema/ListPromptsResult\")({\n ...PaginatedResultMeta.fields,\n prompts: /*#__PURE__*/Schema.Array(Prompt)\n}) {}\n/**\n * Sent from the client to request a list of prompts and prompt templates the\n * server has.\n *\n * @category protocols\n * @since 4.0.0\n */\nexport class ListPrompts extends /*#__PURE__*/Rpc.make(\"prompts/list\", {\n success: ListPromptsResult,\n error: McpError,\n payload: /*#__PURE__*/Schema.UndefinedOr(PaginatedRequestMeta)\n}) {}\n/**\n * Represents the server response to a prompts/get request from the client.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport class GetPromptResult extends /*#__PURE__*/Schema.Class(\"@effect/ai/McpSchema/GetPromptResult\")({\n ...ResultMeta.fields,\n messages: /*#__PURE__*/Schema.Array(PromptMessage),\n /**\n * An optional description for the prompt.\n */\n description: /*#__PURE__*/optional(Schema.String)\n}) {}\n/**\n * Sent from the client to get a prompt provided by the server.\n *\n * @category protocols\n * @since 4.0.0\n */\nexport class GetPrompt extends /*#__PURE__*/Rpc.make(\"prompts/get\", {\n success: GetPromptResult,\n error: McpError,\n payload: {\n ...RequestMeta.fields,\n /**\n * The name of the prompt or prompt template.\n */\n name: Schema.String,\n title: /*#__PURE__*/optional(Schema.String),\n /**\n * Arguments to use for templating the prompt.\n */\n arguments: /*#__PURE__*/optional(/*#__PURE__*/Schema.Record(Schema.String, Schema.String))\n }\n}) {}\n/**\n * Represents a notification that the server's prompt list changed.\n *\n * **When to use**\n *\n * Use to notify clients that `prompts/list` should be requested again.\n *\n * **Details**\n *\n * Servers may send this notification without a previous client subscription.\n *\n * @category protocols\n * @since 4.0.0\n */\nexport class PromptListChangedNotification extends /*#__PURE__*/Rpc.make(\"notifications/prompts/list_changed\", {\n payload: /*#__PURE__*/Schema.UndefinedOr(NotificationMeta)\n}) {}\n// =============================================================================\n// Tools\n// =============================================================================\n/**\n * Schema for additional properties describing a tool to clients.\n *\n * **Details**\n *\n * NOTE: all properties in ToolAnnotations are **hints**. They are not\n * guaranteed to provide a faithful description of tool behavior (including\n * descriptive properties like `title`).\n *\n * **Gotchas**\n *\n * Clients should never make tool use decisions based on ToolAnnotations\n * received from untrusted servers.\n *\n * @category tools\n * @since 4.0.0\n */\nexport class ToolAnnotations extends /*#__PURE__*/Schema.Opaque()(/*#__PURE__*/Schema.Struct({\n /**\n * A human-readable title for the tool.\n */\n title: /*#__PURE__*/optional(Schema.String),\n /**\n * If true, the tool does not modify its environment.\n *\n * Default: `false`\n */\n readOnlyHint: /*#__PURE__*/optionalWithDefault(Schema.Boolean, constFalse),\n /**\n * If true, the tool may perform destructive updates to its environment.\n * If false, the tool performs only additive updates.\n *\n * (This property is meaningful only when `readOnlyHint == false`)\n *\n * Default: `true`\n */\n destructiveHint: /*#__PURE__*/optionalWithDefault(Schema.Boolean, constTrue),\n /**\n * If true, calling the tool repeatedly with the same arguments\n * will have no additional effect on the its environment.\n *\n * (This property is meaningful only when `readOnlyHint == false`)\n *\n * Default: `false`\n */\n idempotentHint: /*#__PURE__*/optionalWithDefault(Schema.Boolean, constFalse),\n /**\n * If true, this tool may interact with an \"open world\" of external\n * entities. If false, the tool's domain of interaction is closed.\n * For example, the world of a web search tool is open, whereas that\n * of a memory tool is not.\n *\n * Default: `true`\n */\n openWorldHint: /*#__PURE__*/optionalWithDefault(Schema.Boolean, constTrue)\n})) {}\n/**\n * Schema for the definition of a tool the client can call.\n *\n * @category tools\n * @since 4.0.0\n */\nexport class Tool extends /*#__PURE__*/Schema.Class(\"@effect/ai/McpSchema/Tool\")({\n /**\n * The name of the tool.\n */\n name: Schema.String,\n title: /*#__PURE__*/optional(Schema.String),\n /**\n * A human-readable description of the tool.\n *\n * This can be used by clients to improve the LLM's understanding of available tools. It can be thought of like a \"hint\" to the model.\n */\n description: /*#__PURE__*/optional(Schema.String),\n /**\n * A JSON Schema object defining the expected parameters for the tool.\n */\n inputSchema: Schema.Any,\n /**\n * Optional additional tool information.\n */\n annotations: /*#__PURE__*/optional(ToolAnnotations),\n /**\n * Optional additional metadata for the client.\n *\n * This parameter name is reserved by MCP to allow clients and servers to\n * attach additional metadata to resources.\n */\n _meta: /*#__PURE__*/optional(/*#__PURE__*/Schema.Record(Schema.String, Schema.Json))\n}) {}\n/**\n * Schema for the server's response to a tools/list request from the client.\n *\n * @category tools\n * @since 4.0.0\n */\nexport class ListToolsResult extends /*#__PURE__*/Schema.Class(\"@effect/ai/McpSchema/ListToolsResult\")({\n ...PaginatedResultMeta.fields,\n tools: /*#__PURE__*/Schema.Array(Tool)\n}) {}\n/**\n * Sent from the client to request a list of tools the server has.\n *\n * @category tools\n * @since 4.0.0\n */\nexport class ListTools extends /*#__PURE__*/Rpc.make(\"tools/list\", {\n success: ListToolsResult,\n error: McpError,\n payload: /*#__PURE__*/Schema.UndefinedOr(PaginatedRequestMeta)\n}) {}\n/**\n * Schema for the server's response to a tool call.\n *\n * **Details**\n *\n * Any errors that originate from the tool SHOULD be reported inside the result\n * object, with `isError` set to true, _not_ as an MCP protocol-level error\n * response. Otherwise, the LLM would not be able to see that an error occurred\n * and self-correct. However, any errors in _finding_ the tool, an error\n * indicating that the server does not support tool calls, or any other\n * exceptional conditions, should be reported as an MCP error response.\n *\n * @category tools\n * @since 4.0.0\n */\nexport class CallToolResult extends /*#__PURE__*/Schema.Class(\"@effect/ai/McpSchema/CallToolResult\")({\n ...ResultMeta.fields,\n content: /*#__PURE__*/Schema.Array(ContentBlock),\n structuredContent: /*#__PURE__*/optional(Schema.Any),\n /**\n * Whether the tool call ended in an error.\n *\n * If not set, this is assumed to be false (the call was successful).\n */\n isError: /*#__PURE__*/optional(Schema.Boolean)\n}) {}\n/**\n * Represents a client request to invoke a tool provided by the server.\n *\n * **When to use**\n *\n * Use when you need to represent a client request that already knows the tool\n * name and asks the server to execute it with argument values.\n *\n * @see {@link ListTools} for discovering available tools before calling one\n * @see {@link CallToolResult} for the successful tool-call result shape\n *\n * @category tools\n * @since 4.0.0\n */\nexport class CallTool extends /*#__PURE__*/Rpc.make(\"tools/call\", {\n success: CallToolResult,\n error: McpError,\n payload: {\n ...RequestMeta.fields,\n name: Schema.String,\n arguments: /*#__PURE__*/Schema.Record(Schema.String, Schema.Any)\n }\n}) {}\n/**\n * Represents a notification that the server's tool list changed.\n *\n * **When to use**\n *\n * Use to notify clients that `tools/list` should be requested again.\n *\n * **Details**\n *\n * Servers may send this notification without a previous client subscription.\n *\n * @category tools\n * @since 4.0.0\n */\nexport class ToolListChangedNotification extends /*#__PURE__*/Rpc.make(\"notifications/tools/list_changed\", {\n payload: /*#__PURE__*/Schema.UndefinedOr(NotificationMeta)\n}) {}\n// =============================================================================\n// Logging\n// =============================================================================\n/**\n * Schema for log message severity levels, mapped to syslog message severities\n * as specified in RFC 5424 section 6.2.1:\n * https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1.\n *\n * @category logging\n * @since 4.0.0\n */\nexport const LoggingLevel = /*#__PURE__*/Schema.Literals([\"debug\", \"info\", \"notice\", \"warning\", \"error\", \"critical\", \"alert\", \"emergency\"]);\n/**\n * Sent from the client to the server to enable or adjust logging.\n *\n * @category logging\n * @since 4.0.0\n */\nexport class SetLevel extends /*#__PURE__*/Rpc.make(\"logging/setLevel\", {\n payload: {\n ...RequestMeta.fields,\n /**\n * The level of logging that the client wants to receive from the server.\n * The server should send all logs at this level and higher (i.e., more\n * severe) to the client as notifications/message.\n */\n level: LoggingLevel\n },\n error: McpError\n}) {}\n/**\n * Sent from the server to the client carrying a log message.\n *\n * **Details**\n *\n * The notification includes the severity level, optional logger name, and\n * JSON-serializable log data.\n *\n * @category logging\n * @since 4.0.0\n */\nexport class LoggingMessageNotification extends /*#__PURE__*/Rpc.make(\"notifications/message\", {\n payload: /*#__PURE__*/Schema.Struct({\n ...NotificationMeta.fields,\n /**\n * The severity of this log message.\n */\n level: LoggingLevel,\n /**\n * An optional name of the logger issuing this message.\n */\n logger: /*#__PURE__*/optional(Schema.String),\n /**\n * The data to be logged, such as a string message or an object. Any JSON\n * serializable type is allowed here.\n */\n data: Schema.Any\n })\n}) {}\n// =============================================================================\n// Sampling\n// =============================================================================\n/**\n * Describes a message issued to or received from an LLM API.\n *\n * @category sampling\n * @since 4.0.0\n */\nexport class SamplingMessage extends /*#__PURE__*/Schema.Opaque()(/*#__PURE__*/Schema.Struct({\n role: Role,\n content: /*#__PURE__*/Schema.Union([TextContent, ImageContent, AudioContent])\n})) {}\n/**\n * Schema for model selection hints.\n *\n * **Details**\n *\n * Keys not declared here are currently left unspecified by the spec and are up\n * to the client to interpret.\n *\n * @category sampling\n * @since 4.0.0\n */\nexport class ModelHint extends /*#__PURE__*/Schema.Opaque()(/*#__PURE__*/Schema.Struct({\n /**\n * A hint for a model name.\n *\n * The client SHOULD treat this as a substring of a model name; for example:\n * - `claude-3-5-sonnet` should match `claude-3-5-sonnet-20241022`\n * - `sonnet` should match `claude-3-5-sonnet-20241022`, `claude-3-sonnet-20240229`, etc.\n * - `claude` should match any Claude model\n *\n * The client MAY also map the string to a different provider's model name or\n * a different model family, as long as it fills a similar niche; for example:\n * - `gemini-1.5-flash` could match `claude-3-haiku-20240307`\n */\n name: /*#__PURE__*/optional(Schema.String)\n})) {}\n/**\n * Schema for the server's model selection preferences requested of the client\n * during sampling.\n *\n * **Details**\n *\n * Because LLMs can vary along multiple dimensions, choosing the \"best\" model is\n * rarely straightforward. Different models excel in different areas, some are\n * faster but less capable, others are more capable but more expensive, and so\n * on. This interface allows servers to express their priorities across multiple\n * dimensions to help clients make an appropriate selection for their use case.\n *\n * **Gotchas**\n *\n * These preferences are always advisory. The client MAY ignore them. It is also\n * up to the client to decide how to interpret these preferences and how to\n * balance them against other considerations.\n *\n * @category sampling\n * @since 4.0.0\n */\nexport class ModelPreferences extends /*#__PURE__*/Schema.Class(\"@effect/ai/McpSchema/ModelPreferences\")({\n /**\n * Optional hints to use for model selection.\n *\n * If multiple hints are specified, the client MUST evaluate them in order\n * (such that the first match is taken).\n *\n * The client SHOULD prioritize these hints over the numeric priorities, but\n * MAY still use the priorities to select from ambiguous matches.\n */\n hints: /*#__PURE__*/optional(/*#__PURE__*/Schema.Array(ModelHint)),\n /**\n * How much to prioritize cost when selecting a model. A value of 0 means cost\n * is not important, while a value of 1 means cost is the most important\n * factor.\n */\n costPriority: /*#__PURE__*/optional(/*#__PURE__*/Schema.Number.check(/*#__PURE__*/Schema.isBetween({\n minimum: 0,\n maximum: 1\n }))),\n /**\n * How much to prioritize sampling speed (latency) when selecting a model. A\n * value of 0 means speed is not important, while a value of 1 means speed is\n * the most important factor.\n */\n speedPriority: /*#__PURE__*/optional(/*#__PURE__*/Schema.Number.check(/*#__PURE__*/Schema.isBetween({\n minimum: 0,\n maximum: 1\n }))),\n /**\n * How much to prioritize intelligence and capabilities when selecting a\n * model. A value of 0 means intelligence is not important, while a value of 1\n * means intelligence is the most important factor.\n */\n intelligencePriority: /*#__PURE__*/optional(/*#__PURE__*/Schema.Number.check(/*#__PURE__*/Schema.isBetween({\n minimum: 0,\n maximum: 1\n })))\n}) {}\n/**\n * Represents a client response to an MCP sampling request.\n *\n * **When to use**\n *\n * Use to return the message produced by client-side model sampling.\n *\n * **Details**\n *\n * The client should let the user inspect the sampled message before returning\n * it to the server.\n *\n * @category sampling\n * @since 4.0.0\n */\nexport class CreateMessageResult extends /*#__PURE__*/Schema.Class(\"@effect/ai/McpSchema/CreateMessageResult\")({\n /**\n * The name of the model that generated the message.\n */\n model: Schema.String,\n /**\n * The reason why sampling stopped, if known.\n */\n stopReason: /*#__PURE__*/optional(Schema.String)\n}) {}\n/**\n * Represents a server request for the client to sample an LLM.\n *\n * **When to use**\n *\n * Use when you need to request model sampling from an MCP client on behalf of a\n * server.\n *\n * **Details**\n *\n * The client chooses the model and should ask the user to approve the sampling\n * request before it begins.\n *\n * @category sampling\n * @since 4.0.0\n */\nexport class CreateMessage extends /*#__PURE__*/Rpc.make(\"sampling/createMessage\", {\n success: CreateMessageResult,\n error: McpError,\n payload: {\n messages: /*#__PURE__*/Schema.Array(SamplingMessage),\n /**\n * The server's preferences for which model to select. The client MAY ignore\n * these preferences.\n */\n modelPreferences: /*#__PURE__*/optional(ModelPreferences),\n /**\n * An optional system prompt the server wants to use for sampling. The\n * client MAY modify or omit this prompt.\n */\n systemPrompt: /*#__PURE__*/optional(Schema.String),\n /**\n * A request to include context from one or more MCP servers (including the\n * caller), to be attached to the prompt. The client MAY ignore this request.\n */\n includeContext: /*#__PURE__*/optional(/*#__PURE__*/Schema.Literals([\"none\", \"thisServer\", \"allServers\"])),\n temperature: /*#__PURE__*/optional(Schema.Number),\n /**\n * The maximum number of tokens to sample, as requested by the server. The\n * client MAY choose to sample fewer tokens than requested.\n */\n maxTokens: Schema.Number,\n stopSequences: /*#__PURE__*/optional(/*#__PURE__*/Schema.Array(Schema.String)),\n /**\n * Optional metadata to pass through to the LLM provider. The format of\n * this metadata is provider-specific.\n */\n metadata: Schema.Any\n }\n}) {}\n// =============================================================================\n// Autocomplete\n// =============================================================================\n/**\n * Schema for a reference to a resource or resource template definition.\n *\n * @category autocomplete\n * @since 4.0.0\n */\nexport class ResourceReference extends /*#__PURE__*/Schema.Opaque()(/*#__PURE__*/Schema.Struct({\n type: /*#__PURE__*/Schema.tag(\"ref/resource\"),\n /**\n * The URI or URI template of the resource.\n */\n uri: Schema.String\n})) {}\n/**\n * Schema for a prompt reference used in autocomplete requests.\n *\n * @category autocomplete\n * @since 4.0.0\n */\nexport class PromptReference extends /*#__PURE__*/Schema.Opaque()(/*#__PURE__*/Schema.Struct({\n type: /*#__PURE__*/Schema.tag(\"ref/prompt\"),\n /**\n * The name of the prompt or prompt template\n */\n name: Schema.String,\n title: /*#__PURE__*/optional(Schema.String)\n})) {}\n/**\n * Schema for the server's response to a completion/complete request.\n *\n * @category autocomplete\n * @since 4.0.0\n */\nexport class CompleteResult extends /*#__PURE__*/Schema.Opaque()(/*#__PURE__*/Schema.Struct({\n completion: /*#__PURE__*/Schema.Struct({\n /**\n * An array of completion values. Must not exceed 100 items.\n */\n values: /*#__PURE__*/Schema.Array(Schema.String),\n /**\n * The total number of completion options available. This can exceed the\n * number of values actually sent in the response.\n */\n total: /*#__PURE__*/optional(Schema.Number),\n /**\n * Indicates whether there are additional completion options beyond those\n * provided in the current response, even if the exact total is unknown.\n */\n hasMore: /*#__PURE__*/optional(Schema.Boolean)\n })\n})) {\n /**\n * Empty completion result used when a completion request has no values.\n *\n * @since 4.0.0\n */\n static empty = /*#__PURE__*/CompleteResult.make({\n completion: {\n values: [],\n total: 0,\n hasMore: false\n }\n });\n}\n/**\n * Sent from the client to the server to ask for completion options.\n *\n * @category autocomplete\n * @since 4.0.0\n */\nexport class Complete extends /*#__PURE__*/Rpc.make(\"completion/complete\", {\n success: CompleteResult,\n error: McpError,\n payload: /*#__PURE__*/Schema.Struct({\n ref: /*#__PURE__*/Schema.Union([PromptReference, ResourceReference]),\n /**\n * The argument's information\n */\n argument: /*#__PURE__*/Schema.Struct({\n /**\n * The name of the argument\n */\n name: Schema.String,\n /**\n * The value of the argument to use for completion matching.\n */\n value: Schema.String\n }),\n /**\n * Additional, optional context for completions\n */\n context: /*#__PURE__*/optionalWithDefault(/*#__PURE__*/Schema.Struct({\n /**\n * Previously-resolved variables in a URI template or prompt.\n */\n arguments: /*#__PURE__*/optionalWithDefault(/*#__PURE__*/Schema.Record(Schema.String, Schema.String), () => ({}))\n }), () => ({\n arguments: {}\n }))\n })\n}) {}\n// =============================================================================\n// Roots\n// =============================================================================\n/**\n * Represents a root directory or file that the server can operate on.\n *\n * @category roots\n * @since 4.0.0\n */\nexport class Root extends /*#__PURE__*/Schema.Class(\"@effect/ai/McpSchema/Root\")({\n /**\n * The URI identifying the root. This *must* start with file:// for now.\n * This restriction may be relaxed in future versions of the protocol to allow\n * other URI schemes.\n */\n uri: Schema.String,\n /**\n * An optional name for the root. This can be used to provide a human-readable\n * identifier for the root, which may be useful for display purposes or for\n * referencing the root in other parts of the application.\n */\n name: /*#__PURE__*/optional(Schema.String)\n}) {}\n/**\n * Represents a client response containing the roots available to the server.\n *\n * **When to use**\n *\n * Use to return the directories or files that an MCP server may operate on.\n *\n * @category roots\n * @since 4.0.0\n */\nexport class ListRootsResult extends /*#__PURE__*/Schema.Class(\"@effect/ai/McpSchema/ListRootsResult\")({\n roots: /*#__PURE__*/Schema.Array(Root)\n}) {}\n/**\n * Sent from the server to request a list of root URIs from the client. Roots\n * allow servers to ask for specific directories or files to operate on. A\n * common example for roots is providing a set of repositories or directories a\n * server should operate on.\n *\n * **Details**\n *\n * This request is typically used when the server needs to understand the file\n * system structure or access specific locations that the client has permission\n * to read from.\n *\n * @category roots\n * @since 4.0.0\n */\nexport class ListRoots extends /*#__PURE__*/Rpc.make(\"roots/list\", {\n success: ListRootsResult,\n error: McpError,\n payload: /*#__PURE__*/Schema.UndefinedOr(RequestMeta)\n}) {}\n/**\n * Represents a notification that the client's root list changed.\n *\n * **When to use**\n *\n * Use to tell the server that it should request an updated roots list.\n *\n * **Details**\n *\n * Send this when the client adds, removes, or modifies a root.\n *\n * @category roots\n * @since 4.0.0\n */\nexport class RootsListChangedNotification extends /*#__PURE__*/Rpc.make(\"notifications/roots/list_changed\", {\n payload: /*#__PURE__*/Schema.UndefinedOr(NotificationMeta)\n}) {}\n// =============================================================================\n// Elicitation\n// =============================================================================\n/**\n * Schema for an accepted client response to an elicitation request.\n *\n * @category elicitation\n * @since 4.0.0\n */\nexport class ElicitAcceptResult extends /*#__PURE__*/Schema.Class(\"@effect/ai/McpSchema/ElicitAcceptResult\")({\n ...ResultMeta.fields,\n /**\n * The user action in response to the elicitation.\n * - \"accept\": User submitted the form/confirmed the action\n * - \"decline\": User explicitly declined the action\n * - \"cancel\": User dismissed without making an explicit choice\n */\n action: /*#__PURE__*/Schema.Literal(\"accept\"),\n /**\n * The submitted form data, only present when action is \"accept\".\n * Contains values matching the requested schema.\n */\n content: Schema.Any\n}) {}\n/**\n * Schema for a declined or canceled client response to an elicitation request.\n *\n * @category elicitation\n * @since 4.0.0\n */\nexport class ElicitDeclineResult extends /*#__PURE__*/Schema.Class(\"@effect/ai/McpSchema/ElicitDeclineResult\")({\n ...ResultMeta.fields,\n /**\n * The user action in response to the elicitation.\n * - \"accept\": User submitted the form/confirmed the action\n * - \"decline\": User explicitly declined the action\n * - \"cancel\": User dismissed without making an explicit choice\n */\n action: /*#__PURE__*/Schema.Literals([\"cancel\", \"decline\"])\n}) {}\n/**\n * Schema for every client response to an elicitation request.\n *\n * @category elicitation\n * @since 4.0.0\n */\nexport const ElicitResult = /*#__PURE__*/Schema.Union([ElicitAcceptResult, ElicitDeclineResult]);\n/**\n * Sent from the server asking the client to collect structured input from the\n * user.\n *\n * **Details**\n *\n * The client responds with accepted content, an explicit decline, or a\n * cancellation.\n *\n * @category elicitation\n * @since 4.0.0\n */\nexport class Elicit extends /*#__PURE__*/Rpc.make(\"elicitation/create\", {\n success: ElicitResult,\n error: McpError,\n payload: {\n /**\n * A message to display to the user, explaining what they are being\n * elicited for.\n */\n message: Schema.String,\n /**\n * A restricted subset of JSON Schema.\n * Only top-level properties are allowed, without nesting.\n */\n requestedSchema: Schema.Any\n }\n}) {}\n/**\n * Error raised when an MCP elicitation request is declined or fails before\n * accepted content is returned.\n *\n * **Details**\n *\n * The error stores the original elicitation request and, when available, the\n * underlying cause.\n *\n * @category elicitation\n * @since 4.0.0\n */\nexport class ElicitationDeclined extends /*#__PURE__*/Schema.ErrorClass(\"@effect/ai/McpSchema/ElicitationDeclined\")({\n _tag: /*#__PURE__*/Schema.tag(\"ElicitationDeclined\"),\n request: Elicit.payloadSchema,\n cause: /*#__PURE__*/optional(/*#__PURE__*/Schema.Defect())\n}) {}\n// =============================================================================\n// McpServerClient\n// =============================================================================\n/**\n * Service available while handling an MCP client request.\n *\n * **Details**\n *\n * It exposes the current client id, the client's initialize payload, and a\n * scoped RPC client for server-initiated requests back to that client.\n *\n * @category client\n * @since 4.0.0\n */\nexport class McpServerClient extends /*#__PURE__*/Context.Service()(\"effect/ai/McpSchema/McpServerClient\") {}\n/**\n * RPC middleware that provides `McpServerClient` to handlers for initialized\n * MCP clients.\n *\n * @category middleware\n * @since 4.0.0\n */\nexport class McpServerClientMiddleware extends /*#__PURE__*/RpcMiddleware.Service()(\"effect/ai/McpSchema/McpServerClientMiddleware\") {}\n/**\n * RPC group for requests that MCP clients send to the server.\n *\n * **Details**\n *\n * The group includes initialization, resource, prompt, tool, logging,\n * completion, and ping requests, and installs `McpServerClientMiddleware` for\n * handlers.\n *\n * @category protocols\n * @since 4.0.0\n */\nexport class ClientRequestRpcs extends /*#__PURE__*/RpcGroup.make(Ping, Initialize, Complete, SetLevel, GetPrompt, ListPrompts, ListResources, ListResourceTemplates, ReadResource, Subscribe, Unsubscribe, CallTool, ListTools).middleware(McpServerClientMiddleware) {}\n/**\n * RPC group for notifications that MCP clients send to the server, such as\n * cancellation, progress, initialization completion, and roots list changes.\n *\n * @category protocols\n * @since 4.0.0\n */\nexport class ClientNotificationRpcs extends /*#__PURE__*/RpcGroup.make(CancelledNotification, ProgressNotification, InitializedNotification, RootsListChangedNotification) {}\n/**\n * RPC group combining all client-to-server MCP requests and notifications.\n *\n * @category protocols\n * @since 4.0.0\n */\nexport class ClientRpcs extends /*#__PURE__*/ClientRequestRpcs.merge(ClientNotificationRpcs) {}\n/**\n * RPC group for requests that an MCP server can send to a client, including\n * ping, sampling, roots listing, and elicitation.\n *\n * @category protocols\n * @since 4.0.0\n */\nexport class ServerRequestRpcs extends /*#__PURE__*/RpcGroup.make(Ping, CreateMessage, ListRoots, Elicit) {}\n/**\n * RPC group for notifications that an MCP server can send to a client,\n * including cancellation, progress, logging, and list or resource update\n * notifications.\n *\n * @category protocols\n * @since 4.0.0\n */\nexport class ServerNotificationRpcs extends /*#__PURE__*/RpcGroup.make(CancelledNotification, ProgressNotification, LoggingMessageNotification, ResourceUpdatedNotification, ResourceListChangedNotification, ToolListChangedNotification, PromptListChangedNotification) {}\nconst ParamSchemaTypeId = \"~effect/ai/McpSchema/ParamSchema\";\n/**\n * Returns `true` when a schema was created with `param` and therefore carries\n * a resource URI template parameter name.\n *\n * @category parameters\n * @since 4.0.0\n */\nexport function isParam(schema) {\n return Predicate.hasProperty(schema, ParamSchemaTypeId);\n}\n/**\n * Creates a parameter for a resource URI template.\n *\n * @category parameters\n * @since 4.0.0\n */\nexport function param(name, schema) {\n return Schema.make(schema.ast, {\n [ParamSchemaTypeId]: ParamSchemaTypeId,\n name,\n schema\n });\n}\n/**\n * Annotation to conditionally enable or disable tools based on client\n * information.\n *\n * @category annotations\n * @since 4.0.0\n */\nexport class EnabledWhen extends /*#__PURE__*/Context.Service()(\"effect/unstable/ai/McpSchema/EnabledWhen\") {}\n//# sourceMappingURL=McpSchema.js.map","/**\n * Builds Model Context Protocol (MCP) servers with Effect.\n *\n * The `McpServer` service stores the tools, resources, resource templates,\n * prompts, completions, initialized clients, and outgoing notifications exposed\n * by a server. This module also includes the server runner, custom protocol,\n * stdio, and HTTP layers, registration helpers, and APIs that let handlers ask\n * the connected client for structured input or read its advertised\n * capabilities.\n *\n * @since 4.0.0\n */\nimport * as Arr from \"../../Array.js\";\nimport * as Cause from \"../../Cause.js\";\nimport * as Context from \"../../Context.js\";\nimport * as Effect from \"../../Effect.js\";\nimport * as Exit from \"../../Exit.js\";\nimport * as Fiber from \"../../Fiber.js\";\nimport * as Layer from \"../../Layer.js\";\nimport * as Option from \"../../Option.js\";\nimport * as Queue from \"../../Queue.js\";\nimport * as RcMap from \"../../RcMap.js\";\nimport { CurrentLogLevel } from \"../../References.js\";\nimport * as Schema from \"../../Schema.js\";\nimport * as SchemaAST from \"../../SchemaAST.js\";\nimport * as Sink from \"../../Sink.js\";\nimport * as Stream from \"../../Stream.js\";\nimport * as FindMyWay from \"../http/FindMyWay.js\";\nimport * as Headers from \"../http/Headers.js\";\nimport { appendPreResponseHandlerUnsafe } from \"../http/HttpEffect.js\";\nimport * as HttpRouter from \"../http/HttpRouter.js\";\nimport * as HttpServerRequest from \"../http/HttpServerRequest.js\";\nimport * as HttpServerResponse from \"../http/HttpServerResponse.js\";\nimport * as Rpc from \"../rpc/Rpc.js\";\nimport * as RpcClient from \"../rpc/RpcClient.js\";\nimport * as RpcMessage from \"../rpc/RpcMessage.js\";\nimport * as RpcSerialization from \"../rpc/RpcSerialization.js\";\nimport * as RpcServer from \"../rpc/RpcServer.js\";\nimport { CallToolResult, ClientNotificationRpcs, ClientRpcs, CompleteResult, Elicit, ElicitationDeclined, EnabledWhen, GetPromptResult, InternalError, InvalidParams, isParam, ListPromptsResult, ListResourcesResult, ListResourceTemplatesResult, ListToolsResult, McpServerClient, McpServerClientMiddleware, Prompt, Resource, ResourceTemplate, ServerNotificationRpcs, ServerRequestRpcs, TextContent, Tool as McpTool } from \"./McpSchema.js\";\nimport * as Tool from \"./Tool.js\";\n/**\n * Service that stores and serves an MCP server's registered tools, resources,\n * prompts, completions, and outgoing notifications.\n *\n * **Details**\n *\n * Handlers use this service to register capabilities and resolve incoming MCP\n * requests.\n *\n * @category server\n * @since 4.0.0\n */\nexport class McpServer extends /*#__PURE__*/Context.Service()(\"effect/ai/McpServer\") {\n /**\n * Builds an MCP server service from registered tools, prompts, resources, and completions.\n *\n * @since 4.0.0\n */\n static make = /*#__PURE__*/Effect.gen(function* () {\n const matcher = makeUriMatcher();\n const tools = Arr.empty();\n const toolMap = new Map();\n const resources = [];\n const resourceTemplates = [];\n const prompts = [];\n const promptMap = new Map();\n const completionsMap = new Map();\n const notificationsQueue = yield* Queue.make();\n const listChangedHandles = new Map();\n const notifications = yield* RpcClient.makeNoSerialization(ServerNotificationRpcs, {\n spanPrefix: \"McpServer/Notifications\",\n onFromClient: options => Effect.suspend(() => {\n const message = options.message;\n if (message._tag !== \"Request\") {\n return Effect.void;\n }\n if (message.tag.includes(\"list_changed\")) {\n if (!listChangedHandles.has(message.tag)) {\n listChangedHandles.set(message.tag, setTimeout(() => {\n Queue.offerUnsafe(notificationsQueue, message);\n listChangedHandles.delete(message.tag);\n }, 0));\n }\n } else {\n Queue.offerUnsafe(notificationsQueue, message);\n }\n return notifications.write({\n clientId: 0,\n requestId: message.id,\n _tag: \"Exit\",\n exit: Exit.void\n });\n })\n });\n return McpServer.of({\n notifications: notifications.client,\n notificationsQueue,\n initializedClients: new Set(),\n get tools() {\n return tools;\n },\n addTool: options => Effect.suspend(() => {\n tools.push(options);\n toolMap.set(options.tool.name, options.handle);\n return notifications.client[\"notifications/tools/list_changed\"]({});\n }),\n callTool: request => Effect.suspend(() => {\n const handle = toolMap.get(request.name);\n if (!handle) {\n return Effect.fail(new InvalidParams({\n message: `Tool '${request.name}' not found`\n }));\n }\n return handle(request.arguments);\n }),\n get resources() {\n return resources;\n },\n get resourceTemplates() {\n return resourceTemplates;\n },\n addResource: options => Effect.suspend(() => {\n resources.push(options);\n matcher.add(options.resource.uri, {\n _tag: \"Resource\",\n effect: options.handle\n });\n return notifications.client[\"notifications/resources/list_changed\"]({});\n }),\n addResourceTemplate: ({\n annotations,\n completions,\n handle,\n routerPath,\n template\n }) => Effect.suspend(() => {\n resourceTemplates.push({\n template,\n annotations\n });\n matcher.add(routerPath, {\n _tag: \"ResourceTemplate\",\n handle\n });\n for (const [param, handle] of Object.entries(completions)) {\n completionsMap.set(`ref/resource/${template.uriTemplate}/${param}`, handle);\n }\n return notifications.client[\"notifications/resources/list_changed\"]({});\n }),\n findResource: uri => Effect.suspend(() => {\n const match = matcher.find(uri);\n if (!match) {\n return Effect.succeed({\n contents: []\n });\n } else if (match.handler._tag === \"Resource\") {\n return match.handler.effect;\n }\n const params = [];\n for (const key of Object.keys(match.params)) {\n params[Number(key)] = match.params[key];\n }\n return match.handler.handle(uri, params);\n }),\n get prompts() {\n return prompts;\n },\n addPrompt: options => Effect.suspend(() => {\n prompts.push(options);\n promptMap.set(options.prompt.name, options.handle);\n for (const [param, handle] of Object.entries(options.completions)) {\n completionsMap.set(`ref/prompt/${options.prompt.name}/${param}`, handle);\n }\n return notifications.client[\"notifications/prompts/list_changed\"]({});\n }),\n getPromptResult: Effect.fnUntraced(function* ({\n arguments: params,\n name\n }) {\n const handler = promptMap.get(name);\n if (!handler) {\n return yield* new InvalidParams({\n message: `Prompt '${name}' not found`\n });\n }\n return yield* handler(params ?? {});\n }),\n completion: Effect.fnUntraced(function* (complete) {\n const ref = complete.ref;\n const key = ref.type === \"ref/resource\" ? `ref/resource/${ref.uri}/${complete.argument.name}` : `ref/prompt/${ref.name}/${complete.argument.name}`;\n const handler = completionsMap.get(key);\n return handler ? yield* handler(complete.argument.value) : CompleteResult.empty;\n })\n });\n });\n /**\n * Layer that provides the MCP server and client services.\n *\n * @since 4.0.0\n */\n static layer = /*#__PURE__*/Layer.effect(McpServer)(McpServer.make);\n}\nconst LATEST_PROTOCOL_VERSION = \"2025-06-18\";\nconst SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, \"2025-03-26\", \"2024-11-05\", \"2024-10-07\"];\nconst mcpSessionIdHeader = \"mcp-session-id\";\nconst mcpProtocolVersionHeader = \"mcp-protocol-version\";\n/**\n * Runs an MCP server over the current `RpcServer.Protocol`.\n *\n * **Details**\n *\n * The server performs initialization and session handling, serves registered\n * tools, resources, and prompts, and forwards queued server notifications to\n * initialized clients.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const run = /*#__PURE__*/Effect.fnUntraced(function* (options) {\n const protocol = yield* RpcServer.Protocol;\n const server = yield* McpServer;\n const isHttp = Option.isSome(yield* Effect.serviceOption(HttpRouter.HttpRouter));\n const clientSessions = new Map();\n const handlers = yield* Layer.build(layerHandlers(options, {\n clientSessions\n }));\n const clients = yield* RcMap.make({\n lookup: Effect.fnUntraced(function* (clientId) {\n let write;\n const client = yield* RpcClient.make(ServerRequestRpcs, {\n spanPrefix: \"McpServer/Client\"\n }).pipe(Effect.provideServiceEffect(RpcClient.Protocol, RpcClient.Protocol.make(Effect.fnUntraced(function* (writeResponse) {\n let cid = 0;\n write = message => writeResponse(cid, message);\n return {\n send(id, request, _transferables) {\n cid = id;\n return protocol.send(clientId, {\n ...request,\n headers: undefined,\n traceId: undefined,\n spanId: undefined,\n sampled: undefined\n });\n },\n supportsAck: true,\n supportsTransferables: false,\n supportsStructuredClone: false\n };\n }))));\n return {\n client,\n write\n };\n }),\n idleTimeToLive: 10000\n });\n const clientMiddleware = McpServerClientMiddleware.of((effect, {\n client,\n headers,\n rpc\n }) => {\n const initializePayload = getInitializedClient(clientSessions, client.id, headers);\n const isInitialize = rpc._tag === \"initialize\";\n if (!isInitialize && !initializePayload) {\n const fiber = Fiber.getCurrent();\n const httpRequest = Context.getOrUndefined(fiber.context, HttpServerRequest.HttpServerRequest);\n if (httpRequest) {\n appendPreResponseHandlerUnsafe(httpRequest, () => Effect.succeed(HttpServerResponse.empty({\n status: 404\n })));\n }\n return Effect.die(new Error(`Mcp-Session-Id does not exist`));\n }\n return Effect.provideService(effect, McpServerClient, McpServerClient.of({\n clientId: client.id,\n initializePayload: initializePayload,\n getClient: RcMap.get(clients, client.id).pipe(Effect.map(({\n client\n }) => client))\n }));\n });\n const patchedProtocol = RpcServer.Protocol.of({\n ...protocol,\n run: f => protocol.run((clientId, request_) => {\n const request = request_;\n switch (request._tag) {\n case \"Request\":\n {\n if (isHttp) {\n const fiber = Fiber.getCurrent();\n const httpRequest = Context.getUnsafe(fiber.context, HttpServerRequest.HttpServerRequest);\n const client = getInitializedClient(clientSessions, clientId, httpRequest.headers);\n if (client) {\n appendPreResponseHandlerUnsafe(httpRequest, (_, res) => Effect.succeed(HttpServerResponse.setHeader(res, mcpProtocolVersionHeader, client.protocolVersion)));\n }\n }\n const rpc = ClientNotificationRpcs.requests.get(request.tag);\n if (rpc) {\n if (request.tag === \"notifications/cancelled\") {\n return f(clientId, {\n _tag: \"Interrupt\",\n requestId: String(request.payload.requestId)\n });\n }\n const handler = handlers.mapUnsafe.get(request.tag);\n return handler ? handler.handler(request.payload, {\n rpc,\n requestId: RpcMessage.RequestId(request.id),\n client: new Rpc.ServerClient(clientId),\n headers: Headers.fromInput(request.headers)\n }) : Effect.void;\n }\n return f(clientId, request);\n }\n case \"Ping\":\n case \"Ack\":\n case \"Interrupt\":\n case \"Eof\":\n return f(clientId, request);\n case \"Pong\":\n case \"Exit\":\n case \"Chunk\":\n case \"ClientProtocolError\":\n case \"Defect\":\n return RcMap.get(clients, clientId).pipe(Effect.flatMap(({\n write\n }) => write(request)), Effect.scoped);\n }\n })\n });\n const encodeNotification = Schema.encodeUnknownEffect(Schema.Union(Array.from(ServerNotificationRpcs.requests.values(), rpc => rpc.payloadSchema)));\n yield* Queue.take(server.notificationsQueue).pipe(Effect.flatMap(Effect.fnUntraced(function* (request) {\n const encoded = yield* encodeNotification(request.payload);\n const message = {\n _tag: \"Request\",\n tag: request.tag,\n payload: encoded\n };\n const clientIds = yield* patchedProtocol.clientIds;\n for (const clientId of server.initializedClients.keys()) {\n if (!clientIds.has(clientId)) {\n server.initializedClients.delete(clientId);\n continue;\n }\n yield* patchedProtocol.send(clientId, message);\n }\n })), Effect.catchCause(() => Effect.void), Effect.forever, Effect.forkScoped);\n return yield* RpcServer.make(ClientRpcs, {\n spanPrefix: \"McpServer\",\n disableFatalDefects: true\n }).pipe(Effect.provideService(RpcServer.Protocol, patchedProtocol), Effect.provideService(McpServerClientMiddleware, clientMiddleware), Effect.provide(handlers));\n}, Effect.scoped);\n/**\n * Creates a layer that starts an MCP server over an existing\n * `RpcServer.Protocol` and provides the `McpServer` and `McpServerClient`\n * services.\n *\n * **When to use**\n *\n * Use when you already have a custom or externally provided\n * `RpcServer.Protocol` and want to start an MCP server as part of a layer\n * graph.\n *\n * **Details**\n *\n * The returned layer forks `run(options)` in the layer scope and merges\n * `McpServer.layer`, so registration layers can use the `McpServer` service\n * while the server is running.\n *\n * **Gotchas**\n *\n * Unlike `layerStdio` and `layerHttp`, this layer does not install a concrete\n * transport. The surrounding layer graph must provide `RpcServer.Protocol`.\n *\n * @see {@link run} for the effect form used by this layer\n * @see {@link layerStdio} for a stdio-backed layer that installs the MCP protocol and NDJSON-RPC serialization\n * @see {@link layerHttp} for an HTTP-backed layer that registers with `HttpRouter` and installs JSON-RPC serialization\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layer = options => Layer.effectDiscard(Effect.forkScoped(run(options))).pipe(Layer.provideMerge(McpServer.layer));\n/**\n * Runs the McpServer, using stdio for input and output.\n *\n * **Example** (Running an MCP server over stdio)\n *\n * ```ts\n * import { Effect, Layer, Logger, Schema } from \"effect\"\n * import { NodeRuntime, NodeStdio } from \"@effect/platform-node\"\n * import { McpSchema, McpServer } from \"effect/unstable/ai\"\n *\n * const idParam = McpSchema.param(\"id\", Schema.Number)\n *\n * // Define a resource template for a README file\n * const ReadmeTemplate = McpServer.resource`file://readme/${idParam}`({\n * name: \"README Template\",\n * // You can add auto-completion for the ID parameter\n * completion: {\n * id: (_) => Effect.succeed([1, 2, 3, 4, 5])\n * },\n * content: Effect.fn(function*(_uri, id) {\n * return `# MCP Server Demo - ID: ${id}`\n * })\n * })\n *\n * // Define a test prompt with parameters\n * const TestPrompt = McpServer.prompt({\n * name: \"Test Prompt\",\n * description: \"A test prompt to demonstrate MCP server capabilities\",\n * parameters: {\n * flightNumber: Schema.String\n * },\n * completion: {\n * flightNumber: () => Effect.succeed([\"FL123\", \"FL456\", \"FL789\"])\n * },\n * content: ({ flightNumber }) =>\n * Effect.succeed(`Get the booking details for flight number: ${flightNumber}`)\n * })\n *\n * // Merge all the resources and prompts into a single server layer\n * const ServerLayer = Layer.mergeAll(\n * ReadmeTemplate,\n * TestPrompt\n * ).pipe(\n * // Provide the MCP server implementation\n * Layer.provide(McpServer.layerStdio({\n * name: \"Demo Server\",\n * version: \"1.0.0\",\n * })),\n * Layer.provide(NodeStdio.layer),\n * Layer.provide(Layer.succeed(Logger.LogToStderr)(true))\n * )\n *\n * Layer.launch(ServerLayer).pipe(NodeRuntime.runMain)\n * ```\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerStdio = options => layer(options).pipe(Layer.provide(RpcServer.layerProtocolStdio), Layer.provide(RpcSerialization.layerNdJsonRpc()));\n/**\n * Registers an HTTP POST JSON-RPC route at `options.path` on the current\n * `HttpRouter`.\n *\n * **When to use**\n *\n * Use to expose an MCP server through an existing `HttpRouter`.\n *\n * **Details**\n *\n * This layer composes `layer(options)`, `RpcServer.layerProtocolHttp(options)`,\n * and `RpcSerialization.layerJsonRpc()`.\n *\n * @see {@link layerStdio} for exposing the server over stdio\n * @see {@link layer} for the base MCP server layer without a transport protocol\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerHttp = options => layer(options).pipe(Layer.provide(RpcServer.layerProtocolHttp(options)), Layer.provide(RpcSerialization.layerJsonRpc()));\n/**\n * Registers a `Toolkit` with the `McpServer`.\n *\n * @category tools\n * @since 4.0.0\n */\nexport const registerToolkit = /*#__PURE__*/Effect.fnUntraced(function* (toolkit) {\n const registry = yield* McpServer;\n const built = yield* toolkit;\n const services = yield* Effect.context();\n for (const tool of Object.values(built.tools)) {\n const annotations = tool.annotations;\n const toolMeta = Context.getOrUndefined(annotations, Tool.Meta);\n const mcpTool = new McpTool({\n name: tool.name,\n description: Tool.getDescription(tool),\n inputSchema: Tool.getJsonSchema(tool),\n annotations: {\n ...Context.getOption(tool.annotations, Tool.Title).pipe(Option.map(title => ({\n title\n })), Option.getOrUndefined),\n readOnlyHint: Context.get(tool.annotations, Tool.Readonly),\n destructiveHint: Context.get(tool.annotations, Tool.Destructive),\n idempotentHint: Context.get(tool.annotations, Tool.Idempotent),\n openWorldHint: Context.get(tool.annotations, Tool.OpenWorld)\n },\n _meta: toolMeta\n });\n yield* registry.addTool({\n tool: mcpTool,\n annotations,\n handle(payload) {\n return built.handle(tool.name, payload).pipe(Stream.unwrap, Stream.run(Sink.last()), Effect.flatMap(Effect.fromOption), Effect.provideContext(services), Effect.matchCause({\n onFailure: cause => new CallToolResult({\n isError: true,\n content: [{\n type: \"text\",\n text: Cause.pretty(cause)\n }]\n }),\n onSuccess: result => new CallToolResult({\n isError: false,\n structuredContent: typeof result.encodedResult === \"object\" ? result.encodedResult : undefined,\n content: [{\n type: \"text\",\n text: JSON.stringify(result.encodedResult)\n }]\n })\n }), Effect.tapCause(Effect.log));\n }\n });\n }\n});\n/**\n * Registers an `AiToolkit` with the `McpServer`.\n *\n * @category tools\n * @since 4.0.0\n */\nexport const toolkit = toolkit => Layer.effectDiscard(registerToolkit(toolkit)).pipe(Layer.provide(McpServer.layer));\n/**\n * Registers an MCP resource or resource template from an Effect program.\n *\n * **When to use**\n *\n * Use when you are already inside an Effect program with an `McpServer`\n * service and need to add a concrete resource or URI-template resource\n * directly.\n *\n * @see {@link resource} for the layer-based resource registration wrapper\n *\n * @category resources\n * @since 4.0.0\n */\nexport const registerResource = function () {\n if (arguments.length === 1) {\n const options = arguments[0];\n return Effect.gen(function* () {\n const services = yield* Effect.context();\n const registry = yield* McpServer;\n yield* registry.addResource({\n resource: new Resource({\n ...options,\n annotations: options\n }),\n handle: options.content.pipe(Effect.provideContext(services), Effect.map(content => resolveResourceContent(options.uri, content)), Effect.catchCause(cause => {\n const prettyError = Cause.prettyErrors(cause)[0];\n return Effect.fail(new InternalError({\n message: prettyError.message\n }));\n })),\n annotations: options.annotations ?? Context.empty()\n });\n });\n }\n const {\n params,\n routerPath,\n schema,\n uriPath\n } = compileUriTemplate(...arguments);\n return Effect.fnUntraced(function* (options) {\n const services = yield* Effect.context();\n const registry = yield* McpServer;\n const decode = Schema.decodeUnknownEffect(schema);\n const template = new ResourceTemplate({\n ...options,\n uriTemplate: uriPath,\n annotations: options\n });\n const completions = {};\n for (const [param, handle] of Object.entries(options.completion ?? {})) {\n const encodeArray = Schema.encodeUnknownEffect(Schema.Array(params[param]));\n const handler = input => handle(input).pipe(Effect.flatMap(encodeArray), Effect.map(values => ({\n completion: {\n values: values,\n total: values.length,\n hasMore: false\n }\n })), Effect.catchCause(cause => {\n const prettyError = Cause.prettyErrors(cause)[0];\n return Effect.fail(new InternalError({\n message: prettyError.message\n }));\n }), Effect.provideContext(services));\n completions[param] = handler;\n }\n yield* registry.addResourceTemplate({\n template,\n routerPath,\n completions,\n annotations: options.annotations ?? Context.empty(),\n handle: (uri, params) => decode(params).pipe(Effect.mapError(error => new InvalidParams({\n message: error.message\n })), Effect.flatMap(params => options.content(uri, ...params).pipe(Effect.map(content => resolveResourceContent(uri, content)), Effect.catchCause(cause => {\n const prettyError = Cause.prettyErrors(cause)[0];\n return Effect.fail(new InternalError({\n message: prettyError.message\n }));\n }))), Effect.provideContext(services))\n });\n });\n};\n/**\n * Creates a layer that registers an MCP resource or resource template.\n *\n * **When to use**\n *\n * Use to compose resource registration into an MCP server layer.\n *\n * @see {@link registerResource} for the Effect-level resource registration API\n *\n * @category resources\n * @since 4.0.0\n */\nexport const resource = function () {\n if (arguments.length === 1) {\n return Layer.effectDiscard(registerResource(arguments[0])).pipe(Layer.provide(McpServer.layer));\n }\n const register = registerResource(...arguments);\n return options => Layer.effectDiscard(register(options)).pipe(Layer.provide(McpServer.layer));\n};\n/**\n * Registers an MCP prompt from an Effect program.\n *\n * **When to use**\n *\n * Use when you are already inside an Effect program with an `McpServer`\n * service and need to add a prompt handler directly.\n *\n * **Details**\n *\n * Parameters are decoded with the supplied schema, completion handlers encode\n * per-parameter suggestions, and string prompt content is converted into a user\n * text message.\n *\n * @see {@link prompt} for the layer-based prompt registration wrapper\n *\n * @category prompts\n * @since 4.0.0\n */\nexport const registerPrompt = options => {\n const args = Arr.empty();\n const props = options.parameters ?? {};\n for (const [name, prop] of Object.entries(props)) {\n args.push({\n name,\n description: SchemaAST.resolveDescription(prop.ast),\n required: !SchemaAST.isOptional(prop.ast)\n });\n }\n const prompt = new Prompt({\n name: options.name,\n description: options.description,\n arguments: args\n });\n const decode = options.parameters ? Schema.decodeEffect(Schema.Struct(props)) : () => Effect.succeed({});\n const completion = options.completion ?? {};\n return Effect.gen(function* () {\n const registry = yield* McpServer;\n const services = yield* Effect.context();\n const completions = {};\n for (const [param, handle] of Object.entries(completion)) {\n const encodeArray = Schema.encodeEffect(Schema.Array(props[param]));\n const handler = input => handle(input).pipe(Effect.flatMap(encodeArray), Effect.map(values => ({\n completion: {\n values: values,\n total: values.length,\n hasMore: false\n }\n })), Effect.catchCause(cause => {\n const prettyError = Cause.prettyErrors(cause)[0];\n return Effect.fail(new InternalError({\n message: prettyError.message\n }));\n }), Effect.provide(services));\n completions[param] = handler;\n }\n yield* registry.addPrompt({\n prompt,\n completions,\n annotations: options.annotations ?? Context.empty(),\n handle: params => decode(params).pipe(Effect.mapError(error => new InvalidParams({\n message: error.message\n })), Effect.flatMap(params => options.content(params)), Effect.map(messages => {\n messages = typeof messages === \"string\" ? [{\n role: \"user\",\n content: TextContent.make({\n text: messages\n })\n }] : messages;\n return new GetPromptResult({\n messages,\n description: prompt.description\n });\n }), Effect.catchCause(cause => {\n const prettyError = Cause.prettyErrors(cause)[0];\n return Effect.fail(new InternalError({\n message: prettyError.message\n }));\n }), Effect.provideContext(services))\n });\n });\n};\n/**\n * Creates a layer that registers an MCP prompt.\n *\n * **When to use**\n *\n * Use to compose prompt registration into an MCP server layer.\n *\n * **Details**\n *\n * Parameters are decoded with the supplied schema, completion handlers encode\n * per-parameter suggestions, and string prompt content is converted into a user\n * text message.\n *\n * @see {@link registerPrompt} for the Effect-level prompt registration API\n *\n * @category prompts\n * @since 4.0.0\n */\nexport const prompt = options => Layer.effectDiscard(registerPrompt(options)).pipe(Layer.provide(McpServer.layer));\n/**\n * Collects structured input from the current MCP client and decodes the\n * accepted response with `schema`.\n *\n * **Details**\n *\n * Accepted content is decoded with the supplied schema, declined requests fail\n * with `ElicitationDeclined`, and canceled requests interrupt the effect.\n *\n * @category elicitation\n * @since 4.0.0\n */\nexport const elicit = /*#__PURE__*/Effect.fnUntraced(function* (options) {\n const {\n getClient\n } = yield* McpServerClient;\n const client = yield* getClient;\n const schema = options.schema;\n const request = Elicit.payloadSchema.make({\n message: options.message,\n requestedSchema: Tool.getJsonSchemaFromSchema(schema)\n });\n const res = yield* client[\"elicitation/create\"](request).pipe(Effect.catchCause(cause => Effect.fail(new ElicitationDeclined({\n cause: Cause.squash(cause),\n request\n }))));\n switch (res.action) {\n case \"accept\":\n return yield* Effect.orDie(Schema.decodeUnknownEffect(schema)(res.content));\n case \"cancel\":\n return yield* Effect.interrupt;\n case \"decline\":\n return yield* new ElicitationDeclined({\n request\n });\n }\n}, Effect.scoped);\n/**\n * Accesses the current client's capabilities.\n *\n * @category capabilities\n * @since 4.0.0\n */\nexport const clientCapabilities = /*#__PURE__*/McpServerClient.useSync(_ => _.initializePayload.capabilities);\n// -----------------------------------------------------------------------------\n// Internal\n// -----------------------------------------------------------------------------\nconst makeUriMatcher = () => {\n const router = FindMyWay.make({\n ignoreTrailingSlash: true,\n ignoreDuplicateSlashes: true,\n caseSensitive: true\n });\n const add = (uri, value) => {\n router.on(\"GET\", uri, value);\n };\n const find = uri => router.find(\"GET\", uri);\n return {\n add,\n find\n };\n};\nconst compileUriTemplate = (segments, ...schemas) => {\n let routerPath = segments[0].replace(\":\", \"::\");\n let uriPath = segments[0];\n const params = {};\n let pathSchema = Schema.Tuple([]);\n if (schemas.length > 0) {\n const arr = [];\n for (let i = 0; i < schemas.length; i++) {\n const toCodecStringTree = Schema.toCodecStringTree(schemas[i]);\n const segment = segments[i + 1];\n const key = String(i);\n arr.push(toCodecStringTree);\n routerPath += `:${key}${segment.replace(\":\", \"::\")}`;\n const schema = schemas[i];\n const paramName = isParam(schema) ? schema.name : `param${key}`;\n params[paramName] = toCodecStringTree;\n uriPath += `{${paramName}}${segment}`;\n }\n pathSchema = Schema.Tuple(arr);\n }\n return {\n routerPath,\n uriPath,\n schema: pathSchema,\n params\n };\n};\nconst layerHandlers = (serverInfo, options) => ClientRpcs.toLayer(Effect.gen(function* () {\n const server = yield* McpServer;\n let currentLogLevel = yield* CurrentLogLevel;\n return ClientRpcs.of({\n // Requests\n ping: () => Effect.succeed({}),\n initialize(params, {\n client\n }) {\n const requestedVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(params.protocolVersion) ? params.protocolVersion : LATEST_PROTOCOL_VERSION;\n if (requestedVersion !== params.protocolVersion) {\n params = {\n ...params,\n protocolVersion: requestedVersion\n };\n }\n const capabilities = {\n completions: {}\n };\n if (server.tools.length > 0) {\n capabilities.tools = {\n listChanged: true\n };\n }\n if (server.resources.length > 0 || server.resourceTemplates.length > 0) {\n capabilities.resources = {\n listChanged: true,\n subscribe: false\n };\n }\n if (server.prompts.length > 0) {\n capabilities.prompts = {\n listChanged: true\n };\n }\n if (serverInfo.extensions) {\n capabilities.extensions = serverInfo.extensions;\n }\n return Effect.withFiber(fiber => {\n const httpRequest = Context.getOrUndefined(fiber.context, HttpServerRequest.HttpServerRequest);\n if (httpRequest) {\n const sessionId = crypto.randomUUID();\n options.clientSessions.set(sessionId, params);\n appendPreResponseHandlerUnsafe(httpRequest, (_req, res) => Effect.succeed(HttpServerResponse.setHeaders(res, {\n [mcpSessionIdHeader]: sessionId,\n [mcpProtocolVersionHeader]: requestedVersion\n })));\n } else {\n options.clientSessions.set(String(client.id), params);\n }\n return Effect.succeed({\n capabilities,\n serverInfo,\n protocolVersion: requestedVersion\n });\n });\n },\n \"completion/complete\": r => server.completion(r).pipe(Effect.provideService(CurrentLogLevel, currentLogLevel)),\n \"logging/setLevel\": ({\n level\n }) => Effect.sync(() => {\n switch (level) {\n case \"notice\":\n case \"info\":\n currentLogLevel = \"Info\";\n break;\n case \"error\":\n currentLogLevel = \"Error\";\n break;\n case \"debug\":\n currentLogLevel = \"Debug\";\n break;\n case \"warning\":\n currentLogLevel = \"Warn\";\n break;\n case \"critical\":\n case \"alert\":\n case \"emergency\":\n currentLogLevel = \"Fatal\";\n break;\n }\n }),\n \"prompts/get\": r => server.getPromptResult(r).pipe(Effect.provideService(CurrentLogLevel, currentLogLevel)),\n \"prompts/list\": (_, {\n client,\n headers\n }) => Effect.sync(() => {\n const initialized = getInitializedClient(options.clientSessions, client.id, headers);\n return new ListPromptsResult({\n prompts: filterByClient(initialized, server.prompts, \"prompt\")\n });\n }),\n \"resources/list\": (_, {\n client,\n headers\n }) => Effect.sync(() => {\n const initialized = getInitializedClient(options.clientSessions, client.id, headers);\n return new ListResourcesResult({\n resources: filterByClient(initialized, server.resources, \"resource\")\n });\n }),\n \"resources/read\": ({\n uri\n }) => server.findResource(uri).pipe(Effect.provideService(CurrentLogLevel, currentLogLevel)),\n \"resources/subscribe\": () => InternalError.notImplemented,\n \"resources/unsubscribe\": () => InternalError.notImplemented,\n \"resources/templates/list\": (_, {\n client,\n headers\n }) => Effect.sync(() => {\n const initialized = getInitializedClient(options.clientSessions, client.id, headers);\n return new ListResourceTemplatesResult({\n resourceTemplates: filterByClient(initialized, server.resourceTemplates, \"template\")\n });\n }),\n \"tools/call\": r => server.callTool(r).pipe(Effect.provideService(CurrentLogLevel, currentLogLevel)),\n \"tools/list\": (_, {\n client,\n headers\n }) => Effect.sync(() => {\n const initialized = getInitializedClient(options.clientSessions, client.id, headers);\n return new ListToolsResult({\n tools: filterByClient(initialized, server.tools, \"tool\")\n });\n }),\n // Notifications\n \"notifications/cancelled\": _ => Effect.void,\n \"notifications/initialized\": _ => Effect.void,\n \"notifications/progress\": _ => Effect.void,\n \"notifications/roots/list_changed\": _ => Effect.void\n });\n}));\nconst resolveResourceContent = (uri, content) => {\n if (typeof content === \"string\") {\n return {\n contents: [{\n uri,\n text: content\n }]\n };\n } else if (content instanceof Uint8Array) {\n return {\n contents: [{\n uri,\n blob: content\n }]\n };\n }\n return content;\n};\nconst filterByClient = (client, items, prop) => {\n if (!client) {\n return items.map(item => item[prop]);\n }\n const out = Arr.empty();\n for (let i = 0; i < items.length; i++) {\n const item = items[i];\n const enabledWhen = Context.getOrUndefined(item.annotations, EnabledWhen);\n if (!enabledWhen || enabledWhen(client)) {\n out.push(item[prop]);\n }\n }\n return out;\n};\nconst getInitializedClient = (sessions, clientId, headers) => {\n const sessionId = headers[mcpSessionIdHeader];\n if (sessionId === undefined) {\n return sessions.get(String(clientId));\n }\n return sessions.get(sessionId);\n};\n//# sourceMappingURL=McpServer.js.map","import { Array, Effect, Schema as S } from 'effect'\nimport { AiError, Tool, Toolkit } from 'effect/unstable/ai'\nimport { NoteSchema } from './note'\nimport { NoteStore } from './store'\n\nconst projects = Tool.make('projects', {\n description:\n 'List the projects the store holds, each with its id, the absolute directory it lives in, and the address it was last framed at.',\n success: S.Struct({\n projects: S.Array(\n S.Struct({\n id: S.String,\n name: S.String,\n directory: S.NullOr(S.String),\n address: S.NullOr(S.String),\n }),\n ),\n }),\n})\n\nconst notes = Tool.make('notes', {\n description: \"List a project's open, unaddressed notes, in the order they were made.\",\n parameters: S.Struct({ project: S.String }),\n success: S.Struct({ notes: S.Array(NoteSchema) }),\n})\n\nconst acknowledgement = S.Struct({ ok: S.Boolean })\n\nconst resolve = Tool.make('resolve', {\n description: 'Mark a note addressed, once you have dealt with it.',\n parameters: S.Struct({ project: S.String, seq: S.Number }),\n success: acknowledgement,\n})\n\nconst discard = Tool.make('discard', {\n description: 'Discard a note that no longer applies.',\n parameters: S.Struct({ project: S.String, seq: S.Number }),\n success: acknowledgement,\n})\n\nexport const toolkit = Toolkit.make(projects, notes, resolve, discard)\n\nconst surface = <A, E>(tool: string, work: Effect.Effect<A, E>): Effect.Effect<A, AiError.UnknownError> =>\n work.pipe(\n Effect.tapError((error) => Effect.logError(`the ${tool} tool could not reach the store`, error)),\n Effect.mapError(() => new AiError.UnknownError({ description: `the ${tool} tool could not reach the store` })),\n )\n\nexport const handlers = toolkit.toLayer(\n Effect.gen(function* () {\n const store = yield* NoteStore\n return {\n projects: () => surface('projects', store.projects).pipe(Effect.map((list) => ({ projects: list }))),\n notes: ({ project }) =>\n surface('notes', store.list(project)).pipe(\n Effect.map((list) => ({ notes: Array.filter(list, (note) => !note.addressed) })),\n ),\n resolve: ({ project, seq }) =>\n surface('resolve', store.resolve(project, seq)).pipe(Effect.as({ ok: true })),\n discard: ({ project, seq }) =>\n surface('discard', store.discard(project, seq)).pipe(Effect.as({ ok: true })),\n }\n }),\n)\n","import { Effect, Layer, Option, PubSub, Schema } from 'effect'\nimport {\n HttpRouter,\n HttpServerRequest,\n HttpServerResponse,\n} from 'effect/unstable/http'\nimport { McpServer } from 'effect/unstable/ai'\nimport { NodeHttpServer } from '@effect/platform-node'\nimport { createServer } from 'node:http'\nimport { dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { DraftSchema } from './note'\nimport { NoteStore } from './store'\nimport { handlers, toolkit } from './mcp'\n\nconst SeqBody = Schema.Struct({ project: Schema.String, seq: Schema.Number })\nconst EditBody = Schema.Struct({ project: Schema.String, seq: Schema.Number, text: Schema.String })\n\nconst notFound = Effect.succeed(HttpServerResponse.text('Not found', { status: 404 }))\n\nconst root = dirname(fileURLToPath(import.meta.url))\n\nconst capture = Effect.gen(function* () {\n const store = yield* NoteStore\n const draft = yield* HttpServerRequest.schemaBodyJson(DraftSchema)\n const note = yield* store.record(draft)\n return yield* HttpServerResponse.json(note)\n})\n\nconst resolve = Effect.gen(function* () {\n const store = yield* NoteStore\n const { project, seq } = yield* HttpServerRequest.schemaBodyJson(SeqBody)\n yield* store.resolve(project, seq)\n return yield* HttpServerResponse.json({ ok: true })\n})\n\nconst discard = Effect.gen(function* () {\n const store = yield* NoteStore\n const { project, seq } = yield* HttpServerRequest.schemaBodyJson(SeqBody)\n yield* store.discard(project, seq)\n return yield* HttpServerResponse.json({ ok: true })\n})\n\nconst edit = Effect.gen(function* () {\n const store = yield* NoteStore\n const { project, seq, text } = yield* HttpServerRequest.schemaBodyJson(EditBody)\n yield* store.edit(project, seq, text)\n return yield* HttpServerResponse.json({ ok: true })\n})\n\nconst feed = Effect.gen(function* () {\n const store = yield* NoteStore\n const request = yield* HttpServerRequest.HttpServerRequest\n const project = new URL(request.url, 'http://localhost').searchParams.get('project')\n return yield* Option.match(Option.fromNullishOr(project), {\n onNone: () => Effect.succeed(HttpServerResponse.text('project is required', { status: 400 })),\n onSome: (found) =>\n store.list(found).pipe(Effect.flatMap((notes) => HttpServerResponse.json(notes))),\n })\n})\n\nconst noCache = { 'cache-control': 'no-store' }\n\nconst overlay = HttpServerResponse.file(join(root, '..', 'dist', 'overlay.js'), {\n headers: noCache,\n}).pipe(\n Effect.catchCause((cause) =>\n Effect.logWarning('could not read the overlay script', cause).pipe(Effect.andThen(notFound)),\n ),\n)\n\nconst page = HttpServerResponse.file(join(root, 'ui.html'), {\n headers: noCache,\n}).pipe(\n Effect.catchCause((cause) =>\n Effect.logWarning('could not read the setup page', cause).pipe(Effect.andThen(notFound)),\n ),\n)\n\nconst uiScript = HttpServerResponse.file(join(root, '..', 'dist', 'ui.js'), {\n headers: noCache,\n}).pipe(\n Effect.catchCause((cause) =>\n Effect.logWarning('could not read the setup script', cause).pipe(Effect.andThen(notFound)),\n ),\n)\n\nconst live = Effect.gen(function* () {\n const store = yield* NoteStore\n const request = yield* HttpServerRequest.HttpServerRequest\n const project = new URL(request.url, 'http://localhost').searchParams.get('project')\n return yield* Option.match(Option.fromNullishOr(project), {\n onNone: () => Effect.succeed(HttpServerResponse.text('project is required', { status: 400 })),\n onSome: (found) =>\n Effect.gen(function* () {\n const socket = yield* request.upgrade\n const write = yield* socket.writer\n const subscription = yield* PubSub.subscribe(store.changes)\n const pushMatching = Effect.forever(\n PubSub.take(subscription).pipe(\n Effect.flatMap((note) =>\n note.project === found ? write(JSON.stringify(note)) : Effect.void,\n ),\n ),\n )\n yield* Effect.race(pushMatching, socket.run(() => Effect.void))\n return HttpServerResponse.empty()\n }).pipe(\n Effect.catchCause((cause) => Effect.logDebug('a live notes socket closed', cause)),\n Effect.as(HttpServerResponse.empty()),\n ),\n })\n})\n\nconst handling = <R>(\n work: Effect.Effect<HttpServerResponse.HttpServerResponse, unknown, R>,\n): Effect.Effect<HttpServerResponse.HttpServerResponse, never, R> =>\n work.pipe(\n Effect.catchCause((cause) =>\n Effect.logError('a notes request failed', cause).pipe(\n Effect.as(HttpServerResponse.text('The notes store failed', { status: 500 })),\n ),\n ),\n )\n\nexport const noteHandlers = {\n capture: handling(capture),\n feed: handling(feed),\n live,\n resolve: handling(resolve),\n discard: handling(discard),\n edit: handling(edit),\n overlay,\n} as const\n\nconst routes = Layer.mergeAll(\n HttpRouter.add('POST', '/notes/capture', noteHandlers.capture),\n HttpRouter.add('GET', '/notes/feed', noteHandlers.feed),\n HttpRouter.add('GET', '/notes/live', noteHandlers.live),\n HttpRouter.add('POST', '/notes/resolve', noteHandlers.resolve),\n HttpRouter.add('POST', '/notes/discard', noteHandlers.discard),\n HttpRouter.add('POST', '/notes/edit', noteHandlers.edit),\n HttpRouter.add('GET', '/notes.js', noteHandlers.overlay),\n HttpRouter.add('GET', '/ui.js', uiScript),\n HttpRouter.add('GET', '/', page),\n)\n\nexport const mcpAt = (path: HttpRouter.PathInput) =>\n McpServer.toolkit(toolkit).pipe(\n Layer.provide(handlers),\n Layer.provide(McpServer.layerHttp({ name: 'loom', version: '0.0.10', path })),\n )\n\nconst mcp = mcpAt('/mcp')\n\nimport { Logger } from 'effect'\n\nexport const designLogger = Logger.layer([Logger.consoleLogFmt])\n\nconst app = Layer.mergeAll(\n routes,\n mcp,\n HttpRouter.cors({ allowedMethods: ['GET', 'POST'], allowedHeaders: ['Content-Type'] }),\n)\n\nexport const notesServer = (\n port: number,\n store: Layer.Layer<NoteStore> = NoteStore.layer,\n) =>\n HttpRouter.serve(app).pipe(\n Layer.provide(store),\n Layer.provide(NodeHttpServer.layer(() => createServer(), { port })),\n )\n","import { Effect, Layer, Option } from 'effect'\nimport {\n HttpRouter,\n HttpServerRequest,\n HttpServerResponse,\n} from 'effect/unstable/http'\nimport { NodeHttpServer } from '@effect/platform-node'\nimport { createServer } from 'node:http'\nimport { mcpAt, noteHandlers } from './api'\nimport { NoteStore } from './store'\n\nconst MOUNT = '/__loom'\n\nconst CLOSING_BODY = /<\\/body>/i\n\nconst tagFor = (project: string): string =>\n `<script type=\"module\" src=\"${MOUNT}/notes.js\" data-loom-project=\"${project}\"></script>`\n\nconst injected = (html: string, project: string): string =>\n CLOSING_BODY.test(html)\n ? html.replace(CLOSING_BODY, () => `${tagFor(project)}</body>`)\n : `${html}${tagFor(project)}`\n\nconst HOP = new Set([\n 'accept-encoding',\n 'connection',\n 'content-length',\n 'host',\n 'keep-alive',\n 'proxy-authenticate',\n 'proxy-authorization',\n 'te',\n 'trailer',\n 'transfer-encoding',\n 'upgrade',\n])\n\nconst carried = (headers: Record<string, string>): Record<string, string> =>\n Object.fromEntries(\n Object.entries(headers).filter(([name]) => !HOP.has(name.toLowerCase())),\n )\n\nconst sent = (\n request: HttpServerRequest.HttpServerRequest,\n): Effect.Effect<Uint8Array | undefined> =>\n request.method === 'GET' || request.method === 'HEAD'\n ? Effect.succeed(undefined)\n : Effect.map(request.arrayBuffer, (raw) => new Uint8Array(raw)).pipe(\n Effect.catchCause(() => Effect.succeed(undefined)),\n )\n\nconst relocated = (held: Response, origin: string): Record<string, string> =>\n Option.match(Option.fromNullishOr(held.headers.get('location')), {\n onNone: () => ({}),\n onSome: (where) => ({\n location: where.startsWith(origin) ? where.slice(origin.length) : where,\n }),\n })\n\nconst answering = (held: Response, origin: string, project: string, type: string) =>\n type.includes('text/html')\n ? Effect.map(Effect.promise(() => held.text()), (html) =>\n HttpServerResponse.text(injected(html, project), {\n status: held.status,\n contentType: type,\n headers: relocated(held, origin),\n }),\n )\n : Effect.map(Effect.promise(() => held.arrayBuffer()), (raw) =>\n HttpServerResponse.uint8Array(new Uint8Array(raw), {\n status: held.status,\n contentType: type,\n headers: relocated(held, origin),\n }),\n )\n\nconst silent = Effect.succeed(\n HttpServerResponse.text('The application is not answering', { status: 502 }),\n)\n\nconst forward = (origin: string, project: string) =>\n Effect.gen(function* () {\n const request = yield* HttpServerRequest.HttpServerRequest\n const url = new URL(request.url, 'http://localhost')\n const body = yield* sent(request)\n const held = yield* Effect.tryPromise(() =>\n fetch(`${origin}${url.pathname}${url.search}`, {\n method: request.method,\n headers: { ...carried(request.headers), 'accept-encoding': 'identity' },\n body,\n redirect: 'manual',\n }),\n )\n return yield* answering(\n held,\n origin,\n project,\n held.headers.get('content-type') ?? 'application/octet-stream',\n )\n }).pipe(Effect.catchCause(() => silent))\n\nconst routes = (origin: string, project: string) =>\n Layer.mergeAll(\n HttpRouter.add('POST', `${MOUNT}/notes/capture`, noteHandlers.capture),\n HttpRouter.add('GET', `${MOUNT}/notes/feed`, noteHandlers.feed),\n HttpRouter.add('GET', `${MOUNT}/notes/live`, noteHandlers.live),\n HttpRouter.add('POST', `${MOUNT}/notes/resolve`, noteHandlers.resolve),\n HttpRouter.add('POST', `${MOUNT}/notes/discard`, noteHandlers.discard),\n HttpRouter.add('POST', `${MOUNT}/notes/edit`, noteHandlers.edit),\n HttpRouter.add('GET', `${MOUNT}/notes.js`, noteHandlers.overlay),\n mcpAt(`${MOUNT}/mcp`),\n HttpRouter.add('*', '*', forward(origin, project)),\n )\n\nexport const designServer = (options: {\n readonly port: number\n readonly application: string\n readonly project: string\n readonly store: Layer.Layer<NoteStore>\n}) =>\n HttpRouter.serve(routes(options.application, options.project)).pipe(\n Layer.provide(options.store),\n Layer.provide(NodeHttpServer.layer(() => createServer(), { port: options.port })),\n )\n"],"x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,55,56,57,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80],"mappings":";;;;;;;;;;;;;;;;;AAAA,IAAMA,UAAQ;CACV,uBAAuB,CAAC,KAAK;CAC7B,2BAA2B,CAAC,KAAK;CACjC,gDAAgD,CAAC,KAAK;CACtD,qCAAqC,CAAC,KAAK;CAC3C,qCAAqC,CAAC,KAAK;CAC3C,mCAAmC,CAAC,KAAK;CACzC,8BAA8B,CAAC,MAAM;CACrC,oCAAoC,CAAC,KAAK;CAC1C,qCAAqC,CAAC,KAAK;CAC3C,qCAAqC,CAAC,KAAK;CAC3C,4BAA4B,CAAC,KAAK;CAClC,2BAA2B,CAAC,OAAO,OAAO;CAC1C,+DAA+D,CAAC,KAAK;CACrE,2CAA2C,CAAC,MAAM;CAClD,6BAA6B,CAAC,OAAO,MAAM;CAC3C,iCAAiC,CAAC,KAAK;CACvC,8BAA8B,CAAC,OAAO;CACtC,uBAAuB,CAAC,KAAK;CAC7B,+BAA+B,CAAC,OAAO;CACvC,yCAAyC,CAAC,KAAK;CAC/C,yCAAyC,CAAC,KAAK;CAC/C,gCAAgC,CAAC,KAAK;CACtC,wCAAwC,CAAC,KAAK;CAC9C,6BAA6B,CAAC,KAAK;CACnC,2CAA2C,CAAC,KAAK;CACjD,0DAA0D,CAAC,KAAK;CAChE,uDAAuD,CAAC,KAAK;CAC7D,wCAAwC,CAAC,KAAK;CAC9C,uCAAuC,CAAC,MAAM;CAC9C,iCAAiC,CAAC,KAAK;CACvC,iCAAiC,CAAC,MAAM;CACxC,iCAAiC,CAAC,SAAS;CAC3C,+BAA+B,CAAC,OAAO;CACvC,gCAAgC,CAAC,QAAQ;CACzC,sCAAsC,CAAC,K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