ff-effect 0.0.8 → 0.0.11

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,"sources":["../../../src/for/inngest/index.ts","../../../../../node_modules/.bun/@effect+platform@0.94.2+8cc8b89dc7ad56db/node_modules/@effect/platform/src/Cookies.ts","../../../../../node_modules/.bun/@effect+platform@0.94.2+8cc8b89dc7ad56db/node_modules/@effect/platform/src/Error.ts","../../../../../node_modules/.bun/@effect+platform@0.94.2+8cc8b89dc7ad56db/node_modules/@effect/platform/src/Headers.ts","../../../../../node_modules/.bun/@effect+platform@0.94.2+8cc8b89dc7ad56db/node_modules/@effect/platform/src/HttpIncomingMessage.ts","../../../../../node_modules/.bun/@effect+platform@0.94.2+8cc8b89dc7ad56db/node_modules/@effect/platform/src/FileSystem.ts","../../../../../node_modules/.bun/@effect+platform@0.94.2+8cc8b89dc7ad56db/node_modules/@effect/platform/src/internal/fileSystem.ts","../../../../../node_modules/.bun/@effect+platform@0.94.2+8cc8b89dc7ad56db/node_modules/@effect/platform/src/UrlParams.ts","../../../../../node_modules/.bun/@effect+platform@0.94.2+8cc8b89dc7ad56db/node_modules/@effect/platform/src/HttpTraceContext.ts","../../../../../node_modules/.bun/@effect+platform@0.94.2+8cc8b89dc7ad56db/node_modules/@effect/platform/src/internal/httpBody.ts","../../../../../node_modules/.bun/@effect+platform@0.94.2+8cc8b89dc7ad56db/node_modules/@effect/platform/src/HttpApp.ts","../../../../../node_modules/.bun/@effect+platform@0.94.2+8cc8b89dc7ad56db/node_modules/@effect/platform/src/HttpBody.ts","../../../../../node_modules/.bun/@effect+platform@0.94.2+8cc8b89dc7ad56db/node_modules/@effect/platform/src/HttpServerRespondable.ts","../../../../../node_modules/.bun/@effect+platform@0.94.2+8cc8b89dc7ad56db/node_modules/@effect/platform/src/HttpServerResponse.ts","../../../../../node_modules/.bun/@effect+platform@0.94.2+8cc8b89dc7ad56db/node_modules/@effect/platform/src/internal/httpServerResponse.ts","../../../../../node_modules/.bun/@effect+platform@0.94.2+8cc8b89dc7ad56db/node_modules/@effect/platform/src/internal/httpServerError.ts","../../../../../node_modules/.bun/@effect+platform@0.94.2+8cc8b89dc7ad56db/node_modules/@effect/platform/src/HttpServerError.ts","../../../../../node_modules/.bun/@effect+platform@0.94.2+8cc8b89dc7ad56db/node_modules/@effect/platform/src/HttpServerRequest.ts","../../../../../node_modules/.bun/@effect+platform@0.94.2+8cc8b89dc7ad56db/node_modules/@effect/platform/src/HttpMethod.ts","../../../../../node_modules/.bun/@effect+platform@0.94.2+8cc8b89dc7ad56db/node_modules/@effect/platform/src/internal/httpServerRequest.ts","../../../../../node_modules/.bun/@effect+platform@0.94.2+8cc8b89dc7ad56db/node_modules/@effect/platform/src/Multipart.ts","../../../../../node_modules/.bun/multipasta@0.2.7/node_modules/multipasta/src/internal/contentType.ts","../../../../../node_modules/.bun/multipasta@0.2.7/node_modules/multipasta/src/internal/headers.ts","../../../../../node_modules/.bun/multipasta@0.2.7/node_modules/multipasta/src/internal/search.ts","../../../../../node_modules/.bun/multipasta@0.2.7/node_modules/multipasta/src/internal/multipart.ts","../../../../../node_modules/.bun/multipasta@0.2.7/node_modules/multipasta/src/index.ts","../../../../../node_modules/.bun/@effect+platform@0.94.2+8cc8b89dc7ad56db/node_modules/@effect/platform/src/internal/path.ts","../../../../../node_modules/.bun/@effect+platform@0.94.2+8cc8b89dc7ad56db/node_modules/@effect/platform/src/Path.ts","../../../../../node_modules/.bun/@effect+platform@0.94.2+8cc8b89dc7ad56db/node_modules/@effect/platform/src/internal/httpApp.ts","../../../../../node_modules/.bun/@effect+platform@0.94.2+8cc8b89dc7ad56db/node_modules/@effect/platform/src/internal/httpMiddleware.ts","../../../src/extract.ts","../../../src/for/inngest/cron.ts","../../../src/for/inngest/step.ts","../../../src/run-promise-unwrapped.ts"],"sourcesContent":["import { HttpApp } from '@effect/platform';\nimport { type Cron, Data, Effect, FiberSet, Layer } from 'effect';\nimport * as Context from 'effect/Context';\nimport * as Inspectable from 'effect/Inspectable';\nimport type { GetEvents, GetFunctionInput, Inngest } from 'inngest';\nimport { serve } from 'inngest/bun';\nimport { extract } from '../../extract';\nimport { cronToString } from './cron';\nimport { wrapStep } from './step';\n\nexport const TagTypeId = Context.TagTypeId;\nexport const NodeInspectSymbol = Inspectable.NodeInspectSymbol;\n\nexport class InngestError extends Data.TaggedError('ff-effect/InngestError')<{\n\tmessage: string;\n\tcause?: unknown;\n}> {}\n\ndeclare const InngestFunctionBrand: unique symbol;\n\n/** Opaque wrapper around inngest's InngestFunction to avoid leaking internal types */\nexport type InngestFunction = { readonly [InngestFunctionBrand]: true };\n\n// biome-ignore lint/suspicious/noExplicitAny: matches Inngest.Any\ntype AnyInngest = Inngest<any>;\n\ntype CreateFunctionParams<TClient extends AnyInngest> = Parameters<\n\tTClient['createFunction']\n>;\n\ntype FunctionConfig<TClient extends AnyInngest> =\n\tCreateFunctionParams<TClient>[0];\n\ntype FunctionTrigger<TClient extends AnyInngest> =\n\tCreateFunctionParams<TClient>[1];\n\ntype TriggerInput<TClient extends AnyInngest> =\n\t| FunctionTrigger<TClient>\n\t| CronTrigger;\n\ntype ExtractTriggerName<TClient extends AnyInngest, T> = T extends {\n\tevent: infer E extends keyof GetEvents<TClient, true> & string;\n}\n\t? E\n\t: keyof GetEvents<TClient, true> & string;\n\ntype CronTrigger = { cron: Cron.Cron };\n\nfunction isCronTrigger(trigger: unknown): trigger is CronTrigger {\n\treturn (\n\t\ttypeof trigger === 'object' &&\n\t\ttrigger !== null &&\n\t\t'cron' in trigger &&\n\t\ttypeof (trigger as CronTrigger).cron === 'object' &&\n\t\t(trigger as CronTrigger).cron !== null &&\n\t\t'minutes' in (trigger as CronTrigger).cron\n\t);\n}\n\nfunction resolveTrigger<TClient extends AnyInngest>(\n\ttrigger: TriggerInput<TClient>,\n): FunctionTrigger<TClient> {\n\tif (Array.isArray(trigger)) {\n\t\treturn trigger.map((t) =>\n\t\t\tresolveTrigger<TClient>(t),\n\t\t) as FunctionTrigger<TClient>;\n\t}\n\tif (isCronTrigger(trigger)) {\n\t\treturn { cron: cronToString(trigger.cron) } as FunctionTrigger<TClient>;\n\t}\n\treturn trigger as FunctionTrigger<TClient>;\n}\n\ntype EffectHandlerCtx<\n\tTClient extends AnyInngest,\n\tTTriggerName extends keyof GetEvents<TClient, true> &\n\t\tstring = keyof GetEvents<TClient, true> & string,\n> = Omit<GetFunctionInput<TClient, TTriggerName>, 'step'> & {\n\tstep: ReturnType<typeof wrapStep<unknown>>;\n};\n\nconst defaultPrefix = '@ff-effect/Inngest' as const;\n\nexport function createInngest<\n\tTClient extends AnyInngest,\n\tE,\n\tR,\n\tT extends string = typeof defaultPrefix,\n>(createClient: Effect.Effect<TClient, E, R>, opts?: { tagId?: T }) {\n\tconst tagId = (opts?.tagId ?? defaultPrefix) as T;\n\n\ttype Tag = typeof tagId;\n\tconst Tag = Context.Tag(tagId)<Tag, TClient>();\n\n\tconst send = (\n\t\tpayload: Parameters<TClient['send']>[0],\n\t): Effect.Effect<{ ids: string[] }, InngestError, Tag> =>\n\t\tEffect.gen(function* () {\n\t\t\tconst c = yield* Tag;\n\t\t\treturn yield* Effect.tryPromise({\n\t\t\t\t// @ts-expect-error inngest generic variance issue between constrained and inferred client types\n\t\t\t\ttry: () => c.send(payload) as Promise<{ ids: string[] }>,\n\t\t\t\tcatch: (cause) =>\n\t\t\t\t\tnew InngestError({ message: 'Failed to send event', cause }),\n\t\t\t});\n\t\t});\n\n\tconst createFunction = <TTrigger extends TriggerInput<TClient>, A, EH, RH>(\n\t\tconfig: FunctionConfig<TClient>,\n\t\ttrigger: TTrigger,\n\t\thandler: (\n\t\t\tctx: EffectHandlerCtx<TClient, ExtractTriggerName<TClient, TTrigger>>,\n\t\t) => Effect.Effect<A, EH, RH>,\n\t) =>\n\t\tEffect.gen(function* () {\n\t\t\tconst c = yield* Tag;\n\t\t\tconst ext_handler = yield* extract(handler);\n\t\t\tconst resolvedTrigger = resolveTrigger<TClient>(trigger);\n\t\t\tconst runPromise = yield* FiberSet.makeRuntimePromise();\n\n\t\t\treturn c.createFunction(\n\t\t\t\tconfig,\n\t\t\t\tresolvedTrigger,\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: inngest middleware produces unresolvable context type\n\t\t\t\tasync (ctx: any) => {\n\t\t\t\t\tconst effectStep = wrapStep(ctx.step);\n\t\t\t\t\treturn runPromise(\n\t\t\t\t\t\text_handler({\n\t\t\t\t\t\t\t...ctx,\n\t\t\t\t\t\t\tstep: effectStep,\n\t\t\t\t\t\t} as unknown as EffectHandlerCtx<\n\t\t\t\t\t\t\tTClient,\n\t\t\t\t\t\t\tExtractTriggerName<TClient, TTrigger>\n\t\t\t\t\t\t>),\n\t\t\t\t\t);\n\t\t\t\t},\n\t\t\t) as unknown as InngestFunction;\n\t\t});\n\n\ttype ServeOpts = {\n\t\tfunctions: InngestFunction[];\n\t\tservePath?: string;\n\t\tsigningKey?: string;\n\t\tsigningKeyFallback?: string;\n\t\tlogLevel?: 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'silent';\n\t\tstreaming?: 'allow' | 'force' | false;\n\t};\n\n\tfunction buildServe(client: TClient, httpOpts: ServeOpts) {\n\t\treturn serve({\n\t\t\tclient,\n\t\t\tfunctions: httpOpts.functions as unknown as Parameters<\n\t\t\t\ttypeof serve\n\t\t\t>[0]['functions'],\n\t\t\t...(httpOpts.servePath != null && { servePath: httpOpts.servePath }),\n\t\t\t...(httpOpts.signingKey != null && {\n\t\t\t\tsigningKey: httpOpts.signingKey,\n\t\t\t}),\n\t\t\t...(httpOpts.signingKeyFallback != null && {\n\t\t\t\tsigningKeyFallback: httpOpts.signingKeyFallback,\n\t\t\t}),\n\t\t\t...(httpOpts.logLevel != null && { logLevel: httpOpts.logLevel }),\n\t\t\t...(httpOpts.streaming != null && { streaming: httpOpts.streaming }),\n\t\t});\n\t}\n\n\tconst fetchHandler = (httpOpts: ServeOpts) =>\n\t\tEffect.gen(function* () {\n\t\t\tconst c = yield* Tag;\n\t\t\treturn buildServe(c, httpOpts);\n\t\t});\n\n\tconst httpHandler = (httpOpts: ServeOpts) =>\n\t\tEffect.gen(function* () {\n\t\t\tconst c = yield* Tag;\n\t\t\treturn HttpApp.fromWebHandler(buildServe(c, httpOpts));\n\t\t});\n\n\treturn {\n\t\tTag,\n\t\tlayer: Layer.effect(Tag, createClient),\n\t\tcreateFunction,\n\t\tsend,\n\t\tfetchHandler,\n\t\thttpHandler,\n\t};\n}\n","/**\n * @since 1.0.0\n */\nimport * as Duration from \"effect/Duration\"\nimport * as Either from \"effect/Either\"\nimport { dual, identity } from \"effect/Function\"\nimport * as Inspectable from \"effect/Inspectable\"\nimport * as Option from \"effect/Option\"\nimport { type Pipeable, pipeArguments } from \"effect/Pipeable\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Record from \"effect/Record\"\nimport type * as Types from \"effect/Types\"\nimport { TypeIdError } from \"./Error.js\"\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const TypeId: unique symbol = Symbol.for(\"@effect/platform/Cookies\")\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isCookies = (u: unknown): u is Cookies => Predicate.hasProperty(u, TypeId)\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Cookies extends Pipeable, Inspectable.Inspectable {\n readonly [TypeId]: TypeId\n readonly cookies: Record.ReadonlyRecord<string, Cookie>\n}\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const CookieTypeId: unique symbol = Symbol.for(\"@effect/platform/Cookies/Cookie\")\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type CookieTypeId = typeof CookieTypeId\n\n/**\n * @since 1.0.0\n * @category cookie\n */\nexport interface Cookie extends Inspectable.Inspectable {\n readonly [CookieTypeId]: CookieTypeId\n readonly name: string\n readonly value: string\n readonly valueEncoded: string\n readonly options?: {\n readonly domain?: string | undefined\n readonly expires?: Date | undefined\n readonly maxAge?: Duration.DurationInput | undefined\n readonly path?: string | undefined\n readonly priority?: \"low\" | \"medium\" | \"high\" | undefined\n readonly httpOnly?: boolean | undefined\n readonly secure?: boolean | undefined\n readonly partitioned?: boolean | undefined\n readonly sameSite?: \"lax\" | \"strict\" | \"none\" | undefined\n } | undefined\n}\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const ErrorTypeId: unique symbol = Symbol.for(\"@effect/platform/Cookies/CookieError\")\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type ErrorTypeId = typeof ErrorTypeId\n\n/**\n * @since 1.0.0\n * @category errors\n */\nexport class CookiesError extends TypeIdError(ErrorTypeId, \"CookieError\")<{\n readonly reason: \"InvalidName\" | \"InvalidValue\" | \"InvalidDomain\" | \"InvalidPath\" | \"InfinityMaxAge\"\n}> {\n get message() {\n return this.reason\n }\n}\n\nconst Proto: Omit<Cookies, \"cookies\"> = {\n [TypeId]: TypeId,\n ...Inspectable.BaseProto,\n toJSON(this: Cookies) {\n return {\n _id: \"@effect/platform/Cookies\",\n cookies: Record.map(this.cookies, (cookie) => cookie.toJSON())\n }\n },\n pipe() {\n return pipeArguments(this, arguments)\n }\n}\n\n/**\n * Create a Cookies object from an Iterable\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const fromReadonlyRecord = (cookies: Record.ReadonlyRecord<string, Cookie>): Cookies => {\n const self = Object.create(Proto)\n self.cookies = cookies\n return self\n}\n\n/**\n * Create a Cookies object from an Iterable\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const fromIterable = (cookies: Iterable<Cookie>): Cookies => {\n const record: Record<string, Cookie> = {}\n for (const cookie of cookies) {\n record[cookie.name] = cookie\n }\n return fromReadonlyRecord(record)\n}\n\n/**\n * Create a Cookies object from a set of Set-Cookie headers\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const fromSetCookie = (headers: Iterable<string> | string): Cookies => {\n const arrayHeaders = typeof headers === \"string\" ? [headers] : headers\n const cookies: Array<Cookie> = []\n for (const header of arrayHeaders) {\n const cookie = parseSetCookie(header.trim())\n if (Option.isSome(cookie)) {\n cookies.push(cookie.value)\n }\n }\n\n return fromIterable(cookies)\n}\n\nfunction parseSetCookie(header: string): Option.Option<Cookie> {\n const parts = header.split(\";\").map((_) => _.trim()).filter((_) => _ !== \"\")\n if (parts.length === 0) {\n return Option.none()\n }\n\n const firstEqual = parts[0].indexOf(\"=\")\n if (firstEqual === -1) {\n return Option.none()\n }\n const name = parts[0].slice(0, firstEqual)\n if (!fieldContentRegExp.test(name)) {\n return Option.none()\n }\n\n const valueEncoded = parts[0].slice(firstEqual + 1)\n const value = tryDecodeURIComponent(valueEncoded)\n\n if (parts.length === 1) {\n return Option.some(Object.assign(Object.create(CookieProto), {\n name,\n value,\n valueEncoded\n }))\n }\n\n const options: Types.Mutable<Cookie[\"options\"]> = {}\n\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\n switch (key.toLowerCase()) {\n case \"domain\": {\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 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 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 if (value === undefined) {\n break\n }\n if (value[0] === \"/\") {\n options.path = value\n }\n break\n }\n case \"priority\": {\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 options.httpOnly = true\n break\n }\n case \"secure\": {\n options.secure = true\n break\n }\n case \"partitioned\": {\n options.partitioned = true\n break\n }\n case \"samesite\": {\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\n return Option.some(Object.assign(Object.create(CookieProto), {\n name,\n value,\n valueEncoded,\n options: Object.keys(options).length > 0 ? options : undefined\n }))\n}\n\n/**\n * An empty Cookies object\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const empty: Cookies = fromIterable([])\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isEmpty = (self: Cookies): boolean => Record.isEmptyRecord(self.cookies)\n\n// eslint-disable-next-line no-control-regex\nconst fieldContentRegExp = /^[\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+$/\n\nconst CookieProto = {\n [CookieTypeId]: CookieTypeId,\n ...Inspectable.BaseProto,\n toJSON(this: Cookie) {\n return {\n _id: \"@effect/platform/Cookies/Cookie\",\n name: this.name,\n value: this.value,\n options: this.options\n }\n }\n}\n\n/**\n * Create a new cookie\n *\n * @since 1.0.0\n * @category constructors\n */\nexport function makeCookie(\n name: string,\n value: string,\n options?: Cookie[\"options\"] | undefined\n): Either.Either<Cookie, CookiesError> {\n if (!fieldContentRegExp.test(name)) {\n return Either.left(new CookiesError({ reason: \"InvalidName\" }))\n }\n const encodedValue = encodeURIComponent(value)\n if (encodedValue && !fieldContentRegExp.test(encodedValue)) {\n return Either.left(new CookiesError({ reason: \"InvalidValue\" }))\n }\n\n if (options !== undefined) {\n if (options.domain !== undefined && !fieldContentRegExp.test(options.domain)) {\n return Either.left(new CookiesError({ reason: \"InvalidDomain\" }))\n }\n\n if (options.path !== undefined && !fieldContentRegExp.test(options.path)) {\n return Either.left(new CookiesError({ reason: \"InvalidPath\" }))\n }\n\n if (options.maxAge !== undefined && !Duration.isFinite(Duration.decode(options.maxAge))) {\n return Either.left(new CookiesError({ reason: \"InfinityMaxAge\" }))\n }\n }\n\n return Either.right(Object.assign(Object.create(CookieProto), {\n name,\n value,\n valueEncoded: encodedValue,\n options\n }))\n}\n\n/**\n * Create a new cookie, throwing an error if invalid\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const unsafeMakeCookie = (\n name: string,\n value: string,\n options?: Cookie[\"options\"] | undefined\n): Cookie => Either.getOrThrowWith(makeCookie(name, value, options), identity)\n\n/**\n * Add a cookie to a Cookies object\n *\n * @since 1.0.0\n * @category combinators\n */\nexport const setCookie: {\n /**\n * Add a cookie to a Cookies object\n *\n * @since 1.0.0\n * @category combinators\n */\n (cookie: Cookie): (self: Cookies) => Cookies\n /**\n * Add a cookie to a Cookies object\n *\n * @since 1.0.0\n * @category combinators\n */\n (self: Cookies, cookie: Cookie): Cookies\n} = dual(\n 2,\n (self: Cookies, cookie: Cookie) =>\n fromReadonlyRecord(Record.set(\n self.cookies,\n cookie.name,\n cookie\n ))\n)\n\n/**\n * Add multiple cookies to a Cookies object\n *\n * @since 1.0.0\n * @category combinators\n */\nexport const setAllCookie: {\n /**\n * Add multiple cookies to a Cookies object\n *\n * @since 1.0.0\n * @category combinators\n */\n (cookies: Iterable<Cookie>): (self: Cookies) => Cookies\n /**\n * Add multiple cookies to a Cookies object\n *\n * @since 1.0.0\n * @category combinators\n */\n (self: Cookies, cookies: Iterable<Cookie>): Cookies\n} = dual(2, (self: Cookies, cookies: Iterable<Cookie>) => {\n const record = { ...self.cookies }\n for (const cookie of cookies) {\n record[cookie.name] = cookie\n }\n return fromReadonlyRecord(record)\n})\n\n/**\n * Combine two Cookies objects, removing duplicates from the first\n *\n * @since 1.0.0\n * @category combinators\n */\nexport const merge: {\n /**\n * Combine two Cookies objects, removing duplicates from the first\n *\n * @since 1.0.0\n * @category combinators\n */\n (that: Cookies): (self: Cookies) => Cookies\n /**\n * Combine two Cookies objects, removing duplicates from the first\n *\n * @since 1.0.0\n * @category combinators\n */\n (self: Cookies, that: Cookies): Cookies\n} = dual(2, (self: Cookies, that: Cookies) =>\n fromReadonlyRecord({\n ...self.cookies,\n ...that.cookies\n }))\n\n/**\n * Remove a cookie by name\n *\n * @since 1.0.0\n * @category combinators\n */\nexport const remove: {\n /**\n * Remove a cookie by name\n *\n * @since 1.0.0\n * @category combinators\n */\n (name: string): (self: Cookies) => Cookies\n /**\n * Remove a cookie by name\n *\n * @since 1.0.0\n * @category combinators\n */\n (self: Cookies, name: string): Cookies\n} = dual(2, (self: Cookies, name: string) => fromReadonlyRecord(Record.remove(self.cookies, name)))\n\n/**\n * Get a cookie from a Cookies object\n *\n * @since 1.0.0\n * @category combinators\n */\nexport const get: {\n /**\n * Get a cookie from a Cookies object\n *\n * @since 1.0.0\n * @category combinators\n */\n (name: string): (self: Cookies) => Option.Option<Cookie>\n /**\n * Get a cookie from a Cookies object\n *\n * @since 1.0.0\n * @category combinators\n */\n (self: Cookies, name: string): Option.Option<Cookie>\n} = dual(\n (args) => isCookies(args[0]),\n (self: Cookies, name: string): Option.Option<Cookie> => Record.get(self.cookies, name)\n)\n\n/**\n * Get a cookie from a Cookies object\n *\n * @since 1.0.0\n * @category combinators\n */\nexport const getValue: {\n /**\n * Get a cookie from a Cookies object\n *\n * @since 1.0.0\n * @category combinators\n */\n (name: string): (self: Cookies) => Option.Option<string>\n /**\n * Get a cookie from a Cookies object\n *\n * @since 1.0.0\n * @category combinators\n */\n (self: Cookies, name: string): Option.Option<string>\n} = dual(\n (args) => isCookies(args[0]),\n (self: Cookies, name: string): Option.Option<string> =>\n Option.map(Record.get(self.cookies, name), (cookie) => cookie.value)\n)\n\n/**\n * Add a cookie to a Cookies object\n *\n * @since 1.0.0\n * @category combinators\n */\nexport const set: {\n /**\n * Add a cookie to a Cookies object\n *\n * @since 1.0.0\n * @category combinators\n */\n (name: string, value: string, options?: Cookie[\"options\"]): (self: Cookies) => Either.Either<Cookies, CookiesError>\n /**\n * Add a cookie to a Cookies object\n *\n * @since 1.0.0\n * @category combinators\n */\n (self: Cookies, name: string, value: string, options?: Cookie[\"options\"]): Either.Either<Cookies, CookiesError>\n} = dual(\n (args) => isCookies(args[0]),\n (self: Cookies, name: string, value: string, options?: Cookie[\"options\"]) =>\n Either.map(\n makeCookie(name, value, options),\n (cookie) => fromReadonlyRecord(Record.set(self.cookies, name, cookie))\n )\n)\n\n/**\n * Add a cookie to a Cookies object\n *\n * @since 1.0.0\n * @category combinators\n */\nexport const unsafeSet: {\n /**\n * Add a cookie to a Cookies object\n *\n * @since 1.0.0\n * @category combinators\n */\n (name: string, value: string, options?: Cookie[\"options\"]): (self: Cookies) => Cookies\n /**\n * Add a cookie to a Cookies object\n *\n * @since 1.0.0\n * @category combinators\n */\n (self: Cookies, name: string, value: string, options?: Cookie[\"options\"]): Cookies\n} = dual(\n (args) => isCookies(args[0]),\n (self: Cookies, name: string, value: string, options?: Cookie[\"options\"]) =>\n fromReadonlyRecord(Record.set(\n self.cookies,\n name,\n unsafeMakeCookie(name, value, options)\n ))\n)\n\n/**\n * Add multiple cookies to a Cookies object\n *\n * @since 1.0.0\n * @category combinators\n */\nexport const setAll: {\n /**\n * Add multiple cookies to a Cookies object\n *\n * @since 1.0.0\n * @category combinators\n */\n (\n cookies: Iterable<readonly [name: string, value: string, options?: Cookie[\"options\"]]>\n ): (self: Cookies) => Either.Either<Cookies, CookiesError>\n /**\n * Add multiple cookies to a Cookies object\n *\n * @since 1.0.0\n * @category combinators\n */\n (\n self: Cookies,\n cookies: Iterable<readonly [name: string, value: string, options?: Cookie[\"options\"]]>\n ): Either.Either<Cookies, CookiesError>\n} = dual(\n 2,\n (\n self: Cookies,\n cookies: Iterable<readonly [name: string, value: string, options?: Cookie[\"options\"]]>\n ): Either.Either<Cookies, CookiesError> => {\n const record: Record<string, Cookie> = { ...self.cookies }\n for (const [name, value, options] of cookies) {\n const either = makeCookie(name, value, options)\n if (Either.isLeft(either)) {\n return either as Either.Left<CookiesError, never>\n }\n record[name] = either.right\n }\n return Either.right(fromReadonlyRecord(record))\n }\n)\n\n/**\n * Add multiple cookies to a Cookies object, throwing an error if invalid\n *\n * @since 1.0.0\n * @category combinators\n */\nexport const unsafeSetAll: {\n /**\n * Add multiple cookies to a Cookies object, throwing an error if invalid\n *\n * @since 1.0.0\n * @category combinators\n */\n (\n cookies: Iterable<readonly [name: string, value: string, options?: Cookie[\"options\"]]>\n ): (self: Cookies) => Cookies\n /**\n * Add multiple cookies to a Cookies object, throwing an error if invalid\n *\n * @since 1.0.0\n * @category combinators\n */\n (\n self: Cookies,\n cookies: Iterable<readonly [name: string, value: string, options?: Cookie[\"options\"]]>\n ): Cookies\n} = dual(\n 2,\n (\n self: Cookies,\n cookies: Iterable<readonly [name: string, value: string, options?: Cookie[\"options\"]]>\n ): Cookies => Either.getOrThrowWith(setAll(self, cookies), identity)\n)\n\n/**\n * Serialize a cookie into a string\n *\n * Adapted from https://github.com/fastify/fastify-cookie under MIT License\n *\n * @since 1.0.0\n * @category encoding\n */\nexport function serializeCookie(self: Cookie): string {\n let str = self.name + \"=\" + self.valueEncoded\n\n if (self.options === undefined) {\n return str\n }\n const options = self.options\n\n if (options.maxAge !== undefined) {\n const maxAge = Duration.toSeconds(options.maxAge)\n str += \"; Max-Age=\" + Math.trunc(maxAge)\n }\n\n if (options.domain !== undefined) {\n str += \"; Domain=\" + options.domain\n }\n\n if (options.path !== undefined) {\n str += \"; Path=\" + options.path\n }\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\n if (options.expires !== undefined) {\n str += \"; Expires=\" + options.expires.toUTCString()\n }\n\n if (options.httpOnly) {\n str += \"; HttpOnly\"\n }\n\n if (options.secure) {\n str += \"; Secure\"\n }\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\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\n return str\n}\n\n/**\n * Serialize a Cookies object into a Cookie header\n *\n * @since 1.0.0\n * @category encoding\n */\nexport const toCookieHeader = (self: Cookies): string =>\n Object.values(self.cookies).map((cookie) => `${cookie.name}=${cookie.valueEncoded}`).join(\"; \")\n\n/**\n * To record\n *\n * @since 1.0.0\n * @category encoding\n */\nexport const toRecord = (self: Cookies): Record<string, string> => {\n const record: Record<string, string> = {}\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/**\n * Serialize a Cookies object into Headers object containing one or more Set-Cookie headers\n *\n * @since 1.0.0\n * @category encoding\n */\nexport const toSetCookieHeaders = (self: Cookies): Array<string> => Object.values(self.cookies).map(serializeCookie)\n\n/**\n * Parse a cookie header into a record of key-value pairs\n *\n * Adapted from https://github.com/fastify/fastify-cookie under MIT License\n *\n * @since 1.0.0\n * @category decoding\n */\nexport function parseHeader(header: string): Record<string, string> {\n const result: Record<string, string> = {}\n\n const strLen = header.length\n let pos = 0\n let terminatorPos = 0\n\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\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\n const key = header.substring(pos, eqIdx++).trim()\n if (result[key] === undefined) {\n const val = header.charCodeAt(eqIdx) === 0x22\n ? header.substring(eqIdx + 1, terminatorPos - 1).trim()\n : header.substring(eqIdx, terminatorPos).trim()\n\n result[key] = !(val.indexOf(\"%\") === -1)\n ? tryDecodeURIComponent(val)\n : val\n }\n\n pos = terminatorPos + 1\n }\n\n return result\n}\n\nconst tryDecodeURIComponent = (str: string): string => {\n try {\n return decodeURIComponent(str)\n } catch {\n return str\n }\n}\n","/**\n * @since 1.0.0\n */\nimport type * as Cause from \"effect/Cause\"\nimport * as Data from \"effect/Data\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Schema from \"effect/Schema\"\nimport type { Simplify } from \"effect/Types\"\n\n/**\n * @since 1.0.0\n * @category type id\n */\nexport const TypeId: unique symbol = Symbol.for(\"@effect/platform/Error\")\n\n/**\n * @since 1.0.0\n * @category type id\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isPlatformError = (u: unknown): u is PlatformError => Predicate.hasProperty(u, TypeId)\n\n/**\n * @since 1.0.0\n * @category error\n */\nexport const TypeIdError = <const TypeId extends symbol, const Tag extends string>(\n typeId: TypeId,\n tag: Tag\n): new<A extends Record<string, any>>(\n args: Simplify<A>\n) =>\n & Cause.YieldableError\n & Record<TypeId, TypeId>\n & { readonly _tag: Tag }\n & Readonly<A> =>\n{\n class Base extends Data.Error<{}> {\n readonly _tag = tag\n }\n ;(Base.prototype as any)[typeId] = typeId\n ;(Base.prototype as any).name = tag\n return Base as any\n}\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport const Module = Schema.Literal(\n \"Clipboard\",\n \"Command\",\n \"FileSystem\",\n \"KeyValueStore\",\n \"Path\",\n \"Stream\",\n \"Terminal\"\n)\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport class BadArgument extends Schema.TaggedError<BadArgument>(\"@effect/platform/Error/BadArgument\")(\"BadArgument\", {\n module: Module,\n method: Schema.String,\n description: Schema.optional(Schema.String),\n cause: Schema.optional(Schema.Defect)\n}) {\n /**\n * @since 1.0.0\n */\n readonly [TypeId]: typeof TypeId = TypeId\n\n /**\n * @since 1.0.0\n */\n get message(): string {\n return `${this.module}.${this.method}${this.description ? `: ${this.description}` : \"\"}`\n }\n}\n\n/**\n * @since 1.0.0\n * @category Model\n */\nexport const SystemErrorReason = Schema.Literal(\n \"AlreadyExists\",\n \"BadResource\",\n \"Busy\",\n \"InvalidData\",\n \"NotFound\",\n \"PermissionDenied\",\n \"TimedOut\",\n \"UnexpectedEof\",\n \"Unknown\",\n \"WouldBlock\",\n \"WriteZero\"\n)\n\n/**\n * @since 1.0.0\n * @category Model\n */\nexport type SystemErrorReason = typeof SystemErrorReason.Type\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport class SystemError extends Schema.TaggedError<SystemError>(\"@effect/platform/Error/SystemError\")(\"SystemError\", {\n reason: SystemErrorReason,\n module: Module,\n method: Schema.String,\n description: Schema.optional(Schema.String),\n syscall: Schema.optional(Schema.String),\n pathOrDescriptor: Schema.optional(Schema.Union(Schema.String, Schema.Number)),\n cause: Schema.optional(Schema.Defect)\n}) {\n /**\n * @since 1.0.0\n */\n readonly [TypeId]: typeof TypeId = TypeId\n\n /**\n * @since 1.0.0\n */\n get message(): string {\n return `${this.reason}: ${this.module}.${this.method}${\n this.pathOrDescriptor !== undefined ? ` (${this.pathOrDescriptor})` : \"\"\n }${this.description ? `: ${this.description}` : \"\"}`\n }\n}\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport type PlatformError = BadArgument | SystemError\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport const PlatformError: Schema.Union<[\n typeof BadArgument,\n typeof SystemError\n]> = Schema.Union(BadArgument, SystemError)\n","/**\n * @since 1.0.0\n */\nimport * as FiberRef from \"effect/FiberRef\"\nimport * as FiberRefs from \"effect/FiberRefs\"\nimport { dual, identity } from \"effect/Function\"\nimport { globalValue } from \"effect/GlobalValue\"\nimport { type Redactable, symbolRedactable } from \"effect/Inspectable\"\nimport type * as Option from \"effect/Option\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Record from \"effect/Record\"\nimport * as Redacted from \"effect/Redacted\"\nimport * as Schema from \"effect/Schema\"\nimport * as String from \"effect/String\"\nimport type { Mutable } from \"effect/Types\"\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const HeadersTypeId: unique symbol = Symbol.for(\"@effect/platform/Headers\")\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type HeadersTypeId = typeof HeadersTypeId\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isHeaders = (u: unknown): u is Headers => Predicate.hasProperty(u, HeadersTypeId)\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Headers extends Redactable {\n readonly [HeadersTypeId]: HeadersTypeId\n readonly [key: string]: string\n}\n\nconst Proto = Object.assign(Object.create(null), {\n [HeadersTypeId]: HeadersTypeId,\n [symbolRedactable](\n this: Headers,\n fiberRefs: FiberRefs.FiberRefs\n ): Record<string, string | Redacted.Redacted<string>> {\n return redact(this, FiberRefs.getOrDefault(fiberRefs, currentRedactedNames))\n }\n})\n\nconst make = (input: Record.ReadonlyRecord<string, string>): Mutable<Headers> =>\n Object.assign(Object.create(Proto), input) as Headers\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport const schemaFromSelf: Schema.Schema<Headers> = Schema.declare(isHeaders, {\n typeConstructor: { _tag: \"effect/platform/Headers\" },\n identifier: \"Headers\",\n equivalence: () => Record.getEquivalence(String.Equivalence)\n})\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport const schema: Schema.Schema<Headers, Record.ReadonlyRecord<string, string>> = Schema\n .transform(\n Schema.Record({ key: Schema.String, value: Schema.String }),\n schemaFromSelf,\n { strict: true, decode: (record) => fromInput(record), encode: identity }\n )\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport type Input =\n | Record.ReadonlyRecord<string, string | ReadonlyArray<string> | undefined>\n | Iterable<readonly [string, string]>\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const empty: Headers = Object.create(Proto)\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const fromInput: (input?: Input) => Headers = (input) => {\n if (input === undefined) {\n return empty\n } else if (Symbol.iterator in input) {\n const out: Record<string, string> = Object.create(Proto)\n for (const [k, v] of input) {\n out[k.toLowerCase()] = v\n }\n return out as Headers\n }\n const out: Record<string, string> = 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 as string\n }\n }\n return out as Headers\n}\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const unsafeFromRecord = (input: Record.ReadonlyRecord<string, string>): Headers =>\n Object.setPrototypeOf(input, Proto) as Headers\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const has: {\n /**\n * @since 1.0.0\n * @category combinators\n */\n (key: string): (self: Headers) => boolean\n /**\n * @since 1.0.0\n * @category combinators\n */\n (self: Headers, key: string): boolean\n} = dual<\n /**\n * @since 1.0.0\n * @category combinators\n */\n (key: string) => (self: Headers) => boolean,\n /**\n * @since 1.0.0\n * @category combinators\n */\n (self: Headers, key: string) => boolean\n>(2, (self, key) => key.toLowerCase() in self)\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const get: {\n /**\n * @since 1.0.0\n * @category combinators\n */\n (key: string): (self: Headers) => Option.Option<string>\n /**\n * @since 1.0.0\n * @category combinators\n */\n (self: Headers, key: string): Option.Option<string>\n} = dual<\n /**\n * @since 1.0.0\n * @category combinators\n */\n (key: string) => (self: Headers) => Option.Option<string>,\n /**\n * @since 1.0.0\n * @category combinators\n */\n (self: Headers, key: string) => Option.Option<string>\n>(2, (self, key) => Record.get(self as Record<string, string>, key.toLowerCase()))\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const set: {\n /**\n * @since 1.0.0\n * @category combinators\n */\n (key: string, value: string): (self: Headers) => Headers\n /**\n * @since 1.0.0\n * @category combinators\n */\n (self: Headers, key: string, value: string): Headers\n} = dual<\n /**\n * @since 1.0.0\n * @category combinators\n */\n (key: string, value: string) => (self: Headers) => Headers,\n /**\n * @since 1.0.0\n * @category combinators\n */\n (self: Headers, key: string, value: string) => Headers\n>(3, (self, key, value) => {\n const out = make(self)\n out[key.toLowerCase()] = value\n return out\n})\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const setAll: {\n /**\n * @since 1.0.0\n * @category combinators\n */\n (headers: Input): (self: Headers) => Headers\n /**\n * @since 1.0.0\n * @category combinators\n */\n (self: Headers, headers: Input): Headers\n} = dual<\n /**\n * @since 1.0.0\n * @category combinators\n */\n (headers: Input) => (self: Headers) => Headers,\n /**\n * @since 1.0.0\n * @category combinators\n */\n (self: Headers, headers: Input) => Headers\n>(2, (self, headers) =>\n make({\n ...self,\n ...fromInput(headers)\n }))\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const merge: {\n /**\n * @since 1.0.0\n * @category combinators\n */\n (headers: Headers): (self: Headers) => Headers\n /**\n * @since 1.0.0\n * @category combinators\n */\n (self: Headers, headers: Headers): Headers\n} = dual<\n /**\n * @since 1.0.0\n * @category combinators\n */\n (headers: Headers) => (self: Headers) => Headers,\n /**\n * @since 1.0.0\n * @category combinators\n */\n (self: Headers, headers: Headers) => Headers\n>(2, (self, headers) => {\n const out = make(self)\n Object.assign(out, headers)\n return out\n})\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const remove: {\n /**\n * @since 1.0.0\n * @category combinators\n */\n (key: string | RegExp | ReadonlyArray<string | RegExp>): (self: Headers) => Headers\n /**\n * @since 1.0.0\n * @category combinators\n */\n (self: Headers, key: string | RegExp | ReadonlyArray<string | RegExp>): Headers\n} = dual<\n /**\n * @since 1.0.0\n * @category combinators\n */\n (key: string | RegExp | ReadonlyArray<string | RegExp>) => (self: Headers) => Headers,\n /**\n * @since 1.0.0\n * @category combinators\n */\n (self: Headers, key: string | RegExp | ReadonlyArray<string | RegExp>) => Headers\n>(2, (self, key) => {\n const out = make(self)\n const modify = (key: string | RegExp) => {\n if (typeof key === \"string\") {\n const k = key.toLowerCase()\n if (k in self) {\n delete out[k]\n }\n } else {\n for (const name in self) {\n if (key.test(name)) {\n delete out[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 as string | RegExp)\n }\n return out\n})\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const redact: {\n /**\n * @since 1.0.0\n * @category combinators\n */\n (key: string | RegExp | ReadonlyArray<string | RegExp>): (self: Headers) => Record<string, string | Redacted.Redacted>\n /**\n * @since 1.0.0\n * @category combinators\n */\n (self: Headers, key: string | RegExp | ReadonlyArray<string | RegExp>): Record<string, string | Redacted.Redacted>\n} = dual(\n 2,\n (\n self: Headers,\n key: string | RegExp | ReadonlyArray<string | RegExp>\n ): Record<string, string | Redacted.Redacted> => {\n const out: Record<string, string | Redacted.Redacted> = { ...self }\n const modify = (key: string | RegExp) => {\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 as string | RegExp)\n }\n return out\n }\n)\n\n/**\n * @since 1.0.0\n * @category fiber refs\n */\nexport const currentRedactedNames: FiberRef.FiberRef<ReadonlyArray<string | RegExp>> = globalValue(\n \"@effect/platform/Headers/currentRedactedNames\",\n () =>\n FiberRef.unsafeMake<ReadonlyArray<string | RegExp>>([\n \"authorization\",\n \"cookie\",\n \"set-cookie\",\n \"x-api-key\"\n ])\n)\n","/**\n * @since 1.0.0\n */\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport { dual } from \"effect/Function\"\nimport * as Inspectable from \"effect/Inspectable\"\nimport * as Option from \"effect/Option\"\nimport type * as ParseResult from \"effect/ParseResult\"\nimport * as Schema from \"effect/Schema\"\nimport type { ParseOptions } from \"effect/SchemaAST\"\nimport type * as Stream from \"effect/Stream\"\nimport * as FileSystem from \"./FileSystem.js\"\nimport type * as Headers from \"./Headers.js\"\nimport * as UrlParams from \"./UrlParams.js\"\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const TypeId: unique symbol = Symbol.for(\"@effect/platform/HttpIncomingMessage\")\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface HttpIncomingMessage<E> extends Inspectable.Inspectable {\n readonly [TypeId]: TypeId\n readonly headers: Headers.Headers\n readonly remoteAddress: Option.Option<string>\n readonly json: Effect.Effect<unknown, E>\n readonly text: Effect.Effect<string, E>\n readonly urlParamsBody: Effect.Effect<UrlParams.UrlParams, E>\n readonly arrayBuffer: Effect.Effect<ArrayBuffer, E>\n readonly stream: Stream.Stream<Uint8Array, E>\n}\n\n/**\n * @since 1.0.0\n * @category schema\n */\nexport const schemaBodyJson = <A, I, R>(schema: Schema.Schema<A, I, R>, options?: ParseOptions | undefined) => {\n const parse = Schema.decodeUnknown(schema, options)\n return <E>(self: HttpIncomingMessage<E>): Effect.Effect<A, E | ParseResult.ParseError, R> =>\n Effect.flatMap(self.json, parse)\n}\n\n/**\n * @since 1.0.0\n * @category schema\n */\nexport const schemaBodyUrlParams = <\n A,\n I extends Readonly<Record<string, string | ReadonlyArray<string> | undefined>>,\n R\n>(\n schema: Schema.Schema<A, I, R>,\n options?: ParseOptions | undefined\n) => {\n const decode = UrlParams.schemaStruct(schema, options)\n return <E>(self: HttpIncomingMessage<E>): Effect.Effect<A, E | ParseResult.ParseError, R> =>\n Effect.flatMap(self.urlParamsBody, decode)\n}\n\n/**\n * @since 1.0.0\n * @category schema\n */\nexport const schemaHeaders = <A, I extends Readonly<Record<string, string | undefined>>, R>(\n schema: Schema.Schema<A, I, R>,\n options?: ParseOptions | undefined\n) => {\n const parse = Schema.decodeUnknown(schema, options)\n return <E>(self: HttpIncomingMessage<E>): Effect.Effect<A, ParseResult.ParseError, R> => parse(self.headers)\n}\n\n/**\n * @since 1.0.0\n * @category fiber refs\n */\nexport class MaxBodySize extends Context.Reference<MaxBodySize>()(\"@effect/platform/HttpIncomingMessage/MaxBodySize\", {\n defaultValue: Option.none<FileSystem.Size>\n}) {}\n\n/**\n * @since 1.0.0\n * @category fiber refs\n */\nexport const withMaxBodySize = dual<\n /**\n * @since 1.0.0\n * @category fiber refs\n */\n (size: Option.Option<FileSystem.SizeInput>) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n /**\n * @since 1.0.0\n * @category fiber refs\n */\n <A, E, R>(effect: Effect.Effect<A, E, R>, size: Option.Option<FileSystem.SizeInput>) => Effect.Effect<A, E, R>\n>(2, (effect, size) => Effect.provideService(effect, MaxBodySize, Option.map(size, FileSystem.Size)))\n\n/**\n * @since 1.0.0\n */\nexport const inspect = <E>(self: HttpIncomingMessage<E>, that: object): object => {\n const contentType = self.headers[\"content-type\"] ?? \"\"\n let body: unknown\n if (contentType.includes(\"application/json\")) {\n try {\n body = Effect.runSync(self.json)\n } catch {\n //\n }\n } else if (contentType.includes(\"text/\") || contentType.includes(\"urlencoded\")) {\n try {\n body = Effect.runSync(self.text)\n } catch {\n //\n }\n }\n const obj: any = {\n ...that,\n headers: Inspectable.redact(self.headers),\n remoteAddress: self.remoteAddress.toJSON()\n }\n if (body !== undefined) {\n obj.body = body\n }\n return obj\n}\n","/**\n * @since 1.0.0\n */\nimport * as Brand from \"effect/Brand\"\nimport type { Tag } from \"effect/Context\"\nimport * as Context from \"effect/Context\"\nimport * as Data from \"effect/Data\"\nimport type * as Effect from \"effect/Effect\"\nimport type { Layer } from \"effect/Layer\"\nimport type { Option } from \"effect/Option\"\nimport type { Scope } from \"effect/Scope\"\nimport type { Sink } from \"effect/Sink\"\nimport type { Stream } from \"effect/Stream\"\nimport type { PlatformError } from \"./Error.js\"\nimport * as internal from \"./internal/fileSystem.js\"\n\n/**\n * @since 1.0.0\n * @category model\n */\nexport interface FileSystem {\n /**\n * Check if a file can be accessed.\n * You can optionally specify the level of access to check for.\n */\n readonly access: (\n path: string,\n options?: AccessFileOptions\n ) => Effect.Effect<void, PlatformError>\n /**\n * Copy a file or directory from `fromPath` to `toPath`.\n *\n * Equivalent to `cp -r`.\n */\n readonly copy: (\n fromPath: string,\n toPath: string,\n options?: CopyOptions\n ) => Effect.Effect<void, PlatformError>\n /**\n * Copy a file from `fromPath` to `toPath`.\n */\n readonly copyFile: (\n fromPath: string,\n toPath: string\n ) => Effect.Effect<void, PlatformError>\n /**\n * Change the permissions of a file.\n */\n readonly chmod: (\n path: string,\n mode: number\n ) => Effect.Effect<void, PlatformError>\n /**\n * Change the owner and group of a file.\n */\n readonly chown: (\n path: string,\n uid: number,\n gid: number\n ) => Effect.Effect<void, PlatformError>\n /**\n * Check if a path exists.\n */\n readonly exists: (\n path: string\n ) => Effect.Effect<boolean, PlatformError>\n /**\n * Create a hard link from `fromPath` to `toPath`.\n */\n readonly link: (\n fromPath: string,\n toPath: string\n ) => Effect.Effect<void, PlatformError>\n /**\n * Create a directory at `path`. You can optionally specify the mode and\n * whether to recursively create nested directories.\n */\n readonly makeDirectory: (\n path: string,\n options?: MakeDirectoryOptions\n ) => Effect.Effect<void, PlatformError>\n /**\n * Create a temporary directory.\n *\n * By default the directory will be created inside the system's default\n * temporary directory, but you can specify a different location by setting\n * the `directory` option.\n *\n * You can also specify a prefix for the directory name by setting the\n * `prefix` option.\n */\n readonly makeTempDirectory: (\n options?: MakeTempDirectoryOptions\n ) => Effect.Effect<string, PlatformError>\n /**\n * Create a temporary directory inside a scope.\n *\n * Functionally equivalent to `makeTempDirectory`, but the directory will be\n * automatically deleted when the scope is closed.\n */\n readonly makeTempDirectoryScoped: (\n options?: MakeTempDirectoryOptions\n ) => Effect.Effect<string, PlatformError, Scope>\n /**\n * Create a temporary file.\n * The directory creation is functionally equivalent to `makeTempDirectory`.\n * The file name will be a randomly generated string.\n */\n readonly makeTempFile: (\n options?: MakeTempFileOptions\n ) => Effect.Effect<string, PlatformError>\n /**\n * Create a temporary file inside a scope.\n *\n * Functionally equivalent to `makeTempFile`, but the file will be\n * automatically deleted when the scope is closed.\n */\n readonly makeTempFileScoped: (\n options?: MakeTempFileOptions\n ) => Effect.Effect<string, PlatformError, Scope>\n /**\n * Open a file at `path` with the specified `options`.\n *\n * The file handle will be automatically closed when the scope is closed.\n */\n readonly open: (\n path: string,\n options?: OpenFileOptions\n ) => Effect.Effect<File, PlatformError, Scope>\n /**\n * List the contents of a directory.\n *\n * You can recursively list the contents of nested directories by setting the\n * `recursive` option.\n */\n readonly readDirectory: (\n path: string,\n options?: ReadDirectoryOptions\n ) => Effect.Effect<Array<string>, PlatformError>\n /**\n * Read the contents of a file.\n */\n readonly readFile: (\n path: string\n ) => Effect.Effect<Uint8Array, PlatformError>\n /**\n * Read the contents of a file.\n */\n readonly readFileString: (\n path: string,\n encoding?: string\n ) => Effect.Effect<string, PlatformError>\n /**\n * Read the destination of a symbolic link.\n */\n readonly readLink: (\n path: string\n ) => Effect.Effect<string, PlatformError>\n /**\n * Resolve a path to its canonicalized absolute pathname.\n */\n readonly realPath: (\n path: string\n ) => Effect.Effect<string, PlatformError>\n /**\n * Remove a file or directory.\n */\n readonly remove: (\n path: string,\n options?: RemoveOptions\n ) => Effect.Effect<void, PlatformError>\n /**\n * Rename a file or directory.\n */\n readonly rename: (\n oldPath: string,\n newPath: string\n ) => Effect.Effect<void, PlatformError>\n /**\n * Create a writable `Sink` for the specified `path`.\n */\n readonly sink: (\n path: string,\n options?: SinkOptions\n ) => Sink<void, Uint8Array, never, PlatformError>\n /**\n * Get information about a file at `path`.\n */\n readonly stat: (\n path: string\n ) => Effect.Effect<File.Info, PlatformError>\n /**\n * Create a readable `Stream` for the specified `path`.\n *\n * Changing the `bufferSize` option will change the internal buffer size of\n * the stream. It defaults to `4`.\n *\n * The `chunkSize` option will change the size of the chunks emitted by the\n * stream. It defaults to 64kb.\n *\n * Changing `offset` and `bytesToRead` will change the offset and the number\n * of bytes to read from the file.\n */\n readonly stream: (\n path: string,\n options?: StreamOptions\n ) => Stream<Uint8Array, PlatformError>\n /**\n * Create a symbolic link from `fromPath` to `toPath`.\n */\n readonly symlink: (\n fromPath: string,\n toPath: string\n ) => Effect.Effect<void, PlatformError>\n /**\n * Truncate a file to a specified length. If the `length` is not specified,\n * the file will be truncated to length `0`.\n */\n readonly truncate: (\n path: string,\n length?: SizeInput\n ) => Effect.Effect<void, PlatformError>\n /**\n * Change the file system timestamps of the file at `path`.\n */\n readonly utimes: (\n path: string,\n atime: Date | number,\n mtime: Date | number\n ) => Effect.Effect<void, PlatformError>\n /**\n * Watch a directory or file for changes.\n *\n * By default, only changes to the direct children of the directory are reported.\n * Set the `recursive` option to `true` to watch for changes in subdirectories as well.\n *\n * Note: The `recursive` option behavior depends on the backend implementation:\n * - When using the default Node.js `fs.watch()` backend: The `recursive`\n * option is supported on all platforms (Node.js v20+).\n * - When using `@parcel/watcher` (via `NodeFileSystem/ParcelWatcher` layer):\n * Watching is always recursive on all platforms. This option is ignored.\n */\n readonly watch: (path: string, options?: WatchOptions) => Stream<WatchEvent, PlatformError>\n /**\n * Write data to a file at `path`.\n */\n readonly writeFile: (\n path: string,\n data: Uint8Array,\n options?: WriteFileOptions\n ) => Effect.Effect<void, PlatformError>\n /**\n * Write a string to a file at `path`.\n */\n readonly writeFileString: (\n path: string,\n data: string,\n options?: WriteFileStringOptions\n ) => Effect.Effect<void, PlatformError>\n}\n\n/**\n * Represents a size in bytes.\n *\n * @since 1.0.0\n * @category sizes\n */\nexport type Size = Brand.Branded<bigint, \"Size\">\n\n/**\n * Represents a size in bytes.\n *\n * @since 1.0.0\n * @category sizes\n */\nexport type SizeInput = bigint | number | Size\n\n/**\n * @since 1.0.0\n * @category sizes\n */\nexport const Size: (bytes: SizeInput) => Size = internal.Size\n\n/**\n * @since 1.0.0\n * @category sizes\n */\nexport const KiB: (n: number) => Size = internal.KiB\n\n/**\n * @since 1.0.0\n * @category sizes\n */\nexport const MiB: (n: number) => Size = internal.MiB\n\n/**\n * @since 1.0.0\n * @category sizes\n */\nexport const GiB: (n: number) => Size = internal.GiB\n\n/**\n * @since 1.0.0\n * @category sizes\n */\nexport const TiB: (n: number) => Size = internal.TiB\n\n/**\n * @since 1.0.0\n * @category sizes\n */\nexport const PiB: (n: number) => Size = internal.PiB\n\n/**\n * @since 1.0.0\n * @category model\n */\nexport type OpenFlag =\n | \"r\"\n | \"r+\"\n | \"w\"\n | \"wx\"\n | \"w+\"\n | \"wx+\"\n | \"a\"\n | \"ax\"\n | \"a+\"\n | \"ax+\"\n\n/**\n * @since 1.0.0\n * @category options\n */\nexport interface AccessFileOptions {\n readonly ok?: boolean\n readonly readable?: boolean\n readonly writable?: boolean\n}\n\n/**\n * @since 1.0.0\n * @category options\n */\nexport interface MakeDirectoryOptions {\n readonly recursive?: boolean\n readonly mode?: number\n}\n\n/**\n * @since 1.0.0\n * @category options\n */\nexport interface CopyOptions {\n readonly overwrite?: boolean\n readonly preserveTimestamps?: boolean\n}\n\n/**\n * @since 1.0.0\n * @category options\n */\nexport interface MakeTempDirectoryOptions {\n readonly directory?: string\n readonly prefix?: string\n}\n\n/**\n * @since 1.0.0\n * @category options\n */\nexport interface MakeTempFileOptions {\n readonly directory?: string\n readonly prefix?: string\n readonly suffix?: string\n}\n\n/**\n * @since 1.0.0\n * @category options\n */\nexport interface OpenFileOptions {\n readonly flag?: OpenFlag\n readonly mode?: number\n}\n\n/**\n * @since 1.0.0\n * @category options\n */\nexport interface ReadDirectoryOptions {\n readonly recursive?: boolean\n}\n\n/**\n * @since 1.0.0\n * @category options\n */\nexport interface RemoveOptions {\n /**\n * When `true`, you can recursively remove nested directories.\n */\n readonly recursive?: boolean\n /**\n * When `true`, exceptions will be ignored if `path` does not exist.\n */\n readonly force?: boolean\n}\n\n/**\n * @since 1.0.0\n * @category options\n */\nexport interface SinkOptions extends OpenFileOptions {}\n\n/**\n * @since 1.0.0\n * @category options\n */\nexport interface StreamOptions {\n readonly bufferSize?: number\n readonly bytesToRead?: SizeInput\n readonly chunkSize?: SizeInput\n readonly offset?: SizeInput\n}\n\n/**\n * @since 1.0.0\n * @category options\n */\nexport interface WriteFileOptions {\n readonly flag?: OpenFlag\n readonly mode?: number\n}\n\n/**\n * @since 1.0.0\n * @category options\n */\nexport interface WriteFileStringOptions {\n readonly flag?: OpenFlag\n readonly mode?: number\n}\n\n/**\n * @since 1.0.0\n * @category options\n */\nexport interface WatchOptions {\n /**\n * When `true`, the watcher will also watch for changes in subdirectories.\n */\n readonly recursive?: boolean\n}\n\n/**\n * @since 1.0.0\n * @category tag\n */\nexport const FileSystem: Tag<FileSystem, FileSystem> = internal.tag\n\n/**\n * @since 1.0.0\n * @category constructor\n */\nexport const make: (\n impl: Omit<FileSystem, \"exists\" | \"readFileString\" | \"stream\" | \"sink\" | \"writeFileString\">\n) => FileSystem = internal.make\n\n/**\n * Create a no-op file system that can be used for testing.\n *\n * @since 1.0.0\n * @category constructor\n */\nexport const makeNoop: (fileSystem: Partial<FileSystem>) => FileSystem = internal.makeNoop\n\n/**\n * Create a no-op file system that can be used for testing.\n *\n * @since 1.0.0\n * @category layers\n */\nexport const layerNoop: (fileSystem: Partial<FileSystem>) => Layer<FileSystem> = internal.layerNoop\n\n/**\n * @since 1.0.0\n * @category type id\n */\nexport const FileTypeId: unique symbol = Symbol.for(\n \"@effect/platform/FileSystem/File\"\n)\n\n/**\n * @since 1.0.0\n * @category type id\n */\nexport type FileTypeId = typeof FileTypeId\n\n/**\n * @since 1.0.0\n * @category guard\n */\nexport const isFile = (u: unknown): u is File => typeof u === \"object\" && u !== null && FileTypeId in u\n\n/**\n * @since 1.0.0\n * @category model\n */\nexport interface File {\n readonly [FileTypeId]: FileTypeId\n readonly fd: File.Descriptor\n readonly stat: Effect.Effect<File.Info, PlatformError>\n readonly seek: (offset: SizeInput, from: SeekMode) => Effect.Effect<void>\n readonly sync: Effect.Effect<void, PlatformError>\n readonly read: (buffer: Uint8Array) => Effect.Effect<Size, PlatformError>\n readonly readAlloc: (size: SizeInput) => Effect.Effect<Option<Uint8Array>, PlatformError>\n readonly truncate: (length?: SizeInput) => Effect.Effect<void, PlatformError>\n readonly write: (buffer: Uint8Array) => Effect.Effect<Size, PlatformError>\n readonly writeAll: (buffer: Uint8Array) => Effect.Effect<void, PlatformError>\n}\n\n/**\n * @since 1.0.0\n */\nexport declare namespace File {\n /**\n * @since 1.0.0\n * @category model\n */\n export type Descriptor = Brand.Branded<number, \"FileDescriptor\">\n\n /**\n * @since 1.0.0\n * @category model\n */\n export type Type =\n | \"File\"\n | \"Directory\"\n | \"SymbolicLink\"\n | \"BlockDevice\"\n | \"CharacterDevice\"\n | \"FIFO\"\n | \"Socket\"\n | \"Unknown\"\n\n /**\n * @since 1.0.0\n * @category model\n */\n export interface Info {\n readonly type: Type\n readonly mtime: Option<Date>\n readonly atime: Option<Date>\n readonly birthtime: Option<Date>\n readonly dev: number\n readonly ino: Option<number>\n readonly mode: number\n readonly nlink: Option<number>\n readonly uid: Option<number>\n readonly gid: Option<number>\n readonly rdev: Option<number>\n readonly size: Size\n readonly blksize: Option<Size>\n readonly blocks: Option<number>\n }\n}\n\n/**\n * @since 1.0.0\n * @category constructor\n */\nexport const FileDescriptor = Brand.nominal<File.Descriptor>()\n\n/**\n * @since 1.0.0\n * @category model\n */\nexport type SeekMode = \"start\" | \"current\"\n\n/**\n * @since 1.0.0\n * @category model\n */\nexport type WatchEvent = WatchEvent.Create | WatchEvent.Update | WatchEvent.Remove\n\n/**\n * @since 1.0.0\n * @category model\n */\nexport declare namespace WatchEvent {\n /**\n * @since 1.0.0\n * @category model\n */\n export interface Create {\n readonly _tag: \"Create\"\n readonly path: string\n }\n\n /**\n * @since 1.0.0\n * @category model\n */\n export interface Update {\n readonly _tag: \"Update\"\n readonly path: string\n }\n\n /**\n * @since 1.0.0\n * @category model\n */\n export interface Remove {\n readonly _tag: \"Remove\"\n readonly path: string\n }\n}\n\n/**\n * @since 1.0.0\n * @category constructor\n */\nexport const WatchEventCreate: Data.Case.Constructor<WatchEvent.Create, \"_tag\"> = Data.tagged<WatchEvent.Create>(\n \"Create\"\n)\n\n/**\n * @since 1.0.0\n * @category constructor\n */\nexport const WatchEventUpdate: Data.Case.Constructor<WatchEvent.Update, \"_tag\"> = Data.tagged<WatchEvent.Update>(\n \"Update\"\n)\n\n/**\n * @since 1.0.0\n * @category constructor\n */\nexport const WatchEventRemove: Data.Case.Constructor<WatchEvent.Remove, \"_tag\"> = Data.tagged<WatchEvent.Remove>(\n \"Remove\"\n)\n\n/**\n * @since 1.0.0\n * @category file watcher\n */\nexport class WatchBackend extends Context.Tag(\"@effect/platform/FileSystem/WatchBackend\")<\n WatchBackend,\n {\n readonly register: (\n path: string,\n stat: File.Info,\n options?: WatchOptions\n ) => Option<Stream<WatchEvent, PlatformError>>\n }\n>() {\n}\n","import * as Channel from \"effect/Channel\"\nimport * as Chunk from \"effect/Chunk\"\nimport { GenericTag } from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport { identity, pipe } from \"effect/Function\"\nimport * as Layer from \"effect/Layer\"\nimport * as Option from \"effect/Option\"\nimport * as Sink from \"effect/Sink\"\nimport * as Stream from \"effect/Stream\"\nimport * as Error from \"../Error.js\"\nimport type { File, FileSystem, Size as Size_, SizeInput, StreamOptions } from \"../FileSystem.js\"\n\n/** @internal */\nexport const tag = GenericTag<FileSystem>(\"@effect/platform/FileSystem\")\n\n/** @internal */\nexport const Size = (bytes: SizeInput) => typeof bytes === \"bigint\" ? bytes as Size_ : BigInt(bytes) as Size_\n\n/** @internal */\nexport const KiB = (n: number) => Size(n * 1024)\n\n/** @internal */\nexport const MiB = (n: number) => Size(n * 1024 * 1024)\n\n/** @internal */\nexport const GiB = (n: number) => Size(n * 1024 * 1024 * 1024)\n\n/** @internal */\nexport const TiB = (n: number) => Size(n * 1024 * 1024 * 1024 * 1024)\n\nconst bigint1024 = BigInt(1024)\nconst bigintPiB = bigint1024 * bigint1024 * bigint1024 * bigint1024 * bigint1024\n\n/** @internal */\nexport const PiB = (n: number) => Size(BigInt(n) * bigintPiB)\n\n/** @internal */\nexport const make = (\n impl: Omit<FileSystem, \"exists\" | \"readFileString\" | \"stream\" | \"sink\" | \"writeFileString\">\n): FileSystem => {\n return tag.of({\n ...impl,\n exists: (path) =>\n pipe(\n impl.access(path),\n Effect.as(true),\n Effect.catchTag(\"SystemError\", (e) => e.reason === \"NotFound\" ? Effect.succeed(false) : Effect.fail(e))\n ),\n readFileString: (path, encoding) =>\n Effect.tryMap(impl.readFile(path), {\n try: (_) => new TextDecoder(encoding).decode(_),\n catch: (cause) =>\n new Error.BadArgument({\n module: \"FileSystem\",\n method: \"readFileString\",\n description: \"invalid encoding\",\n cause\n })\n }),\n stream: (path, options) =>\n pipe(\n impl.open(path, { flag: \"r\" }),\n options?.offset ?\n Effect.tap((file) => file.seek(options.offset!, \"start\")) :\n identity,\n Effect.map((file) => stream(file, options)),\n Stream.unwrapScoped\n ),\n sink: (path, options) =>\n pipe(\n impl.open(path, { flag: \"w\", ...options }),\n Effect.map((file) => Sink.forEach((_: Uint8Array) => file.writeAll(_))),\n Sink.unwrapScoped\n ),\n writeFileString: (path, data, options) =>\n Effect.flatMap(\n Effect.try({\n try: () => new TextEncoder().encode(data),\n catch: (cause) =>\n new Error.BadArgument({\n module: \"FileSystem\",\n method: \"writeFileString\",\n description: \"could not encode string\",\n cause\n })\n }),\n (_) => impl.writeFile(path, _, options)\n )\n })\n}\n\nconst notFound = (method: string, path: string) =>\n new Error.SystemError({\n module: \"FileSystem\",\n method,\n reason: \"NotFound\",\n description: \"No such file or directory\",\n pathOrDescriptor: path\n })\n\n/** @internal */\nexport const makeNoop = (\n fileSystem: Partial<FileSystem>\n): FileSystem => {\n return {\n access(path) {\n return Effect.fail(notFound(\"access\", path))\n },\n chmod(path) {\n return Effect.fail(notFound(\"chmod\", path))\n },\n chown(path) {\n return Effect.fail(notFound(\"chown\", path))\n },\n copy(path) {\n return Effect.fail(notFound(\"copy\", path))\n },\n copyFile(path) {\n return Effect.fail(notFound(\"copyFile\", path))\n },\n exists() {\n return Effect.succeed(false)\n },\n link(path) {\n return Effect.fail(notFound(\"link\", path))\n },\n makeDirectory() {\n return Effect.die(\"not implemented\")\n },\n makeTempDirectory() {\n return Effect.die(\"not implemented\")\n },\n makeTempDirectoryScoped() {\n return Effect.die(\"not implemented\")\n },\n makeTempFile() {\n return Effect.die(\"not implemented\")\n },\n makeTempFileScoped() {\n return Effect.die(\"not implemented\")\n },\n open(path) {\n return Effect.fail(notFound(\"open\", path))\n },\n readDirectory(path) {\n return Effect.fail(notFound(\"readDirectory\", path))\n },\n readFile(path) {\n return Effect.fail(notFound(\"readFile\", path))\n },\n readFileString(path) {\n return Effect.fail(notFound(\"readFileString\", path))\n },\n readLink(path) {\n return Effect.fail(notFound(\"readLink\", path))\n },\n realPath(path) {\n return Effect.fail(notFound(\"realPath\", path))\n },\n remove() {\n return Effect.void\n },\n rename(oldPath) {\n return Effect.fail(notFound(\"rename\", oldPath))\n },\n sink(path) {\n return Sink.fail(notFound(\"sink\", path))\n },\n stat(path) {\n return Effect.fail(notFound(\"stat\", path))\n },\n stream(path) {\n return Stream.fail(notFound(\"stream\", path))\n },\n symlink(fromPath) {\n return Effect.fail(notFound(\"symlink\", fromPath))\n },\n truncate(path) {\n return Effect.fail(notFound(\"truncate\", path))\n },\n utimes(path) {\n return Effect.fail(notFound(\"utimes\", path))\n },\n watch(path) {\n return Stream.fail(notFound(\"watch\", path))\n },\n writeFile(path) {\n return Effect.fail(notFound(\"writeFile\", path))\n },\n writeFileString(path) {\n return Effect.fail(notFound(\"writeFileString\", path))\n },\n ...fileSystem\n }\n}\n\n/** @internal */\nexport const layerNoop = (\n fileSystem: Partial<FileSystem>\n): Layer.Layer<FileSystem> => Layer.succeed(tag, makeNoop(fileSystem))\n\n/** @internal */\nconst stream = (file: File, {\n bufferSize = 16,\n bytesToRead: bytesToRead_,\n chunkSize: chunkSize_ = Size(64 * 1024)\n}: StreamOptions = {}) => {\n const bytesToRead = bytesToRead_ !== undefined ? Size(bytesToRead_) : undefined\n const chunkSize = Size(chunkSize_)\n\n function loop(\n totalBytesRead: bigint\n ): Channel.Channel<Chunk.Chunk<Uint8Array>, unknown, Error.PlatformError, unknown, void, unknown> {\n if (bytesToRead !== undefined && bytesToRead <= totalBytesRead) {\n return Channel.void\n }\n\n const toRead = bytesToRead !== undefined && (bytesToRead - totalBytesRead) < chunkSize\n ? bytesToRead - totalBytesRead\n : chunkSize\n\n return Channel.flatMap(\n file.readAlloc(toRead),\n Option.match({\n onNone: () => Channel.void,\n onSome: (buf) =>\n Channel.flatMap(\n Channel.write(Chunk.of(buf)),\n (_) => loop(totalBytesRead + BigInt(buf.length))\n )\n })\n )\n }\n\n return Stream.bufferChunks(\n Stream.fromChannel(loop(BigInt(0))),\n { capacity: bufferSize }\n )\n}\n","/**\n * @since 1.0.0\n */\nimport * as Arr from \"effect/Array\"\nimport type * as Effect from \"effect/Effect\"\nimport * as Either from \"effect/Either\"\nimport { dual } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport type * as ParseResult from \"effect/ParseResult\"\nimport * as Schema from \"effect/Schema\"\nimport type { ParseOptions } from \"effect/SchemaAST\"\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface UrlParams extends ReadonlyArray<readonly [string, string]> {}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport type Input =\n | CoercibleRecord\n | Iterable<readonly [string, Coercible]>\n | URLSearchParams\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport type Coercible = string | number | bigint | boolean | null | undefined\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface CoercibleRecord {\n readonly [key: string]: Coercible | ReadonlyArray<Coercible> | CoercibleRecord\n}\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const fromInput = (input: Input): UrlParams => {\n const parsed = fromInputNested(input)\n const out: Array<[string, string]> = []\n for (let i = 0; i < parsed.length; i++) {\n if (Array.isArray(parsed[i][0])) {\n const [keys, value] = parsed[i] as [Array<string>, string]\n out.push([`${keys[0]}[${keys.slice(1).join(\"][\")}]`, value])\n } else {\n out.push(parsed[i] as [string, string])\n }\n }\n return out\n}\n\nconst fromInputNested = (input: Input): Array<[string | Array<string>, any]> => {\n const entries = Symbol.iterator in input ? Arr.fromIterable(input) : Object.entries(input)\n const out: Array<[string | Array<string>, string]> = []\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 as CoercibleRecord)\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/**\n * @since 1.0.0\n * @category schemas\n */\nexport const schemaFromSelf: Schema.Schema<UrlParams> = Schema.Array(\n Schema.Tuple(Schema.String, Schema.String)\n).annotations({ identifier: \"UrlParams\" })\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const empty: UrlParams = []\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const getAll: {\n /**\n * @since 1.0.0\n * @category combinators\n */\n (key: string): (self: UrlParams) => ReadonlyArray<string>\n /**\n * @since 1.0.0\n * @category combinators\n */\n (self: UrlParams, key: string): ReadonlyArray<string>\n} = dual(\n 2,\n (self: UrlParams, key: string): ReadonlyArray<string> =>\n Arr.reduce(self, [] as Array<string>, (acc, [k, value]) => {\n if (k === key) {\n acc.push(value)\n }\n return acc\n })\n)\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const getFirst: {\n /**\n * @since 1.0.0\n * @category combinators\n */\n (key: string): (self: UrlParams) => Option.Option<string>\n /**\n * @since 1.0.0\n * @category combinators\n */\n (self: UrlParams, key: string): Option.Option<string>\n} = dual(2, (self: UrlParams, key: string): Option.Option<string> =>\n Option.map(\n Arr.findFirst(self, ([k]) => k === key),\n ([, value]) => value\n ))\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const getLast: {\n /**\n * @since 1.0.0\n * @category combinators\n */\n (key: string): (self: UrlParams) => Option.Option<string>\n /**\n * @since 1.0.0\n * @category combinators\n */\n (self: UrlParams, key: string): Option.Option<string>\n} = dual(2, (self: UrlParams, key: string): Option.Option<string> =>\n Option.map(\n Arr.findLast(self, ([k]) => k === key),\n ([, value]) => value\n ))\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const set: {\n /**\n * @since 1.0.0\n * @category combinators\n */\n (key: string, value: Coercible): (self: UrlParams) => UrlParams\n /**\n * @since 1.0.0\n * @category combinators\n */\n (self: UrlParams, key: string, value: Coercible): UrlParams\n} = dual(3, (self: UrlParams, key: string, value: Coercible): UrlParams =>\n Arr.append(\n Arr.filter(self, ([k]) => k !== key),\n [key, String(value)]\n ))\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const setAll: {\n /**\n * @since 1.0.0\n * @category combinators\n */\n (input: Input): (self: UrlParams) => UrlParams\n /**\n * @since 1.0.0\n * @category combinators\n */\n (self: UrlParams, input: Input): UrlParams\n} = dual(2, (self: UrlParams, input: Input): UrlParams => {\n const out = fromInput(input) as Array<readonly [string, string]>\n const keys = new Set()\n for (let i = 0; i < out.length; i++) {\n keys.add(out[i][0])\n }\n for (let i = 0; i < self.length; i++) {\n if (keys.has(self[i][0])) continue\n out.push(self[i])\n }\n return out\n})\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const append: {\n /**\n * @since 1.0.0\n * @category combinators\n */\n (key: string, value: Coercible): (self: UrlParams) => UrlParams\n /**\n * @since 1.0.0\n * @category combinators\n */\n (self: UrlParams, key: string, value: Coercible): UrlParams\n} = dual(3, (self: UrlParams, key: string, value: Coercible): UrlParams =>\n Arr.append(\n self,\n [key, String(value)]\n ))\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const appendAll: {\n /**\n * @since 1.0.0\n * @category combinators\n */\n (input: Input): (self: UrlParams) => UrlParams\n /**\n * @since 1.0.0\n * @category combinators\n */\n (self: UrlParams, input: Input): UrlParams\n} = dual(2, (self: UrlParams, input: Input): UrlParams => Arr.appendAll(self, fromInput(input)))\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const remove: {\n /**\n * @since 1.0.0\n * @category combinators\n */\n (key: string): (self: UrlParams) => UrlParams\n /**\n * @since 1.0.0\n * @category combinators\n */\n (self: UrlParams, key: string): UrlParams\n} = dual(2, (self: UrlParams, key: string): UrlParams => Arr.filter(self, ([k]) => k !== key))\n\n/**\n * @since 1.0.0\n * @category conversions\n */\nexport const makeUrl = (url: string, params: UrlParams, hash: Option.Option<string>): Either.Either<URL, Error> => {\n try {\n const urlInstance = new URL(url, baseUrl())\n for (let i = 0; i < params.length; i++) {\n const [key, value] = params[i]\n if (value !== undefined) {\n urlInstance.searchParams.append(key, value)\n }\n }\n if (hash._tag === \"Some\") {\n urlInstance.hash = hash.value\n }\n return Either.right(urlInstance)\n } catch (e) {\n return Either.left(e as Error)\n }\n}\n\n/**\n * @since 1.0.0\n * @category conversions\n */\nexport const toString = (self: UrlParams): string => new URLSearchParams(self as any).toString()\n\nconst baseUrl = (): string | undefined => {\n if (\n \"location\" in globalThis &&\n globalThis.location !== undefined &&\n globalThis.location.origin !== undefined &&\n globalThis.location.pathname !== undefined\n ) {\n return location.origin + location.pathname\n }\n return undefined\n}\n\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**\n *\n * ```ts\n * import * as assert from \"node:assert\"\n * import { UrlParams } from \"@effect/platform\"\n *\n * const urlParams = UrlParams.fromInput({ a: 1, b: true, c: \"string\", e: [1, 2, 3] })\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 * @since 1.0.0\n * @category conversions\n */\nexport const toRecord = (self: UrlParams): Record<string, string | Arr.NonEmptyArray<string>> => {\n const out: Record<string, string | Arr.NonEmptyArray<string>> = Object.create(null)\n for (const [k, value] of self) {\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/**\n * @since 1.0.0\n * @category schema\n */\nexport const schemaJson = <A, I, R>(schema: Schema.Schema<A, I, R>, options?: ParseOptions | undefined): {\n (\n field: string\n ): (self: UrlParams) => Effect.Effect<A, ParseResult.ParseError, R>\n (\n self: UrlParams,\n field: string\n ): Effect.Effect<A, ParseResult.ParseError, R>\n} => {\n const parse = Schema.decodeUnknown(Schema.parseJson(schema), options)\n return dual<\n (field: string) => (self: UrlParams) => Effect.Effect<A, ParseResult.ParseError, R>,\n (self: UrlParams, field: string) => Effect.Effect<A, ParseResult.ParseError, R>\n >(2, (self, field) => parse(Option.getOrElse(getLast(self, field), () => \"\")))\n}\n\n/**\n * Extract schema from all key-value pairs in the given `UrlParams`.\n *\n * **Example**\n *\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Effect, Schema } from \"effect\"\n * import { UrlParams } from \"@effect/platform\"\n *\n * Effect.gen(function* () {\n * const urlParams = UrlParams.fromInput({ \"a\": [10, \"string\"], \"b\": false })\n * const result = yield* UrlParams.schemaStruct(Schema.Struct({\n * a: Schema.Tuple(Schema.NumberFromString, Schema.String),\n * b: Schema.BooleanFromString\n * }))(urlParams)\n *\n * assert.deepStrictEqual(result, {\n * a: [10, \"string\"],\n * b: false\n * })\n * })\n * ```\n *\n * @since 1.0.0\n * @category schema\n */\nexport const schemaStruct = <A, I extends Record<string, string | ReadonlyArray<string> | undefined>, R>(\n schema: Schema.Schema<A, I, R>,\n options?: ParseOptions | undefined\n) =>\n(self: UrlParams): Effect.Effect<A, ParseResult.ParseError, R> => {\n const parse = Schema.decodeUnknown(schema, options)\n return parse(toRecord(self))\n}\n\n/**\n * @since 1.0.0\n * @category schema\n */\nexport const schemaFromString: Schema.Schema<UrlParams, string> = Schema.transform(\n Schema.String,\n schemaFromSelf,\n {\n decode(fromA) {\n return fromInput(new URLSearchParams(fromA))\n },\n encode(toI) {\n return toString(toI)\n }\n }\n)\n\n/**\n * @since 1.0.0\n * @category schema\n */\nexport const schemaRecord = <A, I extends Record<string, string | ReadonlyArray<string> | undefined>, R>(\n schema: Schema.Schema<A, I, R>\n): Schema.Schema<A, UrlParams, R> =>\n Schema.transform(\n schemaFromSelf,\n schema,\n {\n decode(fromA) {\n return toRecord(fromA) as I\n },\n encode(toI) {\n return fromInput(toI as Input) as UrlParams\n }\n }\n )\n\n/**\n * @since 1.0.0\n * @category schema\n */\nexport const schemaParse = <A, I extends Record<string, string | ReadonlyArray<string> | undefined>, R>(\n schema: Schema.Schema<A, I, R>\n): Schema.Schema<A, string, R> =>\n Schema.compose(\n schemaFromString,\n schemaRecord(schema)\n )\n","/**\n * @since 1.0.0\n */\nimport * as Option from \"effect/Option\"\nimport * as Tracer from \"effect/Tracer\"\nimport * as Headers from \"./Headers.js\"\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface FromHeaders {\n (headers: Headers.Headers): Option.Option<Tracer.ExternalSpan>\n}\n\n/**\n * @since 1.0.0\n * @category encoding\n */\nexport const toHeaders = (span: Tracer.Span): Headers.Headers =>\n Headers.unsafeFromRecord({\n b3: `${span.traceId}-${span.spanId}-${span.sampled ? \"1\" : \"0\"}${\n span.parent._tag === \"Some\" ? `-${span.parent.value.spanId}` : \"\"\n }`,\n traceparent: `00-${span.traceId}-${span.spanId}-${span.sampled ? \"01\" : \"00\"}`\n })\n\n/**\n * @since 1.0.0\n * @category decoding\n */\nexport const fromHeaders = (headers: Headers.Headers): Option.Option<Tracer.ExternalSpan> => {\n let span = w3c(headers)\n if (span._tag === \"Some\") {\n return span\n }\n span = b3(headers)\n if (span._tag === \"Some\") {\n return span\n }\n return xb3(headers)\n}\n\n/**\n * @since 1.0.0\n * @category decoding\n */\nexport const b3: FromHeaders = (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/**\n * @since 1.0.0\n * @category decoding\n */\nexport const xb3: FromHeaders = (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}\n\nconst w3cTraceId = /^[0-9a-f]{32}$/i\nconst w3cSpanId = /^[0-9a-f]{16}$/i\n\n/**\n * @since 1.0.0\n * @category decoding\n */\nexport const w3c: FromHeaders = (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 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 return Option.none()\n }\n }\n}\n","import * as Data from \"effect/Data\"\nimport * as Effect from \"effect/Effect\"\nimport { identity } from \"effect/Function\"\nimport * as Inspectable from \"effect/Inspectable\"\nimport * as Schema from \"effect/Schema\"\nimport type { ParseOptions } from \"effect/SchemaAST\"\nimport * as Stream_ from \"effect/Stream\"\nimport type * as PlatformError from \"../Error.js\"\nimport * as FileSystem from \"../FileSystem.js\"\nimport type * as Body from \"../HttpBody.js\"\nimport * as UrlParams from \"../UrlParams.js\"\n\n/** @internal */\nexport const TypeId: Body.TypeId = Symbol.for(\n \"@effect/platform/HttpBody\"\n) as Body.TypeId\n\n/** @internal */\nexport const ErrorTypeId: Body.ErrorTypeId = Symbol.for(\n \"@effect/platform/HttpBody/HttpBodyError\"\n) as Body.ErrorTypeId\n\nconst bodyError = Data.tagged<Body.HttpBodyError>(\"HttpBodyError\")\n\n/** @internal */\nexport const HttpBodyError = (reason: Body.ErrorReason): Body.HttpBodyError =>\n bodyError({ [ErrorTypeId]: ErrorTypeId, reason })\n\nabstract class BodyBase implements Body.HttpBody.Proto {\n readonly [TypeId]: Body.TypeId\n abstract readonly _tag: string\n constructor() {\n this[TypeId] = TypeId\n }\n abstract toJSON(): unknown\n [Inspectable.NodeInspectSymbol](): unknown {\n return this.toJSON()\n }\n toString(): string {\n return Inspectable.format(this)\n }\n}\n\nclass EmptyImpl extends BodyBase implements Body.Empty {\n readonly _tag = \"Empty\"\n toJSON(): unknown {\n return {\n _id: \"@effect/platform/HttpBody\",\n _tag: \"Empty\"\n }\n }\n}\n\n/** @internal */\nexport const empty: Body.Empty = new EmptyImpl()\n\nclass RawImpl extends BodyBase implements Body.Raw {\n readonly _tag = \"Raw\"\n constructor(\n readonly body: unknown,\n readonly contentType?: string | undefined,\n readonly contentLength?: number | undefined\n ) {\n super()\n }\n toJSON(): unknown {\n return {\n _id: \"@effect/platform/HttpBody\",\n _tag: \"Raw\",\n body: this.body,\n contentType: this.contentType,\n contentLength: this.contentLength\n }\n }\n}\n\n/** @internal */\nexport const raw = (body: unknown, options?: {\n readonly contentType?: string | undefined\n readonly contentLength?: number | undefined\n}): Body.Raw => new RawImpl(body, options?.contentType, options?.contentLength)\n\nclass Uint8ArrayImpl extends BodyBase implements Body.Uint8Array {\n readonly _tag = \"Uint8Array\"\n constructor(\n readonly body: Uint8Array,\n readonly contentType: string\n ) {\n super()\n }\n get contentLength(): number {\n return this.body.length\n }\n toJSON(): unknown {\n const toString = this.contentType.startsWith(\"text/\") || this.contentType.endsWith(\"json\")\n return {\n _id: \"@effect/platform/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/** @internal */\nexport const uint8Array = (body: Uint8Array, contentType?: string): Body.Uint8Array =>\n new Uint8ArrayImpl(body, contentType ?? \"application/octet-stream\")\n\nconst encoder = new TextEncoder()\n\n/** @internal */\nexport const text = (body: string, contentType?: string): Body.Uint8Array =>\n uint8Array(encoder.encode(body), contentType ?? \"text/plain\")\n\n/** @internal */\nexport const unsafeJson = (body: unknown): Body.Uint8Array => text(JSON.stringify(body), \"application/json\")\n\n/** @internal */\nexport const json = (body: unknown): Effect.Effect<Body.Uint8Array, Body.HttpBodyError> =>\n Effect.try({\n try: () => unsafeJson(body),\n catch: (error) => HttpBodyError({ _tag: \"JsonError\", error })\n })\n\n/** @internal */\nexport const urlParams = (urlParams: UrlParams.UrlParams): Body.Uint8Array =>\n text(UrlParams.toString(urlParams), \"application/x-www-form-urlencoded\")\n\n/** @internal */\nexport const jsonSchema = <A, I, R>(schema: Schema.Schema<A, I, R>, options?: ParseOptions) => {\n const encode = Schema.encode(schema, options)\n return (body: A): Effect.Effect<Body.Uint8Array, Body.HttpBodyError, R> =>\n Effect.flatMap(\n Effect.mapError(encode(body), (error) => HttpBodyError({ _tag: \"SchemaError\", error })),\n json\n )\n}\n\n/** @internal */\nexport const file = (\n path: string,\n options?: FileSystem.StreamOptions & { readonly contentType?: string }\n): Effect.Effect<Body.Stream, PlatformError.PlatformError, FileSystem.FileSystem> =>\n Effect.flatMap(\n FileSystem.FileSystem,\n (fs) =>\n Effect.map(fs.stat(path), (info) =>\n stream(\n fs.stream(path, options),\n options?.contentType,\n Number(info.size)\n ))\n )\n\n/** @internal */\nexport const fileInfo = (\n path: string,\n info: FileSystem.File.Info,\n options?: FileSystem.StreamOptions & { readonly contentType?: string }\n): Effect.Effect<Body.Stream, PlatformError.PlatformError, FileSystem.FileSystem> =>\n Effect.map(\n FileSystem.FileSystem,\n (fs) =>\n stream(\n fs.stream(path, options),\n options?.contentType,\n Number(info.size)\n )\n )\n\n/** @internal */\nexport const fileWeb = (file: Body.HttpBody.FileLike): Body.Stream =>\n stream(Stream_.fromReadableStream(() => file.stream() as ReadableStream<Uint8Array>, identity), file.type, file.size)\n\nclass FormDataImpl extends BodyBase implements Body.FormData {\n readonly _tag = \"FormData\"\n constructor(\n readonly formData: FormData\n ) {\n super()\n }\n toJSON(): unknown {\n return {\n _id: \"@effect/platform/HttpBody\",\n _tag: \"FormData\",\n formData: this.formData\n }\n }\n}\n\n/** @internal */\nexport const formData = (body: FormData): Body.FormData => new FormDataImpl(body)\n\n/** @internal */\nexport const formDataRecord = (\n entries: Body.FormDataInput\n): Body.FormData => {\n const formData = new FormData()\n for (const [key, value] of Object.entries(entries)) {\n if (Array.isArray(value)) {\n for (const item of value) {\n if (item == null) continue\n formData.append(key, typeof value === \"object\" ? item as any : String(item))\n }\n } else if (value != null) {\n formData.append(key, typeof value === \"object\" ? value as any : String(value))\n }\n }\n return new FormDataImpl(formData)\n}\n\nclass StreamImpl extends BodyBase implements Body.Stream {\n readonly _tag = \"Stream\"\n constructor(\n readonly stream: Stream_.Stream<Uint8Array, unknown>,\n readonly contentType: string,\n readonly contentLength?: number | undefined\n ) {\n super()\n }\n toJSON(): unknown {\n return {\n _id: \"@effect/platform/HttpBody\",\n _tag: \"Stream\",\n contentType: this.contentType,\n contentLength: this.contentLength\n }\n }\n}\n\n/** @internal */\nexport const stream = (\n body: Stream_.Stream<Uint8Array, unknown>,\n contentType?: string | undefined,\n contentLength?: number | undefined\n): Body.Stream => new StreamImpl(body, contentType ?? \"application/octet-stream\", contentLength)\n","/**\n * @since 1.0.0\n */\nimport * as Cause from \"effect/Cause\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport * as Fiber from \"effect/Fiber\"\nimport type * as FiberRef from \"effect/FiberRef\"\nimport * as GlobalValue from \"effect/GlobalValue\"\nimport * as Layer from \"effect/Layer\"\nimport * as Option from \"effect/Option\"\nimport * as Runtime from \"effect/Runtime\"\nimport * as Scope from \"effect/Scope\"\nimport * as Stream from \"effect/Stream\"\nimport type * as Types from \"effect/Types\"\nimport { unify } from \"effect/Unify\"\nimport * as HttpBody from \"./HttpBody.js\"\nimport type { HttpMiddleware } from \"./HttpMiddleware.js\"\nimport * as ServerError from \"./HttpServerError.js\"\nimport * as ServerRequest from \"./HttpServerRequest.js\"\nimport * as ServerResponse from \"./HttpServerResponse.js\"\nimport * as internal from \"./internal/httpApp.js\"\nimport * as internalMiddleware from \"./internal/httpMiddleware.js\"\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport type HttpApp<A = ServerResponse.HttpServerResponse, E = never, R = never> = Effect.Effect<\n A,\n E,\n R | ServerRequest.HttpServerRequest\n>\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport type Default<E = never, R = never> = HttpApp<ServerResponse.HttpServerResponse, E, R>\n\nconst handledSymbol = Symbol.for(\"@effect/platform/HttpApp/handled\")\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const toHandled = <E, R, _, EH, RH>(\n self: Default<E, R>,\n handleResponse: (\n request: ServerRequest.HttpServerRequest,\n response: ServerResponse.HttpServerResponse\n ) => Effect.Effect<_, EH, RH>,\n middleware?: HttpMiddleware | undefined\n): Effect.Effect<void, never, Exclude<R | RH | ServerRequest.HttpServerRequest, Scope.Scope>> => {\n const responded = Effect.withFiberRuntime<\n ServerResponse.HttpServerResponse,\n E | EH | ServerError.ResponseError,\n R | RH | ServerRequest.HttpServerRequest\n >((fiber) =>\n Effect.flatMap(self, (response) => {\n const request = Context.unsafeGet(fiber.currentContext, ServerRequest.HttpServerRequest)\n const handler = fiber.getFiberRef(currentPreResponseHandlers)\n if (handler._tag === \"None\") {\n ;(request as any)[handledSymbol] = true\n return Effect.as(handleResponse(request, response), response)\n }\n return Effect.tap(handler.value(request, response), (response) => {\n ;(request as any)[handledSymbol] = true\n return handleResponse(request, response)\n })\n })\n )\n\n const withErrorHandling = Effect.catchAllCause(\n responded,\n (cause) =>\n Effect.withFiberRuntime<\n ServerResponse.HttpServerResponse,\n E | EH | ServerError.ResponseError,\n ServerRequest.HttpServerRequest | RH\n >((fiber) =>\n Effect.flatMap(ServerError.causeResponse(cause), ([response, cause]) => {\n const request = Context.unsafeGet(fiber.currentContext, ServerRequest.HttpServerRequest)\n const handler = fiber.getFiberRef(currentPreResponseHandlers)\n if (handler._tag === \"None\") {\n ;(request as any)[handledSymbol] = true\n return Effect.zipRight(\n handleResponse(request, response),\n Cause.isEmptyType(cause) ? Effect.succeed(response) : Effect.failCause(cause)\n )\n }\n return Effect.zipRight(\n Effect.tap(handler.value(request, response), (response) => {\n ;(request as any)[handledSymbol] = true\n return handleResponse(request, response)\n }),\n Cause.isEmptyType(cause) ? Effect.succeed(response) : Effect.failCause(cause)\n )\n })\n )\n )\n\n const withMiddleware = unify(\n middleware === undefined ?\n internalMiddleware.tracer(withErrorHandling) :\n Effect.matchCauseEffect(internalMiddleware.tracer(middleware(withErrorHandling)), {\n onFailure: (cause): Effect.Effect<void, EH, RH> =>\n Effect.withFiberRuntime((fiber) => {\n const request = Context.unsafeGet(fiber.currentContext, ServerRequest.HttpServerRequest)\n if (handledSymbol in request) {\n return Effect.void\n }\n return Effect.matchCauseEffect(ServerError.causeResponse(cause), {\n onFailure: (_cause) => handleResponse(request, ServerResponse.empty({ status: 500 })),\n onSuccess: ([response]) => handleResponse(request, response)\n })\n }),\n onSuccess: (response): Effect.Effect<void, EH, RH> =>\n Effect.withFiberRuntime((fiber) => {\n const request = Context.unsafeGet(fiber.currentContext, ServerRequest.HttpServerRequest)\n return handledSymbol in request ? Effect.void : handleResponse(request, response)\n })\n })\n )\n\n return Effect.uninterruptible(scoped(withMiddleware)) as any\n}\n\n/**\n * If you want to finalize the http request scope elsewhere, you can use this\n * function to eject from the default scope closure.\n *\n * @since 1.0.0\n * @category Scope\n */\nexport const ejectDefaultScopeClose = (scope: Scope.Scope): void => {\n ejectedScopes.add(scope)\n}\n\n/**\n * @since 1.0.0\n * @category Scope\n */\nexport const unsafeEjectStreamScope = (\n response: ServerResponse.HttpServerResponse\n): ServerResponse.HttpServerResponse => {\n if (response.body._tag !== \"Stream\") {\n return response\n }\n const fiber = Option.getOrThrow(Fiber.getCurrentFiber())\n const scope = Context.unsafeGet(fiber.currentContext, Scope.Scope) as Scope.CloseableScope\n ejectDefaultScopeClose(scope)\n return ServerResponse.setBody(\n response,\n HttpBody.stream(\n Stream.ensuring(response.body.stream, Scope.close(scope, Exit.void)),\n response.body.contentType,\n response.body.contentLength\n )\n )\n}\n\nconst ejectedScopes = GlobalValue.globalValue(\n \"@effect/platform/HttpApp/ejectedScopes\",\n () => new WeakSet<Scope.Scope>()\n)\n\nconst scoped = <A, E, R>(effect: Effect.Effect<A, E, R>) =>\n Effect.flatMap(Scope.make(), (scope) =>\n Effect.onExit(Scope.extend(effect, scope), (exit) => {\n if (ejectedScopes.has(scope)) {\n return Effect.void\n }\n return Scope.close(scope, exit)\n }))\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport type PreResponseHandler = (\n request: ServerRequest.HttpServerRequest,\n response: ServerResponse.HttpServerResponse\n) => Effect.Effect<ServerResponse.HttpServerResponse, ServerError.ResponseError>\n\n/**\n * @since 1.0.0\n * @category fiber refs\n */\nexport const currentPreResponseHandlers: FiberRef.FiberRef<Option.Option<PreResponseHandler>> =\n internal.currentPreResponseHandlers\n\n/**\n * @since 1.0.0\n * @category fiber refs\n */\nexport const appendPreResponseHandler: (handler: PreResponseHandler) => Effect.Effect<void> =\n internal.appendPreResponseHandler\n\n/**\n * @since 1.0.0\n * @category fiber refs\n */\nexport const withPreResponseHandler = internal.withPreResponseHandler\n\n/**\n * @since 1.0.0\n * @category conversions\n */\nexport const toWebHandlerRuntime = <R>(runtime: Runtime.Runtime<R>) => {\n const httpRuntime: Types.Mutable<Runtime.Runtime<R>> = Runtime.make(runtime)\n const run = Runtime.runFork(httpRuntime)\n return <E>(self: Default<E, R | Scope.Scope>, middleware?: HttpMiddleware | undefined) => {\n const resolveSymbol = Symbol.for(\"@effect/platform/HttpApp/resolve\")\n const httpApp = toHandled(self, (request, response) => {\n response = unsafeEjectStreamScope(response)\n ;(request as any)[resolveSymbol](\n ServerResponse.toWeb(response, { withoutBody: request.method === \"HEAD\", runtime })\n )\n return Effect.void\n }, middleware)\n return (request: Request, context?: Context.Context<never> | undefined): Promise<Response> =>\n new Promise((resolve) => {\n const contextMap = new Map<string, any>(runtime.context.unsafeMap)\n if (Context.isContext(context)) {\n for (const [key, value] of context.unsafeMap) {\n contextMap.set(key, value)\n }\n }\n const httpServerRequest = ServerRequest.fromWeb(request)\n contextMap.set(ServerRequest.HttpServerRequest.key, httpServerRequest)\n ;(httpServerRequest as any)[resolveSymbol] = resolve\n httpRuntime.context = Context.unsafeMake(contextMap)\n const fiber = run(httpApp as any)\n request.signal?.addEventListener(\"abort\", () => {\n fiber.unsafeInterruptAsFork(ServerError.clientAbortFiberId)\n }, { once: true })\n })\n }\n}\n\n/**\n * @since 1.0.0\n * @category conversions\n */\nexport const toWebHandler: <E>(\n self: Default<E, Scope.Scope>,\n middleware?: HttpMiddleware | undefined\n) => (request: Request, context?: Context.Context<never> | undefined) => Promise<Response> = toWebHandlerRuntime(\n Runtime.defaultRuntime\n)\n\n/**\n * @since 1.0.0\n * @category conversions\n */\nexport const toWebHandlerLayerWith = <E, R, RE, EX>(\n layer: Layer.Layer<R, RE>,\n options: {\n readonly toHandler: (\n runtime: Runtime.Runtime<R>\n ) => Effect.Effect<\n Effect.Effect<ServerResponse.HttpServerResponse, E, R | Scope.Scope | ServerRequest.HttpServerRequest>,\n EX\n >\n readonly middleware?: HttpMiddleware | undefined\n readonly memoMap?: Layer.MemoMap | undefined\n }\n): {\n readonly dispose: () => Promise<void>\n readonly handler: (request: Request, context?: Context.Context<never> | undefined) => Promise<Response>\n} => {\n const scope = Effect.runSync(Scope.make())\n const dispose = () => Effect.runPromise(Scope.close(scope, Exit.void))\n\n let handlerCache: ((request: Request, context?: Context.Context<never> | undefined) => Promise<Response>) | undefined\n let handlerPromise:\n | Promise<(request: Request, context?: Context.Context<never> | undefined) => Promise<Response>>\n | undefined\n function handler(request: Request, context?: Context.Context<never> | undefined): Promise<Response> {\n if (handlerCache) {\n return handlerCache(request, context)\n }\n handlerPromise ??= Effect.gen(function*() {\n const runtime = yield* (options.memoMap\n ? Layer.toRuntimeWithMemoMap(layer, options.memoMap)\n : Layer.toRuntime(layer))\n return handlerCache = toWebHandlerRuntime(runtime)(\n yield* options.toHandler(runtime),\n options.middleware\n )\n }).pipe(\n Scope.extend(scope),\n Effect.runPromise\n )\n return handlerPromise.then((f) => f(request, context))\n }\n return { dispose, handler } as const\n}\n\n/**\n * @since 1.0.0\n * @category conversions\n */\nexport const toWebHandlerLayer = <E, R, RE>(\n self: Default<E, R | Scope.Scope>,\n layer: Layer.Layer<R, RE>,\n options?: {\n readonly memoMap?: Layer.MemoMap | undefined\n readonly middleware?: HttpMiddleware | undefined\n }\n): {\n readonly dispose: () => Promise<void>\n readonly handler: (request: Request, context?: Context.Context<never> | undefined) => Promise<Response>\n} =>\n toWebHandlerLayerWith(layer, {\n ...options,\n toHandler: () => Effect.succeed(self)\n })\n\n/**\n * @since 1.0.0\n * @category conversions\n */\nexport const fromWebHandler = (\n handler: (request: Request) => Promise<Response>\n): Default<ServerError.HttpServerError> =>\n Effect.async((resume, signal) => {\n const fiber = Option.getOrThrow(Fiber.getCurrentFiber())\n const request = Context.unsafeGet(fiber.currentContext, ServerRequest.HttpServerRequest)\n const requestResult = ServerRequest.toWebEither(request, {\n signal,\n runtime: Runtime.make({\n context: fiber.currentContext,\n fiberRefs: fiber.getFiberRefs(),\n runtimeFlags: Runtime.defaultRuntimeFlags\n })\n })\n if (requestResult._tag === \"Left\") {\n return resume(Effect.fail(requestResult.left))\n }\n handler(requestResult.right).then(\n (response) => resume(Effect.succeed(ServerResponse.fromWeb(response))),\n (cause) =>\n resume(Effect.fail(\n new ServerError.RequestError({\n cause,\n request,\n reason: \"Transport\",\n description: \"HttpApp.fromWebHandler: Error in handler\"\n })\n ))\n )\n })\n","/**\n * @since 1.0.0\n */\nimport type * as Effect from \"effect/Effect\"\nimport type { Inspectable } from \"effect/Inspectable\"\nimport type * as ParseResult from \"effect/ParseResult\"\nimport * as Predicate from \"effect/Predicate\"\nimport type * as Schema from \"effect/Schema\"\nimport type * as Stream_ from \"effect/Stream\"\nimport type * as PlatformError from \"./Error.js\"\nimport type * as FileSystem from \"./FileSystem.js\"\nimport * as internal from \"./internal/httpBody.js\"\nimport type * as UrlParams from \"./UrlParams.js\"\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const TypeId: unique symbol = internal.TypeId\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isHttpBody = (u: unknown): u is HttpBody => Predicate.hasProperty(u, TypeId)\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport type HttpBody = Empty | Raw | Uint8Array | FormData | Stream\n\n/**\n * @since 1.0.0\n */\nexport declare namespace HttpBody {\n /**\n * @since 1.0.0\n * @category models\n */\n export interface Proto extends Inspectable {\n readonly [TypeId]: TypeId\n readonly _tag: string\n readonly contentType?: string | undefined\n readonly contentLength?: number | undefined\n }\n\n /**\n * @since 1.0.0\n * @category models\n */\n export interface FileLike {\n readonly name: string\n readonly lastModified: number\n readonly size: number\n readonly stream: () => unknown\n readonly type: string\n }\n}\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const ErrorTypeId: unique symbol = internal.ErrorTypeId\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type ErrorTypeId = typeof ErrorTypeId\n\n/**\n * @since 1.0.0\n * @category errors\n */\nexport interface HttpBodyError {\n readonly [ErrorTypeId]: ErrorTypeId\n readonly _tag: \"HttpBodyError\"\n readonly reason: ErrorReason\n}\n\n/**\n * @since 1.0.0\n * @category errors\n */\nexport const HttpBodyError: (reason: ErrorReason) => HttpBodyError = internal.HttpBodyError\n\n/**\n * @since 1.0.0\n * @category errors\n */\nexport type ErrorReason = {\n readonly _tag: \"JsonError\"\n readonly error: unknown\n} | {\n readonly _tag: \"SchemaError\"\n readonly error: ParseResult.ParseError\n}\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Empty extends HttpBody.Proto {\n readonly _tag: \"Empty\"\n}\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const empty: Empty = internal.empty\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Raw extends HttpBody.Proto {\n readonly _tag: \"Raw\"\n readonly body: unknown\n}\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const raw: (\n body: unknown,\n options?: {\n readonly contentType?: string | undefined\n readonly contentLength?: number | undefined\n } | undefined\n) => Raw = internal.raw\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Uint8Array extends HttpBody.Proto {\n readonly _tag: \"Uint8Array\"\n readonly body: globalThis.Uint8Array\n readonly contentType: string\n readonly contentLength: number\n}\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const uint8Array: (body: globalThis.Uint8Array, contentType?: string) => Uint8Array = internal.uint8Array\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const text: (body: string, contentType?: string) => Uint8Array = internal.text\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const unsafeJson: (body: unknown) => Uint8Array = internal.unsafeJson\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const json: (body: unknown) => Effect.Effect<Uint8Array, HttpBodyError> = internal.json\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const jsonSchema: <A, I, R>(\n schema: Schema.Schema<A, I, R>\n) => (body: A) => Effect.Effect<Uint8Array, HttpBodyError, R> = internal.jsonSchema\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const urlParams: (urlParams: UrlParams.UrlParams) => Uint8Array = internal.urlParams\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface FormData extends HttpBody.Proto {\n readonly _tag: \"FormData\"\n readonly formData: globalThis.FormData\n}\n\n/**\n * @since 1.0.0\n * @category FormData\n */\nexport const formData: (body: globalThis.FormData) => FormData = internal.formData\n\n/**\n * @since 1.0.0\n * @category FormData\n */\nexport type FormDataInput = Record<string, FormDataCoercible | ReadonlyArray<FormDataCoercible>>\n\n/**\n * @since 1.0.0\n * @category FormData\n */\nexport type FormDataCoercible = string | number | boolean | File | Blob | null | undefined\n\n/**\n * @since 1.0.0\n * @category FormData\n */\nexport const formDataRecord: (entries: FormDataInput) => FormData = internal.formDataRecord\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Stream extends HttpBody.Proto {\n readonly _tag: \"Stream\"\n readonly stream: Stream_.Stream<globalThis.Uint8Array, unknown>\n readonly contentType: string\n readonly contentLength?: number | undefined\n}\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const stream: (\n body: Stream_.Stream<globalThis.Uint8Array, unknown>,\n contentType?: string,\n contentLength?: number\n) => Stream = internal.stream\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const file: (\n path: string,\n options?: FileSystem.StreamOptions & { readonly contentType?: string }\n) => Effect.Effect<Stream, PlatformError.PlatformError, FileSystem.FileSystem> = internal.file\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const fileInfo: (\n path: string,\n info: FileSystem.File.Info,\n options?: FileSystem.StreamOptions & { readonly contentType?: string }\n) => Effect.Effect<Stream, PlatformError.PlatformError, FileSystem.FileSystem> = internal.fileInfo\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const fileWeb: (file: HttpBody.FileLike) => Stream = internal.fileWeb\n","/**\n * @since 1.0.0\n */\nimport * as Cause from \"effect/Cause\"\nimport * as Effect from \"effect/Effect\"\nimport * as ParseResult from \"effect/ParseResult\"\nimport { hasProperty } from \"effect/Predicate\"\nimport type { HttpServerResponse } from \"./HttpServerResponse.js\"\nimport * as ServerResponse from \"./HttpServerResponse.js\"\n\n/**\n * @since 1.0.0\n * @category symbols\n */\nexport const symbol: unique symbol = Symbol.for(\"@effect/platform/HttpServerRespondable\")\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Respondable {\n readonly [symbol]: () => Effect.Effect<HttpServerResponse, unknown>\n}\n\n/**\n * @since 1.0.0\n * @category guards\n */\nexport const isRespondable = (u: unknown): u is Respondable => hasProperty(u, symbol)\n\nconst badRequest = ServerResponse.empty({ status: 400 })\nconst notFound = ServerResponse.empty({ status: 404 })\n\n/**\n * @since 1.0.0\n * @category accessors\n */\nexport const toResponse = (self: Respondable): Effect.Effect<HttpServerResponse> => {\n if (ServerResponse.isServerResponse(self)) {\n return Effect.succeed(self)\n }\n return Effect.orDie(self[symbol]())\n}\n\n/**\n * @since 1.0.0\n * @category accessors\n */\nexport const toResponseOrElse = (u: unknown, orElse: HttpServerResponse): Effect.Effect<HttpServerResponse> => {\n if (ServerResponse.isServerResponse(u)) {\n return Effect.succeed(u)\n } else if (isRespondable(u)) {\n return Effect.catchAllCause(u[symbol](), () => Effect.succeed(orElse))\n // add support for some commmon types\n } else if (ParseResult.isParseError(u)) {\n return Effect.succeed(badRequest)\n } else if (Cause.isNoSuchElementException(u)) {\n return Effect.succeed(notFound)\n }\n return Effect.succeed(orElse)\n}\n\n/**\n * @since 1.0.0\n * @category accessors\n */\nexport const toResponseOrElseDefect = (u: unknown, orElse: HttpServerResponse): Effect.Effect<HttpServerResponse> => {\n if (ServerResponse.isServerResponse(u)) {\n return Effect.succeed(u)\n } else if (isRespondable(u)) {\n return Effect.catchAllCause(u[symbol](), () => Effect.succeed(orElse))\n }\n return Effect.succeed(orElse)\n}\n","/**\n * @since 1.0.0\n */\nimport type * as Effect from \"effect/Effect\"\nimport type { Inspectable } from \"effect/Inspectable\"\nimport type * as Runtime from \"effect/Runtime\"\nimport type * as Schema from \"effect/Schema\"\nimport type { ParseOptions } from \"effect/SchemaAST\"\nimport * as Stream from \"effect/Stream\"\nimport type { Cookie, CookiesError } from \"./Cookies.js\"\nimport * as Cookies from \"./Cookies.js\"\nimport type * as PlatformError from \"./Error.js\"\nimport type * as FileSystem from \"./FileSystem.js\"\nimport type * as Headers from \"./Headers.js\"\nimport * as Body from \"./HttpBody.js\"\nimport type * as Platform from \"./HttpPlatform.js\"\nimport type { Respondable } from \"./HttpServerRespondable.js\"\nimport * as internal from \"./internal/httpServerResponse.js\"\nimport type * as Template from \"./Template.js\"\nimport type * as UrlParams from \"./UrlParams.js\"\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const TypeId: unique symbol = Symbol.for(\"@effect/platform/HttpServerResponse\")\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface HttpServerResponse extends Effect.Effect<HttpServerResponse>, Inspectable, Respondable {\n readonly [TypeId]: TypeId\n readonly status: number\n readonly statusText?: string | undefined\n readonly headers: Headers.Headers\n readonly cookies: Cookies.Cookies\n readonly body: Body.HttpBody\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Options {\n readonly status?: number | undefined\n readonly statusText?: string | undefined\n readonly headers?: Headers.Input | undefined\n readonly cookies?: Cookies.Cookies | undefined\n readonly contentType?: string | undefined\n readonly contentLength?: number | undefined\n}\n\n/**\n * @since 1.0.0\n */\nexport declare namespace Options {\n /**\n * @since 1.0.0\n * @category models\n */\n export interface WithContent extends Omit<Options, \"contentType\" | \"contentLength\"> {}\n\n /**\n * @since 1.0.0\n * @category models\n */\n export interface WithContentType extends Omit<Options, \"contentLength\"> {}\n}\n\n/**\n * @since 1.0.0\n */\nexport const isServerResponse: (u: unknown) => u is HttpServerResponse = internal.isServerResponse\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const empty: (options?: Options.WithContent | undefined) => HttpServerResponse = internal.empty\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const redirect: (location: string | URL, options?: Options.WithContentType | undefined) => HttpServerResponse =\n internal.redirect\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const uint8Array: (body: Uint8Array, options?: Options.WithContentType | undefined) => HttpServerResponse =\n internal.uint8Array\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const text: (body: string, options?: Options.WithContentType | undefined) => HttpServerResponse = internal.text\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const html: {\n /**\n * @since 1.0.0\n * @category constructors\n */\n <A extends ReadonlyArray<Template.Interpolated>>(strings: TemplateStringsArray, ...args: A): Effect.Effect<HttpServerResponse, Template.Interpolated.Error<A[number]>, Template.Interpolated.Context<A[number]>>\n /**\n * @since 1.0.0\n * @category constructors\n */\n (html: string): HttpServerResponse\n} = internal.html\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const htmlStream: <A extends ReadonlyArray<Template.InterpolatedWithStream>>(\n strings: TemplateStringsArray,\n ...args: A\n) => Effect.Effect<HttpServerResponse, never, Template.Interpolated.Context<A[number]>> = internal.htmlStream\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const json: (\n body: unknown,\n options?: Options.WithContentType | undefined\n) => Effect.Effect<HttpServerResponse, Body.HttpBodyError> = internal.json\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const schemaJson: <A, I, R>(\n schema: Schema.Schema<A, I, R>,\n options?: ParseOptions | undefined\n) => (body: A, options?: Options.WithContent | undefined) => Effect.Effect<HttpServerResponse, Body.HttpBodyError, R> =\n internal.schemaJson\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const unsafeJson: (body: unknown, options?: Options.WithContentType | undefined) => HttpServerResponse =\n internal.unsafeJson\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const urlParams: (body: UrlParams.Input, options?: Options.WithContentType | undefined) => HttpServerResponse =\n internal.urlParams\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const raw: (body: unknown, options?: Options | undefined) => HttpServerResponse = internal.raw\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const formData: (body: FormData, options?: Options.WithContent | undefined) => HttpServerResponse =\n internal.formData\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const stream: <E>(\n body: Stream.Stream<Uint8Array, E, never>,\n options?: Options | undefined\n) => HttpServerResponse = internal.stream\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const file: (\n path: string,\n options?: (Options & FileSystem.StreamOptions) | undefined\n) => Effect.Effect<HttpServerResponse, PlatformError.PlatformError, Platform.HttpPlatform> = internal.file\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const fileWeb: (\n file: Body.HttpBody.FileLike,\n options?: (Options.WithContent & FileSystem.StreamOptions) | undefined\n) => Effect.Effect<HttpServerResponse, never, Platform.HttpPlatform> = internal.fileWeb\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const setHeader: {\n /**\n * @since 1.0.0\n * @category combinators\n */\n (key: string, value: string): (self: HttpServerResponse) => HttpServerResponse\n /**\n * @since 1.0.0\n * @category combinators\n */\n (self: HttpServerResponse, key: string, value: string): HttpServerResponse\n} = internal.setHeader\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const setHeaders: {\n /**\n * @since 1.0.0\n * @category combinators\n */\n (input: Headers.Input): (self: HttpServerResponse) => HttpServerResponse\n /**\n * @since 1.0.0\n * @category combinators\n */\n (self: HttpServerResponse, input: Headers.Input): HttpServerResponse\n} = internal.setHeaders\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const removeCookie: {\n /**\n * @since 1.0.0\n * @category combinators\n */\n (name: string): (self: HttpServerResponse) => HttpServerResponse\n /**\n * @since 1.0.0\n * @category combinators\n */\n (self: HttpServerResponse, name: string): HttpServerResponse\n} = internal.removeCookie\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const expireCookie: {\n /**\n * @since 1.0.0\n * @category combinators\n */\n (name: string, options?: Omit<Cookie[\"options\"], \"expires\" | \"maxAge\">): (self: HttpServerResponse) => HttpServerResponse\n /**\n * @since 1.0.0\n * @category combinators\n */\n (\n self: HttpServerResponse,\n name: string,\n options?: Omit<Cookie[\"options\"], \"expires\" | \"maxAge\">\n ): HttpServerResponse\n} = internal.expireCookie\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const replaceCookies: {\n /**\n * @since 1.0.0\n * @category combinators\n */\n (cookies: Cookies.Cookies): (self: HttpServerResponse) => HttpServerResponse\n /**\n * @since 1.0.0\n * @category combinators\n */\n (self: HttpServerResponse, cookies: Cookies.Cookies): HttpServerResponse\n} = internal.replaceCookies\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const setCookie: {\n /**\n * @since 1.0.0\n * @category combinators\n */\n (name: string, value: string, options?: Cookie[\"options\"]): (\n self: HttpServerResponse\n ) => Effect.Effect<\n HttpServerResponse,\n CookiesError\n >\n /**\n * @since 1.0.0\n * @category combinators\n */\n (\n self: HttpServerResponse,\n name: string,\n value: string,\n options?: Cookie[\"options\"]\n ): Effect.Effect<\n HttpServerResponse,\n CookiesError\n >\n} = internal.setCookie\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const unsafeSetCookie: {\n /**\n * @since 1.0.0\n * @category combinators\n */\n (name: string, value: string, options?: Cookie[\"options\"]): (self: HttpServerResponse) => HttpServerResponse\n /**\n * @since 1.0.0\n * @category combinators\n */\n (\n self: HttpServerResponse,\n name: string,\n value: string,\n options?: Cookie[\"options\"]\n ): HttpServerResponse\n} = internal.unsafeSetCookie\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const updateCookies: {\n /**\n * @since 1.0.0\n * @category combinators\n */\n (f: (cookies: Cookies.Cookies) => Cookies.Cookies): (self: HttpServerResponse) => HttpServerResponse\n /**\n * @since 1.0.0\n * @category combinators\n */\n (self: HttpServerResponse, f: (cookies: Cookies.Cookies) => Cookies.Cookies): HttpServerResponse\n} = internal.updateCookies\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const mergeCookies: {\n /**\n * @since 1.0.0\n * @category combinators\n */\n (cookies: Cookies.Cookies): (self: HttpServerResponse) => HttpServerResponse\n /**\n * @since 1.0.0\n * @category combinators\n */\n (self: HttpServerResponse, cookies: Cookies.Cookies): HttpServerResponse\n} = internal.mergeCookies\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const setCookies: {\n /**\n * @since 1.0.0\n * @category combinators\n */\n (\n cookies: Iterable<\n readonly [\n name: string,\n value: string,\n options?: Cookie[\"options\"]\n ]\n >\n ): (self: HttpServerResponse) => Effect.Effect<HttpServerResponse, CookiesError, never>\n /**\n * @since 1.0.0\n * @category combinators\n */\n (\n self: HttpServerResponse,\n cookies: Iterable<\n readonly [\n name: string,\n value: string,\n options?: Cookie[\"options\"]\n ]\n >\n ): Effect.Effect<HttpServerResponse, CookiesError, never>\n} = internal.setCookies\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const unsafeSetCookies: {\n /**\n * @since 1.0.0\n * @category combinators\n */\n (\n cookies: Iterable<\n readonly [\n name: string,\n value: string,\n options?: Cookie[\"options\"]\n ]\n >\n ): (self: HttpServerResponse) => HttpServerResponse\n /**\n * @since 1.0.0\n * @category combinators\n */\n (\n self: HttpServerResponse,\n cookies: Iterable<\n readonly [\n name: string,\n value: string,\n options?: Cookie[\"options\"]\n ]\n >\n ): HttpServerResponse\n} = internal.unsafeSetCookies\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const setBody: {\n /**\n * @since 1.0.0\n * @category combinators\n */\n (body: Body.HttpBody): (self: HttpServerResponse) => HttpServerResponse\n /**\n * @since 1.0.0\n * @category combinators\n */\n (self: HttpServerResponse, body: Body.HttpBody): HttpServerResponse\n} = internal.setBody\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const setStatus: {\n /**\n * @since 1.0.0\n * @category combinators\n */\n (status: number, statusText?: string | undefined): (self: HttpServerResponse) => HttpServerResponse\n /**\n * @since 1.0.0\n * @category combinators\n */\n (self: HttpServerResponse, status: number, statusText?: string | undefined): HttpServerResponse\n} = internal.setStatus\n\n/**\n * @since 1.0.0\n * @category conversions\n */\nexport const toWeb: (\n response: HttpServerResponse,\n options?: {\n readonly withoutBody?: boolean | undefined\n readonly runtime?: Runtime.Runtime<never> | undefined\n }\n) => Response = internal.toWeb\n\n/**\n * @since 1.0.0\n * @category conversions\n */\nexport const fromWeb = (response: Response): HttpServerResponse => {\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 as any,\n cookies: Cookies.fromSetCookie(setCookieHeaders)\n })\n if (response.body) {\n const contentType = headers.get(\"content-type\")\n self = setBody(\n self,\n Body.stream(\n Stream.fromReadableStream({\n evaluate: () => response.body!,\n onError: (e) => e\n }),\n contentType ?? undefined\n )\n )\n }\n return self\n}\n","import * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Effectable from \"effect/Effectable\"\nimport { dual } from \"effect/Function\"\nimport * as Inspectable from \"effect/Inspectable\"\nimport * as Runtime from \"effect/Runtime\"\nimport type * as Schema from \"effect/Schema\"\nimport type { ParseOptions } from \"effect/SchemaAST\"\nimport * as Stream from \"effect/Stream\"\nimport * as Cookies from \"../Cookies.js\"\nimport type * as PlatformError from \"../Error.js\"\nimport type * as FileSystem from \"../FileSystem.js\"\nimport * as Headers from \"../Headers.js\"\nimport type * as Body from \"../HttpBody.js\"\nimport type * as Platform from \"../HttpPlatform.js\"\nimport type * as Respondable from \"../HttpServerRespondable.js\"\nimport type * as ServerResponse from \"../HttpServerResponse.js\"\nimport * as Template from \"../Template.js\"\nimport * as UrlParams from \"../UrlParams.js\"\nimport * as internalBody from \"./httpBody.js\"\n\n/** @internal */\nexport const TypeId: ServerResponse.TypeId = Symbol.for(\"@effect/platform/HttpServerResponse\") as ServerResponse.TypeId\n\nconst respondableSymbol: typeof Respondable.symbol = Symbol.for(\n \"@effect/platform/HttpServerRespondable\"\n) as typeof Respondable.symbol\n\nclass ServerResponseImpl extends Effectable.StructuralClass<ServerResponse.HttpServerResponse>\n implements ServerResponse.HttpServerResponse\n{\n readonly [TypeId]: ServerResponse.TypeId\n readonly headers: Headers.Headers\n constructor(\n readonly status: number,\n readonly statusText: string | undefined,\n headers: Headers.Headers,\n readonly cookies: Cookies.Cookies,\n readonly body: Body.HttpBody\n ) {\n super()\n this[TypeId] = TypeId\n if (body.contentType || body.contentLength) {\n const newHeaders = { ...headers }\n if (body.contentType) {\n newHeaders[\"content-type\"] = body.contentType\n }\n if (body.contentLength) {\n newHeaders[\"content-length\"] = body.contentLength.toString()\n }\n this.headers = newHeaders\n } else {\n this.headers = headers\n }\n }\n\n commit(): Effect.Effect<ServerResponse.HttpServerResponse> {\n return Effect.succeed(this)\n }\n\n [respondableSymbol](): Effect.Effect<ServerResponse.HttpServerResponse, unknown> {\n return Effect.succeed(this)\n }\n\n [Inspectable.NodeInspectSymbol]() {\n return this.toJSON()\n }\n\n toString(): string {\n return Inspectable.format(this)\n }\n\n toJSON() {\n return {\n _id: \"@effect/platform/HttpServerResponse\",\n status: this.status,\n statusText: this.statusText,\n headers: Inspectable.redact(this.headers),\n cookies: this.cookies.toJSON(),\n body: this.body.toJSON()\n }\n }\n}\n\n/** @internal */\nexport const isServerResponse = (u: unknown): u is ServerResponse.HttpServerResponse =>\n typeof u === \"object\" && u !== null && TypeId in u\n\n/** @internal */\nexport const empty = (options?: ServerResponse.Options.WithContent | undefined): ServerResponse.HttpServerResponse =>\n new ServerResponseImpl(\n options?.status ?? 204,\n options?.statusText,\n options?.headers ? Headers.fromInput(options.headers) : Headers.empty,\n options?.cookies ?? Cookies.empty,\n internalBody.empty\n )\n\n/** @internal */\nexport const redirect = (\n location: string | URL,\n options?: ServerResponse.Options.WithContentType | undefined\n): ServerResponse.HttpServerResponse => {\n const headers = Headers.unsafeFromRecord({ location: location.toString() })\n return new ServerResponseImpl(\n options?.status ?? 302,\n options?.statusText,\n options?.headers ?\n Headers.merge(\n headers,\n Headers.fromInput(options.headers)\n ) :\n headers,\n options?.cookies ?? Cookies.empty,\n internalBody.empty\n )\n}\n\n/** @internal */\nexport const uint8Array = (\n body: Uint8Array,\n options?: ServerResponse.Options.WithContentType\n): ServerResponse.HttpServerResponse => {\n const headers = options?.headers ? Headers.fromInput(options.headers) : Headers.empty\n return new ServerResponseImpl(\n options?.status ?? 200,\n options?.statusText,\n headers,\n options?.cookies ?? Cookies.empty,\n internalBody.uint8Array(body, getContentType(options, headers))\n )\n}\n\n/** @internal */\nexport const text = (\n body: string,\n options?: ServerResponse.Options.WithContentType\n): ServerResponse.HttpServerResponse => {\n const headers = options?.headers ? Headers.fromInput(options.headers) : Headers.empty\n return new ServerResponseImpl(\n options?.status ?? 200,\n options?.statusText,\n headers,\n options?.cookies ?? Cookies.empty,\n internalBody.text(body, getContentType(options, headers))\n )\n}\n\n/** @internal */\nexport const html: {\n <A extends ReadonlyArray<Template.Interpolated>>(\n strings: TemplateStringsArray,\n ...args: A\n ): Effect.Effect<\n ServerResponse.HttpServerResponse,\n Template.Interpolated.Error<A[number]>,\n Template.Interpolated.Context<A[number]>\n >\n (html: string): ServerResponse.HttpServerResponse\n} = (\n strings: TemplateStringsArray | string,\n ...args: ReadonlyArray<Template.Interpolated>\n) => {\n if (typeof strings === \"string\") {\n return text(strings, { contentType: \"text/html\" })\n }\n\n return Effect.map(\n Template.make(strings, ...args),\n (_) => text(_, { contentType: \"text/html\" })\n ) as any\n}\n\n/** @internal */\nexport const htmlStream = <A extends ReadonlyArray<Template.InterpolatedWithStream>>(\n strings: TemplateStringsArray,\n ...args: A\n): Effect.Effect<\n ServerResponse.HttpServerResponse,\n never,\n Template.Interpolated.Context<A[number]>\n> =>\n Effect.map(\n Effect.context<any>(),\n (context) =>\n stream(\n Stream.provideContext(\n Stream.encodeText(Template.stream(strings, ...args)),\n context\n ),\n { contentType: \"text/html\" }\n )\n )\n\n/** @internal */\nexport const json = (\n body: unknown,\n options?: ServerResponse.Options.WithContent | undefined\n): Effect.Effect<ServerResponse.HttpServerResponse, Body.HttpBodyError> =>\n Effect.map(internalBody.json(body), (body) =>\n new ServerResponseImpl(\n options?.status ?? 200,\n options?.statusText,\n options?.headers ? Headers.fromInput(options.headers) : Headers.empty,\n options?.cookies ?? Cookies.empty,\n body\n ))\n\n/** @internal */\nexport const unsafeJson = (\n body: unknown,\n options?: ServerResponse.Options.WithContent | undefined\n): ServerResponse.HttpServerResponse =>\n new ServerResponseImpl(\n options?.status ?? 200,\n options?.statusText,\n options?.headers ? Headers.fromInput(options.headers) : Headers.empty,\n options?.cookies ?? Cookies.empty,\n internalBody.unsafeJson(body)\n )\n\n/** @internal */\nexport const schemaJson = <A, I, R>(\n schema: Schema.Schema<A, I, R>,\n options?: ParseOptions | undefined\n) => {\n const encode = internalBody.jsonSchema(schema, options)\n return (\n body: A,\n options?: ServerResponse.Options.WithContent | undefined\n ): Effect.Effect<ServerResponse.HttpServerResponse, Body.HttpBodyError, R> =>\n Effect.map(encode(body), (body) =>\n new ServerResponseImpl(\n options?.status ?? 200,\n options?.statusText,\n options?.headers ? Headers.fromInput(options.headers) : Headers.empty,\n options?.cookies ?? Cookies.empty,\n body\n ))\n}\n\nconst httpPlatform = Context.GenericTag<Platform.HttpPlatform>(\"@effect/platform/HttpPlatform\")\n\n/** @internal */\nexport const file = (\n path: string,\n options?: (ServerResponse.Options & FileSystem.StreamOptions) | undefined\n): Effect.Effect<ServerResponse.HttpServerResponse, PlatformError.PlatformError, Platform.HttpPlatform> =>\n Effect.flatMap(\n httpPlatform,\n (platform) => platform.fileResponse(path, options)\n )\n\n/** @internal */\nexport const fileWeb = (\n file: Body.HttpBody.FileLike,\n options?: (ServerResponse.Options.WithContent & FileSystem.StreamOptions) | undefined\n): Effect.Effect<ServerResponse.HttpServerResponse, never, Platform.HttpPlatform> =>\n Effect.flatMap(\n httpPlatform,\n (platform) => platform.fileWebResponse(file, options)\n )\n\n/** @internal */\nexport const urlParams = (\n body: UrlParams.Input,\n options?: ServerResponse.Options.WithContent | undefined\n): ServerResponse.HttpServerResponse =>\n new ServerResponseImpl(\n options?.status ?? 200,\n options?.statusText,\n options?.headers ? Headers.fromInput(options.headers) : Headers.empty,\n options?.cookies ?? Cookies.empty,\n internalBody.text(UrlParams.toString(UrlParams.fromInput(body)), \"application/x-www-form-urlencoded\")\n )\n\n/** @internal */\nexport const raw = (body: unknown, options?: ServerResponse.Options | undefined): ServerResponse.HttpServerResponse =>\n new ServerResponseImpl(\n options?.status ?? 200,\n options?.statusText,\n options?.headers ? Headers.fromInput(options.headers) : Headers.empty,\n options?.cookies ?? Cookies.empty,\n internalBody.raw(body, {\n contentType: options?.contentType,\n contentLength: options?.contentLength\n })\n )\n\n/** @internal */\nexport const formData = (\n body: FormData,\n options?: ServerResponse.Options.WithContent | undefined\n): ServerResponse.HttpServerResponse =>\n new ServerResponseImpl(\n options?.status ?? 200,\n options?.statusText,\n options?.headers ? Headers.fromInput(options.headers) : Headers.empty,\n options?.cookies ?? Cookies.empty,\n internalBody.formData(body)\n )\n\n/** @internal */\nexport const stream = <E>(\n body: Stream.Stream<Uint8Array, E>,\n options?: ServerResponse.Options | undefined\n): ServerResponse.HttpServerResponse => {\n const headers = options?.headers ? Headers.fromInput(options.headers) : Headers.empty\n return new ServerResponseImpl(\n options?.status ?? 200,\n options?.statusText,\n headers,\n options?.cookies ?? Cookies.empty,\n internalBody.stream(body, getContentType(options, headers), options?.contentLength)\n )\n}\n\n/** @internal */\nexport const getContentType = (\n options: ServerResponse.Options | undefined,\n headers: Headers.Headers\n): string | undefined => {\n if (options?.contentType) {\n return options.contentType\n } else if (options?.headers) {\n return headers[\"content-type\"]\n } else {\n return\n }\n}\n\n/** @internal */\nexport const setHeader = dual<\n (key: string, value: string) => (self: ServerResponse.HttpServerResponse) => ServerResponse.HttpServerResponse,\n (self: ServerResponse.HttpServerResponse, key: string, value: string) => ServerResponse.HttpServerResponse\n>(3, (self, key, value) =>\n new ServerResponseImpl(\n self.status,\n self.statusText,\n Headers.set(self.headers, key, value),\n self.cookies,\n self.body\n ))\n\n/** @internal */\nexport const replaceCookies = dual<\n (cookies: Cookies.Cookies) => (self: ServerResponse.HttpServerResponse) => ServerResponse.HttpServerResponse,\n (self: ServerResponse.HttpServerResponse, cookies: Cookies.Cookies) => ServerResponse.HttpServerResponse\n>(2, (self, cookies) =>\n new ServerResponseImpl(\n self.status,\n self.statusText,\n self.headers,\n cookies,\n self.body\n ))\n\n/** @internal */\nexport const setCookie = dual<\n (\n name: string,\n value: string,\n options?: Cookies.Cookie[\"options\"]\n ) => (\n self: ServerResponse.HttpServerResponse\n ) => Effect.Effect<ServerResponse.HttpServerResponse, Cookies.CookiesError>,\n (\n self: ServerResponse.HttpServerResponse,\n name: string,\n value: string,\n options?: Cookies.Cookie[\"options\"]\n ) => Effect.Effect<ServerResponse.HttpServerResponse, Cookies.CookiesError>\n>(\n (args) => isServerResponse(args[0]),\n (self, name, value, options) =>\n Effect.map(Cookies.set(self.cookies, name, value, options), (cookies) =>\n new ServerResponseImpl(\n self.status,\n self.statusText,\n self.headers,\n cookies,\n self.body\n ))\n)\n\n/** @internal */\nexport const unsafeSetCookie = dual<\n (\n name: string,\n value: string,\n options?: Cookies.Cookie[\"options\"]\n ) => (self: ServerResponse.HttpServerResponse) => ServerResponse.HttpServerResponse,\n (\n self: ServerResponse.HttpServerResponse,\n name: string,\n value: string,\n options?: Cookies.Cookie[\"options\"]\n ) => ServerResponse.HttpServerResponse\n>(\n (args) => isServerResponse(args[0]),\n (self, name, value, options) =>\n new ServerResponseImpl(\n self.status,\n self.statusText,\n self.headers,\n Cookies.unsafeSet(self.cookies, name, value, options),\n self.body\n )\n)\n\n/** @internal */\nexport const updateCookies = dual<\n (\n f: (cookies: Cookies.Cookies) => Cookies.Cookies\n ) => (self: ServerResponse.HttpServerResponse) => ServerResponse.HttpServerResponse,\n (\n self: ServerResponse.HttpServerResponse,\n f: (cookies: Cookies.Cookies) => Cookies.Cookies\n ) => ServerResponse.HttpServerResponse\n>(2, (self, f) =>\n new ServerResponseImpl(\n self.status,\n self.statusText,\n self.headers,\n f(self.cookies),\n self.body\n ))\n\n/** @internal */\nexport const setCookies = dual<\n (\n cookies: Iterable<readonly [name: string, value: string, options?: Cookies.Cookie[\"options\"]]>\n ) => (\n self: ServerResponse.HttpServerResponse\n ) => Effect.Effect<ServerResponse.HttpServerResponse, Cookies.CookiesError>,\n (\n self: ServerResponse.HttpServerResponse,\n cookies: Iterable<readonly [name: string, value: string, options?: Cookies.Cookie[\"options\"]]>\n ) => Effect.Effect<ServerResponse.HttpServerResponse, Cookies.CookiesError>\n>(\n 2,\n (self, cookies) =>\n Effect.map(Cookies.setAll(self.cookies, cookies), (cookies) =>\n new ServerResponseImpl(\n self.status,\n self.statusText,\n self.headers,\n cookies,\n self.body\n ))\n)\n\n/** @internal */\nexport const mergeCookies = dual<\n (\n cookies: Cookies.Cookies\n ) => (\n self: ServerResponse.HttpServerResponse\n ) => ServerResponse.HttpServerResponse,\n (\n self: ServerResponse.HttpServerResponse,\n cookies: Cookies.Cookies\n ) => ServerResponse.HttpServerResponse\n>(\n 2,\n (self, cookies) =>\n new ServerResponseImpl(\n self.status,\n self.statusText,\n self.headers,\n Cookies.merge(self.cookies, cookies),\n self.body\n )\n)\n\n/** @internal */\nexport const unsafeSetCookies = dual<\n (\n cookies: Iterable<readonly [name: string, value: string, options?: Cookies.Cookie[\"options\"]]>\n ) => (self: ServerResponse.HttpServerResponse) => ServerResponse.HttpServerResponse,\n (\n self: ServerResponse.HttpServerResponse,\n cookies: Iterable<readonly [name: string, value: string, options?: Cookies.Cookie[\"options\"]]>\n ) => ServerResponse.HttpServerResponse\n>(\n 2,\n (self, cookies) =>\n new ServerResponseImpl(\n self.status,\n self.statusText,\n self.headers,\n Cookies.unsafeSetAll(self.cookies, cookies),\n self.body\n )\n)\n\n/** @internal */\nexport const removeCookie = dual<\n (\n name: string\n ) => (self: ServerResponse.HttpServerResponse) => ServerResponse.HttpServerResponse,\n (\n self: ServerResponse.HttpServerResponse,\n name: string\n ) => ServerResponse.HttpServerResponse\n>(\n 2,\n (self, name) =>\n new ServerResponseImpl(\n self.status,\n self.statusText,\n self.headers,\n Cookies.remove(self.cookies, name),\n self.body\n )\n)\n\n/** @internal */\nexport const expireCookie = dual<\n (\n name: string,\n options?: Omit<Cookies.Cookie[\"options\"], \"expires\" | \"maxAge\">\n ) => (self: ServerResponse.HttpServerResponse) => ServerResponse.HttpServerResponse,\n (\n self: ServerResponse.HttpServerResponse,\n name: string,\n options?: Omit<Cookies.Cookie[\"options\"], \"expires\" | \"maxAge\">\n ) => ServerResponse.HttpServerResponse\n>(\n 3,\n (self, name, options) =>\n new ServerResponseImpl(\n self.status,\n self.statusText,\n self.headers,\n Cookies.unsafeSet(self.cookies, name, \"\", {\n ...(options ?? {}),\n maxAge: 0\n }),\n self.body\n )\n)\n\n/** @internal */\nexport const setHeaders = dual<\n (input: Headers.Input) => (self: ServerResponse.HttpServerResponse) => ServerResponse.HttpServerResponse,\n (self: ServerResponse.HttpServerResponse, input: Headers.Input) => ServerResponse.HttpServerResponse\n>(2, (self, input) =>\n new ServerResponseImpl(\n self.status,\n self.statusText,\n Headers.setAll(self.headers, input),\n self.cookies,\n self.body\n ))\n\n/** @internal */\nexport const setStatus = dual<\n (\n status: number,\n statusText?: string\n ) => (self: ServerResponse.HttpServerResponse) => ServerResponse.HttpServerResponse,\n (self: ServerResponse.HttpServerResponse, status: number, statusText?: string) => ServerResponse.HttpServerResponse\n>((args) => isServerResponse(args[0]), (self, status, statusText) =>\n new ServerResponseImpl(\n status,\n statusText,\n self.headers,\n self.cookies,\n self.body\n ))\n\n/** @internal */\nexport const setBody = dual<\n (body: Body.HttpBody) => (self: ServerResponse.HttpServerResponse) => ServerResponse.HttpServerResponse,\n (self: ServerResponse.HttpServerResponse, body: Body.HttpBody) => ServerResponse.HttpServerResponse\n>(2, (self, body) => {\n let headers = self.headers\n if (body._tag === \"Empty\") {\n headers = Headers.remove(Headers.remove(headers, \"Content-Type\"), \"Content-length\")\n }\n return new ServerResponseImpl(\n self.status,\n self.statusText,\n headers,\n self.cookies,\n body\n )\n})\n\n/** @internal */\nexport const toWeb = (response: ServerResponse.HttpServerResponse, options?: {\n readonly withoutBody?: boolean | undefined\n readonly runtime?: Runtime.Runtime<never> | undefined\n}): Response => {\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 as string,\n headers\n })\n }\n const body = response.body\n switch (body._tag) {\n case \"Empty\": {\n return new Response(undefined, {\n status: response.status,\n statusText: response.statusText as string,\n headers\n })\n }\n case \"Uint8Array\":\n case \"Raw\": {\n if (body.body instanceof Response) {\n for (const [key, value] of headers as any) {\n body.body.headers.set(key, value)\n }\n return body.body\n }\n return new Response(body.body as any, {\n status: response.status,\n statusText: response.statusText,\n headers\n })\n }\n case \"FormData\": {\n return new Response(body.formData as any, {\n status: response.status,\n statusText: response.statusText,\n headers\n })\n }\n case \"Stream\": {\n return new Response(Stream.toReadableStreamRuntime(body.stream, options?.runtime ?? Runtime.defaultRuntime), {\n status: response.status,\n statusText: response.statusText,\n headers\n })\n }\n }\n}\n","import * as Cause from \"effect/Cause\"\nimport * as Effect from \"effect/Effect\"\nimport type * as Exit from \"effect/Exit\"\nimport * as FiberId from \"effect/FiberId\"\nimport { globalValue } from \"effect/GlobalValue\"\nimport * as Option from \"effect/Option\"\nimport * as Predicate from \"effect/Predicate\"\nimport type * as Error from \"../HttpServerError.js\"\nimport * as Respondable from \"../HttpServerRespondable.js\"\nimport type { HttpServerResponse } from \"../HttpServerResponse.js\"\nimport * as internalServerResponse from \"./httpServerResponse.js\"\n\n/** @internal */\nexport const TypeId: Error.TypeId = Symbol.for(\n \"@effect/platform/HttpServerError\"\n) as Error.TypeId\n\n/** @internal */\nexport const isServerError = (u: unknown): u is Error.HttpServerError => Predicate.hasProperty(u, TypeId)\n\n/** @internal */\nexport const clientAbortFiberId = globalValue(\n \"@effect/platform/HttpServerError/clientAbortFiberId\",\n () => FiberId.runtime(-499, 0)\n)\n\n/** @internal */\nexport const causeResponse = <E>(\n cause: Cause.Cause<E>\n): Effect.Effect<readonly [HttpServerResponse, Cause.Cause<E>]> => {\n const [effect, stripped] = Cause.reduce(\n cause,\n [Effect.succeed(internalServerError), Cause.empty as Cause.Cause<E>] as const,\n (acc, cause) => {\n const withoutInterrupt = Cause.isInterruptType(acc[1]) ? Cause.empty : acc[1]\n switch (cause._tag) {\n case \"Fail\": {\n return Option.some(\n [\n Respondable.toResponseOrElse(cause.error, internalServerError),\n combineCauses(withoutInterrupt, cause)\n ] as const\n )\n }\n case \"Die\": {\n const isResponse = internalServerResponse.isServerResponse(cause.defect)\n return Option.some(\n [\n Respondable.toResponseOrElseDefect(cause.defect, internalServerError),\n isResponse ? withoutInterrupt : combineCauses(withoutInterrupt, cause)\n ] as const\n )\n }\n case \"Interrupt\": {\n if (acc[1]._tag !== \"Empty\") {\n return Option.none()\n }\n const response = cause.fiberId === clientAbortFiberId ? clientAbortError : serverAbortError\n return Option.some([Effect.succeed(response), cause] as const)\n }\n default: {\n return Option.none()\n }\n }\n }\n )\n return Effect.map(effect, (response) => {\n if (Cause.isEmptyType(stripped)) {\n return [response, Cause.empty] as const\n }\n return [response, Cause.sequential(stripped, Cause.die(response))] as const\n })\n}\n\nconst combineCauses = <A = never, B = never>(left: Cause.Cause<A>, right: Cause.Cause<B>): Cause.Cause<A | B> => {\n if (Cause.isEmptyType(left)) {\n return right\n } else if (Cause.isEmptyType(right)) {\n return left\n }\n return Cause.sequential(left, right)\n}\n\n/** @internal */\nexport const causeResponseStripped = <E>(\n cause: Cause.Cause<E>\n): readonly [response: HttpServerResponse, cause: Option.Option<Cause.Cause<E>>] => {\n let response: HttpServerResponse | undefined\n const stripped = Cause.stripSomeDefects(cause, (defect) => {\n if (internalServerResponse.isServerResponse(defect)) {\n response = defect\n return Option.some(Cause.empty)\n }\n return Option.none()\n })\n return [response ?? internalServerError, stripped]\n}\n\nconst internalServerError = internalServerResponse.empty({ status: 500 })\nconst clientAbortError = internalServerResponse.empty({ status: 499 })\nconst serverAbortError = internalServerResponse.empty({ status: 503 })\n\n/** @internal */\nexport const exitResponse = <E>(exit: Exit.Exit<HttpServerResponse, E>): HttpServerResponse => {\n if (exit._tag === \"Success\") {\n return exit.value\n }\n return causeResponseStripped(exit.cause)[0]\n}\n","/**\n * @since 1.0.0\n */\nimport type * as Cause from \"effect/Cause\"\nimport type * as Effect from \"effect/Effect\"\nimport type * as Exit from \"effect/Exit\"\nimport type * as FiberId from \"effect/FiberId\"\nimport type * as Option from \"effect/Option\"\nimport { TypeIdError } from \"./Error.js\"\nimport type * as ServerRequest from \"./HttpServerRequest.js\"\nimport * as Respondable from \"./HttpServerRespondable.js\"\nimport * as ServerResponse from \"./HttpServerResponse.js\"\nimport * as internal from \"./internal/httpServerError.js\"\n\n/**\n * @since 1.0.0\n * @category type id\n */\nexport const TypeId: unique symbol = internal.TypeId\n\n/**\n * @since 1.0.0\n * @category type id\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 1.0.0\n * @category error\n */\nexport type HttpServerError = RequestError | ResponseError | RouteNotFound | ServeError\n\n/**\n * @since 1.0.0\n * @category error\n */\nexport class RequestError extends TypeIdError(TypeId, \"RequestError\")<{\n readonly request: ServerRequest.HttpServerRequest\n readonly reason: \"Transport\" | \"Decode\"\n readonly cause?: unknown\n readonly description?: string\n}> implements Respondable.Respondable {\n /**\n * @since 1.0.0\n */\n [Respondable.symbol]() {\n return ServerResponse.empty({ status: 400 })\n }\n\n get methodAndUrl() {\n return `${this.request.method} ${this.request.url}`\n }\n\n get message() {\n return this.description ?\n `${this.reason}: ${this.description} (${this.methodAndUrl})` :\n `${this.reason} error (${this.methodAndUrl})`\n }\n}\n\n/**\n * @since 1.0.0\n * @category predicates\n */\nexport const isServerError: (u: unknown) => u is HttpServerError = internal.isServerError\n\n/**\n * @since 1.0.0\n * @category error\n */\nexport class RouteNotFound extends TypeIdError(TypeId, \"RouteNotFound\")<{\n readonly request: ServerRequest.HttpServerRequest\n}> {\n constructor(options: { request: ServerRequest.HttpServerRequest }) {\n super(options)\n ;(this as any).stack = `${this.name}: ${this.message}`\n }\n /**\n * @since 1.0.0\n */\n [Respondable.symbol]() {\n return ServerResponse.empty({ status: 404 })\n }\n get message() {\n return `${this.request.method} ${this.request.url} not found`\n }\n}\n\n/**\n * @since 1.0.0\n * @category error\n */\nexport class ResponseError extends TypeIdError(TypeId, \"ResponseError\")<{\n readonly request: ServerRequest.HttpServerRequest\n readonly response: ServerResponse.HttpServerResponse\n readonly reason: \"Decode\"\n readonly cause?: unknown\n readonly description?: string\n}> {\n /**\n * @since 1.0.0\n */\n [Respondable.symbol]() {\n return ServerResponse.empty({ status: 500 })\n }\n\n get methodAndUrl() {\n return `${this.request.method} ${this.request.url}`\n }\n\n get message() {\n const info = `${this.response.status} ${this.methodAndUrl}`\n return this.description ?\n `${this.description} (${info})` :\n `${this.reason} error (${info})`\n }\n}\n\n/**\n * @since 1.0.0\n * @category error\n */\nexport class ServeError extends TypeIdError(TypeId, \"ServeError\")<{\n readonly cause: unknown\n}> {}\n\n/**\n * @since 1.0.0\n */\nexport const clientAbortFiberId: FiberId.FiberId = internal.clientAbortFiberId\n\n/**\n * @since 1.0.0\n */\nexport const causeResponse: <E>(\n cause: Cause.Cause<E>\n) => Effect.Effect<readonly [ServerResponse.HttpServerResponse, Cause.Cause<E>]> = internal.causeResponse\n\n/**\n * @since 1.0.0\n */\nexport const causeResponseStripped: <E>(\n cause: Cause.Cause<E>\n) => readonly [response: ServerResponse.HttpServerResponse, cause: Option.Option<Cause.Cause<E>>] =\n internal.causeResponseStripped\n\n/**\n * @since 1.0.0\n */\nexport const exitResponse: <E>(\n exit: Exit.Exit<ServerResponse.HttpServerResponse, E>\n) => ServerResponse.HttpServerResponse = internal.exitResponse\n","/**\n * @since 1.0.0\n */\nimport type { Channel } from \"effect/Channel\"\nimport type { Chunk } from \"effect/Chunk\"\nimport type * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Either from \"effect/Either\"\nimport * as Option from \"effect/Option\"\nimport type * as ParseResult from \"effect/ParseResult\"\nimport type { ReadonlyRecord } from \"effect/Record\"\nimport * as Runtime from \"effect/Runtime\"\nimport type * as Schema from \"effect/Schema\"\nimport type { ParseOptions } from \"effect/SchemaAST\"\nimport type * as Scope from \"effect/Scope\"\nimport * as Stream from \"effect/Stream\"\nimport type * as FileSystem from \"./FileSystem.js\"\nimport type * as Headers from \"./Headers.js\"\nimport type * as IncomingMessage from \"./HttpIncomingMessage.js\"\nimport { hasBody, type HttpMethod } from \"./HttpMethod.js\"\nimport * as Error from \"./HttpServerError.js\"\nimport * as internal from \"./internal/httpServerRequest.js\"\nimport type * as Multipart from \"./Multipart.js\"\nimport type * as Path from \"./Path.js\"\nimport type * as Socket from \"./Socket.js\"\n\nexport {\n /**\n * @since 1.0.0\n * @category fiber refs\n */\n MaxBodySize,\n /**\n * @since 1.0.0\n * @category fiber refs\n */\n withMaxBodySize\n} from \"./HttpIncomingMessage.js\"\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const TypeId: unique symbol = internal.TypeId\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface HttpServerRequest extends IncomingMessage.HttpIncomingMessage<Error.RequestError> {\n readonly [TypeId]: TypeId\n readonly source: unknown\n readonly url: string\n readonly originalUrl: string\n readonly method: HttpMethod\n readonly cookies: ReadonlyRecord<string, string>\n\n readonly multipart: Effect.Effect<\n Multipart.Persisted,\n Multipart.MultipartError,\n Scope.Scope | FileSystem.FileSystem | Path.Path\n >\n readonly multipartStream: Stream.Stream<Multipart.Part, Multipart.MultipartError>\n\n readonly upgrade: Effect.Effect<Socket.Socket, Error.RequestError>\n\n readonly modify: (\n options: {\n readonly url?: string\n readonly headers?: Headers.Headers\n readonly remoteAddress?: string\n }\n ) => HttpServerRequest\n}\n\n/**\n * @since 1.0.0\n * @category context\n */\nexport const HttpServerRequest: Context.Tag<HttpServerRequest, HttpServerRequest> = internal.serverRequestTag\n\n/**\n * @since 1.0.0\n * @category search params\n */\nexport interface ParsedSearchParams {\n readonly _: unique symbol\n}\n\n/**\n * @since 1.0.0\n * @category search params\n */\nexport const ParsedSearchParams: Context.Tag<ParsedSearchParams, ReadonlyRecord<string, string | Array<string>>> =\n internal.parsedSearchParamsTag\n\n/**\n * @since 1.0.0\n * @category search params\n */\nexport const searchParamsFromURL: (url: URL) => ReadonlyRecord<string, string | Array<string>> =\n internal.searchParamsFromURL\n\n/**\n * @since 1.0.0\n * @category accessors\n */\nexport const persistedMultipart: Effect.Effect<\n unknown,\n Multipart.MultipartError,\n Scope.Scope | FileSystem.FileSystem | Path.Path | HttpServerRequest\n> = internal.multipartPersisted\n\n/**\n * @since 1.0.0\n * @category accessors\n */\nexport const upgrade: Effect.Effect<Socket.Socket, Error.RequestError, HttpServerRequest> = internal.upgrade\n\n/**\n * @since 1.0.0\n * @category accessors\n */\nexport const upgradeChannel: <IE = never>() => Channel<\n Chunk<Uint8Array>,\n Chunk<Uint8Array | string | Socket.CloseEvent>,\n Error.RequestError | IE | Socket.SocketError,\n IE,\n void,\n unknown,\n HttpServerRequest\n> = internal.upgradeChannel\n\n/**\n * @since 1.0.0\n * @category schema\n */\nexport const schemaCookies: <A, I extends Readonly<Record<string, string | undefined>>, R>(\n schema: Schema.Schema<A, I, R>,\n options?: ParseOptions | undefined\n) => Effect.Effect<A, ParseResult.ParseError, HttpServerRequest | R> = internal.schemaCookies\n\n/**\n * @since 1.0.0\n * @category schema\n */\nexport const schemaHeaders: <A, I extends Readonly<Record<string, string | undefined>>, R>(\n schema: Schema.Schema<A, I, R>,\n options?: ParseOptions | undefined\n) => Effect.Effect<A, ParseResult.ParseError, HttpServerRequest | R> = internal.schemaHeaders\n\n/**\n * @since 1.0.0\n * @category schema\n */\nexport const schemaSearchParams: <A, I extends Readonly<Record<string, string | ReadonlyArray<string> | undefined>>, R>(\n schema: Schema.Schema<A, I, R>,\n options?: ParseOptions | undefined\n) => Effect.Effect<A, ParseResult.ParseError, ParsedSearchParams | R> = internal.schemaSearchParams\n\n/**\n * @since 1.0.0\n * @category schema\n */\nexport const schemaBodyJson: <A, I, R>(\n schema: Schema.Schema<A, I, R>,\n options?: ParseOptions | undefined\n) => Effect.Effect<A, Error.RequestError | ParseResult.ParseError, HttpServerRequest | R> = internal.schemaBodyJson\n\n/**\n * @since 1.0.0\n * @category schema\n */\nexport const schemaBodyForm: <A, I extends Partial<Multipart.Persisted>, R>(\n schema: Schema.Schema<A, I, R>,\n options?: ParseOptions | undefined\n) => Effect.Effect<\n A,\n Multipart.MultipartError | ParseResult.ParseError | Error.RequestError,\n R | HttpServerRequest | Scope.Scope | FileSystem.FileSystem | Path.Path\n> = internal.schemaBodyForm\n\n/**\n * @since 1.0.0\n * @category schema\n */\nexport const schemaBodyUrlParams: <\n A,\n I extends Readonly<Record<string, string | ReadonlyArray<string> | undefined>>,\n R\n>(\n schema: Schema.Schema<A, I, R>,\n options?: ParseOptions | undefined\n) => Effect.Effect<A, ParseResult.ParseError | Error.RequestError, R | HttpServerRequest> = internal.schemaBodyUrlParams\n\n/**\n * @since 1.0.0\n * @category schema\n */\nexport const schemaBodyMultipart: <A, I extends Partial<Multipart.Persisted>, R>(\n schema: Schema.Schema<A, I, R>,\n options?: ParseOptions | undefined\n) => Effect.Effect<\n A,\n Multipart.MultipartError | ParseResult.ParseError,\n R | HttpServerRequest | Scope.Scope | FileSystem.FileSystem | Path.Path\n> = internal.schemaBodyMultipart\n\n/**\n * @since 1.0.0\n * @category schema\n */\nexport const schemaBodyFormJson: <A, I, R>(\n schema: Schema.Schema<A, I, R>,\n options?: ParseOptions | undefined\n) => (\n field: string\n) => Effect.Effect<\n A,\n ParseResult.ParseError | Error.RequestError,\n R | HttpServerRequest | FileSystem.FileSystem | Path.Path | Scope.Scope\n> = internal.schemaBodyFormJson\n\n/**\n * @since 1.0.0\n * @category conversions\n */\nexport const fromWeb: (request: Request) => HttpServerRequest = internal.fromWeb\n\n/**\n * @since 1.0.0\n * @category conversions\n */\nexport const toWebEither = (self: HttpServerRequest, options?: {\n readonly signal?: AbortSignal | undefined\n readonly runtime?: Runtime.Runtime<never> | undefined\n}): Either.Either<Request, Error.RequestError> => {\n if (self.source instanceof Request) {\n return Either.right(self.source)\n }\n const ourl = toURL(self)\n if (Option.isNone(ourl)) {\n return Either.left(\n new Error.RequestError({\n request: self,\n reason: \"Decode\",\n description: \"Invalid URL\"\n })\n )\n }\n const requestInit: RequestInit = {\n method: self.method,\n headers: self.headers,\n signal: options?.signal\n }\n if (hasBody(self.method)) {\n requestInit.body = Stream.toReadableStreamRuntime(self.stream, options?.runtime ?? Runtime.defaultRuntime)\n ;(requestInit as any).duplex = \"half\"\n }\n return Either.right(new Request(ourl.value, requestInit))\n}\n\n/**\n * @since 1.0.0\n * @category conversions\n */\nexport const toWeb = (self: HttpServerRequest, options?: {\n readonly signal?: AbortSignal | undefined\n}): Effect.Effect<Request, Error.RequestError> =>\n Effect.flatMap(Effect.runtime<never>(), (runtime) =>\n toWebEither(self, {\n signal: options?.signal,\n runtime\n }))\n\n/**\n * @since 1.0.0\n * @category conversions\n */\nexport const toURL: (self: HttpServerRequest) => Option.Option<URL> = internal.toURL\n","/**\n * @since 1.0.0\n * @category models\n */\nexport type HttpMethod =\n | \"GET\"\n | \"POST\"\n | \"PUT\"\n | \"DELETE\"\n | \"PATCH\"\n | \"HEAD\"\n | \"OPTIONS\"\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport declare namespace HttpMethod {\n /**\n * @since 1.0.0\n * @category models\n */\n export type NoBody = \"GET\" | \"HEAD\" | \"OPTIONS\"\n\n /**\n * @since 1.0.0\n * @category models\n */\n export type WithBody = Exclude<HttpMethod, NoBody>\n}\n\n/**\n * @since 1.0.0\n */\nexport const hasBody = (method: HttpMethod): boolean => method !== \"GET\" && method !== \"HEAD\" && method !== \"OPTIONS\"\n\n/**\n * @since 1.0.0\n */\nexport const all: ReadonlySet<HttpMethod> = new Set([\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"HEAD\", \"OPTIONS\"])\n\n/**\n * Tests if a value is a `HttpMethod`.\n *\n * **Example**\n *\n * ```ts\n * import { HttpMethod } from \"@effect/platform\"\n *\n * console.log(HttpMethod.isHttpMethod(\"GET\"))\n * // true\n * console.log(HttpMethod.isHttpMethod(\"get\"))\n * // false\n * console.log(HttpMethod.isHttpMethod(1))\n * // false\n * ```\n *\n * @since 1.0.0\n * @category refinements\n */\nexport const isHttpMethod = (u: unknown): u is HttpMethod => all.has(u as HttpMethod)\n","import * as Channel from \"effect/Channel\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Inspectable from \"effect/Inspectable\"\nimport * as Option from \"effect/Option\"\nimport type * as ParseResult from \"effect/ParseResult\"\nimport type { ReadonlyRecord } from \"effect/Record\"\nimport * as Schema from \"effect/Schema\"\nimport type { ParseOptions } from \"effect/SchemaAST\"\nimport type * as Scope from \"effect/Scope\"\nimport * as Stream from \"effect/Stream\"\nimport * as Cookies from \"../Cookies.js\"\nimport type * as FileSystem from \"../FileSystem.js\"\nimport * as Headers from \"../Headers.js\"\nimport * as IncomingMessage from \"../HttpIncomingMessage.js\"\nimport type { HttpMethod } from \"../HttpMethod.js\"\nimport * as Error from \"../HttpServerError.js\"\nimport type * as ServerRequest from \"../HttpServerRequest.js\"\nimport * as Multipart from \"../Multipart.js\"\nimport type * as Path from \"../Path.js\"\nimport * as Socket from \"../Socket.js\"\nimport * as UrlParams from \"../UrlParams.js\"\n\n/** @internal */\nexport const TypeId: ServerRequest.TypeId = Symbol.for(\"@effect/platform/HttpServerRequest\") as ServerRequest.TypeId\n\n/** @internal */\nexport const serverRequestTag = Context.GenericTag<ServerRequest.HttpServerRequest>(\n \"@effect/platform/HttpServerRequest\"\n)\n\n/** @internal */\nexport const parsedSearchParamsTag = Context.GenericTag<\n ServerRequest.ParsedSearchParams,\n ReadonlyRecord<string, string | Array<string>>\n>(\"@effect/platform/HttpServerRequest/ParsedSearchParams\")\n\n/** @internal */\nexport const upgrade = Effect.flatMap(serverRequestTag, (request) => request.upgrade)\n\n/** @internal */\nexport const upgradeChannel = <IE = never>() => Channel.unwrap(Effect.map(upgrade, Socket.toChannelWith<IE>()))\n\n/** @internal */\nexport const multipartPersisted = Effect.flatMap(serverRequestTag, (request) => request.multipart)\n\n/** @internal */\nexport const searchParamsFromURL = (url: URL): ReadonlyRecord<string, string | Array<string>> => {\n const out: Record<string, string | Array<string>> = {}\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/** @internal */\nexport const schemaCookies = <A, I extends Readonly<Record<string, string | undefined>>, R>(\n schema: Schema.Schema<A, I, R>,\n options?: ParseOptions | undefined\n) => {\n const parse = Schema.decodeUnknown(schema, options)\n return Effect.flatMap(serverRequestTag, (req) => parse(req.cookies))\n}\n\n/** @internal */\nexport const schemaHeaders = <A, I extends Readonly<Record<string, string | undefined>>, R>(\n schema: Schema.Schema<A, I, R>,\n options?: ParseOptions | undefined\n) => {\n const parse = IncomingMessage.schemaHeaders(schema, options)\n return Effect.flatMap(serverRequestTag, parse)\n}\n\n/** @internal */\nexport const schemaSearchParams = <\n A,\n I extends Readonly<Record<string, string | ReadonlyArray<string> | undefined>>,\n R\n>(\n schema: Schema.Schema<A, I, R>,\n options?: ParseOptions | undefined\n) => {\n const parse = Schema.decodeUnknown(schema, options)\n return Effect.flatMap(parsedSearchParamsTag, parse)\n}\n\n/** @internal */\nexport const schemaBodyJson = <A, I, R>(schema: Schema.Schema<A, I, R>, options?: ParseOptions | undefined) => {\n const parse = IncomingMessage.schemaBodyJson(schema, options)\n return Effect.flatMap(serverRequestTag, parse)\n}\n\nconst isMultipart = (request: ServerRequest.HttpServerRequest) =>\n request.headers[\"content-type\"]?.toLowerCase().includes(\"multipart/form-data\")\n\n/** @internal */\nexport const schemaBodyForm = <A, I extends Partial<Multipart.Persisted>, R>(\n schema: Schema.Schema<A, I, R>,\n options?: ParseOptions | undefined\n) => {\n const parseMultipart = Multipart.schemaPersisted(schema, options)\n const parseUrlParams = IncomingMessage.schemaBodyUrlParams(schema as Schema.Schema<A, any, R>, options)\n return Effect.flatMap(serverRequestTag, (request): Effect.Effect<\n A,\n Multipart.MultipartError | ParseResult.ParseError | Error.RequestError,\n R | ServerRequest.HttpServerRequest | Scope.Scope | FileSystem.FileSystem | Path.Path\n > => {\n if (isMultipart(request)) {\n return Effect.flatMap(request.multipart, parseMultipart)\n }\n return parseUrlParams(request)\n })\n}\n\n/** @internal */\nexport const schemaBodyUrlParams = <\n A,\n I extends Readonly<Record<string, string | ReadonlyArray<string> | undefined>>,\n R\n>(\n schema: Schema.Schema<A, I, R>,\n options?: ParseOptions | undefined\n) => {\n const parse = IncomingMessage.schemaBodyUrlParams(schema, options)\n return Effect.flatMap(serverRequestTag, parse)\n}\n\n/** @internal */\nexport const schemaBodyMultipart = <A, I extends Partial<Multipart.Persisted>, R>(\n schema: Schema.Schema<A, I, R>,\n options?: ParseOptions | undefined\n) => {\n const parse = Multipart.schemaPersisted(schema, options)\n return Effect.flatMap(multipartPersisted, parse)\n}\n\n/** @internal */\nexport const schemaBodyFormJson = <A, I, R>(schema: Schema.Schema<A, I, R>, options?: ParseOptions | undefined) => {\n const parseMultipart = Multipart.schemaJson(schema, options)\n const parseUrlParams = UrlParams.schemaJson(schema, options)\n return (field: string) =>\n Effect.flatMap(\n serverRequestTag,\n (\n request\n ): Effect.Effect<\n A,\n ParseResult.ParseError | Error.RequestError,\n R | FileSystem.FileSystem | Path.Path | Scope.Scope | ServerRequest.HttpServerRequest\n > => {\n if (isMultipart(request)) {\n return Effect.flatMap(\n Effect.mapError(request.multipart, (cause) =>\n new Error.RequestError({\n request,\n reason: \"Decode\",\n cause\n })),\n parseMultipart(field)\n )\n }\n return Effect.flatMap(request.urlParamsBody, parseUrlParams(field))\n }\n )\n}\n\n/** @internal */\nexport const fromWeb = (request: globalThis.Request): ServerRequest.HttpServerRequest =>\n new ServerRequestImpl(request, removeHost(request.url))\n\nconst removeHost = (url: string) => {\n if (url[0] === \"/\") {\n return url\n }\n const index = url.indexOf(\"/\", url.indexOf(\"//\") + 2)\n return index === -1 ? \"/\" : url.slice(index)\n}\n\nclass ServerRequestImpl extends Inspectable.Class implements ServerRequest.HttpServerRequest {\n readonly [TypeId]: ServerRequest.TypeId\n readonly [IncomingMessage.TypeId]: IncomingMessage.TypeId\n constructor(\n readonly source: Request,\n readonly url: string,\n public headersOverride?: Headers.Headers,\n private remoteAddressOverride?: string\n ) {\n super()\n this[TypeId] = TypeId\n this[IncomingMessage.TypeId] = IncomingMessage.TypeId\n }\n toJSON(): unknown {\n return IncomingMessage.inspect(this, {\n _id: \"@effect/platform/HttpServerRequest\",\n method: this.method,\n url: this.originalUrl\n })\n }\n modify(\n options: {\n readonly url?: string | undefined\n readonly headers?: Headers.Headers | undefined\n readonly remoteAddress?: string | undefined\n }\n ) {\n return new ServerRequestImpl(\n this.source,\n options.url ?? this.url,\n options.headers ?? this.headersOverride,\n options.remoteAddress ?? this.remoteAddressOverride\n )\n }\n get method(): HttpMethod {\n return this.source.method.toUpperCase() as HttpMethod\n }\n get originalUrl() {\n return this.source.url\n }\n get remoteAddress(): Option.Option<string> {\n return this.remoteAddressOverride ? Option.some(this.remoteAddressOverride) : Option.none()\n }\n get headers(): Headers.Headers {\n this.headersOverride ??= Headers.fromInput(this.source.headers as any)\n return this.headersOverride\n }\n\n private cachedCookies: ReadonlyRecord<string, string> | undefined\n get cookies() {\n if (this.cachedCookies) {\n return this.cachedCookies\n }\n return this.cachedCookies = Cookies.parseHeader(this.headers.cookie ?? \"\")\n }\n\n get stream(): Stream.Stream<Uint8Array, Error.RequestError> {\n return this.source.body\n ? Stream.fromReadableStream(() => this.source.body as any, (cause) =>\n new Error.RequestError({\n request: this,\n reason: \"Decode\",\n cause\n }))\n : Stream.fail(\n new Error.RequestError({\n request: this,\n reason: \"Decode\",\n description: \"can not create stream from empty body\"\n })\n )\n }\n\n private textEffect: Effect.Effect<string, Error.RequestError> | undefined\n get text(): Effect.Effect<string, Error.RequestError> {\n if (this.textEffect) {\n return this.textEffect\n }\n this.textEffect = Effect.runSync(Effect.cached(\n Effect.tryPromise({\n try: () => this.source.text(),\n catch: (cause) =>\n new Error.RequestError({\n request: this,\n reason: \"Decode\",\n cause\n })\n })\n ))\n return this.textEffect\n }\n\n get json(): Effect.Effect<unknown, Error.RequestError> {\n return Effect.tryMap(this.text, {\n try: (_) => JSON.parse(_) as unknown,\n catch: (cause) =>\n new Error.RequestError({\n request: this,\n reason: \"Decode\",\n cause\n })\n })\n }\n\n get urlParamsBody(): Effect.Effect<UrlParams.UrlParams, Error.RequestError> {\n return Effect.flatMap(this.text, (_) =>\n Effect.try({\n try: () => UrlParams.fromInput(new URLSearchParams(_)),\n catch: (cause) =>\n new Error.RequestError({\n request: this,\n reason: \"Decode\",\n cause\n })\n }))\n }\n\n private multipartEffect:\n | Effect.Effect<\n Multipart.Persisted,\n Multipart.MultipartError,\n Scope.Scope | FileSystem.FileSystem | Path.Path\n >\n | undefined\n get multipart(): Effect.Effect<\n Multipart.Persisted,\n Multipart.MultipartError,\n Scope.Scope | FileSystem.FileSystem | Path.Path\n > {\n if (this.multipartEffect) {\n return this.multipartEffect\n }\n this.multipartEffect = Effect.runSync(Effect.cached(\n Multipart.toPersisted(this.multipartStream)\n ))\n return this.multipartEffect\n }\n\n get multipartStream(): Stream.Stream<Multipart.Part, Multipart.MultipartError> {\n return Stream.pipeThroughChannel(\n Stream.mapError(this.stream, (cause) => new Multipart.MultipartError({ reason: \"InternalError\", cause })),\n Multipart.makeChannel(this.headers)\n )\n }\n\n private arrayBufferEffect: Effect.Effect<ArrayBuffer, Error.RequestError> | undefined\n get arrayBuffer(): Effect.Effect<ArrayBuffer, Error.RequestError> {\n if (this.arrayBufferEffect) {\n return this.arrayBufferEffect\n }\n this.arrayBufferEffect = Effect.runSync(Effect.cached(\n Effect.tryPromise({\n try: () => this.source.arrayBuffer(),\n catch: (cause) =>\n new Error.RequestError({\n request: this,\n reason: \"Decode\",\n cause\n })\n })\n ))\n return this.arrayBufferEffect\n }\n\n get upgrade(): Effect.Effect<Socket.Socket, Error.RequestError> {\n return Effect.fail(\n new Error.RequestError({\n request: this,\n reason: \"Decode\",\n description: \"Not an upgradeable ServerRequest\"\n })\n )\n }\n}\n\n/** @internal */\nexport const toURL = (self: ServerRequest.HttpServerRequest): Option.Option<URL> => {\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 * @since 1.0.0\n */\nimport type * as Cause from \"effect/Cause\"\nimport * as Channel from \"effect/Channel\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport { constant, dual } from \"effect/Function\"\nimport * as Inspectable from \"effect/Inspectable\"\nimport * as Mailbox from \"effect/Mailbox\"\nimport * as Option from \"effect/Option\"\nimport type * as ParseResult from \"effect/ParseResult\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Schema from \"effect/Schema\"\nimport type { ParseOptions } from \"effect/SchemaAST\"\nimport type * as Scope from \"effect/Scope\"\nimport type * as AsyncInput from \"effect/SingleProducerAsyncInput\"\nimport * as Stream from \"effect/Stream\"\nimport * as MP from \"multipasta\"\nimport * as FileSystem from \"./FileSystem.js\"\nimport * as IncomingMessage from \"./HttpIncomingMessage.js\"\nimport * as Path from \"./Path.js\"\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const TypeId: unique symbol = Symbol.for(\"@effect/platform/Multipart\")\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport type Part = Field | File\n\n/**\n * @since 1.0.0\n */\nexport declare namespace Part {\n /**\n * @since 1.0.0\n * @category models\n */\n export interface Proto extends Inspectable.Inspectable {\n readonly [TypeId]: TypeId\n readonly _tag: string\n }\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Field extends Part.Proto {\n readonly _tag: \"Field\"\n readonly key: string\n readonly contentType: string\n readonly value: string\n}\n\n/**\n * @since 1.0.0\n * @category Guards\n */\nexport const isPart = (u: unknown): u is Part => Predicate.hasProperty(u, TypeId)\n\n/**\n * @since 1.0.0\n * @category Guards\n */\nexport const isField = (u: unknown): u is Field => isPart(u) && u._tag === \"Field\"\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface File extends Part.Proto {\n readonly _tag: \"File\"\n readonly key: string\n readonly name: string\n readonly contentType: string\n readonly content: Stream.Stream<Uint8Array, MultipartError>\n readonly contentEffect: Effect.Effect<Uint8Array, MultipartError>\n}\n\n/**\n * @since 1.0.0\n * @category Guards\n */\nexport const isFile = (u: unknown): u is File => isPart(u) && u._tag === \"File\"\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface PersistedFile extends Part.Proto {\n readonly _tag: \"PersistedFile\"\n readonly key: string\n readonly name: string\n readonly contentType: string\n readonly path: string\n}\n\n/**\n * @since 1.0.0\n * @category Guards\n */\nexport const isPersistedFile = (u: unknown): u is PersistedFile =>\n Predicate.hasProperty(u, TypeId) && Predicate.isTagged(u, \"PersistedFile\")\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Persisted {\n readonly [key: string]: ReadonlyArray<PersistedFile> | ReadonlyArray<string> | string\n}\n\n/**\n * @since 1.0.0\n * @category Errors\n */\nexport const ErrorTypeId: unique symbol = Symbol.for(\n \"@effect/platform/Multipart/MultipartError\"\n)\n\n/**\n * @since 1.0.0\n * @category Errors\n */\nexport type ErrorTypeId = typeof ErrorTypeId\n\n/**\n * @since 1.0.0\n * @category Errors\n */\nexport class MultipartError extends Schema.TaggedError<MultipartError>()(\"MultipartError\", {\n reason: Schema.Literal(\"FileTooLarge\", \"FieldTooLarge\", \"BodyTooLarge\", \"TooManyParts\", \"InternalError\", \"Parse\"),\n cause: Schema.Defect\n}) {\n /**\n * @since 1.0.0\n */\n readonly [ErrorTypeId]: ErrorTypeId = ErrorTypeId\n\n /**\n * @since 1.0.0\n */\n get message(): string {\n return this.reason\n }\n}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport const FileSchema: Schema.Schema<PersistedFile> = Schema.declare(isPersistedFile, {\n typeConstructor: { _tag: \"effect/platform/Multipart.PersistedFile\" },\n identifier: \"PersistedFile\",\n jsonSchema: {\n type: \"string\",\n format: \"binary\"\n }\n})\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport const FilesSchema: Schema.Schema<ReadonlyArray<PersistedFile>> = Schema.Array(FileSchema)\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport const SingleFileSchema: Schema.transform<\n Schema.Schema<ReadonlyArray<PersistedFile>>,\n Schema.Schema<PersistedFile>\n> = Schema.transform(FilesSchema.pipe(Schema.itemsCount(1)), FileSchema, {\n strict: true,\n decode: ([file]) => file,\n encode: (file) => [file]\n})\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport const schemaPersisted = <A, I extends Partial<Persisted>, R>(\n schema: Schema.Schema<A, I, R>,\n options?: ParseOptions | undefined\n): (persisted: Persisted) => Effect.Effect<\n A,\n ParseResult.ParseError,\n R\n> => Schema.decodeUnknown(schema, options)\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport const schemaJson = <A, I, R>(schema: Schema.Schema<A, I, R>, options?: ParseOptions | undefined): {\n (\n field: string\n ): (persisted: Persisted) => Effect.Effect<A, ParseResult.ParseError, R>\n (\n persisted: Persisted,\n field: string\n ): Effect.Effect<A, ParseResult.ParseError, R>\n} => {\n const fromJson = Schema.parseJson(schema)\n return dual<\n (\n field: string\n ) => (\n persisted: Persisted\n ) => Effect.Effect<A, ParseResult.ParseError, R>,\n (\n persisted: Persisted,\n field: string\n ) => Effect.Effect<A, ParseResult.ParseError, R>\n >(2, (persisted, field) =>\n Effect.map(\n Schema.decodeUnknown(\n Schema.Struct({\n [field]: fromJson\n }),\n options\n )(persisted),\n (_) => _[field]\n ))\n}\n\n/**\n * @since 1.0.0\n * @category Config\n */\nexport const makeConfig = (\n headers: Record<string, string>\n): Effect.Effect<MP.BaseConfig> =>\n Effect.withFiberRuntime((fiber) => {\n const mimeTypes = Context.get(fiber.currentContext, FieldMimeTypes)\n return Effect.succeed<MP.BaseConfig>({\n headers,\n maxParts: Option.getOrUndefined(Context.get(fiber.currentContext, MaxParts)),\n maxFieldSize: Number(Context.get(fiber.currentContext, MaxFieldSize)),\n maxPartSize: Context.get(fiber.currentContext, MaxFileSize).pipe(Option.map(Number), Option.getOrUndefined),\n maxTotalSize: Context.get(fiber.currentContext, IncomingMessage.MaxBodySize).pipe(\n Option.map(Number),\n Option.getOrUndefined\n ),\n isFile: mimeTypes.length === 0 ? undefined : (info: MP.PartInfo): boolean =>\n !Chunk.some(\n mimeTypes,\n (_) => info.contentType.includes(_)\n ) && MP.defaultIsFile(info)\n })\n })\n\n/**\n * @since 1.0.0\n * @category Parsers\n */\nexport const makeChannel = <IE>(\n headers: Record<string, string>,\n bufferSize = 16\n): Channel.Channel<\n Chunk.Chunk<Part>,\n Chunk.Chunk<Uint8Array>,\n MultipartError | IE,\n IE,\n unknown,\n unknown\n> =>\n Channel.acquireUseRelease(\n Effect.all([\n makeConfig(headers),\n Mailbox.make<Chunk.Chunk<Uint8Array>>(bufferSize)\n ]),\n ([config, mailbox]) => {\n let partsBuffer: Array<Part> = []\n let exit = Option.none<Exit.Exit<void, IE | MultipartError>>()\n\n const input: AsyncInput.AsyncInputProducer<IE, Chunk.Chunk<Uint8Array>, unknown> = {\n awaitRead: () => Effect.void,\n emit(element) {\n return mailbox.offer(element)\n },\n error(cause) {\n exit = Option.some(Exit.failCause(cause))\n return mailbox.end\n },\n done(_value) {\n return mailbox.end\n }\n }\n\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: Array<Uint8Array> = []\n let finished = false\n const take: Channel.Channel<Chunk.Chunk<Uint8Array>> = Channel.suspend(() => {\n if (chunks.length === 0) {\n return finished ? Channel.void : Channel.zipRight(pump, take)\n }\n const chunk = Chunk.unsafeFromArray(chunks)\n chunks = []\n return finished ? Channel.write(chunk) : Channel.zipRight(\n Channel.write(chunk),\n Channel.zipRight(pump, take)\n )\n })\n partsBuffer.push(new FileImpl(info, take))\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.void)\n }\n })\n\n const pump = Channel.flatMap(\n mailbox.takeAll,\n ([chunks, done]) =>\n Channel.sync(() => {\n Chunk.forEach(chunks, Chunk.forEach(parser.write))\n if (done) {\n parser.end()\n }\n })\n )\n\n const partsChannel: Channel.Channel<\n Chunk.Chunk<Part>,\n unknown,\n IE | MultipartError\n > = Channel.flatMap(\n pump,\n () => {\n if (partsBuffer.length === 0) {\n return exit._tag === \"None\" ? partsChannel : writeExit(exit.value)\n }\n const chunk = Chunk.unsafeFromArray(partsBuffer)\n partsBuffer = []\n return Channel.zipRight(\n Channel.write(chunk),\n exit._tag === \"None\" ? partsChannel : writeExit(exit.value)\n )\n }\n )\n\n return Channel.embedInput(partsChannel, input)\n },\n ([, mailbox]) => mailbox.shutdown\n )\n\nconst writeExit = <A, E>(\n self: Exit.Exit<A, E>\n): Channel.Channel<never, unknown, E> => self._tag === \"Success\" ? Channel.void : Channel.failCause(self.cause)\n\nfunction convertError(cause: MP.MultipartError): MultipartError {\n switch (cause._tag) {\n case \"ReachedLimit\": {\n switch (cause.limit) {\n case \"MaxParts\": {\n return new MultipartError({ reason: \"TooManyParts\", cause })\n }\n case \"MaxFieldSize\": {\n return new MultipartError({ reason: \"FieldTooLarge\", cause })\n }\n case \"MaxPartSize\": {\n return new MultipartError({ reason: \"FileTooLarge\", cause })\n }\n case \"MaxTotalSize\": {\n return new MultipartError({ reason: \"BodyTooLarge\", cause })\n }\n }\n }\n default: {\n return new MultipartError({ reason: \"Parse\", cause })\n }\n }\n}\n\nabstract class PartBase extends Inspectable.Class {\n readonly [TypeId]: TypeId\n constructor() {\n super()\n this[TypeId] = TypeId\n }\n}\n\nclass FieldImpl extends PartBase implements Field {\n readonly _tag = \"Field\"\n\n constructor(\n readonly key: string,\n readonly contentType: string,\n readonly value: string\n ) {\n super()\n }\n\n toJSON(): unknown {\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}\n\nclass FileImpl extends PartBase implements File {\n readonly _tag = \"File\"\n readonly key: string\n readonly name: string\n readonly contentType: string\n readonly content: Stream.Stream<Uint8Array, MultipartError>\n readonly contentEffect: Effect.Effect<Uint8Array, MultipartError>\n\n constructor(\n info: MP.PartInfo,\n channel: Channel.Channel<Chunk.Chunk<Uint8Array>, unknown, never, unknown, void, unknown>\n ) {\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(\n Channel.pipeTo(collectUint8Array),\n Channel.run,\n Effect.mapError((cause) => new MultipartError({ reason: \"InternalError\", cause }))\n )\n }\n\n toJSON(): unknown {\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}\n\nconst defaultWriteFile = (path: string, file: File) =>\n Effect.flatMap(\n FileSystem.FileSystem,\n (fs) =>\n Effect.mapError(\n Stream.run(file.content, fs.sink(path)),\n (cause) => new MultipartError({ reason: \"InternalError\", cause })\n )\n )\n\n/**\n * @since 1.0.0\n */\nexport const collectUint8Array = Channel.suspend(() => {\n let accumulator = new Uint8Array(0)\n const loop: Channel.Channel<\n never,\n Chunk.Chunk<Uint8Array>,\n unknown,\n unknown,\n Uint8Array\n > = Channel.readWithCause({\n onInput(chunk: Chunk.Chunk<Uint8Array>) {\n for (const element of chunk) {\n const newAccumulator = new Uint8Array(accumulator.length + element.length)\n newAccumulator.set(accumulator, 0)\n newAccumulator.set(element, accumulator.length)\n accumulator = newAccumulator\n }\n return loop\n },\n onFailure: (cause: Cause.Cause<unknown>) => Channel.failCause(cause),\n onDone: () => Channel.succeed(accumulator)\n })\n return loop\n})\n\n/**\n * @since 1.0.0\n * @category Conversions\n */\nexport const toPersisted = (\n stream: Stream.Stream<Part, MultipartError>,\n writeFile = defaultWriteFile\n): Effect.Effect<Persisted, MultipartError, FileSystem.FileSystem | Path.Path | Scope.Scope> =>\n Effect.gen(function*() {\n const fs = yield* FileSystem.FileSystem\n const path_ = yield* Path.Path\n const dir = yield* fs.makeTempDirectoryScoped()\n const persisted: Record<string, Array<PersistedFile> | Array<string> | string> = 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] as string, part.value]\n } else {\n ;(persisted[part.key] as Array<string>).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(\n file.key,\n file.name,\n file.contentType,\n path\n )\n if (Array.isArray(persisted[part.key])) {\n ;(persisted[part.key] as Array<PersistedFile>).push(filePart)\n } else {\n persisted[part.key] = [filePart]\n }\n return writeFile(path, file)\n })\n return persisted\n }).pipe(\n Effect.catchTags({\n SystemError: (cause) => Effect.fail(new MultipartError({ reason: \"InternalError\", cause })),\n BadArgument: (cause) => Effect.fail(new MultipartError({ reason: \"InternalError\", cause }))\n })\n )\n\nclass PersistedFileImpl extends PartBase implements PersistedFile {\n readonly _tag = \"PersistedFile\"\n\n constructor(\n readonly key: string,\n readonly name: string,\n readonly contentType: string,\n readonly path: string\n ) {\n super()\n }\n\n toJSON(): unknown {\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/**\n * @since 1.0.0\n * @category fiber refs\n */\nexport const withLimits: {\n /**\n * @since 1.0.0\n * @category fiber refs\n */\n (\n options: {\n readonly maxParts?: Option.Option<number> | undefined\n readonly maxFieldSize?: FileSystem.SizeInput | undefined\n readonly maxFileSize?: Option.Option<FileSystem.SizeInput> | undefined\n readonly maxTotalSize?: Option.Option<FileSystem.SizeInput> | undefined\n readonly fieldMimeTypes?: ReadonlyArray<string> | undefined\n }\n ): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n /**\n * @since 1.0.0\n * @category fiber refs\n */\n <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n options: {\n readonly maxParts?: Option.Option<number> | undefined\n readonly maxFieldSize?: FileSystem.SizeInput | undefined\n readonly maxFileSize?: Option.Option<FileSystem.SizeInput> | undefined\n readonly maxTotalSize?: Option.Option<FileSystem.SizeInput> | undefined\n readonly fieldMimeTypes?: ReadonlyArray<string> | undefined\n }\n ): Effect.Effect<A, E, R>\n} = dual(2, <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n options: {\n readonly maxParts?: Option.Option<number> | undefined\n readonly maxFieldSize?: FileSystem.SizeInput | undefined\n readonly maxFileSize?: Option.Option<FileSystem.SizeInput> | undefined\n readonly maxTotalSize?: Option.Option<FileSystem.SizeInput> | undefined\n readonly fieldMimeTypes?: ReadonlyArray<string> | undefined\n }\n): Effect.Effect<A, E, R> => Effect.provide(effect, withLimitsContext(options)))\n\nconst withLimitsContext = (options: {\n readonly maxParts?: Option.Option<number> | undefined\n readonly maxFieldSize?: FileSystem.SizeInput | undefined\n readonly maxFileSize?: Option.Option<FileSystem.SizeInput> | undefined\n readonly maxTotalSize?: Option.Option<FileSystem.SizeInput> | undefined\n readonly fieldMimeTypes?: ReadonlyArray<string> | undefined\n}) => {\n const contextMap = new Map<string, unknown>()\n if (options.maxParts !== undefined) {\n contextMap.set(MaxParts.key, options.maxParts)\n }\n if (options.maxFieldSize !== undefined) {\n contextMap.set(MaxFieldSize.key, FileSystem.Size(options.maxFieldSize))\n }\n if (options.maxFileSize !== undefined) {\n contextMap.set(MaxFileSize.key, Option.map(options.maxFileSize, FileSystem.Size))\n }\n if (options.maxTotalSize !== undefined) {\n contextMap.set(IncomingMessage.MaxBodySize.key, Option.map(options.maxTotalSize, FileSystem.Size))\n }\n if (options.fieldMimeTypes !== undefined) {\n contextMap.set(FieldMimeTypes.key, Chunk.fromIterable(options.fieldMimeTypes))\n }\n return Context.unsafeMake(contextMap)\n}\n\n/**\n * @since 1.0.0\n * @category fiber refs\n */\nexport const withLimitsStream: {\n /**\n * @since 1.0.0\n * @category fiber refs\n */\n (\n options: {\n readonly maxParts?: Option.Option<number> | undefined\n readonly maxFieldSize?: FileSystem.SizeInput | undefined\n readonly maxFileSize?: Option.Option<FileSystem.SizeInput> | undefined\n readonly maxTotalSize?: Option.Option<FileSystem.SizeInput> | undefined\n readonly fieldMimeTypes?: ReadonlyArray<string> | undefined\n }\n ): <A, E, R>(stream: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R>\n /**\n * @since 1.0.0\n * @category fiber refs\n */\n <A, E, R>(\n stream: Stream.Stream<A, E, R>,\n options: {\n readonly maxParts?: Option.Option<number> | undefined\n readonly maxFieldSize?: FileSystem.SizeInput | undefined\n readonly maxFileSize?: Option.Option<FileSystem.SizeInput> | undefined\n readonly maxTotalSize?: Option.Option<FileSystem.SizeInput> | undefined\n readonly fieldMimeTypes?: ReadonlyArray<string> | undefined\n }\n ): Stream.Stream<A, E, R>\n} = dual(2, <A, E, R>(\n stream: Stream.Stream<A, E, R>,\n options: {\n readonly maxParts?: Option.Option<number> | undefined\n readonly maxFieldSize?: FileSystem.SizeInput | undefined\n readonly maxFileSize?: Option.Option<FileSystem.SizeInput> | undefined\n readonly maxTotalSize?: Option.Option<FileSystem.SizeInput> | undefined\n readonly fieldMimeTypes?: ReadonlyArray<string> | undefined\n }\n): Stream.Stream<A, E, R> => Stream.provideSomeContext(stream, withLimitsContext(options)))\n\n/**\n * @since 1.0.0\n * @category fiber refs\n */\nexport declare namespace withLimits {\n /**\n * @since 1.0.0\n * @category fiber refs\n */\n export type Options = {\n readonly maxParts?: Option.Option<number> | undefined\n readonly maxFieldSize?: FileSystem.SizeInput | undefined\n readonly maxFileSize?: Option.Option<FileSystem.SizeInput> | undefined\n readonly maxTotalSize?: Option.Option<FileSystem.SizeInput> | undefined\n readonly fieldMimeTypes?: ReadonlyArray<string> | undefined\n }\n}\n\n/**\n * @since 1.0.0\n * @category fiber refs\n */\nexport class MaxParts extends Context.Reference<MaxParts>()(\"@effect/platform/Multipart/MaxParts\", {\n defaultValue: Option.none<number>\n}) {}\n\n/**\n * @since 1.0.0\n * @category fiber refs\n */\nexport const withMaxParts: {\n /**\n * @since 1.0.0\n * @category fiber refs\n */\n (count: Option.Option<number>): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n /**\n * @since 1.0.0\n * @category fiber refs\n */\n <A, E, R>(effect: Effect.Effect<A, E, R>, count: Option.Option<number>): Effect.Effect<A, E, R>\n} = dual(\n 2,\n <A, E, R>(effect: Effect.Effect<A, E, R>, count: Option.Option<number>): Effect.Effect<A, E, R> =>\n Effect.provideService(effect, MaxParts, count)\n)\n\n/**\n * @since 1.0.0\n * @category fiber refs\n */\nexport class MaxFieldSize extends Context.Reference<MaxFieldSize>()(\"@effect/platform/Multipart/MaxFieldSize\", {\n defaultValue: constant(FileSystem.Size(10 * 1024 * 1024))\n}) {}\n\n/**\n * @since 1.0.0\n * @category fiber refs\n */\nexport const withMaxFieldSize: {\n /**\n * @since 1.0.0\n * @category fiber refs\n */\n (size: FileSystem.SizeInput): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n /**\n * @since 1.0.0\n * @category fiber refs\n */\n <A, E, R>(effect: Effect.Effect<A, E, R>, size: FileSystem.SizeInput): Effect.Effect<A, E, R>\n} = dual(\n 2,\n <A, E, R>(effect: Effect.Effect<A, E, R>, size: FileSystem.SizeInput): Effect.Effect<A, E, R> =>\n Effect.provideService(effect, MaxFieldSize, FileSystem.Size(size))\n)\n\n/**\n * @since 1.0.0\n * @category fiber refs\n */\nexport class MaxFileSize extends Context.Reference<MaxFileSize>()(\"@effect/platform/Multipart/MaxFileSize\", {\n defaultValue: Option.none<FileSystem.Size>\n}) {}\n\n/**\n * @since 1.0.0\n * @category fiber refs\n */\nexport const withMaxFileSize: {\n /**\n * @since 1.0.0\n * @category fiber refs\n */\n (size: Option.Option<FileSystem.SizeInput>): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n /**\n * @since 1.0.0\n * @category fiber refs\n */\n <A, E, R>(effect: Effect.Effect<A, E, R>, size: Option.Option<FileSystem.SizeInput>): Effect.Effect<A, E, R>\n} = dual(\n 2,\n <A, E, R>(effect: Effect.Effect<A, E, R>, size: Option.Option<FileSystem.SizeInput>): Effect.Effect<A, E, R> =>\n Effect.provideService(\n effect,\n MaxFileSize,\n Option.map(size, FileSystem.Size)\n )\n)\n\n/**\n * @since 1.0.0\n * @category fiber refs\n */\nexport class FieldMimeTypes extends Context.Reference<FieldMimeTypes>()(\"@effect/platform/Multipart/FieldMimeTypes\", {\n defaultValue: constant<Chunk.Chunk<string>>(Chunk.make(\"application/json\"))\n}) {}\n\n/**\n * @since 1.0.0\n * @category fiber refs\n */\nexport const withFieldMimeTypes: {\n /**\n * @since 1.0.0\n * @category fiber refs\n */\n (mimeTypes: ReadonlyArray<string>): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n /**\n * @since 1.0.0\n * @category fiber refs\n */\n <A, E, R>(effect: Effect.Effect<A, E, R>, mimeTypes: ReadonlyArray<string>): Effect.Effect<A, E, R>\n} = dual(\n 2,\n <A, E, R>(effect: Effect.Effect<A, E, R>, mimeTypes: ReadonlyArray<string>): Effect.Effect<A, E, R> =>\n Effect.provideService(effect, FieldMimeTypes, Chunk.fromIterable(mimeTypes))\n)\n","// taken from https://github.com/fastify/fast-content-type-parse\n// under the MIT license\n\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 =\n /; *([!#$%&'*+.^\\w`|~-]+)=(\"(?:[\\v\\u0020\\u0021\\u0023-\\u005b\\u005d-\\u007e\\u0080-\\u00ff]|\\\\[\\v\\u0020-\\u00ff])*\"|[!#$%&'*+.^\\w`|~-]+) */gu\n\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/**\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\n// default ContentType to prevent repeated object creation\nconst defaultContentType = { value: \"\", parameters: Object.create(null) }\n\nexport function parse(\n header: string | undefined,\n withoutSlash = false,\n): {\n readonly value: string\n readonly parameters: Record<string, string>\n} {\n if (typeof header !== \"string\") {\n return defaultContentType\n }\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\n if (mediaRE.test(type) === false) {\n return defaultContentType\n }\n\n const result = {\n value: type.toLowerCase(),\n parameters: Object.create(null),\n }\n\n // parse parameters\n if (index === -1) {\n return result\n }\n\n let key: string\n let match: RegExpExecArray | null\n let value: string\n\n paramRE.lastIndex = index\n\n while ((match = paramRE.exec(header))) {\n if (match.index !== index) {\n return defaultContentType\n }\n\n index += match[0].length\n key = match[1].toLowerCase()\n value = match[2]\n\n if (value[0] === '\"') {\n // remove quotes and escapes\n value = value.slice(1, value.length - 1)\n\n !withoutSlash &&\n quotedPairRE.test(value) &&\n (value = value.replace(quotedPairRE, \"$1\"))\n }\n\n result.parameters[key] = value\n }\n\n if (index !== header.length) {\n return defaultContentType\n }\n\n return result\n}\n","import { Continue, FailureReason, ReturnValue } from \"../HeadersParser.js\"\n\nconst constMaxPairs = 100\nconst constMaxSize = 16 * 1024\n\nconst enum State {\n key,\n whitespace,\n value,\n}\n\nconst constContinue: Continue = { _tag: \"Continue\" }\n\nconst constNameChars = [\n 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,\n 0, 0, 0, 0, 0, 0, 0, 1, 0,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1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n]\n\nexport function make() {\n const decoder = new TextDecoder()\n const state = {\n state: State.key,\n headers: Object.create(null) as Record<string, string | Array<string>>,\n key: \"\",\n value: undefined as undefined | Uint8Array,\n crlf: 0,\n previousChunk: undefined as undefined | Uint8Array,\n pairs: 0,\n size: 0,\n }\n\n function reset(value: ReturnValue): ReturnValue {\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\n function concatUint8Array(a: Uint8Array, b: Uint8Array): Uint8Array {\n const newUint8Array = new Uint8Array(a.length + b.length)\n newUint8Array.set(a)\n newUint8Array.set(b, a.length)\n return newUint8Array\n }\n\n function error(reason: FailureReason) {\n return reset({ _tag: \"Failure\", reason, headers: state.headers })\n }\n\n return function write(chunk: Uint8Array, start: number): ReturnValue {\n let endOffset = 0\n let previousCursor: number | undefined\n if (state.previousChunk !== undefined) {\n endOffset = state.previousChunk.length\n previousCursor = endOffset\n\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\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\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\n if (\n chunk[i + 1] === 32 &&\n chunk[i + 2] !== 32 &&\n chunk[i + 2] !== 9\n ) {\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\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\n if (state.state === State.whitespace) {\n for (; start < end; start++) {\n if (state.size++ > constMaxSize) {\n return error(\"HeaderTooLarge\")\n }\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\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\n if (chunk[i] === 13 || state.crlf > 0) {\n let byte = chunk[i]\n\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\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 =\n state.value === undefined\n ? chunk.subarray(start, i - state.crlf)\n : concatUint8Array(\n state.value,\n chunk.subarray(start, i - state.crlf),\n )\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] = [\n state.headers[state.key] as string,\n value,\n ]\n } else {\n ;(state.headers[state.key] as Array<string>).push(value)\n }\n\n start = i\n state.size--\n\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\n state.pairs++\n state.key = \"\"\n state.value = undefined\n state.crlf = 0\n state.state = State.key\n\n continue outer\n }\n } else if (constValueChars[chunk[i]] !== 1) {\n return error(\"InvalidHeaderValue\")\n }\n }\n\n if (i === end) {\n state.value =\n state.value === undefined\n ? chunk.subarray(start, end)\n : concatUint8Array(state.value, chunk.subarray(start, end))\n return constContinue\n }\n }\n }\n\n if (start > end) {\n state.size += end - start\n }\n\n return constContinue\n }\n}\n","interface SearchState {\n readonly needle: Uint8Array\n readonly needleLength: number\n readonly indexes: Record<number, ReadonlyArray<number>>\n readonly firstByte: number\n\n previousChunk: Uint8Array | undefined\n previousChunkLength: number\n matchIndex: number\n}\n\nfunction makeState(needle_: string): SearchState {\n const needle = new TextEncoder().encode(needle_)\n const needleLength = needle.length\n\n const indexes: Record<number, number[]> = {}\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\n return {\n needle,\n needleLength,\n indexes,\n firstByte: needle[0],\n previousChunk: undefined,\n previousChunkLength: 0,\n matchIndex: 0,\n }\n}\n\nexport function make(\n needle: string,\n callback: (index: number, chunk: Uint8Array) => void,\n seed?: Uint8Array,\n) {\n const state = makeState(needle)\n if (seed !== undefined) {\n state.previousChunk = seed\n state.previousChunkLength = seed.length\n }\n\n function makeIndexOf(): (\n chunk: Uint8Array,\n needle: Uint8Array,\n fromIndex: number,\n ) => number {\n // on node.js use the Buffer api\n if (\n \"Buffer\" in globalThis &&\n !(\"Bun\" in globalThis || \"Deno\" in globalThis)\n ) {\n return function (chunk, needle, fromIndex) {\n return Buffer.prototype.indexOf.call(chunk, needle, fromIndex)\n }\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\n return function (chunk, needle, fromIndex) {\n const lengthTotal = chunk.length\n let i = fromIndex + state.needleLength - 1\n\n while (i < lengthTotal) {\n for (\n let j = state.needleLength - 1, k = i;\n j >= 0 && chunk[k] === needle[j];\n j--, k--\n ) {\n if (j === 0) return k\n }\n i += skipTable[chunk[i]]\n }\n\n return -1\n }\n }\n\n const indexOf = makeIndexOf()\n\n function write(chunk: Uint8Array): void {\n let chunkLength = chunk.length\n\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\n if (chunkLength < state.needleLength) {\n state.previousChunk = chunk\n state.previousChunkLength = chunkLength\n return\n }\n\n let pos = 0\n while (pos < chunkLength) {\n const match = indexOf(chunk, state.needle, pos)\n\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 (\n chunk[chunkLength - 1 - index] === state.firstByte &&\n i > earliestIndex\n ) {\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(\n state.matchIndex,\n chunk.subarray(pos, chunkLength - 1 - earliestIndex),\n )\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\n break\n }\n }\n\n function end(): void {\n if (state.previousChunk !== undefined && state.previousChunk !== seed) {\n callback(state.matchIndex, state.previousChunk)\n }\n\n state.previousChunk = seed\n state.previousChunkLength = seed?.length ?? 0\n state.matchIndex = 0\n }\n\n return { write, end } as const\n}\n","import { Config, MultipartError, PartInfo } from \"../index.js\"\nimport * as CT from \"./contentType.js\"\nimport * as HP from \"./headers.js\"\nimport * as Search from \"./search.js\"\n\nconst enum State {\n headers,\n body,\n}\n\nconst errInvalidDisposition: MultipartError = { _tag: \"InvalidDisposition\" }\nconst errEndNotReached: MultipartError = { _tag: \"EndNotReached\" }\nconst errMaxParts: MultipartError = { _tag: \"ReachedLimit\", limit: \"MaxParts\" }\nconst errMaxTotalSize: MultipartError = {\n _tag: \"ReachedLimit\",\n limit: \"MaxTotalSize\",\n}\nconst errMaxPartSize: MultipartError = {\n _tag: \"ReachedLimit\",\n limit: \"MaxPartSize\",\n}\nconst errMaxFieldSize: MultipartError = {\n _tag: \"ReachedLimit\",\n limit: \"MaxFieldSize\",\n}\n\nconst constCR = new TextEncoder().encode(\"\\r\\n\")\n\nexport function defaultIsFile(info: PartInfo) {\n return (\n info.filename !== undefined ||\n info.contentType === \"application/octet-stream\"\n )\n}\n\nfunction parseBoundary(headers: Record<string, string>) {\n const contentType = CT.parse(headers[\"content-type\"])\n return contentType.parameters.boundary\n}\n\nfunction noopOnChunk(_chunk: Uint8Array | null) {}\n\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}: Config) {\n const boundary = parseBoundary(headers)\n if (boundary === undefined) {\n onError({ _tag: \"InvalidBoundary\" })\n return {\n write: noopOnChunk,\n end() {},\n }\n }\n\n const state = {\n state: State.headers,\n index: 0,\n parts: 0,\n onChunk: noopOnChunk,\n info: undefined as any as PartInfo,\n headerSkip: 0,\n partSize: 0,\n totalSize: 0,\n isFile: false,\n fieldChunks: [] as Array<Uint8Array>,\n fieldSize: 0,\n }\n\n function skipBody() {\n state.state = State.body\n state.isFile = true\n state.onChunk = noopOnChunk\n }\n\n const headerParser = HP.make()\n\n const split = Search.make(\n `\\r\\n--${boundary}`,\n 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\n state.state = State.headers\n state.index = index\n state.headerSkip = 2 // skip the first \\r\\n\n\n // trailing --\n if (chunk[0] === 45 && chunk[1] === 45) {\n return onDone()\n }\n\n state.parts++\n if (state.parts > maxParts) {\n onError(errMaxParts)\n }\n }\n\n if ((state.partSize += chunk.length) > maxPartSize) {\n onError(errMaxPartSize)\n }\n\n if (state.state === State.headers) {\n const result = headerParser(chunk, state.headerSkip)\n state.headerSkip = 0\n\n if (result._tag === \"Continue\") {\n return\n } else if (result._tag === \"Failure\") {\n skipBody()\n return onError({ _tag: \"BadHeaders\", error: result })\n }\n\n const contentType = CT.parse(result.headers[\"content-type\"] as string)\n const contentDisposition = CT.parse(\n result.headers[\"content-disposition\"] as string,\n true,\n )\n\n if (\n \"form-data\" === contentDisposition.value &&\n !(\"name\" in contentDisposition.parameters)\n ) {\n skipBody()\n return onError(errInvalidDisposition)\n }\n\n let encodedFilename: string | undefined\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\n state.info = {\n name: contentDisposition.parameters.name ?? \"\",\n filename: encodedFilename ?? contentDisposition.parameters.filename,\n contentType:\n contentType.value === \"\"\n ? contentDisposition.parameters.filename !== undefined\n ? \"application/octet-stream\"\n : \"text/plain\"\n : contentType.value,\n contentTypeParameters: contentType.parameters,\n contentDisposition: contentDisposition.value,\n contentDispositionParameters: contentDisposition.parameters as any,\n headers: result.headers,\n }\n\n state.state = State.body\n state.isFile = isFile(state.info)\n\n if (state.isFile) {\n state.onChunk = onPart(state.info)\n }\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 },\n constCR,\n )\n\n return {\n write(chunk: Uint8Array) {\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\n state.state = State.headers\n state.index = 0\n state.parts = 0\n state.onChunk = noopOnChunk\n state.info = undefined as any as PartInfo\n state.totalSize = 0\n state.partSize = 0\n state.fieldChunks = []\n state.fieldSize = 0\n },\n } as const\n}\n\nconst utf8Decoder = new TextDecoder(\"utf-8\")\nfunction getDecoder(charset: string) {\n if (charset === \"utf-8\" || charset === \"utf8\" || charset === \"\") {\n return utf8Decoder\n }\n\n try {\n return new TextDecoder(charset)\n } catch (error) {\n return utf8Decoder\n }\n}\n\nexport function decodeField(info: PartInfo, value: Uint8Array): string {\n return getDecoder(info.contentTypeParameters.charset ?? \"utf-8\").decode(value)\n}\n","import * as internal from \"./internal/multipart.js\"\nimport type * as HeadersParser from \"./HeadersParser.js\"\n\nexport interface PartInfo {\n readonly name: string\n readonly filename?: string | undefined\n readonly contentType: string\n readonly contentTypeParameters: Record<string, string>\n readonly contentDisposition: string\n readonly contentDispositionParameters: Record<string, string>\n readonly headers: Record<string, string | Array<string>>\n}\n\nexport type MultipartError =\n | {\n readonly _tag: \"InvalidBoundary\"\n }\n | {\n readonly _tag: \"BadHeaders\"\n readonly error: HeadersParser.Failure\n }\n | {\n readonly _tag: \"InvalidDisposition\"\n }\n | {\n readonly _tag: \"ReachedLimit\"\n readonly limit:\n | \"MaxParts\"\n | \"MaxTotalSize\"\n | \"MaxPartSize\"\n | \"MaxFieldSize\"\n }\n | {\n readonly _tag: \"EndNotReached\"\n }\n\nexport type BaseConfig = {\n readonly headers: Record<string, string>\n readonly isFile?: ((info: PartInfo) => boolean) | undefined\n readonly maxParts?: number | undefined\n readonly maxTotalSize?: number | undefined\n readonly maxPartSize?: number | undefined\n readonly maxFieldSize?: number | undefined\n}\n\nexport type Config = BaseConfig & {\n readonly onField: (info: PartInfo, value: Uint8Array) => void\n readonly onFile: (info: PartInfo) => (chunk: Uint8Array | null) => void\n readonly onError: (error: MultipartError) => void\n readonly onDone: () => void\n}\nexport interface Parser {\n readonly write: (chunk: Uint8Array) => void\n readonly end: () => void\n}\n\nexport const make: (options: Config) => Parser = internal.make\n\nexport const defaultIsFile: (info: PartInfo) => boolean = internal.defaultIsFile\n\nexport const decodeField: (info: PartInfo, value: Uint8Array) => string =\n internal.decodeField\n","import { GenericTag } from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport { identity } from \"effect/Function\"\nimport * as Layer from \"effect/Layer\"\nimport { BadArgument } from \"../Error.js\"\nimport type * as Api from \"../Path.js\"\n\n/** @internal */\nexport const TypeId: Api.TypeId = Symbol.for(\"@effect/platform/Path\") as Api.TypeId\n\n/** @internal */\nexport const Path = GenericTag<Api.Path>(\"@effect/platform/Path\")\n\n/**\n * The following functions are adapted from the Node.js source code:\n * https://github.com/nodejs/node/blob/main/lib/internal/url.js\n *\n * The following license applies to these functions:\n * - MIT\n */\n\n// Resolves . and .. elements in a path with directory names\nfunction normalizeStringPosix(path: string, allowAboveRoot: boolean) {\n let res = \"\"\n let lastSegmentLength = 0\n let lastSlash = -1\n let dots = 0\n let code\n for (let i = 0; i <= path.length; ++i) {\n if (i < path.length) {\n code = path.charCodeAt(i)\n } else if (code === 47 /*/*/) {\n break\n } else {\n code = 47 /*/*/\n }\n if (code === 47 /*/*/) {\n if (lastSlash === i - 1 || dots === 1) {\n // NOOP\n } else if (lastSlash !== i - 1 && dots === 2) {\n if (\n res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== 46 /*.*/ ||\n res.charCodeAt(res.length - 2) !== 46 /*.*/\n ) {\n if (res.length > 2) {\n const lastSlashIndex = res.lastIndexOf(\"/\")\n if (lastSlashIndex !== res.length - 1) {\n if (lastSlashIndex === -1) {\n res = \"\"\n lastSegmentLength = 0\n } else {\n res = res.slice(0, lastSlashIndex)\n lastSegmentLength = res.length - 1 - res.lastIndexOf(\"/\")\n }\n lastSlash = i\n dots = 0\n continue\n }\n } else if (res.length === 2 || res.length === 1) {\n res = \"\"\n lastSegmentLength = 0\n lastSlash = i\n dots = 0\n continue\n }\n }\n if (allowAboveRoot) {\n if (res.length > 0) {\n res += \"/..\"\n } else {\n res = \"..\"\n }\n lastSegmentLength = 2\n }\n } else {\n if (res.length > 0) {\n res += \"/\" + path.slice(lastSlash + 1, i)\n } else {\n res = path.slice(lastSlash + 1, i)\n }\n lastSegmentLength = i - lastSlash - 1\n }\n lastSlash = i\n dots = 0\n } else if (code === 46 /*.*/ && dots !== -1) {\n ++dots\n } else {\n dots = -1\n }\n }\n return res\n}\n\nfunction _format(sep: string, pathObject: Partial<Api.Path.Parsed>) {\n const dir = pathObject.dir || pathObject.root\n const base = pathObject.base || (pathObject.name || \"\") + (pathObject.ext || \"\")\n if (!dir) {\n return base\n }\n if (dir === pathObject.root) {\n return dir + base\n }\n return dir + sep + base\n}\n\nfunction fromFileUrl(url: URL): Effect.Effect<string, BadArgument> {\n if (url.protocol !== \"file:\") {\n return Effect.fail(\n new BadArgument({\n module: \"Path\",\n method: \"fromFileUrl\",\n description: \"URL must be of scheme file\"\n })\n )\n } else if (url.hostname !== \"\") {\n return Effect.fail(\n new BadArgument({\n module: \"Path\",\n method: \"fromFileUrl\",\n description: \"Invalid file URL host\"\n })\n )\n }\n const pathname = url.pathname\n for (let n = 0; n < pathname.length; n++) {\n if (pathname[n] === \"%\") {\n const third = pathname.codePointAt(n + 2)! | 0x20\n if (pathname[n + 1] === \"2\" && third === 102) {\n return Effect.fail(\n new BadArgument({\n module: \"Path\",\n method: \"fromFileUrl\",\n description: \"must not include encoded / characters\"\n })\n )\n }\n }\n }\n return Effect.succeed(decodeURIComponent(pathname))\n}\n\nconst resolve: Api.Path[\"resolve\"] = function resolve() {\n let resolvedPath = \"\"\n let resolvedAbsolute = false\n let cwd: string | undefined = undefined\n\n for (let i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {\n let path: string\n if (i >= 0) {\n path = arguments[i]\n } else {\n const process = (globalThis as any).process\n if (\n cwd === undefined && \"process\" in globalThis &&\n typeof process === \"object\" &&\n process !== null &&\n typeof process.cwd === \"function\"\n ) {\n cwd = process.cwd()\n }\n path = cwd!\n }\n\n // Skip empty entries\n if (path.length === 0) {\n continue\n }\n\n resolvedPath = path + \"/\" + resolvedPath\n resolvedAbsolute = path.charCodeAt(0) === 47 /*/*/\n }\n\n // At this point the path should be resolved to a full absolute path, but\n // handle relative paths to be safe (might happen when process.cwd() fails)\n\n // Normalize the path\n resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute)\n\n if (resolvedAbsolute) {\n if (resolvedPath.length > 0) {\n return \"/\" + resolvedPath\n } else {\n return \"/\"\n }\n } else if (resolvedPath.length > 0) {\n return resolvedPath\n } else {\n return \".\"\n }\n}\n\nconst CHAR_FORWARD_SLASH = 47\n\nfunction toFileUrl(filepath: string) {\n const outURL = new URL(\"file://\")\n let resolved = resolve(filepath)\n // path.resolve strips trailing slashes so we must add them back\n const filePathLast = filepath.charCodeAt(filepath.length - 1)\n if (\n (filePathLast === CHAR_FORWARD_SLASH) &&\n resolved[resolved.length - 1] !== \"/\"\n ) {\n resolved += \"/\"\n }\n outURL.pathname = encodePathChars(resolved)\n return Effect.succeed(outURL)\n}\n\nconst percentRegEx = /%/g\nconst backslashRegEx = /\\\\/g\nconst newlineRegEx = /\\n/g\nconst carriageReturnRegEx = /\\r/g\nconst tabRegEx = /\\t/g\n\nfunction encodePathChars(filepath: string) {\n if (filepath.includes(\"%\")) {\n filepath = filepath.replace(percentRegEx, \"%25\")\n }\n if (filepath.includes(\"\\\\\")) {\n filepath = filepath.replace(backslashRegEx, \"%5C\")\n }\n if (filepath.includes(\"\\n\")) {\n filepath = filepath.replace(newlineRegEx, \"%0A\")\n }\n if (filepath.includes(\"\\r\")) {\n filepath = filepath.replace(carriageReturnRegEx, \"%0D\")\n }\n if (filepath.includes(\"\\t\")) {\n filepath = filepath.replace(tabRegEx, \"%09\")\n }\n return filepath\n}\n\nconst posixImpl = Path.of({\n [TypeId]: TypeId,\n resolve,\n normalize(path) {\n if (path.length === 0) return \".\"\n\n const isAbsolute = path.charCodeAt(0) === 47 /*/*/\n const trailingSeparator = path.charCodeAt(path.length - 1) === 47 /*/*/\n\n // Normalize the path\n path = normalizeStringPosix(path, !isAbsolute)\n\n if (path.length === 0 && !isAbsolute) path = \".\"\n if (path.length > 0 && trailingSeparator) path += \"/\"\n\n if (isAbsolute) return \"/\" + path\n return path\n },\n\n isAbsolute(path) {\n return path.length > 0 && path.charCodeAt(0) === 47 /*/*/\n },\n\n join() {\n if (arguments.length === 0) {\n return \".\"\n }\n let joined\n for (let i = 0; i < arguments.length; ++i) {\n const arg = arguments[i]\n if (arg.length > 0) {\n if (joined === undefined) {\n joined = arg\n } else {\n joined += \"/\" + arg\n }\n }\n }\n if (joined === undefined) {\n return \".\"\n }\n return posixImpl.normalize(joined)\n },\n\n relative(from, to) {\n if (from === to) return \"\"\n\n from = posixImpl.resolve(from)\n to = posixImpl.resolve(to)\n\n if (from === to) return \"\"\n\n // Trim any leading backslashes\n let fromStart = 1\n for (; fromStart < from.length; ++fromStart) {\n if (from.charCodeAt(fromStart) !== 47 /*/*/) {\n break\n }\n }\n const fromEnd = from.length\n const fromLen = fromEnd - fromStart\n\n // Trim any leading backslashes\n let toStart = 1\n for (; toStart < to.length; ++toStart) {\n if (to.charCodeAt(toStart) !== 47 /*/*/) {\n break\n }\n }\n const toEnd = to.length\n const toLen = toEnd - toStart\n\n // Compare paths to find the longest common path from root\n const length = fromLen < toLen ? fromLen : toLen\n let lastCommonSep = -1\n let i = 0\n for (; i <= length; ++i) {\n if (i === length) {\n if (toLen > length) {\n if (to.charCodeAt(toStart + i) === 47 /*/*/) {\n // We get here if `from` is the exact base path for `to`.\n // For example: from='/foo/bar'; to='/foo/bar/baz'\n return to.slice(toStart + i + 1)\n } else if (i === 0) {\n // We get here if `from` is the root\n // For example: from='/'; to='/foo'\n return to.slice(toStart + i)\n }\n } else if (fromLen > length) {\n if (from.charCodeAt(fromStart + i) === 47 /*/*/) {\n // We get here if `to` is the exact base path for `from`.\n // For example: from='/foo/bar/baz'; to='/foo/bar'\n lastCommonSep = i\n } else if (i === 0) {\n // We get here if `to` is the root.\n // For example: from='/foo'; to='/'\n lastCommonSep = 0\n }\n }\n break\n }\n const fromCode = from.charCodeAt(fromStart + i)\n const toCode = to.charCodeAt(toStart + i)\n if (fromCode !== toCode) {\n break\n } else if (fromCode === 47 /*/*/) {\n lastCommonSep = i\n }\n }\n\n let out = \"\"\n // Generate the relative path based on the path difference between `to`\n // and `from`\n for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {\n if (i === fromEnd || from.charCodeAt(i) === 47 /*/*/) {\n if (out.length === 0) {\n out += \"..\"\n } else {\n out += \"/..\"\n }\n }\n }\n\n // Lastly, append the rest of the destination (`to`) path that comes after\n // the common path parts\n if (out.length > 0) {\n return out + to.slice(toStart + lastCommonSep)\n } else {\n toStart += lastCommonSep\n if (to.charCodeAt(toStart) === 47 /*/*/) {\n ++toStart\n }\n return to.slice(toStart)\n }\n },\n\n dirname(path) {\n if (path.length === 0) return \".\"\n let code = path.charCodeAt(0)\n const hasRoot = code === 47 /*/*/\n let end = -1\n let matchedSlash = true\n for (let i = path.length - 1; i >= 1; --i) {\n code = path.charCodeAt(i)\n if (code === 47 /*/*/) {\n if (!matchedSlash) {\n end = i\n break\n }\n } else {\n // We saw the first non-path separator\n matchedSlash = false\n }\n }\n\n if (end === -1) return hasRoot ? \"/\" : \".\"\n if (hasRoot && end === 1) return \"//\"\n return path.slice(0, end)\n },\n\n basename(path, ext) {\n let start = 0\n let end = -1\n let matchedSlash = true\n let i\n\n if (ext !== undefined && ext.length > 0 && ext.length <= path.length) {\n if (ext.length === path.length && ext === path) return \"\"\n let extIdx = ext.length - 1\n let firstNonSlashEnd = -1\n for (i = path.length - 1; i >= 0; --i) {\n const code = path.charCodeAt(i)\n if (code === 47 /*/*/) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n start = i + 1\n break\n }\n } else {\n if (firstNonSlashEnd === -1) {\n // We saw the first non-path separator, remember this index in case\n // we need it if the extension ends up not matching\n matchedSlash = false\n firstNonSlashEnd = i + 1\n }\n if (extIdx >= 0) {\n // Try to match the explicit extension\n if (code === ext.charCodeAt(extIdx)) {\n if (--extIdx === -1) {\n // We matched the extension, so mark this as the end of our path\n // component\n end = i\n }\n } else {\n // Extension does not match, so our result is the entire path\n // component\n extIdx = -1\n end = firstNonSlashEnd\n }\n }\n }\n }\n\n if (start === end) end = firstNonSlashEnd\n else if (end === -1) end = path.length\n return path.slice(start, end)\n } else {\n for (i = path.length - 1; i >= 0; --i) {\n if (path.charCodeAt(i) === 47 /*/*/) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n start = i + 1\n break\n }\n } else if (end === -1) {\n // We saw the first non-path separator, mark this as the end of our\n // path component\n matchedSlash = false\n end = i + 1\n }\n }\n\n if (end === -1) return \"\"\n return path.slice(start, end)\n }\n },\n\n extname(path) {\n let startDot = -1\n let startPart = 0\n let end = -1\n let matchedSlash = true\n // Track the state of characters (if any) we see before our first dot and\n // after any path separator we find\n let preDotState = 0\n for (let i = path.length - 1; i >= 0; --i) {\n const code = path.charCodeAt(i)\n if (code === 47 /*/*/) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n startPart = i + 1\n break\n }\n continue\n }\n if (end === -1) {\n // We saw the first non-path separator, mark this as the end of our\n // extension\n matchedSlash = false\n end = i + 1\n }\n if (code === 46 /*.*/) {\n // If this is our first dot, mark it as the start of our extension\n if (startDot === -1) {\n startDot = i\n } else if (preDotState !== 1) {\n preDotState = 1\n }\n } else if (startDot !== -1) {\n // We saw a non-dot and non-path separator before our dot, so we should\n // have a good chance at having a non-empty extension\n preDotState = -1\n }\n }\n\n if (\n startDot === -1 || end === -1 ||\n // We saw a non-dot character immediately before the dot\n preDotState === 0 ||\n // The (right-most) trimmed path component is exactly '..'\n preDotState === 1 && startDot === end - 1 && startDot === startPart + 1\n ) {\n return \"\"\n }\n return path.slice(startDot, end)\n },\n\n format: function format(pathObject) {\n if (pathObject === null || typeof pathObject !== \"object\") {\n throw new TypeError(\"The \\\"pathObject\\\" argument must be of type Object. Received type \" + typeof pathObject)\n }\n return _format(\"/\", pathObject)\n },\n\n parse(path) {\n const ret = { root: \"\", dir: \"\", base: \"\", ext: \"\", name: \"\" }\n if (path.length === 0) return ret\n let code = path.charCodeAt(0)\n const isAbsolute = code === 47 /*/*/\n let start\n if (isAbsolute) {\n ret.root = \"/\"\n start = 1\n } else {\n start = 0\n }\n let startDot = -1\n let startPart = 0\n let end = -1\n let matchedSlash = true\n let i = path.length - 1\n\n // Track the state of characters (if any) we see before our first dot and\n // after any path separator we find\n let preDotState = 0\n\n // Get non-dir info\n for (; i >= start; --i) {\n code = path.charCodeAt(i)\n if (code === 47 /*/*/) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n startPart = i + 1\n break\n }\n continue\n }\n if (end === -1) {\n // We saw the first non-path separator, mark this as the end of our\n // extension\n matchedSlash = false\n end = i + 1\n }\n if (code === 46 /*.*/) {\n // If this is our first dot, mark it as the start of our extension\n if (startDot === -1) startDot = i\n else if (preDotState !== 1) preDotState = 1\n } else if (startDot !== -1) {\n // We saw a non-dot and non-path separator before our dot, so we should\n // have a good chance at having a non-empty extension\n preDotState = -1\n }\n }\n\n if (\n startDot === -1 || end === -1 ||\n // We saw a non-dot character immediately before the dot\n preDotState === 0 ||\n // The (right-most) trimmed path component is exactly '..'\n preDotState === 1 && startDot === end - 1 && startDot === startPart + 1\n ) {\n if (end !== -1) {\n if (startPart === 0 && isAbsolute) ret.base = ret.name = path.slice(1, end)\n else ret.base = ret.name = path.slice(startPart, end)\n }\n } else {\n if (startPart === 0 && isAbsolute) {\n ret.name = path.slice(1, startDot)\n ret.base = path.slice(1, end)\n } else {\n ret.name = path.slice(startPart, startDot)\n ret.base = path.slice(startPart, end)\n }\n ret.ext = path.slice(startDot, end)\n }\n\n if (startPart > 0) ret.dir = path.slice(0, startPart - 1)\n else if (isAbsolute) ret.dir = \"/\"\n\n return ret\n },\n\n sep: \"/\",\n fromFileUrl,\n toFileUrl,\n toNamespacedPath: identity\n})\n\n/** @internal */\nexport const layer = Layer.succeed(Path, posixImpl)\n","/**\n * @since 1.0.0\n */\n\nimport type { Tag } from \"effect/Context\"\nimport type { Effect } from \"effect/Effect\"\nimport type { Layer } from \"effect/Layer\"\nimport type { BadArgument } from \"./Error.js\"\nimport * as internal from \"./internal/path.js\"\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const TypeId: unique symbol = internal.TypeId\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 1.0.0\n * @category model\n */\nexport interface Path {\n readonly [TypeId]: TypeId\n readonly sep: string\n readonly basename: (path: string, suffix?: string) => string\n readonly dirname: (path: string) => string\n readonly extname: (path: string) => string\n readonly format: (pathObject: Partial<Path.Parsed>) => string\n readonly fromFileUrl: (url: URL) => Effect<string, BadArgument>\n readonly isAbsolute: (path: string) => boolean\n readonly join: (...paths: ReadonlyArray<string>) => string\n readonly normalize: (path: string) => string\n readonly parse: (path: string) => Path.Parsed\n readonly relative: (from: string, to: string) => string\n readonly resolve: (...pathSegments: ReadonlyArray<string>) => string\n readonly toFileUrl: (path: string) => Effect<URL, BadArgument>\n readonly toNamespacedPath: (path: string) => string\n}\n\n/**\n * @since 1.0.0\n */\nexport declare namespace Path {\n /**\n * @since 1.0.0\n * @category model\n */\n export interface Parsed {\n readonly root: string\n readonly dir: string\n readonly base: string\n readonly ext: string\n readonly name: string\n }\n}\n\n/**\n * @since 1.0.0\n * @category tag\n */\nexport const Path: Tag<Path, Path> = internal.Path\n\n/**\n * An implementation of the Path interface that can be used in all environments\n * (including browsers).\n *\n * It uses the POSIX standard for paths.\n *\n * @since 1.0.0\n * @category layer\n */\nexport const layer: Layer<Path> = internal.layer\n","import * as Effect from \"effect/Effect\"\nimport * as FiberRef from \"effect/FiberRef\"\nimport { dual } from \"effect/Function\"\nimport { globalValue } from \"effect/GlobalValue\"\nimport * as Option from \"effect/Option\"\nimport type { HttpApp, PreResponseHandler } from \"../HttpApp.js\"\n\n/** @internal */\nexport const currentPreResponseHandlers: FiberRef.FiberRef<Option.Option<PreResponseHandler>> = globalValue(\n Symbol.for(\"@effect/platform/HttpApp/preResponseHandlers\"),\n () => FiberRef.unsafeMake<Option.Option<PreResponseHandler>>(Option.none())\n)\n\n/** @internal */\nexport const appendPreResponseHandler: (handler: PreResponseHandler) => Effect.Effect<void> = (\n handler: PreResponseHandler\n) =>\n FiberRef.update(\n currentPreResponseHandlers,\n Option.match({\n onNone: () => Option.some(handler),\n onSome: (prev) =>\n Option.some((request, response) =>\n Effect.flatMap(prev(request, response), (response) => handler(request, response))\n )\n })\n )\n\n/** @internal */\nexport const withPreResponseHandler = dual<\n (handler: PreResponseHandler) => <A, E, R>(self: HttpApp<A, E, R>) => HttpApp<A, E, R>,\n <A, E, R>(self: HttpApp<A, E, R>, handler: PreResponseHandler) => HttpApp<A, E, R>\n>(2, (self, handler) =>\n Effect.locallyWith(\n self,\n currentPreResponseHandlers,\n Option.match({\n onNone: () => Option.some(handler),\n onSome: (prev) =>\n Option.some((request, response) =>\n Effect.flatMap(prev(request, response), (response) => handler(request, response))\n )\n })\n ))\n","import * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as FiberRef from \"effect/FiberRef\"\nimport { constFalse, dual } from \"effect/Function\"\nimport * as Function from \"effect/Function\"\nimport { globalValue } from \"effect/GlobalValue\"\nimport * as Layer from \"effect/Layer\"\nimport * as Option from \"effect/Option\"\nimport type * as Predicate from \"effect/Predicate\"\nimport type { ReadonlyRecord } from \"effect/Record\"\nimport * as Headers from \"../Headers.js\"\nimport type * as App from \"../HttpApp.js\"\nimport type * as Middleware from \"../HttpMiddleware.js\"\nimport * as ServerError from \"../HttpServerError.js\"\nimport * as ServerRequest from \"../HttpServerRequest.js\"\nimport * as ServerResponse from \"../HttpServerResponse.js\"\nimport type { HttpServerResponse } from \"../HttpServerResponse.js\"\nimport * as TraceContext from \"../HttpTraceContext.js\"\nimport * as internalHttpApp from \"./httpApp.js\"\n\n/** @internal */\nexport const make = <M extends Middleware.HttpMiddleware>(middleware: M): M => middleware\n\n/** @internal */\nexport const loggerDisabled = globalValue(\n Symbol.for(\"@effect/platform/HttpMiddleware/loggerDisabled\"),\n () => FiberRef.unsafeMake(false)\n)\n\n/** @internal */\nexport const withLoggerDisabled = <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n Effect.zipRight(\n FiberRef.set(loggerDisabled, true),\n self\n )\n\n/** @internal */\nexport const currentTracerDisabledWhen = globalValue(\n Symbol.for(\"@effect/platform/HttpMiddleware/tracerDisabledWhen\"),\n () => FiberRef.unsafeMake<Predicate.Predicate<ServerRequest.HttpServerRequest>>(constFalse)\n)\n\n/** @internal */\nexport const withTracerDisabledWhen = dual<\n (\n predicate: Predicate.Predicate<ServerRequest.HttpServerRequest>\n ) => <A, E, R>(layer: Layer.Layer<A, E, R>) => Layer.Layer<A, E, R>,\n <A, E, R>(\n layer: Layer.Layer<A, E, R>,\n predicate: Predicate.Predicate<ServerRequest.HttpServerRequest>\n ) => Layer.Layer<A, E, R>\n>(2, (self, pred) => Layer.locally(self, currentTracerDisabledWhen, pred))\n\n/** @internal */\nexport const withTracerDisabledWhenEffect = dual<\n (\n predicate: Predicate.Predicate<ServerRequest.HttpServerRequest>\n ) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n predicate: Predicate.Predicate<ServerRequest.HttpServerRequest>\n ) => Effect.Effect<A, E, R>\n>(2, (self, pred) => Effect.locally(self, currentTracerDisabledWhen, pred))\n\n/** @internal */\nexport const withTracerDisabledForUrls = dual<\n (\n urls: ReadonlyArray<string>\n ) => <A, E, R>(layer: Layer.Layer<A, E, R>) => Layer.Layer<A, E, R>,\n <A, E, R>(\n layer: Layer.Layer<A, E, R>,\n urls: ReadonlyArray<string>\n ) => Layer.Layer<A, E, R>\n>(2, (self, urls) => Layer.locally(self, currentTracerDisabledWhen, (req) => urls.includes(req.url)))\n\n/** @internal */\nexport const SpanNameGenerator = Context.Reference<Middleware.SpanNameGenerator>()(\n \"@effect/platform/HttpMiddleware/SpanNameGenerator\",\n {\n defaultValue: () => (request: ServerRequest.HttpServerRequest) => `http.server ${request.method}`\n }\n)\n\n/** @internal */\nexport const withSpanNameGenerator = dual<\n (\n f: (request: ServerRequest.HttpServerRequest) => string\n ) => <A, E, R>(layer: Layer.Layer<A, E, R>) => Layer.Layer<A, E, R>,\n <A, E, R>(\n layer: Layer.Layer<A, E, R>,\n f: (request: ServerRequest.HttpServerRequest) => string\n ) => Layer.Layer<A, E, R>\n>(2, (self, f) => Layer.provide(self, Layer.succeed(SpanNameGenerator, f)))\n\n/** @internal */\nexport const logger = make((httpApp) => {\n let counter = 0\n return Effect.withFiberRuntime((fiber) => {\n const request = Context.unsafeGet(fiber.currentContext, ServerRequest.HttpServerRequest)\n return Effect.withLogSpan(\n Effect.flatMap(Effect.exit(httpApp), (exit) => {\n if (fiber.getFiberRef(loggerDisabled)) {\n return exit\n } else if (exit._tag === \"Failure\") {\n const [response, cause] = ServerError.causeResponseStripped(exit.cause)\n return Effect.zipRight(\n Effect.annotateLogs(Effect.log(cause._tag === \"Some\" ? cause.value : \"Sent HTTP Response\"), {\n \"http.method\": request.method,\n \"http.url\": request.url,\n \"http.status\": response.status\n }),\n exit\n )\n }\n return Effect.zipRight(\n Effect.annotateLogs(Effect.log(\"Sent HTTP response\"), {\n \"http.method\": request.method,\n \"http.url\": request.url,\n \"http.status\": exit.value.status\n }),\n exit\n )\n }),\n `http.span.${++counter}`\n )\n })\n})\n\n/** @internal */\nexport const tracer = make((httpApp) =>\n Effect.withFiberRuntime((fiber) => {\n const request = Context.unsafeGet(fiber.currentContext, ServerRequest.HttpServerRequest)\n const disabled = fiber.getFiberRef(currentTracerDisabledWhen)(request)\n if (disabled) {\n return httpApp\n }\n const url = Option.getOrUndefined(ServerRequest.toURL(request))\n if (url !== undefined && (url.username !== \"\" || url.password !== \"\")) {\n url.username = \"REDACTED\"\n url.password = \"REDACTED\"\n }\n const redactedHeaderNames = fiber.getFiberRef(Headers.currentRedactedNames)\n const redactedHeaders = Headers.redact(request.headers, redactedHeaderNames)\n const nameGenerator = Context.get(fiber.currentContext, SpanNameGenerator)\n return Effect.useSpan(\n nameGenerator(request),\n {\n parent: Option.getOrUndefined(TraceContext.fromHeaders(request.headers)),\n kind: \"server\",\n captureStackTrace: false\n },\n (span) => {\n span.attribute(\"http.request.method\", request.method)\n if (url !== undefined) {\n span.attribute(\"url.full\", url.toString())\n span.attribute(\"url.path\", url.pathname)\n const query = url.search.slice(1)\n if (query !== \"\") {\n span.attribute(\"url.query\", url.search.slice(1))\n }\n span.attribute(\"url.scheme\", url.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 redactedHeaders) {\n span.attribute(`http.request.header.${name}`, String(redactedHeaders[name]))\n }\n if (request.remoteAddress._tag === \"Some\") {\n span.attribute(\"client.address\", request.remoteAddress.value)\n }\n return Effect.flatMap(\n Effect.exit(Effect.withParentSpan(httpApp, span)),\n (exit) => {\n const response = ServerError.exitResponse(exit)\n span.attribute(\"http.response.status_code\", response.status)\n const redactedHeaders = Headers.redact(response.headers, redactedHeaderNames)\n for (const name in redactedHeaders) {\n span.attribute(`http.response.header.${name}`, String(redactedHeaders[name]))\n }\n return exit\n }\n )\n }\n )\n })\n)\n\n/** @internal */\nexport const xForwardedHeaders = make((httpApp) =>\n Effect.updateService(httpApp, ServerRequest.HttpServerRequest, (request) => {\n const host = request.headers[\"x-forwarded-host\"]\n const remoteAddress = request.headers[\"x-forwarded-for\"]?.split(\",\")[0].trim()\n return request.modify({\n headers: host !== undefined ? Headers.set(request.headers, \"host\", host) : undefined,\n remoteAddress\n })\n })\n)\n\n/** @internal */\nexport const searchParamsParser = <E, R>(httpApp: App.Default<E, R>) =>\n Effect.withFiberRuntime<\n HttpServerResponse,\n E,\n ServerRequest.HttpServerRequest | Exclude<R, ServerRequest.ParsedSearchParams>\n >((fiber) => {\n const context = fiber.currentContext\n const request = Context.unsafeGet(context, ServerRequest.HttpServerRequest)\n const params = ServerRequest.searchParamsFromURL(new URL(request.originalUrl))\n return Effect.locally(\n httpApp,\n FiberRef.currentContext,\n Context.add(context, ServerRequest.ParsedSearchParams, params)\n ) as any\n })\n\n/** @internal */\nexport const cors = (options?: {\n readonly allowedOrigins?: ReadonlyArray<string> | Predicate.Predicate<string> | undefined\n readonly allowedMethods?: ReadonlyArray<string> | undefined\n readonly allowedHeaders?: ReadonlyArray<string> | undefined\n readonly exposedHeaders?: ReadonlyArray<string> | undefined\n readonly maxAge?: number | undefined\n readonly credentials?: boolean | undefined\n}) => {\n const opts = {\n allowedOrigins: [],\n allowedMethods: [\"GET\", \"HEAD\", \"PUT\", \"PATCH\", \"POST\", \"DELETE\"],\n allowedHeaders: [],\n exposedHeaders: [],\n credentials: false,\n ...options\n }\n\n const isAllowedOrigin = typeof opts.allowedOrigins === \"function\"\n ? opts.allowedOrigins\n : (origin: string) => (opts.allowedOrigins as ReadonlyArray<string>).includes(origin)\n\n const allowOrigin = typeof opts.allowedOrigins === \"function\" || opts.allowedOrigins.length > 1 ?\n (originHeader: string): ReadonlyRecord<string, string> | undefined => {\n if (isAllowedOrigin(originHeader)) {\n return {\n \"access-control-allow-origin\": originHeader,\n vary: \"Origin\"\n }\n }\n return undefined\n } :\n opts.allowedOrigins.length === 1 ?\n Function.constant({\n \"access-control-allow-origin\": opts.allowedOrigins[0],\n vary: \"Origin\"\n }) :\n Function.constant({\n \"access-control-allow-origin\": \"*\"\n })\n\n const allowMethods = opts.allowedMethods.length > 0\n ? { \"access-control-allow-methods\": opts.allowedMethods.join(\", \") }\n : undefined\n\n const allowCredentials = opts.credentials\n ? { \"access-control-allow-credentials\": \"true\" }\n : undefined\n\n const allowHeaders = (\n accessControlRequestHeaders: string | undefined\n ): ReadonlyRecord<string, string> | undefined => {\n if (opts.allowedHeaders.length === 0 && accessControlRequestHeaders) {\n return {\n vary: \"Access-Control-Request-Headers\",\n \"access-control-allow-headers\": accessControlRequestHeaders\n }\n }\n\n if (opts.allowedHeaders) {\n return {\n \"access-control-allow-headers\": opts.allowedHeaders.join(\",\")\n }\n }\n\n return undefined\n }\n\n const exposeHeaders = opts.exposedHeaders.length > 0\n ? { \"access-control-expose-headers\": opts.exposedHeaders.join(\",\") }\n : undefined\n\n const maxAge = opts.maxAge\n ? { \"access-control-max-age\": opts.maxAge.toString() }\n : undefined\n\n const headersFromRequest = (request: ServerRequest.HttpServerRequest) => {\n const origin = request.headers[\"origin\"]\n return Headers.unsafeFromRecord({\n ...allowOrigin(origin),\n ...allowCredentials,\n ...exposeHeaders\n })\n }\n\n const headersFromRequestOptions = (request: ServerRequest.HttpServerRequest) => {\n const origin = request.headers[\"origin\"]\n const accessControlRequestHeaders = request.headers[\"access-control-request-headers\"]\n return Headers.unsafeFromRecord({\n ...allowOrigin(origin),\n ...allowCredentials,\n ...exposeHeaders,\n ...allowMethods,\n ...allowHeaders(accessControlRequestHeaders),\n ...maxAge\n })\n }\n\n const preResponseHandler = (request: ServerRequest.HttpServerRequest, response: HttpServerResponse) =>\n Effect.succeed(ServerResponse.setHeaders(response, headersFromRequest(request)))\n\n return <E, R>(httpApp: App.Default<E, R>): App.Default<E, R> =>\n Effect.withFiberRuntime((fiber) => {\n const request = Context.unsafeGet(fiber.currentContext, ServerRequest.HttpServerRequest)\n if (request.method === \"OPTIONS\") {\n return Effect.succeed(ServerResponse.empty({\n status: 204,\n headers: headersFromRequestOptions(request)\n }))\n }\n return Effect.zipRight(internalHttpApp.appendPreResponseHandler(preResponseHandler), httpApp)\n })\n}\n","import { Context, Effect, pipe } from 'effect';\n\n// biome-ignore lint/suspicious/noExplicitAny: type inference pattern\ntype InferClass<T> = T extends new (...args: any[]) => infer R ? R : never;\n\nexport function extract<\n\t// biome-ignore lint/suspicious/noExplicitAny: type inference pattern\n\tP extends any[],\n\tA,\n\tE,\n\tR,\n\t// biome-ignore lint/suspicious/noExplicitAny: type inference pattern\n\tINFERRED_EXCLUDED extends Context.Tag<any, any> = never,\n\tEXCLUDED = InferClass<INFERRED_EXCLUDED>,\n>(\n\teffect: (...params: P) => Effect.Effect<A, E, R>,\n\toptions?: { exclude?: Array<INFERRED_EXCLUDED> },\n): Effect.Effect<\n\t(...params: P) => Effect.Effect<A, E, Extract<R, EXCLUDED>>,\n\tnever,\n\tExclude<R, EXCLUDED>\n> {\n\t// @ts-expect-error quite hard to type, check unit test\n\treturn Effect.gen(function* () {\n\t\tconst runtime = yield* Effect.runtime();\n\n\t\tconst context = runtime.context.pipe(\n\t\t\toptions?.exclude ? Context.omit(...options.exclude) : (e) => e,\n\t\t) as Context.Context<Exclude<R, EXCLUDED>>;\n\n\t\treturn (...params: P) => pipe(effect(...params), Effect.provide(context));\n\t});\n}\n","import type { Cron } from 'effect';\nimport { Option } from 'effect';\n\nfunction fieldToString(field: ReadonlySet<number>, max: number) {\n\tif (field.size === 0 || field.size === max) return '*';\n\treturn Array.from(field)\n\t\t.sort((a, b) => a - b)\n\t\t.join(',');\n}\n\nexport function cronToString(cron: Cron.Cron) {\n\tconst minutes = fieldToString(cron.minutes, 60);\n\tconst hours = fieldToString(cron.hours, 24);\n\tconst days = fieldToString(cron.days, 31);\n\tconst months = fieldToString(cron.months, 12);\n\tconst weekdays = fieldToString(cron.weekdays, 7);\n\n\tconst expr = `${minutes} ${hours} ${days} ${months} ${weekdays}`;\n\tif (Option.isSome(cron.tz)) return `TZ=${cron.tz.value} ${expr}`;\n\treturn expr;\n}\n","import { Duration, Effect } from 'effect';\nimport { runPromiseUnwrapped } from '../../run-promise-unwrapped';\nimport { InngestError } from './index';\n\ntype OriginalStep = {\n\trun: (id: string, fn: () => Promise<unknown>) => Promise<unknown>;\n\tsleep: (id: string, time: number | string) => Promise<void>;\n\tsleepUntil: (id: string, time: Date | string) => Promise<void>;\n\tinvoke: (id: string, opts: unknown) => Promise<unknown>;\n\twaitForEvent: (id: string, opts: unknown) => Promise<unknown>;\n\tsendEvent: (id: string, payload: unknown) => Promise<unknown>;\n};\n\nexport type WrappedStep<TStep> = ReturnType<typeof wrapStep<TStep>>;\n\nexport function wrapStep<TStep>(step: TStep) {\n\tconst s = step as unknown as OriginalStep;\n\n\treturn {\n\t\trun: <A, E>(id: string, fn: () => Effect.Effect<A, E, never>) =>\n\t\t\tEffect.tryPromise({\n\t\t\t\ttry: () => s.run(id, () => runPromiseUnwrapped(fn())),\n\t\t\t\tcatch: (cause) =>\n\t\t\t\t\tnew InngestError({ message: `Step \"${id}\" failed`, cause }),\n\t\t\t}) as Effect.Effect<A, InngestError>,\n\n\t\tsleep: (id: string, duration: Duration.DurationInput) =>\n\t\t\tEffect.tryPromise({\n\t\t\t\ttry: () => s.sleep(id, Duration.toMillis(Duration.decode(duration))),\n\t\t\t\tcatch: (cause) =>\n\t\t\t\t\tnew InngestError({\n\t\t\t\t\t\tmessage: `Step sleep \"${id}\" failed`,\n\t\t\t\t\t\tcause,\n\t\t\t\t\t}),\n\t\t\t}),\n\n\t\tsleepUntil: (id: string, time: Date | string) =>\n\t\t\tEffect.tryPromise({\n\t\t\t\ttry: () => s.sleepUntil(id, time),\n\t\t\t\tcatch: (cause) =>\n\t\t\t\t\tnew InngestError({\n\t\t\t\t\t\tmessage: `Step sleepUntil \"${id}\" failed`,\n\t\t\t\t\t\tcause,\n\t\t\t\t\t}),\n\t\t\t}),\n\n\t\tinvoke: <TResult = unknown>(id: string, opts: unknown) =>\n\t\t\tEffect.tryPromise({\n\t\t\t\ttry: () => s.invoke(id, opts),\n\t\t\t\tcatch: (cause) =>\n\t\t\t\t\tnew InngestError({\n\t\t\t\t\t\tmessage: `Step invoke \"${id}\" failed`,\n\t\t\t\t\t\tcause,\n\t\t\t\t\t}),\n\t\t\t}) as Effect.Effect<TResult, InngestError>,\n\n\t\twaitForEvent: <TEvent = unknown>(id: string, opts: unknown) =>\n\t\t\tEffect.tryPromise({\n\t\t\t\ttry: () => s.waitForEvent(id, opts),\n\t\t\t\tcatch: (cause) =>\n\t\t\t\t\tnew InngestError({\n\t\t\t\t\t\tmessage: `Step waitForEvent \"${id}\" failed`,\n\t\t\t\t\t\tcause,\n\t\t\t\t\t}),\n\t\t\t}) as Effect.Effect<TEvent | null, InngestError>,\n\n\t\tsendEvent: (id: string, payload: unknown) =>\n\t\t\tEffect.tryPromise({\n\t\t\t\ttry: () => s.sendEvent(id, payload),\n\t\t\t\tcatch: (cause) =>\n\t\t\t\t\tnew InngestError({\n\t\t\t\t\t\tmessage: `Step sendEvent \"${id}\" failed`,\n\t\t\t\t\t\tcause,\n\t\t\t\t\t}),\n\t\t\t}) as Effect.Effect<{ ids: string[] }, InngestError>,\n\t};\n}\n","import { Cause, Effect, Exit } from 'effect';\n\n/**\n * A simple wrapper around Effect.runPromiseExit that throws the error if it's a failure\n **/\nexport async function runPromiseUnwrapped<A, E>(\n\teffect: Effect.Effect<A, E, never>,\n) {\n\tconst exit = await Effect.runPromiseExit(effect);\n\treturn Exit.match(exit, {\n\t\tonSuccess: (value) => value,\n\t\tonFailure: (cause) => {\n\t\t\tthrow Cause.isFailType(cause) ? cause.error : cause;\n\t\t},\n\t});\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA,2BAAAA;AAAA,EAAA,iBAAAC;AAAA,EAAA;AAAA;AAAA;;;ACGA,eAA0B;AAC1B,aAAwB;AACxB,sBAA+B;AAC/B,kBAA6B;AAC7B,aAAwB;AACxB,sBAA6C;AAC7C,IAAAC,aAA2B;AAC3B,aAAwB;;;ACNxB,WAAsB;AACtB,gBAA2B;AAC3B,aAAwB;AAOjB,IAAMC,SAAwBC,uBAAOC,IAAI,wBAAwB;AAkBjE,IAAMC,cAAcA,CACzBC,QACAC,SAOgB;EAEhB,MAAMC,aAAkBC,WAAS;IACtBC,OAAOH;;AAElB;AAAEC,OAAKG,UAAkBL,MAAM,IAAIA;AACjCE,OAAKG,UAAkBC,OAAOL;AAChC,SAAOC;AACT;AAMO,IAAMK,SAASC,gBAAOC,eAC3B,aACA,WACA,cACA,iBACA,QACA,UACA,UAAU;AAON,IAAOC,cAAP,eAA2BF,gBAAOG,mBAAyB,oCAAoC,EAAE,eAAe;EACpHC,QAAQL;EACRM,QAAeC;EACfC,aAAaP,gBAAOQ,gBAAgBF,aAAM;EAC1CG,OAAOT,gBAAOQ,gBAAgBE,aAAM;CACrC,GAAC;;;;EAIS,CAACC,MAAM,IAAmBA;;;;EAKnC,IAAIC,UAAO;AACT,WAAO,GAAG,KAAKR,MAAM,IAAI,KAAKC,MAAM,GAAG,KAAKE,cAAc,KAAK,KAAKA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WF,WAAS,WAAW,QAAiB,UAAqB;AACzD,eAAO,kBAAM;AAAA,MACZ;AAAA,MACA,WAAW,SAAS;AAAA,MAGpB,GAAI,SAAS,aAAa,QAAQ,EAAE,WAAW,SAAS,UAAU;AAAA,MAClE,GAAI,SAAS,cAAc,QAAQ;AAAA,QAClC,YAAY,SAAS;AAAA,MACtB;AAAA,MACA,GAAI,SAAS,sBAAsB,QAAQ;AAAA,QAC1C,oBAAoB,SAAS;AAAA,MAC9B;AAAA,MACA,GAAI,SAAS,YAAY,QAAQ,EAAE,UAAU,SAAS,SAAS;AAAA,MAC/D,GAAI,SAAS,aAAa,QAAQ,EAAE,WAAW,SAAS,UAAU;AAAA,IACnE,CAAC;AAAA,EACF;AAEA,QAAM,eAAe,CAAC,aACrB,sBAAO,IAAI,aAAa;AACvB,UAAM,IAAI,OAAOD;AACjB,WAAO,WAAW,GAAG,QAAQ;AAAA,EAC9B,CAAC;AAEF,QAAM,cAAc,CAAC,aACpB,sBAAO,IAAI,aAAa;AACvB,UAAM,IAAI,OAAOA;AACjB,WAAO,gBAAQ,eAAe,WAAW,GAAG,QAAQ,CAAC;AAAA,EACtD,CAAC;AAEF,SAAO;AAAA,IACN,KAAAA;AAAA,IACA,OAAO,qBAAM,OAAOA,MAAK,YAAY;AAAA,IACrC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACD;AACD;","names":["NodeInspectSymbol","TagTypeId","Predicate","TypeId","Symbol","for","TypeIdError","typeId","tag","Base","Error","_tag","prototype","name","Module","Schema","Literal","BadArgument","TaggedError","module","method","String","description","optional","cause","Defect","TypeId","message","SystemErrorReason","SystemError","reason","syscall","pathOrDescriptor","Union","Number","undefined","TypeId","Symbol","for","CookieTypeId","Symbol","for","Proto","TypeId","BaseProto","toJSON","_id","cookies","map","cookie","pipe","pipeArguments","arguments","fromReadonlyRecord","self","Object","create","fromIterable","record","name","fromSetCookie","headers","arrayHeaders","header","parseSetCookie","trim","isSome","push","value","parts","split","_","filter","length","none","firstEqual","indexOf","slice","fieldContentRegExp","test","valueEncoded","tryDecodeURIComponent","some","assign","CookieProto","options","i","part","equalIndex","key","undefined","toLowerCase","domain","replace","date","Date","isNaN","getTime","expires","maxAge","parseInt","seconds","path","priority","httpOnly","secure","partitioned","sameSite","keys","empty","isEmpty","isEmptyRecord","CookieTypeId","serializeCookie","self","str","name","valueEncoded","options","undefined","maxAge","toSeconds","Math","trunc","domain","path","priority","expires","toUTCString","httpOnly","secure","partitioned","sameSite","toSetCookieHeaders","self","Object","values","cookies","map","serializeCookie","parseHeader","header","result","strLen","length","pos","terminatorPos","indexOf","eqIdx","key","substring","trim","undefined","val","charCodeAt","tryDecodeURIComponent","str","decodeURIComponent","import_Function","Predicate","Record","Schema","String","HeadersTypeId","Symbol","for","Proto","Object","assign","create","HeadersTypeId","symbolRedactable","fiberRefs","redact","getOrDefault","currentRedactedNames","make","input","empty","Object","create","Proto","fromInput","input","undefined","Symbol","iterator","out","k","v","toLowerCase","entries","Array","isArray","join","remove","dual","self","key","out","make","modify","k","toLowerCase","name","test","Array","isArray","i","length","redact","currentRedactedNames","globalValue","unsafeMake","Context","Effect","import_Function","Inspectable","Option","Schema","Data","import_Function","Option","tag","GenericTag","Size","bytes","BigInt","bigint1024","BigInt","bigintPiB","Size","FileSystem","tag","Either","import_Function","Option","Schema","fromInput","input","parsed","fromInputNested","out","i","length","Array","isArray","keys","value","push","slice","join","entries","Symbol","iterator","fromIterable","Object","key","undefined","String","nested","k","v","TypeId","Symbol","for","MaxBodySize","Context","Reference","defaultValue","none","inspect","self","that","contentType","headers","body","includes","runSync","json","text","obj","redact","remoteAddress","toJSON","undefined","Option","fromHeaders","headers","span","w3c","_tag","b3","xb3","none","parts","split","length","some","externalSpan","traceId","spanId","sampled","w3cTraceId","w3cSpanId","version","flags","test","parseInt","Data","Effect","import_Function","Inspectable","Schema","TypeId","Symbol","for","BodyBase","TypeId","constructor","NodeInspectSymbol","toJSON","toString","format","EmptyImpl","_tag","_id","empty","StreamImpl","BodyBase","stream","contentType","contentLength","_tag","constructor","toJSON","_id","body","appendPreResponseHandler","currentPreResponseHandlers","withPreResponseHandler","Cause","Context","Effect","Exit","Layer","Option","Runtime","Stream","Predicate","stream","Effect","Stream","Context","Effect","import_Function","Inspectable","Stream","TypeId","Symbol","for","respondableSymbol","ServerResponseImpl","StructuralClass","status","statusText","cookies","body","headers","constructor","contentType","contentLength","newHeaders","toString","commit","succeed","NodeInspectSymbol","toJSON","format","_id","redact","isServerResponse","u","empty","options","fromInput","setBody","dual","self","body","headers","_tag","remove","ServerResponseImpl","status","statusText","cookies","toWeb","response","options","globalThis","Headers","isEmpty","toAdd","toSetCookieHeaders","header","append","withoutBody","Response","undefined","key","value","set","formData","toReadableStreamRuntime","stream","runtime","defaultRuntime","isServerResponse","empty","setBody","toWeb","fromWeb","response","headers","globalThis","Headers","setCookieHeaders","getSetCookie","delete","self","empty","status","statusText","cookies","fromSetCookie","body","contentType","get","setBody","stream","fromReadableStream","evaluate","onError","e","undefined","symbol","Symbol","for","isRespondable","u","hasProperty","badRequest","ServerResponse","empty","status","notFound","toResponseOrElse","u","orElse","isServerResponse","succeed","isRespondable","catchAllCause","symbol","isParseError","badRequest","isNoSuchElementException","notFound","toResponseOrElseDefect","Cause","Effect","import_GlobalValue","Option","Predicate","TypeId","Symbol","for","clientAbortFiberId","globalValue","runtime","causeResponse","cause","effect","stripped","reduce","succeed","internalServerError","empty","acc","withoutInterrupt","isInterruptType","_tag","some","toResponseOrElse","error","combineCauses","isResponse","isServerResponse","defect","toResponseOrElseDefect","none","response","fiberId","clientAbortError","serverAbortError","map","isEmptyType","sequential","die","left","right","causeResponseStripped","stripSomeDefects","internalServerResponse","status","exitResponse","exit","value","TypeId","RequestError","TypeIdError","symbol","empty","status","methodAndUrl","request","method","url","message","description","reason","RouteNotFound","TypeIdError","TypeId","constructor","options","stack","name","message","symbol","empty","status","request","method","url","ResponseError","methodAndUrl","info","response","description","reason","clientAbortFiberId","causeResponse","exitResponse","Effect","Either","Option","Runtime","Stream","hasBody","method","Channel","Context","Effect","Inspectable","Option","Schema","Stream","Channel","Chunk","Context","Effect","import_Function","Inspectable","Option","Predicate","Schema","Stream","paramRE","quotedPairRE","mediaTypeRE","mediaTypeRENoSlash","defaultContentType","value","parameters","Object","create","parse","header","withoutSlash","index","indexOf","type","slice","trim","mediaRE","test","result","toLowerCase","key","match","lastIndex","exec","length","replace","constMaxPairs","constMaxSize","State","constContinue","_tag","constNameChars","constValueChars","make","decoder","TextDecoder","state","key","headers","Object","create","value","undefined","crlf","previousChunk","pairs","size","reset","concatUint8Array","a","b","newUint8Array","Uint8Array","length","set","error","reason","write","chunk","start","endOffset","previousCursor","newChunk","end","outer","i","decode","subarray","toLowerCase","whitespace","byte","push","endPosition","makeState","needle_","needle","TextEncoder","encode","needleLength","length","indexes","i","b","undefined","push","firstByte","previousChunk","previousChunkLength","matchIndex","make","callback","seed","state","makeIndexOf","globalThis","chunk","fromIndex","Buffer","prototype","indexOf","call","skipTable","Uint8Array","fill","lastIndex","lengthTotal","j","k","write","chunkLength","newChunk","set","pos","match","subarray","earliestIndex","len","index","end","State","errInvalidDisposition","_tag","errEndNotReached","errMaxParts","limit","errMaxTotalSize","errMaxPartSize","errMaxFieldSize","constCR","TextEncoder","encode","defaultIsFile","info","filename","undefined","contentType","parseBoundary","headers","parse","parameters","boundary","noopOnChunk","_chunk","make","onFile","onPart","onField","onError","onDone","isFile","maxParts","Infinity","maxTotalSize","maxPartSize","maxFieldSize","write","end","state","index","parts","onChunk","headerSkip","partSize","totalSize","fieldChunks","fieldSize","skipBody","body","headerParser","split","chunk","length","buf","Uint8Array","offset","i","set","result","error","contentDisposition","value","encodedFilename","decodeURIComponent","name","contentTypeParameters","contentDispositionParameters","endPosition","subarray","push","utf8Decoder","TextDecoder","getDecoder","charset","decodeField","decode","make","defaultIsFile","decodeField","import_Context","Effect","import_Function","Layer","TypeId","Symbol","for","Path","GenericTag","normalizeStringPosix","path","allowAboveRoot","res","lastSegmentLength","lastSlash","dots","code","i","length","charCodeAt","lastSlashIndex","lastIndexOf","slice","_format","sep","pathObject","dir","root","base","name","ext","fromFileUrl","url","protocol","fail","BadArgument","module","method","description","hostname","pathname","n","third","codePointAt","succeed","decodeURIComponent","resolve","resolvedPath","resolvedAbsolute","cwd","undefined","arguments","process","globalThis","CHAR_FORWARD_SLASH","toFileUrl","filepath","outURL","URL","resolved","filePathLast","encodePathChars","percentRegEx","backslashRegEx","newlineRegEx","carriageReturnRegEx","tabRegEx","includes","replace","posixImpl","of","normalize","isAbsolute","trailingSeparator","join","joined","arg","relative","from","to","fromStart","fromEnd","fromLen","toStart","toEnd","toLen","lastCommonSep","fromCode","toCode","out","dirname","hasRoot","end","matchedSlash","basename","start","extIdx","firstNonSlashEnd","extname","startDot","startPart","preDotState","format","TypeError","parse","ret","toNamespacedPath","identity","Path","TypeId","Symbol","for","ErrorTypeId","Symbol","for","MultipartError","Schema","TaggedError","reason","Literal","cause","Defect","message","makeConfig","headers","withFiberRuntime","fiber","mimeTypes","get","currentContext","FieldMimeTypes","succeed","maxParts","getOrUndefined","MaxParts","maxFieldSize","Number","MaxFieldSize","maxPartSize","MaxFileSize","pipe","map","maxTotalSize","MaxBodySize","isFile","length","undefined","info","some","_","contentType","includes","defaultIsFile","makeChannel","bufferSize","acquireUseRelease","all","make","config","mailbox","partsBuffer","exit","none","input","awaitRead","void","emit","element","offer","error","cause","failCause","end","done","_value","parser","onField","value","push","FieldImpl","name","decodeField","onFile","chunks","finished","take","suspend","zipRight","pump","chunk","unsafeFromArray","write","FileImpl","onError","error_","fail","convertError","onDone","flatMap","takeAll","sync","Chunk","forEach","partsChannel","_tag","writeExit","embedInput","shutdown","self","limit","MultipartError","reason","PartBase","Class","TypeId","constructor","key","toJSON","_id","content","contentEffect","channel","filename","fromChannel","pipeTo","collectUint8Array","run","mapError","defaultWriteFile","path","file","FileSystem","fs","sink","Channel","accumulator","Uint8Array","loop","readWithCause","onInput","newAccumulator","set","onFailure","toPersisted","stream","writeFile","gen","path_","Path","dir","makeTempDirectoryScoped","persisted","Object","create","runForEach","part","join","basename","slice","filePart","PersistedFileImpl","Array","isArray","catchTags","SystemError","BadArgument","MaxParts","Context","Reference","defaultValue","none","MaxFieldSize","Context","Reference","defaultValue","constant","FileSystem","Size","MaxFileSize","Context","Reference","defaultValue","none","FieldMimeTypes","Context","Reference","defaultValue","constant","Chunk","make","TypeId","Symbol","for","serverRequestTag","Context","GenericTag","fromWeb","request","ServerRequestImpl","removeHost","url","index","indexOf","slice","Class","source","headersOverride","remoteAddressOverride","TypeId","constructor","toJSON","inspect","_id","method","originalUrl","modify","options","headers","remoteAddress","toUpperCase","some","none","fromInput","cachedCookies","cookies","parseHeader","cookie","stream","body","fromReadableStream","cause","RequestError","reason","fail","description","textEffect","text","runSync","cached","tryPromise","try","catch","json","tryMap","_","JSON","parse","urlParamsBody","flatMap","URLSearchParams","multipartEffect","multipart","toPersisted","multipartStream","pipeThroughChannel","mapError","MultipartError","makeChannel","arrayBufferEffect","arrayBuffer","upgrade","toURL","self","host","protocol","URL","HttpServerRequest","serverRequestTag","fromWeb","toWebEither","self","options","source","Request","right","ourl","toURL","isNone","left","RequestError","request","reason","description","requestInit","method","headers","signal","hasBody","body","toReadableStreamRuntime","stream","runtime","defaultRuntime","duplex","value","toURL","Effect","FiberRef","import_Function","import_GlobalValue","Option","currentPreResponseHandlers","globalValue","Symbol","for","unsafeMake","none","appendPreResponseHandler","handler","update","match","onNone","some","onSome","prev","request","response","flatMap","withPreResponseHandler","dual","self","locallyWith","Context","Effect","FiberRef","import_Function","import_GlobalValue","Layer","Option","make","middleware","currentTracerDisabledWhen","globalValue","Symbol","for","unsafeMake","constFalse","SpanNameGenerator","Context","Reference","defaultValue","request","method","tracer","make","httpApp","withFiberRuntime","fiber","request","unsafeGet","currentContext","HttpServerRequest","disabled","getFiberRef","currentTracerDisabledWhen","url","getOrUndefined","toURL","undefined","username","password","redactedHeaderNames","currentRedactedNames","redactedHeaders","redact","headers","nameGenerator","get","SpanNameGenerator","useSpan","parent","fromHeaders","kind","captureStackTrace","span","attribute","method","toString","pathname","query","search","slice","protocol","name","String","remoteAddress","_tag","value","flatMap","exit","withParentSpan","response","exitResponse","status","handledSymbol","Symbol","for","toHandled","self","handleResponse","middleware","responded","withFiberRuntime","fiber","flatMap","response","request","unsafeGet","currentContext","HttpServerRequest","handler","getFiberRef","currentPreResponseHandlers","_tag","as","tap","value","withErrorHandling","catchAllCause","cause","causeResponse","zipRight","isEmptyType","succeed","failCause","withMiddleware","unify","undefined","tracer","matchCauseEffect","onFailure","void","_cause","empty","status","onSuccess","uninterruptible","scoped","ejectDefaultScopeClose","scope","ejectedScopes","add","unsafeEjectStreamScope","body","getOrThrow","getCurrentFiber","Scope","setBody","stream","ensuring","close","contentType","contentLength","GlobalValue","globalValue","WeakSet","effect","make","onExit","extend","exit","has","appendPreResponseHandler","withPreResponseHandler","toWebHandlerRuntime","runtime","httpRuntime","run","runFork","resolveSymbol","httpApp","toWeb","withoutBody","method","context","Promise","resolve","contextMap","Map","unsafeMap","isContext","key","set","httpServerRequest","fromWeb","unsafeMake","signal","addEventListener","unsafeInterruptAsFork","clientAbortFiberId","once","toWebHandler","defaultRuntime","toWebHandlerLayerWith","layer","options","runSync","dispose","runPromise","handlerCache","handlerPromise","gen","memoMap","toRuntimeWithMemoMap","toRuntime","toHandler","pipe","then","f","toWebHandlerLayer","fromWebHandler","async","resume","requestResult","toWebEither","fiberRefs","getFiberRefs","runtimeFlags","defaultRuntimeFlags","fail","left","right","RequestError","reason","description","import_effect","Context","Inspectable","runtime","context","import_effect","import_effect","import_effect","exit","TagTypeId","NodeInspectSymbol","Tag","runPromise"]}