ignotum 0.0.0 → 0.0.2

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.
Files changed (57) hide show
  1. package/README.md +161 -0
  2. package/dist/cli/bin.d.mts +1 -0
  3. package/dist/cli/bin.mjs +1696 -0
  4. package/dist/cli/bin.mjs.map +1 -0
  5. package/dist/runtime/api-BXXIZc_Q.js +119 -0
  6. package/dist/runtime/api-BXXIZc_Q.js.map +1 -0
  7. package/dist/runtime/api-Cpx57mk3.d.ts +47 -0
  8. package/dist/runtime/client/jsx-dev-runtime.d.ts +2 -0
  9. package/dist/runtime/client/jsx-dev-runtime.js +2 -0
  10. package/dist/runtime/client/jsx-runtime.d.ts +2 -0
  11. package/dist/runtime/client/jsx-runtime.js +2 -0
  12. package/dist/runtime/client.d.ts +29 -0
  13. package/dist/runtime/client.js +364 -0
  14. package/dist/runtime/client.js.map +1 -0
  15. package/dist/runtime/index-BgWROoyk.d.ts +249 -0
  16. package/dist/runtime/internal/api.d.ts +2 -0
  17. package/dist/runtime/internal/api.js +2 -0
  18. package/dist/runtime/internal/server.d.ts +6 -0
  19. package/dist/runtime/internal/server.js +7 -0
  20. package/dist/runtime/internal/server.js.map +1 -0
  21. package/dist/runtime/internal/types.d.ts +2 -0
  22. package/dist/runtime/internal/types.js +2 -0
  23. package/dist/runtime/result-B2W-z2wG.js +136 -0
  24. package/dist/runtime/result-B2W-z2wG.js.map +1 -0
  25. package/dist/runtime/result-C1ZdsM6Y.d.ts +106 -0
  26. package/dist/runtime/schema-CNEVLF7D.js +116 -0
  27. package/dist/runtime/schema-CNEVLF7D.js.map +1 -0
  28. package/dist/runtime/server.d.ts +9 -0
  29. package/dist/runtime/server.js +9 -0
  30. package/dist/runtime/server.js.map +1 -0
  31. package/package.json +81 -2
  32. package/src/cli/agent-files.ts +35 -0
  33. package/src/cli/bin.ts +5 -0
  34. package/src/cli/client-plugin.ts +66 -0
  35. package/src/cli/codegen.ts +203 -0
  36. package/src/cli/command.ts +155 -0
  37. package/src/cli/dev.ts +206 -0
  38. package/src/cli/new-project.ts +377 -0
  39. package/src/cli/package-manager.ts +55 -0
  40. package/src/client/errors.ts +83 -0
  41. package/src/client/hooks.ts +141 -0
  42. package/src/client/index.ts +90 -0
  43. package/src/client/jsx-dev-runtime.ts +2 -0
  44. package/src/client/jsx-runtime.ts +2 -0
  45. package/src/client/query.ts +17 -0
  46. package/src/client/sync.ts +487 -0
  47. package/src/dev-runtime/database.ts +374 -0
  48. package/src/dev-runtime/dev-database.ts +199 -0
  49. package/src/dev-runtime/functions.ts +293 -0
  50. package/src/dev-runtime/id.ts +11 -0
  51. package/src/dev-runtime/sync.ts +473 -0
  52. package/src/internal/api.ts +141 -0
  53. package/src/internal/http-paths.ts +5 -0
  54. package/src/internal/server.ts +3 -0
  55. package/src/internal/types.ts +2 -0
  56. package/src/raw.d.ts +4 -0
  57. package/src/server/index.ts +8 -0
