ignotum 0.0.2 → 0.0.3
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.
- package/dist/cli/bin.mjs +5895 -48
- package/dist/cli/bin.mjs.map +1 -1
- package/dist/runtime/{index-BgWROoyk.d.ts → index-C6KO3ZdI.d.ts} +30 -8
- package/dist/runtime/internal/server.d.ts +1 -1
- package/dist/runtime/internal/server.js +1 -1
- package/dist/runtime/internal/types.d.ts +1 -1
- package/dist/runtime/internal/types.js +1 -1
- package/dist/runtime/{schema-CNEVLF7D.js → schema-wiFI7rgx.js} +56 -5
- package/dist/runtime/schema-wiFI7rgx.js.map +1 -0
- package/dist/runtime/server.d.ts +1 -1
- package/dist/runtime/server.js +1 -1
- package/package.json +3 -3
- package/dist/runtime/schema-CNEVLF7D.js.map +0 -1
package/dist/cli/bin.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bin.mjs","names":["dev","client","devServer","gettingStarted","index","manualSetup","schema","serverFunctions","values","agents","skill","runDev","packageJson.version"],"sources":["../../package.json","../../../contracts/dist/value-Briqf-Ua.js","../../../contracts/dist/runtime/sync.js","../../src/cli/codegen.ts","../../src/dev-runtime/dev-database.ts","../../src/cli/client-plugin.ts","../../../runtime/dist/functions.js","../../../runtime/dist/sync.js","../../src/internal/http-paths.ts","../../../contracts/dist/runtime/id.js","../../../contracts/dist/runtime/result.js","../../../contracts/dist/runtime/schema.js","../../../contracts/dist/schema/index.js","../../../runtime/dist/id.js","../../src/dev-runtime/database.ts","../../src/dev-runtime/id.ts","../../../contracts/dist/runtime/functions.js","../../src/dev-runtime/functions.ts","../../src/dev-runtime/sync.ts","../../src/cli/dev.ts","../../../../docs/agent/AGENTS.md?raw","../../../../docs/agent/skills/ignotum/SKILL.md?raw","../../../../docs/user/client.md?raw","../../../../docs/user/dev-server.md?raw","../../../../docs/user/getting-started.md?raw","../../../../docs/user/index.md?raw","../../../../docs/user/manual-setup.md?raw","../../../../docs/user/schema.md?raw","../../../../docs/user/server-functions.md?raw","../../../../docs/user/values.md?raw","../../src/cli/agent-files.ts","../../src/cli/package-manager.ts","../../src/cli/new-project.ts","../../src/cli/command.ts","../../src/cli/bin.ts"],"sourcesContent":["","import { Predicate, Schema } from \"effect\";\n//#region src/runtime/value.ts\nconst TransportValueSchema = Schema.suspend(() => Schema.Union([\n\tSchema.Null,\n\tSchema.Boolean,\n\tSchema.Finite,\n\tSchema.String,\n\tSchema.Date,\n\tSchema.Array(TransportValueSchema),\n\tSchema.Record(Schema.String, Schema.UndefinedOr(TransportValueSchema))\n]));\nconst encodeTransportValue = (value) => {\n\tif (Predicate.isDate(value)) return Schema.encodeSync(Schema.DateFromMillis)(value);\n\tif (globalThis.Array.isArray(value)) return value.map(encodeTransportValue);\n\tif (Predicate.isNumber(value)) return Schema.decodeSync(Schema.Finite)(value);\n\tif (Predicate.isNull(value) || Predicate.isString(value) || Predicate.isBoolean(value)) return value;\n\treturn Object.fromEntries(Object.entries(value).flatMap(([key, child]) => child === void 0 ? [] : [[key, encodeTransportValue(child)]]));\n};\nconst encodeTransportObject = (value) => Schema.decodeUnknownSync(Schema.JsonObject)(encodeTransportValue(Schema.decodeUnknownSync(TransportValueSchema)(value)));\nconst collectDatePaths = (value, path, paths) => {\n\tif (Predicate.isDate(value)) {\n\t\tSchema.decodeSync(Schema.Date)(value);\n\t\tpaths.push(path);\n\t\treturn;\n\t}\n\tif (globalThis.Array.isArray(value)) {\n\t\tfor (const [index, child] of value.entries()) collectDatePaths(child, [...path, index], paths);\n\t\treturn;\n\t}\n\tif (value === void 0 || Predicate.isNull(value) || Predicate.isString(value) || Predicate.isNumber(value) || Predicate.isBoolean(value)) return;\n\tfor (const [key, child] of Object.entries(value)) collectDatePaths(child, [...path, key], paths);\n};\nconst datePathsOf = (value) => {\n\tconst paths = [];\n\tcollectDatePaths(value, [], paths);\n\treturn paths;\n};\nconst datePathsOfObject = (value) => datePathsOf(Schema.decodeUnknownSync(TransportValueSchema)(value));\nconst pathKey = (path) => JSON.stringify(path);\nconst decodeTransportValueAt = (value, path, encodedDatePaths) => {\n\tif (encodedDatePaths.has(pathKey(path))) return Schema.decodeUnknownSync(Schema.DateFromMillis)(value);\n\tif (globalThis.Array.isArray(value)) return value.map((item, index) => decodeTransportValueAt(item, [...path, index], encodedDatePaths));\n\tif (Predicate.isNull(value) || Predicate.isString(value) || Predicate.isNumber(value) || Predicate.isBoolean(value)) return value;\n\treturn Object.fromEntries(Object.entries(value).map(([key, item]) => [key, decodeTransportValueAt(item, [...path, key], encodedDatePaths)]));\n};\nconst decodeTransportValue = (value, datePaths) => decodeTransportValueAt(value, [], new Set(datePaths.map(pathKey)));\nconst decodeTransportObject = (value, datePaths) => {\n\tconst encodedDatePaths = new Set(datePaths.map(pathKey));\n\treturn Object.fromEntries(Object.entries(value).map(([key, child]) => [key, decodeTransportValueAt(child, [key], encodedDatePaths)]));\n};\n//#endregion\nexport { decodeTransportValue as a, decodeTransportObject as i, datePathsOf as n, encodeTransportObject as o, datePathsOfObject as r, encodeTransportValue as s, TransportValueSchema as t };\n\n//# sourceMappingURL=value-Briqf-Ua.js.map","import { a as decodeTransportValue, i as decodeTransportObject, n as datePathsOf, o as encodeTransportObject, r as datePathsOfObject, s as encodeTransportValue, t as TransportValueSchema } from \"../value-Briqf-Ua.js\";\nimport { Schema } from \"effect\";\n//#region src/runtime/sync.ts\nconst FunctionNamePart = Schema.String.check(Schema.isPattern(/^[A-Za-z_$][A-Za-z0-9_$]*$/));\nconst ApiFunctionAddressParts = Schema.TemplateLiteralParser([\n\t\"api.\",\n\tFunctionNamePart,\n\t\".\",\n\tFunctionNamePart\n]);\nconst FunctionAddress = Schema.TemplateLiteral([\n\t\"api.\",\n\tFunctionNamePart,\n\t\".\",\n\tFunctionNamePart\n]);\nconst apiFunctionParts = (address) => {\n\tconst [, moduleName, , functionName] = Schema.decodeSync(ApiFunctionAddressParts)(address);\n\treturn {\n\t\tfunctionName,\n\t\tmoduleName\n\t};\n};\nconst SubscriptionId = Schema.Natural.pipe(Schema.brand(\"ignotum/sync/SubscriptionId\"));\nconst RequestId = Schema.Natural.pipe(Schema.brand(\"ignotum/sync/RequestId\"));\nconst Subscribe = Schema.Struct({\n\ttype: Schema.Literal(\"Subscribe\"),\n\tid: SubscriptionId,\n\tfunction: FunctionAddress,\n\targs: Schema.Json\n});\nconst Unsubscribe = Schema.Struct({\n\ttype: Schema.Literal(\"Unsubscribe\"),\n\tid: SubscriptionId\n});\nconst Mutate = Schema.Struct({\n\ttype: Schema.Literal(\"Mutate\"),\n\tid: RequestId,\n\tfunction: FunctionAddress,\n\targs: Schema.Json\n});\nconst ClientMessage = Schema.Union([\n\tSubscribe,\n\tUnsubscribe,\n\tMutate\n]);\nconst QueryOperation = Schema.Struct({\n\ttype: Schema.Literal(\"Query\"),\n\tid: SubscriptionId\n});\nconst MutateOperation = Schema.Struct({\n\ttype: Schema.Literal(\"Mutate\"),\n\tid: RequestId\n});\nconst Operation = Schema.Union([QueryOperation, MutateOperation]);\nconst DatePath = Schema.Array(Schema.Union([Schema.String, Schema.Natural]));\nconst DatePaths = Schema.Array(DatePath);\nconst WireResult = Schema.Union([Schema.Struct({\n\ttype: Schema.Literal(\"Success\"),\n\tvalue: Schema.optional(Schema.Json),\n\tdates: Schema.optional(DatePaths)\n}), Schema.Struct({\n\ttype: Schema.Literal(\"Failure\"),\n\terror: Schema.Json,\n\tdates: Schema.optional(DatePaths)\n})]);\nconst QuerySnapshot = Schema.Struct({\n\ttype: Schema.Literal(\"QuerySnapshot\"),\n\tid: SubscriptionId,\n\tresult: WireResult\n});\nconst MutationResult = Schema.Struct({\n\ttype: Schema.Literal(\"MutationResult\"),\n\tid: RequestId,\n\tresult: WireResult\n});\nconst ProtocolErrorCode = Schema.Literals([\n\t\"DuplicateOperationId\",\n\t\"FunctionUnavailable\",\n\t\"InvalidArguments\",\n\t\"InvalidMessage\",\n\t\"UnknownFunction\",\n\t\"WrongFunctionKind\"\n]);\nconst ProtocolError = Schema.Struct({\n\ttype: Schema.Literal(\"ProtocolError\"),\n\toperation: Schema.optional(Operation),\n\tcode: ProtocolErrorCode,\n\tmessage: Schema.String\n});\nconst ServerMessage = Schema.Union([\n\tQuerySnapshot,\n\tMutationResult,\n\tProtocolError\n]);\nconst ClientMessageJson = Schema.fromJsonString(ClientMessage);\nconst ServerMessageJson = Schema.fromJsonString(ServerMessage);\n//#endregion\nexport { ClientMessage, ClientMessageJson, DatePath, FunctionAddress, FunctionNamePart, Operation, ProtocolErrorCode, RequestId, ServerMessage, ServerMessageJson, SubscriptionId, TransportValueSchema, WireResult, apiFunctionParts, datePathsOf, datePathsOfObject, decodeTransportObject, decodeTransportValue, encodeTransportObject, encodeTransportValue };\n\n//# sourceMappingURL=sync.js.map","import { Array, Effect, FileSystem, Path, Schema, String } from \"effect\";\n\nimport { FunctionNamePart } from \"@ignotum/contracts/runtime/sync\";\n\nconst generatedHeader = \"// Generated by `ignotum codegen`. Do not edit.\";\n\nexport class SchemaNotFound extends Schema.TaggedError<SchemaNotFound>()(\"SchemaNotFound\", {\n message: Schema.String,\n path: Schema.String,\n}) {}\n\nexport class InvalidFunctionModuleName extends Schema.TaggedError<InvalidFunctionModuleName>()(\n \"InvalidFunctionModuleName\",\n {\n message: Schema.String,\n path: Schema.String,\n },\n) {}\n\nexport class GeneratedFileConflict extends Schema.TaggedError<GeneratedFileConflict>()(\n \"GeneratedFileConflict\",\n {\n message: Schema.String,\n path: Schema.String,\n },\n) {}\n\ninterface GeneratedOutput {\n readonly content: string;\n readonly path: string;\n}\n\nexport interface CodegenResult {\n readonly functionModules: ReadonlyArray<string>;\n readonly written: ReadonlyArray<string>;\n readonly unchanged: ReadonlyArray<string>;\n}\n\nconst isFunctionModuleFile = (fileName: string): boolean =>\n fileName.endsWith(\".ts\") &&\n !fileName.endsWith(\".test.ts\") &&\n !fileName.endsWith(\".spec.ts\") &&\n fileName !== \"index.ts\" &&\n fileName !== \"schema.ts\" &&\n !fileName.startsWith(\"_\");\n\nconst moduleNameFromFile = (filePath: string, fileName: string) => {\n const moduleName = fileName.slice(0, -\".ts\".length);\n\n return Schema.decodeEffect(FunctionNamePart)(moduleName).pipe(\n Effect.mapError(() =>\n InvalidFunctionModuleName.make({\n message: `Server function file names must be valid TypeScript identifiers. Rename ${fileName}.`,\n path: filePath,\n }),\n ),\n );\n};\n\nconst renderServerBindings = (): string => `${generatedHeader}\n\nimport { bindSchema } from \"ignotum/internal/server\";\n\nimport schema from \"../server/schema.js\";\n\nexport const { mutation, query, values } = bindSchema(schema);\n`;\n\nconst renderTypes = (): string => `${generatedHeader}\n\nimport type {\n Document as DocumentFor,\n Id as IdFor,\n SchemaDefinitionOf,\n} from \"ignotum/internal/types\";\n\nimport type schema from \"../server/schema.js\";\n\nexport type DataModel = SchemaDefinitionOf<typeof schema>;\nexport type Doc<TableName extends Extract<keyof DataModel, string>> = DocumentFor<\n DataModel,\n TableName\n>;\nexport type Id<TableName extends Extract<keyof DataModel, string>> = IdFor<TableName>;\n`;\n\nconst renderApi = (moduleNames: ReadonlyArray<string>): string => {\n const modules = Array.match(moduleNames, {\n onEmpty: () => \" // No server function modules found.\",\n onNonEmpty: (names) =>\n Array.join(\n Array.map(\n names,\n (moduleName) => ` readonly ${moduleName}: typeof import(\"../server/${moduleName}.js\");`,\n ),\n \"\\n\",\n ),\n });\n return `${generatedHeader}\n\nimport { createApi } from \"ignotum/internal/api\";\n\ntype Modules = {\n${modules}\n};\n\nexport const api = createApi<Modules>();\n`;\n};\n\nconst inspectOutput = Effect.fn(\"Codegen.inspectOutput\")(function* (output: GeneratedOutput) {\n const fileSystem = yield* FileSystem.FileSystem;\n const exists = yield* fileSystem.exists(output.path);\n\n if (!exists) {\n return \"write\" as const;\n }\n\n const current = yield* fileSystem.readFileString(output.path);\n\n if (current === output.content) {\n return \"unchanged\" as const;\n }\n\n if (!current.startsWith(generatedHeader)) {\n return yield* GeneratedFileConflict.make({\n message: `Refusing to overwrite ${output.path} because it was not created by Ignotum.`,\n path: output.path,\n });\n }\n\n return \"write\" as const;\n});\n\nconst writeOutput = Effect.fn(\"Codegen.writeOutput\")(function* (output: GeneratedOutput) {\n const fileSystem = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const directory = path.dirname(output.path);\n\n yield* fileSystem.makeDirectory(directory, { recursive: true });\n yield* Effect.scoped(\n Effect.gen(function* () {\n const temporaryPath = yield* fileSystem.makeTempFileScoped({\n directory,\n prefix: \".ignotum-\",\n suffix: \".ts\",\n });\n\n yield* fileSystem.writeFileString(temporaryPath, output.content);\n yield* fileSystem.rename(temporaryPath, output.path);\n }),\n );\n});\n\nexport const generate = Effect.fn(\"Codegen.generate\")(function* (projectDirectory: string) {\n const fileSystem = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const serverDirectory = path.join(projectDirectory, \"server\");\n const schemaPath = path.join(serverDirectory, \"schema.ts\");\n const schemaExists = yield* fileSystem.exists(schemaPath);\n\n if (!schemaExists) {\n return yield* SchemaNotFound.make({\n message: `No Ignotum schema found at ${schemaPath}.`,\n path: schemaPath,\n });\n }\n\n const entries = yield* fileSystem.readDirectory(serverDirectory);\n const functionFiles = Array.sort(String.Order)(Array.filter(entries, isFunctionModuleFile));\n const functionModules = yield* Effect.forEach(functionFiles, (fileName) =>\n moduleNameFromFile(path.join(serverDirectory, fileName), fileName),\n );\n const outputs: ReadonlyArray<GeneratedOutput> = [\n {\n content: renderServerBindings(),\n path: path.join(projectDirectory, \"_generated\", \"server.ts\"),\n },\n {\n content: renderApi(functionModules),\n path: path.join(projectDirectory, \"_generated\", \"api.ts\"),\n },\n {\n content: renderTypes(),\n path: path.join(projectDirectory, \"_generated\", \"types.ts\"),\n },\n ];\n const inspections = yield* Effect.forEach(outputs, inspectOutput);\n const inspectedOutputs = Array.zip(outputs, inspections);\n const outputsToWrite = Array.map(\n Array.filter(inspectedOutputs, ([, inspection]) => inspection === \"write\"),\n ([output]) => output,\n );\n const unchanged = Array.map(\n Array.filter(inspectedOutputs, ([, inspection]) => inspection === \"unchanged\"),\n ([output]) => output.path,\n );\n const written = Array.map(outputsToWrite, (output) => output.path);\n\n yield* Effect.forEach(outputsToWrite, writeOutput, { discard: true });\n\n return { functionModules, unchanged, written } satisfies CodegenResult;\n});\n","import { Crypto, Effect, FileSystem, Option, Path, Predicate, Schema } from \"effect\";\n\nconst databaseFileNames = [\"state.db\", \"state.db-shm\", \"state.db-wal\", \"state.db-journal\"] as const;\nconst lockFileName = \"lock.json\";\n\nconst DevDatabaseLockRecord = Schema.Struct({\n pid: Schema.Int,\n token: Schema.String,\n});\nconst DevDatabaseLockRecordJson = Schema.fromJsonString(DevDatabaseLockRecord);\ntype DevDatabaseLockRecord = typeof DevDatabaseLockRecord.Type;\n\nexport class DevDatabaseResetFailed extends Schema.TaggedError<DevDatabaseResetFailed>()(\n \"DevDatabaseResetFailed\",\n {\n cause: Schema.Defect(),\n message: Schema.String,\n path: Schema.String,\n },\n) {}\n\nexport class DevDatabaseInUse extends Schema.TaggedError<DevDatabaseInUse>()(\"DevDatabaseInUse\", {\n message: Schema.String,\n path: Schema.String,\n pid: Schema.Int,\n}) {}\n\nexport class DevDatabaseLockFailed extends Schema.TaggedError<DevDatabaseLockFailed>()(\n \"DevDatabaseLockFailed\",\n {\n cause: Schema.Defect(),\n message: Schema.String,\n path: Schema.String,\n },\n) {}\n\nexport const devDatabasePath = Effect.fn(\"DevDatabase.path\")(function* (projectDirectory: string) {\n const path = yield* Path.Path;\n return path.join(projectDirectory, \".ignotum\", \"dev\", \"state.db\");\n});\n\nconst processIsRunning = (pid: number): boolean => {\n try {\n process.kill(pid, 0);\n return true;\n } catch (cause) {\n return !(Predicate.hasProperty(cause, \"code\") && cause.code === \"ESRCH\");\n }\n};\n\nexport const acquireDevDatabaseLock = Effect.fn(\"DevDatabase.acquireLock\")(function* (\n projectDirectory: string,\n) {\n const crypto = yield* Crypto.Crypto;\n const fileSystem = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const databasePath = yield* devDatabasePath(projectDirectory);\n const directory = path.dirname(databasePath);\n const lockPath = path.join(directory, lockFileName);\n const record: DevDatabaseLockRecord = {\n pid: process.pid,\n token: yield* crypto.randomUUIDv4,\n };\n const encoded = yield* Schema.encodeEffect(DevDatabaseLockRecordJson)(record).pipe(\n Effect.mapError((cause) =>\n DevDatabaseLockFailed.make({\n cause,\n message: `Could not encode the development database lock at ${lockPath}.`,\n path: lockPath,\n }),\n ),\n );\n\n yield* fileSystem.makeDirectory(directory, { recursive: true }).pipe(\n Effect.mapError((cause) =>\n DevDatabaseLockFailed.make({\n cause,\n message: `Could not create the development state directory at ${directory}.`,\n path: lockPath,\n }),\n ),\n );\n\n const createLock = () =>\n fileSystem.writeFileString(lockPath, encoded, { flag: \"wx\" }).pipe(\n Effect.matchEffect({\n onFailure: (cause) =>\n cause.reason._tag === \"AlreadyExists\"\n ? Effect.succeed(false)\n : DevDatabaseLockFailed.make({\n cause,\n message: `Could not create the development database lock at ${lockPath}.`,\n path: lockPath,\n }),\n onSuccess: () => Effect.succeed(true),\n }),\n );\n\n const readLock = Effect.fn(\"DevDatabase.readLock\")(function* () {\n const content = yield* fileSystem.readFileString(lockPath).pipe(\n Effect.mapError((cause) =>\n DevDatabaseLockFailed.make({\n cause,\n message: `Could not read the development database lock at ${lockPath}.`,\n path: lockPath,\n }),\n ),\n );\n return yield* Schema.decodeEffect(DevDatabaseLockRecordJson)(content).pipe(\n Effect.mapError((cause) =>\n DevDatabaseLockFailed.make({\n cause,\n message: `The development database lock at ${lockPath} is invalid. Remove it and try again.`,\n path: lockPath,\n }),\n ),\n );\n });\n\n const failInUse = (current: DevDatabaseLockRecord) =>\n DevDatabaseInUse.make({\n message: `Another Ignotum development server is using ${databasePath} with process ${current.pid}.`,\n path: lockPath,\n pid: current.pid,\n });\n\n const acquire = Effect.gen(function* () {\n if (yield* createLock()) return record;\n\n const current = yield* readLock();\n if (processIsRunning(current.pid)) return yield* failInUse(current);\n\n yield* fileSystem.remove(lockPath).pipe(\n Effect.mapError((cause) =>\n DevDatabaseLockFailed.make({\n cause,\n message: `Could not remove the stale development database lock at ${lockPath}.`,\n path: lockPath,\n }),\n ),\n );\n\n if (yield* createLock()) return record;\n return yield* failInUse(yield* readLock());\n });\n\n const release = (owned: DevDatabaseLockRecord) =>\n Effect.gen(function* () {\n if (!(yield* fileSystem.exists(lockPath))) return;\n const content = yield* fileSystem.readFileString(lockPath);\n const current = Schema.decodeOption(DevDatabaseLockRecordJson)(content);\n if (Option.isNone(current) || current.value.token !== owned.token) return;\n yield* fileSystem.remove(lockPath);\n }).pipe(\n Effect.catchCause((cause) =>\n Effect.logWarning(`Could not release the development database lock at ${lockPath}.`).pipe(\n Effect.annotateLogs({ cause }),\n ),\n ),\n );\n\n yield* Effect.acquireRelease(acquire, release);\n});\n\nexport const resetDevDatabase = Effect.fn(\"DevDatabase.reset\")(function* (\n projectDirectory: string,\n) {\n return yield* Effect.scoped(\n Effect.gen(function* () {\n yield* acquireDevDatabaseLock(projectDirectory);\n const fileSystem = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const directory = path.join(projectDirectory, \".ignotum\", \"dev\");\n const databasePath = yield* devDatabasePath(projectDirectory);\n let removed = 0;\n\n yield* Effect.forEach(\n databaseFileNames,\n Effect.fn(\"DevDatabase.removeFile\")(function* (fileName) {\n const filePath = path.join(directory, fileName);\n if (!(yield* fileSystem.exists(filePath))) return;\n yield* fileSystem.remove(filePath);\n removed += 1;\n }),\n { discard: true },\n ).pipe(\n Effect.mapError((cause) =>\n DevDatabaseResetFailed.make({\n cause,\n message: `Could not reset ${databasePath}. Stop the Ignotum dev server and try again.`,\n path: databasePath,\n }),\n ),\n );\n\n return { databasePath, removed } as const;\n }),\n );\n});\n","import type { Plugin } from \"vite\";\n\nconst clientEntryId = \"virtual:ignotum/client-entry\";\nconst resolvedClientEntryId = `\\0${clientEntryId}`;\n\nconst document = `<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>Ignotum</title>\n </head>\n <body>\n <div id=\"app\"></div>\n <script type=\"module\">\n import \"${clientEntryId}\"\n </script>\n </body>\n</html>`;\n\nconst clientEntry = `import \"preact/debug\"\nimport { render } from \"preact\"\nimport { jsx } from \"preact/jsx-runtime\"\n\nimport \"/styles.css\"\nimport App from \"/App.tsx\"\n\nconst root = document.getElementById(\"app\")\n\nif (root === null) {\n throw new Error(\"Ignotum mount element is missing.\")\n}\n\nrender(jsx(App, {}), root)\n`;\n\nexport const ignotumClientPlugin = (): Plugin => ({\n name: \"ignotum:client\",\n\n configureServer: (server) => {\n server.middlewares.use((request, response, next) => {\n const acceptsHtml = request.headers.accept?.includes(\"text/html\") === true;\n const isNavigation = request.method === \"GET\" || request.method === \"HEAD\";\n\n if (!acceptsHtml || !isNavigation) {\n next();\n return;\n }\n\n const requestUrl = request.originalUrl ?? request.url ?? \"/\";\n\n void server\n .transformIndexHtml(requestUrl, document)\n .then((html) => {\n response.statusCode = 200;\n response.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n response.end(request.method === \"HEAD\" ? undefined : html);\n })\n .catch(next);\n });\n },\n\n load: (id) => (id === resolvedClientEntryId ? clientEntry : undefined),\n\n resolveId: (id) => (id === clientEntryId ? resolvedClientEntryId : undefined),\n});\n","import { Context } from \"effect\";\n//#region src/functions.ts\nvar FunctionRuntime = class extends Context.Service()(\"@ignotum/runtime/functions/FunctionRuntime\") {};\n//#endregion\nexport { FunctionRuntime };\n\n//# sourceMappingURL=functions.js.map","import { Context } from \"effect\";\n//#region src/sync.ts\nvar QueryInvalidation = class extends Context.Service()(\"@ignotum/runtime/sync/QueryInvalidation\") {};\n//#endregion\nexport { QueryInvalidation };\n\n//# sourceMappingURL=sync.js.map","export const ignotumPathPrefix = \"/_ignotum\";\nexport const syncPath = `${ignotumPathPrefix}/sync`;\n\nexport const isIgnotumPath = (pathname: string): boolean =>\n pathname === ignotumPathPrefix || pathname.startsWith(`${ignotumPathPrefix}/`);\n","import { Schema } from \"effect\";\n//#region src/runtime/id.ts\nconst IdAlphabet = \"0123456789abcdefghijklmnopqrstuvwxyz\";\nconst IdLength = 24;\nconst GeneratedId = Schema.String.check(Schema.isPattern(/^[0-9a-z]{24}$/)).pipe(Schema.brand(\"ignotum/id\"));\n//#endregion\nexport { GeneratedId, IdAlphabet, IdLength };\n\n//# sourceMappingURL=id.js.map","import { i as decodeTransportObject } from \"../value-Briqf-Ua.js\";\nimport { Brand, Effect, Effectable, Function, Option, Predicate, Schema } from \"effect\";\n//#region src/runtime/result.ts\nconst ResultTypeId = Symbol.for(\"ignotum/runtime/result/Result\");\nconst CompletedResultTypeId = Symbol.for(\"ignotum/runtime/result/Completed\");\nconst PendingResultTypeId = Symbol.for(\"ignotum/runtime/result/Pending\");\nconst ErrorBrand = \"ignotum/error\";\nconst makeErrorValue = Brand.nominal();\nconst ErrorValueSchema = Schema.StructWithRest(Schema.Struct({ _tag: Schema.String }), [Schema.Record(Schema.String, Schema.Json)]).pipe(Schema.brand(ErrorBrand));\nvar InternalServerErrorCause = class extends Schema.TaggedError()(\"InternalServerError\", { requestId: Schema.String }) {};\nconst InternalServerError = InternalServerErrorCause;\nconst InternalServerErrorSchema = InternalServerErrorCause.pipe(Schema.brand(ErrorBrand));\nconst effectOf = (value) => Predicate.hasProperty(value, ResultTypeId) ? value[ResultTypeId] : Effect.succeed(value);\nfunction makeResultEffectBase() {\n\tconst Base = function() {};\n\tBase.prototype = Effectable.Prototype({\n\t\tlabel: \"IgnotumResult\",\n\t\tevaluate() {\n\t\t\treturn this[ResultTypeId];\n\t\t}\n\t});\n\treturn Base;\n}\nconst ResultEffectBase = makeResultEffectBase();\nvar ResultOperation = class ResultOperation extends ResultEffectBase {\n\t[ResultTypeId];\n\tconstructor(effect, completed) {\n\t\tsuper();\n\t\tthis[ResultTypeId] = effect;\n\t\tif (completed !== void 0) Object.defineProperty(this, CompletedResultTypeId, { value: completed });\n\t}\n\tcatch(cases) {\n\t\tconst effectCases = {};\n\t\tfor (const [tag, handler] of Object.entries(cases)) if (Predicate.isFunction(handler)) effectCases[tag] = (failure) => effectOf(handler(failure));\n\t\tconst runtimeEffect = this[ResultTypeId];\n\t\tconst caught = Effect.catchTags(runtimeEffect, effectCases);\n\t\treturn new ResultOperation(caught);\n\t}\n};\nvar PendingQueryResult = class {\n\t[PendingResultTypeId] = PendingResultTypeId;\n};\nconst inspectResult = (value) => {\n\tif (!Predicate.hasProperty(value, CompletedResultTypeId)) return void 0;\n\treturn value[CompletedResultTypeId];\n};\nconst effectFromResult = (result) => result[ResultTypeId];\nconst resultFromEffect = (effect) => new ResultOperation(effect);\nconst isFailureResult = (result) => Predicate.hasProperty(result, CompletedResultTypeId) && Predicate.isObject(result[CompletedResultTypeId]) && Predicate.hasProperty(result[CompletedResultTypeId], \"type\") && result[CompletedResultTypeId].type === \"Failure\";\nconst succeed = (value) => new ResultOperation(Effect.succeed(value), {\n\ttype: \"Success\",\n\tvalue\n});\nconst fail = (error) => new ResultOperation(Effect.fail(error), {\n\ttype: \"Failure\",\n\terror\n});\nconst tryResult = (body) => {\n\treturn new ResultOperation(Effect.gen(body));\n};\nconst match = Function.dual(2, (result, matchers) => {\n\tif (result instanceof PendingQueryResult) {\n\t\tif (matchers.pending === void 0) throw new Error(\"A pending Result requires a pending matcher.\");\n\t\treturn matchers.pending();\n\t}\n\tif (!Predicate.hasProperty(result, ResultTypeId)) throw new Error(\"Unknown Result implementation.\");\n\tconst inspected = inspectResult(result);\n\tif (inspected?.type === \"Success\") {\n\t\tconst value = inspected.value;\n\t\treturn matchers.value(value);\n\t}\n\tif (!isFailureResult(result)) throw new Error(\"Unknown or incomplete Result operation.\");\n\tconst error = result[CompletedResultTypeId].error;\n\tif (error._tag === \"InternalServerError\") {\n\t\tconst internalError = Schema.decodeUnknownSync(InternalServerErrorSchema)(error);\n\t\tconst handler = matchers.internalError;\n\t\tif (handler === void 0) throw internalError;\n\t\treturn handler(internalError);\n\t}\n\tconst errorMatcher = matchers.error;\n\tif (errorMatcher === void 0) throw new Error(`No matcher was provided for ${error._tag}.`);\n\tif (Predicate.isFunction(errorMatcher)) return errorMatcher(error);\n\tconst handlers = errorMatcher;\n\tconst handler = Object.hasOwn(handlers, error._tag) ? handlers[error._tag] : void 0;\n\tif (handler === void 0) throw new Error(`No matcher was provided for ${error._tag}.`);\n\treturn handler(error);\n});\nconst pending = () => new PendingQueryResult();\nconst failureFromWire = (error, datePaths = []) => {\n\tconst internalError = Schema.decodeUnknownOption(InternalServerErrorSchema)(error);\n\tif (Option.isSome(internalError)) return fail(internalError.value);\n\tconst decoded = Schema.decodeUnknownOption(ErrorValueSchema)(error);\n\tif (Option.isNone(decoded)) throw new Error(\"The server returned an invalid application error.\");\n\tconst restored = decodeTransportObject(decoded.value, datePaths);\n\treturn fail(makeErrorValue({\n\t\t...restored,\n\t\t_tag: decoded.value._tag\n\t}));\n};\nconst documentNotFound = (table, id) => Brand.nominal()({\n\t_tag: \"DocumentNotFound\",\n\ttable,\n\tid\n});\nconst Result = {\n\tfail,\n\tmatch,\n\tsucceed,\n\ttry: tryResult\n};\n//#endregion\nexport { ErrorBrand, ErrorValueSchema, InternalServerError, InternalServerErrorSchema, Result, documentNotFound, effectFromResult, failureFromWire, inspectResult, match, pending, resultFromEffect };\n\n//# sourceMappingURL=result.js.map","//#region src/runtime/schema.ts\nconst FunctionSchemaTypeId = Symbol.for(\"ignotum/runtime/schema/FunctionSchema\");\nconst attachFunctionSchema = (schema) => (definition) => {\n\tObject.defineProperty(definition, FunctionSchemaTypeId, {\n\t\tconfigurable: false,\n\t\tenumerable: false,\n\t\tvalue: schema,\n\t\twritable: false\n\t});\n\treturn definition;\n};\nconst getFunctionSchema = (value) => value[FunctionSchemaTypeId];\n//#endregion\nexport { FunctionSchemaTypeId, attachFunctionSchema, getFunctionSchema };\n\n//# sourceMappingURL=schema.js.map","import { Result } from \"../runtime/result.js\";\nimport { bindValues, table, values } from \"./values.js\";\nimport { attachFunctionSchema } from \"../runtime/schema.js\";\n//#region src/schema/types.ts\nconst SchemaDefinitionTypeId = Symbol.for(\"ignotum/schema/SchemaDefinition\");\n//#endregion\n//#region src/schema/definition.ts\nconst defineSchema = (define) => ({\n\t_tag: \"Schema\",\n\t[SchemaDefinitionTypeId]: define({\n\t\ttable,\n\t\tvalues\n\t})\n});\n//#endregion\n//#region src/schema/server.ts\nconst makeFunctionBuilder = (schema, kind) => {\n\tconst define = (definition) => attachFunctionSchema(schema)({\n\t\t_tag: kind,\n\t\t...definition\n\t});\n\treturn define;\n};\nconst makeFunctionBuilders = (schema) => ({\n\tmutation: makeFunctionBuilder(schema, \"Mutation\"),\n\tquery: makeFunctionBuilder(schema, \"Query\")\n});\nconst bindSchema = (schema) => ({\n\tvalues: bindValues(),\n\t...makeFunctionBuilders(schema)\n});\n//#endregion\nexport { Result, SchemaDefinitionTypeId, bindSchema, bindValues, defineSchema, table, values };\n\n//# sourceMappingURL=index.js.map","import { Context } from \"effect\";\n//#region src/id.ts\nvar IdGenerator = class extends Context.Service()(\"@ignotum/runtime/id/IdGenerator\") {};\n//#endregion\nexport { IdGenerator };\n\n//# sourceMappingURL=id.js.map","import { Context, DateTime, Effect, Layer, Option, Schema } from \"effect\";\nimport { SqlClient, SqlError, SqlSchema } from \"effect/unstable/sql\";\nimport { GeneratedId, type GeneratedId as GeneratedIdType } from \"@ignotum/contracts/runtime/id\";\nimport {\n documentNotFound,\n resultFromEffect,\n type DocumentNotFoundValue,\n type Result,\n} from \"@ignotum/contracts/runtime/result\";\nimport type {\n RuntimeSchemaDefinition,\n RuntimeTableDefinition,\n} from \"@ignotum/contracts/runtime/schema\";\nimport { SchemaDefinitionTypeId } from \"@ignotum/contracts/schema\";\nimport { IdGenerator } from \"@ignotum/runtime/id\";\n\ninterface RuntimeObject {\n readonly [fieldName: string]: RuntimeDocumentValue | undefined;\n}\ntype RuntimeDocumentValue =\n | null\n | boolean\n | number\n | string\n | Date\n | ReadonlyArray<RuntimeDocumentValue>\n | RuntimeObject;\ntype RuntimeValue = RuntimeObject;\n\nexport interface RuntimeDocument {\n readonly [fieldName: string]: RuntimeDocumentValue | undefined;\n readonly id: GeneratedIdType;\n readonly createdAt: Date;\n readonly updatedAt: Date;\n}\n\nexport interface LocalDatabaseReader {\n readonly find: (tableName: string, id: string) => Result<RuntimeDocument | undefined, never>;\n readonly get: (tableName: string, id: string) => Result<RuntimeDocument, DocumentNotFoundValue>;\n readonly query: (tableName: string) => {\n readonly collect: () => Result<ReadonlyArray<RuntimeDocument>, never>;\n };\n}\n\nexport interface LocalDatabaseWriter extends LocalDatabaseReader {\n readonly delete: (tableName: string, id: string) => Result<void, never>;\n readonly insert: (tableName: string, value: RuntimeValue) => Result<GeneratedIdType, never>;\n readonly patch: (tableName: string, id: string, value: RuntimeValue) => Result<void, never>;\n readonly replace: (tableName: string, id: string, value: RuntimeValue) => Result<void, never>;\n}\n\nexport interface LocalQueryContext {\n readonly db: LocalDatabaseReader;\n}\n\nexport interface LocalMutationContext {\n readonly db: LocalDatabaseWriter;\n}\n\ninterface LocalDatabaseService {\n readonly queryTransaction: <Success, Failure>(\n schema: RuntimeSchemaDefinition,\n use: (context: Readonly<LocalQueryContext>) => Effect.Effect<Success, Failure>,\n ) => Effect.Effect<Success, Failure | SqlError.SqlError>;\n readonly mutationTransaction: <Success, Failure>(\n schema: RuntimeSchemaDefinition,\n use: (context: Readonly<LocalMutationContext>) => Effect.Effect<Success, Failure>,\n ) => Effect.Effect<Success, Failure | SqlError.SqlError>;\n}\n\nconst StoredDocument = Schema.Struct({\n id: GeneratedId,\n tableName: Schema.String,\n createdAt: Schema.Int,\n updatedAt: Schema.Int,\n fields: Schema.String,\n});\ntype StoredDocument = typeof StoredDocument.Type;\n\nconst DocumentLookup = Schema.Struct({\n id: Schema.String,\n tableName: Schema.String,\n});\nconst TableLookup = Schema.Struct({ tableName: Schema.String });\ntype DatabaseOperation = \"collect\" | \"get\" | \"insert\" | \"patch\" | \"replace\";\n\nexport class UnknownDatabaseTable extends Schema.TaggedError<UnknownDatabaseTable>()(\n \"UnknownDatabaseTable\",\n {\n message: Schema.String,\n tableName: Schema.String,\n },\n) {}\n\nexport class DocumentSchemaMismatch extends Schema.TaggedError<DocumentSchemaMismatch>()(\n \"DocumentSchemaMismatch\",\n {\n cause: Schema.Defect(),\n id: Schema.NullOr(Schema.String),\n message: Schema.String,\n operation: Schema.Literals([\"collect\", \"get\", \"insert\", \"patch\", \"replace\"]),\n tableName: Schema.String,\n },\n) {}\n\nconst schemaMismatch = (\n tableName: string,\n id: string | null,\n operation: DatabaseOperation,\n cause: unknown,\n) =>\n DocumentSchemaMismatch.make({\n cause,\n id,\n message: `Document fields for ${tableName} did not match its schema during ${operation}.`,\n operation,\n tableName,\n });\n\nconst tableFor = Effect.fn(\"LocalDatabase.tableFor\")(function* (\n schema: RuntimeSchemaDefinition,\n tableName: string,\n) {\n const table = schema[SchemaDefinitionTypeId][tableName];\n if (table === undefined) {\n return yield* UnknownDatabaseTable.make({\n message: `Unknown database table ${tableName}.`,\n tableName,\n });\n }\n return table;\n});\n\nconst fieldsCodec = (table: RuntimeTableDefinition) =>\n // SAFETY: defineSchema creates every table schema with Schema.Struct, so its\n // decoded value is a string-keyed object and the authoring API needs no services.\n Schema.fromJsonString(\n Schema.make<Schema.Codec<RuntimeValue, Schema.Json>>(Schema.toCodecJson(table.schema).ast),\n );\n\nconst encodeFields = Effect.fn(\"LocalDatabase.encodeFields\")(function* (\n schema: RuntimeSchemaDefinition,\n tableName: string,\n value: RuntimeValue,\n operation: Extract<DatabaseOperation, \"insert\" | \"patch\" | \"replace\">,\n id: string | null,\n) {\n const table = yield* tableFor(schema, tableName);\n return yield* Schema.encodeEffect(fieldsCodec(table), {\n onExcessProperty: \"error\",\n })(value).pipe(Effect.mapError((cause) => schemaMismatch(tableName, id, operation, cause)));\n});\n\nconst decodeFields = Effect.fn(\"LocalDatabase.decodeFields\")(function* (\n schema: RuntimeSchemaDefinition,\n row: StoredDocument,\n operation: Extract<DatabaseOperation, \"collect\" | \"get\" | \"patch\">,\n) {\n const table = yield* tableFor(schema, row.tableName);\n return yield* Schema.decodeEffect(fieldsCodec(table), {\n onExcessProperty: \"error\",\n })(row.fields).pipe(\n Effect.mapError((cause) => schemaMismatch(row.tableName, row.id, operation, cause)),\n );\n});\n\nconst toRuntimeDocument = Effect.fn(\"LocalDatabase.toRuntimeDocument\")(function* (\n schema: RuntimeSchemaDefinition,\n row: StoredDocument,\n operation: Extract<DatabaseOperation, \"collect\" | \"get\">,\n) {\n const fields = yield* decodeFields(schema, row, operation);\n return {\n ...fields,\n id: row.id,\n createdAt: DateTime.toDate(DateTime.makeUnsafe(row.createdAt)),\n updatedAt: DateTime.toDate(DateTime.makeUnsafe(row.updatedAt)),\n } satisfies RuntimeDocument;\n});\n\nconst nextUpdatedAt = (now: DateTime.DateTime, previous: number): number =>\n Math.max(DateTime.toEpochMillis(now), previous + 1);\n\nexport class LocalDatabase extends Context.Service<LocalDatabase, LocalDatabaseService>()(\n \"ignotum/dev-runtime/database/LocalDatabase\",\n) {\n static readonly layer = Layer.effect(\n LocalDatabase,\n Effect.gen(function* () {\n const ids = yield* IdGenerator;\n const sql = yield* SqlClient.SqlClient;\n\n yield* sql`\n CREATE TABLE IF NOT EXISTS documents (\n id TEXT PRIMARY KEY NOT NULL\n CHECK (length(id) = 24 AND id NOT GLOB '*[^0-9a-z]*'),\n tableName TEXT NOT NULL,\n createdAt INTEGER NOT NULL,\n updatedAt INTEGER NOT NULL,\n fields TEXT NOT NULL CHECK (json_valid(fields))\n ) STRICT\n `;\n yield* sql`\n CREATE INDEX IF NOT EXISTS documents_table_name_idx\n ON documents (tableName)\n `;\n\n const findStored = SqlSchema.findOneOption({\n Request: DocumentLookup,\n Result: StoredDocument,\n execute: ({ id, tableName }) => sql`\n SELECT id, tableName, createdAt, updatedAt, fields\n FROM documents\n WHERE id = ${id} AND tableName = ${tableName}\n LIMIT 1\n `,\n });\n const collectStored = SqlSchema.findAll({\n Request: TableLookup,\n Result: StoredDocument,\n execute: ({ tableName }) => sql`\n SELECT id, tableName, createdAt, updatedAt, fields\n FROM documents\n WHERE tableName = ${tableName}\n ORDER BY createdAt ASC, id ASC\n `,\n });\n\n const find = Effect.fn(\"LocalDatabase.find\")(function* (\n schema: RuntimeSchemaDefinition,\n tableName: string,\n id: string,\n ) {\n yield* tableFor(schema, tableName);\n const row = yield* findStored({ id, tableName });\n if (Option.isNone(row)) return undefined;\n return yield* toRuntimeDocument(schema, row.value, \"get\");\n });\n\n const collect = Effect.fn(\"LocalDatabase.collect\")(function* (\n schema: RuntimeSchemaDefinition,\n tableName: string,\n ) {\n yield* tableFor(schema, tableName);\n const rows = yield* collectStored({ tableName });\n return yield* Effect.forEach(rows, (row) => toRuntimeDocument(schema, row, \"collect\"));\n });\n\n const insert = Effect.fn(\"LocalDatabase.insert\")(function* (\n schema: RuntimeSchemaDefinition,\n tableName: string,\n value: RuntimeValue,\n ) {\n const fields = yield* encodeFields(schema, tableName, value, \"insert\", null);\n const id = yield* ids.generate;\n const now = DateTime.toEpochMillis(yield* DateTime.now);\n yield* sql`\n INSERT INTO documents (id, tableName, createdAt, updatedAt, fields)\n VALUES (${id}, ${tableName}, ${now}, ${now}, ${fields})\n `;\n return id;\n });\n\n const deleteDocument = Effect.fn(\"LocalDatabase.delete\")(function* (\n schema: RuntimeSchemaDefinition,\n tableName: string,\n id: string,\n ) {\n yield* tableFor(schema, tableName);\n yield* sql`DELETE FROM documents WHERE id = ${id} AND tableName = ${tableName}`;\n });\n\n const patch = Effect.fn(\"LocalDatabase.patch\")(function* (\n schema: RuntimeSchemaDefinition,\n tableName: string,\n id: string,\n value: RuntimeValue,\n ) {\n yield* tableFor(schema, tableName);\n const stored = yield* findStored({ id, tableName });\n if (Option.isNone(stored)) return;\n const current = yield* decodeFields(schema, stored.value, \"patch\");\n const fields = yield* encodeFields(\n schema,\n tableName,\n { ...current, ...value },\n \"patch\",\n id,\n );\n const updatedAt = nextUpdatedAt(yield* DateTime.now, stored.value.updatedAt);\n yield* sql`\n UPDATE documents\n SET fields = ${fields}, updatedAt = ${updatedAt}\n WHERE id = ${id} AND tableName = ${tableName}\n `;\n });\n\n const replace = Effect.fn(\"LocalDatabase.replace\")(function* (\n schema: RuntimeSchemaDefinition,\n tableName: string,\n id: string,\n value: RuntimeValue,\n ) {\n yield* tableFor(schema, tableName);\n const stored = yield* findStored({ id, tableName });\n if (Option.isNone(stored)) return;\n const fields = yield* encodeFields(schema, tableName, value, \"replace\", id);\n const updatedAt = nextUpdatedAt(yield* DateTime.now, stored.value.updatedAt);\n yield* sql`\n UPDATE documents\n SET fields = ${fields}, updatedAt = ${updatedAt}\n WHERE id = ${id} AND tableName = ${tableName}\n `;\n });\n\n const makeReader = (schema: RuntimeSchemaDefinition): LocalDatabaseReader =>\n Object.freeze({\n find: (tableName: string, id: string) =>\n resultFromEffect(find(schema, tableName, id).pipe(Effect.orDie)),\n get: (tableName: string, id: string) =>\n resultFromEffect(\n find(schema, tableName, id).pipe(\n Effect.orDie,\n Effect.flatMap((document) =>\n document === undefined\n ? Effect.fail(documentNotFound(tableName, id))\n : Effect.succeed(document),\n ),\n ),\n ),\n query: (tableName: string) =>\n Object.freeze({\n collect: () => resultFromEffect(collect(schema, tableName).pipe(Effect.orDie)),\n }),\n });\n\n const makeWriter = (schema: RuntimeSchemaDefinition): LocalDatabaseWriter => {\n const reader = makeReader(schema);\n return Object.freeze({\n ...reader,\n delete: (tableName: string, id: string) =>\n resultFromEffect(deleteDocument(schema, tableName, id).pipe(Effect.orDie)),\n insert: (tableName: string, value: RuntimeValue) =>\n resultFromEffect(insert(schema, tableName, value).pipe(Effect.orDie)),\n patch: (tableName: string, id: string, value: RuntimeValue) =>\n resultFromEffect(patch(schema, tableName, id, value).pipe(Effect.orDie)),\n replace: (tableName: string, id: string, value: RuntimeValue) =>\n resultFromEffect(replace(schema, tableName, id, value).pipe(Effect.orDie)),\n });\n };\n\n return LocalDatabase.of({\n queryTransaction: (schema, use) =>\n sql.withTransaction(\n Effect.gen(function* () {\n const context = Object.freeze({\n db: makeReader(schema),\n });\n return yield* use(context);\n }),\n ),\n mutationTransaction: (schema, use) =>\n sql.withTransaction(\n Effect.gen(function* () {\n const context = Object.freeze({\n db: makeWriter(schema),\n });\n return yield* use(context);\n }),\n ),\n });\n }),\n );\n}\n","import { GeneratedId, IdAlphabet, IdLength } from \"@ignotum/contracts/runtime/id\";\nimport { IdGenerator } from \"@ignotum/runtime/id\";\nimport { Effect, Layer } from \"effect\";\nimport { customAlphabet } from \"nanoid\";\n\nexport const idGeneratorLayer = Layer.sync(IdGenerator, () => {\n const nanoid = customAlphabet(IdAlphabet, IdLength);\n return IdGenerator.of({\n generate: Effect.sync(() => GeneratedId.make(nanoid())),\n });\n});\n","import { FunctionAddress } from \"./sync.js\";\nimport { Schema } from \"effect\";\n//#region src/runtime/functions.ts\nconst FunctionKind = Schema.Literals([\"Mutation\", \"Query\"]);\nvar UnknownFunction = class extends Schema.TaggedError()(\"UnknownFunction\", {\n\tfunction: FunctionAddress,\n\tmessage: Schema.String\n}) {};\nvar WrongFunctionKind = class extends Schema.TaggedError()(\"WrongFunctionKind\", {\n\tactual: FunctionKind,\n\texpected: FunctionKind,\n\tfunction: FunctionAddress,\n\tmessage: Schema.String\n}) {};\nvar InvalidArguments = class extends Schema.TaggedError()(\"InvalidArguments\", {\n\tfunction: FunctionAddress,\n\tmessage: Schema.String\n}) {};\nvar FunctionUnavailable = class extends Schema.TaggedError()(\"FunctionUnavailable\", {\n\tcause: Schema.Defect(),\n\tfunction: FunctionAddress,\n\tmessage: Schema.String\n}) {};\n//#endregion\nexport { FunctionKind, FunctionUnavailable, InvalidArguments, UnknownFunction, WrongFunctionKind };\n\n//# sourceMappingURL=functions.js.map","import {\n FunctionUnavailable,\n InvalidArguments,\n UnknownFunction,\n WrongFunctionKind,\n type FunctionKind,\n type FunctionResolutionError,\n} from \"@ignotum/contracts/runtime/functions\";\nimport {\n getFunctionSchema,\n type FunctionSchemaCarrier,\n type RuntimeSchemaDefinition,\n} from \"@ignotum/contracts/runtime/schema\";\nimport { ErrorValueSchema, type ErrorValue } from \"@ignotum/contracts/runtime/result\";\nimport {\n FunctionAddress,\n apiFunctionParts,\n datePathsOf,\n datePathsOfObject,\n type TransportValue,\n type WireResult,\n} from \"@ignotum/contracts/runtime/sync\";\nimport { FunctionRuntime } from \"@ignotum/runtime/functions\";\nimport { Cause, Context, Effect, Layer, Path, Predicate, Schema, Semaphore } from \"effect\";\nimport { nanoid } from \"nanoid\";\nimport type { ViteDevServer } from \"vite\";\nimport { normalizePath } from \"vite\";\n\nimport { LocalDatabase, type LocalMutationContext, type LocalQueryContext } from \"./database.js\";\n\nexport { FunctionUnavailable, InvalidArguments, UnknownFunction, WrongFunctionKind };\nexport type { FunctionKind };\n\ntype RuntimeFields = Readonly<Record<string, Schema.ConstraintDecoder<unknown>>>;\n\ndeclare const FunctionArgumentsTypeId: unique symbol;\nexport interface FunctionArguments {\n readonly [FunctionArgumentsTypeId]?: never;\n}\n\nexport type RuntimeHandlerContext = LocalMutationContext | LocalQueryContext;\n\nexport interface RuntimeFunctionDefinition {\n readonly _tag: FunctionKind;\n readonly args?: RuntimeFields;\n readonly returns?: Schema.Codec<unknown, unknown>;\n readonly errors?: Schema.Codec<unknown, unknown>;\n readonly handler: (\n context: RuntimeHandlerContext,\n args: FunctionArguments,\n ) => Generator<Effect.Effect<unknown, ErrorValue, never>, TransportValue | void, never>;\n}\n\nexport interface ResolvedFunction {\n readonly definition: RuntimeFunctionDefinition;\n readonly args: FunctionArguments;\n readonly schema: RuntimeSchemaDefinition;\n}\n\ninterface RuntimeFunctionCandidate extends FunctionSchemaCarrier {\n readonly _tag?: unknown;\n readonly args?: unknown;\n readonly returns?: unknown;\n readonly errors?: unknown;\n readonly handler?: unknown;\n}\n\nconst inspectRuntimeFunctionDefinition = (\n value: RuntimeFunctionCandidate,\n):\n | { readonly definition: RuntimeFunctionDefinition; readonly schema: RuntimeSchemaDefinition }\n | undefined => {\n const schema = getFunctionSchema(value);\n if (\n schema === undefined ||\n !Predicate.hasProperty(value, \"_tag\") ||\n (value._tag !== \"Mutation\" && value._tag !== \"Query\") ||\n (Predicate.hasProperty(value, \"args\") &&\n value.args !== undefined &&\n !Predicate.isObject(value.args)) ||\n (Predicate.hasProperty(value, \"returns\") &&\n value.returns !== undefined &&\n !Schema.isSchema(value.returns)) ||\n (Predicate.hasProperty(value, \"errors\") &&\n value.errors !== undefined &&\n !Schema.isSchema(value.errors)) ||\n !Predicate.hasProperty(value, \"handler\") ||\n !Predicate.isFunction(value.handler)\n ) {\n return undefined;\n }\n\n if (\n Predicate.hasProperty(value, \"args\") &&\n Predicate.isObject(value.args) &&\n !Object.values(value.args).every(Schema.isSchema)\n ) {\n return undefined;\n }\n\n // SAFETY: every RuntimeFunctionDefinition property and argument Schema was\n // checked above. Predicate.hasProperty does not retain the literal tag type.\n return { definition: value as RuntimeFunctionDefinition, schema };\n};\n\nexport class FunctionRegistry extends Context.Service<\n FunctionRegistry,\n {\n readonly resolve: (\n functionAddress: FunctionAddress,\n kind: FunctionKind,\n args: Schema.Json,\n ) => Effect.Effect<ResolvedFunction, FunctionResolutionError>;\n }\n>()(\"ignotum/dev-runtime/functions/FunctionRegistry\") {\n static layer(server: ViteDevServer, projectDirectory: string) {\n return Layer.effect(\n FunctionRegistry,\n Effect.gen(function* () {\n const path = yield* Path.Path;\n return FunctionRegistry.of({\n resolve: Effect.fn(\"FunctionRegistry.resolve\")(function* (functionAddress, kind, args) {\n const { functionName, moduleName } = apiFunctionParts(functionAddress);\n const modulePath = normalizePath(\n path.join(projectDirectory, \"server\", `${moduleName}.ts`),\n );\n const loadedModule = yield* Effect.tryPromise({\n try: () => server.ssrLoadModule(modulePath),\n catch: (cause) =>\n FunctionUnavailable.make({\n cause,\n function: functionAddress,\n message: `Could not load ${functionAddress}.`,\n }),\n });\n const candidate = loadedModule[functionName];\n\n const inspected = Predicate.isObject(candidate)\n ? inspectRuntimeFunctionDefinition(candidate)\n : undefined;\n if (inspected === undefined) {\n return yield* UnknownFunction.make({\n function: functionAddress,\n message: `Unknown server function ${functionAddress}.`,\n });\n }\n const definition = inspected.definition;\n\n if (definition._tag !== kind) {\n return yield* WrongFunctionKind.make({\n actual: definition._tag,\n expected: kind,\n function: functionAddress,\n message: `${functionAddress} is a ${definition._tag.toLowerCase()}, not a ${kind.toLowerCase()}.`,\n });\n }\n\n const decodedArgs = yield* Schema.decodeEffect(\n Schema.toCodecJson(Schema.Struct(definition.args ?? {})),\n )(args).pipe(\n Effect.mapError(() =>\n InvalidArguments.make({\n function: functionAddress,\n message: `Invalid arguments for ${functionAddress}.`,\n }),\n ),\n );\n\n return { args: decodedArgs, definition, schema: inspected.schema };\n }),\n });\n }),\n );\n }\n}\n\nclass MutationApplicationFailure extends Schema.TaggedError<MutationApplicationFailure>()(\n \"MutationApplicationFailure\",\n { error: Schema.Json },\n) {}\n\nexport class FunctionExecutor extends Context.Service<\n FunctionExecutor,\n {\n readonly execute: (\n functionAddress: FunctionAddress,\n kind: FunctionKind,\n resolved: ResolvedFunction,\n ) => Effect.Effect<WireResult>;\n }\n>()(\"ignotum/dev-runtime/functions/FunctionExecutor\") {\n static readonly layer = Layer.effect(\n FunctionExecutor,\n Effect.gen(function* () {\n const database = yield* LocalDatabase;\n const mutationSemaphore = yield* Semaphore.make(1);\n\n const encodeSuccess = (\n definition: RuntimeFunctionDefinition,\n value: TransportValue | void,\n ) =>\n definition.returns === undefined\n ? Schema.encodeUnknownEffect(Schema.Undefined)(value).pipe(\n Effect.orDie,\n Effect.as<WireResult>({ type: \"Success\" }),\n )\n : Schema.encodeEffect(Schema.toCodecJson(definition.returns))(value).pipe(\n Effect.orDie,\n Effect.map((encoded): WireResult => {\n const result: WireResult = { type: \"Success\", value: encoded };\n const dates = datePathsOf(value);\n return dates.length === 0 ? result : { ...result, dates };\n }),\n );\n\n const encodeFailure = (definition: RuntimeFunctionDefinition, error: ErrorValue) =>\n Schema.encodeEffect(Schema.toCodecJson(definition.errors ?? ErrorValueSchema))(error).pipe(\n Effect.orDie,\n Effect.map((encoded): WireResult => {\n const result: WireResult = { type: \"Failure\", error: encoded };\n const dates = datePathsOfObject(error);\n return dates.length === 0 ? result : { ...result, dates };\n }),\n );\n\n return FunctionExecutor.of({\n execute: Effect.fn(\"FunctionExecutor.execute\")(function* (functionAddress, kind, resolved) {\n const invoke = (context: RuntimeHandlerContext) =>\n Effect.gen(() => resolved.definition.handler(context, resolved.args)).pipe(\n Effect.matchEffect({\n onFailure: (error) => encodeFailure(resolved.definition, error),\n onSuccess: (value) => encodeSuccess(resolved.definition, value),\n }),\n );\n\n const execution =\n kind === \"Query\"\n ? database.queryTransaction(resolved.schema, invoke)\n : mutationSemaphore.withPermits(1)(\n database\n .mutationTransaction(resolved.schema, (context) =>\n invoke(context).pipe(\n Effect.flatMap((result) =>\n result.type === \"Failure\"\n ? Effect.fail(MutationApplicationFailure.make({ error: result.error }))\n : Effect.succeed(result),\n ),\n ),\n )\n .pipe(\n Effect.catchTags({\n MutationApplicationFailure: ({ error }) =>\n Effect.succeed({ type: \"Failure\" as const, error }),\n }),\n ),\n );\n\n return yield* execution.pipe(\n Effect.orDie,\n Effect.catchCauseIf(\n (cause) => !Cause.hasInterruptsOnly(cause),\n (cause) => {\n const requestId = nanoid();\n return Effect.logError(`${functionAddress} failed during execution.`).pipe(\n Effect.annotateLogs({ cause, function: functionAddress, requestId }),\n Effect.as({\n type: \"Failure\" as const,\n error: { _tag: \"InternalServerError\", requestId },\n }),\n );\n },\n ),\n );\n }),\n });\n }),\n );\n}\n\n/** Adapts the Vite/SQLite development implementation to the shared runtime contract. */\nexport const functionRuntimeLayer = Layer.effect(\n FunctionRuntime,\n Effect.gen(function* () {\n const registry = yield* FunctionRegistry;\n const executor = yield* FunctionExecutor;\n return FunctionRuntime.of({\n prepare: Effect.fn(\"DevFunctionRuntime.prepare\")(function* (functionAddress, kind, args) {\n const resolved = yield* registry.resolve(functionAddress, kind, args);\n return { execute: executor.execute(functionAddress, kind, resolved) };\n }),\n });\n }),\n);\n","// @effect-diagnostics-next-line nodeBuiltinImport:off Vite exposes its HTTP server through Node's adapter types.\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport { NodeHttpServer, NodeServices, NodeSocket } from \"@effect/platform-node\";\nimport { SqliteClient } from \"@effect/sql-sqlite-node\";\nimport {\n ClientMessageJson,\n ServerMessageJson,\n type ClientMessage,\n type FunctionAddress,\n type Operation,\n type ProtocolErrorCode,\n type ServerMessage,\n type SubscriptionId,\n type WireResult,\n} from \"@ignotum/contracts/runtime/sync\";\nimport {\n Effect,\n Context,\n FileSystem,\n Function,\n FiberSet,\n HashMap,\n Layer,\n ManagedRuntime,\n Option,\n Path,\n PartitionedSemaphore,\n PubSub,\n Ref,\n Schema,\n Semaphore,\n} from \"effect\";\nimport { HttpServerRequest, HttpServerResponse } from \"effect/unstable/http\";\nimport type * as Socket from \"effect/unstable/socket/Socket\";\nimport type { Plugin, ViteDevServer } from \"vite\";\nimport { FunctionRuntime, type PreparedFunction } from \"@ignotum/runtime/functions\";\nimport { QueryInvalidation } from \"@ignotum/runtime/sync\";\n\nimport { generate } from \"../cli/codegen.js\";\nimport { isIgnotumPath, syncPath } from \"../internal/http-paths.js\";\nimport { LocalDatabase } from \"./database.js\";\nimport { idGeneratorLayer } from \"./id.js\";\nimport { FunctionExecutor, FunctionRegistry, functionRuntimeLayer } from \"./functions.js\";\n\ninterface QuerySubscription {\n readonly args: Schema.Json;\n readonly function: FunctionAddress;\n}\n\nexport { QueryInvalidation };\n\nexport const queryInvalidationLayer = Layer.effect(\n QueryInvalidation,\n Effect.gen(function* () {\n const pubsub = yield* PubSub.unbounded<void>();\n return QueryInvalidation.of({\n publish: PubSub.publish(pubsub, undefined),\n subscribe: PubSub.subscribe(pubsub),\n });\n }),\n);\n\nconst operationForQuery = (subscriptionId: SubscriptionId): Operation => ({\n type: \"Query\",\n id: subscriptionId,\n});\n\nconst protocolError = (\n code: ProtocolErrorCode,\n message: string,\n operation?: Operation,\n): ServerMessage => {\n if (operation === undefined) {\n return { type: \"ProtocolError\", code, message };\n }\n return { type: \"ProtocolError\", code, message, operation };\n};\n\nexport const runSession = Effect.fn(\"SyncServer.runSession\")(function* (socket: Socket.Socket) {\n const runtime = yield* FunctionRuntime;\n const invalidation = yield* QueryInvalidation;\n const subscriptions = yield* Ref.make(HashMap.empty<SubscriptionId, QuerySubscription>());\n const invocationFibers = yield* FiberSet.make();\n const querySemaphore = yield* PartitionedSemaphore.make<SubscriptionId>({ permits: 1 });\n const messageSemaphore = yield* Semaphore.make(1);\n const writeSemaphore = yield* Semaphore.make(1);\n const write = yield* socket.writer;\n\n const send = Effect.fn(\"SyncServer.send\")(function* (message: ServerMessage) {\n yield* writeSemaphore.withPermits(1)(\n Schema.encodeEffect(ServerMessageJson)(message).pipe(Effect.flatMap(write)),\n );\n });\n\n const sendResolutionError = (\n operation: Operation,\n error:\n | { readonly _tag: \"UnknownFunction\"; readonly message: string }\n | { readonly _tag: \"WrongFunctionKind\"; readonly message: string }\n | { readonly _tag: \"InvalidArguments\"; readonly message: string }\n | { readonly _tag: \"FunctionUnavailable\"; readonly message: string },\n deliver: (\n message: ServerMessage,\n ) => Effect.Effect<void, Schema.SchemaError | Socket.SocketError> = send,\n ) => {\n const code: ProtocolErrorCode = error._tag;\n return deliver(protocolError(code, error.message, operation));\n };\n\n const isActive = (subscriptionId: SubscriptionId, subscription: QuerySubscription) =>\n Ref.get(subscriptions).pipe(\n Effect.map(\n (current) => Option.getOrUndefined(HashMap.get(current, subscriptionId)) === subscription,\n ),\n );\n\n const sendIfActive = Effect.fn(\"SyncServer.sendIfActive\")(function* (\n subscriptionId: SubscriptionId,\n subscription: QuerySubscription,\n message: ServerMessage,\n ) {\n if (yield* isActive(subscriptionId, subscription)) {\n yield* send(message);\n }\n });\n\n const executeQuery = Effect.fn(\"SyncServer.executeQuery\")(function* (\n subscriptionId: SubscriptionId,\n subscription: QuerySubscription,\n previouslyPrepared?: PreparedFunction,\n ) {\n if (!(yield* isActive(subscriptionId, subscription))) return;\n\n const operation = operationForQuery(subscriptionId);\n const deliver = (message: ServerMessage) => sendIfActive(subscriptionId, subscription, message);\n const prepared =\n previouslyPrepared ??\n (yield* runtime.prepare(subscription.function, \"Query\", subscription.args).pipe(\n Effect.catchTags({\n FunctionUnavailable: (error) => sendResolutionError(operation, error, deliver),\n InvalidArguments: (error) => sendResolutionError(operation, error, deliver),\n UnknownFunction: (error) => sendResolutionError(operation, error, deliver),\n WrongFunctionKind: (error) => sendResolutionError(operation, error, deliver),\n }),\n ));\n if (prepared === undefined) return;\n\n const result = yield* prepared.execute;\n yield* deliver({\n type: \"QuerySnapshot\",\n id: subscriptionId,\n result,\n });\n });\n\n const scheduleQuery = (\n subscriptionId: SubscriptionId,\n subscription: QuerySubscription,\n previouslyPrepared?: PreparedFunction,\n ) =>\n querySemaphore\n .withPermits(\n subscriptionId,\n 1,\n )(executeQuery(subscriptionId, subscription, previouslyPrepared))\n .pipe(\n Effect.catchCause((cause) =>\n Effect.logError(\"A query refresh fiber failed.\").pipe(\n Effect.annotateLogs({ cause, function: subscription.function, subscriptionId }),\n ),\n ),\n FiberSet.run(invocationFibers),\n Effect.asVoid,\n );\n\n const refresh = Effect.fn(\"SyncServer.refresh\")(function* () {\n const current = yield* Ref.get(subscriptions);\n yield* Effect.forEach(HashMap.toEntries(current), ([subscriptionId, subscription]) =>\n scheduleQuery(subscriptionId, subscription),\n );\n });\n\n const invalidations = yield* invalidation.subscribe;\n yield* PubSub.take(invalidations).pipe(\n Effect.flatMap(refresh),\n Effect.forever,\n Effect.forkScoped,\n );\n\n const handleSubscribe = Effect.fn(\"SyncServer.handleSubscribe\")(function* (\n message: Extract<ClientMessage, { readonly type: \"Subscribe\" }>,\n ) {\n const operation = operationForQuery(message.id);\n const current = yield* Ref.get(subscriptions);\n\n if (HashMap.has(current, message.id)) {\n yield* send(\n protocolError(\n \"DuplicateOperationId\",\n `Subscription ${message.id} already exists.`,\n operation,\n ),\n );\n return;\n }\n\n const prepared = yield* runtime.prepare(message.function, \"Query\", message.args).pipe(\n Effect.catchTags({\n FunctionUnavailable: (error) => sendResolutionError(operation, error),\n InvalidArguments: (error) => sendResolutionError(operation, error),\n UnknownFunction: (error) => sendResolutionError(operation, error),\n WrongFunctionKind: (error) => sendResolutionError(operation, error),\n }),\n );\n\n if (prepared === undefined) {\n return;\n }\n\n const subscription = { args: message.args, function: message.function };\n yield* Ref.update(subscriptions, HashMap.set(message.id, subscription));\n yield* scheduleQuery(message.id, subscription, prepared);\n });\n\n const handleMutate = Effect.fn(\"SyncServer.handleMutate\")(function* (\n message: Extract<ClientMessage, { readonly type: \"Mutate\" }>,\n ) {\n const operation: Operation = { type: \"Mutate\", id: message.id };\n const prepared = yield* runtime.prepare(message.function, \"Mutation\", message.args).pipe(\n Effect.catchTags({\n FunctionUnavailable: (error) => sendResolutionError(operation, error),\n InvalidArguments: (error) => sendResolutionError(operation, error),\n UnknownFunction: (error) => sendResolutionError(operation, error),\n WrongFunctionKind: (error) => sendResolutionError(operation, error),\n }),\n );\n\n if (prepared === undefined) {\n return;\n }\n\n yield* prepared.execute.pipe(\n Effect.flatMap((result: WireResult) => {\n const response = send({ type: \"MutationResult\", id: message.id, result });\n return result.type === \"Success\"\n ? response.pipe(Effect.ensuring(invalidation.publish))\n : response;\n }),\n Effect.catchCause((cause) =>\n Effect.logError(\"A mutation invocation fiber failed.\").pipe(\n Effect.annotateLogs({ cause, function: message.function, requestId: message.id }),\n ),\n ),\n FiberSet.run(invocationFibers),\n Effect.asVoid,\n );\n });\n\n const handleMessage = Effect.fn(\"SyncServer.handleMessage\")(function* (text: string) {\n const message = yield* Schema.decodeEffect(ClientMessageJson)(text).pipe(\n Effect.catch(() =>\n send(protocolError(\"InvalidMessage\", \"The WebSocket frame is not valid Ignotum JSON.\")),\n ),\n );\n\n if (message === undefined) {\n return;\n }\n\n switch (message.type) {\n case \"Subscribe\":\n yield* handleSubscribe(message);\n return;\n case \"Unsubscribe\":\n yield* Ref.update(subscriptions, HashMap.remove(message.id));\n return;\n case \"Mutate\":\n yield* handleMutate(message);\n return;\n }\n });\n\n yield* socket.runString((text) => messageSemaphore.withPermits(1)(handleMessage(text)));\n});\n\ninterface SyncHandlersService {\n readonly http: (request: IncomingMessage, response: ServerResponse) => void;\n readonly upgrade: NodeJS.EventEmitter extends infer _EventEmitter\n ? (request: IncomingMessage, socket: import(\"node:stream\").Duplex, head: Buffer) => void\n : never;\n readonly reload: (file: string, event: \"add\" | \"change\" | \"unlink\") => Effect.Effect<void>;\n}\n\nclass SyncHandlers extends Context.Service<SyncHandlers, SyncHandlersService>()(\n \"ignotum/dev-runtime/sync/SyncHandlers\",\n) {}\n\nconst makeHandlersLayer = (\n server: ViteDevServer,\n projectDirectory: string,\n databasePath: string,\n) => {\n const databaseLayer = LocalDatabase.layer.pipe(\n Layer.provide(Layer.merge(idGeneratorLayer, SqliteClient.layer({ filename: databasePath }))),\n );\n const executorLayer = FunctionExecutor.layer.pipe(Layer.provide(databaseLayer));\n const devFunctionRuntimeLayer = functionRuntimeLayer.pipe(\n Layer.provide(\n Layer.merge(\n FunctionRegistry.layer(server, projectDirectory).pipe(Layer.provide(NodeServices.layer)),\n executorLayer,\n ),\n ),\n );\n const dependencies = Layer.mergeAll(\n devFunctionRuntimeLayer,\n queryInvalidationLayer,\n NodeServices.layer,\n );\n\n return Layer.effect(\n SyncHandlers,\n Effect.gen(function* () {\n const invalidation = yield* QueryInvalidation;\n const fileSystem = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const scope = yield* Effect.scope;\n const reloadSemaphore = yield* Semaphore.make(1);\n const webSocketServer = yield* Effect.acquireRelease(\n Effect.sync(\n () => new NodeSocket.NodeWS.WebSocketServer({ maxPayload: 1024 * 1024, noServer: true }),\n ),\n (instance) =>\n Effect.callback<void>((resume) => {\n instance.close(() => resume(Effect.void));\n }),\n );\n const httpApp = Effect.gen(function* () {\n const request = yield* HttpServerRequest.HttpServerRequest;\n const pathname = new URL(request.url, \"http://ignotum.local\").pathname;\n return yield* HttpServerResponse.json(\n pathname === syncPath\n ? { code: \"UpgradeRequired\", message: `Connect to ${syncPath} with WebSocket.` }\n : { code: \"NotFound\", message: \"Unknown Ignotum API route.\" },\n { status: pathname === syncPath ? 426 : 404 },\n );\n });\n const socketApp = Effect.gen(function* () {\n const request = yield* HttpServerRequest.HttpServerRequest;\n const socket = yield* request.upgrade;\n yield* runSession(socket);\n return HttpServerResponse.empty();\n });\n const http = yield* NodeHttpServer.makeHandler(httpApp, { scope });\n const upgrade = yield* NodeHttpServer.makeUpgradeHandler(\n Effect.succeed(webSocketServer),\n socketApp,\n { scope },\n );\n const serverDirectory = path.join(projectDirectory, \"server\");\n const reloadUnsafe = Effect.fn(\"SyncServer.reload\")(function* (\n file: string,\n event: \"add\" | \"change\" | \"unlink\",\n ) {\n const relative = path.relative(serverDirectory, file);\n if (relative.startsWith(\"..\") || path.isAbsolute(relative) || !file.endsWith(\".ts\")) {\n return;\n }\n\n if (event !== \"change\") {\n yield* generate(projectDirectory).pipe(\n Effect.provideService(FileSystem.FileSystem, fileSystem),\n Effect.provideService(Path.Path, path),\n );\n }\n yield* invalidation.publish;\n });\n const reload = (file: string, event: \"add\" | \"change\" | \"unlink\") =>\n reloadSemaphore\n .withPermits(1)(reloadUnsafe(file, event))\n .pipe(\n Effect.catchCause((cause) =>\n Effect.logError(\"Could not reload Ignotum server functions.\").pipe(\n Effect.annotateLogs({ cause, event, file }),\n ),\n ),\n );\n\n return SyncHandlers.of({ http, reload, upgrade });\n }),\n ).pipe(Layer.provide(dependencies));\n};\n\nconst isApiPath = (request: IncomingMessage): boolean => {\n const pathname = new URL(request.url ?? \"/\", \"http://ignotum.local\").pathname;\n return isIgnotumPath(pathname);\n};\n\nconst isAppOrigin = (host: string | undefined, origin: string | undefined): boolean => {\n if (host === undefined || origin === undefined) return false;\n\n return Option.match(Schema.decodeOption(Schema.URLFromString)(origin), {\n onNone: () => false,\n onSome: (url) => url.origin === origin && url.host === host,\n });\n};\n\nconst rejectUpgrade = (socket: import(\"node:stream\").Duplex): void => {\n socket.write(\"HTTP/1.1 403 Forbidden\\r\\nConnection: close\\r\\nContent-Length: 0\\r\\n\\r\\n\", () =>\n socket.destroy(),\n );\n};\n\nexport const syncPluginInternals = { isAppOrigin };\n\nexport const ignotumSyncPlugin: {\n (databasePath: string): (projectDirectory: string) => Plugin;\n (projectDirectory: string, databasePath: string): Plugin;\n} = Function.dual(2, (projectDirectory: string, databasePath: string): Plugin => ({\n name: \"ignotum:sync\",\n configureServer: (server) => {\n if (server.httpServer === null) {\n throw new Error(\"Ignotum sync requires Vite's Node HTTP server.\");\n }\n\n const runtime = ManagedRuntime.make(makeHandlersLayer(server, projectDirectory, databasePath));\n const httpServer = server.httpServer;\n return runtime.runPromise(SyncHandlers).then(\n (handlers) => {\n const onUpgrade = (\n request: IncomingMessage,\n socket: import(\"node:stream\").Duplex,\n head: Buffer,\n ) => {\n if (new URL(request.url ?? \"/\", \"http://ignotum.local\").pathname !== syncPath) return;\n if (!isAppOrigin(request.headers.host, request.headers.origin)) {\n rejectUpgrade(socket);\n return;\n }\n handlers.upgrade(request, socket, head);\n };\n const onAdd = (file: string) => runtime.runFork(handlers.reload(file, \"add\"));\n const onChange = (file: string) => runtime.runFork(handlers.reload(file, \"change\"));\n const onUnlink = (file: string) => runtime.runFork(handlers.reload(file, \"unlink\"));\n const cleanup = () => {\n httpServer.off(\"upgrade\", onUpgrade);\n server.watcher.off(\"add\", onAdd);\n server.watcher.off(\"change\", onChange);\n server.watcher.off(\"unlink\", onUnlink);\n void runtime.dispose();\n };\n\n httpServer.on(\"upgrade\", onUpgrade);\n httpServer.once(\"close\", cleanup);\n server.watcher.on(\"add\", onAdd);\n server.watcher.on(\"change\", onChange);\n server.watcher.on(\"unlink\", onUnlink);\n server.middlewares.use((request, response, next) => {\n if (!isApiPath(request)) {\n next();\n return;\n }\n handlers.http(request, response);\n });\n },\n (error) => {\n void runtime.dispose();\n throw error;\n },\n );\n },\n}));\n","import { createRequire } from \"node:module\";\nimport { fileURLToPath } from \"node:url\";\n\nimport prefresh from \"@prefresh/vite\";\nimport tailwindcss from \"@tailwindcss/vite\";\nimport { Effect, FileSystem, Path, Schema } from \"effect\";\nimport { createServer, defaultClientConditions, normalizePath } from \"vite\";\nimport type { Alias, ViteDevServer } from \"vite\";\n\nimport { generate } from \"./codegen.js\";\nimport { ignotumClientPlugin } from \"./client-plugin.js\";\nimport { acquireDevDatabaseLock, devDatabasePath } from \"../dev-runtime/dev-database.js\";\nimport { ignotumSyncPlugin } from \"../dev-runtime/sync.js\";\n\nconst requiredClientFiles = [\"App.tsx\", \"styles.css\"] as const;\nconst preactSpecifiers = [\n \"preact/jsx-dev-runtime\",\n \"preact/jsx-runtime\",\n \"preact/devtools\",\n \"preact/debug\",\n \"preact/hooks\",\n \"preact\",\n] as const;\nconst prefreshSpecifiers = [\"@prefresh/core\", \"@prefresh/utils\"] as const;\n\nexport class ClientFileNotFound extends Schema.TaggedError<ClientFileNotFound>()(\n \"ClientFileNotFound\",\n {\n message: Schema.String,\n path: Schema.String,\n },\n) {}\n\nexport class ClientRuntimeResolutionFailed extends Schema.TaggedError<ClientRuntimeResolutionFailed>()(\n \"ClientRuntimeResolutionFailed\",\n {\n cause: Schema.Defect(),\n message: Schema.String,\n },\n) {}\n\nexport class ViteStartupFailed extends Schema.TaggedError<ViteStartupFailed>()(\n \"ViteStartupFailed\",\n {\n cause: Schema.Defect(),\n message: Schema.String,\n },\n) {}\n\nexport interface DevOptions {\n readonly host: string;\n readonly open: boolean;\n readonly port: number;\n readonly projectDirectory: string;\n}\n\nconst validateClientFiles = Effect.fn(\"Dev.validateClientFiles\")(function* (\n projectDirectory: string,\n) {\n const fileSystem = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const clientDirectory = path.join(projectDirectory, \"client\");\n\n yield* Effect.forEach(\n requiredClientFiles,\n Effect.fn(\"Dev.validateClientFile\")(function* (fileName) {\n const filePath = path.join(clientDirectory, fileName);\n const exists = yield* fileSystem.exists(filePath);\n\n if (!exists) {\n return yield* ClientFileNotFound.make({\n message: `Required client file not found: ${filePath}`,\n path: filePath,\n });\n }\n }),\n { discard: true },\n );\n});\n\nconst resolveClientAliases = Effect.fn(\"Dev.resolveClientAliases\")(function* () {\n return yield* Effect.try({\n try: (): Array<Alias> => {\n const prefreshRequire = createRequire(import.meta.resolve(\"@prefresh/vite\"));\n\n return [\n {\n find: /^tailwindcss$/,\n replacement: normalizePath(fileURLToPath(import.meta.resolve(\"tailwindcss/index.css\"))),\n },\n ...preactSpecifiers.map((specifier) => ({\n find: specifier,\n replacement: normalizePath(fileURLToPath(import.meta.resolve(specifier))),\n })),\n ...prefreshSpecifiers.map((specifier) => ({\n find: specifier,\n replacement: normalizePath(prefreshRequire.resolve(specifier)),\n })),\n ];\n },\n catch: (cause) =>\n ClientRuntimeResolutionFailed.make({\n cause,\n message: \"Ignotum could not resolve its client runtime.\",\n }),\n });\n});\n\nconst acquireViteServer = Effect.fn(\"Dev.acquireViteServer\")(function* (options: DevOptions) {\n const fileSystem = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const aliases = yield* resolveClientAliases();\n const clientDirectory = path.join(options.projectDirectory, \"client\");\n const databasePath = yield* devDatabasePath(options.projectDirectory);\n const stateDirectory = path.dirname(databasePath);\n const sourceClientEntry = fileURLToPath(new URL(\"../../src/client/index.ts\", import.meta.url));\n const sourceContractsEntry = fileURLToPath(\n new URL(\"../../../contracts/src/schema/index.ts\", import.meta.url),\n );\n const hasSourceClient = yield* fileSystem.exists(sourceClientEntry);\n const hasSourceContracts = yield* fileSystem.exists(sourceContractsEntry);\n const hasWorkspaceSourceExports = hasSourceClient && hasSourceContracts;\n\n yield* fileSystem.makeDirectory(stateDirectory, { recursive: true });\n\n return yield* Effect.acquireRelease(\n Effect.tryPromise({\n try: () =>\n prefresh().then((prefreshPlugin) =>\n createServer({\n appType: \"spa\",\n configFile: false,\n mode: \"development\",\n root: clientDirectory,\n plugins: [\n ignotumSyncPlugin(options.projectDirectory, databasePath),\n ignotumClientPlugin(),\n prefreshPlugin,\n tailwindcss(),\n ],\n oxc: {\n jsx: {\n importSource: \"ignotum/client\",\n runtime: \"automatic\",\n },\n },\n resolve: {\n alias: aliases,\n conditions: [\n ...(hasWorkspaceSourceExports ? [\"@ignotum/source\"] : []),\n ...defaultClientConditions,\n ],\n dedupe: [\"preact\"],\n tsconfigPaths: true,\n },\n server: {\n forwardConsole: {\n logLevels: [\"warn\", \"error\"],\n unhandledErrors: true,\n },\n host: options.host,\n open: options.open,\n port: options.port,\n strictPort: true,\n },\n }),\n ),\n catch: (cause) =>\n ViteStartupFailed.make({\n cause,\n message: \"Ignotum could not create the Vite development server.\",\n }),\n }),\n (server) => Effect.promise(() => server.close()),\n );\n});\n\nconst listen = Effect.fn(\"Dev.listen\")(function* (server: ViteDevServer) {\n yield* Effect.tryPromise({\n try: () => server.listen(),\n catch: (cause) =>\n ViteStartupFailed.make({\n cause,\n message: \"Ignotum could not start the Vite development server.\",\n }),\n });\n});\n\nexport const dev = Effect.fn(\"Dev.run\")(function* (options: DevOptions) {\n yield* validateClientFiles(options.projectDirectory);\n yield* generate(options.projectDirectory);\n\n return yield* Effect.scoped(\n Effect.gen(function* () {\n yield* acquireDevDatabaseLock(options.projectDirectory);\n const server = yield* acquireViteServer(options);\n\n yield* listen(server);\n yield* Effect.sync(() => {\n server.printUrls();\n server.bindCLIShortcuts({ print: true });\n });\n return yield* Effect.never;\n }),\n );\n});\n","export default \"# AGENTS.md\\n\\nThis is an Ignotum app. Before changing it, read `.agents/skills/ignotum/SKILL.md`.\\n\\nThe skill explains how to inspect the project, which bundled reference to read, and how to check\\nyour changes.\\n\";","export default \"---\\nname: ignotum\\ndescription: Build and modify an Ignotum app. Use when working on its schema, server functions, generated API, client UI, or local development workflow.\\n---\\n\\n# Working on an Ignotum app\\n\\nAn Ignotum app defines a database schema, server functions, and a JSX client. Ignotum supplies the\\ndatabase runtime, generated bindings, realtime query updates, Vite dev server, JSX runtime, and\\nTailwind setup.\\n\\nThe current release supports local development. Do not assume that authentication, files, actions,\\nworkflows, scheduled jobs, or production deployment APIs exist.\\n\\n## Start with the app\\n\\nInspect `server/schema.ts`, the function modules in `server`, the files in `client`, `package.json`,\\nand `tsconfig.json` before changing code.\\n\\nTreat `_generated` as compiler output. Read it when you need to understand an inferred type, but do\\nnot edit it. After code changes, regenerate the bindings and run the typechecker:\\n\\n```sh\\nnpx ignotum codegen\\nnpx tsc --noEmit\\n```\\n\\nFor normal Ignotum app work, do not add an HTML file, Vite configuration, Tailwind configuration,\\nAPI routes, or direct database setup.\\n\\n## Read the relevant reference\\n\\nThe bundled references are the Ignotum user guides. Read only the guides needed for the task:\\n\\n- For project creation and installation, read [getting started](references/getting-started.md) or\\n [manual setup](references/manual-setup.md).\\n- For tables, fields, IDs, and generated document types, read\\n [schema syntax](references/schema.md).\\n- For validators and their TypeScript types, read [values](references/values.md).\\n- For queries, mutations, database access, Results, and application errors, read\\n [server functions](references/server-functions.md).\\n- For hooks, query state, mutations, JSX, and Tailwind, read [client](references/client.md).\\n- For development commands, code generation, flags, and local data, read\\n [dev server](references/dev-server.md).\\n- For the complete guide list, read the [documentation index](references/index.md).\\n\\n## Rules that cross guide boundaries\\n\\n- Define tables in `server/schema.ts`.\\n- Put queries and mutations in TypeScript files directly inside `server`.\\n- Import server builders from `@/_generated/server.js` and client references from\\n `@/_generated/api.js`. Keep the `.js` suffix.\\n- Put code used by both the client and server in `shared` and import it through `@/shared`.\\n- Never edit `_generated`.\\n- Use JSX and hooks from `ignotum/client`, not React or Preact packages directly.\\n- Keep the app inside Ignotum's current model unless the user explicitly asks to move beyond it.\\n\";","export default \"# Client\\n\\nIgnotum apps use JSX, hooks from `ignotum/client`, and Tailwind CSS. Import server function\\nreferences from `@/_generated/api.js`:\\n\\n```tsx\\nimport { Query, Result, useMutation, useQuery } from \\\"ignotum/client\\\";\\n\\nimport { api } from \\\"@/_generated/api.js\\\";\\n```\\n\\n## Tailwind CSS\\n\\nEvery app has `client/styles.css` with the Tailwind import:\\n\\n```css\\n@import \\\"tailwindcss\\\";\\n```\\n\\nStyle JSX with Tailwind utility classes. Use the JSX `class` attribute:\\n\\n```tsx\\nexport default function App() {\\n return (\\n <main class=\\\"mx-auto max-w-xl px-6 py-16\\\">\\n <h1 class=\\\"text-2xl font-semibold text-zinc-950\\\">Todos</h1>\\n </main>\\n );\\n}\\n```\\n\\nThe dev server loads `styles.css` and configures Tailwind. The app does not need a Tailwind\\nconfiguration file.\\n\\n## Run a query\\n\\n`useQuery` takes a generated query reference. Pass the typed arguments when the query declares\\nthem:\\n\\n```tsx\\nconst todos = useQuery(api.todos.list);\\nconst todo = useQuery(api.todos.get, { id });\\nconst selectedTodo = useQuery(api.todos.get, id === undefined ? Query.skip : { id });\\n```\\n\\n`Query.skip` keeps a query pending without opening a subscription. Use it when the arguments are\\nnot available yet.\\n\\nThe first value is pending. Match every state with `Result.match`:\\n\\n```tsx\\nreturn Result.match(todos, {\\n pending: () => <p class=\\\"text-zinc-500\\\">Loading...</p>,\\n value: (items) => (\\n <ul>\\n {items.map((todo) => (\\n <li key={todo.id}>{todo.text}</li>\\n ))}\\n </ul>\\n ),\\n});\\n```\\n\\nIgnotum keeps an active query up to date. A successful mutation refreshes subscribed queries in\\nevery open client.\\n\\n## Run a mutation\\n\\n`useMutation` takes a generated mutation reference and returns a function:\\n\\n```tsx\\nconst createTodo = useMutation(api.todos.create);\\n\\nvoid createTodo({ text }).then(\\n Result.match({\\n value: (id) => console.log(id),\\n error: {\\n InvalidTodoText: ({ text }) => console.log(`Invalid text: ${text}`),\\n TodoLimitReached: ({ limit }) => console.log(`The limit is ${limit}`),\\n },\\n internalError: ({ requestId }) => console.log(`Request ${requestId} failed.`),\\n }),\\n);\\n```\\n\\nAn argument-free mutation returns a zero-argument function:\\n\\n```tsx\\nconst clearTodos = useMutation(api.todos.clear);\\nvoid clearTodos();\\n```\\n\\nThe client `Result` API only inspects completed server responses. Server-only operations such as\\n`Result.fail`, `Result.succeed`, `Result.try`, `yield*`, and `.catch()` are not available here.\\n\\nApplication errors are handled by `error`, either with one function or an exhaustive map keyed by\\n`_tag`. An `InternalServerError` contains a request ID and is thrown when `Result.match` has no\\n`internalError` handler. During rendering, it reaches the nearest UI error boundary. A mutation can\\nhandle it locally with `internalError`, as above. Connection and protocol failures reject mutation\\npromises; query connection failures go to the nearest UI error boundary.\\n\";","export default \"# Dev server\\n\\nRun the dev server from the project root:\\n\\n```sh\\nnpx ignotum dev\\n```\\n\\nIt expects these files:\\n\\n```text\\nclient/App.tsx\\nclient/styles.css\\nserver/schema.ts\\n```\\n\\nThe dev server generates the client and server bindings, mounts the default export from\\n`client/App.tsx`, loads Tailwind from `client/styles.css`, and serves the app at\\n<http://127.0.0.1:3210>. It reloads client and server changes and updates active queries after\\nserver changes and successful mutations.\\n\\nYou do not need an HTML file, Vite configuration, or Tailwind configuration.\\n\\n## Flags\\n\\nUse flags to change the address or open the browser:\\n\\n```sh\\nnpx ignotum dev --host 0.0.0.0 --port 3000 --open\\n```\\n\\nThe defaults are host `127.0.0.1`, port `3210`, and no automatic browser opening.\\n\\n## Code generation\\n\\nThe dev server runs code generation when it starts. It updates generated files when you add or\\nremove a server function file.\\n\\nRun code generation before typechecking without the dev server:\\n\\n```sh\\nnpx ignotum codegen\\nnpx tsc --noEmit\\n```\\n\\nIgnotum creates:\\n\\n- `_generated/server.ts` with schema-bound `query`, `mutation`, and `values` exports;\\n- `_generated/api.ts` with client references such as `api.todos.list`;\\n- `_generated/types.ts` with `DataModel`, `Doc`, and `Id`.\\n\\nDo not edit generated files.\\n\\n## Local data\\n\\nData persists between dev-server restarts. Stop the server and reset that data with:\\n\\n```sh\\nnpx ignotum dev db reset\\n```\\n\";","export default \"# Getting started\\n\\nIgnotum requires Node.js 22.18 or newer.\\n\\nCreate an app:\\n\\n```sh\\nnpx ignotum new my-app\\ncd my-app\\nnpx ignotum dev\\n```\\n\\nOpen <http://127.0.0.1:3210>. The generated app is a small counter with a schema, a query, a\\nmutation, and a JSX client.\\n\\n`ignotum new` installs dependencies with pnpm when it is available. It falls back to npm only when\\npnpm is not installed. It generates `_generated`, initializes a Git repository, and creates an\\n`Init` commit containing the generated files after the rest of the setup finishes.\\n\\nPass `.` to create the app in the current directory. The directory must be empty:\\n\\n```sh\\nnpx ignotum new .\\n```\\n\\nUse `--no-git` to skip Git or `--no-install` to skip dependency installation. You can install the\\ndependencies later with the same pnpm and npm fallback behavior:\\n\\n```sh\\nnpx ignotum install\\n```\\n\\nRead [schema syntax](schema.md), [server functions](server-functions.md), and the\\n[client guide](client.md) to build the app. The [manual setup](manual-setup.md) recreates the counter\\napp without `ignotum new`.\\n\";","export default \"# Ignotum\\n\\nAn Ignotum app has a schema, server functions, and a client. Ignotum is opinionated about the\\nclient tooling. Every app uses JSX, hooks from `ignotum/client`, and Tailwind CSS.\\n\\nThe current release supports local development.\\n\\n- [Getting started](getting-started.md) creates and runs a counter app with `ignotum new`.\\n- [Manual setup](manual-setup.md) recreates the generated counter app by hand.\\n- [Schema syntax](schema.md) covers tables, fields, IDs, and generated document types.\\n- [Values](values.md) lists every value validator and its TypeScript type.\\n- [Server functions](server-functions.md) covers queries, mutations, database access, and errors.\\n- [Client](client.md) covers queries, mutations, results, and Tailwind styling.\\n- [Dev server](dev-server.md) covers local development, code generation, flags, and data reset.\\n\";","export default \"# Manual setup\\n\\nIgnotum requires Node.js 22.18 or newer. This guide recreates the counter app from `ignotum new`\\nwithout running the project generator. It uses pnpm to install dependencies.\\n\\nCreate the project directory:\\n\\n```sh\\nmkdir my-ignotum-app\\ncd my-ignotum-app\\n```\\n\\nCreate this structure:\\n\\n```text\\nmy-ignotum-app/\\n client/\\n App.tsx\\n styles.css\\n server/\\n counter.ts\\n schema.ts\\n shared/\\n utils.ts\\n package.json\\n tsconfig.json\\n```\\n\\n## Configure the package\\n\\nAdd `package.json`:\\n\\n```json\\n{\\n \\\"name\\\": \\\"my-ignotum-app\\\",\\n \\\"private\\\": true,\\n \\\"version\\\": \\\"0.0.0\\\",\\n \\\"type\\\": \\\"module\\\",\\n \\\"scripts\\\": {\\n \\\"typecheck\\\": \\\"ignotum codegen && tsc --noEmit\\\"\\n },\\n \\\"dependencies\\\": {\\n \\\"ignotum\\\": \\\"latest\\\"\\n },\\n \\\"devDependencies\\\": {\\n \\\"typescript\\\": \\\"^7.0.2\\\"\\n },\\n \\\"engines\\\": {\\n \\\"node\\\": \\\">=22.18.0\\\"\\n }\\n}\\n```\\n\\nInstall the dependencies:\\n\\n```sh\\npnpm install\\n```\\n\\n## Configure TypeScript\\n\\nAdd `tsconfig.json`:\\n\\n```json\\n{\\n \\\"compilerOptions\\\": {\\n \\\"target\\\": \\\"ES2023\\\",\\n \\\"lib\\\": [\\\"ES2023\\\", \\\"DOM\\\", \\\"DOM.Iterable\\\"],\\n \\\"module\\\": \\\"NodeNext\\\",\\n \\\"moduleResolution\\\": \\\"NodeNext\\\",\\n \\\"jsx\\\": \\\"react-jsx\\\",\\n \\\"jsxImportSource\\\": \\\"ignotum/client\\\",\\n \\\"strict\\\": true,\\n \\\"noEmit\\\": true,\\n \\\"skipLibCheck\\\": true,\\n \\\"paths\\\": {\\n \\\"@/*\\\": [\\\"./*\\\"]\\n }\\n },\\n \\\"include\\\": [\\\"_generated\\\", \\\"client\\\", \\\"server\\\", \\\"shared\\\"]\\n}\\n```\\n\\n## Add shared code\\n\\nAdd `shared/utils.ts`:\\n\\n```ts\\nexport const counterIncrement = 1;\\n```\\n\\nBoth the client and server can import files in `shared` through `@/shared`.\\n\\n## Define the schema\\n\\nAdd `server/schema.ts`:\\n\\n```ts\\nimport { defineSchema } from \\\"ignotum/server\\\";\\n\\nexport default defineSchema(({ table, values }) => ({\\n counters: table({\\n value: values.number(),\\n }),\\n}));\\n```\\n\\n## Add the server functions\\n\\nAdd `server/counter.ts`:\\n\\n```ts\\nimport { mutation, query, values } from \\\"@/_generated/server.js\\\";\\nimport { counterIncrement } from \\\"@/shared/utils.js\\\";\\n\\nexport const get = query({\\n returns: values.number(),\\n\\n handler: function* (ctx) {\\n const counters = yield* ctx.db.query(\\\"counters\\\").collect();\\n return counters[0]?.value ?? 0;\\n },\\n});\\n\\nexport const increment = mutation({\\n returns: values.number(),\\n\\n handler: function* (ctx) {\\n const counters = yield* ctx.db.query(\\\"counters\\\").collect();\\n const counter = counters[0];\\n const value = (counter?.value ?? 0) + counterIncrement;\\n\\n if (counter === undefined) {\\n yield* ctx.db.insert(\\\"counters\\\", { value });\\n } else {\\n yield* ctx.db.patch(\\\"counters\\\", counter.id, { value });\\n }\\n\\n return value;\\n },\\n});\\n```\\n\\nKeep the `.js` suffix on imports from `@/_generated`, even though the generated files use\\nTypeScript.\\n\\n## Add the client\\n\\nAdd `client/styles.css`:\\n\\n```css\\n@import \\\"tailwindcss\\\";\\n```\\n\\nAdd `client/App.tsx`:\\n\\n```tsx\\nimport { Result, useMutation, useQuery } from \\\"ignotum/client\\\";\\n\\nimport { api } from \\\"@/_generated/api.js\\\";\\nimport { counterIncrement } from \\\"@/shared/utils.js\\\";\\n\\nexport default function App() {\\n const count = useQuery(api.counter.get);\\n const increment = useMutation(api.counter.increment);\\n\\n return (\\n <main class=\\\"mx-auto max-w-sm px-6 py-20 text-center\\\">\\n <h1 class=\\\"text-2xl font-semibold\\\">Counter</h1>\\n {Result.match(count, {\\n pending: () => <p class=\\\"mt-6\\\">Loading...</p>,\\n value: (value) => (\\n <>\\n <p class=\\\"my-6 text-5xl tabular-nums\\\">{value}</p>\\n <button\\n class=\\\"rounded bg-zinc-900 px-4 py-2 text-white\\\"\\n type=\\\"button\\\"\\n onClick={() => void increment()}\\n >\\n Increment by {counterIncrement}\\n </button>\\n </>\\n ),\\n })}\\n </main>\\n );\\n}\\n```\\n\\nIgnotum loads Tailwind from `client/styles.css`. You do not need an HTML file, Vite configuration,\\nor Tailwind configuration.\\n\\n## Run the app\\n\\nStart the dev server:\\n\\n```sh\\nnpx ignotum dev\\n```\\n\\nOpen <http://127.0.0.1:3210>. Ignotum creates `_generated` before starting the app.\\n\\nRead [schema syntax](schema.md), [server functions](server-functions.md), and the\\n[client guide](client.md) to continue building the app.\\n\";","export default \"# Schema syntax\\n\\nDefine the data model in `server/schema.ts`. The keys returned from `defineSchema` are table\\nnames, and each `table` call defines that table's fields:\\n\\n```ts\\nimport { defineSchema } from \\\"ignotum/server\\\";\\n\\nexport default defineSchema(({ table, values }) => ({\\n users: table({\\n name: values.string(),\\n }),\\n todos: table({\\n text: values.string(),\\n completed: values.boolean(),\\n ownerId: values.optional(values.id(\\\"users\\\")),\\n }),\\n}));\\n```\\n\\n## Field values\\n\\nRead [values](values.md) for the complete validator list and the TypeScript type produced by each\\none. `values.id` only accepts a table declared in the same schema. Arrays and objects can be nested,\\nand their contents can use any value validator.\\n\\n## System fields\\n\\nIgnotum adds three fields to every stored document:\\n\\n| Field | Type |\\n| ----------- | ------------------------- |\\n| `id` | The ID type for its table |\\n| `createdAt` | `Date` |\\n| `updatedAt` | `Date` |\\n\\nDo not declare these fields in a table. Do not pass them to `insert`, `patch`, or `replace`.\\n\\n## Generated types\\n\\n`_generated/types.ts` exports the data model, document, and ID types:\\n\\n```ts\\nimport type { DataModel, Doc, Id } from \\\"@/_generated/types.js\\\";\\n\\ntype Todo = Doc<\\\"todos\\\">;\\ntype TodoId = Id<\\\"todos\\\">;\\n```\\n\\n`Doc<\\\"todos\\\">` includes the fields from the `todos` table and its three system fields. An\\n`Id<\\\"todos\\\">` cannot be passed where an `Id<\\\"users\\\">` is required.\\n\";","export default \"# Server functions\\n\\nPut queries and mutations in `.ts` files directly inside `server`. The file name becomes the API\\nmodule, and each exported function keeps its export name:\\n\\n```text\\nserver/todos.ts -> api.todos.list\\nserver/users.ts -> api.users.get\\n```\\n\\nIgnotum ignores `schema.ts`, `index.ts`, test files, and names beginning with `_`.\\n\\nImport schema-bound builders from the generated server file. Import `Result` only when the module\\nintroduces or catches typed errors:\\n\\n```ts\\nimport { Result } from \\\"ignotum/server\\\";\\n\\nimport { mutation, query, values } from \\\"@/_generated/server.js\\\";\\n```\\n\\nKeep the `.js` suffix on generated imports.\\n\\n## Define a function\\n\\nA function has optional argument, return, and public error schemas, plus a generator handler:\\n\\n```ts\\nexport const getTitle = query({\\n args: {\\n id: values.id(\\\"todos\\\"),\\n },\\n returns: values.string(),\\n\\n handler: function* (ctx, args) {\\n const todo = yield* ctx.db.get(\\\"todos\\\", args.id);\\n return todo.text;\\n },\\n});\\n```\\n\\nOmit `args` when the function takes no arguments. Omit `returns` when it returns nothing. An\\nomitted `returns` only permits a `void` handler; Ignotum never infers an unchecked return schema.\\n`yield*` waits for an Ignotum operation and propagates its typed application errors. Return\\nsuccessful values with ordinary `return`.\\n\\nIgnotum validates arguments before running the handler. It also validates returned values and\\npublic application errors before sending them to a client.\\n\\nAn argument-free query and a mutation with no return value can stay small:\\n\\n```ts\\nexport const list = query({\\n returns: values.array(Todo),\\n\\n handler: function* (ctx) {\\n return yield* ctx.db.query(\\\"todos\\\").collect();\\n },\\n});\\n\\nexport const remove = mutation({\\n args: { id: values.id(\\\"todos\\\") },\\n\\n handler: function* (ctx, args) {\\n yield* ctx.db.delete(\\\"todos\\\", args.id);\\n },\\n});\\n```\\n\\nCall an argument-free query as `useQuery(api.todos.list)`. An argument-free mutation returns a\\nzero-argument function:\\n\\n```ts\\nconst clear = useMutation(api.todos.clear);\\nvoid clear();\\n```\\n\\n## Database reads\\n\\nUse `find` when a missing document is a normal result:\\n\\n```ts\\nconst todo = yield * ctx.db.find(\\\"todos\\\", args.id);\\n// Todo | undefined\\n```\\n\\nUse `get` when the document should exist:\\n\\n```ts\\nconst todo = yield * ctx.db.get(\\\"todos\\\", args.id);\\n// Todo\\n```\\n\\nA missing `get` fails with a typed `DocumentNotFound` value containing `table` and `id`. Collect a\\nwhole table through a query:\\n\\n```ts\\nconst todos = yield * ctx.db.query(\\\"todos\\\").collect();\\n```\\n\\nQuery handlers only receive read methods.\\n\\n## Database writes\\n\\nMutation handlers receive the read methods and these writes:\\n\\n```ts\\nconst id =\\n yield *\\n ctx.db.insert(\\\"todos\\\", {\\n text: \\\"Learn Ignotum\\\",\\n completed: false,\\n });\\n\\nyield * ctx.db.patch(\\\"todos\\\", id, { completed: true });\\n\\nyield *\\n ctx.db.replace(\\\"todos\\\", id, {\\n text: \\\"Build an app\\\",\\n completed: false,\\n });\\n\\nyield * ctx.db.delete(\\\"todos\\\", id);\\n```\\n\\n`patch` changes only supplied fields. `replace` requires every non-optional table field. Ignotum\\nrolls back a mutation when its handler fails with a typed application error or encounters an\\ninternal failure.\\n\\n## Application errors\\n\\nDefine an application error with `values.error`. Its name becomes `_tag`:\\n\\n```ts\\nconst TodoNotFound = values.error(\\\"TodoNotFound\\\", {\\n id: values.id(\\\"todos\\\"),\\n});\\n```\\n\\n`Result.fail` deliberately stops the operation with a typed error:\\n\\n```ts\\nyield * Result.fail(TodoNotFound({ id: args.id }));\\n```\\n\\nThe `errors` field is optional. If omitted, Ignotum infers the handler's remaining application\\nerrors. If supplied, it is the public contract and the handler must conform to it:\\n\\n```ts\\nexport const toggle = mutation({\\n args: {\\n id: values.id(\\\"todos\\\"),\\n },\\n returns: values.boolean(),\\n errors: TodoNotFound,\\n\\n handler: function* (ctx, args) {\\n const todo = yield* ctx.db.get(\\\"todos\\\", args.id).catch({\\n DocumentNotFound: (error) => Result.fail(TodoNotFound({ id: error.id })),\\n });\\n\\n const completed = !todo.completed;\\n yield* ctx.db.patch(\\\"todos\\\", args.id, { completed });\\n return completed;\\n },\\n});\\n```\\n\\nCombine public errors with `values.union`:\\n\\n```ts\\nerrors: values.union(InvalidTodoText, TodoLimitReached),\\n```\\n\\n## Catch and recover\\n\\nEvery Result operation has a partial, tag-based `catch`. Handlers receive the narrowed error type.\\nUnmatched errors continue through the channel:\\n\\n```ts\\nconst settings =\\n yield *\\n loadSettings().catch({\\n SettingsNotFound: () => defaultSettings,\\n });\\n```\\n\\nReturn a plain value to recover. Return `Result.fail(...)` to map one error to another. Unknown tag\\nnames fail the TypeScript check.\\n\\nUse `Result.try` for one catch boundary around several operations:\\n\\n```ts\\nconst author =\\n yield *\\n Result.try(function* () {\\n const membership = yield* ctx.db.get(\\\"memberships\\\", topic.membershipId);\\n return yield* ctx.db.get(\\\"users\\\", membership.userId);\\n }).catch({\\n DocumentNotFound: () => Result.fail(InvalidAuthor({ topicId: topic.id })),\\n });\\n```\\n\\nThere is no async variant. Ignotum operations always use `yield*` in server code.\\n\\n## Standalone results\\n\\n`Result.succeed` remains useful for helpers that return a Result:\\n\\n```ts\\nfunction validateName(name: string) {\\n if (name.length === 0) {\\n return Result.fail(InvalidName({}));\\n }\\n\\n return Result.succeed(name.trim());\\n}\\n```\\n\\nA handler can use the helper with `const name = yield* validateName(args.name)`. Normal handlers do\\nnot wrap successful returns in `Result.succeed`.\\n\\n## Internal failures and defects\\n\\nDatabase outages, internal runtime failures, and thrown JavaScript exceptions are not application\\nerrors. Ignotum logs their full cause and sends only:\\n\\n```ts\\n{\\n _tag: \\\"InternalServerError\\\",\\n requestId: \\\"...\\\",\\n}\\n```\\n\\nEvery generated client function includes `InternalServerError` in its Result error union. The\\nrequest ID links the client-visible failure to server logs without exposing private details.\\n`InternalServerError` is reserved by Ignotum: never define it with `values.error` or include it in a\\nfunction's `errors` schema.\\n\";","export default \"# Values\\n\\nUse `values` validators to describe table fields, function arguments, return values, and application\\nerrors. Each validator checks values at runtime and supplies the matching TypeScript type.\\n\\n| Validator | TypeScript type | Notes |\\n| ----------------------------------------- | ------------------------------------- | ---------------------------------------------------------------------------------------------------- |\\n| `values.string()` | `string` | |\\n| `values.number()` | `number` | Accepts finite JavaScript numbers, including integers. |\\n| `values.integer()` | `number` | Accepts safe integers. |\\n| `values.boolean()` | `boolean` | |\\n| `values.date()` | `Date` | Accepts valid JavaScript dates. |\\n| `values.null()` | `null` | Accepts only `null`. |\\n| `values.literal(value)` | The exact type of `value` | Accepts one string, finite number, or boolean value. |\\n| `values.literals(first, second, ...rest)` | A union of the supplied literal types | Requires at least two string, finite number, or boolean values. |\\n| `values.id(\\\"todos\\\")` | `Id<\\\"todos\\\">` | Accepts an ID for a table declared in the same schema. IDs for different tables are different types. |\\n| `values.optional(value)` | `T \\\\| undefined` | Makes an object or table field optional. The field may be omitted. |\\n| `values.nullable(value)` | `T \\\\| null` | The value remains required unless it is also wrapped with `optional`. |\\n| `values.array(value)` | `ReadonlyArray<T>` | Every item must match `value`. |\\n| `values.object(fields)` | An object matching `fields` | Defines an object with known field names. |\\n| `values.record(value)` | `Readonly<Record<string, T>>` | Defines an object with dynamic string keys whose values all match `value`. |\\n| `values.union(...values)` | A union of the supplied types | Accepts a value matching any supplied validator. |\\n| `values.never()` | `never` | No value can pass this validator. |\\n| `values.error(\\\"Name\\\", fields)` | A tagged error object | Defines an application error whose `_tag` is the supplied name. |\\n\\n`T` means the TypeScript type produced by the wrapped validator.\\n\\n## Examples\\n\\n```ts\\nconst TodoStatus = values.literals(\\\"pending\\\", \\\"completed\\\");\\n\\nconst Todo = values.object({\\n status: TodoStatus,\\n scheduledAt: values.nullable(values.date()),\\n scores: values.record(values.integer()),\\n title: values.string(),\\n});\\n```\\n\\nUse `optional` when a field may be absent. Use `nullable` when a present field may contain `null`:\\n\\n```ts\\nvalues.object({\\n nickname: values.optional(values.string()),\\n deletedAt: values.nullable(values.date()),\\n});\\n```\\n\";","import agents from \"../../../../docs/agent/AGENTS.md?raw\";\nimport skill from \"../../../../docs/agent/skills/ignotum/SKILL.md?raw\";\nimport client from \"../../../../docs/user/client.md?raw\";\nimport devServer from \"../../../../docs/user/dev-server.md?raw\";\nimport gettingStarted from \"../../../../docs/user/getting-started.md?raw\";\nimport index from \"../../../../docs/user/index.md?raw\";\nimport manualSetup from \"../../../../docs/user/manual-setup.md?raw\";\nimport schema from \"../../../../docs/user/schema.md?raw\";\nimport serverFunctions from \"../../../../docs/user/server-functions.md?raw\";\nimport values from \"../../../../docs/user/values.md?raw\";\n\nexport interface ProjectFile {\n readonly content: string;\n readonly path: string;\n}\n\nconst references = [\n [\"client.md\", client],\n [\"dev-server.md\", devServer],\n [\"getting-started.md\", gettingStarted],\n [\"index.md\", index],\n [\"manual-setup.md\", manualSetup],\n [\"schema.md\", schema],\n [\"server-functions.md\", serverFunctions],\n [\"values.md\", values],\n] as const;\n\nexport const agentProjectFiles: ReadonlyArray<ProjectFile> = [\n { content: agents, path: \"AGENTS.md\" },\n { content: skill, path: \".agents/skills/ignotum/SKILL.md\" },\n ...references.map(([name, content]) => ({\n content,\n path: `.agents/skills/ignotum/references/${name}`,\n })),\n];\n","import { Effect, Schema } from \"effect\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/unstable/process\";\n\nexport type PackageManager = \"npm\" | \"pnpm\";\n\nexport class DependencyInstallationFailed extends Schema.TaggedError<DependencyInstallationFailed>()(\n \"DependencyInstallationFailed\",\n {\n cause: Schema.optional(Schema.Defect()),\n message: Schema.String,\n path: Schema.String,\n },\n) {}\n\nconst installWith = Effect.fn(\"PackageManager.installWith\")(function* (\n projectDirectory: string,\n packageManager: PackageManager,\n) {\n const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n const exitCode = yield* spawner.exitCode(\n ChildProcess.make(packageManager, [\"install\"], {\n cwd: projectDirectory,\n stderr: \"inherit\",\n stdin: \"inherit\",\n stdout: \"inherit\",\n }),\n );\n\n if (exitCode !== ChildProcessSpawner.ExitCode(0)) {\n return yield* DependencyInstallationFailed.make({\n message: `${packageManager} install exited with code ${exitCode} in ${projectDirectory}.`,\n path: projectDirectory,\n });\n }\n\n return packageManager;\n});\n\nexport const installDependencies = Effect.fn(\"PackageManager.installDependencies\")(function* (\n projectDirectory: string,\n) {\n return yield* installWith(projectDirectory, \"pnpm\").pipe(\n Effect.catchReasons(\"PlatformError\", {\n NotFound: () => installWith(projectDirectory, \"npm\"),\n }),\n Effect.catchTags({\n PlatformError: (cause) =>\n DependencyInstallationFailed.make({\n cause,\n message: `Could not run pnpm or npm in ${projectDirectory}.`,\n path: projectDirectory,\n }),\n }),\n );\n});\n","import { Effect, FileSystem, Path, Schema, String } from \"effect\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/unstable/process\";\n\nimport { agentProjectFiles, type ProjectFile } from \"./agent-files.js\";\nimport { generate } from \"./codegen.js\";\nimport { installDependencies, type PackageManager } from \"./package-manager.js\";\n\nexport interface NewProjectOptions {\n readonly currentDirectory: string;\n readonly directory: string;\n readonly git: boolean;\n readonly install: boolean;\n}\n\nexport interface NewProjectResult {\n readonly directory: string;\n readonly gitInitialized: boolean;\n readonly packageManager: PackageManager | null;\n readonly projectName: string;\n}\n\nexport class ProjectDirectoryNotEmpty extends Schema.TaggedError<ProjectDirectoryNotEmpty>()(\n \"ProjectDirectoryNotEmpty\",\n {\n message: Schema.String,\n path: Schema.String,\n },\n) {}\n\nexport class InvalidProjectName extends Schema.TaggedError<InvalidProjectName>()(\n \"InvalidProjectName\",\n {\n message: Schema.String,\n path: Schema.String,\n },\n) {}\n\nexport class GitInitializationFailed extends Schema.TaggedError<GitInitializationFailed>()(\n \"GitInitializationFailed\",\n {\n cause: Schema.optional(Schema.Defect()),\n message: Schema.String,\n path: Schema.String,\n },\n) {}\n\nconst packageJson = (projectName: string): string =>\n `${JSON.stringify(\n {\n name: projectName,\n private: true,\n version: \"0.0.0\",\n type: \"module\",\n scripts: {\n typecheck: \"ignotum codegen && tsc --noEmit\",\n },\n dependencies: {\n ignotum: \"latest\",\n },\n devDependencies: {\n typescript: \"^7.0.2\",\n },\n engines: {\n node: \">=22.18.0\",\n },\n },\n null,\n 2,\n )}\\n`;\n\nconst tsconfig = `{\n \"compilerOptions\": {\n \"target\": \"ES2023\",\n \"lib\": [\"ES2023\", \"DOM\", \"DOM.Iterable\"],\n \"module\": \"NodeNext\",\n \"moduleResolution\": \"NodeNext\",\n \"jsx\": \"react-jsx\",\n \"jsxImportSource\": \"ignotum/client\",\n \"strict\": true,\n \"noEmit\": true,\n \"skipLibCheck\": true,\n \"paths\": {\n \"@/*\": [\"./*\"]\n }\n },\n \"include\": [\"_generated\", \"client\", \"server\", \"shared\"]\n}\n`;\n\nconst gitignore = `node_modules/\n.ignotum/\n\n.env\n.env.*\n!.env.example\n\n.DS_Store\nThumbs.db\n`;\n\nconst schema = `import { defineSchema } from \"ignotum/server\";\n\nexport default defineSchema(({ table, values }) => ({\n counters: table({\n value: values.number(),\n }),\n}));\n`;\n\nconst counterFunctions = `import { mutation, query, values } from \"@/_generated/server.js\";\nimport { counterIncrement } from \"@/shared/utils.js\";\n\nexport const get = query({\n returns: values.number(),\n\n handler: function* (ctx) {\n const counters = yield* ctx.db.query(\"counters\").collect();\n return counters[0]?.value ?? 0;\n },\n});\n\nexport const increment = mutation({\n returns: values.number(),\n\n handler: function* (ctx) {\n const counters = yield* ctx.db.query(\"counters\").collect();\n const counter = counters[0];\n const value = (counter?.value ?? 0) + counterIncrement;\n\n if (counter === undefined) {\n yield* ctx.db.insert(\"counters\", { value });\n } else {\n yield* ctx.db.patch(\"counters\", counter.id, { value });\n }\n\n return value;\n },\n});\n`;\n\nconst app = `import { Result, useMutation, useQuery } from \"ignotum/client\";\n\nimport { api } from \"@/_generated/api.js\";\nimport { counterIncrement } from \"@/shared/utils.js\";\n\nexport default function App() {\n const count = useQuery(api.counter.get);\n const increment = useMutation(api.counter.increment);\n\n return (\n <main class=\"mx-auto max-w-sm px-6 py-20 text-center\">\n <h1 class=\"text-2xl font-semibold\">Counter</h1>\n {Result.match(count, {\n pending: () => <p class=\"mt-6\">Loading...</p>,\n value: (value) => (\n <>\n <p class=\"my-6 text-5xl tabular-nums\">{value}</p>\n <button\n class=\"rounded bg-zinc-900 px-4 py-2 text-white\"\n type=\"button\"\n onClick={() => void increment()}\n >\n Increment by {counterIncrement}\n </button>\n </>\n ),\n })}\n </main>\n );\n}\n`;\n\nconst utils = `export const counterIncrement = 1;\n`;\n\nconst styles = `@import \"tailwindcss\";\n`;\n\nconst readme = (projectName: string): string => `# ${projectName}\n\nA small Ignotum counter app.\n\n## Getting started\n\nYou need Node.js 22.18 or newer. The project generator installs dependencies by default. If you\ncreated the project with \\`--no-install\\`, install them now:\n\n\\`\\`\\`sh\nnpx ignotum install\n\\`\\`\\`\n\nThis command uses pnpm when it is installed and otherwise uses npm.\n\nStart the app:\n\n\\`\\`\\`sh\nnpx ignotum dev\n\\`\\`\\`\n\nOpen <http://127.0.0.1:3210>.\n\nThe project generator creates \\`_generated\\`. The dev server checks those files before it starts\nand updates them when the schema or server functions change.\n\n## Project files\n\n- \\`server/schema.ts\\` defines the database tables.\n- \\`server/counter.ts\\` defines the query and mutation used by the counter.\n- \\`client/App.tsx\\` is the UI.\n- \\`client/styles.css\\` loads Tailwind CSS.\n- \\`shared/utils.ts\\` contains code shared across the app.\n- \\`_generated\\` contains Ignotum's generated types and bindings. Do not edit it by hand.\n\nRun the typechecker after a change:\n\n\\`\\`\\`sh\nnpx ignotum codegen\nnpx tsc --noEmit\n\\`\\`\\`\n\n## Claude Code\n\nIf you use Claude Code, rename \\`AGENTS.md\\` to \\`CLAUDE.md\\` and \\`.agents\\` to \\`.claude\\` so it\ncan find the project instructions and Ignotum skill.\n`;\n\nconst projectFiles = (projectName: string): ReadonlyArray<ProjectFile> => [\n { content: app, path: \"client/App.tsx\" },\n { content: styles, path: \"client/styles.css\" },\n { content: counterFunctions, path: \"server/counter.ts\" },\n { content: schema, path: \"server/schema.ts\" },\n { content: utils, path: \"shared/utils.ts\" },\n { content: packageJson(projectName), path: \"package.json\" },\n { content: tsconfig, path: \"tsconfig.json\" },\n { content: gitignore, path: \".gitignore\" },\n { content: readme(projectName), path: \"README.md\" },\n ...agentProjectFiles,\n];\n\nconst writeProjectFile = Effect.fn(\"NewProject.writeProjectFile\")(function* (\n projectDirectory: string,\n file: ProjectFile,\n) {\n const fileSystem = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const filePath = path.join(projectDirectory, file.path);\n\n yield* fileSystem.makeDirectory(path.dirname(filePath), { recursive: true });\n yield* fileSystem.writeFileString(filePath, file.content, { flag: \"wx\" });\n});\n\nconst gitExitCode = Effect.fn(\"NewProject.gitExitCode\")(function* (\n projectDirectory: string,\n args: ReadonlyArray<string>,\n) {\n const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n return yield* spawner\n .exitCode(\n ChildProcess.make(\"git\", args, {\n cwd: projectDirectory,\n stderr: \"ignore\",\n stdout: \"ignore\",\n }),\n )\n .pipe(\n Effect.mapError((cause) =>\n GitInitializationFailed.make({\n cause,\n message: `Could not run Git in ${projectDirectory}.`,\n path: projectDirectory,\n }),\n ),\n );\n});\n\nconst runGit = Effect.fn(\"NewProject.runGit\")(function* (\n projectDirectory: string,\n args: ReadonlyArray<string>,\n action: string,\n) {\n const exitCode = yield* gitExitCode(projectDirectory, args);\n\n if (exitCode !== ChildProcessSpawner.ExitCode(0)) {\n return yield* GitInitializationFailed.make({\n message: `Git exited with code ${exitCode} while ${action} in ${projectDirectory}.`,\n path: projectDirectory,\n });\n }\n});\n\nconst initializeGit = Effect.fn(\"NewProject.initializeGit\")(function* (projectDirectory: string) {\n yield* runGit(projectDirectory, [\"init\", \"--quiet\"], \"initializing the repository\");\n yield* runGit(projectDirectory, [\"add\", \"--all\"], \"staging the initial files\");\n\n const [hasName, hasEmail] = yield* Effect.all(\n [\n gitExitCode(projectDirectory, [\"config\", \"user.name\"]),\n gitExitCode(projectDirectory, [\"config\", \"user.email\"]),\n ],\n { concurrency: \"unbounded\" },\n ).pipe(\n Effect.map((exitCodes) =>\n exitCodes.map((exitCode) => exitCode === ChildProcessSpawner.ExitCode(0)),\n ),\n );\n const identity =\n hasName === true && hasEmail === true\n ? []\n : [\"-c\", \"user.name=Ignotum\", \"-c\", \"user.email=ignotum@localhost\"];\n\n yield* runGit(\n projectDirectory,\n [...identity, \"commit\", \"--quiet\", \"--no-gpg-sign\", \"-m\", \"Init\"],\n \"creating the initial commit\",\n );\n});\n\nexport const createProject = Effect.fn(\"NewProject.createProject\")(function* (\n options: NewProjectOptions,\n) {\n const fileSystem = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const projectDirectory = path.resolve(options.currentDirectory, options.directory);\n const projectName = String.kebabCase(path.basename(projectDirectory));\n\n if (projectName.length === 0) {\n return yield* InvalidProjectName.make({\n message: `Could not derive a package name from ${projectDirectory}.`,\n path: projectDirectory,\n });\n }\n\n const exists = yield* fileSystem.exists(projectDirectory);\n\n if (exists) {\n const info = yield* fileSystem.stat(projectDirectory);\n if (info.type !== \"Directory\") {\n return yield* ProjectDirectoryNotEmpty.make({\n message: `${projectDirectory} already exists and is not an empty directory.`,\n path: projectDirectory,\n });\n }\n\n const entries = yield* fileSystem.readDirectory(projectDirectory);\n if (entries.length > 0) {\n return yield* ProjectDirectoryNotEmpty.make({\n message: `${projectDirectory} is not empty. Choose an empty directory.`,\n path: projectDirectory,\n });\n }\n } else {\n yield* fileSystem.makeDirectory(projectDirectory, { recursive: true });\n }\n\n yield* Effect.forEach(\n projectFiles(projectName),\n (file) => writeProjectFile(projectDirectory, file),\n {\n discard: true,\n },\n );\n\n yield* generate(projectDirectory);\n\n const packageManager = options.install ? yield* installDependencies(projectDirectory) : null;\n\n if (options.git) {\n yield* initializeGit(projectDirectory);\n }\n\n return {\n directory: projectDirectory,\n gitInitialized: options.git,\n packageManager,\n projectName,\n } satisfies NewProjectResult;\n});\n","import { NodeRuntime, NodeServices } from \"@effect/platform-node\";\nimport { Effect, Path, Schema, Terminal } from \"effect\";\nimport { Argument, CliError, Command, Flag } from \"effect/unstable/cli\";\n\nimport packageJson from \"../../package.json\" with { type: \"json\" };\nimport { generate } from \"./codegen.js\";\nimport { resetDevDatabase } from \"../dev-runtime/dev-database.js\";\nimport { dev as runDev } from \"./dev.js\";\nimport { createProject } from \"./new-project.js\";\nimport { installDependencies } from \"./package-manager.js\";\n\nconst DevPort = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65_535 }));\n\nconst codegen = Command.make(\n \"codegen\",\n {},\n Effect.fn(\"codegen\")(function* () {\n const path = yield* Path.Path;\n const terminal = yield* Terminal.Terminal;\n const result = yield* generate(path.resolve(\".\")).pipe(\n Effect.mapError((error) =>\n CliError.UserError.make({ cause: error, userMessage: error.message }),\n ),\n );\n\n yield* terminal.display(\n `Generated ${result.written.length} file${result.written.length === 1 ? \"\" : \"s\"}; ${result.unchanged.length} unchanged.\\n`,\n );\n }),\n);\n\nconst resetDevDatabaseCommand = Command.make(\n \"reset\",\n {},\n Effect.fn(\"dev db reset\")(function* () {\n const path = yield* Path.Path;\n const terminal = yield* Terminal.Terminal;\n const result = yield* resetDevDatabase(path.resolve(\".\")).pipe(\n Effect.mapError((error) =>\n CliError.UserError.make({ cause: error, userMessage: error.message }),\n ),\n );\n const message =\n result.removed === 0\n ? `Development database is already empty: ${result.databasePath}\\n`\n : `Reset development database: ${result.databasePath}\\n`;\n yield* terminal.display(message);\n }),\n).pipe(Command.withDescription(\"Delete the local SQLite development database.\"));\n\nconst devDatabase = Command.make(\"db\").pipe(\n Command.withDescription(\"Manage the local development database.\"),\n Command.withSubcommands([resetDevDatabaseCommand]),\n);\n\nconst dev = Command.make(\n \"dev\",\n {\n host: Flag.string(\"host\").pipe(Flag.withDefault(\"127.0.0.1\")),\n open: Flag.boolean(\"open\").pipe(Flag.withDefault(false)),\n port: Flag.integer(\"port\").pipe(Flag.withSchema(DevPort), Flag.withDefault(3210)),\n },\n Effect.fn(\"dev\")(function* ({ host, open, port }) {\n const path = yield* Path.Path;\n\n return yield* runDev({\n host,\n open,\n port,\n projectDirectory: path.resolve(\".\"),\n }).pipe(\n Effect.mapError((error) =>\n CliError.UserError.make({ cause: error, userMessage: error.message }),\n ),\n );\n }),\n).pipe(\n Command.withDescription(\"Run the local Ignotum development server.\"),\n Command.withSubcommands([devDatabase]),\n);\n\nconst install = Command.make(\n \"install\",\n {},\n Effect.fn(\"install\")(function* () {\n const path = yield* Path.Path;\n const terminal = yield* Terminal.Terminal;\n const packageManager = yield* installDependencies(path.resolve(\".\")).pipe(\n Effect.mapError((error) =>\n CliError.UserError.make({ cause: error, userMessage: error.message }),\n ),\n );\n\n yield* terminal.display(`Installed dependencies with ${packageManager}.\\n`);\n }),\n).pipe(Command.withDescription(\"Install dependencies with pnpm, or npm when pnpm is unavailable.\"));\n\nconst newProject = Command.make(\n \"new\",\n {\n directory: Argument.string(\"directory\").pipe(\n Argument.withDescription('Directory to create. Use \".\" for the current directory.'),\n ),\n git: Flag.boolean(\"git\").pipe(\n Flag.withDescription(\"Initialize a Git repository. Use --no-git to skip it.\"),\n Flag.withDefault(true),\n ),\n install: Flag.boolean(\"install\").pipe(\n Flag.withDescription(\"Install dependencies. Use --no-install to skip it.\"),\n Flag.withDefault(true),\n ),\n },\n Effect.fn(\"new\")(function* ({ directory, git, install }) {\n const path = yield* Path.Path;\n const terminal = yield* Terminal.Terminal;\n const currentDirectory = path.resolve(\".\");\n const result = yield* createProject({ currentDirectory, directory, git, install }).pipe(\n Effect.mapError((error) =>\n CliError.UserError.make({ cause: error, userMessage: error.message }),\n ),\n );\n const changeDirectory = result.directory === currentDirectory ? \"\" : ` cd ${directory}\\n`;\n\n const installCommand = result.packageManager === null ? \" npx ignotum install\\n\" : \"\";\n\n yield* terminal.display(\n `Created ${result.projectName} in ${result.directory}.\\n\\nNext steps:\\n${changeDirectory}${installCommand} npx ignotum dev\\n`,\n );\n }),\n).pipe(\n Command.withDescription(\"Create a new Ignotum app in an empty directory.\"),\n Command.withExamples([\n {\n command: \"ignotum new my-app\",\n description: \"Create an app in a new directory.\",\n },\n {\n command: \"ignotum new . --no-git --no-install\",\n description: \"Create an app in the current directory without Git or dependency installation.\",\n },\n ]),\n);\n\nconst ignotum = Command.make(\"ignotum\").pipe(\n Command.withSubcommands([newProject, install, codegen, dev]),\n);\n\nexport const main = (): void => {\n ignotum.pipe(\n Command.run({ version: packageJson.version }),\n // @effect-diagnostics-next-line strictEffectProvide:off\n Effect.provide(NodeServices.layer),\n NodeRuntime.runMain,\n );\n};\n","#!/usr/bin/env node\n\nimport { main } from \"./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|
1
|
+
{"version":3,"file":"bin.mjs","names":["Effect","Cause","Effect","Cause","make","FileSystem","Path","Effect","Predicate","ChildProcess","NodeSink.fromWritable","NodeStream.fromReadable","makeSpawner","layer","EventEmitter","http","URL","createHash","Duplex","Effect","make","layer","layer","NodeCrypto.layer","Error","Effect","Path","FileSystem","Option","Crypto","Cause","layer","layer","NodeFileSystem.layer","Option","Effect","NodeStream.toString","NodeStream.fromReadable","NodeStream.toArrayBuffer","makeParser","make","Effect","NodeStream.fromReadable","MP.make","NodeStream.toUint8Array","Effect","NodePath","layer","layer","NodePath.layer","layer","layer","NodeStdio.layer","make","Effect","Option","Terminal","Predicate","layer","layer","NodeTerminal.layer","layer","NodeChildProcessSpawner.layer","NodeFileSystem.layer","NodeCrypto.layer","NodePath.layer","NodeStdio.layer","NodeTerminal.layer","Effect","Context","NodeMultipart.persisted","NodeMultipart.stream","HttpIncomingMessage","Cause","runMain","NodeRuntime.runMain","Array","Path","String","Path","TypeId","make","Effect","Context","backupDatabase","Semaphore","Layer","Path","SqliteClient.layer","NodeServices.layer","Path","HttpServerRequest","NodeHttpServer.makeHandler","NodeHttpServer.makeUpgradeHandler","Path","dev","client","devServer","gettingStarted","index","manualSetup","schema","serverFunctions","values","agents","skill","ChildProcessSpawner","Path","ChildProcessSpawner","String","Path","runDev","packageJson.version","NodeServices.layer","NodeRuntime.runMain"],"sources":["../../../../node_modules/.pnpm/@effect+platform-node-shared@4.0.0-rc.111_effect@4.0.0-rc.111/node_modules/@effect/platform-node-shared/dist/internal/nodeChildProcessSpawner.js","../../../../node_modules/.pnpm/@effect+platform-node-shared@4.0.0-rc.111_effect@4.0.0-rc.111/node_modules/@effect/platform-node-shared/dist/internal/utils.js","../../../../node_modules/.pnpm/@effect+platform-node-shared@4.0.0-rc.111_effect@4.0.0-rc.111/node_modules/@effect/platform-node-shared/dist/NodeSink.js","../../../../node_modules/.pnpm/@effect+platform-node-shared@4.0.0-rc.111_effect@4.0.0-rc.111/node_modules/@effect/platform-node-shared/dist/NodeStream.js","../../../../node_modules/.pnpm/@effect+platform-node-shared@4.0.0-rc.111_effect@4.0.0-rc.111/node_modules/@effect/platform-node-shared/dist/NodeChildProcessSpawner.js","../../../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/constants.js","../../../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/buffer-util.js","../../../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/limiter.js","../../../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/permessage-deflate.js","../../../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/validation.js","../../../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/receiver.js","../../../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/sender.js","../../../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/event-target.js","../../../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/extension.js","../../../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/websocket.js","../../../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/stream.js","../../../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/subprotocol.js","../../../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/websocket-server.js","../../../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/wrapper.mjs","../../../../node_modules/.pnpm/@effect+platform-node-shared@4.0.0-rc.111_effect@4.0.0-rc.111/node_modules/@effect/platform-node-shared/dist/NodeCrypto.js","../../../../node_modules/.pnpm/@effect+platform-node@4.0.0-rc.111_effect@4.0.0-rc.111_redis@6.2.1/node_modules/@effect/platform-node/dist/NodeCrypto.js","../../../../node_modules/.pnpm/@effect+platform-node-shared@4.0.0-rc.111_effect@4.0.0-rc.111/node_modules/@effect/platform-node-shared/dist/NodeFileSystem.js","../../../../node_modules/.pnpm/@effect+platform-node@4.0.0-rc.111_effect@4.0.0-rc.111_redis@6.2.1/node_modules/@effect/platform-node/dist/NodeFileSystem.js","../../../../node_modules/.pnpm/@effect+platform-node@4.0.0-rc.111_effect@4.0.0-rc.111_redis@6.2.1/node_modules/@effect/platform-node/dist/NodeHttpIncomingMessage.js","../../../../node_modules/.pnpm/@effect+platform-node@4.0.0-rc.111_effect@4.0.0-rc.111_redis@6.2.1/node_modules/@effect/platform-node/dist/NodeMultipartParser.js","../../../../node_modules/.pnpm/@effect+platform-node@4.0.0-rc.111_effect@4.0.0-rc.111_redis@6.2.1/node_modules/@effect/platform-node/dist/NodeMultipart.js","../../../../node_modules/.pnpm/@effect+platform-node-shared@4.0.0-rc.111_effect@4.0.0-rc.111/node_modules/@effect/platform-node-shared/dist/NodePath.js","../../../../node_modules/.pnpm/@effect+platform-node@4.0.0-rc.111_effect@4.0.0-rc.111_redis@6.2.1/node_modules/@effect/platform-node/dist/NodePath.js","../../../../node_modules/.pnpm/@effect+platform-node-shared@4.0.0-rc.111_effect@4.0.0-rc.111/node_modules/@effect/platform-node-shared/dist/NodeStdio.js","../../../../node_modules/.pnpm/@effect+platform-node@4.0.0-rc.111_effect@4.0.0-rc.111_redis@6.2.1/node_modules/@effect/platform-node/dist/NodeStdio.js","../../../../node_modules/.pnpm/@effect+platform-node-shared@4.0.0-rc.111_effect@4.0.0-rc.111/node_modules/@effect/platform-node-shared/dist/NodeTerminal.js","../../../../node_modules/.pnpm/@effect+platform-node@4.0.0-rc.111_effect@4.0.0-rc.111_redis@6.2.1/node_modules/@effect/platform-node/dist/NodeTerminal.js","../../../../node_modules/.pnpm/@effect+platform-node@4.0.0-rc.111_effect@4.0.0-rc.111_redis@6.2.1/node_modules/@effect/platform-node/dist/NodeServices.js","../../../../node_modules/.pnpm/@effect+platform-node@4.0.0-rc.111_effect@4.0.0-rc.111_redis@6.2.1/node_modules/@effect/platform-node/dist/NodeHttpServer.js","../../../../node_modules/.pnpm/@effect+platform-node-shared@4.0.0-rc.111_effect@4.0.0-rc.111/node_modules/@effect/platform-node-shared/dist/NodeRuntime.js","../../../../node_modules/.pnpm/@effect+platform-node@4.0.0-rc.111_effect@4.0.0-rc.111_redis@6.2.1/node_modules/@effect/platform-node/dist/NodeRuntime.js","../../package.json","../../../contracts/dist/value-Briqf-Ua.js","../../../contracts/dist/runtime/sync.js","../../src/cli/codegen.ts","../../src/dev-runtime/dev-database.ts","../../src/cli/client-plugin.ts","../../../../node_modules/.pnpm/@effect+sql-sqlite-node@4.0.0-rc.111_effect@4.0.0-rc.111/node_modules/@effect/sql-sqlite-node/dist/SqliteClient.js","../../../runtime/dist/functions.js","../../../runtime/dist/sync.js","../../src/internal/http-paths.ts","../../../contracts/dist/runtime/id.js","../../../contracts/dist/runtime/result.js","../../../contracts/dist/runtime/schema.js","../../../contracts/dist/schema/index.js","../../../runtime/dist/id.js","../../src/dev-runtime/database.ts","../../src/dev-runtime/id.ts","../../../contracts/dist/runtime/functions.js","../../src/dev-runtime/functions.ts","../../src/dev-runtime/sync.ts","../../src/cli/dev.ts","../../../../docs/agent/AGENTS.md?raw","../../../../docs/agent/skills/ignotum/SKILL.md?raw","../../../../docs/user/client.md?raw","../../../../docs/user/dev-server.md?raw","../../../../docs/user/getting-started.md?raw","../../../../docs/user/index.md?raw","../../../../docs/user/manual-setup.md?raw","../../../../docs/user/schema.md?raw","../../../../docs/user/server-functions.md?raw","../../../../docs/user/values.md?raw","../../src/cli/agent-files.ts","../../src/cli/package-manager.ts","../../src/cli/new-project.ts","../../src/cli/command.ts","../../src/cli/bin.ts"],"sourcesContent":["export const buildSpawnOptions = (options, base, platform) => {\n const detached = options.detached ?? platform !== \"win32\";\n return {\n ...base,\n detached,\n shell: options.shell,\n windowsHide: options.windowsHide ?? !detached\n };\n};\n//# sourceMappingURL=nodeChildProcessSpawner.js.map","import * as PlatformError from \"effect/PlatformError\";\n/** @internal */\nexport const handleErrnoException = (module, method) => (err, [path]) => {\n let reason = \"Unknown\";\n switch (err.code) {\n case \"ENOENT\":\n reason = \"NotFound\";\n break;\n case \"EACCES\":\n reason = \"PermissionDenied\";\n break;\n case \"EEXIST\":\n reason = \"AlreadyExists\";\n break;\n case \"EISDIR\":\n reason = \"BadResource\";\n break;\n case \"ENOTDIR\":\n reason = \"BadResource\";\n break;\n case \"EBUSY\":\n reason = \"Busy\";\n break;\n case \"ELOOP\":\n reason = \"BadResource\";\n break;\n }\n return PlatformError.systemError({\n _tag: reason,\n module,\n method,\n pathOrDescriptor: path,\n syscall: err.syscall,\n cause: err\n });\n};\n//# sourceMappingURL=utils.js.map","import * as Cause from \"effect/Cause\";\nimport * as Channel from \"effect/Channel\";\nimport * as Effect from \"effect/Effect\";\nimport { identity } from \"effect/Function\";\nimport * as Pull from \"effect/Pull\";\nimport * as Sink from \"effect/Sink\";\n/**\n * Creates a `Sink` that writes chunks to a Node writable stream, respecting\n * backpressure, mapping writable errors with `onError`, and ending the stream\n * on completion unless `endOnDone` is `false`.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromWritable = options => Sink.fromChannel(Channel.mapDone(fromWritableChannel(options), _ => [_]));\n/**\n * Creates a `Channel` that pulls chunks from upstream and writes them to a\n * Node writable stream, respecting backpressure and optionally ending the\n * writable when upstream is done.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromWritableChannel = options => Channel.fromTransform(pull => {\n const writable = options.evaluate();\n return Effect.succeed(pullIntoWritable({\n ...options,\n writable,\n pull\n }));\n});\n/**\n * Writes Effect chunks into a Node writable stream.\n *\n * **When to use**\n *\n * Use to implement custom Node stream adapters that already have an upstream\n * pull and need direct control over a writable stream.\n *\n * **Details**\n *\n * The loop waits for `drain` when needed, fails on writable errors, and ends\n * the writable on upstream completion unless `endOnDone` is `false`.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const pullIntoWritable = options => options.pull.pipe(Effect.flatMap(chunk => {\n let i = 0;\n return Effect.callback(function loop(resume) {\n for (; i < chunk.length;) {\n const success = options.writable.write(chunk[i++], options.encoding);\n if (!success) {\n options.writable.once(\"drain\", () => loop(resume));\n return;\n }\n }\n resume(Effect.void);\n });\n}), Effect.forever({\n disableYield: true\n}), Effect.raceFirst(Effect.callback(resume => {\n const onError = error => resume(Effect.fail(options.onError(error)));\n options.writable.once(\"error\", onError);\n return Effect.sync(() => {\n options.writable.off(\"error\", onError);\n });\n})), options.endOnDone !== false ? Pull.catchDone(_ => {\n if (\"closed\" in options.writable && options.writable.closed) {\n return Cause.done(_);\n }\n return Effect.callback(resume => {\n options.writable.once(\"finish\", () => resume(Cause.done(_)));\n options.writable.end();\n });\n}) : identity);\n//# sourceMappingURL=NodeSink.js.map","/**\n * Adapters between Node streams and Effect streams, channels, and readables.\n *\n * This module is the stream boundary for Node APIs. It wraps `Readable` and\n * `Duplex` values as Effect `Stream`s and `Channel`s, pipes Effect streams\n * through Node duplex streams, exposes an Effect `Stream` back to Node as a\n * `Readable`, and collects readable payloads into strings, array buffers, or\n * `Uint8Array`s with optional byte limits.\n *\n * @since 4.0.0\n */\nimport * as Arr from \"effect/Array\";\nimport * as Cause from \"effect/Cause\";\nimport * as Channel from \"effect/Channel\";\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 { dual } from \"effect/Function\";\nimport * as Latch from \"effect/Latch\";\nimport * as MutableRef from \"effect/MutableRef\";\nimport * as Pull from \"effect/Pull\";\nimport * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\nimport { Readable } from \"node:stream\";\nimport { pullIntoWritable } from \"./NodeSink.js\";\n/**\n * Converts a Node readable stream into an Effect `Stream`, reading chunks with\n * an optional chunk size, mapping stream errors with `onError`, and destroying\n * the readable on completion unless `closeOnDone` is `false`.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromReadable = options => Stream.fromChannel(fromReadableChannel(options));\n/**\n * Creates a `Channel` that pulls chunks from a Node readable stream, mapping\n * errors with `onError` and destroying the readable on completion unless\n * `closeOnDone` is `false`.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromReadableChannel = options => Channel.fromTransform((_, scope) => readableToPullUnsafe({\n scope,\n readable: options.evaluate(),\n onError: options.onError ?? defaultOnError,\n chunkSize: options.chunkSize,\n closeOnDone: options.closeOnDone\n}));\n/**\n * Creates a `Channel` over a Node `Duplex`, writing upstream chunks with\n * backpressure while emitting chunks read from the duplex and optionally ending\n * the writable side when upstream completes.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromDuplex = options => Channel.fromTransform((upstream, scope) => {\n const duplex = options.evaluate();\n const exit = MutableRef.make(undefined);\n return pullIntoWritable({\n pull: upstream,\n writable: duplex,\n onError: options.onError ?? defaultOnError,\n endOnDone: options.endOnDone,\n encoding: options.encoding\n }).pipe(Effect.catchCause(cause => {\n if (Pull.isDoneCause(cause)) return Effect.void;\n exit.current = Exit.failCause(cause);\n return Effect.void;\n }), Effect.forkIn(scope), Effect.flatMap(() => readableToPullUnsafe({\n scope,\n exit,\n readable: duplex,\n onError: options.onError ?? defaultOnError,\n chunkSize: options.chunkSize\n })));\n});\n/**\n * Pipes an Effect `Stream` through a Node `Duplex`, writing the stream's\n * chunks to the duplex and emitting chunks read back from it.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const pipeThroughDuplex = /*#__PURE__*/dual(2, (self, options) => Stream.pipeThroughChannelOrFail(self, fromDuplex(options)));\n/**\n * Pipes a stream of strings or bytes through a Node `Duplex` using default\n * options and `Cause.UnknownError` for stream failures.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const pipeThroughSimple = /*#__PURE__*/dual(2, (self, duplex) => pipeThroughDuplex(self, {\n evaluate: duplex\n}));\n/**\n * Converts an Effect `Stream` into a Node `Readable`, using the caller's\n * Effect context to run the stream and destroying the readable if the stream\n * fails.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toReadable = stream => Effect.map(Effect.context(), context => new StreamAdapter(context, stream));\n/**\n * Converts a service-free Effect `Stream` into a Node `Readable` using an\n * empty Effect context.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toReadableNever = stream => new StreamAdapter(Context.empty(), stream);\n/**\n * Consumes a Node readable stream into a string using the selected encoding,\n * failing through `onError` on stream errors or when `maxBytes` is exceeded\n * and destroying the stream on interruption or failure.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toString = (readable, options) => {\n const maxBytesNumber = options?.maxBytes !== undefined ? Number(options.maxBytes) : undefined;\n const onError = options?.onError ?? defaultOnError;\n const encoding = options?.encoding ?? \"utf8\";\n return Effect.callback(resume => {\n const stream = readable();\n stream.setEncoding(encoding);\n stream.once(\"error\", err => {\n if (\"closed\" in stream && !stream.closed) {\n stream.destroy();\n }\n resume(Effect.fail(onError(err)));\n });\n let string = \"\";\n let bytes = 0;\n stream.once(\"end\", () => {\n resume(Effect.succeed(string));\n });\n stream.on(\"data\", chunk => {\n string += chunk;\n bytes += Buffer.byteLength(chunk);\n if (maxBytesNumber !== undefined && bytes > maxBytesNumber) {\n if (\"closed\" in stream && !stream.closed) {\n stream.destroy();\n }\n resume(Effect.fail(onError(new Error(\"maxBytes exceeded\"))));\n }\n });\n return Effect.sync(() => {\n if (\"closed\" in stream && !stream.closed) {\n stream.destroy();\n }\n });\n });\n};\n/**\n * Consumes a Node readable stream into an `ArrayBuffer`, failing through\n * `onError` on stream errors or when `maxBytes` is exceeded and destroying the\n * stream on interruption or failure.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toArrayBuffer = (readable, options) => {\n const maxBytesNumber = options?.maxBytes !== undefined ? Number(options.maxBytes) : undefined;\n const onError = options?.onError ?? defaultOnError;\n return Effect.callback(resume => {\n const stream = readable();\n const buffers = [];\n let bytes = 0;\n stream.once(\"error\", err => {\n if (\"closed\" in stream && !stream.closed) {\n stream.destroy();\n }\n resume(Effect.fail(onError(err)));\n });\n stream.once(\"end\", () => {\n const buffer = buffers.length === 1 ? buffers[0] : Buffer.concat(buffers);\n if (buffer.byteOffset === 0 && buffer.buffer.byteLength === buffer.byteLength) {\n return resume(Effect.succeed(buffer.buffer));\n }\n resume(Effect.succeed(buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength)));\n });\n stream.on(\"data\", chunk => {\n buffers.push(chunk);\n bytes += chunk.length;\n if (maxBytesNumber !== undefined && bytes > maxBytesNumber) {\n if (\"closed\" in stream && !stream.closed) {\n stream.destroy();\n }\n resume(Effect.fail(onError(new Error(\"maxBytes exceeded\"))));\n }\n });\n return Effect.sync(() => {\n if (\"closed\" in stream && !stream.closed) {\n stream.destroy();\n }\n });\n });\n};\n/**\n * Consumes a Node readable stream into a `Uint8Array`, using the same error\n * mapping and `maxBytes` handling as `toArrayBuffer`.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toUint8Array = (readable, options) => Effect.map(toArrayBuffer(readable, options), buffer => new Uint8Array(buffer));\n// ----------------------------------------------------------------------------\n// internal\n// ----------------------------------------------------------------------------\nconst readableToPullUnsafe = options => {\n const readable = options.readable;\n const closeOnDone = options.closeOnDone ?? true;\n const exit = options.exit ?? MutableRef.make(undefined);\n const latch = Latch.makeUnsafe(false);\n function onReadable() {\n latch.openUnsafe();\n }\n function onError(error) {\n exit.current = Exit.fail(options.onError(error));\n latch.openUnsafe();\n }\n function onEnd() {\n exit.current = Exit.fail(Cause.Done());\n latch.openUnsafe();\n }\n readable.on(\"readable\", onReadable);\n readable.once(\"error\", onError);\n readable.once(\"end\", onEnd);\n const pull = Effect.suspend(function loop() {\n let item = options.readable.read(options.chunkSize);\n if (item === null) {\n if (exit.current) {\n return exit.current;\n }\n if (readable.readableEnded) {\n return Effect.fail(Cause.Done());\n }\n latch.closeUnsafe();\n return Effect.flatMap(latch.await, loop);\n }\n const chunk = Arr.of(item);\n while (true) {\n item = options.readable.read(options.chunkSize);\n if (item === null) break;\n chunk.push(item);\n }\n return Effect.succeed(chunk);\n });\n return Effect.as(Scope.addFinalizer(options.scope, Effect.sync(() => {\n readable.off(\"readable\", onReadable);\n readable.off(\"error\", onError);\n readable.off(\"end\", onEnd);\n if (closeOnDone && \"closed\" in options.readable && !options.readable.closed) {\n options.readable.destroy();\n }\n })), pull);\n};\nclass StreamAdapter extends Readable {\n readLatch;\n fiber = undefined;\n constructor(context, stream) {\n super({});\n this.readLatch = Latch.makeUnsafe(false);\n this.fiber = Stream.runForEachArray(stream, chunk => this.readLatch.whenOpen(Effect.sync(() => {\n this.readLatch.closeUnsafe();\n for (let i = 0; i < chunk.length; i++) {\n const item = chunk[i];\n if (typeof item === \"string\") {\n this.push(item, \"utf8\");\n } else {\n this.push(item);\n }\n }\n }))).pipe(this.readLatch.whenOpen, Effect.provideContext(context), Effect.runFork);\n this.fiber.addObserver(exit => {\n this.fiber = undefined;\n if (Exit.isSuccess(exit)) {\n this.push(null);\n } else {\n this.destroy(Cause.squash(exit.cause));\n }\n });\n }\n _read(_size) {\n this.readLatch.openUnsafe();\n }\n _destroy(error, callback) {\n if (!this.fiber) {\n return callback(error);\n }\n Effect.runFork(Fiber.interrupt(this.fiber)).addObserver(exit => {\n callback(exit._tag === \"Failure\" ? Cause.squash(exit.cause) : error);\n });\n }\n}\nconst defaultOnError = error => new Cause.UnknownError(error);\n//# sourceMappingURL=NodeStream.js.map","import * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Path from \"effect/Path\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Sink from \"effect/Sink\";\nimport * as Stream from \"effect/Stream\";\nimport * as ChildProcess from \"effect/unstable/process/ChildProcess\";\nimport { ChildProcessSpawner, ExitCode, make as makeSpawner, makeHandle, ProcessId } from \"effect/unstable/process/ChildProcessSpawner\";\nimport * as NodeChildProcess from \"node:child_process\";\nimport { PassThrough } from \"node:stream\";\nimport { buildSpawnOptions } from \"./internal/nodeChildProcessSpawner.js\";\nimport { handleErrnoException } from \"./internal/utils.js\";\nimport * as NodeSink from \"./NodeSink.js\";\nimport * as NodeStream from \"./NodeStream.js\";\nconst toError = error => error instanceof globalThis.Error ? error : new globalThis.Error(String(error));\nconst toPlatformError = (method, error, command) => {\n const {\n commands\n } = flattenCommand(command);\n const commandStr = commands.reduce((acc, curr) => {\n const cmd = `${curr.command} ${curr.args.join(\" \")}`;\n return acc.length === 0 ? cmd : `${acc} | ${cmd}`;\n }, \"\");\n return handleErrnoException(\"ChildProcess\", method)(error, [commandStr]);\n};\nconst taskkill = (childProcess, onExit = () => {}) => NodeChildProcess.execFile(\"taskkill\", [\"/pid\", String(childProcess.pid), \"/T\", \"/F\"], {\n windowsHide: true\n}, onExit);\nconst make = /*#__PURE__*/Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const resolveWorkingDirectory = Effect.fnUntraced(function* (options) {\n if (Predicate.isUndefined(options.cwd)) return undefined;\n // Validate that the specified directory is accessible\n yield* fs.access(options.cwd);\n return path.resolve(options.cwd);\n });\n const resolveEnvironment = options => {\n return options.extendEnv ? {\n ...globalThis.process.env,\n ...options.env\n } : options.env;\n };\n const inputToStdioOption = input => Stream.isStream(input) ? \"pipe\" : input;\n const outputToStdioOption = input => Sink.isSink(input) ? \"pipe\" : input;\n const resolveStdinOption = options => {\n const defaultConfig = {\n stream: \"pipe\",\n encoding: \"utf-8\",\n endOnDone: true\n };\n if (Predicate.isUndefined(options.stdin)) {\n return defaultConfig;\n }\n if (typeof options.stdin === \"string\") {\n return {\n ...defaultConfig,\n stream: options.stdin\n };\n }\n if (Stream.isStream(options.stdin)) {\n return {\n ...defaultConfig,\n stream: options.stdin\n };\n }\n return {\n stream: options.stdin.stream,\n encoding: options.stdin.encoding ?? defaultConfig.encoding,\n endOnDone: options.stdin.endOnDone ?? defaultConfig.endOnDone\n };\n };\n const resolveOutputOption = (options, streamName) => {\n const option = options[streamName];\n if (Predicate.isUndefined(option)) {\n return {\n stream: \"pipe\"\n };\n }\n if (typeof option === \"string\") {\n return {\n stream: option\n };\n }\n if (Sink.isSink(option)) {\n return {\n stream: option\n };\n }\n return {\n stream: option.stream\n };\n };\n const resolveAdditionalFds = options => {\n if (Predicate.isUndefined(options.additionalFds)) {\n return [];\n }\n const result = [];\n for (const [name, config] of Object.entries(options.additionalFds)) {\n const fd = ChildProcess.parseFdName(name);\n if (Predicate.isNotUndefined(fd)) {\n result.push({\n fd,\n config\n });\n }\n }\n // Sort by fd number to ensure correct ordering\n return result.sort((a, b) => a.fd - b.fd);\n };\n const buildStdioArray = (stdinConfig, stdoutConfig, stderrConfig, additionalFds) => {\n const stdio = [inputToStdioOption(stdinConfig.stream), outputToStdioOption(stdoutConfig.stream), outputToStdioOption(stderrConfig.stream)];\n if (additionalFds.length === 0) {\n return stdio;\n }\n // Find the maximum fd number to size the array correctly\n const maxFd = additionalFds.reduce((max, {\n fd\n }) => Math.max(max, fd), 2);\n // Fill gaps with \"ignore\"\n for (let i = 3; i <= maxFd; i++) {\n stdio[i] = \"ignore\";\n }\n // Set up additional fds as \"pipe\"\n for (const {\n fd\n } of additionalFds) {\n stdio[fd] = \"pipe\";\n }\n return stdio;\n };\n const setupAdditionalFds = Effect.fnUntraced(function* (command, childProcess, additionalFds) {\n if (additionalFds.length === 0) {\n return {\n getInputFd: () => Sink.drain,\n getOutputFd: () => Stream.empty\n };\n }\n const inputSinks = new Map();\n const outputStreams = new Map();\n for (const {\n config,\n fd\n } of additionalFds) {\n const nodeStream = childProcess.stdio[fd];\n switch (config.type) {\n case \"input\":\n {\n // Create a sink to write to for input file descriptors\n let sink = Sink.drain;\n if (nodeStream && \"write\" in nodeStream) {\n sink = NodeSink.fromWritable({\n evaluate: () => nodeStream,\n onError: error => toPlatformError(`fromWritable(fd${fd})`, toError(error), command)\n });\n }\n // If user provided a stream, pipe it into the sink\n if (config.stream) {\n yield* Effect.forkScoped(Stream.run(config.stream, sink));\n }\n inputSinks.set(fd, sink);\n break;\n }\n case \"output\":\n {\n // Create a stream to read from for output file descriptors\n let stream = Stream.empty;\n if (nodeStream && \"read\" in nodeStream) {\n const passThrough = new PassThrough();\n nodeStream.on(\"error\", error => passThrough.destroy(error));\n nodeStream.pipe(passThrough);\n stream = NodeStream.fromReadable({\n evaluate: () => passThrough,\n onError: error => toPlatformError(`fromReadable(fd${fd})`, toError(error), command)\n });\n }\n // If user provided a sink, transduce the stream through it\n if (config.sink) {\n stream = Stream.transduce(stream, config.sink);\n }\n outputStreams.set(fd, stream);\n break;\n }\n }\n }\n return {\n getInputFd: fd => inputSinks.get(fd) ?? Sink.drain,\n getOutputFd: fd => outputStreams.get(fd) ?? Stream.empty\n };\n });\n const setupChildStdin = (command, childProcess, config) => Effect.suspend(() => {\n // If the child process has a standard input stream, connect it to the\n // sink that will attached to the process handle\n let sink = Sink.drain;\n if (Predicate.isNotNull(childProcess.stdin)) {\n sink = NodeSink.fromWritable({\n evaluate: () => childProcess.stdin,\n onError: error => toPlatformError(\"fromWritable(stdin)\", toError(error), command),\n endOnDone: config.endOnDone,\n encoding: config.encoding\n });\n }\n // If the user provided a `Stream`, run it into the stdin sink\n if (Stream.isStream(config.stream)) {\n return Effect.as(Effect.forkScoped(Stream.run(config.stream, sink)), sink);\n }\n return Effect.succeed(sink);\n });\n const setupChildOutputStreams = (command, childProcess, stdoutConfig, stderrConfig) => {\n let stdout = childProcess.stdout ? (() => {\n const passThrough = new PassThrough();\n childProcess.stdout.on(\"error\", error => passThrough.destroy(error));\n childProcess.stdout.pipe(passThrough);\n return NodeStream.fromReadable({\n evaluate: () => passThrough,\n onError: error => toPlatformError(\"fromReadable(stdout)\", toError(error), command)\n });\n })() : Stream.empty;\n let stderr = childProcess.stderr ? (() => {\n const passThrough = new PassThrough();\n childProcess.stderr.on(\"error\", error => passThrough.destroy(error));\n childProcess.stderr.pipe(passThrough);\n return NodeStream.fromReadable({\n evaluate: () => passThrough,\n onError: error => toPlatformError(\"fromReadable(stderr)\", toError(error), command)\n });\n })() : Stream.empty;\n if (Sink.isSink(stdoutConfig.stream)) {\n stdout = Stream.transduce(stdout, stdoutConfig.stream);\n }\n if (Sink.isSink(stderrConfig.stream)) {\n stderr = Stream.transduce(stderr, stderrConfig.stream);\n }\n const all = Stream.merge(stdout, stderr);\n return {\n stdout,\n stderr,\n all\n };\n };\n const spawn = (command, spawnOptions) => Effect.callback(resume => {\n const deferred = Deferred.makeUnsafe();\n const handle = NodeChildProcess.spawn(command.command, command.args, spawnOptions);\n handle.on(\"error\", error => {\n resume(Effect.fail(toPlatformError(\"spawn\", error, command)));\n });\n handle.on(\"exit\", (...args) => {\n Deferred.doneUnsafe(deferred, Exit.succeed(args));\n });\n handle.on(\"spawn\", () => {\n resume(Effect.succeed([handle, deferred]));\n });\n return Effect.sync(() => {\n handle.kill(\"SIGTERM\");\n });\n });\n const killProcessGroup = (command, childProcess, signal) => {\n if (globalThis.process.platform === \"win32\") {\n return Effect.callback(resume => {\n taskkill(childProcess, error => {\n if (error) {\n resume(Effect.fail(toPlatformError(\"kill\", toError(error), command)));\n } else {\n resume(Effect.void);\n }\n });\n });\n }\n return Effect.try({\n try: () => {\n globalThis.process.kill(-childProcess.pid, signal);\n },\n catch: error => toPlatformError(\"kill\", toError(error), command)\n });\n };\n const killProcessGroupOnExit = (childProcess, signal) => {\n if (globalThis.process.platform === \"win32\") {\n // ignore errors during best-effort cleanup\n taskkill(childProcess);\n return;\n }\n try {\n globalThis.process.kill(-childProcess.pid, signal);\n } catch {\n // ignore errors during best-effort cleanup\n }\n };\n const killProcess = (command, childProcess, signal) => Effect.suspend(() => {\n const killed = childProcess.kill(signal);\n if (!killed) {\n const error = new globalThis.Error(\"Failed to kill child process\");\n return Effect.fail(toPlatformError(\"kill\", error, command));\n }\n return Effect.void;\n });\n const withTimeout = (childProcess, command, options) => kill => {\n const killSignal = options?.killSignal ?? \"SIGTERM\";\n return Predicate.isUndefined(options?.forceKillAfter) ? kill(command, childProcess, killSignal) : Effect.timeoutOrElse(kill(command, childProcess, killSignal), {\n duration: options.forceKillAfter,\n orElse: () => kill(command, childProcess, \"SIGKILL\")\n });\n };\n /**\n * Get the appropriate source stream from a process handle based on the\n * `from` pipe option.\n */\n const getSourceStream = (handle, from) => {\n const fromOption = from ?? \"stdout\";\n switch (fromOption) {\n case \"stdout\":\n return handle.stdout;\n case \"stderr\":\n return handle.stderr;\n case \"all\":\n return handle.all;\n default:\n {\n // Handle fd3, fd4, etc.\n const fd = ChildProcess.parseFdName(fromOption);\n if (Predicate.isNotUndefined(fd)) {\n return handle.getOutputFd(fd);\n }\n // Fallback to stdout for invalid fd names\n return handle.stdout;\n }\n }\n };\n const spawnCommand = Effect.fnUntraced(function* (cmd) {\n switch (cmd._tag) {\n case \"StandardCommand\":\n {\n const stdinConfig = resolveStdinOption(cmd.options);\n const stdoutConfig = resolveOutputOption(cmd.options, \"stdout\");\n const stderrConfig = resolveOutputOption(cmd.options, \"stderr\");\n const resolvedAdditionalFds = resolveAdditionalFds(cmd.options);\n let isReferenced = true;\n const cwd = yield* resolveWorkingDirectory(cmd.options);\n const env = resolveEnvironment(cmd.options);\n const stdio = buildStdioArray(stdinConfig, stdoutConfig, stderrConfig, resolvedAdditionalFds);\n const [childProcess, exitSignal] = yield* Effect.acquireRelease(spawn(cmd, buildSpawnOptions(cmd.options, {\n cwd,\n env,\n stdio\n }, process.platform)), Effect.fnUntraced(function* ([childProcess, exitSignal]) {\n const exited = yield* Deferred.isDone(exitSignal);\n const killWithTimeout = withTimeout(childProcess, cmd, cmd.options);\n if (exited) {\n // Process already exited, check if children need cleanup\n const [code] = yield* Deferred.await(exitSignal);\n if (code !== 0 && Predicate.isNotNull(code)) {\n // Non-zero exit code ,attempt to clean up process group\n return yield* Effect.ignore(killWithTimeout(killProcessGroup));\n }\n return yield* Effect.void;\n }\n if (!isReferenced) {\n return yield* Effect.void;\n }\n // Process is still running, kill it\n return yield* killWithTimeout((command, childProcess, signal) => killProcessGroup(command, childProcess, signal).pipe(Effect.catch(() => killProcess(command, childProcess, signal)), Effect.andThen(Deferred.await(exitSignal)))).pipe(Effect.ignore);\n }));\n const pid = ProcessId(childProcess.pid);\n childProcess.on(\"exit\", code => {\n if (code !== 0 && Predicate.isNotNull(code)) {\n killProcessGroupOnExit(childProcess, cmd.options.killSignal ?? \"SIGTERM\");\n }\n });\n const reref = Effect.sync(() => {\n if (!isReferenced) {\n childProcess.ref();\n isReferenced = true;\n }\n });\n const unref = Effect.sync(() => {\n if (isReferenced) {\n childProcess.unref();\n isReferenced = false;\n }\n return reref;\n });\n const stdin = yield* setupChildStdin(cmd, childProcess, stdinConfig);\n const {\n all,\n stderr,\n stdout\n } = setupChildOutputStreams(cmd, childProcess, stdoutConfig, stderrConfig);\n const {\n getInputFd,\n getOutputFd\n } = yield* setupAdditionalFds(cmd, childProcess, resolvedAdditionalFds);\n const isRunning = Effect.map(Deferred.isDone(exitSignal), done => !done);\n const exitCode = Effect.flatMap(Deferred.await(exitSignal), ([code, signal]) => {\n if (Predicate.isNotNull(code)) {\n return Effect.succeed(ExitCode(code));\n }\n // If code is `null`, then `signal` must be defined. See the NodeJS\n // documentation for the `\"exit\"` event on a `child_process`.\n // https://nodejs.org/api/child_process.html#child_process_event_exit\n const error = new globalThis.Error(`Process interrupted due to receipt of signal: '${signal}'`);\n return Effect.fail(toPlatformError(\"exitCode\", error, cmd));\n });\n const kill = options => {\n const killWithTimeout = withTimeout(childProcess, cmd, options);\n return killWithTimeout((command, childProcess, signal) => killProcessGroup(command, childProcess, signal).pipe(Effect.catch(() => killProcess(command, childProcess, signal)), Effect.andThen(Deferred.await(exitSignal)))).pipe(Effect.asVoid);\n };\n return makeHandle({\n pid,\n exitCode,\n isRunning,\n kill,\n stdin,\n stdout,\n stderr,\n all,\n getInputFd,\n getOutputFd,\n unref\n });\n }\n case \"PipedCommand\":\n {\n const {\n commands,\n pipeOptions\n } = flattenCommand(cmd);\n const [root, ...pipeline] = commands;\n const handles = [yield* spawnCommand(root)];\n for (let i = 0; i < pipeline.length; i++) {\n const command = pipeline[i];\n const options = pipeOptions[i] ?? {};\n const stdinConfig = resolveStdinOption(command.options);\n // Get the appropriate stream from the source based on `from` option\n const sourceStream = Stream.unwrap(Effect.succeed(getSourceStream(handles[handles.length - 1], options.from)));\n // Determine where to pipe: stdin or custom fd\n const toOption = options.to ?? \"stdin\";\n if (toOption === \"stdin\") {\n // Pipe to stdin (default behavior)\n handles.push(yield* spawnCommand(ChildProcess.make(command.command, command.args, {\n ...command.options,\n stdin: {\n ...stdinConfig,\n stream: sourceStream\n }\n })));\n } else {\n // Pipe to custom fd (fd3, fd4, etc.)\n const fd = ChildProcess.parseFdName(toOption);\n if (Predicate.isNotUndefined(fd)) {\n const fdName = ChildProcess.fdName(fd);\n const existingFds = command.options.additionalFds ?? {};\n handles.push(yield* spawnCommand(ChildProcess.make(command.command, command.args, {\n ...command.options,\n additionalFds: {\n ...existingFds,\n [fdName]: {\n type: \"input\",\n stream: sourceStream\n }\n }\n })));\n } else {\n // Invalid fd name, fall back to stdin\n handles.push(yield* spawnCommand(ChildProcess.make(command.command, command.args, {\n ...command.options,\n stdin: {\n ...stdinConfig,\n stream: sourceStream\n }\n })));\n }\n }\n }\n const handle = handles[handles.length - 1];\n const kill = options => Effect.forEach([...handles].reverse(), handle => Effect.ignore(handle.kill(options)), {\n discard: true\n });\n const unref = Effect.gen(function* () {\n const rerefs = [];\n for (const handle of handles) {\n rerefs.push(yield* handle.unref);\n }\n return Effect.forEach([...rerefs].reverse(), reref => reref, {\n discard: true\n });\n });\n return makeHandle({\n pid: handle.pid,\n exitCode: handle.exitCode,\n isRunning: handle.isRunning,\n kill,\n stdin: handle.stdin,\n stdout: handle.stdout,\n stderr: handle.stderr,\n all: handle.all,\n getInputFd: handle.getInputFd,\n getOutputFd: handle.getOutputFd,\n unref\n });\n }\n }\n });\n return makeSpawner(spawnCommand);\n});\n/**\n * Layer that provides the `NodeChildProcessSpawner` implementation.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layer = /*#__PURE__*/Layer.effect(ChildProcessSpawner, make);\n/**\n * Flattens a `Command` into an array of `StandardCommand`s along with pipe\n * options for each connection.\n *\n * @category transforming\n * @since 4.0.0\n */\nexport const flattenCommand = command => {\n const commands = [];\n const pipeOptions = [];\n const flatten = cmd => {\n switch (cmd._tag) {\n case \"StandardCommand\":\n {\n commands.push(cmd);\n break;\n }\n case \"PipedCommand\":\n {\n // Recursively flatten left side first\n flatten(cmd.left);\n // Store the pipe options for this connection\n pipeOptions.push(cmd.options);\n // Then flatten right side\n flatten(cmd.right);\n break;\n }\n }\n };\n flatten(command);\n // The commands array is guaranteed to be non-empty since we always have at\n // least one command in the input. We validate this at runtime and return a\n // properly typed tuple.\n if (commands.length === 0) {\n // This should never happen given a valid Command input\n throw new Error(\"flattenCommand produced empty commands array\");\n }\n const [first, ...rest] = commands;\n const nonEmptyCommands = [first, ...rest];\n return {\n commands: nonEmptyCommands,\n pipeOptions\n };\n};\n//# sourceMappingURL=NodeChildProcessSpawner.js.map","'use strict';\n\nconst BINARY_TYPES = ['nodebuffer', 'arraybuffer', 'fragments'];\nconst hasBlob = typeof Blob !== 'undefined';\n\nif (hasBlob) BINARY_TYPES.push('blob');\n\nmodule.exports = {\n BINARY_TYPES,\n CLOSE_TIMEOUT: 30000,\n EMPTY_BUFFER: Buffer.alloc(0),\n GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11',\n hasBlob,\n kForOnEventAttribute: Symbol('kIsForOnEventAttribute'),\n kListener: Symbol('kListener'),\n kStatusCode: Symbol('status-code'),\n kWebSocket: Symbol('websocket'),\n NOOP: () => {}\n};\n","'use strict';\n\nconst { EMPTY_BUFFER } = require('./constants');\n\nconst FastBuffer = Buffer[Symbol.species];\n\n/**\n * Merges an array of buffers into a new buffer.\n *\n * @param {Buffer[]} list The array of buffers to concat\n * @param {Number} totalLength The total length of buffers in the list\n * @return {Buffer} The resulting buffer\n * @public\n */\nfunction concat(list, totalLength) {\n if (list.length === 0) return EMPTY_BUFFER;\n if (list.length === 1) return list[0];\n\n const target = Buffer.allocUnsafe(totalLength);\n let offset = 0;\n\n for (let i = 0; i < list.length; i++) {\n const buf = list[i];\n target.set(buf, offset);\n offset += buf.length;\n }\n\n if (offset < totalLength) {\n return new FastBuffer(target.buffer, target.byteOffset, offset);\n }\n\n return target;\n}\n\n/**\n * Masks a buffer using the given mask.\n *\n * @param {Buffer} source The buffer to mask\n * @param {Buffer} mask The mask to use\n * @param {Buffer} output The buffer where to store the result\n * @param {Number} offset The offset at which to start writing\n * @param {Number} length The number of bytes to mask.\n * @public\n */\nfunction _mask(source, mask, output, offset, length) {\n for (let i = 0; i < length; i++) {\n output[offset + i] = source[i] ^ mask[i & 3];\n }\n}\n\n/**\n * Unmasks a buffer using the given mask.\n *\n * @param {Buffer} buffer The buffer to unmask\n * @param {Buffer} mask The mask to use\n * @public\n */\nfunction _unmask(buffer, mask) {\n for (let i = 0; i < buffer.length; i++) {\n buffer[i] ^= mask[i & 3];\n }\n}\n\n/**\n * Converts a buffer to an `ArrayBuffer`.\n *\n * @param {Buffer} buf The buffer to convert\n * @return {ArrayBuffer} Converted buffer\n * @public\n */\nfunction toArrayBuffer(buf) {\n if (buf.length === buf.buffer.byteLength) {\n return buf.buffer;\n }\n\n return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);\n}\n\n/**\n * Converts `data` to a `Buffer`.\n *\n * @param {*} data The data to convert\n * @return {Buffer} The buffer\n * @throws {TypeError}\n * @public\n */\nfunction toBuffer(data) {\n toBuffer.readOnly = true;\n\n if (Buffer.isBuffer(data)) return data;\n\n let buf;\n\n if (data instanceof ArrayBuffer) {\n buf = new FastBuffer(data);\n } else if (ArrayBuffer.isView(data)) {\n buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);\n } else {\n buf = Buffer.from(data);\n toBuffer.readOnly = false;\n }\n\n return buf;\n}\n\nmodule.exports = {\n concat,\n mask: _mask,\n toArrayBuffer,\n toBuffer,\n unmask: _unmask\n};\n\n/* istanbul ignore else */\nif (!process.env.WS_NO_BUFFER_UTIL) {\n try {\n const bufferUtil = require('bufferutil');\n\n module.exports.mask = function (source, mask, output, offset, length) {\n if (length < 48) _mask(source, mask, output, offset, length);\n else bufferUtil.mask(source, mask, output, offset, length);\n };\n\n module.exports.unmask = function (buffer, mask) {\n if (buffer.length < 32) _unmask(buffer, mask);\n else bufferUtil.unmask(buffer, mask);\n };\n } catch (e) {\n // Continue regardless of the error.\n }\n}\n","'use strict';\n\nconst kDone = Symbol('kDone');\nconst kRun = Symbol('kRun');\n\n/**\n * A very simple job queue with adjustable concurrency. Adapted from\n * https://github.com/STRML/async-limiter\n */\nclass Limiter {\n /**\n * Creates a new `Limiter`.\n *\n * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed\n * to run concurrently\n */\n constructor(concurrency) {\n this[kDone] = () => {\n this.pending--;\n this[kRun]();\n };\n this.concurrency = concurrency || Infinity;\n this.jobs = [];\n this.pending = 0;\n }\n\n /**\n * Adds a job to the queue.\n *\n * @param {Function} job The job to run\n * @public\n */\n add(job) {\n this.jobs.push(job);\n this[kRun]();\n }\n\n /**\n * Removes a job from the queue and runs it if possible.\n *\n * @private\n */\n [kRun]() {\n if (this.pending === this.concurrency) return;\n\n if (this.jobs.length) {\n const job = this.jobs.shift();\n\n this.pending++;\n job(this[kDone]);\n }\n }\n}\n\nmodule.exports = Limiter;\n","'use strict';\n\nconst zlib = require('zlib');\n\nconst bufferUtil = require('./buffer-util');\nconst Limiter = require('./limiter');\nconst { kStatusCode } = require('./constants');\n\nconst FastBuffer = Buffer[Symbol.species];\nconst TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]);\nconst kPerMessageDeflate = Symbol('permessage-deflate');\nconst kTotalLength = Symbol('total-length');\nconst kCallback = Symbol('callback');\nconst kBuffers = Symbol('buffers');\nconst kError = Symbol('error');\n\n//\n// We limit zlib concurrency, which prevents severe memory fragmentation\n// as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913\n// and https://github.com/websockets/ws/issues/1202\n//\n// Intentionally global; it's the global thread pool that's an issue.\n//\nlet zlibLimiter;\n\n/**\n * permessage-deflate implementation.\n */\nclass PerMessageDeflate {\n /**\n * Creates a PerMessageDeflate instance.\n *\n * @param {Object} [options] Configuration options\n * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support\n * for, or request, a custom client window size\n * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/\n * acknowledge disabling of client context takeover\n * @param {Number} [options.concurrencyLimit=10] The number of concurrent\n * calls to zlib\n * @param {Boolean} [options.isServer=false] Create the instance in either\n * server or client mode\n * @param {Number} [options.maxPayload=0] The maximum allowed message length\n * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the\n * use of a custom server window size\n * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept\n * disabling of server context takeover\n * @param {Number} [options.threshold=1024] Size (in bytes) below which\n * messages should not be compressed if context takeover is disabled\n * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on\n * deflate\n * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on\n * inflate\n */\n constructor(options) {\n this._options = options || {};\n this._threshold =\n this._options.threshold !== undefined ? this._options.threshold : 1024;\n this._maxPayload = this._options.maxPayload | 0;\n this._isServer = !!this._options.isServer;\n this._deflate = null;\n this._inflate = null;\n\n this.params = null;\n\n if (!zlibLimiter) {\n const concurrency =\n this._options.concurrencyLimit !== undefined\n ? this._options.concurrencyLimit\n : 10;\n zlibLimiter = new Limiter(concurrency);\n }\n }\n\n /**\n * @type {String}\n */\n static get extensionName() {\n return 'permessage-deflate';\n }\n\n /**\n * Create an extension negotiation offer.\n *\n * @return {Object} Extension parameters\n * @public\n */\n offer() {\n const params = {};\n\n if (this._options.serverNoContextTakeover) {\n params.server_no_context_takeover = true;\n }\n if (this._options.clientNoContextTakeover) {\n params.client_no_context_takeover = true;\n }\n if (this._options.serverMaxWindowBits) {\n params.server_max_window_bits = this._options.serverMaxWindowBits;\n }\n if (this._options.clientMaxWindowBits) {\n params.client_max_window_bits = this._options.clientMaxWindowBits;\n } else if (this._options.clientMaxWindowBits == null) {\n params.client_max_window_bits = true;\n }\n\n return params;\n }\n\n /**\n * Accept an extension negotiation offer/response.\n *\n * @param {Array} configurations The extension negotiation offers/reponse\n * @return {Object} Accepted configuration\n * @public\n */\n accept(configurations) {\n configurations = this.normalizeParams(configurations);\n\n this.params = this._isServer\n ? this.acceptAsServer(configurations)\n : this.acceptAsClient(configurations);\n\n return this.params;\n }\n\n /**\n * Releases all resources used by the extension.\n *\n * @public\n */\n cleanup() {\n if (this._inflate) {\n this._inflate.close();\n this._inflate = null;\n }\n\n if (this._deflate) {\n const callback = this._deflate[kCallback];\n\n this._deflate.close();\n this._deflate = null;\n\n if (callback) {\n callback(\n new Error(\n 'The deflate stream was closed while data was being processed'\n )\n );\n }\n }\n }\n\n /**\n * Accept an extension negotiation offer.\n *\n * @param {Array} offers The extension negotiation offers\n * @return {Object} Accepted configuration\n * @private\n */\n acceptAsServer(offers) {\n const opts = this._options;\n const accepted = offers.find((params) => {\n if (\n (opts.serverNoContextTakeover === false &&\n params.server_no_context_takeover) ||\n (params.server_max_window_bits &&\n (opts.serverMaxWindowBits === false ||\n (typeof opts.serverMaxWindowBits === 'number' &&\n opts.serverMaxWindowBits > params.server_max_window_bits))) ||\n (typeof opts.clientMaxWindowBits === 'number' &&\n (typeof params.client_max_window_bits === 'number'\n ? opts.clientMaxWindowBits > params.client_max_window_bits\n : !params.client_max_window_bits))\n ) {\n return false;\n }\n\n return true;\n });\n\n if (!accepted) {\n throw new Error('None of the extension offers can be accepted');\n }\n\n if (opts.serverNoContextTakeover) {\n accepted.server_no_context_takeover = true;\n }\n if (opts.clientNoContextTakeover) {\n accepted.client_no_context_takeover = true;\n }\n if (typeof opts.serverMaxWindowBits === 'number') {\n accepted.server_max_window_bits = opts.serverMaxWindowBits;\n }\n if (typeof opts.clientMaxWindowBits === 'number') {\n accepted.client_max_window_bits = opts.clientMaxWindowBits;\n } else if (\n accepted.client_max_window_bits === true ||\n opts.clientMaxWindowBits === false\n ) {\n delete accepted.client_max_window_bits;\n }\n\n return accepted;\n }\n\n /**\n * Accept the extension negotiation response.\n *\n * @param {Array} response The extension negotiation response\n * @return {Object} Accepted configuration\n * @private\n */\n acceptAsClient(response) {\n const params = response[0];\n\n if (\n this._options.clientNoContextTakeover === false &&\n params.client_no_context_takeover\n ) {\n throw new Error('Unexpected parameter \"client_no_context_takeover\"');\n }\n\n if (!params.client_max_window_bits) {\n if (typeof this._options.clientMaxWindowBits === 'number') {\n params.client_max_window_bits = this._options.clientMaxWindowBits;\n }\n } else if (\n this._options.clientMaxWindowBits === false ||\n (typeof this._options.clientMaxWindowBits === 'number' &&\n params.client_max_window_bits > this._options.clientMaxWindowBits)\n ) {\n throw new Error(\n 'Unexpected or invalid parameter \"client_max_window_bits\"'\n );\n }\n\n return params;\n }\n\n /**\n * Normalize parameters.\n *\n * @param {Array} configurations The extension negotiation offers/reponse\n * @return {Array} The offers/response with normalized parameters\n * @private\n */\n normalizeParams(configurations) {\n configurations.forEach((params) => {\n Object.keys(params).forEach((key) => {\n let value = params[key];\n\n if (value.length > 1) {\n throw new Error(`Parameter \"${key}\" must have only a single value`);\n }\n\n value = value[0];\n\n if (key === 'client_max_window_bits') {\n if (value !== true) {\n const num = +value;\n if (!Number.isInteger(num) || num < 8 || num > 15) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n value = num;\n } else if (!this._isServer) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n } else if (key === 'server_max_window_bits') {\n const num = +value;\n if (!Number.isInteger(num) || num < 8 || num > 15) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n value = num;\n } else if (\n key === 'client_no_context_takeover' ||\n key === 'server_no_context_takeover'\n ) {\n if (value !== true) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n } else {\n throw new Error(`Unknown parameter \"${key}\"`);\n }\n\n params[key] = value;\n });\n });\n\n return configurations;\n }\n\n /**\n * Decompress data. Concurrency limited.\n *\n * @param {Buffer} data Compressed data\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @public\n */\n decompress(data, fin, callback) {\n zlibLimiter.add((done) => {\n this._decompress(data, fin, (err, result) => {\n done();\n callback(err, result);\n });\n });\n }\n\n /**\n * Compress data. Concurrency limited.\n *\n * @param {(Buffer|String)} data Data to compress\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @public\n */\n compress(data, fin, callback) {\n zlibLimiter.add((done) => {\n this._compress(data, fin, (err, result) => {\n done();\n callback(err, result);\n });\n });\n }\n\n /**\n * Decompress data.\n *\n * @param {Buffer} data Compressed data\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @private\n */\n _decompress(data, fin, callback) {\n const endpoint = this._isServer ? 'client' : 'server';\n\n if (!this._inflate) {\n const key = `${endpoint}_max_window_bits`;\n const windowBits =\n typeof this.params[key] !== 'number'\n ? zlib.Z_DEFAULT_WINDOWBITS\n : this.params[key];\n\n this._inflate = zlib.createInflateRaw({\n ...this._options.zlibInflateOptions,\n windowBits\n });\n this._inflate[kPerMessageDeflate] = this;\n this._inflate[kTotalLength] = 0;\n this._inflate[kBuffers] = [];\n this._inflate.on('error', inflateOnError);\n this._inflate.on('data', inflateOnData);\n }\n\n this._inflate[kCallback] = callback;\n\n this._inflate.write(data);\n if (fin) this._inflate.write(TRAILER);\n\n this._inflate.flush(() => {\n const err = this._inflate[kError];\n\n if (err) {\n this._inflate.close();\n this._inflate = null;\n callback(err);\n return;\n }\n\n const data = bufferUtil.concat(\n this._inflate[kBuffers],\n this._inflate[kTotalLength]\n );\n\n if (this._inflate._readableState.endEmitted) {\n this._inflate.close();\n this._inflate = null;\n } else {\n this._inflate[kTotalLength] = 0;\n this._inflate[kBuffers] = [];\n\n if (fin && this.params[`${endpoint}_no_context_takeover`]) {\n this._inflate.reset();\n }\n }\n\n callback(null, data);\n });\n }\n\n /**\n * Compress data.\n *\n * @param {(Buffer|String)} data Data to compress\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @private\n */\n _compress(data, fin, callback) {\n const endpoint = this._isServer ? 'server' : 'client';\n\n if (!this._deflate) {\n const key = `${endpoint}_max_window_bits`;\n const windowBits =\n typeof this.params[key] !== 'number'\n ? zlib.Z_DEFAULT_WINDOWBITS\n : this.params[key];\n\n this._deflate = zlib.createDeflateRaw({\n ...this._options.zlibDeflateOptions,\n windowBits\n });\n\n this._deflate[kTotalLength] = 0;\n this._deflate[kBuffers] = [];\n\n this._deflate.on('data', deflateOnData);\n }\n\n this._deflate[kCallback] = callback;\n\n this._deflate.write(data);\n this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {\n if (!this._deflate) {\n //\n // The deflate stream was closed while data was being processed.\n //\n return;\n }\n\n let data = bufferUtil.concat(\n this._deflate[kBuffers],\n this._deflate[kTotalLength]\n );\n\n if (fin) {\n data = new FastBuffer(data.buffer, data.byteOffset, data.length - 4);\n }\n\n //\n // Ensure that the callback will not be called again in\n // `PerMessageDeflate#cleanup()`.\n //\n this._deflate[kCallback] = null;\n\n this._deflate[kTotalLength] = 0;\n this._deflate[kBuffers] = [];\n\n if (fin && this.params[`${endpoint}_no_context_takeover`]) {\n this._deflate.reset();\n }\n\n callback(null, data);\n });\n }\n}\n\nmodule.exports = PerMessageDeflate;\n\n/**\n * The listener of the `zlib.DeflateRaw` stream `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction deflateOnData(chunk) {\n this[kBuffers].push(chunk);\n this[kTotalLength] += chunk.length;\n}\n\n/**\n * The listener of the `zlib.InflateRaw` stream `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction inflateOnData(chunk) {\n this[kTotalLength] += chunk.length;\n\n if (\n this[kPerMessageDeflate]._maxPayload < 1 ||\n this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload\n ) {\n this[kBuffers].push(chunk);\n return;\n }\n\n this[kError] = new RangeError('Max payload size exceeded');\n this[kError].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH';\n this[kError][kStatusCode] = 1009;\n this.removeListener('data', inflateOnData);\n\n //\n // The choice to employ `zlib.reset()` over `zlib.close()` is dictated by the\n // fact that in Node.js versions prior to 13.10.0, the callback for\n // `zlib.flush()` is not called if `zlib.close()` is used. Utilizing\n // `zlib.reset()` ensures that either the callback is invoked or an error is\n // emitted.\n //\n this.reset();\n}\n\n/**\n * The listener of the `zlib.InflateRaw` stream `'error'` event.\n *\n * @param {Error} err The emitted error\n * @private\n */\nfunction inflateOnError(err) {\n //\n // There is no need to call `Zlib#close()` as the handle is automatically\n // closed when an error is emitted.\n //\n this[kPerMessageDeflate]._inflate = null;\n\n if (this[kError]) {\n this[kCallback](this[kError]);\n return;\n }\n\n err[kStatusCode] = 1007;\n this[kCallback](err);\n}\n","'use strict';\n\nconst { isUtf8 } = require('buffer');\n\nconst { hasBlob } = require('./constants');\n\n//\n// Allowed token characters:\n//\n// '!', '#', '$', '%', '&', ''', '*', '+', '-',\n// '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~'\n//\n// tokenChars[32] === 0 // ' '\n// tokenChars[33] === 1 // '!'\n// tokenChars[34] === 0 // '\"'\n// ...\n//\n// prettier-ignore\nconst tokenChars = [\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31\n 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63\n 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127\n];\n\n/**\n * Checks if a status code is allowed in a close frame.\n *\n * @param {Number} code The status code\n * @return {Boolean} `true` if the status code is valid, else `false`\n * @public\n */\nfunction isValidStatusCode(code) {\n return (\n (code >= 1000 &&\n code <= 1014 &&\n code !== 1004 &&\n code !== 1005 &&\n code !== 1006) ||\n (code >= 3000 && code <= 4999)\n );\n}\n\n/**\n * Checks if a given buffer contains only correct UTF-8.\n * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by\n * Markus Kuhn.\n *\n * @param {Buffer} buf The buffer to check\n * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`\n * @public\n */\nfunction _isValidUTF8(buf) {\n const len = buf.length;\n let i = 0;\n\n while (i < len) {\n if ((buf[i] & 0x80) === 0) {\n // 0xxxxxxx\n i++;\n } else if ((buf[i] & 0xe0) === 0xc0) {\n // 110xxxxx 10xxxxxx\n if (\n i + 1 === len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i] & 0xfe) === 0xc0 // Overlong\n ) {\n return false;\n }\n\n i += 2;\n } else if ((buf[i] & 0xf0) === 0xe0) {\n // 1110xxxx 10xxxxxx 10xxxxxx\n if (\n i + 2 >= len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i + 2] & 0xc0) !== 0x80 ||\n (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong\n (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF)\n ) {\n return false;\n }\n\n i += 3;\n } else if ((buf[i] & 0xf8) === 0xf0) {\n // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\n if (\n i + 3 >= len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i + 2] & 0xc0) !== 0x80 ||\n (buf[i + 3] & 0xc0) !== 0x80 ||\n (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong\n (buf[i] === 0xf4 && buf[i + 1] > 0x8f) ||\n buf[i] > 0xf4 // > U+10FFFF\n ) {\n return false;\n }\n\n i += 4;\n } else {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Determines whether a value is a `Blob`.\n *\n * @param {*} value The value to be tested\n * @return {Boolean} `true` if `value` is a `Blob`, else `false`\n * @private\n */\nfunction isBlob(value) {\n return (\n hasBlob &&\n typeof value === 'object' &&\n typeof value.arrayBuffer === 'function' &&\n typeof value.type === 'string' &&\n typeof value.stream === 'function' &&\n (value[Symbol.toStringTag] === 'Blob' ||\n value[Symbol.toStringTag] === 'File')\n );\n}\n\nmodule.exports = {\n isBlob,\n isValidStatusCode,\n isValidUTF8: _isValidUTF8,\n tokenChars\n};\n\nif (isUtf8) {\n module.exports.isValidUTF8 = function (buf) {\n return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);\n };\n} /* istanbul ignore else */ else if (!process.env.WS_NO_UTF_8_VALIDATE) {\n try {\n const isValidUTF8 = require('utf-8-validate');\n\n module.exports.isValidUTF8 = function (buf) {\n return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);\n };\n } catch (e) {\n // Continue regardless of the error.\n }\n}\n","'use strict';\n\nconst { Writable } = require('stream');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst {\n BINARY_TYPES,\n EMPTY_BUFFER,\n kStatusCode,\n kWebSocket\n} = require('./constants');\nconst { concat, toArrayBuffer, unmask } = require('./buffer-util');\nconst { isValidStatusCode, isValidUTF8 } = require('./validation');\n\nconst FastBuffer = Buffer[Symbol.species];\n\nconst GET_INFO = 0;\nconst GET_PAYLOAD_LENGTH_16 = 1;\nconst GET_PAYLOAD_LENGTH_64 = 2;\nconst GET_MASK = 3;\nconst GET_DATA = 4;\nconst INFLATING = 5;\nconst DEFER_EVENT = 6;\n\n/**\n * HyBi Receiver implementation.\n *\n * @extends Writable\n */\nclass Receiver extends Writable {\n /**\n * Creates a Receiver instance.\n *\n * @param {Object} [options] Options object\n * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether\n * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n * multiple times in the same tick\n * @param {String} [options.binaryType=nodebuffer] The type for binary data\n * @param {Object} [options.extensions] An object containing the negotiated\n * extensions\n * @param {Boolean} [options.isServer=false] Specifies whether to operate in\n * client or server mode\n * @param {Number} [options.maxBufferedChunks=0] The maximum number of\n * buffered data chunks\n * @param {Number} [options.maxFragments=0] The maximum number of message\n * fragments\n * @param {Number} [options.maxPayload=0] The maximum allowed message length\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n */\n constructor(options = {}) {\n super();\n\n this._allowSynchronousEvents =\n options.allowSynchronousEvents !== undefined\n ? options.allowSynchronousEvents\n : true;\n this._binaryType = options.binaryType || BINARY_TYPES[0];\n this._extensions = options.extensions || {};\n this._isServer = !!options.isServer;\n this._maxBufferedChunks = options.maxBufferedChunks | 0;\n this._maxFragments = options.maxFragments | 0;\n this._maxPayload = options.maxPayload | 0;\n this._skipUTF8Validation = !!options.skipUTF8Validation;\n this[kWebSocket] = undefined;\n\n this._bufferedBytes = 0;\n this._buffers = [];\n\n this._compressed = false;\n this._payloadLength = 0;\n this._mask = undefined;\n this._fragmented = 0;\n this._masked = false;\n this._fin = false;\n this._opcode = 0;\n\n this._totalPayloadLength = 0;\n this._messageLength = 0;\n this._numFragments = 0;\n this._fragments = [];\n\n this._errored = false;\n this._loop = false;\n this._state = GET_INFO;\n }\n\n /**\n * Implements `Writable.prototype._write()`.\n *\n * @param {Buffer} chunk The chunk of data to write\n * @param {String} encoding The character encoding of `chunk`\n * @param {Function} cb Callback\n * @private\n */\n _write(chunk, encoding, cb) {\n if (this._opcode === 0x08 && this._state == GET_INFO) return cb();\n\n if (\n this._maxBufferedChunks > 0 &&\n this._buffers.length >= this._maxBufferedChunks\n ) {\n cb(\n this.createError(\n RangeError,\n 'Too many buffered chunks',\n false,\n 1008,\n 'WS_ERR_TOO_MANY_BUFFERED_PARTS'\n )\n );\n return;\n }\n\n this._bufferedBytes += chunk.length;\n this._buffers.push(chunk);\n this.startLoop(cb);\n }\n\n /**\n * Consumes `n` bytes from the buffered data.\n *\n * @param {Number} n The number of bytes to consume\n * @return {Buffer} The consumed bytes\n * @private\n */\n consume(n) {\n this._bufferedBytes -= n;\n\n if (n === this._buffers[0].length) return this._buffers.shift();\n\n if (n < this._buffers[0].length) {\n const buf = this._buffers[0];\n this._buffers[0] = new FastBuffer(\n buf.buffer,\n buf.byteOffset + n,\n buf.length - n\n );\n\n return new FastBuffer(buf.buffer, buf.byteOffset, n);\n }\n\n const dst = Buffer.allocUnsafe(n);\n\n do {\n const buf = this._buffers[0];\n const offset = dst.length - n;\n\n if (n >= buf.length) {\n dst.set(this._buffers.shift(), offset);\n } else {\n dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);\n this._buffers[0] = new FastBuffer(\n buf.buffer,\n buf.byteOffset + n,\n buf.length - n\n );\n }\n\n n -= buf.length;\n } while (n > 0);\n\n return dst;\n }\n\n /**\n * Starts the parsing loop.\n *\n * @param {Function} cb Callback\n * @private\n */\n startLoop(cb) {\n this._loop = true;\n\n do {\n switch (this._state) {\n case GET_INFO:\n this.getInfo(cb);\n break;\n case GET_PAYLOAD_LENGTH_16:\n this.getPayloadLength16(cb);\n break;\n case GET_PAYLOAD_LENGTH_64:\n this.getPayloadLength64(cb);\n break;\n case GET_MASK:\n this.getMask();\n break;\n case GET_DATA:\n this.getData(cb);\n break;\n case INFLATING:\n case DEFER_EVENT:\n this._loop = false;\n return;\n }\n } while (this._loop);\n\n if (!this._errored) cb();\n }\n\n /**\n * Reads the first two bytes of a frame.\n *\n * @param {Function} cb Callback\n * @private\n */\n getInfo(cb) {\n if (this._bufferedBytes < 2) {\n this._loop = false;\n return;\n }\n\n const buf = this.consume(2);\n\n if ((buf[0] & 0x30) !== 0x00) {\n const error = this.createError(\n RangeError,\n 'RSV2 and RSV3 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_2_3'\n );\n\n cb(error);\n return;\n }\n\n const compressed = (buf[0] & 0x40) === 0x40;\n\n if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {\n const error = this.createError(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n\n cb(error);\n return;\n }\n\n this._fin = (buf[0] & 0x80) === 0x80;\n this._opcode = buf[0] & 0x0f;\n this._payloadLength = buf[1] & 0x7f;\n\n if (this._opcode === 0x00) {\n if (compressed) {\n const error = this.createError(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n\n cb(error);\n return;\n }\n\n if (!this._fragmented) {\n const error = this.createError(\n RangeError,\n 'invalid opcode 0',\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n\n cb(error);\n return;\n }\n\n this._opcode = this._fragmented;\n } else if (this._opcode === 0x01 || this._opcode === 0x02) {\n if (this._fragmented) {\n const error = this.createError(\n RangeError,\n `invalid opcode ${this._opcode}`,\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n\n cb(error);\n return;\n }\n\n this._compressed = compressed;\n } else if (this._opcode > 0x07 && this._opcode < 0x0b) {\n if (!this._fin) {\n const error = this.createError(\n RangeError,\n 'FIN must be set',\n true,\n 1002,\n 'WS_ERR_EXPECTED_FIN'\n );\n\n cb(error);\n return;\n }\n\n if (compressed) {\n const error = this.createError(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n\n cb(error);\n return;\n }\n\n if (\n this._payloadLength > 0x7d ||\n (this._opcode === 0x08 && this._payloadLength === 1)\n ) {\n const error = this.createError(\n RangeError,\n `invalid payload length ${this._payloadLength}`,\n true,\n 1002,\n 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH'\n );\n\n cb(error);\n return;\n }\n } else {\n const error = this.createError(\n RangeError,\n `invalid opcode ${this._opcode}`,\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n\n cb(error);\n return;\n }\n\n if (!this._fin && !this._fragmented) this._fragmented = this._opcode;\n this._masked = (buf[1] & 0x80) === 0x80;\n\n if (this._isServer) {\n if (!this._masked) {\n const error = this.createError(\n RangeError,\n 'MASK must be set',\n true,\n 1002,\n 'WS_ERR_EXPECTED_MASK'\n );\n\n cb(error);\n return;\n }\n } else if (this._masked) {\n const error = this.createError(\n RangeError,\n 'MASK must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_MASK'\n );\n\n cb(error);\n return;\n }\n\n if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;\n else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;\n else this.haveLength(cb);\n }\n\n /**\n * Gets extended payload length (7+16).\n *\n * @param {Function} cb Callback\n * @private\n */\n getPayloadLength16(cb) {\n if (this._bufferedBytes < 2) {\n this._loop = false;\n return;\n }\n\n this._payloadLength = this.consume(2).readUInt16BE(0);\n this.haveLength(cb);\n }\n\n /**\n * Gets extended payload length (7+64).\n *\n * @param {Function} cb Callback\n * @private\n */\n getPayloadLength64(cb) {\n if (this._bufferedBytes < 8) {\n this._loop = false;\n return;\n }\n\n const buf = this.consume(8);\n const num = buf.readUInt32BE(0);\n\n //\n // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned\n // if payload length is greater than this number.\n //\n if (num > Math.pow(2, 53 - 32) - 1) {\n const error = this.createError(\n RangeError,\n 'Unsupported WebSocket frame: payload length > 2^53 - 1',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH'\n );\n\n cb(error);\n return;\n }\n\n this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);\n this.haveLength(cb);\n }\n\n /**\n * Payload length has been read.\n *\n * @param {Function} cb Callback\n * @private\n */\n haveLength(cb) {\n if (this._payloadLength && this._opcode < 0x08) {\n this._totalPayloadLength += this._payloadLength;\n if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {\n const error = this.createError(\n RangeError,\n 'Max payload size exceeded',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'\n );\n\n cb(error);\n return;\n }\n }\n\n if (this._masked) this._state = GET_MASK;\n else this._state = GET_DATA;\n }\n\n /**\n * Reads mask bytes.\n *\n * @private\n */\n getMask() {\n if (this._bufferedBytes < 4) {\n this._loop = false;\n return;\n }\n\n this._mask = this.consume(4);\n this._state = GET_DATA;\n }\n\n /**\n * Reads data bytes.\n *\n * @param {Function} cb Callback\n * @private\n */\n getData(cb) {\n let data = EMPTY_BUFFER;\n\n if (this._payloadLength) {\n if (this._bufferedBytes < this._payloadLength) {\n this._loop = false;\n return;\n }\n\n data = this.consume(this._payloadLength);\n\n if (\n this._masked &&\n (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0\n ) {\n unmask(data, this._mask);\n }\n }\n\n if (this._opcode > 0x07) {\n this.controlMessage(data, cb);\n return;\n }\n\n if (this._maxFragments > 0 && ++this._numFragments > this._maxFragments) {\n const error = this.createError(\n RangeError,\n 'Too many message fragments',\n false,\n 1008,\n 'WS_ERR_TOO_MANY_BUFFERED_PARTS'\n );\n\n cb(error);\n return;\n }\n\n if (this._compressed) {\n this._state = INFLATING;\n this.decompress(data, cb);\n return;\n }\n\n if (data.length) {\n //\n // This message is not compressed so its length is the sum of the payload\n // length of all fragments.\n //\n this._messageLength = this._totalPayloadLength;\n this._fragments.push(data);\n }\n\n this.dataMessage(cb);\n }\n\n /**\n * Decompresses data.\n *\n * @param {Buffer} data Compressed data\n * @param {Function} cb Callback\n * @private\n */\n decompress(data, cb) {\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n\n perMessageDeflate.decompress(data, this._fin, (err, buf) => {\n if (err) return cb(err);\n\n if (buf.length) {\n this._messageLength += buf.length;\n if (this._messageLength > this._maxPayload && this._maxPayload > 0) {\n const error = this.createError(\n RangeError,\n 'Max payload size exceeded',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'\n );\n\n cb(error);\n return;\n }\n\n this._fragments.push(buf);\n }\n\n this.dataMessage(cb);\n if (this._state === GET_INFO) this.startLoop(cb);\n });\n }\n\n /**\n * Handles a data message.\n *\n * @param {Function} cb Callback\n * @private\n */\n dataMessage(cb) {\n if (!this._fin) {\n this._state = GET_INFO;\n return;\n }\n\n const messageLength = this._messageLength;\n const fragments = this._fragments;\n\n this._totalPayloadLength = 0;\n this._messageLength = 0;\n this._fragmented = 0;\n this._numFragments = 0;\n this._fragments = [];\n\n if (this._opcode === 2) {\n let data;\n\n if (this._binaryType === 'nodebuffer') {\n data = concat(fragments, messageLength);\n } else if (this._binaryType === 'arraybuffer') {\n data = toArrayBuffer(concat(fragments, messageLength));\n } else if (this._binaryType === 'blob') {\n data = new Blob(fragments);\n } else {\n data = fragments;\n }\n\n if (this._allowSynchronousEvents) {\n this.emit('message', data, true);\n this._state = GET_INFO;\n } else {\n this._state = DEFER_EVENT;\n setImmediate(() => {\n this.emit('message', data, true);\n this._state = GET_INFO;\n this.startLoop(cb);\n });\n }\n } else {\n const buf = concat(fragments, messageLength);\n\n if (!this._skipUTF8Validation && !isValidUTF8(buf)) {\n const error = this.createError(\n Error,\n 'invalid UTF-8 sequence',\n true,\n 1007,\n 'WS_ERR_INVALID_UTF8'\n );\n\n cb(error);\n return;\n }\n\n if (this._state === INFLATING || this._allowSynchronousEvents) {\n this.emit('message', buf, false);\n this._state = GET_INFO;\n } else {\n this._state = DEFER_EVENT;\n setImmediate(() => {\n this.emit('message', buf, false);\n this._state = GET_INFO;\n this.startLoop(cb);\n });\n }\n }\n }\n\n /**\n * Handles a control message.\n *\n * @param {Buffer} data Data to handle\n * @return {(Error|RangeError|undefined)} A possible error\n * @private\n */\n controlMessage(data, cb) {\n if (this._opcode === 0x08) {\n if (data.length === 0) {\n this._loop = false;\n this.emit('conclude', 1005, EMPTY_BUFFER);\n this.end();\n } else {\n const code = data.readUInt16BE(0);\n\n if (!isValidStatusCode(code)) {\n const error = this.createError(\n RangeError,\n `invalid status code ${code}`,\n true,\n 1002,\n 'WS_ERR_INVALID_CLOSE_CODE'\n );\n\n cb(error);\n return;\n }\n\n const buf = new FastBuffer(\n data.buffer,\n data.byteOffset + 2,\n data.length - 2\n );\n\n if (!this._skipUTF8Validation && !isValidUTF8(buf)) {\n const error = this.createError(\n Error,\n 'invalid UTF-8 sequence',\n true,\n 1007,\n 'WS_ERR_INVALID_UTF8'\n );\n\n cb(error);\n return;\n }\n\n this._loop = false;\n this.emit('conclude', code, buf);\n this.end();\n }\n\n this._state = GET_INFO;\n return;\n }\n\n if (this._allowSynchronousEvents) {\n this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);\n this._state = GET_INFO;\n } else {\n this._state = DEFER_EVENT;\n setImmediate(() => {\n this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);\n this._state = GET_INFO;\n this.startLoop(cb);\n });\n }\n }\n\n /**\n * Builds an error object.\n *\n * @param {function(new:Error|RangeError)} ErrorCtor The error constructor\n * @param {String} message The error message\n * @param {Boolean} prefix Specifies whether or not to add a default prefix to\n * `message`\n * @param {Number} statusCode The status code\n * @param {String} errorCode The exposed error code\n * @return {(Error|RangeError)} The error\n * @private\n */\n createError(ErrorCtor, message, prefix, statusCode, errorCode) {\n this._loop = false;\n this._errored = true;\n\n const err = new ErrorCtor(\n prefix ? `Invalid WebSocket frame: ${message}` : message\n );\n\n Error.captureStackTrace(err, this.createError);\n err.code = errorCode;\n err[kStatusCode] = statusCode;\n return err;\n }\n}\n\nmodule.exports = Receiver;\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex\" }] */\n\n'use strict';\n\nconst { Duplex } = require('stream');\nconst { randomFillSync } = require('crypto');\nconst {\n types: { isUint8Array }\n} = require('util');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst { EMPTY_BUFFER, kWebSocket, NOOP } = require('./constants');\nconst { isBlob, isValidStatusCode } = require('./validation');\nconst { mask: applyMask, toBuffer } = require('./buffer-util');\n\nconst kByteLength = Symbol('kByteLength');\nconst maskBuffer = Buffer.alloc(4);\nconst RANDOM_POOL_SIZE = 8 * 1024;\nlet randomPool;\nlet randomPoolPointer = RANDOM_POOL_SIZE;\n\nconst DEFAULT = 0;\nconst DEFLATING = 1;\nconst GET_BLOB_DATA = 2;\n\n/**\n * HyBi Sender implementation.\n */\nclass Sender {\n /**\n * Creates a Sender instance.\n *\n * @param {Duplex} socket The connection socket\n * @param {Object} [extensions] An object containing the negotiated extensions\n * @param {Function} [generateMask] The function used to generate the masking\n * key\n */\n constructor(socket, extensions, generateMask) {\n this._extensions = extensions || {};\n\n if (generateMask) {\n this._generateMask = generateMask;\n this._maskBuffer = Buffer.alloc(4);\n }\n\n this._socket = socket;\n\n this._firstFragment = true;\n this._compress = false;\n\n this._bufferedBytes = 0;\n this._queue = [];\n this._state = DEFAULT;\n this.onerror = NOOP;\n this[kWebSocket] = undefined;\n }\n\n /**\n * Frames a piece of data according to the HyBi WebSocket protocol.\n *\n * @param {(Buffer|String)} data The data to frame\n * @param {Object} options Options object\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n * key\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @return {(Buffer|String)[]} The framed data\n * @public\n */\n static frame(data, options) {\n let mask;\n let merge = false;\n let offset = 2;\n let skipMasking = false;\n\n if (options.mask) {\n mask = options.maskBuffer || maskBuffer;\n\n if (options.generateMask) {\n options.generateMask(mask);\n } else {\n if (randomPoolPointer === RANDOM_POOL_SIZE) {\n /* istanbul ignore else */\n if (randomPool === undefined) {\n //\n // This is lazily initialized because server-sent frames must not\n // be masked so it may never be used.\n //\n randomPool = Buffer.alloc(RANDOM_POOL_SIZE);\n }\n\n randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);\n randomPoolPointer = 0;\n }\n\n mask[0] = randomPool[randomPoolPointer++];\n mask[1] = randomPool[randomPoolPointer++];\n mask[2] = randomPool[randomPoolPointer++];\n mask[3] = randomPool[randomPoolPointer++];\n }\n\n skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;\n offset = 6;\n }\n\n let dataLength;\n\n if (typeof data === 'string') {\n if (\n (!options.mask || skipMasking) &&\n options[kByteLength] !== undefined\n ) {\n dataLength = options[kByteLength];\n } else {\n data = Buffer.from(data);\n dataLength = data.length;\n }\n } else {\n dataLength = data.length;\n merge = options.mask && options.readOnly && !skipMasking;\n }\n\n let payloadLength = dataLength;\n\n if (dataLength >= 65536) {\n offset += 8;\n payloadLength = 127;\n } else if (dataLength > 125) {\n offset += 2;\n payloadLength = 126;\n }\n\n const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);\n\n target[0] = options.fin ? options.opcode | 0x80 : options.opcode;\n if (options.rsv1) target[0] |= 0x40;\n\n target[1] = payloadLength;\n\n if (payloadLength === 126) {\n target.writeUInt16BE(dataLength, 2);\n } else if (payloadLength === 127) {\n target[2] = target[3] = 0;\n target.writeUIntBE(dataLength, 4, 6);\n }\n\n if (!options.mask) return [target, data];\n\n target[1] |= 0x80;\n target[offset - 4] = mask[0];\n target[offset - 3] = mask[1];\n target[offset - 2] = mask[2];\n target[offset - 1] = mask[3];\n\n if (skipMasking) return [target, data];\n\n if (merge) {\n applyMask(data, mask, target, offset, dataLength);\n return [target];\n }\n\n applyMask(data, mask, data, 0, dataLength);\n return [target, data];\n }\n\n /**\n * Sends a close message to the other peer.\n *\n * @param {Number} [code] The status code component of the body\n * @param {(String|Buffer)} [data] The message component of the body\n * @param {Boolean} [mask=false] Specifies whether or not to mask the message\n * @param {Function} [cb] Callback\n * @public\n */\n close(code, data, mask, cb) {\n let buf;\n\n if (code === undefined) {\n buf = EMPTY_BUFFER;\n } else if (typeof code !== 'number' || !isValidStatusCode(code)) {\n throw new TypeError('First argument must be a valid error code number');\n } else if (data === undefined || !data.length) {\n buf = Buffer.allocUnsafe(2);\n buf.writeUInt16BE(code, 0);\n } else {\n const length = Buffer.byteLength(data);\n\n if (length > 123) {\n throw new RangeError('The message must not be greater than 123 bytes');\n }\n\n buf = Buffer.allocUnsafe(2 + length);\n buf.writeUInt16BE(code, 0);\n\n if (typeof data === 'string') {\n buf.write(data, 2);\n } else if (isUint8Array(data)) {\n buf.set(data, 2);\n } else {\n throw new TypeError('Second argument must be a string or a Uint8Array');\n }\n }\n\n const options = {\n [kByteLength]: buf.length,\n fin: true,\n generateMask: this._generateMask,\n mask,\n maskBuffer: this._maskBuffer,\n opcode: 0x08,\n readOnly: false,\n rsv1: false\n };\n\n if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, buf, false, options, cb]);\n } else {\n this.sendFrame(Sender.frame(buf, options), cb);\n }\n }\n\n /**\n * Sends a ping message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Boolean} [mask=false] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback\n * @public\n */\n ping(data, mask, cb) {\n let byteLength;\n let readOnly;\n\n if (typeof data === 'string') {\n byteLength = Buffer.byteLength(data);\n readOnly = false;\n } else if (isBlob(data)) {\n byteLength = data.size;\n readOnly = false;\n } else {\n data = toBuffer(data);\n byteLength = data.length;\n readOnly = toBuffer.readOnly;\n }\n\n if (byteLength > 125) {\n throw new RangeError('The data size must not be greater than 125 bytes');\n }\n\n const options = {\n [kByteLength]: byteLength,\n fin: true,\n generateMask: this._generateMask,\n mask,\n maskBuffer: this._maskBuffer,\n opcode: 0x09,\n readOnly,\n rsv1: false\n };\n\n if (isBlob(data)) {\n if (this._state !== DEFAULT) {\n this.enqueue([this.getBlobData, data, false, options, cb]);\n } else {\n this.getBlobData(data, false, options, cb);\n }\n } else if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, data, false, options, cb]);\n } else {\n this.sendFrame(Sender.frame(data, options), cb);\n }\n }\n\n /**\n * Sends a pong message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Boolean} [mask=false] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback\n * @public\n */\n pong(data, mask, cb) {\n let byteLength;\n let readOnly;\n\n if (typeof data === 'string') {\n byteLength = Buffer.byteLength(data);\n readOnly = false;\n } else if (isBlob(data)) {\n byteLength = data.size;\n readOnly = false;\n } else {\n data = toBuffer(data);\n byteLength = data.length;\n readOnly = toBuffer.readOnly;\n }\n\n if (byteLength > 125) {\n throw new RangeError('The data size must not be greater than 125 bytes');\n }\n\n const options = {\n [kByteLength]: byteLength,\n fin: true,\n generateMask: this._generateMask,\n mask,\n maskBuffer: this._maskBuffer,\n opcode: 0x0a,\n readOnly,\n rsv1: false\n };\n\n if (isBlob(data)) {\n if (this._state !== DEFAULT) {\n this.enqueue([this.getBlobData, data, false, options, cb]);\n } else {\n this.getBlobData(data, false, options, cb);\n }\n } else if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, data, false, options, cb]);\n } else {\n this.sendFrame(Sender.frame(data, options), cb);\n }\n }\n\n /**\n * Sends a data message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Object} options Options object\n * @param {Boolean} [options.binary=false] Specifies whether `data` is binary\n * or text\n * @param {Boolean} [options.compress=false] Specifies whether or not to\n * compress `data`\n * @param {Boolean} [options.fin=false] Specifies whether the fragment is the\n * last one\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Function} [cb] Callback\n * @public\n */\n send(data, options, cb) {\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n let opcode = options.binary ? 2 : 1;\n let rsv1 = options.compress;\n\n let byteLength;\n let readOnly;\n\n if (typeof data === 'string') {\n byteLength = Buffer.byteLength(data);\n readOnly = false;\n } else if (isBlob(data)) {\n byteLength = data.size;\n readOnly = false;\n } else {\n data = toBuffer(data);\n byteLength = data.length;\n readOnly = toBuffer.readOnly;\n }\n\n if (this._firstFragment) {\n this._firstFragment = false;\n if (\n rsv1 &&\n perMessageDeflate &&\n perMessageDeflate.params[\n perMessageDeflate._isServer\n ? 'server_no_context_takeover'\n : 'client_no_context_takeover'\n ]\n ) {\n rsv1 = byteLength >= perMessageDeflate._threshold;\n }\n this._compress = rsv1;\n } else {\n rsv1 = false;\n opcode = 0;\n }\n\n if (options.fin) this._firstFragment = true;\n\n const opts = {\n [kByteLength]: byteLength,\n fin: options.fin,\n generateMask: this._generateMask,\n mask: options.mask,\n maskBuffer: this._maskBuffer,\n opcode,\n readOnly,\n rsv1\n };\n\n if (isBlob(data)) {\n if (this._state !== DEFAULT) {\n this.enqueue([this.getBlobData, data, this._compress, opts, cb]);\n } else {\n this.getBlobData(data, this._compress, opts, cb);\n }\n } else if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, data, this._compress, opts, cb]);\n } else {\n this.dispatch(data, this._compress, opts, cb);\n }\n }\n\n /**\n * Gets the contents of a blob as binary data.\n *\n * @param {Blob} blob The blob\n * @param {Boolean} [compress=false] Specifies whether or not to compress\n * the data\n * @param {Object} options Options object\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n * key\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @param {Function} [cb] Callback\n * @private\n */\n getBlobData(blob, compress, options, cb) {\n this._bufferedBytes += options[kByteLength];\n this._state = GET_BLOB_DATA;\n\n blob\n .arrayBuffer()\n .then((arrayBuffer) => {\n if (this._socket.destroyed) {\n const err = new Error(\n 'The socket was closed while the blob was being read'\n );\n\n //\n // `callCallbacks` is called in the next tick to ensure that errors\n // that might be thrown in the callbacks behave like errors thrown\n // outside the promise chain.\n //\n process.nextTick(callCallbacks, this, err, cb);\n return;\n }\n\n this._bufferedBytes -= options[kByteLength];\n const data = toBuffer(arrayBuffer);\n\n if (!compress) {\n this._state = DEFAULT;\n this.sendFrame(Sender.frame(data, options), cb);\n this.dequeue();\n } else {\n this.dispatch(data, compress, options, cb);\n }\n })\n .catch((err) => {\n //\n // `onError` is called in the next tick for the same reason that\n // `callCallbacks` above is.\n //\n process.nextTick(onError, this, err, cb);\n });\n }\n\n /**\n * Dispatches a message.\n *\n * @param {(Buffer|String)} data The message to send\n * @param {Boolean} [compress=false] Specifies whether or not to compress\n * `data`\n * @param {Object} options Options object\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n * key\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @param {Function} [cb] Callback\n * @private\n */\n dispatch(data, compress, options, cb) {\n if (!compress) {\n this.sendFrame(Sender.frame(data, options), cb);\n return;\n }\n\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n\n this._bufferedBytes += options[kByteLength];\n this._state = DEFLATING;\n perMessageDeflate.compress(data, options.fin, (_, buf) => {\n if (this._socket.destroyed) {\n const err = new Error(\n 'The socket was closed while data was being compressed'\n );\n\n callCallbacks(this, err, cb);\n return;\n }\n\n this._bufferedBytes -= options[kByteLength];\n this._state = DEFAULT;\n options.readOnly = false;\n this.sendFrame(Sender.frame(buf, options), cb);\n this.dequeue();\n });\n }\n\n /**\n * Executes queued send operations.\n *\n * @private\n */\n dequeue() {\n while (this._state === DEFAULT && this._queue.length) {\n const params = this._queue.shift();\n\n this._bufferedBytes -= params[3][kByteLength];\n Reflect.apply(params[0], this, params.slice(1));\n }\n }\n\n /**\n * Enqueues a send operation.\n *\n * @param {Array} params Send operation parameters.\n * @private\n */\n enqueue(params) {\n this._bufferedBytes += params[3][kByteLength];\n this._queue.push(params);\n }\n\n /**\n * Sends a frame.\n *\n * @param {(Buffer | String)[]} list The frame to send\n * @param {Function} [cb] Callback\n * @private\n */\n sendFrame(list, cb) {\n if (list.length === 2) {\n this._socket.cork();\n this._socket.write(list[0]);\n this._socket.write(list[1], cb);\n this._socket.uncork();\n } else {\n this._socket.write(list[0], cb);\n }\n }\n}\n\nmodule.exports = Sender;\n\n/**\n * Calls queued callbacks with an error.\n *\n * @param {Sender} sender The `Sender` instance\n * @param {Error} err The error to call the callbacks with\n * @param {Function} [cb] The first callback\n * @private\n */\nfunction callCallbacks(sender, err, cb) {\n if (typeof cb === 'function') cb(err);\n\n for (let i = 0; i < sender._queue.length; i++) {\n const params = sender._queue[i];\n const callback = params[params.length - 1];\n\n if (typeof callback === 'function') callback(err);\n }\n}\n\n/**\n * Handles a `Sender` error.\n *\n * @param {Sender} sender The `Sender` instance\n * @param {Error} err The error\n * @param {Function} [cb] The first pending callback\n * @private\n */\nfunction onError(sender, err, cb) {\n callCallbacks(sender, err, cb);\n sender.onerror(err);\n}\n","'use strict';\n\nconst { kForOnEventAttribute, kListener } = require('./constants');\n\nconst kCode = Symbol('kCode');\nconst kData = Symbol('kData');\nconst kError = Symbol('kError');\nconst kMessage = Symbol('kMessage');\nconst kReason = Symbol('kReason');\nconst kTarget = Symbol('kTarget');\nconst kType = Symbol('kType');\nconst kWasClean = Symbol('kWasClean');\n\n/**\n * Class representing an event.\n */\nclass Event {\n /**\n * Create a new `Event`.\n *\n * @param {String} type The name of the event\n * @throws {TypeError} If the `type` argument is not specified\n */\n constructor(type) {\n this[kTarget] = null;\n this[kType] = type;\n }\n\n /**\n * @type {*}\n */\n get target() {\n return this[kTarget];\n }\n\n /**\n * @type {String}\n */\n get type() {\n return this[kType];\n }\n}\n\nObject.defineProperty(Event.prototype, 'target', { enumerable: true });\nObject.defineProperty(Event.prototype, 'type', { enumerable: true });\n\n/**\n * Class representing a close event.\n *\n * @extends Event\n */\nclass CloseEvent extends Event {\n /**\n * Create a new `CloseEvent`.\n *\n * @param {String} type The name of the event\n * @param {Object} [options] A dictionary object that allows for setting\n * attributes via object members of the same name\n * @param {Number} [options.code=0] The status code explaining why the\n * connection was closed\n * @param {String} [options.reason=''] A human-readable string explaining why\n * the connection was closed\n * @param {Boolean} [options.wasClean=false] Indicates whether or not the\n * connection was cleanly closed\n */\n constructor(type, options = {}) {\n super(type);\n\n this[kCode] = options.code === undefined ? 0 : options.code;\n this[kReason] = options.reason === undefined ? '' : options.reason;\n this[kWasClean] = options.wasClean === undefined ? false : options.wasClean;\n }\n\n /**\n * @type {Number}\n */\n get code() {\n return this[kCode];\n }\n\n /**\n * @type {String}\n */\n get reason() {\n return this[kReason];\n }\n\n /**\n * @type {Boolean}\n */\n get wasClean() {\n return this[kWasClean];\n }\n}\n\nObject.defineProperty(CloseEvent.prototype, 'code', { enumerable: true });\nObject.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true });\nObject.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true });\n\n/**\n * Class representing an error event.\n *\n * @extends Event\n */\nclass ErrorEvent extends Event {\n /**\n * Create a new `ErrorEvent`.\n *\n * @param {String} type The name of the event\n * @param {Object} [options] A dictionary object that allows for setting\n * attributes via object members of the same name\n * @param {*} [options.error=null] The error that generated this event\n * @param {String} [options.message=''] The error message\n */\n constructor(type, options = {}) {\n super(type);\n\n this[kError] = options.error === undefined ? null : options.error;\n this[kMessage] = options.message === undefined ? '' : options.message;\n }\n\n /**\n * @type {*}\n */\n get error() {\n return this[kError];\n }\n\n /**\n * @type {String}\n */\n get message() {\n return this[kMessage];\n }\n}\n\nObject.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true });\nObject.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true });\n\n/**\n * Class representing a message event.\n *\n * @extends Event\n */\nclass MessageEvent extends Event {\n /**\n * Create a new `MessageEvent`.\n *\n * @param {String} type The name of the event\n * @param {Object} [options] A dictionary object that allows for setting\n * attributes via object members of the same name\n * @param {*} [options.data=null] The message content\n */\n constructor(type, options = {}) {\n super(type);\n\n this[kData] = options.data === undefined ? null : options.data;\n }\n\n /**\n * @type {*}\n */\n get data() {\n return this[kData];\n }\n}\n\nObject.defineProperty(MessageEvent.prototype, 'data', { enumerable: true });\n\n/**\n * This provides methods for emulating the `EventTarget` interface. It's not\n * meant to be used directly.\n *\n * @mixin\n */\nconst EventTarget = {\n /**\n * Register an event listener.\n *\n * @param {String} type A string representing the event type to listen for\n * @param {(Function|Object)} handler The listener to add\n * @param {Object} [options] An options object specifies characteristics about\n * the event listener\n * @param {Boolean} [options.once=false] A `Boolean` indicating that the\n * listener should be invoked at most once after being added. If `true`,\n * the listener would be automatically removed when invoked.\n * @public\n */\n addEventListener(type, handler, options = {}) {\n for (const listener of this.listeners(type)) {\n if (\n !options[kForOnEventAttribute] &&\n listener[kListener] === handler &&\n !listener[kForOnEventAttribute]\n ) {\n return;\n }\n }\n\n let wrapper;\n\n if (type === 'message') {\n wrapper = function onMessage(data, isBinary) {\n const event = new MessageEvent('message', {\n data: isBinary ? data : data.toString()\n });\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else if (type === 'close') {\n wrapper = function onClose(code, message) {\n const event = new CloseEvent('close', {\n code,\n reason: message.toString(),\n wasClean: this._closeFrameReceived && this._closeFrameSent\n });\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else if (type === 'error') {\n wrapper = function onError(error) {\n const event = new ErrorEvent('error', {\n error,\n message: error.message\n });\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else if (type === 'open') {\n wrapper = function onOpen() {\n const event = new Event('open');\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else {\n return;\n }\n\n wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];\n wrapper[kListener] = handler;\n\n if (options.once) {\n this.once(type, wrapper);\n } else {\n this.on(type, wrapper);\n }\n },\n\n /**\n * Remove an event listener.\n *\n * @param {String} type A string representing the event type to remove\n * @param {(Function|Object)} handler The listener to remove\n * @public\n */\n removeEventListener(type, handler) {\n for (const listener of this.listeners(type)) {\n if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {\n this.removeListener(type, listener);\n break;\n }\n }\n }\n};\n\nmodule.exports = {\n CloseEvent,\n ErrorEvent,\n Event,\n EventTarget,\n MessageEvent\n};\n\n/**\n * Call an event listener\n *\n * @param {(Function|Object)} listener The listener to call\n * @param {*} thisArg The value to use as `this`` when calling the listener\n * @param {Event} event The event to pass to the listener\n * @private\n */\nfunction callListener(listener, thisArg, event) {\n if (typeof listener === 'object' && listener.handleEvent) {\n listener.handleEvent.call(listener, event);\n } else {\n listener.call(thisArg, event);\n }\n}\n","'use strict';\n\nconst { tokenChars } = require('./validation');\n\n/**\n * Adds an offer to the map of extension offers or a parameter to the map of\n * parameters.\n *\n * @param {Object} dest The map of extension offers or parameters\n * @param {String} name The extension or parameter name\n * @param {(Object|Boolean|String)} elem The extension parameters or the\n * parameter value\n * @private\n */\nfunction push(dest, name, elem) {\n if (dest[name] === undefined) dest[name] = [elem];\n else dest[name].push(elem);\n}\n\n/**\n * Parses the `Sec-WebSocket-Extensions` header into an object.\n *\n * @param {String} header The field value of the header\n * @return {Object} The parsed object\n * @public\n */\nfunction parse(header) {\n const offers = Object.create(null);\n let params = Object.create(null);\n let mustUnescape = false;\n let isEscaping = false;\n let inQuotes = false;\n let extensionName;\n let paramName;\n let start = -1;\n let code = -1;\n let end = -1;\n let i = 0;\n\n for (; i < header.length; i++) {\n code = header.charCodeAt(i);\n\n if (extensionName === undefined) {\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (\n i !== 0 &&\n (code === 0x20 /* ' ' */ || code === 0x09) /* '\\t' */\n ) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n const name = header.slice(start, end);\n if (code === 0x2c) {\n push(offers, name, params);\n params = Object.create(null);\n } else {\n extensionName = name;\n }\n\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else if (paramName === undefined) {\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (code === 0x20 || code === 0x09) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x3b || code === 0x2c) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n push(params, header.slice(start, end), true);\n if (code === 0x2c) {\n push(offers, extensionName, params);\n params = Object.create(null);\n extensionName = undefined;\n }\n\n start = end = -1;\n } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) {\n paramName = header.slice(start, i);\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else {\n //\n // The value of a quoted-string after unescaping must conform to the\n // token ABNF, so only token characters are valid.\n // Ref: https://tools.ietf.org/html/rfc6455#section-9.1\n //\n if (isEscaping) {\n if (tokenChars[code] !== 1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n if (start === -1) start = i;\n else if (!mustUnescape) mustUnescape = true;\n isEscaping = false;\n } else if (inQuotes) {\n if (tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (code === 0x22 /* '\"' */ && start !== -1) {\n inQuotes = false;\n end = i;\n } else if (code === 0x5c /* '\\' */) {\n isEscaping = true;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) {\n inQuotes = true;\n } else if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (start !== -1 && (code === 0x20 || code === 0x09)) {\n if (end === -1) end = i;\n } else if (code === 0x3b || code === 0x2c) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n let value = header.slice(start, end);\n if (mustUnescape) {\n value = value.replace(/\\\\/g, '');\n mustUnescape = false;\n }\n push(params, paramName, value);\n if (code === 0x2c) {\n push(offers, extensionName, params);\n params = Object.create(null);\n extensionName = undefined;\n }\n\n paramName = undefined;\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n }\n }\n\n if (start === -1 || inQuotes || code === 0x20 || code === 0x09) {\n throw new SyntaxError('Unexpected end of input');\n }\n\n if (end === -1) end = i;\n const token = header.slice(start, end);\n if (extensionName === undefined) {\n push(offers, token, params);\n } else {\n if (paramName === undefined) {\n push(params, token, true);\n } else if (mustUnescape) {\n push(params, paramName, token.replace(/\\\\/g, ''));\n } else {\n push(params, paramName, token);\n }\n push(offers, extensionName, params);\n }\n\n return offers;\n}\n\n/**\n * Builds the `Sec-WebSocket-Extensions` header field value.\n *\n * @param {Object} extensions The map of extensions and parameters to format\n * @return {String} A string representing the given object\n * @public\n */\nfunction format(extensions) {\n return Object.keys(extensions)\n .map((extension) => {\n let configurations = extensions[extension];\n if (!Array.isArray(configurations)) configurations = [configurations];\n return configurations\n .map((params) => {\n return [extension]\n .concat(\n Object.keys(params).map((k) => {\n let values = params[k];\n if (!Array.isArray(values)) values = [values];\n return values\n .map((v) => (v === true ? k : `${k}=${v}`))\n .join('; ');\n })\n )\n .join('; ');\n })\n .join(', ');\n })\n .join(', ');\n}\n\nmodule.exports = { format, parse };\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex|Readable$\", \"caughtErrors\": \"none\" }] */\n\n'use strict';\n\nconst EventEmitter = require('events');\nconst https = require('https');\nconst http = require('http');\nconst net = require('net');\nconst tls = require('tls');\nconst { randomBytes, createHash } = require('crypto');\nconst { Duplex, Readable } = require('stream');\nconst { URL } = require('url');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst Receiver = require('./receiver');\nconst Sender = require('./sender');\nconst { isBlob } = require('./validation');\n\nconst {\n BINARY_TYPES,\n CLOSE_TIMEOUT,\n EMPTY_BUFFER,\n GUID,\n kForOnEventAttribute,\n kListener,\n kStatusCode,\n kWebSocket,\n NOOP\n} = require('./constants');\nconst {\n EventTarget: { addEventListener, removeEventListener }\n} = require('./event-target');\nconst { format, parse } = require('./extension');\nconst { toBuffer } = require('./buffer-util');\n\nconst kAborted = Symbol('kAborted');\nconst protocolVersions = [8, 13];\nconst readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];\nconst subprotocolRegex = /^[!#$%&'*+\\-.0-9A-Z^_`|a-z~]+$/;\n\n/**\n * Class representing a WebSocket.\n *\n * @extends EventEmitter\n */\nclass WebSocket extends EventEmitter {\n /**\n * Create a new `WebSocket`.\n *\n * @param {(String|URL)} address The URL to which to connect\n * @param {(String|String[])} [protocols] The subprotocols\n * @param {Object} [options] Connection options\n */\n constructor(address, protocols, options) {\n super();\n\n this._binaryType = BINARY_TYPES[0];\n this._closeCode = 1006;\n this._closeFrameReceived = false;\n this._closeFrameSent = false;\n this._closeMessage = EMPTY_BUFFER;\n this._closeTimer = null;\n this._errorEmitted = false;\n this._extensions = {};\n this._paused = false;\n this._protocol = '';\n this._readyState = WebSocket.CONNECTING;\n this._receiver = null;\n this._sender = null;\n this._socket = null;\n\n if (address !== null) {\n this._bufferedAmount = 0;\n this._isServer = false;\n this._redirects = 0;\n\n if (protocols === undefined) {\n protocols = [];\n } else if (!Array.isArray(protocols)) {\n if (typeof protocols === 'object' && protocols !== null) {\n options = protocols;\n protocols = [];\n } else {\n protocols = [protocols];\n }\n }\n\n initAsClient(this, address, protocols, options);\n } else {\n this._autoPong = options.autoPong;\n this._closeTimeout = options.closeTimeout;\n this._isServer = true;\n }\n }\n\n /**\n * For historical reasons, the custom \"nodebuffer\" type is used by the default\n * instead of \"blob\".\n *\n * @type {String}\n */\n get binaryType() {\n return this._binaryType;\n }\n\n set binaryType(type) {\n if (!BINARY_TYPES.includes(type)) return;\n\n this._binaryType = type;\n\n //\n // Allow to change `binaryType` on the fly.\n //\n if (this._receiver) this._receiver._binaryType = type;\n }\n\n /**\n * @type {Number}\n */\n get bufferedAmount() {\n if (!this._socket) return this._bufferedAmount;\n\n return this._socket._writableState.length + this._sender._bufferedBytes;\n }\n\n /**\n * @type {String}\n */\n get extensions() {\n return Object.keys(this._extensions).join();\n }\n\n /**\n * @type {Boolean}\n */\n get isPaused() {\n return this._paused;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onclose() {\n return null;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onerror() {\n return null;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onopen() {\n return null;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onmessage() {\n return null;\n }\n\n /**\n * @type {String}\n */\n get protocol() {\n return this._protocol;\n }\n\n /**\n * @type {Number}\n */\n get readyState() {\n return this._readyState;\n }\n\n /**\n * @type {String}\n */\n get url() {\n return this._url;\n }\n\n /**\n * Set up the socket and the internal resources.\n *\n * @param {Duplex} socket The network socket between the server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Object} options Options object\n * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether\n * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n * multiple times in the same tick\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Number} [options.maxBufferedChunks=0] The maximum number of\n * buffered data chunks\n * @param {Number} [options.maxFragments=0] The maximum number of message\n * fragments\n * @param {Number} [options.maxPayload=0] The maximum allowed message size\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n * @private\n */\n setSocket(socket, head, options) {\n const receiver = new Receiver({\n allowSynchronousEvents: options.allowSynchronousEvents,\n binaryType: this.binaryType,\n extensions: this._extensions,\n isServer: this._isServer,\n maxBufferedChunks: options.maxBufferedChunks,\n maxFragments: options.maxFragments,\n maxPayload: options.maxPayload,\n skipUTF8Validation: options.skipUTF8Validation\n });\n\n const sender = new Sender(socket, this._extensions, options.generateMask);\n\n this._receiver = receiver;\n this._sender = sender;\n this._socket = socket;\n\n receiver[kWebSocket] = this;\n sender[kWebSocket] = this;\n socket[kWebSocket] = this;\n\n receiver.on('conclude', receiverOnConclude);\n receiver.on('drain', receiverOnDrain);\n receiver.on('error', receiverOnError);\n receiver.on('message', receiverOnMessage);\n receiver.on('ping', receiverOnPing);\n receiver.on('pong', receiverOnPong);\n\n sender.onerror = senderOnError;\n\n //\n // These methods may not be available if `socket` is just a `Duplex`.\n //\n if (socket.setTimeout) socket.setTimeout(0);\n if (socket.setNoDelay) socket.setNoDelay();\n\n if (head.length > 0) socket.unshift(head);\n\n socket.on('close', socketOnClose);\n socket.on('data', socketOnData);\n socket.on('end', socketOnEnd);\n socket.on('error', socketOnError);\n\n this._readyState = WebSocket.OPEN;\n this.emit('open');\n }\n\n /**\n * Emit the `'close'` event.\n *\n * @private\n */\n emitClose() {\n if (!this._socket) {\n this._readyState = WebSocket.CLOSED;\n this.emit('close', this._closeCode, this._closeMessage);\n return;\n }\n\n if (this._extensions[PerMessageDeflate.extensionName]) {\n this._extensions[PerMessageDeflate.extensionName].cleanup();\n }\n\n this._receiver.removeAllListeners();\n this._readyState = WebSocket.CLOSED;\n this.emit('close', this._closeCode, this._closeMessage);\n }\n\n /**\n * Start a closing handshake.\n *\n * +----------+ +-----------+ +----------+\n * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -\n * | +----------+ +-----------+ +----------+ |\n * +----------+ +-----------+ |\n * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING\n * +----------+ +-----------+ |\n * | | | +---+ |\n * +------------------------+-->|fin| - - - -\n * | +---+ | +---+\n * - - - - -|fin|<---------------------+\n * +---+\n *\n * @param {Number} [code] Status code explaining why the connection is closing\n * @param {(String|Buffer)} [data] The reason why the connection is\n * closing\n * @public\n */\n close(code, data) {\n if (this.readyState === WebSocket.CLOSED) return;\n if (this.readyState === WebSocket.CONNECTING) {\n const msg = 'WebSocket was closed before the connection was established';\n abortHandshake(this, this._req, msg);\n return;\n }\n\n if (this.readyState === WebSocket.CLOSING) {\n if (\n this._closeFrameSent &&\n (this._closeFrameReceived || this._receiver._writableState.errorEmitted)\n ) {\n this._socket.end();\n }\n\n return;\n }\n\n this._readyState = WebSocket.CLOSING;\n this._sender.close(code, data, !this._isServer, (err) => {\n //\n // This error is handled by the `'error'` listener on the socket. We only\n // want to know if the close frame has been sent here.\n //\n if (err) return;\n\n this._closeFrameSent = true;\n\n if (\n this._closeFrameReceived ||\n this._receiver._writableState.errorEmitted\n ) {\n this._socket.end();\n }\n });\n\n setCloseTimer(this);\n }\n\n /**\n * Pause the socket.\n *\n * @public\n */\n pause() {\n if (\n this.readyState === WebSocket.CONNECTING ||\n this.readyState === WebSocket.CLOSED\n ) {\n return;\n }\n\n this._paused = true;\n this._socket.pause();\n }\n\n /**\n * Send a ping.\n *\n * @param {*} [data] The data to send\n * @param {Boolean} [mask] Indicates whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when the ping is sent\n * @public\n */\n ping(data, mask, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof data === 'function') {\n cb = data;\n data = mask = undefined;\n } else if (typeof mask === 'function') {\n cb = mask;\n mask = undefined;\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n if (mask === undefined) mask = !this._isServer;\n this._sender.ping(data || EMPTY_BUFFER, mask, cb);\n }\n\n /**\n * Send a pong.\n *\n * @param {*} [data] The data to send\n * @param {Boolean} [mask] Indicates whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when the pong is sent\n * @public\n */\n pong(data, mask, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof data === 'function') {\n cb = data;\n data = mask = undefined;\n } else if (typeof mask === 'function') {\n cb = mask;\n mask = undefined;\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n if (mask === undefined) mask = !this._isServer;\n this._sender.pong(data || EMPTY_BUFFER, mask, cb);\n }\n\n /**\n * Resume the socket.\n *\n * @public\n */\n resume() {\n if (\n this.readyState === WebSocket.CONNECTING ||\n this.readyState === WebSocket.CLOSED\n ) {\n return;\n }\n\n this._paused = false;\n if (!this._receiver._writableState.needDrain) this._socket.resume();\n }\n\n /**\n * Send a data message.\n *\n * @param {*} data The message to send\n * @param {Object} [options] Options object\n * @param {Boolean} [options.binary] Specifies whether `data` is binary or\n * text\n * @param {Boolean} [options.compress] Specifies whether or not to compress\n * `data`\n * @param {Boolean} [options.fin=true] Specifies whether the fragment is the\n * last one\n * @param {Boolean} [options.mask] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when data is written out\n * @public\n */\n send(data, options, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof options === 'function') {\n cb = options;\n options = {};\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n const opts = {\n binary: typeof data !== 'string',\n mask: !this._isServer,\n compress: true,\n fin: true,\n ...options\n };\n\n if (!this._extensions[PerMessageDeflate.extensionName]) {\n opts.compress = false;\n }\n\n this._sender.send(data || EMPTY_BUFFER, opts, cb);\n }\n\n /**\n * Forcibly close the connection.\n *\n * @public\n */\n terminate() {\n if (this.readyState === WebSocket.CLOSED) return;\n if (this.readyState === WebSocket.CONNECTING) {\n const msg = 'WebSocket was closed before the connection was established';\n abortHandshake(this, this._req, msg);\n return;\n }\n\n if (this._socket) {\n this._readyState = WebSocket.CLOSING;\n this._socket.destroy();\n }\n }\n}\n\n/**\n * @constant {Number} CONNECTING\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CONNECTING', {\n enumerable: true,\n value: readyStates.indexOf('CONNECTING')\n});\n\n/**\n * @constant {Number} CONNECTING\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CONNECTING', {\n enumerable: true,\n value: readyStates.indexOf('CONNECTING')\n});\n\n/**\n * @constant {Number} OPEN\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'OPEN', {\n enumerable: true,\n value: readyStates.indexOf('OPEN')\n});\n\n/**\n * @constant {Number} OPEN\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'OPEN', {\n enumerable: true,\n value: readyStates.indexOf('OPEN')\n});\n\n/**\n * @constant {Number} CLOSING\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CLOSING', {\n enumerable: true,\n value: readyStates.indexOf('CLOSING')\n});\n\n/**\n * @constant {Number} CLOSING\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CLOSING', {\n enumerable: true,\n value: readyStates.indexOf('CLOSING')\n});\n\n/**\n * @constant {Number} CLOSED\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CLOSED', {\n enumerable: true,\n value: readyStates.indexOf('CLOSED')\n});\n\n/**\n * @constant {Number} CLOSED\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CLOSED', {\n enumerable: true,\n value: readyStates.indexOf('CLOSED')\n});\n\n[\n 'binaryType',\n 'bufferedAmount',\n 'extensions',\n 'isPaused',\n 'protocol',\n 'readyState',\n 'url'\n].forEach((property) => {\n Object.defineProperty(WebSocket.prototype, property, { enumerable: true });\n});\n\n//\n// Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes.\n// See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface\n//\n['open', 'error', 'close', 'message'].forEach((method) => {\n Object.defineProperty(WebSocket.prototype, `on${method}`, {\n enumerable: true,\n get() {\n for (const listener of this.listeners(method)) {\n if (listener[kForOnEventAttribute]) return listener[kListener];\n }\n\n return null;\n },\n set(handler) {\n for (const listener of this.listeners(method)) {\n if (listener[kForOnEventAttribute]) {\n this.removeListener(method, listener);\n break;\n }\n }\n\n if (typeof handler !== 'function') return;\n\n this.addEventListener(method, handler, {\n [kForOnEventAttribute]: true\n });\n }\n });\n});\n\nWebSocket.prototype.addEventListener = addEventListener;\nWebSocket.prototype.removeEventListener = removeEventListener;\n\nmodule.exports = WebSocket;\n\n/**\n * Initialize a WebSocket client.\n *\n * @param {WebSocket} websocket The client to initialize\n * @param {(String|URL)} address The URL to which to connect\n * @param {Array} protocols The subprotocols\n * @param {Object} [options] Connection options\n * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether any\n * of the `'message'`, `'ping'`, and `'pong'` events can be emitted multiple\n * times in the same tick\n * @param {Boolean} [options.autoPong=true] Specifies whether or not to\n * automatically send a pong in response to a ping\n * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to wait\n * for the closing handshake to finish after `websocket.close()` is called\n * @param {Function} [options.finishRequest] A function which can be used to\n * customize the headers of each http request before it is sent\n * @param {Boolean} [options.followRedirects=false] Whether or not to follow\n * redirects\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the\n * handshake request\n * @param {Number} [options.maxBufferedChunks=262144] The maximum number of\n * buffered data chunks\n * @param {Number} [options.maxFragments=16384] The maximum number of message\n * fragments\n * @param {Number} [options.maxPayload=104857600] The maximum allowed message\n * size\n * @param {Number} [options.maxRedirects=10] The maximum number of redirects\n * allowed\n * @param {String} [options.origin] Value of the `Origin` or\n * `Sec-WebSocket-Origin` header\n * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable\n * permessage-deflate\n * @param {Number} [options.protocolVersion=13] Value of the\n * `Sec-WebSocket-Version` header\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n * @private\n */\nfunction initAsClient(websocket, address, protocols, options) {\n const opts = {\n allowSynchronousEvents: true,\n autoPong: true,\n closeTimeout: CLOSE_TIMEOUT,\n protocolVersion: protocolVersions[1],\n maxBufferedChunks: 256 * 1024,\n maxFragments: 16 * 1024,\n maxPayload: 100 * 1024 * 1024,\n skipUTF8Validation: false,\n perMessageDeflate: true,\n followRedirects: false,\n maxRedirects: 10,\n ...options,\n socketPath: undefined,\n hostname: undefined,\n protocol: undefined,\n timeout: undefined,\n method: 'GET',\n host: undefined,\n path: undefined,\n port: undefined\n };\n\n websocket._autoPong = opts.autoPong;\n websocket._closeTimeout = opts.closeTimeout;\n\n if (!protocolVersions.includes(opts.protocolVersion)) {\n throw new RangeError(\n `Unsupported protocol version: ${opts.protocolVersion} ` +\n `(supported versions: ${protocolVersions.join(', ')})`\n );\n }\n\n let parsedUrl;\n\n if (address instanceof URL) {\n parsedUrl = address;\n } else {\n try {\n parsedUrl = new URL(address);\n } catch {\n throw new SyntaxError(`Invalid URL: ${address}`);\n }\n }\n\n if (parsedUrl.protocol === 'http:') {\n parsedUrl.protocol = 'ws:';\n } else if (parsedUrl.protocol === 'https:') {\n parsedUrl.protocol = 'wss:';\n }\n\n websocket._url = parsedUrl.href;\n\n const isSecure = parsedUrl.protocol === 'wss:';\n const isIpcUrl = parsedUrl.protocol === 'ws+unix:';\n let invalidUrlMessage;\n\n if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) {\n invalidUrlMessage =\n 'The URL\\'s protocol must be one of \"ws:\", \"wss:\", ' +\n '\"http:\", \"https:\", or \"ws+unix:\"';\n } else if (isIpcUrl && !parsedUrl.pathname) {\n invalidUrlMessage = \"The URL's pathname is empty\";\n } else if (parsedUrl.hash) {\n invalidUrlMessage = 'The URL contains a fragment identifier';\n }\n\n if (invalidUrlMessage) {\n const err = new SyntaxError(invalidUrlMessage);\n\n if (websocket._redirects === 0) {\n throw err;\n } else {\n emitErrorAndClose(websocket, err);\n return;\n }\n }\n\n const defaultPort = isSecure ? 443 : 80;\n const key = randomBytes(16).toString('base64');\n const request = isSecure ? https.request : http.request;\n const protocolSet = new Set();\n let perMessageDeflate;\n\n opts.createConnection =\n opts.createConnection || (isSecure ? tlsConnect : netConnect);\n opts.defaultPort = opts.defaultPort || defaultPort;\n opts.port = parsedUrl.port || defaultPort;\n opts.host = parsedUrl.hostname.startsWith('[')\n ? parsedUrl.hostname.slice(1, -1)\n : parsedUrl.hostname;\n opts.headers = {\n ...opts.headers,\n 'Sec-WebSocket-Version': opts.protocolVersion,\n 'Sec-WebSocket-Key': key,\n Connection: 'Upgrade',\n Upgrade: 'websocket'\n };\n opts.path = parsedUrl.pathname + parsedUrl.search;\n opts.timeout = opts.handshakeTimeout;\n\n if (opts.perMessageDeflate) {\n perMessageDeflate = new PerMessageDeflate({\n ...opts.perMessageDeflate,\n isServer: false,\n maxPayload: opts.maxPayload\n });\n opts.headers['Sec-WebSocket-Extensions'] = format({\n [PerMessageDeflate.extensionName]: perMessageDeflate.offer()\n });\n }\n if (protocols.length) {\n for (const protocol of protocols) {\n if (\n typeof protocol !== 'string' ||\n !subprotocolRegex.test(protocol) ||\n protocolSet.has(protocol)\n ) {\n throw new SyntaxError(\n 'An invalid or duplicated subprotocol was specified'\n );\n }\n\n protocolSet.add(protocol);\n }\n\n opts.headers['Sec-WebSocket-Protocol'] = protocols.join(',');\n }\n if (opts.origin) {\n if (opts.protocolVersion < 13) {\n opts.headers['Sec-WebSocket-Origin'] = opts.origin;\n } else {\n opts.headers.Origin = opts.origin;\n }\n }\n if (parsedUrl.username || parsedUrl.password) {\n opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;\n }\n\n if (isIpcUrl) {\n const parts = opts.path.split(':');\n\n opts.socketPath = parts[0];\n opts.path = parts[1];\n }\n\n let req;\n\n if (opts.followRedirects) {\n if (websocket._redirects === 0) {\n websocket._originalIpc = isIpcUrl;\n websocket._originalSecure = isSecure;\n websocket._originalHostOrSocketPath = isIpcUrl\n ? opts.socketPath\n : parsedUrl.host;\n\n const headers = options && options.headers;\n\n //\n // Shallow copy the user provided options so that headers can be changed\n // without mutating the original object.\n //\n options = { ...options, headers: {} };\n\n if (headers) {\n for (const [key, value] of Object.entries(headers)) {\n options.headers[key.toLowerCase()] = value;\n }\n }\n } else if (websocket.listenerCount('redirect') === 0) {\n const isSameHost = isIpcUrl\n ? websocket._originalIpc\n ? opts.socketPath === websocket._originalHostOrSocketPath\n : false\n : websocket._originalIpc\n ? false\n : parsedUrl.host === websocket._originalHostOrSocketPath;\n\n if (!isSameHost || (websocket._originalSecure && !isSecure)) {\n //\n // Match curl 7.77.0 behavior and drop the following headers. These\n // headers are also dropped when following a redirect to a subdomain.\n //\n delete opts.headers.authorization;\n delete opts.headers.cookie;\n\n if (!isSameHost) delete opts.headers.host;\n\n opts.auth = undefined;\n }\n }\n\n //\n // Match curl 7.77.0 behavior and make the first `Authorization` header win.\n // If the `Authorization` header is set, then there is nothing to do as it\n // will take precedence.\n //\n if (opts.auth && !options.headers.authorization) {\n options.headers.authorization =\n 'Basic ' + Buffer.from(opts.auth).toString('base64');\n }\n\n req = websocket._req = request(opts);\n\n if (websocket._redirects) {\n //\n // Unlike what is done for the `'upgrade'` event, no early exit is\n // triggered here if the user calls `websocket.close()` or\n // `websocket.terminate()` from a listener of the `'redirect'` event. This\n // is because the user can also call `request.destroy()` with an error\n // before calling `websocket.close()` or `websocket.terminate()` and this\n // would result in an error being emitted on the `request` object with no\n // `'error'` event listeners attached.\n //\n websocket.emit('redirect', websocket.url, req);\n }\n } else {\n req = websocket._req = request(opts);\n }\n\n if (opts.timeout) {\n req.on('timeout', () => {\n abortHandshake(websocket, req, 'Opening handshake has timed out');\n });\n }\n\n req.on('error', (err) => {\n if (req === null || req[kAborted]) return;\n\n req = websocket._req = null;\n emitErrorAndClose(websocket, err);\n });\n\n req.on('response', (res) => {\n const location = res.headers.location;\n const statusCode = res.statusCode;\n\n if (\n location &&\n opts.followRedirects &&\n statusCode >= 300 &&\n statusCode < 400\n ) {\n if (++websocket._redirects > opts.maxRedirects) {\n abortHandshake(websocket, req, 'Maximum redirects exceeded');\n return;\n }\n\n req.abort();\n\n let addr;\n\n try {\n addr = new URL(location, address);\n } catch (e) {\n const err = new SyntaxError(`Invalid URL: ${location}`);\n emitErrorAndClose(websocket, err);\n return;\n }\n\n initAsClient(websocket, addr, protocols, options);\n } else if (!websocket.emit('unexpected-response', req, res)) {\n abortHandshake(\n websocket,\n req,\n `Unexpected server response: ${res.statusCode}`\n );\n }\n });\n\n req.on('upgrade', (res, socket, head) => {\n websocket.emit('upgrade', res);\n\n //\n // The user may have closed the connection from a listener of the\n // `'upgrade'` event.\n //\n if (websocket.readyState !== WebSocket.CONNECTING) return;\n\n req = websocket._req = null;\n\n const upgrade = res.headers.upgrade;\n\n if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {\n abortHandshake(websocket, socket, 'Invalid Upgrade header');\n return;\n }\n\n const digest = createHash('sha1')\n .update(key + GUID)\n .digest('base64');\n\n if (res.headers['sec-websocket-accept'] !== digest) {\n abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header');\n return;\n }\n\n const serverProt = res.headers['sec-websocket-protocol'];\n let protError;\n\n if (serverProt !== undefined) {\n if (!protocolSet.size) {\n protError = 'Server sent a subprotocol but none was requested';\n } else if (!protocolSet.has(serverProt)) {\n protError = 'Server sent an invalid subprotocol';\n }\n } else if (protocolSet.size) {\n protError = 'Server sent no subprotocol';\n }\n\n if (protError) {\n abortHandshake(websocket, socket, protError);\n return;\n }\n\n if (serverProt) websocket._protocol = serverProt;\n\n const secWebSocketExtensions = res.headers['sec-websocket-extensions'];\n\n if (secWebSocketExtensions !== undefined) {\n if (!perMessageDeflate) {\n const message =\n 'Server sent a Sec-WebSocket-Extensions header but no extension ' +\n 'was requested';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n let extensions;\n\n try {\n extensions = parse(secWebSocketExtensions);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Extensions header';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n const extensionNames = Object.keys(extensions);\n\n if (\n extensionNames.length !== 1 ||\n extensionNames[0] !== PerMessageDeflate.extensionName\n ) {\n const message = 'Server indicated an extension that was not requested';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n try {\n perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Extensions header';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n websocket._extensions[PerMessageDeflate.extensionName] =\n perMessageDeflate;\n }\n\n websocket.setSocket(socket, head, {\n allowSynchronousEvents: opts.allowSynchronousEvents,\n generateMask: opts.generateMask,\n maxBufferedChunks: opts.maxBufferedChunks,\n maxFragments: opts.maxFragments,\n maxPayload: opts.maxPayload,\n skipUTF8Validation: opts.skipUTF8Validation\n });\n });\n\n if (opts.finishRequest) {\n opts.finishRequest(req, websocket);\n } else {\n req.end();\n }\n}\n\n/**\n * Emit the `'error'` and `'close'` events.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {Error} The error to emit\n * @private\n */\nfunction emitErrorAndClose(websocket, err) {\n websocket._readyState = WebSocket.CLOSING;\n //\n // The following assignment is practically useless and is done only for\n // consistency.\n //\n websocket._errorEmitted = true;\n websocket.emit('error', err);\n websocket.emitClose();\n}\n\n/**\n * Create a `net.Socket` and initiate a connection.\n *\n * @param {Object} options Connection options\n * @return {net.Socket} The newly created socket used to start the connection\n * @private\n */\nfunction netConnect(options) {\n options.path = options.socketPath;\n return net.connect(options);\n}\n\n/**\n * Create a `tls.TLSSocket` and initiate a connection.\n *\n * @param {Object} options Connection options\n * @return {tls.TLSSocket} The newly created socket used to start the connection\n * @private\n */\nfunction tlsConnect(options) {\n options.path = undefined;\n\n if (!options.servername && options.servername !== '') {\n options.servername = net.isIP(options.host) ? '' : options.host;\n }\n\n return tls.connect(options);\n}\n\n/**\n * Abort the handshake and emit an error.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to\n * abort or the socket to destroy\n * @param {String} message The error message\n * @private\n */\nfunction abortHandshake(websocket, stream, message) {\n websocket._readyState = WebSocket.CLOSING;\n\n const err = new Error(message);\n Error.captureStackTrace(err, abortHandshake);\n\n if (stream.setHeader) {\n stream[kAborted] = true;\n stream.abort();\n\n if (stream.socket && !stream.socket.destroyed) {\n //\n // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if\n // called after the request completed. See\n // https://github.com/websockets/ws/issues/1869.\n //\n stream.socket.destroy();\n }\n\n process.nextTick(emitErrorAndClose, websocket, err);\n } else {\n stream.destroy(err);\n stream.once('error', websocket.emit.bind(websocket, 'error'));\n stream.once('close', websocket.emitClose.bind(websocket));\n }\n}\n\n/**\n * Handle cases where the `ping()`, `pong()`, or `send()` methods are called\n * when the `readyState` attribute is `CLOSING` or `CLOSED`.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {*} [data] The data to send\n * @param {Function} [cb] Callback\n * @private\n */\nfunction sendAfterClose(websocket, data, cb) {\n if (data) {\n const length = isBlob(data) ? data.size : toBuffer(data).length;\n\n //\n // The `_bufferedAmount` property is used only when the peer is a client and\n // the opening handshake fails. Under these circumstances, in fact, the\n // `setSocket()` method is not called, so the `_socket` and `_sender`\n // properties are set to `null`.\n //\n if (websocket._socket) websocket._sender._bufferedBytes += length;\n else websocket._bufferedAmount += length;\n }\n\n if (cb) {\n const err = new Error(\n `WebSocket is not open: readyState ${websocket.readyState} ` +\n `(${readyStates[websocket.readyState]})`\n );\n process.nextTick(cb, err);\n }\n}\n\n/**\n * The listener of the `Receiver` `'conclude'` event.\n *\n * @param {Number} code The status code\n * @param {Buffer} reason The reason for closing\n * @private\n */\nfunction receiverOnConclude(code, reason) {\n const websocket = this[kWebSocket];\n\n websocket._closeFrameReceived = true;\n websocket._closeMessage = reason;\n websocket._closeCode = code;\n\n if (websocket._socket[kWebSocket] === undefined) return;\n\n websocket._socket.removeListener('data', socketOnData);\n process.nextTick(resume, websocket._socket);\n\n if (code === 1005) websocket.close();\n else websocket.close(code, reason);\n}\n\n/**\n * The listener of the `Receiver` `'drain'` event.\n *\n * @private\n */\nfunction receiverOnDrain() {\n const websocket = this[kWebSocket];\n\n if (!websocket.isPaused) websocket._socket.resume();\n}\n\n/**\n * The listener of the `Receiver` `'error'` event.\n *\n * @param {(RangeError|Error)} err The emitted error\n * @private\n */\nfunction receiverOnError(err) {\n const websocket = this[kWebSocket];\n\n if (websocket._socket[kWebSocket] !== undefined) {\n websocket._socket.removeListener('data', socketOnData);\n\n //\n // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See\n // https://github.com/websockets/ws/issues/1940.\n //\n process.nextTick(resume, websocket._socket);\n\n websocket.close(err[kStatusCode]);\n }\n\n if (!websocket._errorEmitted) {\n websocket._errorEmitted = true;\n websocket.emit('error', err);\n }\n}\n\n/**\n * The listener of the `Receiver` `'finish'` event.\n *\n * @private\n */\nfunction receiverOnFinish() {\n this[kWebSocket].emitClose();\n}\n\n/**\n * The listener of the `Receiver` `'message'` event.\n *\n * @param {Buffer|ArrayBuffer|Buffer[])} data The message\n * @param {Boolean} isBinary Specifies whether the message is binary or not\n * @private\n */\nfunction receiverOnMessage(data, isBinary) {\n this[kWebSocket].emit('message', data, isBinary);\n}\n\n/**\n * The listener of the `Receiver` `'ping'` event.\n *\n * @param {Buffer} data The data included in the ping frame\n * @private\n */\nfunction receiverOnPing(data) {\n const websocket = this[kWebSocket];\n\n if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);\n websocket.emit('ping', data);\n}\n\n/**\n * The listener of the `Receiver` `'pong'` event.\n *\n * @param {Buffer} data The data included in the pong frame\n * @private\n */\nfunction receiverOnPong(data) {\n this[kWebSocket].emit('pong', data);\n}\n\n/**\n * Resume a readable stream\n *\n * @param {Readable} stream The readable stream\n * @private\n */\nfunction resume(stream) {\n stream.resume();\n}\n\n/**\n * The `Sender` error event handler.\n *\n * @param {Error} The error\n * @private\n */\nfunction senderOnError(err) {\n const websocket = this[kWebSocket];\n\n if (websocket.readyState === WebSocket.CLOSED) return;\n if (websocket.readyState === WebSocket.OPEN) {\n websocket._readyState = WebSocket.CLOSING;\n setCloseTimer(websocket);\n }\n\n //\n // `socket.end()` is used instead of `socket.destroy()` to allow the other\n // peer to finish sending queued data. There is no need to set a timer here\n // because `CLOSING` means that it is already set or not needed.\n //\n this._socket.end();\n\n if (!websocket._errorEmitted) {\n websocket._errorEmitted = true;\n websocket.emit('error', err);\n }\n}\n\n/**\n * Set a timer to destroy the underlying raw socket of a WebSocket.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @private\n */\nfunction setCloseTimer(websocket) {\n websocket._closeTimer = setTimeout(\n websocket._socket.destroy.bind(websocket._socket),\n websocket._closeTimeout\n );\n}\n\n/**\n * The listener of the socket `'close'` event.\n *\n * @private\n */\nfunction socketOnClose() {\n const websocket = this[kWebSocket];\n\n this.removeListener('close', socketOnClose);\n this.removeListener('data', socketOnData);\n this.removeListener('end', socketOnEnd);\n\n websocket._readyState = WebSocket.CLOSING;\n\n //\n // The close frame might not have been received or the `'end'` event emitted,\n // for example, if the socket was destroyed due to an error. Ensure that the\n // `receiver` stream is closed after writing any remaining buffered data to\n // it. If the readable side of the socket is in flowing mode then there is no\n // buffered data as everything has been already written. If instead, the\n // socket is paused, any possible buffered data will be read as a single\n // chunk.\n //\n if (\n !this._readableState.endEmitted &&\n !websocket._closeFrameReceived &&\n !websocket._receiver._writableState.errorEmitted &&\n this._readableState.length !== 0\n ) {\n const chunk = this.read(this._readableState.length);\n\n websocket._receiver.write(chunk);\n }\n\n websocket._receiver.end();\n\n this[kWebSocket] = undefined;\n\n clearTimeout(websocket._closeTimer);\n\n if (\n websocket._receiver._writableState.finished ||\n websocket._receiver._writableState.errorEmitted\n ) {\n websocket.emitClose();\n } else {\n websocket._receiver.on('error', receiverOnFinish);\n websocket._receiver.on('finish', receiverOnFinish);\n }\n}\n\n/**\n * The listener of the socket `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction socketOnData(chunk) {\n if (!this[kWebSocket]._receiver.write(chunk)) {\n this.pause();\n }\n}\n\n/**\n * The listener of the socket `'end'` event.\n *\n * @private\n */\nfunction socketOnEnd() {\n const websocket = this[kWebSocket];\n\n websocket._readyState = WebSocket.CLOSING;\n websocket._receiver.end();\n this.end();\n}\n\n/**\n * The listener of the socket `'error'` event.\n *\n * @private\n */\nfunction socketOnError() {\n const websocket = this[kWebSocket];\n\n this.removeListener('error', socketOnError);\n this.on('error', NOOP);\n\n if (websocket) {\n websocket._readyState = WebSocket.CLOSING;\n this.destroy();\n }\n}\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^WebSocket$\" }] */\n'use strict';\n\nconst WebSocket = require('./websocket');\nconst { Duplex } = require('stream');\n\n/**\n * Emits the `'close'` event on a stream.\n *\n * @param {Duplex} stream The stream.\n * @private\n */\nfunction emitClose(stream) {\n stream.emit('close');\n}\n\n/**\n * The listener of the `'end'` event.\n *\n * @private\n */\nfunction duplexOnEnd() {\n if (!this.destroyed && this._writableState.finished) {\n this.destroy();\n }\n}\n\n/**\n * The listener of the `'error'` event.\n *\n * @param {Error} err The error\n * @private\n */\nfunction duplexOnError(err) {\n this.removeListener('error', duplexOnError);\n this.destroy();\n if (this.listenerCount('error') === 0) {\n // Do not suppress the throwing behavior.\n this.emit('error', err);\n }\n}\n\n/**\n * Wraps a `WebSocket` in a duplex stream.\n *\n * @param {WebSocket} ws The `WebSocket` to wrap\n * @param {Object} [options] The options for the `Duplex` constructor\n * @return {Duplex} The duplex stream\n * @public\n */\nfunction createWebSocketStream(ws, options) {\n let terminateOnDestroy = true;\n\n const duplex = new Duplex({\n ...options,\n autoDestroy: false,\n emitClose: false,\n objectMode: false,\n writableObjectMode: false\n });\n\n ws.on('message', function message(msg, isBinary) {\n const data =\n !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;\n\n if (!duplex.push(data)) ws.pause();\n });\n\n ws.once('error', function error(err) {\n if (duplex.destroyed) return;\n\n // Prevent `ws.terminate()` from being called by `duplex._destroy()`.\n //\n // - If the `'error'` event is emitted before the `'open'` event, then\n // `ws.terminate()` is a noop as no socket is assigned.\n // - Otherwise, the error is re-emitted by the listener of the `'error'`\n // event of the `Receiver` object. The listener already closes the\n // connection by calling `ws.close()`. This allows a close frame to be\n // sent to the other peer. If `ws.terminate()` is called right after this,\n // then the close frame might not be sent.\n terminateOnDestroy = false;\n duplex.destroy(err);\n });\n\n ws.once('close', function close() {\n if (duplex.destroyed) return;\n\n duplex.push(null);\n });\n\n duplex._destroy = function (err, callback) {\n if (ws.readyState === ws.CLOSED) {\n callback(err);\n process.nextTick(emitClose, duplex);\n return;\n }\n\n let called = false;\n\n ws.once('error', function error(err) {\n called = true;\n callback(err);\n });\n\n ws.once('close', function close() {\n if (!called) callback(err);\n process.nextTick(emitClose, duplex);\n });\n\n if (terminateOnDestroy) ws.terminate();\n };\n\n duplex._final = function (callback) {\n if (ws.readyState === ws.CONNECTING) {\n ws.once('open', function open() {\n duplex._final(callback);\n });\n return;\n }\n\n // If the value of the `_socket` property is `null` it means that `ws` is a\n // client websocket and the handshake failed. In fact, when this happens, a\n // socket is never assigned to the websocket. Wait for the `'error'` event\n // that will be emitted by the websocket.\n if (ws._socket === null) return;\n\n if (ws._socket._writableState.finished) {\n callback();\n if (duplex._readableState.endEmitted) duplex.destroy();\n } else {\n ws._socket.once('finish', function finish() {\n // `duplex` is not destroyed here because the `'end'` event will be\n // emitted on `duplex` after this `'finish'` event. The EOF signaling\n // `null` chunk is, in fact, pushed when the websocket emits `'close'`.\n callback();\n });\n ws.close();\n }\n };\n\n duplex._read = function () {\n if (ws.isPaused) ws.resume();\n };\n\n duplex._write = function (chunk, encoding, callback) {\n if (ws.readyState === ws.CONNECTING) {\n ws.once('open', function open() {\n duplex._write(chunk, encoding, callback);\n });\n return;\n }\n\n ws.send(chunk, callback);\n };\n\n duplex.on('end', duplexOnEnd);\n duplex.on('error', duplexOnError);\n return duplex;\n}\n\nmodule.exports = createWebSocketStream;\n","'use strict';\n\nconst { tokenChars } = require('./validation');\n\n/**\n * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names.\n *\n * @param {String} header The field value of the header\n * @return {Set} The subprotocol names\n * @public\n */\nfunction parse(header) {\n const protocols = new Set();\n let start = -1;\n let end = -1;\n let i = 0;\n\n for (i; i < header.length; i++) {\n const code = header.charCodeAt(i);\n\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (\n i !== 0 &&\n (code === 0x20 /* ' ' */ || code === 0x09) /* '\\t' */\n ) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x2c /* ',' */) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n\n const protocol = header.slice(start, end);\n\n if (protocols.has(protocol)) {\n throw new SyntaxError(`The \"${protocol}\" subprotocol is duplicated`);\n }\n\n protocols.add(protocol);\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n }\n\n if (start === -1 || end !== -1) {\n throw new SyntaxError('Unexpected end of input');\n }\n\n const protocol = header.slice(start, i);\n\n if (protocols.has(protocol)) {\n throw new SyntaxError(`The \"${protocol}\" subprotocol is duplicated`);\n }\n\n protocols.add(protocol);\n return protocols;\n}\n\nmodule.exports = { parse };\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex$\", \"caughtErrors\": \"none\" }] */\n\n'use strict';\n\nconst EventEmitter = require('events');\nconst http = require('http');\nconst { Duplex } = require('stream');\nconst { createHash } = require('crypto');\n\nconst extension = require('./extension');\nconst PerMessageDeflate = require('./permessage-deflate');\nconst subprotocol = require('./subprotocol');\nconst WebSocket = require('./websocket');\nconst { CLOSE_TIMEOUT, GUID, kWebSocket } = require('./constants');\n\nconst keyRegex = /^[+/0-9A-Za-z]{22}==$/;\n\nconst RUNNING = 0;\nconst CLOSING = 1;\nconst CLOSED = 2;\n\n/**\n * Class representing a WebSocket server.\n *\n * @extends EventEmitter\n */\nclass WebSocketServer extends EventEmitter {\n /**\n * Create a `WebSocketServer` instance.\n *\n * @param {Object} options Configuration options\n * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether\n * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n * multiple times in the same tick\n * @param {Boolean} [options.autoPong=true] Specifies whether or not to\n * automatically send a pong in response to a ping\n * @param {Number} [options.backlog=511] The maximum length of the queue of\n * pending connections\n * @param {Boolean} [options.clientTracking=true] Specifies whether or not to\n * track clients\n * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to\n * wait for the closing handshake to finish after `websocket.close()` is\n * called\n * @param {Function} [options.handleProtocols] A hook to handle protocols\n * @param {String} [options.host] The hostname where to bind the server\n * @param {Number} [options.maxBufferedChunks=262144] The maximum number of\n * buffered data chunks\n * @param {Number} [options.maxFragments=16384] The maximum number of message\n * fragments\n * @param {Number} [options.maxPayload=104857600] The maximum allowed message\n * size\n * @param {Boolean} [options.noServer=false] Enable no server mode\n * @param {String} [options.path] Accept only connections matching this path\n * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable\n * permessage-deflate\n * @param {Number} [options.port] The port where to bind the server\n * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S\n * server to use\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n * @param {Function} [options.verifyClient] A hook to reject connections\n * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`\n * class to use. It must be the `WebSocket` class or class that extends it\n * @param {Function} [callback] A listener for the `listening` event\n */\n constructor(options, callback) {\n super();\n\n options = {\n allowSynchronousEvents: true,\n autoPong: true,\n maxBufferedChunks: 256 * 1024,\n maxFragments: 16 * 1024,\n maxPayload: 100 * 1024 * 1024,\n skipUTF8Validation: false,\n perMessageDeflate: false,\n handleProtocols: null,\n clientTracking: true,\n closeTimeout: CLOSE_TIMEOUT,\n verifyClient: null,\n noServer: false,\n backlog: null, // use default (511 as implemented in net.js)\n server: null,\n host: null,\n path: null,\n port: null,\n WebSocket,\n ...options\n };\n\n if (\n (options.port == null && !options.server && !options.noServer) ||\n (options.port != null && (options.server || options.noServer)) ||\n (options.server && options.noServer)\n ) {\n throw new TypeError(\n 'One and only one of the \"port\", \"server\", or \"noServer\" options ' +\n 'must be specified'\n );\n }\n\n if (options.port != null) {\n this._server = http.createServer((req, res) => {\n const body = http.STATUS_CODES[426];\n\n res.writeHead(426, {\n 'Content-Length': body.length,\n 'Content-Type': 'text/plain'\n });\n res.end(body);\n });\n this._server.listen(\n options.port,\n options.host,\n options.backlog,\n callback\n );\n } else if (options.server) {\n this._server = options.server;\n }\n\n if (this._server) {\n const emitConnection = this.emit.bind(this, 'connection');\n\n this._removeListeners = addListeners(this._server, {\n listening: this.emit.bind(this, 'listening'),\n error: this.emit.bind(this, 'error'),\n upgrade: (req, socket, head) => {\n this.handleUpgrade(req, socket, head, emitConnection);\n }\n });\n }\n\n if (options.perMessageDeflate === true) options.perMessageDeflate = {};\n if (options.clientTracking) {\n this.clients = new Set();\n this._shouldEmitClose = false;\n }\n\n this.options = options;\n this._state = RUNNING;\n }\n\n /**\n * Returns the bound address, the address family name, and port of the server\n * as reported by the operating system if listening on an IP socket.\n * If the server is listening on a pipe or UNIX domain socket, the name is\n * returned as a string.\n *\n * @return {(Object|String|null)} The address of the server\n * @public\n */\n address() {\n if (this.options.noServer) {\n throw new Error('The server is operating in \"noServer\" mode');\n }\n\n if (!this._server) return null;\n return this._server.address();\n }\n\n /**\n * Stop the server from accepting new connections and emit the `'close'` event\n * when all existing connections are closed.\n *\n * @param {Function} [cb] A one-time listener for the `'close'` event\n * @public\n */\n close(cb) {\n if (this._state === CLOSED) {\n if (cb) {\n this.once('close', () => {\n cb(new Error('The server is not running'));\n });\n }\n\n process.nextTick(emitClose, this);\n return;\n }\n\n if (cb) this.once('close', cb);\n\n if (this._state === CLOSING) return;\n this._state = CLOSING;\n\n if (this.options.noServer || this.options.server) {\n if (this._server) {\n this._removeListeners();\n this._removeListeners = this._server = null;\n }\n\n if (this.clients) {\n if (!this.clients.size) {\n process.nextTick(emitClose, this);\n } else {\n this._shouldEmitClose = true;\n }\n } else {\n process.nextTick(emitClose, this);\n }\n } else {\n const server = this._server;\n\n this._removeListeners();\n this._removeListeners = this._server = null;\n\n //\n // The HTTP/S server was created internally. Close it, and rely on its\n // `'close'` event.\n //\n server.close(() => {\n emitClose(this);\n });\n }\n }\n\n /**\n * See if a given request should be handled by this server instance.\n *\n * @param {http.IncomingMessage} req Request object to inspect\n * @return {Boolean} `true` if the request is valid, else `false`\n * @public\n */\n shouldHandle(req) {\n if (this.options.path) {\n const index = req.url.indexOf('?');\n const pathname = index !== -1 ? req.url.slice(0, index) : req.url;\n\n if (pathname !== this.options.path) return false;\n }\n\n return true;\n }\n\n /**\n * Handle a HTTP Upgrade request.\n *\n * @param {http.IncomingMessage} req The request object\n * @param {Duplex} socket The network socket between the server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Function} cb Callback\n * @public\n */\n handleUpgrade(req, socket, head, cb) {\n socket.on('error', socketOnError);\n\n const key = req.headers['sec-websocket-key'];\n const upgrade = req.headers.upgrade;\n const version = +req.headers['sec-websocket-version'];\n\n if (req.method !== 'GET') {\n const message = 'Invalid HTTP method';\n abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);\n return;\n }\n\n if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {\n const message = 'Invalid Upgrade header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n\n if (key === undefined || !keyRegex.test(key)) {\n const message = 'Missing or invalid Sec-WebSocket-Key header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n\n if (version !== 13 && version !== 8) {\n const message = 'Missing or invalid Sec-WebSocket-Version header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {\n 'Sec-WebSocket-Version': '13, 8'\n });\n return;\n }\n\n if (!this.shouldHandle(req)) {\n abortHandshake(socket, 400);\n return;\n }\n\n const secWebSocketProtocol = req.headers['sec-websocket-protocol'];\n let protocols = new Set();\n\n if (secWebSocketProtocol !== undefined) {\n try {\n protocols = subprotocol.parse(secWebSocketProtocol);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Protocol header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n }\n\n const secWebSocketExtensions = req.headers['sec-websocket-extensions'];\n const extensions = {};\n\n if (\n this.options.perMessageDeflate &&\n secWebSocketExtensions !== undefined\n ) {\n const perMessageDeflate = new PerMessageDeflate({\n ...this.options.perMessageDeflate,\n isServer: true,\n maxPayload: this.options.maxPayload\n });\n\n try {\n const offers = extension.parse(secWebSocketExtensions);\n\n if (offers[PerMessageDeflate.extensionName]) {\n perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);\n extensions[PerMessageDeflate.extensionName] = perMessageDeflate;\n }\n } catch (err) {\n const message =\n 'Invalid or unacceptable Sec-WebSocket-Extensions header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n }\n\n //\n // Optionally call external client verification handler.\n //\n if (this.options.verifyClient) {\n const info = {\n origin:\n req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],\n secure: !!(req.socket.authorized || req.socket.encrypted),\n req\n };\n\n if (this.options.verifyClient.length === 2) {\n this.options.verifyClient(info, (verified, code, message, headers) => {\n if (!verified) {\n return abortHandshake(socket, code || 401, message, headers);\n }\n\n this.completeUpgrade(\n extensions,\n key,\n protocols,\n req,\n socket,\n head,\n cb\n );\n });\n return;\n }\n\n if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);\n }\n\n this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);\n }\n\n /**\n * Upgrade the connection to WebSocket.\n *\n * @param {Object} extensions The accepted extensions\n * @param {String} key The value of the `Sec-WebSocket-Key` header\n * @param {Set} protocols The subprotocols\n * @param {http.IncomingMessage} req The request object\n * @param {Duplex} socket The network socket between the server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Function} cb Callback\n * @throws {Error} If called more than once with the same socket\n * @private\n */\n completeUpgrade(extensions, key, protocols, req, socket, head, cb) {\n //\n // Destroy the socket if the client has already sent a FIN packet.\n //\n if (!socket.readable || !socket.writable) return socket.destroy();\n\n if (socket[kWebSocket]) {\n throw new Error(\n 'server.handleUpgrade() was called more than once with the same ' +\n 'socket, possibly due to a misconfiguration'\n );\n }\n\n if (this._state > RUNNING) return abortHandshake(socket, 503);\n\n const digest = createHash('sha1')\n .update(key + GUID)\n .digest('base64');\n\n const headers = [\n 'HTTP/1.1 101 Switching Protocols',\n 'Upgrade: websocket',\n 'Connection: Upgrade',\n `Sec-WebSocket-Accept: ${digest}`\n ];\n\n const ws = new this.options.WebSocket(null, undefined, this.options);\n\n if (protocols.size) {\n //\n // Optionally call external protocol selection handler.\n //\n const protocol = this.options.handleProtocols\n ? this.options.handleProtocols(protocols, req)\n : protocols.values().next().value;\n\n if (protocol) {\n headers.push(`Sec-WebSocket-Protocol: ${protocol}`);\n ws._protocol = protocol;\n }\n }\n\n if (extensions[PerMessageDeflate.extensionName]) {\n const params = extensions[PerMessageDeflate.extensionName].params;\n const value = extension.format({\n [PerMessageDeflate.extensionName]: [params]\n });\n headers.push(`Sec-WebSocket-Extensions: ${value}`);\n ws._extensions = extensions;\n }\n\n //\n // Allow external modification/inspection of handshake headers.\n //\n this.emit('headers', headers, req);\n\n socket.write(headers.concat('\\r\\n').join('\\r\\n'));\n socket.removeListener('error', socketOnError);\n\n ws.setSocket(socket, head, {\n allowSynchronousEvents: this.options.allowSynchronousEvents,\n maxBufferedChunks: this.options.maxBufferedChunks,\n maxFragments: this.options.maxFragments,\n maxPayload: this.options.maxPayload,\n skipUTF8Validation: this.options.skipUTF8Validation\n });\n\n if (this.clients) {\n this.clients.add(ws);\n ws.on('close', () => {\n this.clients.delete(ws);\n\n if (this._shouldEmitClose && !this.clients.size) {\n process.nextTick(emitClose, this);\n }\n });\n }\n\n cb(ws, req);\n }\n}\n\nmodule.exports = WebSocketServer;\n\n/**\n * Add event listeners on an `EventEmitter` using a map of <event, listener>\n * pairs.\n *\n * @param {EventEmitter} server The event emitter\n * @param {Object.<String, Function>} map The listeners to add\n * @return {Function} A function that will remove the added listeners when\n * called\n * @private\n */\nfunction addListeners(server, map) {\n for (const event of Object.keys(map)) server.on(event, map[event]);\n\n return function removeListeners() {\n for (const event of Object.keys(map)) {\n server.removeListener(event, map[event]);\n }\n };\n}\n\n/**\n * Emit a `'close'` event on an `EventEmitter`.\n *\n * @param {EventEmitter} server The event emitter\n * @private\n */\nfunction emitClose(server) {\n server._state = CLOSED;\n server.emit('close');\n}\n\n/**\n * Handle socket errors.\n *\n * @private\n */\nfunction socketOnError() {\n this.destroy();\n}\n\n/**\n * Close the connection when preconditions are not fulfilled.\n *\n * @param {Duplex} socket The socket of the upgrade request\n * @param {Number} code The HTTP response status code\n * @param {String} [message] The HTTP response body\n * @param {Object} [headers] Additional HTTP response headers\n * @private\n */\nfunction abortHandshake(socket, code, message, headers) {\n //\n // The socket is writable unless the user destroyed or ended it before calling\n // `server.handleUpgrade()` or in the `verifyClient` function, which is a user\n // error. Handling this does not make much sense as the worst that can happen\n // is that some of the data written by the user might be discarded due to the\n // call to `socket.end()` below, which triggers an `'error'` event that in\n // turn causes the socket to be destroyed.\n //\n message = message || http.STATUS_CODES[code];\n headers = {\n Connection: 'close',\n 'Content-Type': 'text/html',\n 'Content-Length': Buffer.byteLength(message),\n ...headers\n };\n\n socket.once('finish', socket.destroy);\n\n socket.end(\n `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\\r\\n` +\n Object.keys(headers)\n .map((h) => `${h}: ${headers[h]}`)\n .join('\\r\\n') +\n '\\r\\n\\r\\n' +\n message\n );\n}\n\n/**\n * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least\n * one listener for it, otherwise call `abortHandshake()`.\n *\n * @param {WebSocketServer} server The WebSocket server\n * @param {http.IncomingMessage} req The request object\n * @param {Duplex} socket The socket of the upgrade request\n * @param {Number} code The HTTP response status code\n * @param {String} message The HTTP response body\n * @param {Object} [headers] The HTTP response headers\n * @private\n */\nfunction abortHandshakeOrEmitwsClientError(\n server,\n req,\n socket,\n code,\n message,\n headers\n) {\n if (server.listenerCount('wsClientError')) {\n const err = new Error(message);\n Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);\n\n server.emit('wsClientError', err, socket, req);\n } else {\n abortHandshake(socket, code, message, headers);\n }\n}\n","import createWebSocketStream from './lib/stream.js';\nimport extension from './lib/extension.js';\nimport PerMessageDeflate from './lib/permessage-deflate.js';\nimport Receiver from './lib/receiver.js';\nimport Sender from './lib/sender.js';\nimport subprotocol from './lib/subprotocol.js';\nimport WebSocket from './lib/websocket.js';\nimport WebSocketServer from './lib/websocket-server.js';\n\nexport {\n createWebSocketStream,\n extension,\n PerMessageDeflate,\n Receiver,\n Sender,\n subprotocol,\n WebSocket,\n WebSocketServer\n};\n\nexport default WebSocket;\n","/**\n * Node-compatible implementation of Effect's `Crypto` service.\n *\n * This module builds the service from `node:crypto`, using `randomBytes` for\n * random data and `createHash` for supported digest algorithms. It exports\n * `make` as the concrete service value and `layer` for providing it through\n * Effect context.\n *\n * @since 1.0.0\n */\nimport * as EffectCrypto from \"effect/Crypto\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as PlatformError from \"effect/PlatformError\";\nimport * as NodeCrypto from \"node:crypto\";\nconst toHashAlgorithm = algorithm => {\n switch (algorithm) {\n case \"SHA-1\":\n return \"sha1\";\n case \"SHA-256\":\n return \"sha256\";\n case \"SHA-384\":\n return \"sha384\";\n case \"SHA-512\":\n return \"sha512\";\n }\n};\nconst digest = (algorithm, data) => Effect.try({\n try: () => Uint8Array.from(NodeCrypto.createHash(toHashAlgorithm(algorithm)).update(data).digest()),\n catch: cause => PlatformError.systemError({\n module: \"Crypto\",\n method: \"digest\",\n _tag: \"Unknown\",\n description: \"Could not compute digest\",\n cause\n })\n});\n/**\n * The default Node.js Crypto service implementation.\n *\n * @category constructors\n * @since 1.0.0\n */\nexport const make = /*#__PURE__*/EffectCrypto.make({\n randomBytes: NodeCrypto.randomBytes,\n digest\n});\n/**\n * Layer that provides the Node.js Crypto service implementation.\n *\n * @category layers\n * @since 1.0.0\n */\nexport const layer = /*#__PURE__*/Layer.succeed(EffectCrypto.Crypto, make);\n//# sourceMappingURL=NodeCrypto.js.map","/**\n * The `NodeCrypto` module provides the Node.js `Crypto` service layer for\n * Effect programs. Provide {@link layer} at the edge of a Node application,\n * CLI, script, or test to satisfy `effect/Crypto` with Node's `node:crypto`\n * implementation for secure random bytes, UUID generation, random values, and\n * SHA digest operations.\n *\n * This module is the public Node adapter around the shared Node-compatible\n * implementation. Digest failures are reported as platform errors, and SHA-1\n * remains available only for interoperability with existing protocols.\n *\n * @since 1.0.0\n */\nimport * as NodeCrypto from \"@effect/platform-node-shared/NodeCrypto\";\n/**\n * Layer that provides the Node.js Crypto service implementation.\n *\n * @category layers\n * @since 1.0.0\n */\nexport const layer = NodeCrypto.layer;\n//# sourceMappingURL=NodeCrypto.js.map","/**\n * Shared Node-compatible implementation of Effect's `FileSystem` service.\n *\n * This module adapts Node's `node:fs`, `node:os`, and `node:path` APIs into a\n * `FileSystem` layer for Effect programs running on Node-compatible runtimes.\n * Platform packages use it to provide file and directory I/O, permissions,\n * links, metadata, temporary files and directories, and file watching through\n * the shared `FileSystem` service.\n *\n * @since 4.0.0\n */\nimport * as Cause from \"effect/Cause\";\nimport * as Effect from \"effect/Effect\";\nimport { effectify } from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport { pipe } from \"effect/Function\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Error from \"effect/PlatformError\";\nimport * as Queue from \"effect/Queue\";\nimport * as Stream from \"effect/Stream\";\nimport * as Crypto from \"node:crypto\";\nimport * as NFS from \"node:fs\";\nimport * as OS from \"node:os\";\nimport * as Path from \"node:path\";\nimport { handleErrnoException } from \"./internal/utils.js\";\nconst handleBadArgument = method => err => Error.badArgument({\n module: \"FileSystem\",\n method,\n description: err.message ?? String(err)\n});\n// == access\nconst access = /*#__PURE__*/(() => {\n const nodeAccess = /*#__PURE__*/effectify(NFS.access, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"access\"), /*#__PURE__*/handleBadArgument(\"access\"));\n return (path, options) => {\n let mode = NFS.constants.F_OK;\n if (options?.readable) {\n mode |= NFS.constants.R_OK;\n }\n if (options?.writable) {\n mode |= NFS.constants.W_OK;\n }\n return nodeAccess(path, mode);\n };\n})();\n// == copy\nconst copy = /*#__PURE__*/(() => {\n const nodeCp = /*#__PURE__*/effectify(NFS.cp, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"copy\"), /*#__PURE__*/handleBadArgument(\"copy\"));\n return (fromPath, toPath, options) => nodeCp(fromPath, toPath, {\n force: options?.overwrite ?? false,\n preserveTimestamps: options?.preserveTimestamps ?? false,\n recursive: true\n });\n})();\n// == copyFile\nconst copyFile = /*#__PURE__*/(() => {\n const nodeCopyFile = /*#__PURE__*/effectify(NFS.copyFile, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"copyFile\"), /*#__PURE__*/handleBadArgument(\"copyFile\"));\n return (fromPath, toPath) => nodeCopyFile(fromPath, toPath);\n})();\n// == chmod\nconst chmod = /*#__PURE__*/(() => {\n const nodeChmod = /*#__PURE__*/effectify(NFS.chmod, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"chmod\"), /*#__PURE__*/handleBadArgument(\"chmod\"));\n return (path, mode) => nodeChmod(path, mode);\n})();\n// == chown\nconst chown = /*#__PURE__*/(() => {\n const nodeChown = /*#__PURE__*/effectify(NFS.chown, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"chown\"), /*#__PURE__*/handleBadArgument(\"chown\"));\n return (path, uid, gid) => nodeChown(path, uid, gid);\n})();\n// == glob\nconst glob = /*#__PURE__*/(() => {\n const nodeGlob = /*#__PURE__*/effectify(NFS.glob, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"glob\"), /*#__PURE__*/handleBadArgument(\"glob\"));\n return (pattern, options) => nodeGlob(pattern, {\n cwd: options?.root,\n exclude: options?.exclude\n });\n})();\n// == link\nconst link = /*#__PURE__*/(() => {\n const nodeLink = /*#__PURE__*/effectify(NFS.link, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"link\"), /*#__PURE__*/handleBadArgument(\"link\"));\n return (existingPath, newPath) => nodeLink(existingPath, newPath);\n})();\n// == makeDirectory\nconst makeDirectory = /*#__PURE__*/(() => {\n const nodeMkdir = /*#__PURE__*/effectify(NFS.mkdir, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"makeDirectory\"), /*#__PURE__*/handleBadArgument(\"makeDirectory\"));\n return (path, options) => nodeMkdir(path, {\n recursive: options?.recursive ?? false,\n mode: options?.mode\n });\n})();\n// == makeTempDirectory\nconst makeTempDirectoryFactory = method => {\n const nodeMkdtemp = effectify(NFS.mkdtemp, handleErrnoException(\"FileSystem\", method), handleBadArgument(method));\n return options => Effect.suspend(() => {\n const prefix = options?.prefix ?? \"\";\n const directory = typeof options?.directory === \"string\" ? Path.join(options.directory, \".\") : OS.tmpdir();\n return nodeMkdtemp(prefix ? Path.join(directory, prefix) : directory + \"/\");\n });\n};\nconst makeTempDirectory = /*#__PURE__*/makeTempDirectoryFactory(\"makeTempDirectory\");\n// == remove\nconst removeFactory = method => {\n const nodeRm = effectify(NFS.rm, handleErrnoException(\"FileSystem\", method), handleBadArgument(method));\n return (path, options) => nodeRm(path, {\n recursive: options?.recursive ?? false,\n force: options?.force ?? false\n });\n};\nconst remove = /*#__PURE__*/removeFactory(\"remove\");\n// == makeTempDirectoryScoped\nconst makeTempDirectoryScoped = /*#__PURE__*/(() => {\n const makeDirectory = /*#__PURE__*/makeTempDirectoryFactory(\"makeTempDirectoryScoped\");\n const removeDirectory = /*#__PURE__*/removeFactory(\"makeTempDirectoryScoped\");\n return options => Effect.acquireRelease(makeDirectory(options), directory => Effect.orDie(removeDirectory(directory, {\n recursive: true\n })));\n})();\n// == open\nconst openFactory = method => {\n const nodeOpen = effectify(NFS.open, handleErrnoException(\"FileSystem\", method), handleBadArgument(method));\n const nodeClose = effectify(NFS.close, handleErrnoException(\"FileSystem\", method), handleBadArgument(method));\n return (path, options) => pipe(Effect.acquireRelease(nodeOpen(path, options?.flag ?? \"r\", options?.mode), fd => Effect.orDie(nodeClose(fd))), Effect.map(fd => makeFile(fd, options?.flag?.startsWith(\"a\") ?? false)));\n};\nconst open = /*#__PURE__*/openFactory(\"open\");\nconst makeFile = /*#__PURE__*/(() => {\n const nodeReadFactory = method => effectify(NFS.read, handleErrnoException(\"FileSystem\", method), handleBadArgument(method));\n const nodeRead = /*#__PURE__*/nodeReadFactory(\"read\");\n const nodeReadAlloc = /*#__PURE__*/nodeReadFactory(\"readAlloc\");\n const nodeStat = /*#__PURE__*/effectify(NFS.fstat, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"stat\"), /*#__PURE__*/handleBadArgument(\"stat\"));\n const nodeTruncate = /*#__PURE__*/effectify(NFS.ftruncate, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"truncate\"), /*#__PURE__*/handleBadArgument(\"truncate\"));\n const nodeSync = /*#__PURE__*/effectify(NFS.fsync, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"sync\"), /*#__PURE__*/handleBadArgument(\"sync\"));\n const nodeWriteFactory = method => effectify(NFS.write, handleErrnoException(\"FileSystem\", method), handleBadArgument(method));\n const nodeWrite = /*#__PURE__*/nodeWriteFactory(\"write\");\n const nodeWriteAll = /*#__PURE__*/nodeWriteFactory(\"writeAll\");\n class FileImpl {\n [FileSystem.FileTypeId];\n fd;\n append;\n position = /*#__PURE__*/BigInt(0);\n constructor(fd, append) {\n this[FileSystem.FileTypeId] = FileSystem.FileTypeId;\n this.fd = fd;\n this.append = append;\n }\n get stat() {\n return Effect.map(nodeStat(this.fd), makeFileInfo);\n }\n get sync() {\n return nodeSync(this.fd);\n }\n seek(offset, from) {\n const offsetSize = FileSystem.Size(offset);\n return Effect.sync(() => {\n if (from === \"start\") {\n this.position = offsetSize;\n } else if (from === \"current\") {\n this.position = this.position + offsetSize;\n }\n return FileSystem.Size(this.position);\n });\n }\n read(buffer) {\n return Effect.suspend(() => {\n const position = this.position;\n return Effect.map(nodeRead(this.fd, {\n buffer,\n position\n }), bytesRead => {\n const sizeRead = FileSystem.Size(bytesRead);\n this.position = position + sizeRead;\n return sizeRead;\n });\n });\n }\n readAlloc(size) {\n const sizeNumber = Number(size);\n return Effect.suspend(() => {\n const buffer = Buffer.allocUnsafeSlow(sizeNumber);\n const position = this.position;\n return Effect.map(nodeReadAlloc(this.fd, {\n buffer,\n position\n }), bytesRead => {\n if (bytesRead === 0) {\n return Option.none();\n }\n this.position = position + BigInt(bytesRead);\n if (bytesRead === sizeNumber) {\n return Option.some(buffer);\n }\n const dst = Buffer.allocUnsafeSlow(bytesRead);\n buffer.copy(dst, 0, 0, bytesRead);\n return Option.some(dst);\n });\n });\n }\n truncate(length) {\n return Effect.map(nodeTruncate(this.fd, length ? Number(length) : undefined), () => {\n if (!this.append) {\n const len = BigInt(length ?? 0);\n if (this.position > len) {\n this.position = len;\n }\n }\n });\n }\n write(buffer) {\n return Effect.suspend(() => {\n const position = this.position;\n return Effect.map(nodeWrite(this.fd, buffer, undefined, undefined, this.append ? undefined : Number(position)), bytesWritten => {\n const sizeWritten = FileSystem.Size(bytesWritten);\n if (!this.append) {\n this.position = position + sizeWritten;\n }\n return sizeWritten;\n });\n });\n }\n writeAllChunk(buffer) {\n return Effect.suspend(() => {\n const position = this.position;\n return Effect.flatMap(nodeWriteAll(this.fd, buffer, undefined, undefined, this.append ? undefined : Number(position)), bytesWritten => {\n if (bytesWritten === 0) {\n return Effect.fail(Error.systemError({\n module: \"FileSystem\",\n method: \"writeAll\",\n _tag: \"WriteZero\",\n pathOrDescriptor: this.fd,\n description: \"write returned 0 bytes written\"\n }));\n }\n if (!this.append) {\n this.position = position + BigInt(bytesWritten);\n }\n return bytesWritten < buffer.length ? this.writeAllChunk(buffer.subarray(bytesWritten)) : Effect.void;\n });\n });\n }\n writeAll(buffer) {\n return this.writeAllChunk(buffer);\n }\n }\n return (fd, append) => new FileImpl(fd, append);\n})();\n// == makeTempFile\nconst makeTempFileFactory = method => {\n const makeDirectory = makeTempDirectoryFactory(method);\n return Effect.fnUntraced(function* (options) {\n const directory = yield* makeDirectory(options);\n const random = Crypto.randomBytes(6).toString(\"hex\");\n const name = Path.join(directory, options?.suffix ? `${random}${options.suffix}` : random);\n yield* writeFile(name, new Uint8Array(0));\n return name;\n });\n};\nconst makeTempFile = /*#__PURE__*/makeTempFileFactory(\"makeTempFile\");\n// == makeTempFileScoped\nconst makeTempFileScoped = /*#__PURE__*/(() => {\n const makeFile = /*#__PURE__*/makeTempFileFactory(\"makeTempFileScoped\");\n const removeDirectory = /*#__PURE__*/removeFactory(\"makeTempFileScoped\");\n return options => Effect.acquireRelease(makeFile(options), file => Effect.orDie(removeDirectory(Path.dirname(file), {\n recursive: true\n })));\n})();\n// == readDirectory\nconst readDirectory = (path, options) => Effect.tryPromise({\n try: () => NFS.promises.readdir(path, options),\n catch: err => handleErrnoException(\"FileSystem\", \"readDirectory\")(err, [path])\n});\n// == readFile\nconst readFile = path => Effect.callback((resume, signal) => {\n try {\n NFS.readFile(path, {\n signal\n }, (err, data) => {\n if (err) {\n resume(Effect.fail(handleErrnoException(\"FileSystem\", \"readFile\")(err, [path])));\n } else {\n resume(Effect.succeed(data));\n }\n });\n } catch (err) {\n resume(Effect.fail(handleBadArgument(\"readFile\")(err)));\n }\n});\n// == readLink\nconst readLink = /*#__PURE__*/(() => {\n const nodeReadLink = /*#__PURE__*/effectify(NFS.readlink, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"readLink\"), /*#__PURE__*/handleBadArgument(\"readLink\"));\n return path => nodeReadLink(path);\n})();\n// == realPath\nconst realPath = /*#__PURE__*/(() => {\n const nodeRealPath = /*#__PURE__*/effectify(NFS.realpath, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"realPath\"), /*#__PURE__*/handleBadArgument(\"realPath\"));\n return path => nodeRealPath(path);\n})();\n// == rename\nconst rename = /*#__PURE__*/(() => {\n const nodeRename = /*#__PURE__*/effectify(NFS.rename, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"rename\"), /*#__PURE__*/handleBadArgument(\"rename\"));\n return (oldPath, newPath) => nodeRename(oldPath, newPath);\n})();\n// == stat\nconst makeFileInfo = stat => ({\n type: stat.isFile() ? \"File\" : stat.isDirectory() ? \"Directory\" : stat.isSymbolicLink() ? \"SymbolicLink\" : stat.isBlockDevice() ? \"BlockDevice\" : stat.isCharacterDevice() ? \"CharacterDevice\" : stat.isFIFO() ? \"FIFO\" : stat.isSocket() ? \"Socket\" : \"Unknown\",\n mtime: Option.fromNullishOr(stat.mtime),\n atime: Option.fromNullishOr(stat.atime),\n birthtime: Option.fromNullishOr(stat.birthtime),\n dev: stat.dev,\n rdev: Option.fromNullishOr(stat.rdev),\n ino: Option.fromNullishOr(stat.ino),\n mode: stat.mode,\n nlink: Option.fromNullishOr(stat.nlink),\n uid: Option.fromNullishOr(stat.uid),\n gid: Option.fromNullishOr(stat.gid),\n size: FileSystem.Size(stat.size),\n blksize: stat.blksize !== undefined ? Option.some(FileSystem.Size(stat.blksize)) : Option.none(),\n blocks: Option.fromNullishOr(stat.blocks)\n});\nconst stat = /*#__PURE__*/(() => {\n const nodeStat = /*#__PURE__*/effectify(NFS.stat, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"stat\"), /*#__PURE__*/handleBadArgument(\"stat\"));\n return path => Effect.map(nodeStat(path), makeFileInfo);\n})();\n// == symlink\nconst symlink = /*#__PURE__*/(() => {\n const nodeSymlink = /*#__PURE__*/effectify(NFS.symlink, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"symlink\"), /*#__PURE__*/handleBadArgument(\"symlink\"));\n return (target, path) => nodeSymlink(target, path);\n})();\n// == truncate\nconst truncate = /*#__PURE__*/(() => {\n const nodeTruncate = /*#__PURE__*/effectify(NFS.truncate, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"truncate\"), /*#__PURE__*/handleBadArgument(\"truncate\"));\n return (path, length) => nodeTruncate(path, length !== undefined ? Number(length) : undefined);\n})();\n// == utimes\nconst utimes = /*#__PURE__*/(() => {\n const nodeUtimes = /*#__PURE__*/effectify(NFS.utimes, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"utime\"), /*#__PURE__*/handleBadArgument(\"utime\"));\n return (path, atime, mtime) => nodeUtimes(path, atime, mtime);\n})();\n// == watch\nconst watchNode = (path, options) => Stream.callback(queue => Effect.acquireRelease(Effect.sync(() => {\n const watcher = NFS.watch(path, {\n recursive: options?.recursive ?? false\n }, (event, path) => {\n if (!path) return;\n switch (event) {\n case \"rename\":\n {\n Effect.runFork(Effect.matchEffect(stat(path), {\n onSuccess: _ => Queue.offer(queue, {\n _tag: \"Create\",\n path\n }),\n onFailure: _ => Queue.offer(queue, {\n _tag: \"Remove\",\n path\n })\n }));\n return;\n }\n case \"change\":\n {\n Queue.offerUnsafe(queue, {\n _tag: \"Update\",\n path\n });\n return;\n }\n }\n });\n watcher.on(\"error\", error => {\n Queue.failCauseUnsafe(queue, Cause.fail(Error.systemError({\n module: \"FileSystem\",\n _tag: \"Unknown\",\n method: \"watch\",\n pathOrDescriptor: path,\n cause: error\n })));\n });\n watcher.on(\"close\", () => {\n Queue.endUnsafe(queue);\n });\n return watcher;\n}), watcher => Effect.sync(() => watcher.close())));\nconst watch = (backend, path, options) => stat(path).pipe(Effect.map(stat => backend.pipe(Option.flatMap(_ => _.register(path, stat, options)), Option.getOrElse(() => watchNode(path, options)))), Stream.unwrap);\n// == writeFile\nconst writeFile = (path, data, options) => Effect.callback((resume, signal) => {\n try {\n NFS.writeFile(path, data, {\n signal,\n flag: options?.flag,\n mode: options?.mode\n }, err => {\n if (err) {\n resume(Effect.fail(handleErrnoException(\"FileSystem\", \"writeFile\")(err, [path])));\n } else {\n resume(Effect.void);\n }\n });\n } catch (err) {\n resume(Effect.fail(handleBadArgument(\"writeFile\")(err)));\n }\n});\nconst makeFileSystem = /*#__PURE__*/Effect.map(/*#__PURE__*/Effect.serviceOption(FileSystem.WatchBackend), backend => FileSystem.make({\n access,\n chmod,\n chown,\n copy,\n copyFile,\n glob,\n link,\n makeDirectory,\n makeTempDirectory,\n makeTempDirectoryScoped,\n makeTempFile,\n makeTempFileScoped,\n open,\n readDirectory,\n readFile,\n readLink,\n realPath,\n remove,\n rename,\n stat,\n symlink,\n truncate,\n utimes,\n watch(path, options) {\n return watch(backend, path, options);\n },\n writeFile\n}));\n/**\n * Provides the `FileSystem` service backed by Node filesystem APIs, including\n * file operations, directory operations, links, metadata, and file watching.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layer = /*#__PURE__*/Layer.effect(FileSystem.FileSystem)(makeFileSystem);\n//# sourceMappingURL=NodeFileSystem.js.map","/**\n * Node.js `FileSystem` layer for programs that perform real filesystem I/O.\n *\n * The exported layer satisfies the platform-independent `FileSystem` service\n * with Node-backed operations for files, directories, metadata, permissions,\n * links, temporary paths, and path watching. Effects still call the service from\n * `effect/FileSystem`; this module only chooses the Node implementation.\n *\n * @since 4.0.0\n */\nimport * as NodeFileSystem from \"@effect/platform-node-shared/NodeFileSystem\";\n/**\n * Provides the `FileSystem` service backed by Node filesystem APIs.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layer = NodeFileSystem.layer;\n//# sourceMappingURL=NodeFileSystem.js.map","/**\n * Adapter base for exposing Node `http.IncomingMessage` values as Effect HTTP\n * incoming messages.\n *\n * Server requests and Node client responses both arrive as Node readable\n * streams with raw header objects, socket metadata, and one-shot body\n * consumption. This module's `NodeHttpIncomingMessage` class keeps the original\n * Node message available while presenting Effect's `HttpIncomingMessage` shape:\n * typed headers, remote address lookup, stream access, and text, JSON,\n * URL-encoded, and array-buffer body readers.\n *\n * @since 4.0.0\n */\nimport * as Effect from \"effect/Effect\";\nimport * as Inspectable from \"effect/Inspectable\";\nimport * as Option from \"effect/Option\";\nimport * as Headers from \"effect/unstable/http/Headers\";\nimport * as IncomingMessage from \"effect/unstable/http/HttpIncomingMessage\";\nimport * as UrlParams from \"effect/unstable/http/UrlParams\";\nimport * as NodeStream from \"./NodeStream.js\";\n/**\n * Adapts a Node `IncomingMessage` to Effect HTTP incoming messages.\n *\n * **When to use**\n *\n * Use to implement Node HTTP request or response adapters that expose the\n * Effect HTTP incoming-message interface.\n *\n * **Details**\n *\n * The adapter exposes headers, remote address, stream access, and cached body\n * decoders. Subclasses provide the error mapping for unknown Node errors.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport class NodeHttpIncomingMessage extends Inspectable.Class {\n /**\n * Marks this value as an HTTP incoming message for runtime guards.\n *\n * @since 4.0.0\n */\n [IncomingMessage.TypeId];\n source;\n onError;\n remoteAddressOverride;\n constructor(source, onError, remoteAddressOverride) {\n super();\n this[IncomingMessage.TypeId] = IncomingMessage.TypeId;\n this.source = source;\n this.onError = onError;\n this.remoteAddressOverride = remoteAddressOverride;\n }\n get headers() {\n return Headers.fromInput(this.source.headers);\n }\n get remoteAddress() {\n return this.remoteAddressOverride ?? Option.fromNullishOr(this.source.socket.remoteAddress);\n }\n textEffect;\n get text() {\n if (this.textEffect) {\n return this.textEffect;\n }\n this.textEffect = Effect.runSync(Effect.cached(Effect.flatMap(IncomingMessage.MaxBodySize, maxBodySize => NodeStream.toString(() => this.source, {\n onError: this.onError,\n maxBytes: maxBodySize\n }))));\n this.arrayBufferEffect = Effect.map(this.textEffect, _ => new TextEncoder().encode(_).buffer);\n return this.textEffect;\n }\n get textUnsafe() {\n return Effect.runSync(this.text);\n }\n get json() {\n return Effect.flatMap(this.text, text => Effect.try({\n try: () => text === \"\" ? null : JSON.parse(text),\n catch: this.onError\n }));\n }\n get jsonUnsafe() {\n return Effect.runSync(this.json);\n }\n get urlParamsBody() {\n return Effect.flatMap(this.text, _ => Effect.try({\n try: () => UrlParams.fromInput(new URLSearchParams(_)),\n catch: this.onError\n }));\n }\n get stream() {\n return NodeStream.fromReadable({\n evaluate: () => this.source,\n onError: this.onError\n });\n }\n arrayBufferEffect;\n get arrayBuffer() {\n if (this.arrayBufferEffect) {\n return this.arrayBufferEffect;\n }\n this.arrayBufferEffect = Effect.withFiber(fiber => NodeStream.toArrayBuffer(() => this.source, {\n onError: this.onError,\n maxBytes: fiber.getRef(IncomingMessage.MaxBodySize)\n })).pipe(Effect.cached, Effect.runSync);\n this.textEffect = Effect.map(this.arrayBufferEffect, _ => new TextDecoder().decode(_));\n return this.arrayBufferEffect;\n }\n}\n//# sourceMappingURL=NodeHttpIncomingMessage.js.map","import { make as makeParser } from \"effect/unstable/http/MultipartParser\";\nimport { Duplex, Readable } from \"node:stream\";\n/**\n * A Node.js duplex stream that parses multipart input.\n *\n * @category models\n * @since 4.0.0\n */\nexport class MultipartStream extends Duplex {\n _parser;\n _canWrite = true;\n _writeCallback;\n constructor(config) {\n super({\n readableObjectMode: true\n });\n let currentError;\n let currentFile;\n this._parser = makeParser({\n ...config,\n onField: (info, value) => {\n if (currentError !== undefined) return;\n const field = {\n _tag: \"Field\",\n info,\n value\n };\n this.push(field);\n this.emit(\"field\", field);\n },\n onFile: info => {\n if (currentError !== undefined) return _ => {};\n const file = new FileStream(info, this);\n currentFile = file;\n this.push(file);\n this.emit(\"file\", file);\n return chunk => {\n if (currentError !== undefined) return;\n this._canWrite = file.push(chunk);\n if (chunk === null && !this._canWrite) {\n currentFile = undefined;\n this._resume();\n }\n };\n },\n onError: error => {\n this.emit(\"error\", error);\n currentFile?.emit(\"error\", error);\n currentError = error;\n },\n onDone: () => {\n this.push(null);\n }\n });\n }\n _resume() {\n this._canWrite = true;\n if (this._writeCallback !== undefined) {\n const callback = this._writeCallback;\n this._writeCallback = undefined;\n callback();\n }\n }\n _read(_size) {}\n _write(chunk, encoding, callback) {\n this._parser.write(chunk instanceof Uint8Array ? chunk : Buffer.from(chunk, encoding));\n if (this._canWrite) {\n callback();\n } else {\n this._writeCallback = callback;\n }\n }\n _final(callback) {\n this._parser.end();\n callback();\n }\n}\n/**\n * Creates a Node.js multipart parser stream.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = config => new MultipartStream(config);\n/**\n * A readable stream containing a parsed multipart file.\n *\n * @category models\n * @since 4.0.0\n */\nexport class FileStream extends Readable {\n _tag = \"File\";\n filename;\n info;\n _parent;\n constructor(info, parent) {\n super();\n this.info = info;\n this._parent = parent;\n this.filename = info.filename;\n }\n _read(_size) {\n if (this._parent._canWrite === false) {\n this._parent._resume();\n }\n }\n}\n//# sourceMappingURL=NodeMultipartParser.js.map","/**\n * Node.js multipart parsing for HTTP `multipart/form-data` request bodies.\n *\n * `NodeMultipart` adapts a Node `Readable` plus incoming HTTP headers into\n * Effect's shared multipart model. It can expose form parts as a stream or\n * collect a complete persisted form by writing file uploads to scoped temporary\n * files through the current `FileSystem` and `Path` services. `fileToReadable`\n * returns the underlying Node readable stream for file parts produced by this\n * parser.\n *\n * @since 4.0.0\n */\nimport * as Effect from \"effect/Effect\";\nimport * as Inspectable from \"effect/Inspectable\";\nimport * as Stream from \"effect/Stream\";\nimport * as Multipart from \"effect/unstable/http/Multipart\";\nimport * as MultipartParser from \"effect/unstable/http/MultipartParser\";\nimport * as NFS from \"node:fs\";\nimport * as NodeStreamP from \"node:stream/promises\";\nimport * as MP from \"./NodeMultipartParser.js\";\nimport * as NodeStream from \"./NodeStream.js\";\n/**\n * Parses multipart data from a Node readable request body and headers into a\n * stream of `Multipart.Part` values, converting parser failures to\n * `MultipartError`.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const stream = (source, headers) => Multipart.makeConfig(headers).pipe(Effect.map(config => NodeStream.fromReadable({\n evaluate() {\n const parser = MP.make(config);\n source.pipe(parser);\n return parser;\n },\n onError: error => convertError(error)\n})), Stream.unwrap, Stream.map(convertPart));\n/**\n * Parses multipart data from a Node readable request body and persists file\n * parts using the current `FileSystem`, `Path`, and `Scope` services.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const persisted = (source, headers) => Multipart.toPersisted(stream(source, headers), (path, file) => Effect.tryPromise({\n try: signal => NodeStreamP.pipeline(file.file, NFS.createWriteStream(path), {\n signal\n }),\n catch: cause => Multipart.MultipartError.fromReason(\"InternalError\", cause)\n}));\n/**\n * Returns the underlying Node readable stream for a multipart file produced by\n * the Node multipart parser.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const fileToReadable = file => file.file;\n// -----------------------------------------------------------------------------\n// Internal\n// -----------------------------------------------------------------------------\nconst convertPart = part => part._tag === \"Field\" ? new FieldImpl(part.info, part.value) : new FileImpl(part);\nclass PartBase extends Inspectable.Class {\n [Multipart.TypeId];\n constructor() {\n super();\n this[Multipart.TypeId] = Multipart.TypeId;\n }\n}\nclass FieldImpl extends PartBase {\n _tag = \"Field\";\n key;\n contentType;\n value;\n constructor(info, value) {\n super();\n this.key = info.name;\n this.contentType = info.contentType;\n this.value = MultipartParser.decodeField(info, value);\n }\n toJSON() {\n return {\n _id: \"@effect/platform/Multipart/Part\",\n _tag: \"Field\",\n key: this.key,\n value: this.value,\n contentType: this.contentType\n };\n }\n}\nclass FileImpl extends PartBase {\n _tag = \"File\";\n key;\n name;\n contentType;\n content;\n contentEffect;\n file;\n constructor(file) {\n super();\n this.file = file;\n this.key = file.info.name;\n this.name = file.filename ?? file.info.name;\n this.contentType = file.info.contentType;\n this.content = NodeStream.fromReadable({\n evaluate: () => file,\n onError: cause => Multipart.MultipartError.fromReason(\"InternalError\", cause)\n });\n this.contentEffect = NodeStream.toUint8Array(() => file, {\n onError: cause => Multipart.MultipartError.fromReason(\"InternalError\", cause)\n });\n }\n toJSON() {\n return {\n _id: \"@effect/platform/Multipart/Part\",\n _tag: \"File\",\n key: this.key,\n name: this.name,\n contentType: this.contentType\n };\n }\n}\nfunction convertError(cause) {\n switch (cause._tag) {\n case \"ReachedLimit\":\n {\n switch (cause.limit) {\n case \"MaxParts\":\n {\n return Multipart.MultipartError.fromReason(\"TooManyParts\", cause);\n }\n case \"MaxFieldSize\":\n {\n return Multipart.MultipartError.fromReason(\"FieldTooLarge\", cause);\n }\n case \"MaxPartSize\":\n {\n return Multipart.MultipartError.fromReason(\"FileTooLarge\", cause);\n }\n case \"MaxTotalSize\":\n {\n return Multipart.MultipartError.fromReason(\"BodyTooLarge\", cause);\n }\n }\n }\n default:\n {\n return Multipart.MultipartError.fromReason(\"Parse\", cause);\n }\n }\n}\n//# sourceMappingURL=NodeMultipart.js.map","/**\n * Node-backed provider for Effect's `Path` service.\n *\n * This module turns Node's `node:path` and `node:url` APIs into `Path` layers.\n * `layer` uses the host platform path implementation, while `layerPosix` and\n * `layerWin32` provide fixed POSIX and Windows variants. All three layers also\n * include helpers for converting between file paths and file URLs.\n *\n * @since 4.0.0\n */\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport { Path, TypeId } from \"effect/Path\";\nimport { BadArgument } from \"effect/PlatformError\";\nimport * as NodePath from \"node:path\";\nimport * as NodeUrl from \"node:url\";\nconst fileUrlOps = windows => ({\n fromFileUrl: url => Effect.try({\n try: () => NodeUrl.fileURLToPath(url, {\n windows\n }),\n catch: cause => new BadArgument({\n module: \"Path\",\n method: \"fromFileUrl\",\n cause\n })\n }),\n toFileUrl: path => Effect.try({\n try: () => NodeUrl.pathToFileURL(path, {\n windows\n }),\n catch: cause => new BadArgument({\n module: \"Path\",\n method: \"toFileUrl\",\n cause\n })\n })\n});\n/**\n * Provides the `Path` service using Node's POSIX path implementation plus\n * file URL conversion helpers.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerPosix = /*#__PURE__*/Layer.succeed(Path)({\n [TypeId]: TypeId,\n ...NodePath.posix,\n ... /*#__PURE__*/fileUrlOps(false)\n});\n/**\n * Provides the `Path` service using Node's Windows path implementation plus\n * file URL conversion helpers.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerWin32 = /*#__PURE__*/Layer.succeed(Path)({\n [TypeId]: TypeId,\n ...NodePath.win32,\n ... /*#__PURE__*/fileUrlOps(true)\n});\n/**\n * Provides the default `Path` service using the host platform's Node path\n * implementation plus file URL conversion helpers.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layer = /*#__PURE__*/Layer.succeed(Path)({\n [TypeId]: TypeId,\n ...NodePath,\n ... /*#__PURE__*/fileUrlOps(undefined)\n});\n//# sourceMappingURL=NodePath.js.map","/**\n * Node.js layers for Effect's `Path` service.\n *\n * This module provides the default, POSIX, and Windows variants of the\n * platform-independent `Path` service by reusing the shared Node path\n * implementation. The provided path services include Node file URL conversion\n * behavior.\n *\n * @since 4.0.0\n */\nimport * as NodePath from \"@effect/platform-node-shared/NodePath\";\n/**\n * Provides the default Node `Path` service using the platform's `node:path`\n * implementation.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layer = NodePath.layer;\n/**\n * Provides the `Path` service using Node's POSIX path implementation,\n * regardless of the host platform.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerPosix = NodePath.layerPosix;\n/**\n * Provides the `Path` service using Node's Windows path implementation,\n * regardless of the host platform.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerWin32 = NodePath.layerWin32;\n//# sourceMappingURL=NodePath.js.map","/**\n * Shared Node.js implementation of the Effect `Stdio` service.\n *\n * `NodeStdio` provides {@link Stdio.Stdio} from the current Node process. The\n * exported {@link layer} reads command-line arguments from `process.argv`,\n * consumes input from `process.stdin`, and writes normal and error output to\n * `process.stdout` and `process.stderr`. Standard input remains open, and\n * standard output and error output are not ended unless requested.\n *\n * @since 4.0.0\n */\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport { systemError } from \"effect/PlatformError\";\nimport * as Stdio from \"effect/Stdio\";\nimport { fromWritable } from \"./NodeSink.js\";\nimport { fromReadable } from \"./NodeStream.js\";\n/**\n * Provides `Stdio` from `process.argv`, `process.stdin`, `process.stdout`,\n * and `process.stderr`; stdin remains open and stdout/stderr are not ended by\n * default.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layer = /*#__PURE__*/Layer.succeed(Stdio.Stdio, /*#__PURE__*/Stdio.make({\n args: /*#__PURE__*/Effect.sync(() => process.argv.slice(2)),\n stdinIsTerminal: /*#__PURE__*/Effect.sync(() => process.stdin.isTTY === true),\n stdoutIsTerminal: /*#__PURE__*/Effect.sync(() => process.stdout.isTTY === true),\n stdout: options => fromWritable({\n evaluate: () => process.stdout,\n onError: cause => systemError({\n module: \"Stdio\",\n method: \"stdout\",\n _tag: \"Unknown\",\n cause\n }),\n endOnDone: options?.endOnDone ?? false\n }),\n stderr: options => fromWritable({\n evaluate: () => process.stderr,\n onError: cause => systemError({\n module: \"Stdio\",\n method: \"stderr\",\n _tag: \"Unknown\",\n cause\n }),\n endOnDone: options?.endOnDone ?? false\n }),\n stdin: /*#__PURE__*/fromReadable({\n evaluate: () => process.stdin,\n onError: cause => systemError({\n module: \"Stdio\",\n method: \"stdin\",\n _tag: \"Unknown\",\n cause\n }),\n closeOnDone: false\n })\n}));\n//# sourceMappingURL=NodeStdio.js.map","/**\n * Node.js `Stdio` layer for the current process.\n *\n * The exported layer reuses the shared Node stdio implementation. It satisfies\n * the platform-independent `Stdio` service by reading command-line arguments\n * from `process.argv`, consuming input from `process.stdin`, and writing output\n * streams to `process.stdout` and `process.stderr`.\n *\n * @since 4.0.0\n */\nimport * as NodeStdio from \"@effect/platform-node-shared/NodeStdio\";\n/**\n * Provides the `Stdio` service backed by the current process arguments,\n * stdin, stdout, and stderr streams.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layer = NodeStdio.layer;\n//# sourceMappingURL=NodeStdio.js.map","import * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport { badArgument } from \"effect/PlatformError\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Queue from \"effect/Queue\";\nimport * as RcRef from \"effect/RcRef\";\nimport * as Terminal from \"effect/Terminal\";\nimport * as readline from \"node:readline\";\n/**\n * Creates a scoped process-backed `Terminal` using Node `readline`, enabling\n * TTY raw mode while in scope and using the supplied predicate to decide when\n * key input should end.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = /*#__PURE__*/Effect.fnUntraced(function* (shouldQuit = defaultShouldQuit) {\n const stdin = process.stdin;\n const stdout = process.stdout;\n const lines = yield* Queue.make();\n // stdin \"end\" fires once per process, so remember end-of-input for readers\n // created after the event (Bun never sets `readableEnded`).\n let inputEnded = stdin.readableEnded;\n let readlineActive = false;\n const onStdinEnd = () => {\n inputEnded = true;\n if (!readlineActive) {\n Queue.endUnsafe(lines);\n }\n };\n stdin.once(\"end\", onStdinEnd);\n yield* Effect.addFinalizer(() => Effect.sync(() => stdin.off(\"end\", onStdinEnd)));\n const rlRef = yield* RcRef.make({\n acquire: Effect.acquireRelease(Effect.sync(() => {\n const rl = readline.createInterface({\n input: stdin,\n escapeCodeTimeout: 50\n });\n const onLine = line => Queue.offerUnsafe(lines, line);\n const onClose = () => {\n readlineActive = false;\n Queue.endUnsafe(lines);\n };\n readlineActive = true;\n readline.emitKeypressEvents(stdin, rl);\n rl.on(\"line\", onLine);\n rl.once(\"close\", onClose);\n if (stdin.isTTY) {\n stdin.setRawMode(true);\n }\n return {\n rl,\n onClose,\n onLine\n };\n }), ({\n rl,\n onClose,\n onLine\n }) => Effect.sync(() => {\n readlineActive = false;\n rl.off(\"line\", onLine);\n rl.off(\"close\", onClose);\n if (stdin.isTTY) {\n stdin.setRawMode(false);\n }\n rl.close();\n if (inputEnded) {\n Queue.endUnsafe(lines);\n }\n })),\n idleTimeToLive: \"10 millis\"\n });\n const columns = Effect.sync(() => stdout.columns ?? 0);\n const rows = Effect.sync(() => stdout.rows ?? 0);\n const readInput = Effect.gen(function* () {\n const queue = yield* Queue.make();\n const handleKeypress = (s, k) => {\n const userInput = {\n input: Option.fromUndefinedOr(s),\n key: {\n name: k.name ?? \"\",\n ctrl: !!k.ctrl,\n meta: !!k.meta,\n shift: !!k.shift\n }\n };\n Queue.offerUnsafe(queue, userInput);\n if (shouldQuit(userInput)) {\n Queue.endUnsafe(queue);\n }\n };\n // Deno's `process.stdin` shim does not keep the event loop alive, so a\n // program blocked on input can exit before `end` is ever delivered. A\n // timer holds the loop open for as long as this reader is active.\n const keepAlive = setInterval(() => {}, 2147483647);\n // Without this, consumers (e.g. `Prompt.run`) hang forever on closed stdin.\n const handleEnd = () => {\n clearInterval(keepAlive);\n Queue.endUnsafe(queue);\n };\n yield* Effect.addFinalizer(() => Effect.sync(() => {\n clearInterval(keepAlive);\n stdin.off(\"keypress\", handleKeypress);\n stdin.off(\"end\", handleEnd);\n }));\n stdin.on(\"keypress\", handleKeypress);\n if (inputEnded) {\n handleEnd();\n } else {\n yield* RcRef.get(rlRef);\n stdin.once(\"end\", handleEnd);\n }\n return queue;\n });\n const readLine = Effect.suspend(() => Queue.poll(lines).pipe(Effect.flatMap(Option.match({\n onNone: () => Effect.scoped(Effect.andThen(RcRef.get(rlRef), Queue.take(lines))),\n onSome: Effect.succeed\n })), Effect.mapError(() => new Terminal.QuitError({}))));\n const display = prompt => Effect.uninterruptible(Effect.callback(resume => {\n stdout.write(prompt, err => Predicate.isNullish(err) ? resume(Effect.void) : resume(Effect.fail(badArgument({\n module: \"Terminal\",\n method: \"display\",\n description: \"Failed to write prompt to stdout\",\n cause: err\n }))));\n }));\n return Terminal.make({\n columns,\n rows,\n readInput,\n readLine,\n display\n });\n});\n/**\n * Provides the default process-backed `Terminal` service, ending key input on\n * Ctrl+C or Ctrl+D.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layer = /*#__PURE__*/Layer.effect(Terminal.Terminal, /*#__PURE__*/make(defaultShouldQuit));\nfunction defaultShouldQuit(input) {\n return input.key.ctrl && (input.key.name === \"c\" || input.key.name === \"d\");\n}\n//# sourceMappingURL=NodeTerminal.js.map","/**\n * Node.js implementation of the Effect `Terminal` service.\n *\n * This module reuses the shared Node terminal implementation. `make` creates a\n * scoped process-backed `Terminal` service, and `layer` provides the default\n * service with the standard quit behavior for key input.\n *\n * @since 4.0.0\n */\nimport * as NodeTerminal from \"@effect/platform-node-shared/NodeTerminal\";\n/**\n * Creates a scoped `Terminal` service backed by process stdin/stdout, using the\n * optional predicate to decide when key input should end the input stream.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = NodeTerminal.make;\n/**\n * Provides the default process-backed `Terminal` service, ending key input on\n * the default quit keys.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layer = NodeTerminal.layer;\n//# sourceMappingURL=NodeTerminal.js.map","import * as Layer from \"effect/Layer\";\nimport * as NodeChildProcessSpawner from \"./NodeChildProcessSpawner.js\";\nimport * as NodeCrypto from \"./NodeCrypto.js\";\nimport * as NodeFileSystem from \"./NodeFileSystem.js\";\nimport * as NodePath from \"./NodePath.js\";\nimport * as NodeStdio from \"./NodeStdio.js\";\nimport * as NodeTerminal from \"./NodeTerminal.js\";\n/**\n * Provides the default Node implementations for child process spawning,\n * filesystem, path, stdio, and terminal services.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layer = /*#__PURE__*/Layer.provideMerge(NodeChildProcessSpawner.layer, /*#__PURE__*/Layer.mergeAll(NodeFileSystem.layer, NodeCrypto.layer, NodePath.layer, NodeStdio.layer, NodeTerminal.layer));\n//# sourceMappingURL=NodeServices.js.map","/**\n * Node.js implementation of the Effect `HttpServer`.\n *\n * This module adapts a supplied Node `http.Server` into Effect's\n * platform-independent HTTP server service. It starts the server with Node\n * `listen` options, converts `request` events into `HttpServerRequest` values,\n * writes `HttpServerResponse` bodies through Node's `ServerResponse`, and\n * handles `upgrade` events by exposing the upgraded socket through\n * `HttpServerRequest.upgrade`. It also exports request and upgrade handler\n * constructors plus layers for the server alone, HTTP support services, the\n * combined server, configurable options, and tests.\n *\n * @since 4.0.0\n */\nimport * as Cause from \"effect/Cause\";\nimport * as Config from \"effect/Config\";\nimport * as Context from \"effect/Context\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Fiber from \"effect/Fiber\";\nimport { flow } from \"effect/Function\";\nimport * as Latch from \"effect/Latch\";\nimport * as Layer from \"effect/Layer\";\nimport * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\nimport * as Cookies from \"effect/unstable/http/Cookies\";\nimport * as Etag from \"effect/unstable/http/Etag\";\nimport * as FetchHttpClient from \"effect/unstable/http/FetchHttpClient\";\nimport * as HttpEffect from \"effect/unstable/http/HttpEffect\";\nimport * as HttpIncomingMessage from \"effect/unstable/http/HttpIncomingMessage\";\nimport * as HttpServer from \"effect/unstable/http/HttpServer\";\nimport { causeResponse, ClientAbort, HttpServerError, RequestParseError, ResponseError, ServeError } from \"effect/unstable/http/HttpServerError\";\nimport * as Request from \"effect/unstable/http/HttpServerRequest\";\nimport { HttpServerRequest } from \"effect/unstable/http/HttpServerRequest\";\nimport * as Socket from \"effect/unstable/socket/Socket\";\nimport * as Http from \"node:http\";\nimport { Readable } from \"node:stream\";\nimport { pipeline } from \"node:stream/promises\";\nimport { NodeHttpIncomingMessage } from \"./NodeHttpIncomingMessage.js\";\nimport * as NodeHttpPlatform from \"./NodeHttpPlatform.js\";\nimport * as NodeMultipart from \"./NodeMultipart.js\";\nimport * as NodeServices from \"./NodeServices.js\";\nimport { NodeWS } from \"./NodeSocket.js\";\n/**\n * Creates a scoped `HttpServer` from a Node `http.Server`, starts listening\n * with the supplied options, registers request and upgrade handling, and closes\n * the server during scope finalization with optional graceful-shutdown control.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = /*#__PURE__*/Effect.fnUntraced(function* (evaluate, options) {\n const scope = yield* Effect.scope;\n const server = evaluate();\n const shutdown = yield* Effect.callback(resume => {\n if (!server.listening) {\n return resume(Effect.void);\n }\n server.close(error => {\n if (error) {\n resume(Effect.die(error));\n } else {\n resume(Effect.void);\n }\n });\n }).pipe(Effect.cached);\n const preemptiveShutdown = options.disablePreemptiveShutdown ? Effect.void : Effect.timeoutOrElse(shutdown, {\n duration: options.gracefulShutdownTimeout ?? Duration.seconds(20),\n orElse: () => Effect.void\n });\n yield* Scope.addFinalizer(scope, shutdown);\n yield* Effect.callback(resume => {\n function onError(cause) {\n resume(Effect.fail(new ServeError({\n cause\n })));\n }\n server.on(\"error\", onError);\n server.listen(options, () => {\n server.off(\"error\", onError);\n resume(Effect.void);\n });\n });\n const address = server.address();\n const wss = yield* Effect.acquireRelease(Effect.sync(() => new NodeWS.WebSocketServer({\n ...options.websocket,\n noServer: true\n })), wss => Effect.callback(resume => {\n wss.close(() => resume(Effect.void));\n })).pipe(Scope.provide(scope), Effect.cached);\n return HttpServer.make({\n address: typeof address === \"string\" ? {\n _tag: \"UnixAddress\",\n path: address\n } : {\n _tag: \"TcpAddress\",\n hostname: address.address === \"::\" ? \"0.0.0.0\" : address.address,\n port: address.port\n },\n serve: Effect.fnUntraced(function* (httpApp, middleware) {\n const serveScope = yield* Effect.scope;\n const scope = Scope.forkUnsafe(serveScope, \"parallel\");\n const handler = yield* makeHandler(httpApp, {\n middleware: middleware,\n scope\n });\n const upgradeHandler = yield* makeUpgradeHandler(wss, httpApp, {\n middleware: middleware,\n scope\n });\n yield* Scope.addFinalizerExit(serveScope, () => {\n server.off(\"request\", handler);\n server.off(\"upgrade\", upgradeHandler);\n return preemptiveShutdown;\n });\n server.on(\"request\", handler);\n server.on(\"upgrade\", upgradeHandler);\n })\n });\n});\n/**\n * Creates a Node `request` event handler for an Effect HTTP application,\n * injecting a `HttpServerRequest` and interrupting the request fiber if the\n * client closes the response before it finishes.\n *\n * @category handlers\n * @since 4.0.0\n */\nexport const makeHandler = (httpEffect, options) => {\n const handled = HttpEffect.toHandled(httpEffect, handleResponse, options.middleware);\n return Effect.withFiber(parent => {\n const services = parent.context;\n return Effect.succeed(function handler(nodeRequest, nodeResponse) {\n const context = Context.add(services, HttpServerRequest, new ServerRequestImpl(nodeRequest, nodeResponse));\n const fiber = Fiber.runIn(Effect.runForkWith(context)(handled), options.scope);\n nodeResponse.on(\"close\", () => {\n if (!nodeResponse.writableEnded) {\n fiber.interruptUnsafe(parent.id, ClientAbort.annotation);\n }\n });\n });\n });\n};\n/**\n * Creates a Node `upgrade` event handler for an Effect HTTP application,\n * exposing the upgraded WebSocket as the request's `upgrade` effect and\n * interrupting the request fiber when the socket closes early.\n *\n * @category handlers\n * @since 4.0.0\n */\nexport const makeUpgradeHandler = (lazyWss, httpEffect, options) => {\n const handledApp = HttpEffect.toHandled(httpEffect, handleResponse, options.middleware);\n return Effect.withFiber(parent => {\n const services = parent.context;\n return Effect.succeed(function handler(nodeRequest, socket, head) {\n let nodeResponse_ = undefined;\n const nodeResponse = () => {\n if (nodeResponse_ === undefined) {\n nodeResponse_ = new Http.ServerResponse(nodeRequest);\n nodeResponse_.assignSocket(socket);\n nodeResponse_.on(\"finish\", () => {\n socket.end();\n });\n }\n return nodeResponse_;\n };\n const upgradeEffect = Socket.fromWebSocket(Effect.flatMap(lazyWss, wss => Effect.acquireRelease(Effect.callback(resume => wss.handleUpgrade(nodeRequest, socket, head, ws => {\n resume(Effect.succeed(ws));\n })), ws => Effect.sync(() => ws.close()))));\n const context = Context.add(services, HttpServerRequest, new ServerRequestImpl(nodeRequest, nodeResponse, upgradeEffect));\n const fiber = Fiber.runIn(Effect.runForkWith(context)(handledApp), options.scope);\n socket.on(\"error\", () => {});\n socket.on(\"close\", () => {\n if (!socket.writableEnded) {\n fiber.interruptUnsafe(parent.id, ClientAbort.annotation);\n }\n });\n });\n });\n};\nclass ServerRequestImpl extends NodeHttpIncomingMessage {\n [Request.TypeId];\n response;\n upgradeEffect;\n url;\n headersOverride;\n constructor(source, response, upgradeEffect, url = source.url, headersOverride, remoteAddressOverride) {\n super(source, cause => new HttpServerError({\n reason: new RequestParseError({\n request: this,\n cause\n })\n }), remoteAddressOverride);\n this[Request.TypeId] = Request.TypeId;\n this.response = response;\n this.upgradeEffect = upgradeEffect;\n this.url = url;\n this.headersOverride = headersOverride;\n }\n cachedCookies;\n get cookies() {\n if (this.cachedCookies) {\n return this.cachedCookies;\n }\n return this.cachedCookies = Cookies.parseHeader(this.headers.cookie ?? \"\");\n }\n get resolvedResponse() {\n return typeof this.response === \"function\" ? this.response() : this.response;\n }\n modify(options) {\n return new ServerRequestImpl(this.source, this.response, this.upgradeEffect, options.url ?? this.url, options.headers ?? this.headersOverride, \"remoteAddress\" in options ? options.remoteAddress : this.remoteAddressOverride);\n }\n get originalUrl() {\n return this.source.url;\n }\n cachedMethod;\n get method() {\n return this.cachedMethod ??= this.source.method.toUpperCase();\n }\n get headers() {\n this.headersOverride ??= this.source.headers;\n return this.headersOverride;\n }\n multipartEffect;\n get multipart() {\n if (this.multipartEffect) {\n return this.multipartEffect;\n }\n this.multipartEffect = Effect.runSync(Effect.cached(NodeMultipart.persisted(this.source, this.source.headers)));\n return this.multipartEffect;\n }\n get multipartStream() {\n return NodeMultipart.stream(this.source, this.source.headers);\n }\n get upgrade() {\n return this.upgradeEffect ?? Effect.fail(new HttpServerError({\n reason: new RequestParseError({\n request: this,\n description: \"not an upgradeable ServerRequest\"\n })\n }));\n }\n toString() {\n return `ServerRequest(${this.method} ${this.url})`;\n }\n toJSON() {\n return HttpIncomingMessage.inspect(this, {\n _id: \"HttpServerRequest\",\n method: this.method,\n url: this.originalUrl\n });\n }\n}\n/**\n * Provides an `HttpServer` by creating and managing a scoped Node\n * `http.Server` with the supplied listen and shutdown options.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerServer = /*#__PURE__*/flow(make, /*#__PURE__*/Layer.effect(HttpServer.HttpServer));\n/**\n * Provides the Node HTTP support services used by `NodeHttpServer`, including\n * the HTTP platform, ETag generator, and core Node platform services.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerHttpServices = /*#__PURE__*/Layer.mergeAll(NodeHttpPlatform.layer, Etag.layerWeak, NodeServices.layer);\n/**\n * Provides a Node `HttpServer` together with the Node HTTP platform, ETag, and\n * core platform services required to serve requests.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layer = (evaluate, options) => Layer.mergeAll(layerServer(evaluate, options), layerHttpServices);\n/**\n * Provides a Node `HttpServer` together with the Node HTTP platform, ETag,\n * and core Node platform services, reading the listen and shutdown options from\n * a `Config` value.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerConfig = (evaluate, options) => Layer.mergeAll(Layer.effect(HttpServer.HttpServer)(Effect.flatMap(Config.unwrap(options), options => make(evaluate, options))), layerHttpServices);\n/**\n * Provides a test HTTP server listening on an ephemeral port together with a\n * Fetch-backed `HttpClient` configured for server integration tests.\n *\n * @category testing\n * @since 4.0.0\n */\nexport const layerTest = /*#__PURE__*/HttpServer.layerTestClient.pipe(/*#__PURE__*/Layer.provide(/*#__PURE__*/Layer.fresh(FetchHttpClient.layer).pipe(/*#__PURE__*/Layer.provide(/*#__PURE__*/Layer.succeed(FetchHttpClient.RequestInit)({\n keepalive: false\n})))), /*#__PURE__*/Layer.provideMerge(/*#__PURE__*/layer(Http.createServer, {\n port: 0\n})));\n// -----------------------------------------------------------------------------\n// Internal\n// -----------------------------------------------------------------------------\nconst handleResponse = (request, response) => {\n const nodeResponse = request.resolvedResponse;\n if (nodeResponse.writableEnded) {\n return Effect.void;\n }\n let headers = response.headers;\n if (!Cookies.isEmpty(response.cookies)) {\n headers = {\n ...headers\n };\n const toSet = Cookies.toSetCookieHeaders(response.cookies);\n if (headers[\"set-cookie\"] !== undefined) {\n toSet.push(headers[\"set-cookie\"]);\n }\n headers[\"set-cookie\"] = toSet;\n }\n if (request.method === \"HEAD\") {\n nodeResponse.writeHead(response.status, headers);\n return Effect.andThen(cancelResponseBody(response.body), Effect.callback(resume => {\n let completed = false;\n const done = () => {\n if (completed) return;\n completed = true;\n nodeResponse.off(\"close\", done);\n resume(Effect.void);\n };\n nodeResponse.once(\"close\", done);\n nodeResponse.end(done);\n }));\n }\n const body = response.body;\n switch (body._tag) {\n case \"Empty\":\n {\n nodeResponse.writeHead(response.status, headers);\n nodeResponse.end();\n return Effect.void;\n }\n case \"Raw\":\n {\n nodeResponse.writeHead(response.status, headers);\n if (typeof body.body === \"object\" && body.body !== null && \"pipe\" in body.body && typeof body.body.pipe === \"function\") {\n return Effect.tryPromise({\n try: signal => pipeline(body.body, nodeResponse, {\n signal,\n end: true\n }),\n catch: cause => new HttpServerError({\n reason: new ResponseError({\n request,\n response,\n description: \"Error writing raw response\",\n cause\n })\n })\n }).pipe(Effect.interruptible, Effect.tapCause(handleCause(nodeResponse, response)));\n }\n return Effect.callback(resume => {\n nodeResponse.end(body.body, () => resume(Effect.void));\n });\n }\n case \"Uint8Array\":\n {\n nodeResponse.writeHead(response.status, headers);\n // If the body is less than 1MB, we skip the callback\n if (body.body.length < 1024 * 1024) {\n nodeResponse.end(body.body);\n return Effect.void;\n }\n return Effect.callback(resume => {\n nodeResponse.end(body.body, () => resume(Effect.void));\n });\n }\n case \"FormData\":\n {\n return Effect.suspend(() => {\n const r = new globalThis.Response(body.formData);\n nodeResponse.writeHead(response.status, {\n ...headers,\n ...Object.fromEntries(r.headers)\n });\n return Effect.callback((resume, signal) => {\n Readable.fromWeb(r.body, {\n signal\n }).pipe(nodeResponse).on(\"error\", cause => {\n resume(Effect.fail(new HttpServerError({\n reason: new ResponseError({\n request,\n response,\n description: \"Error writing FormData response\",\n cause\n })\n })));\n }).once(\"finish\", () => {\n resume(Effect.void);\n });\n }).pipe(Effect.interruptible, Effect.tapCause(handleCause(nodeResponse, response)));\n });\n }\n case \"Stream\":\n {\n nodeResponse.writeHead(response.status, headers);\n const drainLatch = Latch.makeUnsafe();\n nodeResponse.on(\"drain\", () => drainLatch.openUnsafe());\n return body.stream.pipe(Stream.orDie, Stream.runForEachArray(array => {\n const chunk = array.length > 1 ? Buffer.concat(array) : array[0];\n if (nodeResponse.write(chunk)) return Effect.void;\n drainLatch.closeUnsafe();\n return drainLatch.await;\n }), Effect.interruptible, Effect.matchCauseEffect({\n onSuccess: () => Effect.sync(() => nodeResponse.end()),\n onFailure: handleCause(nodeResponse, response)\n }));\n }\n }\n};\nconst cancelResponseBody = body => {\n const stream = body._tag === \"Raw\" ? body.body : undefined;\n if (stream instanceof Readable) {\n return Effect.sync(() => stream.destroy());\n }\n return Effect.void;\n};\nconst handleCause = (nodeResponse, originalResponse) => originalCause => Effect.flatMap(causeResponse(originalCause), ([response, cause]) => {\n const headersSent = nodeResponse.headersSent;\n if (!headersSent) {\n nodeResponse.writeHead(response.status);\n }\n if (!nodeResponse.writableEnded) {\n nodeResponse.end();\n }\n return Effect.failCause(headersSent ? Cause.combine(originalCause, Cause.die(originalResponse)) : cause);\n});\n//# sourceMappingURL=NodeHttpServer.js.map","import * as Runtime from \"effect/Runtime\";\n/**\n * Runs an Effect as the Node process main program, interrupting the fiber on\n * `SIGINT` or `SIGTERM` and invoking the configured teardown to determine the\n * process exit code.\n *\n * @category running\n * @since 4.0.0\n */\nexport const runMain = /*#__PURE__*/Runtime.makeRunMain(({\n fiber,\n teardown\n}) => {\n let receivedSignal = false;\n fiber.addObserver(exit => {\n process.removeListener(\"SIGINT\", onSigint);\n process.removeListener(\"SIGTERM\", onSigint);\n teardown(exit, code => {\n if (receivedSignal || code !== 0) {\n process.exit(code);\n }\n });\n });\n function onSigint() {\n receivedSignal = true;\n fiber.interruptUnsafe(fiber.id);\n }\n process.on(\"SIGINT\", onSigint);\n process.on(\"SIGTERM\", onSigint);\n});\n//# sourceMappingURL=NodeRuntime.js.map","/**\n * Node.js process runner for Effect programs.\n *\n * This module exports `runMain`, which runs one Effect as the main process\n * fiber in Node.js. It reuses the shared Node runtime runner, including its\n * error reporting, `SIGINT` / `SIGTERM` interruption, and optional teardown\n * behavior.\n *\n * @since 4.0.0\n */\nimport * as NodeRuntime from \"@effect/platform-node-shared/NodeRuntime\";\n/**\n * Helps you run a main effect with built-in error handling, logging, and signal management.\n *\n * **When to use**\n *\n * Use to run a Node.js application's main Effect with structured error\n * handling, log management, interrupt support, or advanced teardown\n * capabilities.\n *\n * **Details**\n *\n * This function launches an Effect as the main entry point, setting exit codes\n * based on success or failure, handling interrupts (e.g., Ctrl+C), and optionally\n * logging errors. By default, it logs errors and uses a \"pretty\" format, but both\n * behaviors can be turned off. You can also provide custom teardown logic to\n * finalize resources or produce different exit codes.\n *\n * The optional configuration object can include:\n * - `disableErrorReporting`: Turn off automatic error logging.\n * - `teardown`: Provide custom finalization logic.\n *\n * @category running\n * @since 4.0.0\n */\nexport const runMain = NodeRuntime.runMain;\n//# sourceMappingURL=NodeRuntime.js.map","","import { Predicate, Schema } from \"effect\";\n//#region src/runtime/value.ts\nconst TransportValueSchema = Schema.suspend(() => Schema.Union([\n\tSchema.Null,\n\tSchema.Boolean,\n\tSchema.Finite,\n\tSchema.String,\n\tSchema.Date,\n\tSchema.Array(TransportValueSchema),\n\tSchema.Record(Schema.String, Schema.UndefinedOr(TransportValueSchema))\n]));\nconst encodeTransportValue = (value) => {\n\tif (Predicate.isDate(value)) return Schema.encodeSync(Schema.DateFromMillis)(value);\n\tif (globalThis.Array.isArray(value)) return value.map(encodeTransportValue);\n\tif (Predicate.isNumber(value)) return Schema.decodeSync(Schema.Finite)(value);\n\tif (Predicate.isNull(value) || Predicate.isString(value) || Predicate.isBoolean(value)) return value;\n\treturn Object.fromEntries(Object.entries(value).flatMap(([key, child]) => child === void 0 ? [] : [[key, encodeTransportValue(child)]]));\n};\nconst encodeTransportObject = (value) => Schema.decodeUnknownSync(Schema.JsonObject)(encodeTransportValue(Schema.decodeUnknownSync(TransportValueSchema)(value)));\nconst collectDatePaths = (value, path, paths) => {\n\tif (Predicate.isDate(value)) {\n\t\tSchema.decodeSync(Schema.Date)(value);\n\t\tpaths.push(path);\n\t\treturn;\n\t}\n\tif (globalThis.Array.isArray(value)) {\n\t\tfor (const [index, child] of value.entries()) collectDatePaths(child, [...path, index], paths);\n\t\treturn;\n\t}\n\tif (value === void 0 || Predicate.isNull(value) || Predicate.isString(value) || Predicate.isNumber(value) || Predicate.isBoolean(value)) return;\n\tfor (const [key, child] of Object.entries(value)) collectDatePaths(child, [...path, key], paths);\n};\nconst datePathsOf = (value) => {\n\tconst paths = [];\n\tcollectDatePaths(value, [], paths);\n\treturn paths;\n};\nconst datePathsOfObject = (value) => datePathsOf(Schema.decodeUnknownSync(TransportValueSchema)(value));\nconst pathKey = (path) => JSON.stringify(path);\nconst decodeTransportValueAt = (value, path, encodedDatePaths) => {\n\tif (encodedDatePaths.has(pathKey(path))) return Schema.decodeUnknownSync(Schema.DateFromMillis)(value);\n\tif (globalThis.Array.isArray(value)) return value.map((item, index) => decodeTransportValueAt(item, [...path, index], encodedDatePaths));\n\tif (Predicate.isNull(value) || Predicate.isString(value) || Predicate.isNumber(value) || Predicate.isBoolean(value)) return value;\n\treturn Object.fromEntries(Object.entries(value).map(([key, item]) => [key, decodeTransportValueAt(item, [...path, key], encodedDatePaths)]));\n};\nconst decodeTransportValue = (value, datePaths) => decodeTransportValueAt(value, [], new Set(datePaths.map(pathKey)));\nconst decodeTransportObject = (value, datePaths) => {\n\tconst encodedDatePaths = new Set(datePaths.map(pathKey));\n\treturn Object.fromEntries(Object.entries(value).map(([key, child]) => [key, decodeTransportValueAt(child, [key], encodedDatePaths)]));\n};\n//#endregion\nexport { decodeTransportValue as a, decodeTransportObject as i, datePathsOf as n, encodeTransportObject as o, datePathsOfObject as r, encodeTransportValue as s, TransportValueSchema as t };\n\n//# sourceMappingURL=value-Briqf-Ua.js.map","import { a as decodeTransportValue, i as decodeTransportObject, n as datePathsOf, o as encodeTransportObject, r as datePathsOfObject, s as encodeTransportValue, t as TransportValueSchema } from \"../value-Briqf-Ua.js\";\nimport { Schema } from \"effect\";\n//#region src/runtime/sync.ts\nconst FunctionNamePart = Schema.String.check(Schema.isPattern(/^[A-Za-z_$][A-Za-z0-9_$]*$/));\nconst ApiFunctionAddressParts = Schema.TemplateLiteralParser([\n\t\"api.\",\n\tFunctionNamePart,\n\t\".\",\n\tFunctionNamePart\n]);\nconst FunctionAddress = Schema.TemplateLiteral([\n\t\"api.\",\n\tFunctionNamePart,\n\t\".\",\n\tFunctionNamePart\n]);\nconst apiFunctionParts = (address) => {\n\tconst [, moduleName, , functionName] = Schema.decodeSync(ApiFunctionAddressParts)(address);\n\treturn {\n\t\tfunctionName,\n\t\tmoduleName\n\t};\n};\nconst SubscriptionId = Schema.Natural.pipe(Schema.brand(\"ignotum/sync/SubscriptionId\"));\nconst RequestId = Schema.Natural.pipe(Schema.brand(\"ignotum/sync/RequestId\"));\nconst Subscribe = Schema.Struct({\n\ttype: Schema.Literal(\"Subscribe\"),\n\tid: SubscriptionId,\n\tfunction: FunctionAddress,\n\targs: Schema.Json\n});\nconst Unsubscribe = Schema.Struct({\n\ttype: Schema.Literal(\"Unsubscribe\"),\n\tid: SubscriptionId\n});\nconst Mutate = Schema.Struct({\n\ttype: Schema.Literal(\"Mutate\"),\n\tid: RequestId,\n\tfunction: FunctionAddress,\n\targs: Schema.Json\n});\nconst ClientMessage = Schema.Union([\n\tSubscribe,\n\tUnsubscribe,\n\tMutate\n]);\nconst QueryOperation = Schema.Struct({\n\ttype: Schema.Literal(\"Query\"),\n\tid: SubscriptionId\n});\nconst MutateOperation = Schema.Struct({\n\ttype: Schema.Literal(\"Mutate\"),\n\tid: RequestId\n});\nconst Operation = Schema.Union([QueryOperation, MutateOperation]);\nconst DatePath = Schema.Array(Schema.Union([Schema.String, Schema.Natural]));\nconst DatePaths = Schema.Array(DatePath);\nconst WireResult = Schema.Union([Schema.Struct({\n\ttype: Schema.Literal(\"Success\"),\n\tvalue: Schema.optional(Schema.Json),\n\tdates: Schema.optional(DatePaths)\n}), Schema.Struct({\n\ttype: Schema.Literal(\"Failure\"),\n\terror: Schema.Json,\n\tdates: Schema.optional(DatePaths)\n})]);\nconst QuerySnapshot = Schema.Struct({\n\ttype: Schema.Literal(\"QuerySnapshot\"),\n\tid: SubscriptionId,\n\tresult: WireResult\n});\nconst MutationResult = Schema.Struct({\n\ttype: Schema.Literal(\"MutationResult\"),\n\tid: RequestId,\n\tresult: WireResult\n});\nconst ProtocolErrorCode = Schema.Literals([\n\t\"DuplicateOperationId\",\n\t\"FunctionUnavailable\",\n\t\"InvalidArguments\",\n\t\"InvalidMessage\",\n\t\"UnknownFunction\",\n\t\"WrongFunctionKind\"\n]);\nconst ProtocolError = Schema.Struct({\n\ttype: Schema.Literal(\"ProtocolError\"),\n\toperation: Schema.optional(Operation),\n\tcode: ProtocolErrorCode,\n\tmessage: Schema.String\n});\nconst ServerMessage = Schema.Union([\n\tQuerySnapshot,\n\tMutationResult,\n\tProtocolError\n]);\nconst ClientMessageJson = Schema.fromJsonString(ClientMessage);\nconst ServerMessageJson = Schema.fromJsonString(ServerMessage);\n//#endregion\nexport { ClientMessage, ClientMessageJson, DatePath, FunctionAddress, FunctionNamePart, Operation, ProtocolErrorCode, RequestId, ServerMessage, ServerMessageJson, SubscriptionId, TransportValueSchema, WireResult, apiFunctionParts, datePathsOf, datePathsOfObject, decodeTransportObject, decodeTransportValue, encodeTransportObject, encodeTransportValue };\n\n//# sourceMappingURL=sync.js.map","import { Array, Effect, FileSystem, Path, Schema, String } from \"effect\";\n\nimport { FunctionNamePart } from \"@ignotum/contracts/runtime/sync\";\n\nconst generatedHeader = \"// Generated by `ignotum codegen`. Do not edit.\";\n\nexport class SchemaNotFound extends Schema.TaggedError<SchemaNotFound>()(\"SchemaNotFound\", {\n message: Schema.String,\n path: Schema.String,\n}) {}\n\nexport class InvalidFunctionModuleName extends Schema.TaggedError<InvalidFunctionModuleName>()(\n \"InvalidFunctionModuleName\",\n {\n message: Schema.String,\n path: Schema.String,\n },\n) {}\n\nexport class GeneratedFileConflict extends Schema.TaggedError<GeneratedFileConflict>()(\n \"GeneratedFileConflict\",\n {\n message: Schema.String,\n path: Schema.String,\n },\n) {}\n\ninterface GeneratedOutput {\n readonly content: string;\n readonly path: string;\n}\n\nexport interface CodegenResult {\n readonly functionModules: ReadonlyArray<string>;\n readonly written: ReadonlyArray<string>;\n readonly unchanged: ReadonlyArray<string>;\n}\n\nconst isFunctionModuleFile = (fileName: string): boolean =>\n fileName.endsWith(\".ts\") &&\n !fileName.endsWith(\".test.ts\") &&\n !fileName.endsWith(\".spec.ts\") &&\n fileName !== \"index.ts\" &&\n fileName !== \"schema.ts\" &&\n !fileName.startsWith(\"_\");\n\nconst moduleNameFromFile = (filePath: string, fileName: string) => {\n const moduleName = fileName.slice(0, -\".ts\".length);\n\n return Schema.decodeEffect(FunctionNamePart)(moduleName).pipe(\n Effect.mapError(() =>\n InvalidFunctionModuleName.make({\n message: `Server function file names must be valid TypeScript identifiers. Rename ${fileName}.`,\n path: filePath,\n }),\n ),\n );\n};\n\nconst renderServerBindings = (): string => `${generatedHeader}\n\nimport { bindSchema } from \"ignotum/internal/server\";\n\nimport schema from \"../server/schema.js\";\n\nexport const { mutation, query, values } = bindSchema(schema);\n`;\n\nconst renderTypes = (): string => `${generatedHeader}\n\nimport type {\n Document as DocumentFor,\n Id as IdFor,\n SchemaDefinitionOf,\n} from \"ignotum/internal/types\";\n\nimport type schema from \"../server/schema.js\";\n\nexport type DataModel = SchemaDefinitionOf<typeof schema>;\nexport type Doc<TableName extends Extract<keyof DataModel, string>> = DocumentFor<\n DataModel,\n TableName\n>;\nexport type Id<TableName extends Extract<keyof DataModel, string>> = IdFor<TableName>;\n`;\n\nconst renderApi = (moduleNames: ReadonlyArray<string>): string => {\n const modules = Array.match(moduleNames, {\n onEmpty: () => \" // No server function modules found.\",\n onNonEmpty: (names) =>\n Array.join(\n Array.map(\n names,\n (moduleName) => ` readonly ${moduleName}: typeof import(\"../server/${moduleName}.js\");`,\n ),\n \"\\n\",\n ),\n });\n return `${generatedHeader}\n\nimport { createApi } from \"ignotum/internal/api\";\n\ntype Modules = {\n${modules}\n};\n\nexport const api = createApi<Modules>();\n`;\n};\n\nconst inspectOutput = Effect.fn(\"Codegen.inspectOutput\")(function* (output: GeneratedOutput) {\n const fileSystem = yield* FileSystem.FileSystem;\n const exists = yield* fileSystem.exists(output.path);\n\n if (!exists) {\n return \"write\" as const;\n }\n\n const current = yield* fileSystem.readFileString(output.path);\n\n if (current === output.content) {\n return \"unchanged\" as const;\n }\n\n if (!current.startsWith(generatedHeader)) {\n return yield* GeneratedFileConflict.make({\n message: `Refusing to overwrite ${output.path} because it was not created by Ignotum.`,\n path: output.path,\n });\n }\n\n return \"write\" as const;\n});\n\nconst writeOutput = Effect.fn(\"Codegen.writeOutput\")(function* (output: GeneratedOutput) {\n const fileSystem = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const directory = path.dirname(output.path);\n\n yield* fileSystem.makeDirectory(directory, { recursive: true });\n yield* Effect.scoped(\n Effect.gen(function* () {\n const temporaryPath = yield* fileSystem.makeTempFileScoped({\n directory,\n prefix: \".ignotum-\",\n suffix: \".ts\",\n });\n\n yield* fileSystem.writeFileString(temporaryPath, output.content);\n yield* fileSystem.rename(temporaryPath, output.path);\n }),\n );\n});\n\nexport const generate = Effect.fn(\"Codegen.generate\")(function* (projectDirectory: string) {\n const fileSystem = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const serverDirectory = path.join(projectDirectory, \"server\");\n const schemaPath = path.join(serverDirectory, \"schema.ts\");\n const schemaExists = yield* fileSystem.exists(schemaPath);\n\n if (!schemaExists) {\n return yield* SchemaNotFound.make({\n message: `No Ignotum schema found at ${schemaPath}.`,\n path: schemaPath,\n });\n }\n\n const entries = yield* fileSystem.readDirectory(serverDirectory);\n const functionFiles = Array.sort(String.Order)(Array.filter(entries, isFunctionModuleFile));\n const functionModules = yield* Effect.forEach(functionFiles, (fileName) =>\n moduleNameFromFile(path.join(serverDirectory, fileName), fileName),\n );\n const outputs: ReadonlyArray<GeneratedOutput> = [\n {\n content: renderServerBindings(),\n path: path.join(projectDirectory, \"_generated\", \"server.ts\"),\n },\n {\n content: renderApi(functionModules),\n path: path.join(projectDirectory, \"_generated\", \"api.ts\"),\n },\n {\n content: renderTypes(),\n path: path.join(projectDirectory, \"_generated\", \"types.ts\"),\n },\n ];\n const inspections = yield* Effect.forEach(outputs, inspectOutput);\n const inspectedOutputs = Array.zip(outputs, inspections);\n const outputsToWrite = Array.map(\n Array.filter(inspectedOutputs, ([, inspection]) => inspection === \"write\"),\n ([output]) => output,\n );\n const unchanged = Array.map(\n Array.filter(inspectedOutputs, ([, inspection]) => inspection === \"unchanged\"),\n ([output]) => output.path,\n );\n const written = Array.map(outputsToWrite, (output) => output.path);\n\n yield* Effect.forEach(outputsToWrite, writeOutput, { discard: true });\n\n return { functionModules, unchanged, written } satisfies CodegenResult;\n});\n","import { Crypto, Effect, FileSystem, Option, Path, Predicate, Schema } from \"effect\";\n\nconst databaseFileNames = [\"state.db\", \"state.db-shm\", \"state.db-wal\", \"state.db-journal\"] as const;\nconst lockFileName = \"lock.json\";\n\nconst DevDatabaseLockRecord = Schema.Struct({\n pid: Schema.Int,\n token: Schema.String,\n});\nconst DevDatabaseLockRecordJson = Schema.fromJsonString(DevDatabaseLockRecord);\ntype DevDatabaseLockRecord = typeof DevDatabaseLockRecord.Type;\n\nexport class DevDatabaseResetFailed extends Schema.TaggedError<DevDatabaseResetFailed>()(\n \"DevDatabaseResetFailed\",\n {\n cause: Schema.Defect(),\n message: Schema.String,\n path: Schema.String,\n },\n) {}\n\nexport class DevDatabaseInUse extends Schema.TaggedError<DevDatabaseInUse>()(\"DevDatabaseInUse\", {\n message: Schema.String,\n path: Schema.String,\n pid: Schema.Int,\n}) {}\n\nexport class DevDatabaseLockFailed extends Schema.TaggedError<DevDatabaseLockFailed>()(\n \"DevDatabaseLockFailed\",\n {\n cause: Schema.Defect(),\n message: Schema.String,\n path: Schema.String,\n },\n) {}\n\nexport const devDatabasePath = Effect.fn(\"DevDatabase.path\")(function* (projectDirectory: string) {\n const path = yield* Path.Path;\n return path.join(projectDirectory, \".ignotum\", \"dev\", \"state.db\");\n});\n\nconst processIsRunning = (pid: number): boolean => {\n try {\n process.kill(pid, 0);\n return true;\n } catch (cause) {\n return !(Predicate.hasProperty(cause, \"code\") && cause.code === \"ESRCH\");\n }\n};\n\nexport const acquireDevDatabaseLock = Effect.fn(\"DevDatabase.acquireLock\")(function* (\n projectDirectory: string,\n) {\n const crypto = yield* Crypto.Crypto;\n const fileSystem = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const databasePath = yield* devDatabasePath(projectDirectory);\n const directory = path.dirname(databasePath);\n const lockPath = path.join(directory, lockFileName);\n const record: DevDatabaseLockRecord = {\n pid: process.pid,\n token: yield* crypto.randomUUIDv4,\n };\n const encoded = yield* Schema.encodeEffect(DevDatabaseLockRecordJson)(record).pipe(\n Effect.mapError((cause) =>\n DevDatabaseLockFailed.make({\n cause,\n message: `Could not encode the development database lock at ${lockPath}.`,\n path: lockPath,\n }),\n ),\n );\n\n yield* fileSystem.makeDirectory(directory, { recursive: true }).pipe(\n Effect.mapError((cause) =>\n DevDatabaseLockFailed.make({\n cause,\n message: `Could not create the development state directory at ${directory}.`,\n path: lockPath,\n }),\n ),\n );\n\n const createLock = () =>\n fileSystem.writeFileString(lockPath, encoded, { flag: \"wx\" }).pipe(\n Effect.matchEffect({\n onFailure: (cause) =>\n cause.reason._tag === \"AlreadyExists\"\n ? Effect.succeed(false)\n : DevDatabaseLockFailed.make({\n cause,\n message: `Could not create the development database lock at ${lockPath}.`,\n path: lockPath,\n }),\n onSuccess: () => Effect.succeed(true),\n }),\n );\n\n const readLock = Effect.fn(\"DevDatabase.readLock\")(function* () {\n const content = yield* fileSystem.readFileString(lockPath).pipe(\n Effect.mapError((cause) =>\n DevDatabaseLockFailed.make({\n cause,\n message: `Could not read the development database lock at ${lockPath}.`,\n path: lockPath,\n }),\n ),\n );\n return yield* Schema.decodeEffect(DevDatabaseLockRecordJson)(content).pipe(\n Effect.mapError((cause) =>\n DevDatabaseLockFailed.make({\n cause,\n message: `The development database lock at ${lockPath} is invalid. Remove it and try again.`,\n path: lockPath,\n }),\n ),\n );\n });\n\n const failInUse = (current: DevDatabaseLockRecord) =>\n DevDatabaseInUse.make({\n message: `Another Ignotum development server is using ${databasePath} with process ${current.pid}.`,\n path: lockPath,\n pid: current.pid,\n });\n\n const acquire = Effect.gen(function* () {\n if (yield* createLock()) return record;\n\n const current = yield* readLock();\n if (processIsRunning(current.pid)) return yield* failInUse(current);\n\n yield* fileSystem.remove(lockPath).pipe(\n Effect.mapError((cause) =>\n DevDatabaseLockFailed.make({\n cause,\n message: `Could not remove the stale development database lock at ${lockPath}.`,\n path: lockPath,\n }),\n ),\n );\n\n if (yield* createLock()) return record;\n return yield* failInUse(yield* readLock());\n });\n\n const release = (owned: DevDatabaseLockRecord) =>\n Effect.gen(function* () {\n if (!(yield* fileSystem.exists(lockPath))) return;\n const content = yield* fileSystem.readFileString(lockPath);\n const current = Schema.decodeOption(DevDatabaseLockRecordJson)(content);\n if (Option.isNone(current) || current.value.token !== owned.token) return;\n yield* fileSystem.remove(lockPath);\n }).pipe(\n Effect.catchCause((cause) =>\n Effect.logWarning(`Could not release the development database lock at ${lockPath}.`).pipe(\n Effect.annotateLogs({ cause }),\n ),\n ),\n );\n\n yield* Effect.acquireRelease(acquire, release);\n});\n\nexport const resetDevDatabase = Effect.fn(\"DevDatabase.reset\")(function* (\n projectDirectory: string,\n) {\n return yield* Effect.scoped(\n Effect.gen(function* () {\n yield* acquireDevDatabaseLock(projectDirectory);\n const fileSystem = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const directory = path.join(projectDirectory, \".ignotum\", \"dev\");\n const databasePath = yield* devDatabasePath(projectDirectory);\n let removed = 0;\n\n yield* Effect.forEach(\n databaseFileNames,\n Effect.fn(\"DevDatabase.removeFile\")(function* (fileName) {\n const filePath = path.join(directory, fileName);\n if (!(yield* fileSystem.exists(filePath))) return;\n yield* fileSystem.remove(filePath);\n removed += 1;\n }),\n { discard: true },\n ).pipe(\n Effect.mapError((cause) =>\n DevDatabaseResetFailed.make({\n cause,\n message: `Could not reset ${databasePath}. Stop the Ignotum dev server and try again.`,\n path: databasePath,\n }),\n ),\n );\n\n return { databasePath, removed } as const;\n }),\n );\n});\n","import type { Plugin } from \"vite\";\n\nconst clientEntryId = \"virtual:ignotum/client-entry\";\nconst resolvedClientEntryId = `\\0${clientEntryId}`;\n\nconst document = `<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>Ignotum</title>\n </head>\n <body>\n <div id=\"app\"></div>\n <script type=\"module\">\n import \"${clientEntryId}\"\n </script>\n </body>\n</html>`;\n\nconst clientEntry = `import \"preact/debug\"\nimport { render } from \"preact\"\nimport { jsx } from \"preact/jsx-runtime\"\n\nimport \"/styles.css\"\nimport App from \"/App.tsx\"\n\nconst root = document.getElementById(\"app\")\n\nif (root === null) {\n throw new Error(\"Ignotum mount element is missing.\")\n}\n\nrender(jsx(App, {}), root)\n`;\n\nexport const ignotumClientPlugin = (): Plugin => ({\n name: \"ignotum:client\",\n\n configureServer: (server) => {\n server.middlewares.use((request, response, next) => {\n const acceptsHtml = request.headers.accept?.includes(\"text/html\") === true;\n const isNavigation = request.method === \"GET\" || request.method === \"HEAD\";\n\n if (!acceptsHtml || !isNavigation) {\n next();\n return;\n }\n\n const requestUrl = request.originalUrl ?? request.url ?? \"/\";\n\n void server\n .transformIndexHtml(requestUrl, document)\n .then((html) => {\n response.statusCode = 200;\n response.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n response.end(request.method === \"HEAD\" ? undefined : html);\n })\n .catch(next);\n });\n },\n\n load: (id) => (id === resolvedClientEntryId ? clientEntry : undefined),\n\n resolveId: (id) => (id === clientEntryId ? resolvedClientEntryId : undefined),\n});\n","/**\n * Connects Effect SQL to SQLite on Node.js using `node:sqlite`.\n *\n * This module opens a SQLite database and exposes it as both `SqliteClient` and\n * the generic Effect SQL client. It serializes access through one connection,\n * caches prepared statements, enables WAL mode unless disabled, and waits up\n * to five seconds for busy databases by default. Explicit transactions on\n * writable connections use `BEGIN IMMEDIATE` to avoid read-to-write lock\n * upgrades, which serializes them behind other writers even when they only\n * read. Clients opened with `readonly: true` are unaffected. Busy waits block\n * the Node.js event loop because `node:sqlite` is synchronous. Database backup\n * and extension loading are supported; streaming queries and `updateValues`\n * are not.\n *\n * @since 4.0.0\n */\nimport * as Cache from \"effect/Cache\";\nimport * as Config from \"effect/Config\";\nimport * as Context from \"effect/Context\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Fiber from \"effect/Fiber\";\nimport { identity } from \"effect/Function\";\nimport * as Layer from \"effect/Layer\";\nimport * as Scope from \"effect/Scope\";\nimport * as Semaphore from \"effect/Semaphore\";\nimport * as Stream from \"effect/Stream\";\nimport * as Reactivity from \"effect/unstable/reactivity/Reactivity\";\nimport * as Client from \"effect/unstable/sql/SqlClient\";\nimport { classifySqliteError, SqlError } from \"effect/unstable/sql/SqlError\";\nimport * as Statement from \"effect/unstable/sql/Statement\";\nimport { backup as backupDatabase, DatabaseSync } from \"node:sqlite\";\nconst ATTR_DB_SYSTEM_NAME = \"db.system.name\";\nconst MAX_BUSY_TIMEOUT = 2_147_483_647;\n/**\n * Runtime type identifier used to mark Node `SqliteClient` values.\n *\n * @category type IDs\n * @since 4.0.0\n */\nexport const TypeId = \"~@effect/sql-sqlite-node/SqliteClient\";\n/**\n * Service tag for the node SQLite client implementation.\n *\n * @category services\n * @since 4.0.0\n */\nexport const SqliteClient = /*#__PURE__*/Context.Service(\"@effect/sql-sqlite-node/SqliteClient\");\n/**\n * Creates a scoped node SQLite client from the supplied configuration, using a single serialized connection with WAL and a 5-second busy timeout enabled by default. Explicit transactions on writable connections take the write lock for their duration, even when they only read; clients opened with `readonly: true` are unaffected.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = options => Effect.gen(function* () {\n const compiler = Statement.makeCompilerSqlite(options.transformQueryNames);\n const transformRows = options.transformResultNames ? Statement.defaultTransforms(options.transformResultNames).array : undefined;\n const makeConnection = Effect.gen(function* () {\n const scope = yield* Effect.scope;\n const db = new DatabaseSync(options.filename, {\n readOnly: options.readonly ?? false,\n allowExtension: true\n });\n yield* Scope.addFinalizer(scope, Effect.sync(() => db.close()));\n db.enableLoadExtension(false);\n const busyTimeout = Math.min(MAX_BUSY_TIMEOUT, Math.max(0, Math.round(Duration.toMillis(options.busyTimeout ?? Duration.seconds(5)))));\n db.exec(`PRAGMA busy_timeout = ${busyTimeout}`);\n if (options.disableWAL !== true) {\n db.exec(\"PRAGMA journal_mode = WAL\");\n }\n const prepareCache = yield* Cache.make({\n capacity: options.prepareCacheSize ?? 200,\n timeToLive: options.prepareCacheTTL ?? Duration.minutes(10),\n lookup: sql => Effect.try({\n try: () => db.prepare(sql),\n catch: cause => new SqlError({\n reason: classifyError(cause, \"Failed to prepare statement\", \"prepare\")\n })\n })\n });\n const runStatement = (statement, params, raw) => Effect.withFiber(fiber => {\n const useSafeIntegers = Context.get(fiber.context, Client.SafeIntegers);\n return Effect.try({\n try: () => {\n statement.setReadBigInts(useSafeIntegers);\n if (statement.columns().length > 0) {\n return statement.all(...params);\n }\n const result = statement.run(...params);\n return raw ? {\n changes: result.changes,\n lastInsertRowid: result.lastInsertRowid\n } : [];\n },\n catch: cause => new SqlError({\n reason: classifyError(cause, \"Failed to execute statement\", \"execute\")\n })\n });\n });\n const runStatementValues = (statement, params) => Effect.withFiber(fiber => {\n const useSafeIntegers = Context.get(fiber.context, Client.SafeIntegers);\n return Effect.try({\n try: () => {\n statement.setReadBigInts(useSafeIntegers);\n if (statement.columns().length > 0) {\n return statement.all(...params);\n }\n statement.run(...params);\n return [];\n },\n catch: cause => new SqlError({\n reason: classifyError(cause, \"Failed to execute statement\", \"execute\")\n })\n });\n });\n const runStatementValuesUnprepared = (statement, params) => Effect.withFiber(fiber => {\n const useSafeIntegers = Context.get(fiber.context, Client.SafeIntegers);\n return Effect.try({\n try: () => {\n statement.setReadBigInts(useSafeIntegers);\n statement.setReturnArrays(true);\n if (statement.columns().length > 0) {\n return statement.all(...params);\n }\n statement.run(...params);\n return [];\n },\n catch: cause => new SqlError({\n reason: classifyError(cause, \"Failed to execute statement\", \"execute\")\n })\n });\n });\n const run = (sql, params, raw = false) => Effect.flatMap(Cache.get(prepareCache, sql), s => runStatement(s, params, raw));\n const runValues = (sql, params) => Effect.acquireUseRelease(Cache.get(prepareCache, sql), statement => {\n statement.setReturnArrays(true);\n return runStatementValues(statement, params);\n }, statement => Effect.sync(() => statement.setReturnArrays(false)));\n const runValuesUnprepared = (sql, params) => runStatementValuesUnprepared(db.prepare(sql), params);\n return identity({\n execute(sql, params, transformRows) {\n return transformRows ? Effect.map(run(sql, params), transformRows) : run(sql, params);\n },\n executeRaw(sql, params) {\n return run(sql, params, true);\n },\n executeValues(sql, params) {\n return runValues(sql, params);\n },\n executeValuesUnprepared(sql, params) {\n return runValuesUnprepared(sql, params);\n },\n executeUnprepared(sql, params, transformRows) {\n const effect = runStatement(db.prepare(sql), params ?? [], false);\n return transformRows ? Effect.map(effect, transformRows) : effect;\n },\n executeStream(_sql, _params) {\n return Stream.die(\"executeStream not implemented\");\n },\n backup(destination) {\n return Effect.suspend(() => {\n let totalPages = 0;\n return Effect.tryPromise({\n try: () => backupDatabase(db, destination, {\n progress: progress => {\n totalPages = progress.totalPages;\n }\n }).then(pages => ({\n totalPages: totalPages || pages,\n remainingPages: 0\n })),\n catch: cause => new SqlError({\n reason: classifyError(cause, \"Failed to backup database\", \"backup\")\n })\n });\n });\n },\n loadExtension(path) {\n return Effect.acquireUseRelease(Effect.sync(() => db.enableLoadExtension(true)), () => Effect.try({\n try: () => db.loadExtension(path),\n catch: cause => new SqlError({\n reason: classifyError(cause, \"Failed to load extension\", \"loadExtension\")\n })\n }), () => Effect.sync(() => db.enableLoadExtension(false)));\n }\n });\n });\n const semaphore = yield* Semaphore.make(1);\n const connection = yield* makeConnection;\n const acquirer = semaphore.withPermits(1)(Effect.succeed(connection));\n const transactionAcquirer = Effect.uninterruptibleMask(restore => {\n const fiber = Fiber.getCurrent();\n const scope = Context.getUnsafe(fiber.context, Scope.Scope);\n return Effect.as(Effect.tap(restore(semaphore.take(1)), () => Scope.addFinalizer(scope, semaphore.release(1))), connection);\n });\n return Object.assign(yield* Client.make({\n acquirer,\n compiler,\n transactionAcquirer,\n beginTransaction: \"BEGIN IMMEDIATE\",\n spanAttributes: [...(options.spanAttributes ? Object.entries(options.spanAttributes) : []), [ATTR_DB_SYSTEM_NAME, \"sqlite\"]],\n transformRows\n }), {\n [TypeId]: TypeId,\n config: options,\n backup: destination => Effect.flatMap(acquirer, _ => _.backup(destination)),\n loadExtension: path => Effect.flatMap(acquirer, _ => _.loadExtension(path))\n });\n});\n/**\n * Builds a layer from an Effect `Config` value, providing both the node `SqliteClient` service and the generic `SqlClient` service.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerConfig = config => Layer.effectContext(Config.unwrap(config).pipe(Effect.flatMap(make), Effect.map(client => Context.make(SqliteClient, client).pipe(Context.add(Client.SqlClient, client))))).pipe(Layer.provide(Reactivity.layer));\n/**\n * Builds a layer from a node SQLite client configuration, providing both `SqliteClient` and the generic `SqlClient` service.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layer = config => Layer.effectContext(Effect.map(make(config), client => Context.make(SqliteClient, client).pipe(Context.add(Client.SqlClient, client)))).pipe(Layer.provide(Reactivity.layer));\n// internal\nconst classifyError = (cause, message, operation) => classifySqliteError(sqliteCauseWithErrno(cause), {\n message,\n operation\n});\nconst sqliteCauseWithErrno = cause => {\n if (typeof cause !== \"object\" || cause === null || !(\"errcode\" in cause) || \"errno\" in cause) {\n return cause;\n }\n const errcode = cause.errcode;\n if (typeof errcode !== \"number\") {\n return cause;\n }\n return Object.assign(cause, {\n errno: errcode\n });\n};\n//# sourceMappingURL=SqliteClient.js.map","import { Context } from \"effect\";\n//#region src/functions.ts\nvar FunctionRuntime = class extends Context.Service()(\"@ignotum/runtime/functions/FunctionRuntime\") {};\n//#endregion\nexport { FunctionRuntime };\n\n//# sourceMappingURL=functions.js.map","import { Context } from \"effect\";\n//#region src/sync.ts\nvar QueryInvalidation = class extends Context.Service()(\"@ignotum/runtime/sync/QueryInvalidation\") {};\n//#endregion\nexport { QueryInvalidation };\n\n//# sourceMappingURL=sync.js.map","export const ignotumPathPrefix = \"/_ignotum\";\nexport const syncPath = `${ignotumPathPrefix}/sync`;\n\nexport const isIgnotumPath = (pathname: string): boolean =>\n pathname === ignotumPathPrefix || pathname.startsWith(`${ignotumPathPrefix}/`);\n","import { Schema } from \"effect\";\n//#region src/runtime/id.ts\nconst IdAlphabet = \"0123456789abcdefghijklmnopqrstuvwxyz\";\nconst IdLength = 24;\nconst GeneratedId = Schema.String.check(Schema.isPattern(/^[0-9a-z]{24}$/)).pipe(Schema.brand(\"ignotum/id\"));\n//#endregion\nexport { GeneratedId, IdAlphabet, IdLength };\n\n//# sourceMappingURL=id.js.map","import { i as decodeTransportObject } from \"../value-Briqf-Ua.js\";\nimport { Brand, Effect, Effectable, Function, Option, Predicate, Schema } from \"effect\";\n//#region src/runtime/result.ts\nconst ResultTypeId = Symbol.for(\"ignotum/runtime/result/Result\");\nconst CompletedResultTypeId = Symbol.for(\"ignotum/runtime/result/Completed\");\nconst PendingResultTypeId = Symbol.for(\"ignotum/runtime/result/Pending\");\nconst ErrorBrand = \"ignotum/error\";\nconst makeErrorValue = Brand.nominal();\nconst ErrorValueSchema = Schema.StructWithRest(Schema.Struct({ _tag: Schema.String }), [Schema.Record(Schema.String, Schema.Json)]).pipe(Schema.brand(ErrorBrand));\nvar InternalServerErrorCause = class extends Schema.TaggedError()(\"InternalServerError\", { requestId: Schema.String }) {};\nconst InternalServerError = InternalServerErrorCause;\nconst InternalServerErrorSchema = InternalServerErrorCause.pipe(Schema.brand(ErrorBrand));\nconst effectOf = (value) => Predicate.hasProperty(value, ResultTypeId) ? value[ResultTypeId] : Effect.succeed(value);\nfunction makeResultEffectBase() {\n\tconst Base = function() {};\n\tBase.prototype = Effectable.Prototype({\n\t\tlabel: \"IgnotumResult\",\n\t\tevaluate() {\n\t\t\treturn this[ResultTypeId];\n\t\t}\n\t});\n\treturn Base;\n}\nconst ResultEffectBase = makeResultEffectBase();\nvar ResultOperation = class ResultOperation extends ResultEffectBase {\n\t[ResultTypeId];\n\tconstructor(effect, completed) {\n\t\tsuper();\n\t\tthis[ResultTypeId] = effect;\n\t\tif (completed !== void 0) Object.defineProperty(this, CompletedResultTypeId, { value: completed });\n\t}\n\tcatch(cases) {\n\t\tconst effectCases = {};\n\t\tfor (const [tag, handler] of Object.entries(cases)) if (Predicate.isFunction(handler)) effectCases[tag] = (failure) => effectOf(handler(failure));\n\t\tconst runtimeEffect = this[ResultTypeId];\n\t\tconst caught = Effect.catchTags(runtimeEffect, effectCases);\n\t\treturn new ResultOperation(caught);\n\t}\n};\nvar PendingQueryResult = class {\n\t[PendingResultTypeId] = PendingResultTypeId;\n};\nconst inspectResult = (value) => {\n\tif (!Predicate.hasProperty(value, CompletedResultTypeId)) return void 0;\n\treturn value[CompletedResultTypeId];\n};\nconst effectFromResult = (result) => result[ResultTypeId];\nconst resultFromEffect = (effect) => new ResultOperation(effect);\nconst isFailureResult = (result) => Predicate.hasProperty(result, CompletedResultTypeId) && Predicate.isObject(result[CompletedResultTypeId]) && Predicate.hasProperty(result[CompletedResultTypeId], \"type\") && result[CompletedResultTypeId].type === \"Failure\";\nconst succeed = (value) => new ResultOperation(Effect.succeed(value), {\n\ttype: \"Success\",\n\tvalue\n});\nconst fail = (error) => new ResultOperation(Effect.fail(error), {\n\ttype: \"Failure\",\n\terror\n});\nconst tryResult = (body) => {\n\treturn new ResultOperation(Effect.gen(body));\n};\nconst match = Function.dual(2, (result, matchers) => {\n\tif (result instanceof PendingQueryResult) {\n\t\tif (matchers.pending === void 0) throw new Error(\"A pending Result requires a pending matcher.\");\n\t\treturn matchers.pending();\n\t}\n\tif (!Predicate.hasProperty(result, ResultTypeId)) throw new Error(\"Unknown Result implementation.\");\n\tconst inspected = inspectResult(result);\n\tif (inspected?.type === \"Success\") {\n\t\tconst value = inspected.value;\n\t\treturn matchers.value(value);\n\t}\n\tif (!isFailureResult(result)) throw new Error(\"Unknown or incomplete Result operation.\");\n\tconst error = result[CompletedResultTypeId].error;\n\tif (error._tag === \"InternalServerError\") {\n\t\tconst internalError = Schema.decodeUnknownSync(InternalServerErrorSchema)(error);\n\t\tconst handler = matchers.internalError;\n\t\tif (handler === void 0) throw internalError;\n\t\treturn handler(internalError);\n\t}\n\tconst errorMatcher = matchers.error;\n\tif (errorMatcher === void 0) throw new Error(`No matcher was provided for ${error._tag}.`);\n\tif (Predicate.isFunction(errorMatcher)) return errorMatcher(error);\n\tconst handlers = errorMatcher;\n\tconst handler = Object.hasOwn(handlers, error._tag) ? handlers[error._tag] : void 0;\n\tif (handler === void 0) throw new Error(`No matcher was provided for ${error._tag}.`);\n\treturn handler(error);\n});\nconst pending = () => new PendingQueryResult();\nconst failureFromWire = (error, datePaths = []) => {\n\tconst internalError = Schema.decodeUnknownOption(InternalServerErrorSchema)(error);\n\tif (Option.isSome(internalError)) return fail(internalError.value);\n\tconst decoded = Schema.decodeUnknownOption(ErrorValueSchema)(error);\n\tif (Option.isNone(decoded)) throw new Error(\"The server returned an invalid application error.\");\n\tconst restored = decodeTransportObject(decoded.value, datePaths);\n\treturn fail(makeErrorValue({\n\t\t...restored,\n\t\t_tag: decoded.value._tag\n\t}));\n};\nconst documentNotFound = (table, id) => Brand.nominal()({\n\t_tag: \"DocumentNotFound\",\n\ttable,\n\tid\n});\nconst Result = {\n\tfail,\n\tmatch,\n\tsucceed,\n\ttry: tryResult\n};\n//#endregion\nexport { ErrorBrand, ErrorValueSchema, InternalServerError, InternalServerErrorSchema, Result, documentNotFound, effectFromResult, failureFromWire, inspectResult, match, pending, resultFromEffect };\n\n//# sourceMappingURL=result.js.map","//#region src/runtime/schema.ts\nconst FunctionSchemaTypeId = Symbol.for(\"ignotum/runtime/schema/FunctionSchema\");\nconst attachFunctionSchema = (schema) => (definition) => {\n\tObject.defineProperty(definition, FunctionSchemaTypeId, {\n\t\tconfigurable: false,\n\t\tenumerable: false,\n\t\tvalue: schema,\n\t\twritable: false\n\t});\n\treturn definition;\n};\nconst getFunctionSchema = (value) => value[FunctionSchemaTypeId];\n//#endregion\nexport { FunctionSchemaTypeId, attachFunctionSchema, getFunctionSchema };\n\n//# sourceMappingURL=schema.js.map","import { Result } from \"../runtime/result.js\";\nimport { bindValues, table, values } from \"./values.js\";\nimport { attachFunctionSchema } from \"../runtime/schema.js\";\n//#region src/schema/types.ts\nconst SchemaDefinitionTypeId = Symbol.for(\"ignotum/schema/SchemaDefinition\");\n//#endregion\n//#region src/schema/definition.ts\nconst defineSchema = (define) => ({\n\t_tag: \"Schema\",\n\t[SchemaDefinitionTypeId]: define({\n\t\ttable,\n\t\tvalues\n\t})\n});\n//#endregion\n//#region src/schema/server.ts\nconst makeFunctionBuilder = (schema, kind) => {\n\tconst define = (definition) => attachFunctionSchema(schema)({\n\t\t_tag: kind,\n\t\t...definition\n\t});\n\treturn define;\n};\nconst makeFunctionBuilders = (schema) => ({\n\tmutation: makeFunctionBuilder(schema, \"Mutation\"),\n\tquery: makeFunctionBuilder(schema, \"Query\")\n});\nconst bindSchema = (schema) => ({\n\tvalues: bindValues(schema[SchemaDefinitionTypeId]),\n\t...makeFunctionBuilders(schema)\n});\n//#endregion\nexport { Result, SchemaDefinitionTypeId, bindSchema, bindValues, defineSchema, table, values };\n\n//# sourceMappingURL=index.js.map","import { Context } from \"effect\";\n//#region src/id.ts\nvar IdGenerator = class extends Context.Service()(\"@ignotum/runtime/id/IdGenerator\") {};\n//#endregion\nexport { IdGenerator };\n\n//# sourceMappingURL=id.js.map","import { Context, DateTime, Effect, Layer, Option, Schema } from \"effect\";\nimport { SqlClient, SqlError, SqlSchema } from \"effect/unstable/sql\";\nimport { GeneratedId, type GeneratedId as GeneratedIdType } from \"@ignotum/contracts/runtime/id\";\nimport {\n documentNotFound,\n resultFromEffect,\n type DocumentNotFoundValue,\n type Result,\n} from \"@ignotum/contracts/runtime/result\";\nimport type {\n RuntimeSchemaDefinition,\n RuntimeTableDefinition,\n} from \"@ignotum/contracts/runtime/schema\";\nimport { SchemaDefinitionTypeId } from \"@ignotum/contracts/schema\";\nimport { IdGenerator } from \"@ignotum/runtime/id\";\n\ninterface RuntimeObject {\n readonly [fieldName: string]: RuntimeDocumentValue | undefined;\n}\ntype RuntimeDocumentValue =\n | null\n | boolean\n | number\n | string\n | Date\n | ReadonlyArray<RuntimeDocumentValue>\n | RuntimeObject;\ntype RuntimeValue = RuntimeObject;\n\nexport interface RuntimeDocument {\n readonly [fieldName: string]: RuntimeDocumentValue | undefined;\n readonly id: GeneratedIdType;\n readonly createdAt: Date;\n readonly updatedAt: Date;\n}\n\nexport interface LocalDatabaseReader {\n readonly find: (tableName: string, id: string) => Result<RuntimeDocument | undefined, never>;\n readonly get: (tableName: string, id: string) => Result<RuntimeDocument, DocumentNotFoundValue>;\n readonly query: (tableName: string) => {\n readonly collect: () => Result<ReadonlyArray<RuntimeDocument>, never>;\n };\n}\n\nexport interface LocalDatabaseWriter extends LocalDatabaseReader {\n readonly delete: (tableName: string, id: string) => Result<void, never>;\n readonly insert: (tableName: string, value: RuntimeValue) => Result<GeneratedIdType, never>;\n readonly patch: (tableName: string, id: string, value: RuntimeValue) => Result<void, never>;\n readonly replace: (tableName: string, id: string, value: RuntimeValue) => Result<void, never>;\n}\n\nexport interface LocalQueryContext {\n readonly db: LocalDatabaseReader;\n}\n\nexport interface LocalMutationContext {\n readonly db: LocalDatabaseWriter;\n}\n\ninterface LocalDatabaseService {\n readonly queryTransaction: <Success, Failure>(\n schema: RuntimeSchemaDefinition,\n use: (context: Readonly<LocalQueryContext>) => Effect.Effect<Success, Failure>,\n ) => Effect.Effect<Success, Failure | SqlError.SqlError>;\n readonly mutationTransaction: <Success, Failure>(\n schema: RuntimeSchemaDefinition,\n use: (context: Readonly<LocalMutationContext>) => Effect.Effect<Success, Failure>,\n ) => Effect.Effect<Success, Failure | SqlError.SqlError>;\n}\n\nconst StoredDocument = Schema.Struct({\n id: GeneratedId,\n tableName: Schema.String,\n createdAt: Schema.Int,\n updatedAt: Schema.Int,\n fields: Schema.String,\n});\ntype StoredDocument = typeof StoredDocument.Type;\n\nconst DocumentLookup = Schema.Struct({\n id: Schema.String,\n tableName: Schema.String,\n});\nconst TableLookup = Schema.Struct({ tableName: Schema.String });\ntype DatabaseOperation = \"collect\" | \"get\" | \"insert\" | \"patch\" | \"replace\";\n\nexport class UnknownDatabaseTable extends Schema.TaggedError<UnknownDatabaseTable>()(\n \"UnknownDatabaseTable\",\n {\n message: Schema.String,\n tableName: Schema.String,\n },\n) {}\n\nexport class DocumentSchemaMismatch extends Schema.TaggedError<DocumentSchemaMismatch>()(\n \"DocumentSchemaMismatch\",\n {\n cause: Schema.Defect(),\n id: Schema.NullOr(Schema.String),\n message: Schema.String,\n operation: Schema.Literals([\"collect\", \"get\", \"insert\", \"patch\", \"replace\"]),\n tableName: Schema.String,\n },\n) {}\n\nconst schemaMismatch = (\n tableName: string,\n id: string | null,\n operation: DatabaseOperation,\n cause: unknown,\n) =>\n DocumentSchemaMismatch.make({\n cause,\n id,\n message: `Document fields for ${tableName} did not match its schema during ${operation}.`,\n operation,\n tableName,\n });\n\nconst tableFor = Effect.fn(\"LocalDatabase.tableFor\")(function* (\n schema: RuntimeSchemaDefinition,\n tableName: string,\n) {\n const table = schema[SchemaDefinitionTypeId][tableName];\n if (table === undefined) {\n return yield* UnknownDatabaseTable.make({\n message: `Unknown database table ${tableName}.`,\n tableName,\n });\n }\n return table;\n});\n\nconst fieldsCodec = (table: RuntimeTableDefinition) =>\n // SAFETY: defineSchema creates every table schema with Schema.Struct, so its\n // decoded value is a string-keyed object and the authoring API needs no services.\n Schema.fromJsonString(\n Schema.make<Schema.Codec<RuntimeValue, Schema.Json>>(Schema.toCodecJson(table.schema).ast),\n );\n\nconst encodeFields = Effect.fn(\"LocalDatabase.encodeFields\")(function* (\n schema: RuntimeSchemaDefinition,\n tableName: string,\n value: RuntimeValue,\n operation: Extract<DatabaseOperation, \"insert\" | \"patch\" | \"replace\">,\n id: string | null,\n) {\n const table = yield* tableFor(schema, tableName);\n return yield* Schema.encodeEffect(fieldsCodec(table), {\n onExcessProperty: \"error\",\n })(value).pipe(Effect.mapError((cause) => schemaMismatch(tableName, id, operation, cause)));\n});\n\nconst decodeFields = Effect.fn(\"LocalDatabase.decodeFields\")(function* (\n schema: RuntimeSchemaDefinition,\n row: StoredDocument,\n operation: Extract<DatabaseOperation, \"collect\" | \"get\" | \"patch\">,\n) {\n const table = yield* tableFor(schema, row.tableName);\n return yield* Schema.decodeEffect(fieldsCodec(table), {\n onExcessProperty: \"error\",\n })(row.fields).pipe(\n Effect.mapError((cause) => schemaMismatch(row.tableName, row.id, operation, cause)),\n );\n});\n\nconst toRuntimeDocument = Effect.fn(\"LocalDatabase.toRuntimeDocument\")(function* (\n schema: RuntimeSchemaDefinition,\n row: StoredDocument,\n operation: Extract<DatabaseOperation, \"collect\" | \"get\">,\n) {\n const fields = yield* decodeFields(schema, row, operation);\n return {\n ...fields,\n id: row.id,\n createdAt: DateTime.toDate(DateTime.makeUnsafe(row.createdAt)),\n updatedAt: DateTime.toDate(DateTime.makeUnsafe(row.updatedAt)),\n } satisfies RuntimeDocument;\n});\n\nconst nextUpdatedAt = (now: DateTime.DateTime, previous: number): number =>\n Math.max(DateTime.toEpochMillis(now), previous + 1);\n\nexport class LocalDatabase extends Context.Service<LocalDatabase, LocalDatabaseService>()(\n \"ignotum/dev-runtime/database/LocalDatabase\",\n) {\n static readonly layer = Layer.effect(\n LocalDatabase,\n Effect.gen(function* () {\n const ids = yield* IdGenerator;\n const sql = yield* SqlClient.SqlClient;\n\n yield* sql`\n CREATE TABLE IF NOT EXISTS documents (\n id TEXT PRIMARY KEY NOT NULL\n CHECK (length(id) = 24 AND id NOT GLOB '*[^0-9a-z]*'),\n tableName TEXT NOT NULL,\n createdAt INTEGER NOT NULL,\n updatedAt INTEGER NOT NULL,\n fields TEXT NOT NULL CHECK (json_valid(fields))\n ) STRICT\n `;\n yield* sql`\n CREATE INDEX IF NOT EXISTS documents_table_name_idx\n ON documents (tableName)\n `;\n\n const findStored = SqlSchema.findOneOption({\n Request: DocumentLookup,\n Result: StoredDocument,\n execute: ({ id, tableName }) => sql`\n SELECT id, tableName, createdAt, updatedAt, fields\n FROM documents\n WHERE id = ${id} AND tableName = ${tableName}\n LIMIT 1\n `,\n });\n const collectStored = SqlSchema.findAll({\n Request: TableLookup,\n Result: StoredDocument,\n execute: ({ tableName }) => sql`\n SELECT id, tableName, createdAt, updatedAt, fields\n FROM documents\n WHERE tableName = ${tableName}\n ORDER BY createdAt ASC, id ASC\n `,\n });\n\n const find = Effect.fn(\"LocalDatabase.find\")(function* (\n schema: RuntimeSchemaDefinition,\n tableName: string,\n id: string,\n ) {\n yield* tableFor(schema, tableName);\n const row = yield* findStored({ id, tableName });\n if (Option.isNone(row)) return undefined;\n return yield* toRuntimeDocument(schema, row.value, \"get\");\n });\n\n const collect = Effect.fn(\"LocalDatabase.collect\")(function* (\n schema: RuntimeSchemaDefinition,\n tableName: string,\n ) {\n yield* tableFor(schema, tableName);\n const rows = yield* collectStored({ tableName });\n return yield* Effect.forEach(rows, (row) => toRuntimeDocument(schema, row, \"collect\"));\n });\n\n const insert = Effect.fn(\"LocalDatabase.insert\")(function* (\n schema: RuntimeSchemaDefinition,\n tableName: string,\n value: RuntimeValue,\n ) {\n const fields = yield* encodeFields(schema, tableName, value, \"insert\", null);\n const id = yield* ids.generate;\n const now = DateTime.toEpochMillis(yield* DateTime.now);\n yield* sql`\n INSERT INTO documents (id, tableName, createdAt, updatedAt, fields)\n VALUES (${id}, ${tableName}, ${now}, ${now}, ${fields})\n `;\n return id;\n });\n\n const deleteDocument = Effect.fn(\"LocalDatabase.delete\")(function* (\n schema: RuntimeSchemaDefinition,\n tableName: string,\n id: string,\n ) {\n yield* tableFor(schema, tableName);\n yield* sql`DELETE FROM documents WHERE id = ${id} AND tableName = ${tableName}`;\n });\n\n const patch = Effect.fn(\"LocalDatabase.patch\")(function* (\n schema: RuntimeSchemaDefinition,\n tableName: string,\n id: string,\n value: RuntimeValue,\n ) {\n yield* tableFor(schema, tableName);\n const stored = yield* findStored({ id, tableName });\n if (Option.isNone(stored)) return;\n const current = yield* decodeFields(schema, stored.value, \"patch\");\n const fields = yield* encodeFields(\n schema,\n tableName,\n { ...current, ...value },\n \"patch\",\n id,\n );\n const updatedAt = nextUpdatedAt(yield* DateTime.now, stored.value.updatedAt);\n yield* sql`\n UPDATE documents\n SET fields = ${fields}, updatedAt = ${updatedAt}\n WHERE id = ${id} AND tableName = ${tableName}\n `;\n });\n\n const replace = Effect.fn(\"LocalDatabase.replace\")(function* (\n schema: RuntimeSchemaDefinition,\n tableName: string,\n id: string,\n value: RuntimeValue,\n ) {\n yield* tableFor(schema, tableName);\n const stored = yield* findStored({ id, tableName });\n if (Option.isNone(stored)) return;\n const fields = yield* encodeFields(schema, tableName, value, \"replace\", id);\n const updatedAt = nextUpdatedAt(yield* DateTime.now, stored.value.updatedAt);\n yield* sql`\n UPDATE documents\n SET fields = ${fields}, updatedAt = ${updatedAt}\n WHERE id = ${id} AND tableName = ${tableName}\n `;\n });\n\n const makeReader = (schema: RuntimeSchemaDefinition): LocalDatabaseReader =>\n Object.freeze({\n find: (tableName: string, id: string) =>\n resultFromEffect(find(schema, tableName, id).pipe(Effect.orDie)),\n get: (tableName: string, id: string) =>\n resultFromEffect(\n find(schema, tableName, id).pipe(\n Effect.orDie,\n Effect.flatMap((document) =>\n document === undefined\n ? Effect.fail(documentNotFound(tableName, id))\n : Effect.succeed(document),\n ),\n ),\n ),\n query: (tableName: string) =>\n Object.freeze({\n collect: () => resultFromEffect(collect(schema, tableName).pipe(Effect.orDie)),\n }),\n });\n\n const makeWriter = (schema: RuntimeSchemaDefinition): LocalDatabaseWriter => {\n const reader = makeReader(schema);\n return Object.freeze({\n ...reader,\n delete: (tableName: string, id: string) =>\n resultFromEffect(deleteDocument(schema, tableName, id).pipe(Effect.orDie)),\n insert: (tableName: string, value: RuntimeValue) =>\n resultFromEffect(insert(schema, tableName, value).pipe(Effect.orDie)),\n patch: (tableName: string, id: string, value: RuntimeValue) =>\n resultFromEffect(patch(schema, tableName, id, value).pipe(Effect.orDie)),\n replace: (tableName: string, id: string, value: RuntimeValue) =>\n resultFromEffect(replace(schema, tableName, id, value).pipe(Effect.orDie)),\n });\n };\n\n return LocalDatabase.of({\n queryTransaction: (schema, use) =>\n sql.withTransaction(\n Effect.gen(function* () {\n const context = Object.freeze({\n db: makeReader(schema),\n });\n return yield* use(context);\n }),\n ),\n mutationTransaction: (schema, use) =>\n sql.withTransaction(\n Effect.gen(function* () {\n const context = Object.freeze({\n db: makeWriter(schema),\n });\n return yield* use(context);\n }),\n ),\n });\n }),\n );\n}\n","import { GeneratedId, IdAlphabet, IdLength } from \"@ignotum/contracts/runtime/id\";\nimport { IdGenerator } from \"@ignotum/runtime/id\";\nimport { Effect, Layer } from \"effect\";\nimport { customAlphabet } from \"nanoid\";\n\nexport const idGeneratorLayer = Layer.sync(IdGenerator, () => {\n const nanoid = customAlphabet(IdAlphabet, IdLength);\n return IdGenerator.of({\n generate: Effect.sync(() => GeneratedId.make(nanoid())),\n });\n});\n","import { FunctionAddress } from \"./sync.js\";\nimport { Schema } from \"effect\";\n//#region src/runtime/functions.ts\nconst FunctionKind = Schema.Literals([\"Mutation\", \"Query\"]);\nvar UnknownFunction = class extends Schema.TaggedError()(\"UnknownFunction\", {\n\tfunction: FunctionAddress,\n\tmessage: Schema.String\n}) {};\nvar WrongFunctionKind = class extends Schema.TaggedError()(\"WrongFunctionKind\", {\n\tactual: FunctionKind,\n\texpected: FunctionKind,\n\tfunction: FunctionAddress,\n\tmessage: Schema.String\n}) {};\nvar InvalidArguments = class extends Schema.TaggedError()(\"InvalidArguments\", {\n\tfunction: FunctionAddress,\n\tmessage: Schema.String\n}) {};\nvar FunctionUnavailable = class extends Schema.TaggedError()(\"FunctionUnavailable\", {\n\tcause: Schema.Defect(),\n\tfunction: FunctionAddress,\n\tmessage: Schema.String\n}) {};\n//#endregion\nexport { FunctionKind, FunctionUnavailable, InvalidArguments, UnknownFunction, WrongFunctionKind };\n\n//# sourceMappingURL=functions.js.map","import {\n FunctionUnavailable,\n InvalidArguments,\n UnknownFunction,\n WrongFunctionKind,\n type FunctionKind,\n type FunctionResolutionError,\n} from \"@ignotum/contracts/runtime/functions\";\nimport {\n getFunctionSchema,\n type FunctionSchemaCarrier,\n type RuntimeSchemaDefinition,\n} from \"@ignotum/contracts/runtime/schema\";\nimport { ErrorValueSchema, type ErrorValue } from \"@ignotum/contracts/runtime/result\";\nimport {\n FunctionAddress,\n apiFunctionParts,\n datePathsOf,\n datePathsOfObject,\n type TransportValue,\n type WireResult,\n} from \"@ignotum/contracts/runtime/sync\";\nimport { FunctionRuntime } from \"@ignotum/runtime/functions\";\nimport { Cause, Context, Effect, Layer, Path, Predicate, Schema, Semaphore } from \"effect\";\nimport { nanoid } from \"nanoid\";\nimport type { ViteDevServer } from \"vite\";\nimport { normalizePath } from \"vite\";\n\nimport { LocalDatabase, type LocalMutationContext, type LocalQueryContext } from \"./database.js\";\n\nexport { FunctionUnavailable, InvalidArguments, UnknownFunction, WrongFunctionKind };\nexport type { FunctionKind };\n\ntype RuntimeFields = Readonly<Record<string, Schema.ConstraintDecoder<unknown>>>;\n\ndeclare const FunctionArgumentsTypeId: unique symbol;\nexport interface FunctionArguments {\n readonly [FunctionArgumentsTypeId]?: never;\n}\n\nexport type RuntimeHandlerContext = LocalMutationContext | LocalQueryContext;\n\nexport interface RuntimeFunctionDefinition {\n readonly _tag: FunctionKind;\n readonly args?: RuntimeFields;\n readonly returns?: Schema.Codec<unknown, unknown>;\n readonly errors?: Schema.Codec<unknown, unknown>;\n readonly handler: (\n context: RuntimeHandlerContext,\n args: FunctionArguments,\n ) => Generator<Effect.Effect<unknown, ErrorValue, never>, TransportValue | void, never>;\n}\n\nexport interface ResolvedFunction {\n readonly definition: RuntimeFunctionDefinition;\n readonly args: FunctionArguments;\n readonly schema: RuntimeSchemaDefinition;\n}\n\ninterface RuntimeFunctionCandidate extends FunctionSchemaCarrier {\n readonly _tag?: unknown;\n readonly args?: unknown;\n readonly returns?: unknown;\n readonly errors?: unknown;\n readonly handler?: unknown;\n}\n\nconst inspectRuntimeFunctionDefinition = (\n value: RuntimeFunctionCandidate,\n):\n | { readonly definition: RuntimeFunctionDefinition; readonly schema: RuntimeSchemaDefinition }\n | undefined => {\n const schema = getFunctionSchema(value);\n if (\n schema === undefined ||\n !Predicate.hasProperty(value, \"_tag\") ||\n (value._tag !== \"Mutation\" && value._tag !== \"Query\") ||\n (Predicate.hasProperty(value, \"args\") &&\n value.args !== undefined &&\n !Predicate.isObject(value.args)) ||\n (Predicate.hasProperty(value, \"returns\") &&\n value.returns !== undefined &&\n !Schema.isSchema(value.returns)) ||\n (Predicate.hasProperty(value, \"errors\") &&\n value.errors !== undefined &&\n !Schema.isSchema(value.errors)) ||\n !Predicate.hasProperty(value, \"handler\") ||\n !Predicate.isFunction(value.handler)\n ) {\n return undefined;\n }\n\n if (\n Predicate.hasProperty(value, \"args\") &&\n Predicate.isObject(value.args) &&\n !Object.values(value.args).every(Schema.isSchema)\n ) {\n return undefined;\n }\n\n // SAFETY: every RuntimeFunctionDefinition property and argument Schema was\n // checked above. Predicate.hasProperty does not retain the literal tag type.\n return { definition: value as RuntimeFunctionDefinition, schema };\n};\n\nexport class FunctionRegistry extends Context.Service<\n FunctionRegistry,\n {\n readonly resolve: (\n functionAddress: FunctionAddress,\n kind: FunctionKind,\n args: Schema.Json,\n ) => Effect.Effect<ResolvedFunction, FunctionResolutionError>;\n }\n>()(\"ignotum/dev-runtime/functions/FunctionRegistry\") {\n static layer(server: ViteDevServer, projectDirectory: string) {\n return Layer.effect(\n FunctionRegistry,\n Effect.gen(function* () {\n const path = yield* Path.Path;\n return FunctionRegistry.of({\n resolve: Effect.fn(\"FunctionRegistry.resolve\")(function* (functionAddress, kind, args) {\n const { functionName, moduleName } = apiFunctionParts(functionAddress);\n const modulePath = normalizePath(\n path.join(projectDirectory, \"server\", `${moduleName}.ts`),\n );\n const loadedModule = yield* Effect.tryPromise({\n try: () => server.ssrLoadModule(modulePath),\n catch: (cause) =>\n FunctionUnavailable.make({\n cause,\n function: functionAddress,\n message: `Could not load ${functionAddress}.`,\n }),\n });\n const candidate = loadedModule[functionName];\n\n const inspected = Predicate.isObject(candidate)\n ? inspectRuntimeFunctionDefinition(candidate)\n : undefined;\n if (inspected === undefined) {\n return yield* UnknownFunction.make({\n function: functionAddress,\n message: `Unknown server function ${functionAddress}.`,\n });\n }\n const definition = inspected.definition;\n\n if (definition._tag !== kind) {\n return yield* WrongFunctionKind.make({\n actual: definition._tag,\n expected: kind,\n function: functionAddress,\n message: `${functionAddress} is a ${definition._tag.toLowerCase()}, not a ${kind.toLowerCase()}.`,\n });\n }\n\n const decodedArgs = yield* Schema.decodeEffect(\n Schema.toCodecJson(Schema.Struct(definition.args ?? {})),\n )(args).pipe(\n Effect.mapError(() =>\n InvalidArguments.make({\n function: functionAddress,\n message: `Invalid arguments for ${functionAddress}.`,\n }),\n ),\n );\n\n return { args: decodedArgs, definition, schema: inspected.schema };\n }),\n });\n }),\n );\n }\n}\n\nclass MutationApplicationFailure extends Schema.TaggedError<MutationApplicationFailure>()(\n \"MutationApplicationFailure\",\n { error: Schema.Json },\n) {}\n\nexport class FunctionExecutor extends Context.Service<\n FunctionExecutor,\n {\n readonly execute: (\n functionAddress: FunctionAddress,\n kind: FunctionKind,\n resolved: ResolvedFunction,\n ) => Effect.Effect<WireResult>;\n }\n>()(\"ignotum/dev-runtime/functions/FunctionExecutor\") {\n static readonly layer = Layer.effect(\n FunctionExecutor,\n Effect.gen(function* () {\n const database = yield* LocalDatabase;\n const mutationSemaphore = yield* Semaphore.make(1);\n\n const encodeSuccess = (\n definition: RuntimeFunctionDefinition,\n value: TransportValue | void,\n ) =>\n definition.returns === undefined\n ? Schema.encodeUnknownEffect(Schema.Undefined)(value).pipe(\n Effect.orDie,\n Effect.as<WireResult>({ type: \"Success\" }),\n )\n : Schema.encodeEffect(Schema.toCodecJson(definition.returns))(value).pipe(\n Effect.orDie,\n Effect.map((encoded): WireResult => {\n const result: WireResult = { type: \"Success\", value: encoded };\n const dates = datePathsOf(value);\n return dates.length === 0 ? result : { ...result, dates };\n }),\n );\n\n const encodeFailure = (definition: RuntimeFunctionDefinition, error: ErrorValue) =>\n Schema.encodeEffect(Schema.toCodecJson(definition.errors ?? ErrorValueSchema))(error).pipe(\n Effect.orDie,\n Effect.map((encoded): WireResult => {\n const result: WireResult = { type: \"Failure\", error: encoded };\n const dates = datePathsOfObject(error);\n return dates.length === 0 ? result : { ...result, dates };\n }),\n );\n\n return FunctionExecutor.of({\n execute: Effect.fn(\"FunctionExecutor.execute\")(function* (functionAddress, kind, resolved) {\n const invoke = (context: RuntimeHandlerContext) =>\n Effect.gen(() => resolved.definition.handler(context, resolved.args)).pipe(\n Effect.matchEffect({\n onFailure: (error) => encodeFailure(resolved.definition, error),\n onSuccess: (value) => encodeSuccess(resolved.definition, value),\n }),\n );\n\n const execution =\n kind === \"Query\"\n ? database.queryTransaction(resolved.schema, invoke)\n : mutationSemaphore.withPermits(1)(\n database\n .mutationTransaction(resolved.schema, (context) =>\n invoke(context).pipe(\n Effect.flatMap((result) =>\n result.type === \"Failure\"\n ? Effect.fail(MutationApplicationFailure.make({ error: result.error }))\n : Effect.succeed(result),\n ),\n ),\n )\n .pipe(\n Effect.catchTags({\n MutationApplicationFailure: ({ error }) =>\n Effect.succeed({ type: \"Failure\" as const, error }),\n }),\n ),\n );\n\n return yield* execution.pipe(\n Effect.orDie,\n Effect.catchCauseIf(\n (cause) => !Cause.hasInterruptsOnly(cause),\n (cause) => {\n const requestId = nanoid();\n return Effect.logError(`${functionAddress} failed during execution.`).pipe(\n Effect.annotateLogs({ cause, function: functionAddress, requestId }),\n Effect.as({\n type: \"Failure\" as const,\n error: { _tag: \"InternalServerError\", requestId },\n }),\n );\n },\n ),\n );\n }),\n });\n }),\n );\n}\n\n/** Adapts the Vite/SQLite development implementation to the shared runtime contract. */\nexport const functionRuntimeLayer = Layer.effect(\n FunctionRuntime,\n Effect.gen(function* () {\n const registry = yield* FunctionRegistry;\n const executor = yield* FunctionExecutor;\n return FunctionRuntime.of({\n prepare: Effect.fn(\"DevFunctionRuntime.prepare\")(function* (functionAddress, kind, args) {\n const resolved = yield* registry.resolve(functionAddress, kind, args);\n return { execute: executor.execute(functionAddress, kind, resolved) };\n }),\n });\n }),\n);\n","// @effect-diagnostics-next-line nodeBuiltinImport:off Vite exposes its HTTP server through Node's adapter types.\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport { NodeHttpServer, NodeServices, NodeSocket } from \"@effect/platform-node\";\nimport { SqliteClient } from \"@effect/sql-sqlite-node\";\nimport {\n ClientMessageJson,\n ServerMessageJson,\n type ClientMessage,\n type FunctionAddress,\n type Operation,\n type ProtocolErrorCode,\n type ServerMessage,\n type SubscriptionId,\n type WireResult,\n} from \"@ignotum/contracts/runtime/sync\";\nimport {\n Effect,\n Context,\n FileSystem,\n Function,\n FiberSet,\n HashMap,\n Layer,\n ManagedRuntime,\n Option,\n Path,\n PartitionedSemaphore,\n PubSub,\n Ref,\n Schema,\n Semaphore,\n} from \"effect\";\nimport { HttpServerRequest, HttpServerResponse } from \"effect/unstable/http\";\nimport type * as Socket from \"effect/unstable/socket/Socket\";\nimport type { Plugin, ViteDevServer } from \"vite\";\nimport { FunctionRuntime, type PreparedFunction } from \"@ignotum/runtime/functions\";\nimport { QueryInvalidation } from \"@ignotum/runtime/sync\";\n\nimport { generate } from \"../cli/codegen.js\";\nimport { isIgnotumPath, syncPath } from \"../internal/http-paths.js\";\nimport { LocalDatabase } from \"./database.js\";\nimport { idGeneratorLayer } from \"./id.js\";\nimport { FunctionExecutor, FunctionRegistry, functionRuntimeLayer } from \"./functions.js\";\n\ninterface QuerySubscription {\n readonly args: Schema.Json;\n readonly function: FunctionAddress;\n}\n\nexport { QueryInvalidation };\n\nexport const queryInvalidationLayer = Layer.effect(\n QueryInvalidation,\n Effect.gen(function* () {\n const pubsub = yield* PubSub.unbounded<void>();\n return QueryInvalidation.of({\n publish: PubSub.publish(pubsub, undefined),\n subscribe: PubSub.subscribe(pubsub),\n });\n }),\n);\n\nconst operationForQuery = (subscriptionId: SubscriptionId): Operation => ({\n type: \"Query\",\n id: subscriptionId,\n});\n\nconst protocolError = (\n code: ProtocolErrorCode,\n message: string,\n operation?: Operation,\n): ServerMessage => {\n if (operation === undefined) {\n return { type: \"ProtocolError\", code, message };\n }\n return { type: \"ProtocolError\", code, message, operation };\n};\n\nexport const runSession = Effect.fn(\"SyncServer.runSession\")(function* (socket: Socket.Socket) {\n const runtime = yield* FunctionRuntime;\n const invalidation = yield* QueryInvalidation;\n const subscriptions = yield* Ref.make(HashMap.empty<SubscriptionId, QuerySubscription>());\n const invocationFibers = yield* FiberSet.make();\n const querySemaphore = yield* PartitionedSemaphore.make<SubscriptionId>({ permits: 1 });\n const messageSemaphore = yield* Semaphore.make(1);\n const writeSemaphore = yield* Semaphore.make(1);\n const write = yield* socket.writer;\n\n const send = Effect.fn(\"SyncServer.send\")(function* (message: ServerMessage) {\n yield* writeSemaphore.withPermits(1)(\n Schema.encodeEffect(ServerMessageJson)(message).pipe(Effect.flatMap(write)),\n );\n });\n\n const sendResolutionError = (\n operation: Operation,\n error:\n | { readonly _tag: \"UnknownFunction\"; readonly message: string }\n | { readonly _tag: \"WrongFunctionKind\"; readonly message: string }\n | { readonly _tag: \"InvalidArguments\"; readonly message: string }\n | { readonly _tag: \"FunctionUnavailable\"; readonly message: string },\n deliver: (\n message: ServerMessage,\n ) => Effect.Effect<void, Schema.SchemaError | Socket.SocketError> = send,\n ) => {\n const code: ProtocolErrorCode = error._tag;\n return deliver(protocolError(code, error.message, operation));\n };\n\n const isActive = (subscriptionId: SubscriptionId, subscription: QuerySubscription) =>\n Ref.get(subscriptions).pipe(\n Effect.map(\n (current) => Option.getOrUndefined(HashMap.get(current, subscriptionId)) === subscription,\n ),\n );\n\n const sendIfActive = Effect.fn(\"SyncServer.sendIfActive\")(function* (\n subscriptionId: SubscriptionId,\n subscription: QuerySubscription,\n message: ServerMessage,\n ) {\n if (yield* isActive(subscriptionId, subscription)) {\n yield* send(message);\n }\n });\n\n const executeQuery = Effect.fn(\"SyncServer.executeQuery\")(function* (\n subscriptionId: SubscriptionId,\n subscription: QuerySubscription,\n previouslyPrepared?: PreparedFunction,\n ) {\n if (!(yield* isActive(subscriptionId, subscription))) return;\n\n const operation = operationForQuery(subscriptionId);\n const deliver = (message: ServerMessage) => sendIfActive(subscriptionId, subscription, message);\n const prepared =\n previouslyPrepared ??\n (yield* runtime.prepare(subscription.function, \"Query\", subscription.args).pipe(\n Effect.catchTags({\n FunctionUnavailable: (error) => sendResolutionError(operation, error, deliver),\n InvalidArguments: (error) => sendResolutionError(operation, error, deliver),\n UnknownFunction: (error) => sendResolutionError(operation, error, deliver),\n WrongFunctionKind: (error) => sendResolutionError(operation, error, deliver),\n }),\n ));\n if (prepared === undefined) return;\n\n const result = yield* prepared.execute;\n yield* deliver({\n type: \"QuerySnapshot\",\n id: subscriptionId,\n result,\n });\n });\n\n const scheduleQuery = (\n subscriptionId: SubscriptionId,\n subscription: QuerySubscription,\n previouslyPrepared?: PreparedFunction,\n ) =>\n querySemaphore\n .withPermits(\n subscriptionId,\n 1,\n )(executeQuery(subscriptionId, subscription, previouslyPrepared))\n .pipe(\n Effect.catchCause((cause) =>\n Effect.logError(\"A query refresh fiber failed.\").pipe(\n Effect.annotateLogs({ cause, function: subscription.function, subscriptionId }),\n ),\n ),\n FiberSet.run(invocationFibers),\n Effect.asVoid,\n );\n\n const refresh = Effect.fn(\"SyncServer.refresh\")(function* () {\n const current = yield* Ref.get(subscriptions);\n yield* Effect.forEach(HashMap.toEntries(current), ([subscriptionId, subscription]) =>\n scheduleQuery(subscriptionId, subscription),\n );\n });\n\n const invalidations = yield* invalidation.subscribe;\n yield* PubSub.take(invalidations).pipe(\n Effect.flatMap(refresh),\n Effect.forever,\n Effect.forkScoped,\n );\n\n const handleSubscribe = Effect.fn(\"SyncServer.handleSubscribe\")(function* (\n message: Extract<ClientMessage, { readonly type: \"Subscribe\" }>,\n ) {\n const operation = operationForQuery(message.id);\n const current = yield* Ref.get(subscriptions);\n\n if (HashMap.has(current, message.id)) {\n yield* send(\n protocolError(\n \"DuplicateOperationId\",\n `Subscription ${message.id} already exists.`,\n operation,\n ),\n );\n return;\n }\n\n const prepared = yield* runtime.prepare(message.function, \"Query\", message.args).pipe(\n Effect.catchTags({\n FunctionUnavailable: (error) => sendResolutionError(operation, error),\n InvalidArguments: (error) => sendResolutionError(operation, error),\n UnknownFunction: (error) => sendResolutionError(operation, error),\n WrongFunctionKind: (error) => sendResolutionError(operation, error),\n }),\n );\n\n if (prepared === undefined) {\n return;\n }\n\n const subscription = { args: message.args, function: message.function };\n yield* Ref.update(subscriptions, HashMap.set(message.id, subscription));\n yield* scheduleQuery(message.id, subscription, prepared);\n });\n\n const handleMutate = Effect.fn(\"SyncServer.handleMutate\")(function* (\n message: Extract<ClientMessage, { readonly type: \"Mutate\" }>,\n ) {\n const operation: Operation = { type: \"Mutate\", id: message.id };\n const prepared = yield* runtime.prepare(message.function, \"Mutation\", message.args).pipe(\n Effect.catchTags({\n FunctionUnavailable: (error) => sendResolutionError(operation, error),\n InvalidArguments: (error) => sendResolutionError(operation, error),\n UnknownFunction: (error) => sendResolutionError(operation, error),\n WrongFunctionKind: (error) => sendResolutionError(operation, error),\n }),\n );\n\n if (prepared === undefined) {\n return;\n }\n\n yield* prepared.execute.pipe(\n Effect.flatMap((result: WireResult) => {\n const response = send({ type: \"MutationResult\", id: message.id, result });\n return result.type === \"Success\"\n ? response.pipe(Effect.ensuring(invalidation.publish))\n : response;\n }),\n Effect.catchCause((cause) =>\n Effect.logError(\"A mutation invocation fiber failed.\").pipe(\n Effect.annotateLogs({ cause, function: message.function, requestId: message.id }),\n ),\n ),\n FiberSet.run(invocationFibers),\n Effect.asVoid,\n );\n });\n\n const handleMessage = Effect.fn(\"SyncServer.handleMessage\")(function* (text: string) {\n const message = yield* Schema.decodeEffect(ClientMessageJson)(text).pipe(\n Effect.catch(() =>\n send(protocolError(\"InvalidMessage\", \"The WebSocket frame is not valid Ignotum JSON.\")),\n ),\n );\n\n if (message === undefined) {\n return;\n }\n\n switch (message.type) {\n case \"Subscribe\":\n yield* handleSubscribe(message);\n return;\n case \"Unsubscribe\":\n yield* Ref.update(subscriptions, HashMap.remove(message.id));\n return;\n case \"Mutate\":\n yield* handleMutate(message);\n return;\n }\n });\n\n yield* socket.runString((text) => messageSemaphore.withPermits(1)(handleMessage(text)));\n});\n\ninterface SyncHandlersService {\n readonly http: (request: IncomingMessage, response: ServerResponse) => void;\n readonly upgrade: NodeJS.EventEmitter extends infer _EventEmitter\n ? (request: IncomingMessage, socket: import(\"node:stream\").Duplex, head: Buffer) => void\n : never;\n readonly reload: (file: string, event: \"add\" | \"change\" | \"unlink\") => Effect.Effect<void>;\n}\n\nclass SyncHandlers extends Context.Service<SyncHandlers, SyncHandlersService>()(\n \"ignotum/dev-runtime/sync/SyncHandlers\",\n) {}\n\nconst makeHandlersLayer = (\n server: ViteDevServer,\n projectDirectory: string,\n databasePath: string,\n) => {\n const databaseLayer = LocalDatabase.layer.pipe(\n Layer.provide(Layer.merge(idGeneratorLayer, SqliteClient.layer({ filename: databasePath }))),\n );\n const executorLayer = FunctionExecutor.layer.pipe(Layer.provide(databaseLayer));\n const devFunctionRuntimeLayer = functionRuntimeLayer.pipe(\n Layer.provide(\n Layer.merge(\n FunctionRegistry.layer(server, projectDirectory).pipe(Layer.provide(NodeServices.layer)),\n executorLayer,\n ),\n ),\n );\n const dependencies = Layer.mergeAll(\n devFunctionRuntimeLayer,\n queryInvalidationLayer,\n NodeServices.layer,\n );\n\n return Layer.effect(\n SyncHandlers,\n Effect.gen(function* () {\n const invalidation = yield* QueryInvalidation;\n const fileSystem = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const scope = yield* Effect.scope;\n const reloadSemaphore = yield* Semaphore.make(1);\n const webSocketServer = yield* Effect.acquireRelease(\n Effect.sync(\n () => new NodeSocket.NodeWS.WebSocketServer({ maxPayload: 1024 * 1024, noServer: true }),\n ),\n (instance) =>\n Effect.callback<void>((resume) => {\n instance.close(() => resume(Effect.void));\n }),\n );\n const httpApp = Effect.gen(function* () {\n const request = yield* HttpServerRequest.HttpServerRequest;\n const pathname = new URL(request.url, \"http://ignotum.local\").pathname;\n return yield* HttpServerResponse.json(\n pathname === syncPath\n ? { code: \"UpgradeRequired\", message: `Connect to ${syncPath} with WebSocket.` }\n : { code: \"NotFound\", message: \"Unknown Ignotum API route.\" },\n { status: pathname === syncPath ? 426 : 404 },\n );\n });\n const socketApp = Effect.gen(function* () {\n const request = yield* HttpServerRequest.HttpServerRequest;\n const socket = yield* request.upgrade;\n yield* runSession(socket);\n return HttpServerResponse.empty();\n });\n const http = yield* NodeHttpServer.makeHandler(httpApp, { scope });\n const upgrade = yield* NodeHttpServer.makeUpgradeHandler(\n Effect.succeed(webSocketServer),\n socketApp,\n { scope },\n );\n const serverDirectory = path.join(projectDirectory, \"server\");\n const reloadUnsafe = Effect.fn(\"SyncServer.reload\")(function* (\n file: string,\n event: \"add\" | \"change\" | \"unlink\",\n ) {\n const relative = path.relative(serverDirectory, file);\n if (relative.startsWith(\"..\") || path.isAbsolute(relative) || !file.endsWith(\".ts\")) {\n return;\n }\n\n if (event !== \"change\") {\n yield* generate(projectDirectory).pipe(\n Effect.provideService(FileSystem.FileSystem, fileSystem),\n Effect.provideService(Path.Path, path),\n );\n }\n yield* invalidation.publish;\n });\n const reload = (file: string, event: \"add\" | \"change\" | \"unlink\") =>\n reloadSemaphore\n .withPermits(1)(reloadUnsafe(file, event))\n .pipe(\n Effect.catchCause((cause) =>\n Effect.logError(\"Could not reload Ignotum server functions.\").pipe(\n Effect.annotateLogs({ cause, event, file }),\n ),\n ),\n );\n\n return SyncHandlers.of({ http, reload, upgrade });\n }),\n ).pipe(Layer.provide(dependencies));\n};\n\nconst isApiPath = (request: IncomingMessage): boolean => {\n const pathname = new URL(request.url ?? \"/\", \"http://ignotum.local\").pathname;\n return isIgnotumPath(pathname);\n};\n\nconst isAppOrigin = (host: string | undefined, origin: string | undefined): boolean => {\n if (host === undefined || origin === undefined) return false;\n\n return Option.match(Schema.decodeOption(Schema.URLFromString)(origin), {\n onNone: () => false,\n onSome: (url) => url.origin === origin && url.host === host,\n });\n};\n\nconst rejectUpgrade = (socket: import(\"node:stream\").Duplex): void => {\n socket.write(\"HTTP/1.1 403 Forbidden\\r\\nConnection: close\\r\\nContent-Length: 0\\r\\n\\r\\n\", () =>\n socket.destroy(),\n );\n};\n\nexport const syncPluginInternals = { isAppOrigin };\n\nexport const ignotumSyncPlugin: {\n (databasePath: string): (projectDirectory: string) => Plugin;\n (projectDirectory: string, databasePath: string): Plugin;\n} = Function.dual(2, (projectDirectory: string, databasePath: string): Plugin => ({\n name: \"ignotum:sync\",\n configureServer: (server) => {\n if (server.httpServer === null) {\n throw new Error(\"Ignotum sync requires Vite's Node HTTP server.\");\n }\n\n const runtime = ManagedRuntime.make(makeHandlersLayer(server, projectDirectory, databasePath));\n const httpServer = server.httpServer;\n return runtime.runPromise(SyncHandlers).then(\n (handlers) => {\n const onUpgrade = (\n request: IncomingMessage,\n socket: import(\"node:stream\").Duplex,\n head: Buffer,\n ) => {\n if (new URL(request.url ?? \"/\", \"http://ignotum.local\").pathname !== syncPath) return;\n if (!isAppOrigin(request.headers.host, request.headers.origin)) {\n rejectUpgrade(socket);\n return;\n }\n handlers.upgrade(request, socket, head);\n };\n const onAdd = (file: string) => runtime.runFork(handlers.reload(file, \"add\"));\n const onChange = (file: string) => runtime.runFork(handlers.reload(file, \"change\"));\n const onUnlink = (file: string) => runtime.runFork(handlers.reload(file, \"unlink\"));\n const cleanup = () => {\n httpServer.off(\"upgrade\", onUpgrade);\n server.watcher.off(\"add\", onAdd);\n server.watcher.off(\"change\", onChange);\n server.watcher.off(\"unlink\", onUnlink);\n void runtime.dispose();\n };\n\n httpServer.on(\"upgrade\", onUpgrade);\n httpServer.once(\"close\", cleanup);\n server.watcher.on(\"add\", onAdd);\n server.watcher.on(\"change\", onChange);\n server.watcher.on(\"unlink\", onUnlink);\n server.middlewares.use((request, response, next) => {\n if (!isApiPath(request)) {\n next();\n return;\n }\n handlers.http(request, response);\n });\n },\n (error) => {\n void runtime.dispose();\n throw error;\n },\n );\n },\n}));\n","import { createRequire } from \"node:module\";\nimport { fileURLToPath } from \"node:url\";\n\nimport prefresh from \"@prefresh/vite\";\nimport tailwindcss from \"@tailwindcss/vite\";\nimport { Effect, FileSystem, Path, Schema } from \"effect\";\nimport { createServer, defaultClientConditions, normalizePath } from \"vite\";\nimport type { Alias, ViteDevServer } from \"vite\";\n\nimport { generate } from \"./codegen.js\";\nimport { ignotumClientPlugin } from \"./client-plugin.js\";\nimport { acquireDevDatabaseLock, devDatabasePath } from \"../dev-runtime/dev-database.js\";\nimport { ignotumSyncPlugin } from \"../dev-runtime/sync.js\";\n\nconst requiredClientFiles = [\"App.tsx\", \"styles.css\"] as const;\nconst preactSpecifiers = [\n \"preact/jsx-dev-runtime\",\n \"preact/jsx-runtime\",\n \"preact/devtools\",\n \"preact/debug\",\n \"preact/hooks\",\n \"preact\",\n] as const;\nconst prefreshSpecifiers = [\"@prefresh/core\", \"@prefresh/utils\"] as const;\n\nexport class ClientFileNotFound extends Schema.TaggedError<ClientFileNotFound>()(\n \"ClientFileNotFound\",\n {\n message: Schema.String,\n path: Schema.String,\n },\n) {}\n\nexport class ClientRuntimeResolutionFailed extends Schema.TaggedError<ClientRuntimeResolutionFailed>()(\n \"ClientRuntimeResolutionFailed\",\n {\n cause: Schema.Defect(),\n message: Schema.String,\n },\n) {}\n\nexport class ViteStartupFailed extends Schema.TaggedError<ViteStartupFailed>()(\n \"ViteStartupFailed\",\n {\n cause: Schema.Defect(),\n message: Schema.String,\n },\n) {}\n\nexport interface DevOptions {\n readonly host: string;\n readonly open: boolean;\n readonly port: number;\n readonly projectDirectory: string;\n}\n\nconst validateClientFiles = Effect.fn(\"Dev.validateClientFiles\")(function* (\n projectDirectory: string,\n) {\n const fileSystem = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const clientDirectory = path.join(projectDirectory, \"client\");\n\n yield* Effect.forEach(\n requiredClientFiles,\n Effect.fn(\"Dev.validateClientFile\")(function* (fileName) {\n const filePath = path.join(clientDirectory, fileName);\n const exists = yield* fileSystem.exists(filePath);\n\n if (!exists) {\n return yield* ClientFileNotFound.make({\n message: `Required client file not found: ${filePath}`,\n path: filePath,\n });\n }\n }),\n { discard: true },\n );\n});\n\nconst resolveClientAliases = Effect.fn(\"Dev.resolveClientAliases\")(function* () {\n return yield* Effect.try({\n try: (): Array<Alias> => {\n const prefreshRequire = createRequire(import.meta.resolve(\"@prefresh/vite\"));\n\n return [\n {\n find: /^tailwindcss$/,\n replacement: normalizePath(fileURLToPath(import.meta.resolve(\"tailwindcss/index.css\"))),\n },\n ...preactSpecifiers.map((specifier) => ({\n find: specifier,\n replacement: normalizePath(fileURLToPath(import.meta.resolve(specifier))),\n })),\n ...prefreshSpecifiers.map((specifier) => ({\n find: specifier,\n replacement: normalizePath(prefreshRequire.resolve(specifier)),\n })),\n ];\n },\n catch: (cause) =>\n ClientRuntimeResolutionFailed.make({\n cause,\n message: \"Ignotum could not resolve its client runtime.\",\n }),\n });\n});\n\nconst acquireViteServer = Effect.fn(\"Dev.acquireViteServer\")(function* (options: DevOptions) {\n const fileSystem = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const aliases = yield* resolveClientAliases();\n const clientDirectory = path.join(options.projectDirectory, \"client\");\n const databasePath = yield* devDatabasePath(options.projectDirectory);\n const stateDirectory = path.dirname(databasePath);\n const sourceClientEntry = fileURLToPath(new URL(\"../../src/client/index.ts\", import.meta.url));\n const sourceContractsEntry = fileURLToPath(\n new URL(\"../../../contracts/src/schema/index.ts\", import.meta.url),\n );\n const hasSourceClient = yield* fileSystem.exists(sourceClientEntry);\n const hasSourceContracts = yield* fileSystem.exists(sourceContractsEntry);\n const hasWorkspaceSourceExports = hasSourceClient && hasSourceContracts;\n\n yield* fileSystem.makeDirectory(stateDirectory, { recursive: true });\n\n return yield* Effect.acquireRelease(\n Effect.tryPromise({\n try: () =>\n prefresh().then((prefreshPlugin) =>\n createServer({\n appType: \"spa\",\n configFile: false,\n mode: \"development\",\n root: clientDirectory,\n plugins: [\n ignotumSyncPlugin(options.projectDirectory, databasePath),\n ignotumClientPlugin(),\n prefreshPlugin,\n tailwindcss(),\n ],\n oxc: {\n jsx: {\n importSource: \"ignotum/client\",\n runtime: \"automatic\",\n },\n },\n resolve: {\n alias: aliases,\n conditions: [\n ...(hasWorkspaceSourceExports ? [\"@ignotum/source\"] : []),\n ...defaultClientConditions,\n ],\n dedupe: [\"preact\"],\n tsconfigPaths: true,\n },\n server: {\n forwardConsole: {\n logLevels: [\"warn\", \"error\"],\n unhandledErrors: true,\n },\n host: options.host,\n open: options.open,\n port: options.port,\n strictPort: true,\n },\n }),\n ),\n catch: (cause) =>\n ViteStartupFailed.make({\n cause,\n message: \"Ignotum could not create the Vite development server.\",\n }),\n }),\n (server) => Effect.promise(() => server.close()),\n );\n});\n\nconst listen = Effect.fn(\"Dev.listen\")(function* (server: ViteDevServer) {\n yield* Effect.tryPromise({\n try: () => server.listen(),\n catch: (cause) =>\n ViteStartupFailed.make({\n cause,\n message: \"Ignotum could not start the Vite development server.\",\n }),\n });\n});\n\nexport const dev = Effect.fn(\"Dev.run\")(function* (options: DevOptions) {\n yield* validateClientFiles(options.projectDirectory);\n yield* generate(options.projectDirectory);\n\n return yield* Effect.scoped(\n Effect.gen(function* () {\n yield* acquireDevDatabaseLock(options.projectDirectory);\n const server = yield* acquireViteServer(options);\n\n yield* listen(server);\n yield* Effect.sync(() => {\n server.printUrls();\n server.bindCLIShortcuts({ print: true });\n });\n return yield* Effect.never;\n }),\n );\n});\n","export default \"# AGENTS.md\\n\\nThis is an Ignotum app. Before changing it, read `.agents/skills/ignotum/SKILL.md`.\\n\\nThe skill explains how to inspect the project, which bundled reference to read, and how to check\\nyour changes.\\n\";","export default \"---\\nname: ignotum\\ndescription: Build and modify an Ignotum app. Use when working on its schema, server functions, generated API, client UI, or local development workflow.\\n---\\n\\n# Working on an Ignotum app\\n\\nAn Ignotum app defines a database schema, server functions, and a JSX client. Ignotum supplies the\\ndatabase runtime, generated bindings, realtime query updates, Vite dev server, JSX runtime, and\\nTailwind setup.\\n\\nThe current release supports local development. Do not assume that authentication, files, actions,\\nworkflows, scheduled jobs, or production deployment APIs exist.\\n\\n## Start with the app\\n\\nInspect `server/schema.ts`, the function modules in `server`, the files in `client`, `package.json`,\\nand `tsconfig.json` before changing code.\\n\\nTreat `_generated` as compiler output. Read it when you need to understand an inferred type, but do\\nnot edit it. After code changes, regenerate the bindings and run the typechecker:\\n\\n```sh\\nnpx ignotum codegen\\nnpx tsc --noEmit\\n```\\n\\nFor normal Ignotum app work, do not add an HTML file, Vite configuration, Tailwind configuration,\\nAPI routes, or direct database setup.\\n\\n## Read the relevant reference\\n\\nThe bundled references are the Ignotum user guides. Read only the guides needed for the task:\\n\\n- For project creation and installation, read [getting started](references/getting-started.md) or\\n [manual setup](references/manual-setup.md).\\n- For tables, fields, IDs, and generated document types, read\\n [schema syntax](references/schema.md).\\n- For validators and their TypeScript types, read [values](references/values.md).\\n- For queries, mutations, database access, Results, and application errors, read\\n [server functions](references/server-functions.md).\\n- For hooks, query state, mutations, JSX, and Tailwind, read [client](references/client.md).\\n- For development commands, code generation, flags, and local data, read\\n [dev server](references/dev-server.md).\\n- For the complete guide list, read the [documentation index](references/index.md).\\n\\n## Rules that cross guide boundaries\\n\\n- Define tables in `server/schema.ts`.\\n- Put queries and mutations in TypeScript files directly inside `server`.\\n- Import server builders from `@/_generated/server.js` and client references from\\n `@/_generated/api.js`. Keep the `.js` suffix.\\n- Put code used by both the client and server in `shared` and import it through `@/shared`.\\n- Never edit `_generated`.\\n- Use JSX and hooks from `ignotum/client`, not React or Preact packages directly.\\n- Keep the app inside Ignotum's current model unless the user explicitly asks to move beyond it.\\n\";","export default \"# Client\\n\\nIgnotum apps use JSX, hooks from `ignotum/client`, and Tailwind CSS. Import server function\\nreferences from `@/_generated/api.js`:\\n\\n```tsx\\nimport { Query, Result, useMutation, useQuery } from \\\"ignotum/client\\\";\\n\\nimport { api } from \\\"@/_generated/api.js\\\";\\n```\\n\\n## Tailwind CSS\\n\\nEvery app has `client/styles.css` with the Tailwind import:\\n\\n```css\\n@import \\\"tailwindcss\\\";\\n```\\n\\nStyle JSX with Tailwind utility classes. Use the JSX `class` attribute:\\n\\n```tsx\\nexport default function App() {\\n return (\\n <main class=\\\"mx-auto max-w-xl px-6 py-16\\\">\\n <h1 class=\\\"text-2xl font-semibold text-zinc-950\\\">Todos</h1>\\n </main>\\n );\\n}\\n```\\n\\nThe dev server loads `styles.css` and configures Tailwind. The app does not need a Tailwind\\nconfiguration file.\\n\\n## Run a query\\n\\n`useQuery` takes a generated query reference. Pass the typed arguments when the query declares\\nthem:\\n\\n```tsx\\nconst todos = useQuery(api.todos.list);\\nconst todo = useQuery(api.todos.get, { id });\\nconst selectedTodo = useQuery(api.todos.get, id === undefined ? Query.skip : { id });\\n```\\n\\n`Query.skip` keeps a query pending without opening a subscription. Use it when the arguments are\\nnot available yet.\\n\\nThe first value is pending. Match every state with `Result.match`:\\n\\n```tsx\\nreturn Result.match(todos, {\\n pending: () => <p class=\\\"text-zinc-500\\\">Loading...</p>,\\n value: (items) => (\\n <ul>\\n {items.map((todo) => (\\n <li key={todo.id}>{todo.text}</li>\\n ))}\\n </ul>\\n ),\\n});\\n```\\n\\nIgnotum keeps an active query up to date. A successful mutation refreshes subscribed queries in\\nevery open client.\\n\\n## Run a mutation\\n\\n`useMutation` takes a generated mutation reference and returns a function:\\n\\n```tsx\\nconst createTodo = useMutation(api.todos.create);\\n\\nvoid createTodo({ text }).then(\\n Result.match({\\n value: (id) => console.log(id),\\n error: {\\n InvalidTodoText: ({ text }) => console.log(`Invalid text: ${text}`),\\n TodoLimitReached: ({ limit }) => console.log(`The limit is ${limit}`),\\n },\\n internalError: ({ requestId }) => console.log(`Request ${requestId} failed.`),\\n }),\\n);\\n```\\n\\nAn argument-free mutation returns a zero-argument function:\\n\\n```tsx\\nconst clearTodos = useMutation(api.todos.clear);\\nvoid clearTodos();\\n```\\n\\nThe client `Result` API only inspects completed server responses. Server-only operations such as\\n`Result.fail`, `Result.succeed`, `Result.try`, `yield*`, and `.catch()` are not available here.\\n\\nApplication errors are handled by `error`, either with one function or an exhaustive map keyed by\\n`_tag`. An `InternalServerError` contains a request ID and is thrown when `Result.match` has no\\n`internalError` handler. During rendering, it reaches the nearest UI error boundary. A mutation can\\nhandle it locally with `internalError`, as above. Connection and protocol failures reject mutation\\npromises; query connection failures go to the nearest UI error boundary.\\n\";","export default \"# Dev server\\n\\nRun the dev server from the project root:\\n\\n```sh\\nnpx ignotum dev\\n```\\n\\nIt expects these files:\\n\\n```text\\nclient/App.tsx\\nclient/styles.css\\nserver/schema.ts\\n```\\n\\nThe dev server generates the client and server bindings, mounts the default export from\\n`client/App.tsx`, loads Tailwind from `client/styles.css`, and serves the app at\\n<http://127.0.0.1:3210>. It reloads client and server changes and updates active queries after\\nserver changes and successful mutations.\\n\\nYou do not need an HTML file, Vite configuration, or Tailwind configuration.\\n\\n## Flags\\n\\nUse flags to change the address or open the browser:\\n\\n```sh\\nnpx ignotum dev --host 0.0.0.0 --port 3000 --open\\n```\\n\\nThe defaults are host `127.0.0.1`, port `3210`, and no automatic browser opening.\\n\\n## Code generation\\n\\nThe dev server runs code generation when it starts. It updates generated files when you add or\\nremove a server function file.\\n\\nRun code generation before typechecking without the dev server:\\n\\n```sh\\nnpx ignotum codegen\\nnpx tsc --noEmit\\n```\\n\\nIgnotum creates:\\n\\n- `_generated/server.ts` with schema-bound `query`, `mutation`, and `values` exports;\\n- `_generated/api.ts` with client references such as `api.todos.list`;\\n- `_generated/types.ts` with `DataModel`, `Doc`, and `Id`.\\n\\nDo not edit generated files.\\n\\n## Local data\\n\\nData persists between dev-server restarts. Stop the server and reset that data with:\\n\\n```sh\\nnpx ignotum dev db reset\\n```\\n\";","export default \"# Getting started\\n\\nIgnotum requires Node.js 22.18 or newer.\\n\\nCreate an app:\\n\\n```sh\\nnpx ignotum new my-app\\ncd my-app\\nnpx ignotum dev\\n```\\n\\nOpen <http://127.0.0.1:3210>. The generated app is a small counter with a schema, a query, a\\nmutation, and a JSX client.\\n\\n`ignotum new` installs dependencies with pnpm when it is available. It falls back to npm only when\\npnpm is not installed. It generates `_generated`, initializes a Git repository, and creates an\\n`Init` commit containing the generated files after the rest of the setup finishes.\\n\\nPass `.` to create the app in the current directory. The directory must be empty:\\n\\n```sh\\nnpx ignotum new .\\n```\\n\\nUse `--no-git` to skip Git or `--no-install` to skip dependency installation. You can install the\\ndependencies later with the same pnpm and npm fallback behavior:\\n\\n```sh\\nnpx ignotum install\\n```\\n\\nRead [schema syntax](schema.md), [server functions](server-functions.md), and the\\n[client guide](client.md) to build the app. The [manual setup](manual-setup.md) recreates the counter\\napp without `ignotum new`.\\n\";","export default \"# Ignotum\\n\\nAn Ignotum app has a schema, server functions, and a client. Ignotum is opinionated about the\\nclient tooling. Every app uses JSX, hooks from `ignotum/client`, and Tailwind CSS.\\n\\nThe current release supports local development.\\n\\n- [Getting started](getting-started.md) creates and runs a counter app with `ignotum new`.\\n- [Manual setup](manual-setup.md) recreates the generated counter app by hand.\\n- [Schema syntax](schema.md) covers tables, fields, IDs, and generated document types.\\n- [Values](values.md) lists every value validator and its TypeScript type.\\n- [Server functions](server-functions.md) covers queries, mutations, database access, and errors.\\n- [Client](client.md) covers queries, mutations, results, and Tailwind styling.\\n- [Dev server](dev-server.md) covers local development, code generation, flags, and data reset.\\n\";","export default \"# Manual setup\\n\\nIgnotum requires Node.js 22.18 or newer. This guide recreates the counter app from `ignotum new`\\nwithout running the project generator. It uses pnpm to install dependencies.\\n\\nCreate the project directory:\\n\\n```sh\\nmkdir my-ignotum-app\\ncd my-ignotum-app\\n```\\n\\nCreate this structure:\\n\\n```text\\nmy-ignotum-app/\\n client/\\n App.tsx\\n styles.css\\n server/\\n counter.ts\\n schema.ts\\n shared/\\n utils.ts\\n package.json\\n tsconfig.json\\n```\\n\\n## Configure the package\\n\\nAdd `package.json`:\\n\\n```json\\n{\\n \\\"name\\\": \\\"my-ignotum-app\\\",\\n \\\"private\\\": true,\\n \\\"version\\\": \\\"0.0.0\\\",\\n \\\"type\\\": \\\"module\\\",\\n \\\"scripts\\\": {\\n \\\"typecheck\\\": \\\"ignotum codegen && tsc --noEmit\\\"\\n },\\n \\\"dependencies\\\": {\\n \\\"ignotum\\\": \\\"latest\\\"\\n },\\n \\\"devDependencies\\\": {\\n \\\"typescript\\\": \\\"^7.0.2\\\"\\n },\\n \\\"engines\\\": {\\n \\\"node\\\": \\\">=22.18.0\\\"\\n }\\n}\\n```\\n\\nInstall the dependencies:\\n\\n```sh\\npnpm install\\n```\\n\\n## Configure TypeScript\\n\\nAdd `tsconfig.json`:\\n\\n```json\\n{\\n \\\"compilerOptions\\\": {\\n \\\"target\\\": \\\"ES2023\\\",\\n \\\"lib\\\": [\\\"ES2023\\\", \\\"DOM\\\", \\\"DOM.Iterable\\\"],\\n \\\"module\\\": \\\"NodeNext\\\",\\n \\\"moduleResolution\\\": \\\"NodeNext\\\",\\n \\\"jsx\\\": \\\"react-jsx\\\",\\n \\\"jsxImportSource\\\": \\\"ignotum/client\\\",\\n \\\"strict\\\": true,\\n \\\"noEmit\\\": true,\\n \\\"skipLibCheck\\\": true,\\n \\\"paths\\\": {\\n \\\"@/*\\\": [\\\"./*\\\"]\\n }\\n },\\n \\\"include\\\": [\\\"_generated\\\", \\\"client\\\", \\\"server\\\", \\\"shared\\\"]\\n}\\n```\\n\\n## Add shared code\\n\\nAdd `shared/utils.ts`:\\n\\n```ts\\nexport const counterIncrement = 1;\\n```\\n\\nBoth the client and server can import files in `shared` through `@/shared`.\\n\\n## Define the schema\\n\\nAdd `server/schema.ts`:\\n\\n```ts\\nimport { defineSchema } from \\\"ignotum/server\\\";\\n\\nexport default defineSchema(({ table, values }) => ({\\n counters: table({\\n value: values.number(),\\n }),\\n}));\\n```\\n\\n## Add the server functions\\n\\nAdd `server/counter.ts`:\\n\\n```ts\\nimport { mutation, query, values } from \\\"@/_generated/server.js\\\";\\nimport { counterIncrement } from \\\"@/shared/utils.js\\\";\\n\\nexport const get = query({\\n returns: values.number(),\\n\\n handler: function* (ctx) {\\n const counters = yield* ctx.db.query(\\\"counters\\\").collect();\\n return counters[0]?.value ?? 0;\\n },\\n});\\n\\nexport const increment = mutation({\\n returns: values.number(),\\n\\n handler: function* (ctx) {\\n const counters = yield* ctx.db.query(\\\"counters\\\").collect();\\n const counter = counters[0];\\n const value = (counter?.value ?? 0) + counterIncrement;\\n\\n if (counter === undefined) {\\n yield* ctx.db.insert(\\\"counters\\\", { value });\\n } else {\\n yield* ctx.db.patch(\\\"counters\\\", counter.id, { value });\\n }\\n\\n return value;\\n },\\n});\\n```\\n\\nKeep the `.js` suffix on imports from `@/_generated`, even though the generated files use\\nTypeScript.\\n\\n## Add the client\\n\\nAdd `client/styles.css`:\\n\\n```css\\n@import \\\"tailwindcss\\\";\\n```\\n\\nAdd `client/App.tsx`:\\n\\n```tsx\\nimport { Result, useMutation, useQuery } from \\\"ignotum/client\\\";\\n\\nimport { api } from \\\"@/_generated/api.js\\\";\\nimport { counterIncrement } from \\\"@/shared/utils.js\\\";\\n\\nexport default function App() {\\n const count = useQuery(api.counter.get);\\n const increment = useMutation(api.counter.increment);\\n\\n return (\\n <main class=\\\"mx-auto max-w-sm px-6 py-20 text-center\\\">\\n <h1 class=\\\"text-2xl font-semibold\\\">Counter</h1>\\n {Result.match(count, {\\n pending: () => <p class=\\\"mt-6\\\">Loading...</p>,\\n value: (value) => (\\n <>\\n <p class=\\\"my-6 text-5xl tabular-nums\\\">{value}</p>\\n <button\\n class=\\\"rounded bg-zinc-900 px-4 py-2 text-white\\\"\\n type=\\\"button\\\"\\n onClick={() => void increment()}\\n >\\n Increment by {counterIncrement}\\n </button>\\n </>\\n ),\\n })}\\n </main>\\n );\\n}\\n```\\n\\nIgnotum loads Tailwind from `client/styles.css`. You do not need an HTML file, Vite configuration,\\nor Tailwind configuration.\\n\\n## Run the app\\n\\nStart the dev server:\\n\\n```sh\\nnpx ignotum dev\\n```\\n\\nOpen <http://127.0.0.1:3210>. Ignotum creates `_generated` before starting the app.\\n\\nRead [schema syntax](schema.md), [server functions](server-functions.md), and the\\n[client guide](client.md) to continue building the app.\\n\";","export default \"# Schema syntax\\n\\nDefine the data model in `server/schema.ts`. The keys returned from `defineSchema` are table\\nnames, and each `table` call defines that table's fields:\\n\\n```ts\\nimport { defineSchema } from \\\"ignotum/server\\\";\\n\\nexport default defineSchema(({ table, values }) => ({\\n users: table({\\n name: values.string(),\\n }),\\n todos: table({\\n text: values.string(),\\n completed: values.boolean(),\\n ownerId: values.optional(values.id(\\\"users\\\")),\\n }),\\n}));\\n```\\n\\n## Field values\\n\\nRead [values](values.md) for the complete validator list and the TypeScript type produced by each\\none. `values.id` only accepts a table declared in the same schema. Arrays and objects can be nested,\\nand their contents can use any value validator.\\n\\n## System fields\\n\\nIgnotum adds three fields to every stored document:\\n\\n| Field | Type |\\n| ----------- | ------------------------- |\\n| `id` | The ID type for its table |\\n| `createdAt` | `Date` |\\n| `updatedAt` | `Date` |\\n\\nDo not declare these fields in a table. Do not pass them to `insert`, `patch`, or `replace`.\\n\\n## Generated types\\n\\n`_generated/types.ts` exports the data model, document, and ID types:\\n\\n```ts\\nimport type { DataModel, Doc, Id } from \\\"@/_generated/types.js\\\";\\n\\ntype Todo = Doc<\\\"todos\\\">;\\ntype TodoId = Id<\\\"todos\\\">;\\n```\\n\\n`Doc<\\\"todos\\\">` includes the fields from the `todos` table and its three system fields. An\\n`Id<\\\"todos\\\">` cannot be passed where an `Id<\\\"users\\\">` is required.\\n\";","export default \"# Server functions\\n\\nPut queries and mutations in `.ts` files directly inside `server`. The file name becomes the API\\nmodule, and each exported function keeps its export name:\\n\\n```text\\nserver/todos.ts -> api.todos.list\\nserver/users.ts -> api.users.get\\n```\\n\\nIgnotum ignores `schema.ts`, `index.ts`, test files, and names beginning with `_`.\\n\\nImport schema-bound builders from the generated server file. Import `Result` only when the module\\nintroduces or catches typed errors:\\n\\n```ts\\nimport { Result } from \\\"ignotum/server\\\";\\n\\nimport { mutation, query, values } from \\\"@/_generated/server.js\\\";\\n```\\n\\nKeep the `.js` suffix on generated imports.\\n\\n## Define a function\\n\\nA function has optional argument, return, and public error schemas, plus a generator handler:\\n\\n```ts\\nexport const getTitle = query({\\n args: {\\n id: values.id(\\\"todos\\\"),\\n },\\n returns: values.string(),\\n\\n handler: function* (ctx, args) {\\n const todo = yield* ctx.db.get(\\\"todos\\\", args.id);\\n return todo.text;\\n },\\n});\\n```\\n\\nOmit `args` when the function takes no arguments. Omit `returns` when it returns nothing. An\\nomitted `returns` only permits a `void` handler; Ignotum never infers an unchecked return schema.\\n`yield*` waits for an Ignotum operation and propagates its typed application errors. Return\\nsuccessful values with ordinary `return`.\\n\\nIgnotum validates arguments before running the handler. It also validates returned values and\\npublic application errors before sending them to a client.\\n\\nAn argument-free query and a mutation with no return value can stay small:\\n\\n```ts\\nconst Todo = values.doc(\\\"todos\\\");\\n\\nexport const list = query({\\n returns: values.array(Todo),\\n\\n handler: function* (ctx) {\\n return yield* ctx.db.query(\\\"todos\\\").collect();\\n },\\n});\\n\\nexport const remove = mutation({\\n args: { id: values.id(\\\"todos\\\") },\\n\\n handler: function* (ctx, args) {\\n yield* ctx.db.delete(\\\"todos\\\", args.id);\\n },\\n});\\n```\\n\\nCall an argument-free query as `useQuery(api.todos.list)`. An argument-free mutation returns a\\nzero-argument function:\\n\\n```ts\\nconst clear = useMutation(api.todos.clear);\\nvoid clear();\\n```\\n\\n## Database reads\\n\\nUse `find` when a missing document is a normal result:\\n\\n```ts\\nconst todo = yield * ctx.db.find(\\\"todos\\\", args.id);\\n// Todo | undefined\\n```\\n\\nUse `get` when the document should exist:\\n\\n```ts\\nconst todo = yield * ctx.db.get(\\\"todos\\\", args.id);\\n// Todo\\n```\\n\\nA missing `get` fails with a typed `DocumentNotFound` value containing `table` and `id`. Collect a\\nwhole table through a query:\\n\\n```ts\\nconst todos = yield * ctx.db.query(\\\"todos\\\").collect();\\n```\\n\\nQuery handlers only receive read methods.\\n\\n## Database writes\\n\\nMutation handlers receive the read methods and these writes:\\n\\n```ts\\nconst id =\\n yield *\\n ctx.db.insert(\\\"todos\\\", {\\n text: \\\"Learn Ignotum\\\",\\n completed: false,\\n });\\n\\nyield * ctx.db.patch(\\\"todos\\\", id, { completed: true });\\n\\nyield *\\n ctx.db.replace(\\\"todos\\\", id, {\\n text: \\\"Build an app\\\",\\n completed: false,\\n });\\n\\nyield * ctx.db.delete(\\\"todos\\\", id);\\n```\\n\\n`patch` changes only supplied fields. `replace` requires every non-optional table field. Ignotum\\nrolls back a mutation when its handler fails with a typed application error or encounters an\\ninternal failure.\\n\\n## Application errors\\n\\nDefine an application error with `values.error`. Its name becomes `_tag`:\\n\\n```ts\\nconst TodoNotFound = values.error(\\\"TodoNotFound\\\", {\\n id: values.id(\\\"todos\\\"),\\n});\\n```\\n\\n`Result.fail` deliberately stops the operation with a typed error:\\n\\n```ts\\nyield * Result.fail(TodoNotFound({ id: args.id }));\\n```\\n\\nThe `errors` field is optional. If omitted, Ignotum infers the handler's remaining application\\nerrors. If supplied, it is the public contract and the handler must conform to it:\\n\\n```ts\\nexport const toggle = mutation({\\n args: {\\n id: values.id(\\\"todos\\\"),\\n },\\n returns: values.boolean(),\\n errors: TodoNotFound,\\n\\n handler: function* (ctx, args) {\\n const todo = yield* ctx.db.get(\\\"todos\\\", args.id).catch({\\n DocumentNotFound: (error) => Result.fail(TodoNotFound({ id: error.id })),\\n });\\n\\n const completed = !todo.completed;\\n yield* ctx.db.patch(\\\"todos\\\", args.id, { completed });\\n return completed;\\n },\\n});\\n```\\n\\nCombine public errors with `values.union`:\\n\\n```ts\\nerrors: values.union(InvalidTodoText, TodoLimitReached),\\n```\\n\\n## Catch and recover\\n\\nEvery Result operation has a partial, tag-based `catch`. Handlers receive the narrowed error type.\\nUnmatched errors continue through the channel:\\n\\n```ts\\nconst settings =\\n yield *\\n loadSettings().catch({\\n SettingsNotFound: () => defaultSettings,\\n });\\n```\\n\\nReturn a plain value to recover. Return `Result.fail(...)` to map one error to another. Unknown tag\\nnames fail the TypeScript check.\\n\\nUse `Result.try` for one catch boundary around several operations:\\n\\n```ts\\nconst author =\\n yield *\\n Result.try(function* () {\\n const membership = yield* ctx.db.get(\\\"memberships\\\", topic.membershipId);\\n return yield* ctx.db.get(\\\"users\\\", membership.userId);\\n }).catch({\\n DocumentNotFound: () => Result.fail(InvalidAuthor({ topicId: topic.id })),\\n });\\n```\\n\\nThere is no async variant. Ignotum operations always use `yield*` in server code.\\n\\n## Standalone results\\n\\n`Result.succeed` remains useful for helpers that return a Result:\\n\\n```ts\\nfunction validateName(name: string) {\\n if (name.length === 0) {\\n return Result.fail(InvalidName({}));\\n }\\n\\n return Result.succeed(name.trim());\\n}\\n```\\n\\nA handler can use the helper with `const name = yield* validateName(args.name)`. Normal handlers do\\nnot wrap successful returns in `Result.succeed`.\\n\\n## Internal failures and defects\\n\\nDatabase outages, internal runtime failures, and thrown JavaScript exceptions are not application\\nerrors. Ignotum logs their full cause and sends only:\\n\\n```ts\\n{\\n _tag: \\\"InternalServerError\\\",\\n requestId: \\\"...\\\",\\n}\\n```\\n\\nEvery generated client function includes `InternalServerError` in its Result error union. The\\nrequest ID links the client-visible failure to server logs without exposing private details.\\n`InternalServerError` is reserved by Ignotum: never define it with `values.error` or include it in a\\nfunction's `errors` schema.\\n\";","export default \"# Values\\n\\nUse `values` validators to describe table fields, function arguments, return values, and application\\nerrors. Each validator checks values at runtime and supplies the matching TypeScript type.\\n\\n| Validator | TypeScript type | Notes |\\n| ----------------------------------------- | ------------------------------------- | ---------------------------------------------------------------------------------------------------- |\\n| `values.string()` | `string` | |\\n| `values.number()` | `number` | Accepts finite JavaScript numbers, including integers. |\\n| `values.integer()` | `number` | Accepts safe integers. |\\n| `values.boolean()` | `boolean` | |\\n| `values.date()` | `Date` | Accepts valid JavaScript dates. |\\n| `values.null()` | `null` | Accepts only `null`. |\\n| `values.literal(value)` | The exact type of `value` | Accepts one string, finite number, or boolean value. |\\n| `values.literals(first, second, ...rest)` | A union of the supplied literal types | Requires at least two string, finite number, or boolean values. |\\n| `values.id(\\\"todos\\\")` | `Id<\\\"todos\\\">` | Accepts an ID for a table declared in the same schema. IDs for different tables are different types. |\\n| `values.doc(\\\"todos\\\")` | `Doc<\\\"todos\\\">` | Accepts a complete document, including its `id`, `createdAt`, and `updatedAt` system fields. |\\n| `values.optional(value)` | `T \\\\| undefined` | Makes an object or table field optional. The field may be omitted. |\\n| `values.nullable(value)` | `T \\\\| null` | The value remains required unless it is also wrapped with `optional`. |\\n| `values.array(value)` | `ReadonlyArray<T>` | Every item must match `value`. |\\n| `values.object(fields)` | An object matching `fields` | Defines an object with known field names. |\\n| `values.record(value)` | `Readonly<Record<string, T>>` | Defines an object with dynamic string keys whose values all match `value`. |\\n| `values.union(...values)` | A union of the supplied types | Accepts a value matching any supplied validator. |\\n| `values.never()` | `never` | No value can pass this validator. |\\n| `values.error(\\\"Name\\\", fields)` | A tagged error object | Defines an application error whose `_tag` is the supplied name. |\\n\\n`T` means the TypeScript type produced by the wrapped validator.\\n\\n`values.doc` is available on the schema-bound `values` exported by `_generated/server.ts`. It is\\nnot available while defining `server/schema.ts`, because the table definitions are still being\\ncreated there.\\n\\n## Object transforms\\n\\nValidators created by `values.object(fields)` and `values.doc(\\\"table\\\")` support these chainable\\nmethods:\\n\\n| Method | Result |\\n| ------------------- | -------------------------------------------------------------------- |\\n| `.pick(...keys)` | Keeps the listed fields. Every key must exist. |\\n| `.omit(...keys)` | Removes the listed fields. Every key must exist. |\\n| `.extend(fields)` | Adds fields. It rejects names that already exist. |\\n| `.override(fields)` | Replaces validators for existing fields. It rejects new field names. |\\n| `.partial()` | Makes every current field optional. |\\n\\nEach method works from the result of the previous method. Added fields can be picked, omitted, or\\noverridden immediately. An omitted name can be added again with a different validator.\\n\\n```ts\\nconst TodoInput = values.doc(\\\"todos\\\").omit(\\\"id\\\", \\\"createdAt\\\", \\\"updatedAt\\\").partial().extend({\\n requestId: values.string(),\\n});\\n```\\n\\nUse `override` when changing an existing field. This makes replacements visible in the definition\\nand prevents `extend` from silently weakening fields such as `id`:\\n\\n```ts\\nconst EditableTodo = values.doc(\\\"todos\\\").override({\\n title: values.optional(values.string()),\\n});\\n```\\n\\nThese methods are only available on fixed object validators. Arrays, records, unions, errors, and\\nprimitive validators do not expose them. After transforming a document validator, its inferred type\\nmatches the current fields in the chain rather than the complete document type.\\n\\n### Reuse embedded objects in the schema\\n\\nCreate a fixed object validator inside the `defineSchema` callback when several stored fields share\\nan object shape. A transform can derive a stored variant without repeating its fields:\\n\\n```ts\\ndefineSchema(({ table, values }) => {\\n const Contact = values.object({\\n email: values.string(),\\n phone: values.string(),\\n });\\n\\n return {\\n users: table({\\n contact: Contact,\\n }),\\n publicProfiles: table({\\n contact: Contact.omit(\\\"phone\\\"),\\n }),\\n };\\n});\\n```\\n\\nThis pattern suits embedded objects stored by more than one table, including full and reduced\\nversions of the same object. The base validator stays inside `defineSchema`, where `values.id` can\\ncheck its table references against the completed schema.\\n\\n### Derive server function validators from documents\\n\\nUse the schema-bound `values` from `_generated/server.ts` when a function input or output follows a\\nstored document. These validators know every table name and the complete document fields, including\\n`id`, `createdAt`, and `updatedAt`.\\n\\nReusable server validators can live in an ignored server module such as `server/_validators.ts`:\\n\\n```ts\\nimport { values } from \\\"@/_generated/server.js\\\";\\n\\nexport const TodoInput = values.doc(\\\"todos\\\").omit(\\\"id\\\", \\\"createdAt\\\", \\\"updatedAt\\\").partial();\\n\\nexport const PublicTodo = values.doc(\\\"todos\\\").omit(\\\"updatedAt\\\");\\n```\\n\\nImport these validators into queries and mutations that need the same contract. This works well for\\npatch inputs and document projections. Do not import generated validators into `server/schema.ts`.\\nDocument validators depend on the schema, so importing them while defining that schema would create\\na cycle.\\n\\n## Examples\\n\\n```ts\\nconst TodoStatus = values.literals(\\\"pending\\\", \\\"completed\\\");\\n\\nconst Todo = values.doc(\\\"todos\\\");\\n\\nexport const list = query({\\n returns: values.array(Todo),\\n handler: function* (ctx) {\\n return yield* ctx.db.query(\\\"todos\\\").collect();\\n },\\n});\\n```\\n\\nUse the other validators to define reusable values that do not represent a stored document:\\n\\n```ts\\nconst TodoInput = values.object({\\n status: TodoStatus,\\n scheduledAt: values.nullable(values.date()),\\n scores: values.record(values.integer()),\\n title: values.string(),\\n});\\n```\\n\\nUse `optional` when a field may be absent. Use `nullable` when a present field may contain `null`:\\n\\n```ts\\nvalues.object({\\n nickname: values.optional(values.string()),\\n deletedAt: values.nullable(values.date()),\\n});\\n```\\n\";","import agents from \"../../../../docs/agent/AGENTS.md?raw\";\nimport skill from \"../../../../docs/agent/skills/ignotum/SKILL.md?raw\";\nimport client from \"../../../../docs/user/client.md?raw\";\nimport devServer from \"../../../../docs/user/dev-server.md?raw\";\nimport gettingStarted from \"../../../../docs/user/getting-started.md?raw\";\nimport index from \"../../../../docs/user/index.md?raw\";\nimport manualSetup from \"../../../../docs/user/manual-setup.md?raw\";\nimport schema from \"../../../../docs/user/schema.md?raw\";\nimport serverFunctions from \"../../../../docs/user/server-functions.md?raw\";\nimport values from \"../../../../docs/user/values.md?raw\";\n\nexport interface ProjectFile {\n readonly content: string;\n readonly path: string;\n}\n\nconst references = [\n [\"client.md\", client],\n [\"dev-server.md\", devServer],\n [\"getting-started.md\", gettingStarted],\n [\"index.md\", index],\n [\"manual-setup.md\", manualSetup],\n [\"schema.md\", schema],\n [\"server-functions.md\", serverFunctions],\n [\"values.md\", values],\n] as const;\n\nexport const agentProjectFiles: ReadonlyArray<ProjectFile> = [\n { content: agents, path: \"AGENTS.md\" },\n { content: skill, path: \".agents/skills/ignotum/SKILL.md\" },\n ...references.map(([name, content]) => ({\n content,\n path: `.agents/skills/ignotum/references/${name}`,\n })),\n];\n","import { Effect, Schema } from \"effect\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/unstable/process\";\n\nexport type PackageManager = \"npm\" | \"pnpm\";\n\nexport class DependencyInstallationFailed extends Schema.TaggedError<DependencyInstallationFailed>()(\n \"DependencyInstallationFailed\",\n {\n cause: Schema.optional(Schema.Defect()),\n message: Schema.String,\n path: Schema.String,\n },\n) {}\n\nconst installWith = Effect.fn(\"PackageManager.installWith\")(function* (\n projectDirectory: string,\n packageManager: PackageManager,\n) {\n const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n const exitCode = yield* spawner.exitCode(\n ChildProcess.make(packageManager, [\"install\"], {\n cwd: projectDirectory,\n stderr: \"inherit\",\n stdin: \"inherit\",\n stdout: \"inherit\",\n }),\n );\n\n if (exitCode !== ChildProcessSpawner.ExitCode(0)) {\n return yield* DependencyInstallationFailed.make({\n message: `${packageManager} install exited with code ${exitCode} in ${projectDirectory}.`,\n path: projectDirectory,\n });\n }\n\n return packageManager;\n});\n\nexport const installDependencies = Effect.fn(\"PackageManager.installDependencies\")(function* (\n projectDirectory: string,\n) {\n return yield* installWith(projectDirectory, \"pnpm\").pipe(\n Effect.catchReasons(\"PlatformError\", {\n NotFound: () => installWith(projectDirectory, \"npm\"),\n }),\n Effect.catchTags({\n PlatformError: (cause) =>\n DependencyInstallationFailed.make({\n cause,\n message: `Could not run pnpm or npm in ${projectDirectory}.`,\n path: projectDirectory,\n }),\n }),\n );\n});\n","import { Effect, FileSystem, Path, Schema, String } from \"effect\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/unstable/process\";\n\nimport { agentProjectFiles, type ProjectFile } from \"./agent-files.js\";\nimport { generate } from \"./codegen.js\";\nimport { installDependencies, type PackageManager } from \"./package-manager.js\";\n\nexport interface NewProjectOptions {\n readonly currentDirectory: string;\n readonly directory: string;\n readonly git: boolean;\n readonly install: boolean;\n}\n\nexport interface NewProjectResult {\n readonly directory: string;\n readonly gitInitialized: boolean;\n readonly packageManager: PackageManager | null;\n readonly projectName: string;\n}\n\nexport class ProjectDirectoryNotEmpty extends Schema.TaggedError<ProjectDirectoryNotEmpty>()(\n \"ProjectDirectoryNotEmpty\",\n {\n message: Schema.String,\n path: Schema.String,\n },\n) {}\n\nexport class InvalidProjectName extends Schema.TaggedError<InvalidProjectName>()(\n \"InvalidProjectName\",\n {\n message: Schema.String,\n path: Schema.String,\n },\n) {}\n\nexport class GitInitializationFailed extends Schema.TaggedError<GitInitializationFailed>()(\n \"GitInitializationFailed\",\n {\n cause: Schema.optional(Schema.Defect()),\n message: Schema.String,\n path: Schema.String,\n },\n) {}\n\nconst packageJson = (projectName: string): string =>\n `${JSON.stringify(\n {\n name: projectName,\n private: true,\n version: \"0.0.0\",\n type: \"module\",\n scripts: {\n typecheck: \"ignotum codegen && tsc --noEmit\",\n },\n dependencies: {\n ignotum: \"latest\",\n },\n devDependencies: {\n typescript: \"^7.0.2\",\n },\n engines: {\n node: \">=22.18.0\",\n },\n },\n null,\n 2,\n )}\\n`;\n\nconst tsconfig = `{\n \"compilerOptions\": {\n \"target\": \"ES2023\",\n \"lib\": [\"ES2023\", \"DOM\", \"DOM.Iterable\"],\n \"module\": \"NodeNext\",\n \"moduleResolution\": \"NodeNext\",\n \"jsx\": \"react-jsx\",\n \"jsxImportSource\": \"ignotum/client\",\n \"strict\": true,\n \"noEmit\": true,\n \"skipLibCheck\": true,\n \"paths\": {\n \"@/*\": [\"./*\"]\n }\n },\n \"include\": [\"_generated\", \"client\", \"server\", \"shared\"]\n}\n`;\n\nconst gitignore = `node_modules/\n.ignotum/\n\n.env\n.env.*\n!.env.example\n\n.DS_Store\nThumbs.db\n`;\n\nconst schema = `import { defineSchema } from \"ignotum/server\";\n\nexport default defineSchema(({ table, values }) => ({\n counters: table({\n value: values.number(),\n }),\n}));\n`;\n\nconst counterFunctions = `import { mutation, query, values } from \"@/_generated/server.js\";\nimport { counterIncrement } from \"@/shared/utils.js\";\n\nexport const get = query({\n returns: values.number(),\n\n handler: function* (ctx) {\n const counters = yield* ctx.db.query(\"counters\").collect();\n return counters[0]?.value ?? 0;\n },\n});\n\nexport const increment = mutation({\n returns: values.number(),\n\n handler: function* (ctx) {\n const counters = yield* ctx.db.query(\"counters\").collect();\n const counter = counters[0];\n const value = (counter?.value ?? 0) + counterIncrement;\n\n if (counter === undefined) {\n yield* ctx.db.insert(\"counters\", { value });\n } else {\n yield* ctx.db.patch(\"counters\", counter.id, { value });\n }\n\n return value;\n },\n});\n`;\n\nconst app = `import { Result, useMutation, useQuery } from \"ignotum/client\";\n\nimport { api } from \"@/_generated/api.js\";\nimport { counterIncrement } from \"@/shared/utils.js\";\n\nexport default function App() {\n const count = useQuery(api.counter.get);\n const increment = useMutation(api.counter.increment);\n\n return (\n <main class=\"mx-auto max-w-sm px-6 py-20 text-center\">\n <h1 class=\"text-2xl font-semibold\">Counter</h1>\n {Result.match(count, {\n pending: () => <p class=\"mt-6\">Loading...</p>,\n value: (value) => (\n <>\n <p class=\"my-6 text-5xl tabular-nums\">{value}</p>\n <button\n class=\"rounded bg-zinc-900 px-4 py-2 text-white\"\n type=\"button\"\n onClick={() => void increment()}\n >\n Increment by {counterIncrement}\n </button>\n </>\n ),\n })}\n </main>\n );\n}\n`;\n\nconst utils = `export const counterIncrement = 1;\n`;\n\nconst styles = `@import \"tailwindcss\";\n`;\n\nconst readme = (projectName: string): string => `# ${projectName}\n\nA small Ignotum counter app.\n\n## Getting started\n\nYou need Node.js 22.18 or newer. The project generator installs dependencies by default. If you\ncreated the project with \\`--no-install\\`, install them now:\n\n\\`\\`\\`sh\nnpx ignotum install\n\\`\\`\\`\n\nThis command uses pnpm when it is installed and otherwise uses npm.\n\nStart the app:\n\n\\`\\`\\`sh\nnpx ignotum dev\n\\`\\`\\`\n\nOpen <http://127.0.0.1:3210>.\n\nThe project generator creates \\`_generated\\`. The dev server checks those files before it starts\nand updates them when the schema or server functions change.\n\n## Project files\n\n- \\`server/schema.ts\\` defines the database tables.\n- \\`server/counter.ts\\` defines the query and mutation used by the counter.\n- \\`client/App.tsx\\` is the UI.\n- \\`client/styles.css\\` loads Tailwind CSS.\n- \\`shared/utils.ts\\` contains code shared across the app.\n- \\`_generated\\` contains Ignotum's generated types and bindings. Do not edit it by hand.\n\nRun the typechecker after a change:\n\n\\`\\`\\`sh\nnpx ignotum codegen\nnpx tsc --noEmit\n\\`\\`\\`\n\n## Claude Code\n\nIf you use Claude Code, rename \\`AGENTS.md\\` to \\`CLAUDE.md\\` and \\`.agents\\` to \\`.claude\\` so it\ncan find the project instructions and Ignotum skill.\n`;\n\nconst projectFiles = (projectName: string): ReadonlyArray<ProjectFile> => [\n { content: app, path: \"client/App.tsx\" },\n { content: styles, path: \"client/styles.css\" },\n { content: counterFunctions, path: \"server/counter.ts\" },\n { content: schema, path: \"server/schema.ts\" },\n { content: utils, path: \"shared/utils.ts\" },\n { content: packageJson(projectName), path: \"package.json\" },\n { content: tsconfig, path: \"tsconfig.json\" },\n { content: gitignore, path: \".gitignore\" },\n { content: readme(projectName), path: \"README.md\" },\n ...agentProjectFiles,\n];\n\nconst writeProjectFile = Effect.fn(\"NewProject.writeProjectFile\")(function* (\n projectDirectory: string,\n file: ProjectFile,\n) {\n const fileSystem = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const filePath = path.join(projectDirectory, file.path);\n\n yield* fileSystem.makeDirectory(path.dirname(filePath), { recursive: true });\n yield* fileSystem.writeFileString(filePath, file.content, { flag: \"wx\" });\n});\n\nconst gitExitCode = Effect.fn(\"NewProject.gitExitCode\")(function* (\n projectDirectory: string,\n args: ReadonlyArray<string>,\n) {\n const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n return yield* spawner\n .exitCode(\n ChildProcess.make(\"git\", args, {\n cwd: projectDirectory,\n stderr: \"ignore\",\n stdout: \"ignore\",\n }),\n )\n .pipe(\n Effect.mapError((cause) =>\n GitInitializationFailed.make({\n cause,\n message: `Could not run Git in ${projectDirectory}.`,\n path: projectDirectory,\n }),\n ),\n );\n});\n\nconst runGit = Effect.fn(\"NewProject.runGit\")(function* (\n projectDirectory: string,\n args: ReadonlyArray<string>,\n action: string,\n) {\n const exitCode = yield* gitExitCode(projectDirectory, args);\n\n if (exitCode !== ChildProcessSpawner.ExitCode(0)) {\n return yield* GitInitializationFailed.make({\n message: `Git exited with code ${exitCode} while ${action} in ${projectDirectory}.`,\n path: projectDirectory,\n });\n }\n});\n\nconst initializeGit = Effect.fn(\"NewProject.initializeGit\")(function* (projectDirectory: string) {\n yield* runGit(projectDirectory, [\"init\", \"--quiet\"], \"initializing the repository\");\n yield* runGit(projectDirectory, [\"add\", \"--all\"], \"staging the initial files\");\n\n const [hasName, hasEmail] = yield* Effect.all(\n [\n gitExitCode(projectDirectory, [\"config\", \"user.name\"]),\n gitExitCode(projectDirectory, [\"config\", \"user.email\"]),\n ],\n { concurrency: \"unbounded\" },\n ).pipe(\n Effect.map((exitCodes) =>\n exitCodes.map((exitCode) => exitCode === ChildProcessSpawner.ExitCode(0)),\n ),\n );\n const identity =\n hasName === true && hasEmail === true\n ? []\n : [\"-c\", \"user.name=Ignotum\", \"-c\", \"user.email=ignotum@localhost\"];\n\n yield* runGit(\n projectDirectory,\n [...identity, \"commit\", \"--quiet\", \"--no-gpg-sign\", \"-m\", \"Init\"],\n \"creating the initial commit\",\n );\n});\n\nexport const createProject = Effect.fn(\"NewProject.createProject\")(function* (\n options: NewProjectOptions,\n) {\n const fileSystem = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const projectDirectory = path.resolve(options.currentDirectory, options.directory);\n const projectName = String.kebabCase(path.basename(projectDirectory));\n\n if (projectName.length === 0) {\n return yield* InvalidProjectName.make({\n message: `Could not derive a package name from ${projectDirectory}.`,\n path: projectDirectory,\n });\n }\n\n const exists = yield* fileSystem.exists(projectDirectory);\n\n if (exists) {\n const info = yield* fileSystem.stat(projectDirectory);\n if (info.type !== \"Directory\") {\n return yield* ProjectDirectoryNotEmpty.make({\n message: `${projectDirectory} already exists and is not an empty directory.`,\n path: projectDirectory,\n });\n }\n\n const entries = yield* fileSystem.readDirectory(projectDirectory);\n if (entries.length > 0) {\n return yield* ProjectDirectoryNotEmpty.make({\n message: `${projectDirectory} is not empty. Choose an empty directory.`,\n path: projectDirectory,\n });\n }\n } else {\n yield* fileSystem.makeDirectory(projectDirectory, { recursive: true });\n }\n\n yield* Effect.forEach(\n projectFiles(projectName),\n (file) => writeProjectFile(projectDirectory, file),\n {\n discard: true,\n },\n );\n\n yield* generate(projectDirectory);\n\n const packageManager = options.install ? yield* installDependencies(projectDirectory) : null;\n\n if (options.git) {\n yield* initializeGit(projectDirectory);\n }\n\n return {\n directory: projectDirectory,\n gitInitialized: options.git,\n packageManager,\n projectName,\n } satisfies NewProjectResult;\n});\n","import { NodeRuntime, NodeServices } from \"@effect/platform-node\";\nimport { Effect, Path, Schema, Terminal } from \"effect\";\nimport { Argument, CliError, Command, Flag } from \"effect/unstable/cli\";\n\nimport packageJson from \"../../package.json\" with { type: \"json\" };\nimport { generate } from \"./codegen.js\";\nimport { resetDevDatabase } from \"../dev-runtime/dev-database.js\";\nimport { dev as runDev } from \"./dev.js\";\nimport { createProject } from \"./new-project.js\";\nimport { installDependencies } from \"./package-manager.js\";\n\nconst DevPort = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65_535 }));\n\nconst codegen = Command.make(\n \"codegen\",\n {},\n Effect.fn(\"codegen\")(function* () {\n const path = yield* Path.Path;\n const terminal = yield* Terminal.Terminal;\n const result = yield* generate(path.resolve(\".\")).pipe(\n Effect.mapError((error) =>\n CliError.UserError.make({ cause: error, userMessage: error.message }),\n ),\n );\n\n yield* terminal.display(\n `Generated ${result.written.length} file${result.written.length === 1 ? \"\" : \"s\"}; ${result.unchanged.length} unchanged.\\n`,\n );\n }),\n);\n\nconst resetDevDatabaseCommand = Command.make(\n \"reset\",\n {},\n Effect.fn(\"dev db reset\")(function* () {\n const path = yield* Path.Path;\n const terminal = yield* Terminal.Terminal;\n const result = yield* resetDevDatabase(path.resolve(\".\")).pipe(\n Effect.mapError((error) =>\n CliError.UserError.make({ cause: error, userMessage: error.message }),\n ),\n );\n const message =\n result.removed === 0\n ? `Development database is already empty: ${result.databasePath}\\n`\n : `Reset development database: ${result.databasePath}\\n`;\n yield* terminal.display(message);\n }),\n).pipe(Command.withDescription(\"Delete the local SQLite development database.\"));\n\nconst devDatabase = Command.make(\"db\").pipe(\n Command.withDescription(\"Manage the local development database.\"),\n Command.withSubcommands([resetDevDatabaseCommand]),\n);\n\nconst dev = Command.make(\n \"dev\",\n {\n host: Flag.string(\"host\").pipe(Flag.withDefault(\"127.0.0.1\")),\n open: Flag.boolean(\"open\").pipe(Flag.withDefault(false)),\n port: Flag.integer(\"port\").pipe(Flag.withSchema(DevPort), Flag.withDefault(3210)),\n },\n Effect.fn(\"dev\")(function* ({ host, open, port }) {\n const path = yield* Path.Path;\n\n return yield* runDev({\n host,\n open,\n port,\n projectDirectory: path.resolve(\".\"),\n }).pipe(\n Effect.mapError((error) =>\n CliError.UserError.make({ cause: error, userMessage: error.message }),\n ),\n );\n }),\n).pipe(\n Command.withDescription(\"Run the local Ignotum development server.\"),\n Command.withSubcommands([devDatabase]),\n);\n\nconst install = Command.make(\n \"install\",\n {},\n Effect.fn(\"install\")(function* () {\n const path = yield* Path.Path;\n const terminal = yield* Terminal.Terminal;\n const packageManager = yield* installDependencies(path.resolve(\".\")).pipe(\n Effect.mapError((error) =>\n CliError.UserError.make({ cause: error, userMessage: error.message }),\n ),\n );\n\n yield* terminal.display(`Installed dependencies with ${packageManager}.\\n`);\n }),\n).pipe(Command.withDescription(\"Install dependencies with pnpm, or npm when pnpm is unavailable.\"));\n\nconst newProject = Command.make(\n \"new\",\n {\n directory: Argument.string(\"directory\").pipe(\n Argument.withDescription('Directory to create. Use \".\" for the current directory.'),\n ),\n git: Flag.boolean(\"git\").pipe(\n Flag.withDescription(\"Initialize a Git repository. Use --no-git to skip it.\"),\n Flag.withDefault(true),\n ),\n install: Flag.boolean(\"install\").pipe(\n Flag.withDescription(\"Install dependencies. Use --no-install to skip it.\"),\n Flag.withDefault(true),\n ),\n },\n Effect.fn(\"new\")(function* ({ directory, git, install }) {\n const path = yield* Path.Path;\n const terminal = yield* Terminal.Terminal;\n const currentDirectory = path.resolve(\".\");\n const result = yield* createProject({ currentDirectory, directory, git, install }).pipe(\n Effect.mapError((error) =>\n CliError.UserError.make({ cause: error, userMessage: error.message }),\n ),\n );\n const changeDirectory = result.directory === currentDirectory ? \"\" : ` cd ${directory}\\n`;\n\n const installCommand = result.packageManager === null ? \" npx ignotum install\\n\" : \"\";\n\n yield* terminal.display(\n `Created ${result.projectName} in ${result.directory}.\\n\\nNext steps:\\n${changeDirectory}${installCommand} npx ignotum dev\\n`,\n );\n }),\n).pipe(\n Command.withDescription(\"Create a new Ignotum app in an empty directory.\"),\n Command.withExamples([\n {\n command: \"ignotum new my-app\",\n description: \"Create an app in a new directory.\",\n },\n {\n command: \"ignotum new . --no-git --no-install\",\n description: \"Create an app in the current directory without Git or dependency installation.\",\n },\n ]),\n);\n\nconst ignotum = Command.make(\"ignotum\").pipe(\n Command.withSubcommands([newProject, install, codegen, dev]),\n);\n\nexport const main = (): void => {\n ignotum.pipe(\n Command.run({ version: packageJson.version }),\n // @effect-diagnostics-next-line strictEffectProvide:off\n Effect.provide(NodeServices.layer),\n NodeRuntime.runMain,\n );\n};\n","#!/usr/bin/env node\n\nimport { main } from \"./command.js\";\n\nmain();\n"],"x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,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