@@ -0,0 +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/b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;;ACtJA,KAAK"}
@@ -0,0 +1,119 @@
1
+ import { Predicate, Schema } from "effect";
2
+ //#region ../contracts/dist/runtime/sync.js
3
+ const FunctionNamePart = Schema.String.check(Schema.isPattern(/^[A-Za-z_$][A-Za-z0-9_$]*$/));
4
+ Schema.TemplateLiteralParser([
5
+ "api.",
6
+ FunctionNamePart,
7
+ ".",
8
+ FunctionNamePart
9
+ ]);
10
+ const FunctionAddress = Schema.TemplateLiteral([
11
+ "api.",
12
+ FunctionNamePart,
13
+ ".",
14
+ FunctionNamePart
15
+ ]);
16
+ const SubscriptionId = Schema.Natural.pipe(Schema.brand("ignotum/sync/SubscriptionId"));
17
+ const RequestId = Schema.Natural.pipe(Schema.brand("ignotum/sync/RequestId"));
18
+ const Subscribe = Schema.Struct({
19
+ type: Schema.Literal("Subscribe"),
20
+ id: SubscriptionId,
21
+ function: FunctionAddress,
22
+ args: Schema.Json
23
+ });
24
+ const Unsubscribe = Schema.Struct({
25
+ type: Schema.Literal("Unsubscribe"),
26
+ id: SubscriptionId
27
+ });
28
+ const Mutate = Schema.Struct({
29
+ type: Schema.Literal("Mutate"),
30
+ id: RequestId,
31
+ function: FunctionAddress,
32
+ args: Schema.Json
33
+ });
34
+ const ClientMessage = Schema.Union([
35
+ Subscribe,
36
+ Unsubscribe,
37
+ Mutate
38
+ ]);
39
+ const QueryOperation = Schema.Struct({
40
+ type: Schema.Literal("Query"),
41
+ id: SubscriptionId
42
+ });
43
+ const MutateOperation = Schema.Struct({
44
+ type: Schema.Literal("Mutate"),
45
+ id: RequestId
46
+ });
47
+ const Operation = Schema.Union([QueryOperation, MutateOperation]);
48
+ const DatePath = Schema.Array(Schema.Union([Schema.String, Schema.Natural]));
49
+ const DatePaths = Schema.Array(DatePath);
50
+ const WireResult = Schema.Union([Schema.Struct({
51
+ type: Schema.Literal("Success"),
52
+ value: Schema.optional(Schema.Json),
53
+ dates: Schema.optional(DatePaths)
54
+ }), Schema.Struct({
55
+ type: Schema.Literal("Failure"),
56
+ error: Schema.Json,
57
+ dates: Schema.optional(DatePaths)
58
+ })]);
59
+ const QuerySnapshot = Schema.Struct({
60
+ type: Schema.Literal("QuerySnapshot"),
61
+ id: SubscriptionId,
62
+ result: WireResult
63
+ });
64
+ const MutationResult = Schema.Struct({
65
+ type: Schema.Literal("MutationResult"),
66
+ id: RequestId,
67
+ result: WireResult
68
+ });
69
+ const ProtocolErrorCode = Schema.Literals([
70
+ "DuplicateOperationId",
71
+ "FunctionUnavailable",
72
+ "InvalidArguments",
73
+ "InvalidMessage",
74
+ "UnknownFunction",
75
+ "WrongFunctionKind"
76
+ ]);
77
+ const ProtocolError = Schema.Struct({
78
+ type: Schema.Literal("ProtocolError"),
79
+ operation: Schema.optional(Operation),
80
+ code: ProtocolErrorCode,
81
+ message: Schema.String
82
+ });
83
+ const ServerMessage = Schema.Union([
84
+ QuerySnapshot,
85
+ MutationResult,
86
+ ProtocolError
87
+ ]);
88
+ const ClientMessageJson = Schema.fromJsonString(ClientMessage);
89
+ const ServerMessageJson = Schema.fromJsonString(ServerMessage);
90
+ //#endregion
91
+ //#region src/internal/api.ts
92
+ const FunctionReferenceTypeId = Symbol.for("ignotum/internal/api/FunctionReference");
93
+ const functionPathOf = (reference) => reference[FunctionReferenceTypeId];
94
+ const makeModuleReference = (moduleName) => {
95
+ const references = /* @__PURE__ */ new Map();
96
+ return new Proxy({}, { get: (_target, functionName) => {
97
+ if (!Predicate.isString(functionName)) return;
98
+ const existing = references.get(functionName);
99
+ if (existing !== void 0) return existing;
100
+ const reference = { [FunctionReferenceTypeId]: FunctionAddress.make(`api.${moduleName}.${functionName}`) };
101
+ references.set(functionName, reference);
102
+ return reference;
103
+ } });
104
+ };
105
+ function createApi() {
106
+ const modules = /* @__PURE__ */ new Map();
107
+ return new Proxy({}, { get: (_target, moduleName) => {
108
+ if (!Predicate.isString(moduleName)) return;
109
+ const existing = modules.get(moduleName);
110
+ if (existing !== void 0) return existing;
111
+ const moduleReference = makeModuleReference(moduleName);
112
+ modules.set(moduleName, moduleReference);
113
+ return moduleReference;
114
+ } });
115
+ }
116
+ //#endregion
117
+ export { Operation as a, ServerMessageJson as c, FunctionAddress as i, SubscriptionId as l, functionPathOf as n, ProtocolErrorCode as o, ClientMessageJson as r, RequestId as s, createApi as t };
118
+
119
+ //# sourceMappingURL=api-BXXIZc_Q.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-BXXIZc_Q.js","names":[],"sources":["../../../contracts/dist/runtime/sync.js","../../src/internal/api.ts"],"sourcesContent":["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 { Predicate } from \"effect\";\nimport type { Effect } from \"effect\";\n\nimport type { ErrorValue, InternalServerError } from \"@ignotum/contracts/runtime/result\";\nimport { FunctionAddress } from \"@ignotum/contracts/runtime/sync\";\n\nconst FunctionReferenceTypeId: unique symbol = Symbol.for(\"ignotum/internal/api/FunctionReference\");\ndeclare const FunctionReferenceTypesTypeId: unique symbol;\n\ntype FunctionKind = \"Mutation\" | \"Query\";\n\nexport interface FunctionReference<\n Kind extends FunctionKind,\n Args,\n Success,\n Failure extends ErrorValue,\n> {\n readonly [FunctionReferenceTypeId]: FunctionAddress;\n readonly [FunctionReferenceTypesTypeId]?: {\n readonly kind: Kind;\n readonly args: Args;\n readonly value: Success;\n readonly error: Failure;\n };\n}\n\ntype ReferenceTypes<Reference> = Reference extends {\n readonly [FunctionReferenceTypesTypeId]?: infer Types;\n}\n ? Exclude<Types, undefined>\n : never;\n\nexport declare namespace FunctionReference {\n type Args<Reference> =\n ReferenceTypes<Reference> extends { readonly args: infer Args } ? Args : never;\n type Failure<Reference> =\n ReferenceTypes<Reference> extends {\n readonly error: infer Failure;\n }\n ? Failure\n : never;\n type Kind<Reference> =\n ReferenceTypes<Reference> extends { readonly kind: infer Kind } ? Kind : never;\n type Success<Reference> =\n ReferenceTypes<Reference> extends {\n readonly value: infer Success;\n }\n ? Success\n : never;\n}\n\ntype ReferenceOf<Definition> = Definition extends {\n readonly _tag: infer Kind extends FunctionKind;\n readonly handler: (\n ...arguments_: infer HandlerArguments\n ) => Generator<infer Yielded, infer Success, never>;\n}\n ? HandlerArguments extends readonly [infer _Context, ...infer Rest]\n ? FunctionReference<\n Kind,\n Rest extends readonly [infer Args, ...ReadonlyArray<unknown>] ? Args : void,\n Success,\n | (Yielded extends Effect.Effect<unknown, infer Failure extends ErrorValue, never>\n ? Failure\n : never)\n | InternalServerError\n >\n : never\n : never;\n\ntype ApiModule<Module> = {\n readonly [FunctionName in keyof Module as FunctionName extends string\n ? ReferenceOf<Module[FunctionName]> extends never\n ? never\n : FunctionName\n : never]: ReferenceOf<Module[FunctionName]>;\n};\n\nexport type Api<Modules> = {\n readonly [ModuleName in keyof Modules]: ApiModule<Modules[ModuleName]>;\n};\n\nexport const functionPathOf = <\n Kind extends FunctionKind,\n Args,\n Success,\n Failure extends ErrorValue,\n>(\n reference: FunctionReference<Kind, Args, Success, Failure>,\n) => reference[FunctionReferenceTypeId];\n\nconst makeModuleReference = (moduleName: string) => {\n const references = new Map<string, object>();\n\n return new Proxy(\n {},\n {\n get: (_target, functionName) => {\n if (!Predicate.isString(functionName)) {\n return undefined;\n }\n\n const existing = references.get(functionName);\n if (existing !== undefined) {\n return existing;\n }\n\n const reference = {\n [FunctionReferenceTypeId]: FunctionAddress.make(`api.${moduleName}.${functionName}`),\n };\n references.set(functionName, reference);\n return reference;\n },\n },\n );\n};\n\nexport function createApi<Modules>(): Api<Modules>;\nexport function createApi() {\n const modules = new Map<string, object>();\n\n return new Proxy(\n {},\n {\n get: (_target, moduleName) => {\n if (!Predicate.isString(moduleName)) {\n return undefined;\n }\n\n const existing = modules.get(moduleName);\n if (existing !== undefined) {\n return existing;\n }\n\n const moduleReference = makeModuleReference(moduleName);\n modules.set(moduleName, moduleReference);\n return moduleReference;\n },\n },\n );\n}\n"],"mappings":";;AAGA,MAAM,mBAAmB,OAAO,OAAO,MAAM,OAAO,UAAU,4BAA4B,CAAC;AAC3D,OAAO,sBAAsB;CAC5D;CACA;CACA;CACA;AACD,CAAC;AACD,MAAM,kBAAkB,OAAO,gBAAgB;CAC9C;CACA;CACA;CACA;AACD,CAAC;AAQD,MAAM,iBAAiB,OAAO,QAAQ,KAAK,OAAO,MAAM,6BAA6B,CAAC;AACtF,MAAM,YAAY,OAAO,QAAQ,KAAK,OAAO,MAAM,wBAAwB,CAAC;AAC5E,MAAM,YAAY,OAAO,OAAO;CAC/B,MAAM,OAA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ACD,MAAM,gBAAgB,OAAO,OAAO;CACnC,MAAM,OAAO,QAAQ,eAAe;CACpC,WAAW,OAAO,SAAS,SAAS;CACpC,MAAM;CACN,SAAS,OAAO;AACjB,CAAC;AACD,MAAM,gBAAgB,OAAO,MAAM;CAClC;CACA;CACA;AACD,CAAC;AACD,MAAM,oBAAoB,OAAO,eAAe,aAAa;AAC7D,MAAM,oBAAoB,OAAO,eAAe,aAAa;;;AC1F7D,MAAM,0BAAyC,OAAO,IAAI,wCAAwC;AA4ElG,MAAa,kBAMX,cACG,UAAU;AAEf,MAAM,uBAAuB,eAAuB;CAClD,MAAM,6BAAa,IAAI,IAAoB;CAE3C,OAAO,IAAI,MACT,CAAC,GACD,EACE,MAAM,SAAS,iBAAiB;EAC9B,IAAI,CAAC,UAAU,SAAS,YAAY,GAClC;EAGF,MAAM,WAAW,WAAW,IAAI,YAAY;EAC5C,IAAI,aAAa,KAAA,GACf,OAAO;EAGT,MAAM,YAAY,GACf,0BAA0B,gBAAgB,KAAK,OAAO,WAAW,GAAG,cAAc,EACrF;EACA,WAAW,IAAI,cAAc,SAAS;EACtC,OAAO;CACT,EACF,CACF;AACF;AAGA,SAAgB,YAAY;CAC1B,MAAM,0BAAU,IAAI,IAAoB;CAExC,OAAO,IAAI,MACT,CAAC,GACD,EACE,MAAM,SAAS,eAAe;EAC5B,IAAI,CAAC,UAAU,SAAS,UAAU,GAChC;EAGF,MAAM,WAAW,QAAQ,IAAI,UAAU;EACvC,IAAI,aAAa,KAAA,GACf,OAAO;EAGT,MAAM,kBAAkB,oBAAoB,UAAU;EACtD,QAAQ,IAAI,YAAY,eAAe;EACvC,OAAO;CACT,EACF,CACF;AACF"}
@@ -0,0 +1,47 @@
1
+ import { i as InternalServerError, r as ErrorValue } from "./result-C1ZdsM6Y.js";
2
+ import { Effect, Schema } from "effect";
3
+ //#region ../contracts/dist/runtime/sync.d.ts
4
+ declare const FunctionAddress: Schema.TemplateLiteral<readonly ["api.", Schema.String, ".", Schema.String]>;
5
+ type FunctionAddress = typeof FunctionAddress.Type;
6
+ //#endregion
7
+ //#region src/internal/api.d.ts
8
+ declare const FunctionReferenceTypeId: unique symbol;
9
+ declare const FunctionReferenceTypesTypeId: unique symbol;
10
+ type FunctionKind = "Mutation" | "Query";
11
+ interface FunctionReference<Kind extends FunctionKind, Args, Success, Failure extends ErrorValue> {
12
+ readonly [FunctionReferenceTypeId]: FunctionAddress;
13
+ readonly [FunctionReferenceTypesTypeId]?: {
14
+ readonly kind: Kind;
15
+ readonly args: Args;
16
+ readonly value: Success;
17
+ readonly error: Failure;
18
+ };
19
+ }
20
+ type ReferenceTypes<Reference> = Reference extends {
21
+ readonly [FunctionReferenceTypesTypeId]?: infer Types;
22
+ } ? Exclude<Types, undefined> : never;
23
+ declare namespace FunctionReference {
24
+ type Args<Reference> = ReferenceTypes<Reference> extends {
25
+ readonly args: infer Args;
26
+ } ? Args : never;
27
+ type Failure<Reference> = ReferenceTypes<Reference> extends {
28
+ readonly error: infer Failure;
29
+ } ? Failure : never;
30
+ type Kind<Reference> = ReferenceTypes<Reference> extends {
31
+ readonly kind: infer Kind;
32
+ } ? Kind : never;
33
+ type Success<Reference> = ReferenceTypes<Reference> extends {
34
+ readonly value: infer Success;
35
+ } ? Success : never;
36
+ }
37
+ type ReferenceOf<Definition> = Definition extends {
38
+ readonly _tag: infer Kind extends FunctionKind;
39
+ readonly handler: (...arguments_: infer HandlerArguments) => Generator<infer Yielded, infer Success, never>;
40
+ } ? HandlerArguments extends readonly [infer _Context, ...infer Rest] ? FunctionReference<Kind, Rest extends readonly [infer Args, ...ReadonlyArray<unknown>] ? Args : void, Success, (Yielded extends Effect.Effect<unknown, infer Failure extends ErrorValue, never> ? Failure : never) | InternalServerError> : never : never;
41
+ type ApiModule<Module> = { readonly [FunctionName in keyof Module as FunctionName extends string ? ReferenceOf<Module[FunctionName]> extends never ? never : FunctionName : never]: ReferenceOf<Module[FunctionName]>; };
42
+ type Api<Modules> = { readonly [ModuleName in keyof Modules]: ApiModule<Modules[ModuleName]>; };
43
+ declare const functionPathOf: <Kind extends FunctionKind, Args, Success, Failure extends ErrorValue>(reference: FunctionReference<Kind, Args, Success, Failure>) => `api.${string}.${string}`;
44
+ declare function createApi<Modules>(): Api<Modules>;
45
+ //#endregion
46
+ export { functionPathOf as i, FunctionReference as n, createApi as r, Api as t };
47
+ //# sourceMappingURL=api-Cpx57mk3.d.ts.map
@@ -0,0 +1,2 @@
1
+ import { Fragment, JSX, jsx, jsxDEV, jsxs } from "preact/jsx-dev-runtime";
2
+ export { Fragment, type JSX, jsx, jsxDEV, jsxs };