effect 4.0.0-beta.100 → 4.0.0-beta.102

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 (502) hide show
  1. package/dist/Array.d.ts.map +1 -1
  2. package/dist/Array.js +81 -5
  3. package/dist/Array.js.map +1 -1
  4. package/dist/Channel.d.ts.map +1 -1
  5. package/dist/Channel.js +27 -9
  6. package/dist/Channel.js.map +1 -1
  7. package/dist/Config.d.ts +1 -1
  8. package/dist/Config.d.ts.map +1 -1
  9. package/dist/Config.js +6 -5
  10. package/dist/Config.js.map +1 -1
  11. package/dist/ConfigProvider.js +7 -7
  12. package/dist/ConfigProvider.js.map +1 -1
  13. package/dist/Data.d.ts.map +1 -1
  14. package/dist/Data.js +2 -1
  15. package/dist/Data.js.map +1 -1
  16. package/dist/Effect.d.ts +61 -100
  17. package/dist/Effect.d.ts.map +1 -1
  18. package/dist/Effect.js +66 -39
  19. package/dist/Effect.js.map +1 -1
  20. package/dist/FiberHandle.d.ts.map +1 -1
  21. package/dist/FiberHandle.js +3 -2
  22. package/dist/FiberHandle.js.map +1 -1
  23. package/dist/Iterable.d.ts.map +1 -1
  24. package/dist/Iterable.js +2 -1
  25. package/dist/Iterable.js.map +1 -1
  26. package/dist/JsonPatch.d.ts.map +1 -1
  27. package/dist/JsonPatch.js +4 -3
  28. package/dist/JsonPatch.js.map +1 -1
  29. package/dist/JsonSchema.d.ts.map +1 -1
  30. package/dist/JsonSchema.js +9 -11
  31. package/dist/JsonSchema.js.map +1 -1
  32. package/dist/Logger.d.ts.map +1 -1
  33. package/dist/Logger.js +3 -2
  34. package/dist/Logger.js.map +1 -1
  35. package/dist/ManagedRuntime.d.ts +9 -0
  36. package/dist/ManagedRuntime.d.ts.map +1 -1
  37. package/dist/ManagedRuntime.js +3 -0
  38. package/dist/ManagedRuntime.js.map +1 -1
  39. package/dist/Metric.d.ts.map +1 -1
  40. package/dist/Metric.js +4 -3
  41. package/dist/Metric.js.map +1 -1
  42. package/dist/MutableList.d.ts.map +1 -1
  43. package/dist/MutableList.js +4 -0
  44. package/dist/MutableList.js.map +1 -1
  45. package/dist/Optic.d.ts.map +1 -1
  46. package/dist/Optic.js +5 -4
  47. package/dist/Optic.js.map +1 -1
  48. package/dist/Option.d.ts.map +1 -1
  49. package/dist/Option.js +2 -1
  50. package/dist/Option.js.map +1 -1
  51. package/dist/PartitionedSemaphore.d.ts.map +1 -1
  52. package/dist/PartitionedSemaphore.js +1 -4
  53. package/dist/PartitionedSemaphore.js.map +1 -1
  54. package/dist/Record.d.ts +93 -1
  55. package/dist/Record.d.ts.map +1 -1
  56. package/dist/Record.js +57 -19
  57. package/dist/Record.js.map +1 -1
  58. package/dist/References.d.ts +0 -45
  59. package/dist/References.d.ts.map +1 -1
  60. package/dist/References.js +0 -45
  61. package/dist/References.js.map +1 -1
  62. package/dist/Request.d.ts.map +1 -1
  63. package/dist/Request.js +9 -6
  64. package/dist/Request.js.map +1 -1
  65. package/dist/Result.d.ts.map +1 -1
  66. package/dist/Result.js +2 -1
  67. package/dist/Result.js.map +1 -1
  68. package/dist/Schema.d.ts +1269 -496
  69. package/dist/Schema.d.ts.map +1 -1
  70. package/dist/Schema.js +2308 -614
  71. package/dist/Schema.js.map +1 -1
  72. package/dist/SchemaAST.d.ts +2 -2
  73. package/dist/SchemaAST.d.ts.map +1 -1
  74. package/dist/SchemaAST.js +189 -130
  75. package/dist/SchemaAST.js.map +1 -1
  76. package/dist/SchemaError.js +1 -1
  77. package/dist/SchemaError.js.map +1 -1
  78. package/dist/SchemaGetter.d.ts +13 -11
  79. package/dist/SchemaGetter.d.ts.map +1 -1
  80. package/dist/SchemaGetter.js +34 -24
  81. package/dist/SchemaGetter.js.map +1 -1
  82. package/dist/SchemaIssue.js +1 -1
  83. package/dist/SchemaIssue.js.map +1 -1
  84. package/dist/SchemaParser.d.ts.map +1 -1
  85. package/dist/SchemaParser.js +1 -12
  86. package/dist/SchemaParser.js.map +1 -1
  87. package/dist/SchemaRepresentation.d.ts +403 -1504
  88. package/dist/SchemaRepresentation.d.ts.map +1 -1
  89. package/dist/SchemaRepresentation.js +294 -2852
  90. package/dist/SchemaRepresentation.js.map +1 -1
  91. package/dist/SchemaTransformation.d.ts +2 -2
  92. package/dist/SchemaTransformation.js +3 -3
  93. package/dist/SchemaTransformation.js.map +1 -1
  94. package/dist/Semaphore.d.ts +5 -3
  95. package/dist/Semaphore.d.ts.map +1 -1
  96. package/dist/Semaphore.js.map +1 -1
  97. package/dist/Stream.d.ts +15 -9
  98. package/dist/Stream.d.ts.map +1 -1
  99. package/dist/Stream.js +46 -16
  100. package/dist/Stream.js.map +1 -1
  101. package/dist/Struct.d.ts.map +1 -1
  102. package/dist/Struct.js +5 -4
  103. package/dist/Struct.js.map +1 -1
  104. package/dist/Types.d.ts +1 -3
  105. package/dist/Types.d.ts.map +1 -1
  106. package/dist/index.d.ts +0 -4
  107. package/dist/index.d.ts.map +1 -1
  108. package/dist/index.js +0 -4
  109. package/dist/index.js.map +1 -1
  110. package/dist/internal/core.js +3 -2
  111. package/dist/internal/core.js.map +1 -1
  112. package/dist/internal/effect.js +119 -53
  113. package/dist/internal/effect.js.map +1 -1
  114. package/dist/internal/matcher.js +1 -1
  115. package/dist/internal/matcher.js.map +1 -1
  116. package/dist/internal/record.d.ts +0 -3
  117. package/dist/internal/record.d.ts.map +1 -1
  118. package/dist/internal/record.js +10 -5
  119. package/dist/internal/record.js.map +1 -1
  120. package/dist/internal/references.js +0 -4
  121. package/dist/internal/references.js.map +1 -1
  122. package/dist/internal/schema/annotations.js +12 -0
  123. package/dist/internal/schema/annotations.js.map +1 -1
  124. package/dist/internal/schema/fromJsonSchemaDocument.d.ts +2 -0
  125. package/dist/internal/schema/fromJsonSchemaDocument.d.ts.map +1 -0
  126. package/dist/internal/schema/fromJsonSchemaDocument.js +743 -0
  127. package/dist/internal/schema/fromJsonSchemaDocument.js.map +1 -0
  128. package/dist/internal/schema/fromRepresentation.d.ts +2 -0
  129. package/dist/internal/schema/fromRepresentation.d.ts.map +1 -0
  130. package/dist/internal/schema/fromRepresentation.js +252 -0
  131. package/dist/internal/schema/fromRepresentation.js.map +1 -0
  132. package/dist/internal/schema/schema.js +28 -40
  133. package/dist/internal/schema/schema.js.map +1 -1
  134. package/dist/internal/schema/{arbitrary.d.ts → toArbitrary.d.ts} +1 -1
  135. package/dist/internal/schema/toArbitrary.d.ts.map +1 -0
  136. package/dist/internal/schema/{arbitrary.js → toArbitrary.js} +8 -9
  137. package/dist/internal/schema/toArbitrary.js.map +1 -0
  138. package/dist/internal/schema/toCodeDocument.d.ts +2 -0
  139. package/dist/internal/schema/toCodeDocument.d.ts.map +1 -0
  140. package/dist/internal/schema/toCodeDocument.js +438 -0
  141. package/dist/internal/schema/toCodeDocument.js.map +1 -0
  142. package/dist/internal/schema/toEquivalence.d.ts +2 -0
  143. package/dist/internal/schema/toEquivalence.d.ts.map +1 -0
  144. package/dist/internal/schema/{equivalence.js → toEquivalence.js} +15 -13
  145. package/dist/internal/schema/toEquivalence.js.map +1 -0
  146. package/dist/internal/schema/toJsonSchemaDocument.d.ts +2 -0
  147. package/dist/internal/schema/toJsonSchemaDocument.d.ts.map +1 -0
  148. package/dist/internal/schema/toJsonSchemaDocument.js +466 -0
  149. package/dist/internal/schema/toJsonSchemaDocument.js.map +1 -0
  150. package/dist/internal/schema/toRepresentation.d.ts +2 -0
  151. package/dist/internal/schema/toRepresentation.d.ts.map +1 -0
  152. package/dist/internal/schema/toRepresentation.js +369 -0
  153. package/dist/internal/schema/toRepresentation.js.map +1 -0
  154. package/dist/internal/stackTraceLimit.js +3 -6
  155. package/dist/internal/stackTraceLimit.js.map +1 -1
  156. package/dist/testing/TestClock.js +4 -1
  157. package/dist/testing/TestClock.js.map +1 -1
  158. package/dist/unstable/ai/AiError.d.ts +26 -26
  159. package/dist/unstable/ai/AiError.d.ts.map +1 -1
  160. package/dist/unstable/ai/AiError.js +5 -4
  161. package/dist/unstable/ai/AiError.js.map +1 -1
  162. package/dist/unstable/ai/AnthropicStructuredOutput.d.ts +21 -6
  163. package/dist/unstable/ai/AnthropicStructuredOutput.d.ts.map +1 -1
  164. package/dist/unstable/ai/AnthropicStructuredOutput.js +86 -316
  165. package/dist/unstable/ai/AnthropicStructuredOutput.js.map +1 -1
  166. package/dist/unstable/ai/EmbeddingModel.d.ts +1 -1
  167. package/dist/unstable/ai/EmbeddingModel.js +1 -1
  168. package/dist/unstable/ai/EmbeddingModel.js.map +1 -1
  169. package/dist/unstable/ai/LanguageModel.d.ts +4 -1
  170. package/dist/unstable/ai/LanguageModel.d.ts.map +1 -1
  171. package/dist/unstable/ai/LanguageModel.js +19 -17
  172. package/dist/unstable/ai/LanguageModel.js.map +1 -1
  173. package/dist/unstable/ai/McpSchema.d.ts +197 -197
  174. package/dist/unstable/ai/McpSchema.d.ts.map +1 -1
  175. package/dist/unstable/ai/McpSchema.js +13 -13
  176. package/dist/unstable/ai/McpSchema.js.map +1 -1
  177. package/dist/unstable/ai/McpServer.d.ts +4 -4
  178. package/dist/unstable/ai/McpServer.d.ts.map +1 -1
  179. package/dist/unstable/ai/McpServer.js +116 -49
  180. package/dist/unstable/ai/McpServer.js.map +1 -1
  181. package/dist/unstable/ai/OpenAiStructuredOutput.d.ts +32 -10
  182. package/dist/unstable/ai/OpenAiStructuredOutput.d.ts.map +1 -1
  183. package/dist/unstable/ai/OpenAiStructuredOutput.js +193 -377
  184. package/dist/unstable/ai/OpenAiStructuredOutput.js.map +1 -1
  185. package/dist/unstable/ai/Response.d.ts +19 -19
  186. package/dist/unstable/ai/Response.d.ts.map +1 -1
  187. package/dist/unstable/ai/Response.js +14 -14
  188. package/dist/unstable/ai/Response.js.map +1 -1
  189. package/dist/unstable/ai/Tool.d.ts +4 -0
  190. package/dist/unstable/ai/Tool.d.ts.map +1 -1
  191. package/dist/unstable/ai/Tool.js +11 -3
  192. package/dist/unstable/ai/Tool.js.map +1 -1
  193. package/dist/unstable/ai/Toolkit.d.ts +9 -1
  194. package/dist/unstable/ai/Toolkit.d.ts.map +1 -1
  195. package/dist/unstable/ai/Toolkit.js +14 -10
  196. package/dist/unstable/ai/Toolkit.js.map +1 -1
  197. package/dist/unstable/ai/internal/codec-transformer.js +15 -12
  198. package/dist/unstable/ai/internal/codec-transformer.js.map +1 -1
  199. package/dist/unstable/ai/internal/structured-output.d.ts +2 -0
  200. package/dist/unstable/ai/internal/structured-output.d.ts.map +1 -0
  201. package/dist/unstable/ai/internal/structured-output.js +316 -0
  202. package/dist/unstable/ai/internal/structured-output.js.map +1 -0
  203. package/dist/unstable/cli/CliError.d.ts +40 -2
  204. package/dist/unstable/cli/CliError.d.ts.map +1 -1
  205. package/dist/unstable/cli/CliError.js +45 -6
  206. package/dist/unstable/cli/CliError.js.map +1 -1
  207. package/dist/unstable/cli/Command.js +14 -5
  208. package/dist/unstable/cli/Command.js.map +1 -1
  209. package/dist/unstable/cli/Param.js +3 -3
  210. package/dist/unstable/cli/Param.js.map +1 -1
  211. package/dist/unstable/cli/Primitive.js +1 -1
  212. package/dist/unstable/cli/Primitive.js.map +1 -1
  213. package/dist/unstable/cli/internal/command.d.ts +3 -1
  214. package/dist/unstable/cli/internal/command.d.ts.map +1 -1
  215. package/dist/unstable/cli/internal/command.js +11 -4
  216. package/dist/unstable/cli/internal/command.js.map +1 -1
  217. package/dist/unstable/cli/internal/config.d.ts +0 -48
  218. package/dist/unstable/cli/internal/config.d.ts.map +1 -1
  219. package/dist/unstable/cli/internal/config.js +8 -10
  220. package/dist/unstable/cli/internal/config.js.map +1 -1
  221. package/dist/unstable/cluster/ClusterWorkflowEngine.js +1 -1
  222. package/dist/unstable/cluster/ClusterWorkflowEngine.js.map +1 -1
  223. package/dist/unstable/cluster/Entity.js +1 -1
  224. package/dist/unstable/cluster/Entity.js.map +1 -1
  225. package/dist/unstable/cluster/Envelope.d.ts.map +1 -1
  226. package/dist/unstable/cluster/Envelope.js +2 -1
  227. package/dist/unstable/cluster/Envelope.js.map +1 -1
  228. package/dist/unstable/cluster/Reply.js +1 -1
  229. package/dist/unstable/cluster/Reply.js.map +1 -1
  230. package/dist/unstable/cluster/Runner.d.ts +1 -1
  231. package/dist/unstable/cluster/Runner.js +1 -1
  232. package/dist/unstable/cluster/Runner.js.map +1 -1
  233. package/dist/unstable/cluster/RunnerAddress.d.ts +1 -1
  234. package/dist/unstable/cluster/RunnerAddress.js +1 -1
  235. package/dist/unstable/cluster/RunnerAddress.js.map +1 -1
  236. package/dist/unstable/cluster/ShardId.js +1 -1
  237. package/dist/unstable/cluster/ShardId.js.map +1 -1
  238. package/dist/unstable/cluster/Sharding.d.ts.map +1 -1
  239. package/dist/unstable/cluster/Sharding.js +125 -24
  240. package/dist/unstable/cluster/Sharding.js.map +1 -1
  241. package/dist/unstable/cluster/ShardingConfig.d.ts +10 -2
  242. package/dist/unstable/cluster/ShardingConfig.d.ts.map +1 -1
  243. package/dist/unstable/cluster/ShardingConfig.js.map +1 -1
  244. package/dist/unstable/cluster/SingleRunner.d.ts +4 -2
  245. package/dist/unstable/cluster/SingleRunner.d.ts.map +1 -1
  246. package/dist/unstable/cluster/SingleRunner.js +2 -1
  247. package/dist/unstable/cluster/SingleRunner.js.map +1 -1
  248. package/dist/unstable/cluster/SqlMessageStorage.d.ts +7 -4
  249. package/dist/unstable/cluster/SqlMessageStorage.d.ts.map +1 -1
  250. package/dist/unstable/cluster/SqlMessageStorage.js +55 -24
  251. package/dist/unstable/cluster/SqlMessageStorage.js.map +1 -1
  252. package/dist/unstable/cluster/SqlRunnerStorage.d.ts.map +1 -1
  253. package/dist/unstable/cluster/SqlRunnerStorage.js +109 -62
  254. package/dist/unstable/cluster/SqlRunnerStorage.js.map +1 -1
  255. package/dist/unstable/cluster/internal/entityManager.js +19 -7
  256. package/dist/unstable/cluster/internal/entityManager.js.map +1 -1
  257. package/dist/unstable/cluster/internal/shardLock.d.ts +2 -0
  258. package/dist/unstable/cluster/internal/shardLock.d.ts.map +1 -0
  259. package/dist/unstable/cluster/internal/shardLock.js +4 -0
  260. package/dist/unstable/cluster/internal/shardLock.js.map +1 -0
  261. package/dist/unstable/devtools/DevToolsSchema.d.ts +20 -20
  262. package/dist/unstable/devtools/DevToolsSchema.d.ts.map +1 -1
  263. package/dist/unstable/devtools/DevToolsSchema.js +8 -5
  264. package/dist/unstable/devtools/DevToolsSchema.js.map +1 -1
  265. package/dist/unstable/eventlog/EventJournal.d.ts +1 -1
  266. package/dist/unstable/eventlog/EventJournal.js +1 -1
  267. package/dist/unstable/eventlog/EventJournal.js.map +1 -1
  268. package/dist/unstable/eventlog/EventLog.d.ts.map +1 -1
  269. package/dist/unstable/eventlog/EventLog.js +15 -11
  270. package/dist/unstable/eventlog/EventLog.js.map +1 -1
  271. package/dist/unstable/eventlog/EventLogEncryption.d.ts +1 -1
  272. package/dist/unstable/eventlog/EventLogEncryption.js +1 -1
  273. package/dist/unstable/eventlog/EventLogEncryption.js.map +1 -1
  274. package/dist/unstable/eventlog/EventLogMessage.d.ts +26 -26
  275. package/dist/unstable/eventlog/EventLogMessage.d.ts.map +1 -1
  276. package/dist/unstable/eventlog/EventLogMessage.js +8 -3
  277. package/dist/unstable/eventlog/EventLogMessage.js.map +1 -1
  278. package/dist/unstable/eventlog/EventLogRemote.d.ts +1 -1
  279. package/dist/unstable/eventlog/SqlEventJournal.js +2 -2
  280. package/dist/unstable/eventlog/SqlEventJournal.js.map +1 -1
  281. package/dist/unstable/eventlog/SqlEventLogServerEncrypted.js +1 -1
  282. package/dist/unstable/eventlog/SqlEventLogServerEncrypted.js.map +1 -1
  283. package/dist/unstable/eventlog/SqlEventLogServerUnencrypted.js +3 -3
  284. package/dist/unstable/eventlog/SqlEventLogServerUnencrypted.js.map +1 -1
  285. package/dist/unstable/http/Cookies.d.ts.map +1 -1
  286. package/dist/unstable/http/Cookies.js +24 -22
  287. package/dist/unstable/http/Cookies.js.map +1 -1
  288. package/dist/unstable/http/Headers.js +8 -8
  289. package/dist/unstable/http/Headers.js.map +1 -1
  290. package/dist/unstable/http/HttpClientRequest.d.ts +44 -0
  291. package/dist/unstable/http/HttpClientRequest.d.ts.map +1 -1
  292. package/dist/unstable/http/HttpClientRequest.js +14 -0
  293. package/dist/unstable/http/HttpClientRequest.js.map +1 -1
  294. package/dist/unstable/http/HttpRouter.d.ts +2 -2
  295. package/dist/unstable/http/HttpRouter.d.ts.map +1 -1
  296. package/dist/unstable/http/HttpRouter.js.map +1 -1
  297. package/dist/unstable/http/HttpServerRequest.d.ts.map +1 -1
  298. package/dist/unstable/http/HttpServerRequest.js +5 -4
  299. package/dist/unstable/http/HttpServerRequest.js.map +1 -1
  300. package/dist/unstable/http/Multipart.d.ts.map +1 -1
  301. package/dist/unstable/http/Multipart.js +17 -15
  302. package/dist/unstable/http/Multipart.js.map +1 -1
  303. package/dist/unstable/http/Template.js +1 -1
  304. package/dist/unstable/http/Template.js.map +1 -1
  305. package/dist/unstable/http/UrlParams.d.ts.map +1 -1
  306. package/dist/unstable/http/UrlParams.js +17 -14
  307. package/dist/unstable/http/UrlParams.js.map +1 -1
  308. package/dist/unstable/httpapi/HttpApi.js +3 -3
  309. package/dist/unstable/httpapi/HttpApi.js.map +1 -1
  310. package/dist/unstable/httpapi/HttpApiClient.js +5 -5
  311. package/dist/unstable/httpapi/HttpApiClient.js.map +1 -1
  312. package/dist/unstable/httpapi/HttpApiGroup.js +1 -1
  313. package/dist/unstable/httpapi/HttpApiGroup.js.map +1 -1
  314. package/dist/unstable/httpapi/OpenApi.d.ts.map +1 -1
  315. package/dist/unstable/httpapi/OpenApi.js +37 -24
  316. package/dist/unstable/httpapi/OpenApi.js.map +1 -1
  317. package/dist/unstable/observability/OtlpExporter.d.ts +72 -1
  318. package/dist/unstable/observability/OtlpExporter.d.ts.map +1 -1
  319. package/dist/unstable/observability/OtlpExporter.js +69 -4
  320. package/dist/unstable/observability/OtlpExporter.js.map +1 -1
  321. package/dist/unstable/observability/OtlpLogger.d.ts +4 -3
  322. package/dist/unstable/observability/OtlpLogger.d.ts.map +1 -1
  323. package/dist/unstable/observability/OtlpLogger.js +2 -2
  324. package/dist/unstable/observability/OtlpLogger.js.map +1 -1
  325. package/dist/unstable/observability/OtlpMetrics.d.ts +7 -3
  326. package/dist/unstable/observability/OtlpMetrics.d.ts.map +1 -1
  327. package/dist/unstable/observability/OtlpMetrics.js +5 -2
  328. package/dist/unstable/observability/OtlpMetrics.js.map +1 -1
  329. package/dist/unstable/observability/OtlpTracer.d.ts +4 -3
  330. package/dist/unstable/observability/OtlpTracer.d.ts.map +1 -1
  331. package/dist/unstable/observability/OtlpTracer.js +2 -2
  332. package/dist/unstable/observability/OtlpTracer.js.map +1 -1
  333. package/dist/unstable/persistence/Persistable.d.ts.map +1 -1
  334. package/dist/unstable/persistence/Persistable.js +2 -1
  335. package/dist/unstable/persistence/Persistable.js.map +1 -1
  336. package/dist/unstable/persistence/RateLimiter.d.ts +2 -2
  337. package/dist/unstable/persistence/RateLimiter.js +2 -2
  338. package/dist/unstable/persistence/RateLimiter.js.map +1 -1
  339. package/dist/unstable/persistence/Redis.d.ts.map +1 -1
  340. package/dist/unstable/persistence/Redis.js +2 -2
  341. package/dist/unstable/persistence/Redis.js.map +1 -1
  342. package/dist/unstable/process/ChildProcessSpawner.js +3 -1
  343. package/dist/unstable/process/ChildProcessSpawner.js.map +1 -1
  344. package/dist/unstable/reactivity/AsyncResult.d.ts.map +1 -1
  345. package/dist/unstable/reactivity/AsyncResult.js +4 -3
  346. package/dist/unstable/reactivity/AsyncResult.js.map +1 -1
  347. package/dist/unstable/reactivity/Atom.d.ts +83 -0
  348. package/dist/unstable/reactivity/Atom.d.ts.map +1 -1
  349. package/dist/unstable/reactivity/Atom.js +31 -0
  350. package/dist/unstable/reactivity/Atom.js.map +1 -1
  351. package/dist/unstable/reactivity/AtomRegistry.js +1 -1
  352. package/dist/unstable/reactivity/AtomRegistry.js.map +1 -1
  353. package/dist/unstable/rpc/RpcClient.d.ts.map +1 -1
  354. package/dist/unstable/rpc/RpcClient.js +2 -1
  355. package/dist/unstable/rpc/RpcClient.js.map +1 -1
  356. package/dist/unstable/schema/VariantSchema.d.ts +1 -2
  357. package/dist/unstable/schema/VariantSchema.d.ts.map +1 -1
  358. package/dist/unstable/schema/VariantSchema.js +13 -10
  359. package/dist/unstable/schema/VariantSchema.js.map +1 -1
  360. package/dist/unstable/socket/Socket.d.ts +1 -1
  361. package/dist/unstable/socket/Socket.js +1 -1
  362. package/dist/unstable/socket/Socket.js.map +1 -1
  363. package/dist/unstable/sql/SqlError.d.ts +2 -2
  364. package/dist/unstable/sql/SqlError.js +2 -2
  365. package/dist/unstable/sql/SqlError.js.map +1 -1
  366. package/dist/unstable/sql/Statement.d.ts.map +1 -1
  367. package/dist/unstable/sql/Statement.js +7 -6
  368. package/dist/unstable/sql/Statement.js.map +1 -1
  369. package/package.json +1 -1
  370. package/src/Array.ts +86 -25
  371. package/src/Channel.ts +32 -14
  372. package/src/Config.ts +6 -5
  373. package/src/ConfigProvider.ts +7 -7
  374. package/src/Data.ts +3 -2
  375. package/src/Effect.ts +70 -116
  376. package/src/FiberHandle.ts +3 -2
  377. package/src/Iterable.ts +2 -1
  378. package/src/JsonPatch.ts +4 -3
  379. package/src/JsonSchema.ts +9 -11
  380. package/src/Logger.ts +3 -2
  381. package/src/ManagedRuntime.ts +13 -0
  382. package/src/Metric.ts +4 -3
  383. package/src/MutableList.ts +4 -0
  384. package/src/Optic.ts +5 -4
  385. package/src/Option.ts +2 -1
  386. package/src/PartitionedSemaphore.ts +1 -4
  387. package/src/Record.ts +119 -22
  388. package/src/References.ts +0 -46
  389. package/src/Request.ts +5 -7
  390. package/src/Result.ts +2 -1
  391. package/src/Schema.ts +2538 -987
  392. package/src/SchemaAST.ts +228 -149
  393. package/src/SchemaError.ts +1 -1
  394. package/src/SchemaGetter.ts +36 -29
  395. package/src/SchemaIssue.ts +1 -1
  396. package/src/SchemaParser.ts +1 -25
  397. package/src/SchemaRepresentation.ts +697 -3398
  398. package/src/SchemaTransformation.ts +3 -3
  399. package/src/Semaphore.ts +5 -3
  400. package/src/Stream.ts +63 -19
  401. package/src/Struct.ts +5 -4
  402. package/src/Types.ts +1 -3
  403. package/src/index.ts +0 -5
  404. package/src/internal/core.ts +4 -3
  405. package/src/internal/effect.ts +132 -70
  406. package/src/internal/matcher.ts +1 -1
  407. package/src/internal/record.ts +11 -7
  408. package/src/internal/references.ts +0 -5
  409. package/src/internal/schema/annotations.ts +44 -0
  410. package/src/internal/schema/fromJsonSchemaDocument.ts +957 -0
  411. package/src/internal/schema/fromRepresentation.ts +345 -0
  412. package/src/internal/schema/schema.ts +45 -46
  413. package/src/internal/schema/{arbitrary.ts → toArbitrary.ts} +8 -10
  414. package/src/internal/schema/toCodeDocument.ts +572 -0
  415. package/src/internal/schema/{equivalence.ts → toEquivalence.ts} +12 -7
  416. package/src/internal/schema/toJsonSchemaDocument.ts +475 -0
  417. package/src/internal/schema/toRepresentation.ts +401 -0
  418. package/src/internal/stackTraceLimit.ts +3 -7
  419. package/src/testing/TestClock.ts +1 -1
  420. package/src/unstable/ai/AiError.ts +5 -4
  421. package/src/unstable/ai/AnthropicStructuredOutput.ts +102 -333
  422. package/src/unstable/ai/EmbeddingModel.ts +1 -1
  423. package/src/unstable/ai/LanguageModel.ts +30 -28
  424. package/src/unstable/ai/McpSchema.ts +15 -15
  425. package/src/unstable/ai/McpServer.ts +172 -56
  426. package/src/unstable/ai/OpenAiStructuredOutput.ts +230 -395
  427. package/src/unstable/ai/Response.ts +24 -24
  428. package/src/unstable/ai/Tool.ts +22 -4
  429. package/src/unstable/ai/Toolkit.ts +19 -7
  430. package/src/unstable/ai/internal/codec-transformer.ts +13 -7
  431. package/src/unstable/ai/internal/structured-output.ts +458 -0
  432. package/src/unstable/cli/CliError.ts +51 -5
  433. package/src/unstable/cli/Command.ts +4 -4
  434. package/src/unstable/cli/Param.ts +3 -3
  435. package/src/unstable/cli/Primitive.ts +1 -1
  436. package/src/unstable/cli/internal/command.ts +13 -5
  437. package/src/unstable/cli/internal/config.ts +8 -10
  438. package/src/unstable/cluster/ClusterWorkflowEngine.ts +3 -3
  439. package/src/unstable/cluster/Entity.ts +1 -1
  440. package/src/unstable/cluster/Envelope.ts +2 -1
  441. package/src/unstable/cluster/Reply.ts +1 -1
  442. package/src/unstable/cluster/Runner.ts +1 -1
  443. package/src/unstable/cluster/RunnerAddress.ts +1 -1
  444. package/src/unstable/cluster/ShardId.ts +1 -1
  445. package/src/unstable/cluster/Sharding.ts +161 -34
  446. package/src/unstable/cluster/ShardingConfig.ts +5 -1
  447. package/src/unstable/cluster/SingleRunner.ts +4 -2
  448. package/src/unstable/cluster/SqlMessageStorage.ts +83 -35
  449. package/src/unstable/cluster/SqlRunnerStorage.ts +186 -116
  450. package/src/unstable/cluster/internal/entityManager.ts +31 -10
  451. package/src/unstable/cluster/internal/shardLock.ts +9 -0
  452. package/src/unstable/devtools/DevToolsSchema.ts +10 -5
  453. package/src/unstable/eventlog/EventJournal.ts +1 -1
  454. package/src/unstable/eventlog/EventLog.ts +21 -11
  455. package/src/unstable/eventlog/EventLogEncryption.ts +1 -1
  456. package/src/unstable/eventlog/EventLogMessage.ts +10 -3
  457. package/src/unstable/eventlog/SqlEventJournal.ts +2 -2
  458. package/src/unstable/eventlog/SqlEventLogServerEncrypted.ts +1 -1
  459. package/src/unstable/eventlog/SqlEventLogServerUnencrypted.ts +6 -3
  460. package/src/unstable/http/Cookies.ts +29 -24
  461. package/src/unstable/http/Headers.ts +8 -8
  462. package/src/unstable/http/HttpClientRequest.ts +57 -0
  463. package/src/unstable/http/HttpRouter.ts +6 -3
  464. package/src/unstable/http/HttpServerRequest.ts +5 -4
  465. package/src/unstable/http/Multipart.ts +16 -13
  466. package/src/unstable/http/Template.ts +1 -1
  467. package/src/unstable/http/UrlParams.ts +17 -14
  468. package/src/unstable/httpapi/HttpApi.ts +3 -3
  469. package/src/unstable/httpapi/HttpApiClient.ts +5 -5
  470. package/src/unstable/httpapi/HttpApiGroup.ts +1 -1
  471. package/src/unstable/httpapi/OpenApi.ts +52 -28
  472. package/src/unstable/observability/OtlpExporter.ts +109 -5
  473. package/src/unstable/observability/OtlpLogger.ts +5 -5
  474. package/src/unstable/observability/OtlpMetrics.ts +8 -4
  475. package/src/unstable/observability/OtlpTracer.ts +8 -4
  476. package/src/unstable/persistence/Persistable.ts +3 -2
  477. package/src/unstable/persistence/RateLimiter.ts +2 -2
  478. package/src/unstable/persistence/Redis.ts +2 -2
  479. package/src/unstable/process/ChildProcessSpawner.ts +1 -1
  480. package/src/unstable/reactivity/AsyncResult.ts +4 -3
  481. package/src/unstable/reactivity/Atom.ts +92 -0
  482. package/src/unstable/reactivity/AtomRegistry.ts +1 -1
  483. package/src/unstable/rpc/RpcClient.ts +2 -1
  484. package/src/unstable/schema/VariantSchema.ts +14 -24
  485. package/src/unstable/socket/Socket.ts +1 -1
  486. package/src/unstable/sql/SqlError.ts +2 -2
  487. package/src/unstable/sql/Statement.ts +7 -6
  488. package/dist/SchemaUtils.d.ts +0 -28
  489. package/dist/SchemaUtils.d.ts.map +0 -1
  490. package/dist/SchemaUtils.js +0 -45
  491. package/dist/SchemaUtils.js.map +0 -1
  492. package/dist/internal/schema/arbitrary.d.ts.map +0 -1
  493. package/dist/internal/schema/arbitrary.js.map +0 -1
  494. package/dist/internal/schema/equivalence.d.ts +0 -2
  495. package/dist/internal/schema/equivalence.d.ts.map +0 -1
  496. package/dist/internal/schema/equivalence.js.map +0 -1
  497. package/dist/internal/schema/representation.d.ts +0 -2
  498. package/dist/internal/schema/representation.d.ts.map +0 -1
  499. package/dist/internal/schema/representation.js +0 -865
  500. package/dist/internal/schema/representation.js.map +0 -1
  501. package/src/SchemaUtils.ts +0 -51
  502. package/src/internal/schema/representation.ts +0 -795
@@ -1,72 +1,150 @@
1
1
  /**
2
- * Plain data structures for describing schemas in a serializable form. A
3
- * `Representation` is not the original `Schema` object; it is a JSON-friendly
4
- * description of the schema's types, fields, unions, checks, annotations, and
5
- * references.
6
- *
7
- * This module defines the representation node types, document types, and
8
- * codecs used to validate those documents. It can build representation
9
- * documents from schema ASTs, turn representation documents back into schemas,
10
- * convert them to and from JSON Schema documents, and generate TypeScript code
11
- * artifacts for schema definitions.
2
+ * Open, compiler-extensible representation of Effect schemas.
12
3
  *
13
4
  * @since 4.0.0
14
5
  */
15
- import * as Arr from "./Array.ts"
16
- import { format, formatPropertyKey } from "./Formatter.ts"
17
- import { collectBrands } from "./internal/schema/annotations.ts"
18
- import * as InternalRepresentation from "./internal/schema/representation.ts"
19
- import { unescapeToken } from "./JsonPointer.ts"
6
+ import * as InternalRecord from "./internal/record.ts"
7
+ import * as InternalFromJsonSchemaDocument from "./internal/schema/fromJsonSchemaDocument.ts"
8
+ import * as InternalFromRepresentation from "./internal/schema/fromRepresentation.ts"
9
+ import * as InternalSchema from "./internal/schema/schema.ts"
10
+ import * as InternalToCodeDocument from "./internal/schema/toCodeDocument.ts"
11
+ import * as InternalToJsonSchemaDocument from "./internal/schema/toJsonSchemaDocument.ts"
12
+ import * as InternalToRepresentation from "./internal/schema/toRepresentation.ts"
20
13
  import type * as JsonSchema from "./JsonSchema.ts"
21
- import { remainder } from "./Number.ts"
22
14
  import * as Option from "./Option.ts"
23
- import * as Predicate from "./Predicate.ts"
24
- import * as Rec from "./Record.ts"
25
15
  import * as Schema from "./Schema.ts"
26
16
  import * as SchemaAST from "./SchemaAST.ts"
27
17
  import * as SchemaGetter from "./SchemaGetter.ts"
28
18
 
29
- // -----------------------------------------------------------------------------
30
- // specification
31
- // -----------------------------------------------------------------------------
32
-
33
19
  /**
34
- * A custom type declaration, such as `Date`, `Option`, or `ReadonlySet`.
35
- *
36
- * **When to use**
20
+ * Open persistence identity carried by declarations and opaque checks.
37
21
  *
38
- * Use when inspecting or transforming non-primitive schema types.
22
+ * @category annotations
23
+ * @since 4.0.0
24
+ */
25
+ export interface RepresentationAnnotation {
26
+ readonly id: string
27
+ readonly payload: Schema.Json
28
+ }
29
+
30
+ /**
31
+ * Open persistence identity and schema dependencies carried by opaque checks.
39
32
  *
40
- * **Details**
33
+ * @category annotations
34
+ * @since 4.0.0
35
+ */
36
+ export interface CheckRepresentationAnnotation<S> extends RepresentationAnnotation {
37
+ readonly schemas?: ReadonlyArray<S> | undefined
38
+ }
39
+
40
+ /**
41
+ * Input passed to JSON Schema compiler annotations.
41
42
  *
42
- * `typeParameters` holds the inner type arguments, such as the `A` in
43
- * `Option<A>`. `encodedSchema` is the fallback representation when no
44
- * {@link Reviver} recognizes this declaration. `annotations.typeConstructor`
45
- * identifies the declaration kind, such as `{ _tag: "effect/Option" }`.
43
+ * @since 4.0.0
44
+ */
45
+ export declare namespace ToJsonSchema {
46
+ /**
47
+ * Input for a check compiler.
48
+ *
49
+ * @category models
50
+ * @since 4.0.0
51
+ */
52
+ export interface CheckInput {
53
+ readonly type: JsonSchema.Type | undefined
54
+ readonly schemas: ReadonlyArray<JsonSchema.JsonSchema>
55
+ }
56
+
57
+ /**
58
+ * JSON Schema compiler for a check.
59
+ *
60
+ * @category models
61
+ * @since 4.0.0
62
+ */
63
+ export type Check = (input: CheckInput) => JsonSchema.JsonSchema
64
+ }
65
+
66
+ /**
67
+ * Input and output contracts for code generation annotations.
46
68
  *
47
- * @see {@link Reviver}
48
- * @see {@link toSchemaDefaultReviver}
69
+ * @since 4.0.0
70
+ */
71
+ export declare namespace Generation {
72
+ /**
73
+ * Input for declaration code generation.
74
+ *
75
+ * @category models
76
+ * @since 4.0.0
77
+ */
78
+ export interface DeclarationInput {
79
+ readonly typeParameters: ReadonlyArray<Code>
80
+ }
81
+
82
+ /**
83
+ * Output of declaration code generation.
84
+ *
85
+ * @category models
86
+ * @since 4.0.0
87
+ */
88
+ export interface DeclarationOutput {
89
+ readonly runtime: string
90
+ readonly Type: string
91
+ readonly importDeclarations?: ReadonlyArray<string> | undefined
92
+ }
93
+
94
+ /**
95
+ * Declaration code generator.
96
+ *
97
+ * @category models
98
+ * @since 4.0.0
99
+ */
100
+ export type Declaration = (input: DeclarationInput) => DeclarationOutput
101
+
102
+ /**
103
+ * Input for check code generation.
104
+ *
105
+ * @category models
106
+ * @since 4.0.0
107
+ */
108
+ export interface CheckInput {
109
+ readonly schemas: ReadonlyArray<Code>
110
+ }
111
+
112
+ /**
113
+ * Output of check code generation.
114
+ *
115
+ * @category models
116
+ * @since 4.0.0
117
+ */
118
+ export interface CheckOutput {
119
+ readonly runtime: string
120
+ readonly importDeclarations?: ReadonlyArray<string> | undefined
121
+ }
122
+
123
+ /**
124
+ * Check code generator.
125
+ *
126
+ * @category models
127
+ * @since 4.0.0
128
+ */
129
+ export type Check = (input: CheckInput) => CheckOutput
130
+ }
131
+
132
+ /**
133
+ * A custom opaque declaration.
49
134
  *
50
135
  * @category models
51
136
  * @since 4.0.0
52
137
  */
53
138
  export interface Declaration {
54
139
  readonly _tag: "Declaration"
140
+ readonly representation?: RepresentationAnnotation | undefined
55
141
  readonly annotations?: Schema.Annotations.Annotations | undefined
56
142
  readonly typeParameters: ReadonlyArray<Representation>
57
- readonly checks: ReadonlyArray<Check<DeclarationMeta>>
58
- readonly encodedSchema: Representation
143
+ readonly checks: ReadonlyArray<Check>
59
144
  }
60
145
 
61
146
  /**
62
- * A lazily resolved representation used for recursive schemas.
63
- *
64
- * **Details**
65
- *
66
- * `thunk` points to the actual representation, possibly via a
67
- * {@link Reference}. `checks` is always empty on `Suspend` nodes.
68
- *
69
- * @see {@link Reference}
147
+ * A lazily resolved representation.
70
148
  *
71
149
  * @category models
72
150
  * @since 4.0.0
@@ -79,25 +157,7 @@ export interface Suspend {
79
157
  }
80
158
 
81
159
  /**
82
- * A named reference to a definition in the {@link References} map.
83
- *
84
- * **When to use**
85
- *
86
- * Use when a representation should point to a named definition instead of
87
- * embedding the definition inline.
88
- *
89
- * **Details**
90
- *
91
- * `$ref` is the key into `Document.references` or `MultiDocument.references`.
92
- * References are resolved lazily by {@link toSchema} and
93
- * {@link toCodeDocument}.
94
- *
95
- * **Gotchas**
96
- *
97
- * Resolution throws at runtime if the key is not found in the references map.
98
- *
99
- * @see {@link References}
100
- * @see {@link Document}
160
+ * A named reference.
101
161
  *
102
162
  * @category models
103
163
  * @since 4.0.0
@@ -107,244 +167,152 @@ export interface Reference {
107
167
  readonly $ref: string
108
168
  }
109
169
 
110
- /**
111
- * The `null` type.
112
- *
113
- * @category models
114
- * @since 4.0.0
115
- */
116
- export interface Null {
117
- readonly _tag: "Null"
170
+ interface Keyword<Tag extends string> {
171
+ readonly _tag: Tag
118
172
  readonly annotations?: Schema.Annotations.Annotations | undefined
173
+ readonly checks: ReadonlyArray<Check>
119
174
  }
120
175
 
121
176
  /**
122
- * The `undefined` type.
177
+ * The null keyword representation.
123
178
  *
124
179
  * @category models
125
180
  * @since 4.0.0
126
181
  */
127
- export interface Undefined {
128
- readonly _tag: "Undefined"
129
- readonly annotations?: Schema.Annotations.Annotations | undefined
130
- }
131
-
182
+ export interface Null extends Keyword<"Null"> {}
132
183
  /**
133
- * The `void` type.
184
+ * The undefined keyword representation.
134
185
  *
135
186
  * @category models
136
187
  * @since 4.0.0
137
188
  */
138
- export interface Void {
139
- readonly _tag: "Void"
140
- readonly annotations?: Schema.Annotations.Annotations | undefined
141
- }
142
-
189
+ export interface Undefined extends Keyword<"Undefined"> {}
143
190
  /**
144
- * The `never` type (no valid values).
191
+ * The void keyword representation.
145
192
  *
146
193
  * @category models
147
194
  * @since 4.0.0
148
195
  */
149
- export interface Never {
150
- readonly _tag: "Never"
151
- readonly annotations?: Schema.Annotations.Annotations | undefined
152
- }
153
-
196
+ export interface Void extends Keyword<"Void"> {}
154
197
  /**
155
- * The `unknown` type (any value accepted).
198
+ * The never keyword representation.
156
199
  *
157
200
  * @category models
158
201
  * @since 4.0.0
159
202
  */
160
- export interface Unknown {
161
- readonly _tag: "Unknown"
162
- readonly annotations?: Schema.Annotations.Annotations | undefined
163
- }
164
-
203
+ export interface Never extends Keyword<"Never"> {}
165
204
  /**
166
- * The `any` type.
205
+ * The unknown keyword representation.
167
206
  *
168
207
  * @category models
169
208
  * @since 4.0.0
170
209
  */
171
- export interface Any {
172
- readonly _tag: "Any"
173
- readonly annotations?: Schema.Annotations.Annotations | undefined
174
- }
175
-
210
+ export interface Unknown extends Keyword<"Unknown"> {}
176
211
  /**
177
- * The `string` type with optional validation checks.
178
- *
179
- * **Details**
180
- *
181
- * `checks` holds string-specific constraints, such as min/max length, pattern,
182
- * and UUID checks. `contentMediaType` and `contentSchema` indicate that the
183
- * string contains encoded data, such as `"application/json"` with a nested
184
- * schema.
185
- *
186
- * @see {@link StringMeta}
187
- * @see {@link Check}
212
+ * The any keyword representation.
188
213
  *
189
214
  * @category models
190
215
  * @since 4.0.0
191
216
  */
192
- export interface String {
193
- readonly _tag: "String"
194
- readonly annotations?: Schema.Annotations.Annotations | undefined
195
- readonly checks: ReadonlyArray<Check<StringMeta>>
196
- readonly contentMediaType?: string | undefined
197
- readonly contentSchema?: Representation | undefined
198
- }
217
+ export interface Any extends Keyword<"Any"> {}
199
218
 
200
219
  /**
201
- * The `number` type with optional validation checks.
202
- *
203
- * **Details**
204
- *
205
- * `checks` holds number-specific constraints, such as int, finite, min, max,
206
- * multipleOf, and between checks.
207
- *
208
- * @see {@link NumberMeta}
220
+ * A string representation.
209
221
  *
210
222
  * @category models
211
223
  * @since 4.0.0
212
224
  */
213
- export interface Number {
214
- readonly _tag: "Number"
215
- readonly annotations?: Schema.Annotations.Annotations | undefined
216
- readonly checks: ReadonlyArray<Check<NumberMeta>>
217
- }
225
+ export interface String extends Keyword<"String"> {}
218
226
 
219
227
  /**
220
- * The `boolean` type.
228
+ * A number representation.
221
229
  *
222
230
  * @category models
223
231
  * @since 4.0.0
224
232
  */
225
- export interface Boolean {
226
- readonly _tag: "Boolean"
227
- readonly annotations?: Schema.Annotations.Annotations | undefined
228
- }
229
-
233
+ export interface Number extends Keyword<"Number"> {}
230
234
  /**
231
- * The `bigint` type with optional validation checks.
232
- *
233
- * @see {@link BigIntMeta}
235
+ * A boolean representation.
234
236
  *
235
237
  * @category models
236
238
  * @since 4.0.0
237
239
  */
238
- export interface BigInt {
239
- readonly _tag: "BigInt"
240
- readonly annotations?: Schema.Annotations.Annotations | undefined
241
- readonly checks: ReadonlyArray<Check<BigIntMeta>>
242
- }
243
-
240
+ export interface Boolean extends Keyword<"Boolean"> {}
244
241
  /**
245
- * The `symbol` type.
242
+ * A bigint representation.
246
243
  *
247
244
  * @category models
248
245
  * @since 4.0.0
249
246
  */
250
- export interface Symbol {
251
- readonly _tag: "Symbol"
252
- readonly annotations?: Schema.Annotations.Annotations | undefined
253
- }
254
-
247
+ export interface BigInt extends Keyword<"BigInt"> {}
255
248
  /**
256
- * A specific literal value (`string`, `number`, `boolean`, or `bigint`).
249
+ * A symbol representation.
257
250
  *
258
251
  * @category models
259
252
  * @since 4.0.0
260
253
  */
261
- export interface Literal {
262
- readonly _tag: "Literal"
263
- readonly annotations?: Schema.Annotations.Annotations | undefined
264
- readonly literal: string | number | boolean | bigint
265
- }
254
+ export interface Symbol extends Keyword<"Symbol"> {}
266
255
 
267
256
  /**
268
- * A specific unique `symbol` value.
257
+ * A literal representation.
258
+ *
259
+ * **Details**
260
+ *
261
+ * The live representation stores the native literal value. Persistent codecs
262
+ * add an explicit type discriminator when encoding it.
269
263
  *
270
264
  * @category models
271
265
  * @since 4.0.0
272
266
  */
273
- export interface UniqueSymbol {
274
- readonly _tag: "UniqueSymbol"
275
- readonly annotations?: Schema.Annotations.Annotations | undefined
276
- readonly symbol: symbol
267
+ export interface Literal extends Keyword<"Literal"> {
268
+ readonly literal: SchemaAST.LiteralValue
277
269
  }
278
270
 
279
271
  /**
280
- * The `object` keyword type (matches any non-primitive).
272
+ * A unique global symbol representation.
281
273
  *
282
274
  * @category models
283
275
  * @since 4.0.0
284
276
  */
285
- export interface ObjectKeyword {
286
- readonly _tag: "ObjectKeyword"
287
- readonly annotations?: Schema.Annotations.Annotations | undefined
277
+ export interface UniqueSymbol extends Keyword<"UniqueSymbol"> {
278
+ readonly symbol: symbol
288
279
  }
289
280
 
290
281
  /**
291
- * A TypeScript-style enum. Each entry is a `[name, value]` pair.
282
+ * The object keyword representation.
292
283
  *
293
284
  * @category models
294
285
  * @since 4.0.0
295
286
  */
296
- export interface Enum {
297
- readonly _tag: "Enum"
298
- readonly annotations?: Schema.Annotations.Annotations | undefined
299
- readonly enums: ReadonlyArray<readonly [string, string | number]>
300
- }
287
+ export interface ObjectKeyword extends Keyword<"ObjectKeyword"> {}
301
288
 
302
289
  /**
303
- * A template literal type composed of a sequence of parts (literals, strings,
304
- * numbers, etc.).
290
+ * An enum representation.
291
+ *
292
+ * **Details**
293
+ *
294
+ * Enum members are stored as native string or number values. Persistent
295
+ * codecs add an explicit type discriminator when encoding them.
305
296
  *
306
297
  * @category models
307
298
  * @since 4.0.0
308
299
  */
309
- export interface TemplateLiteral {
310
- readonly _tag: "TemplateLiteral"
311
- readonly annotations?: Schema.Annotations.Annotations | undefined
312
- readonly parts: ReadonlyArray<Representation>
300
+ export interface Enum extends Keyword<"Enum"> {
301
+ readonly enums: ReadonlyArray<readonly [string, string | number]>
313
302
  }
314
303
 
315
304
  /**
316
- * An array or tuple type.
317
- *
318
- * **Details**
319
- *
320
- * `elements` are the fixed positional elements, or tuple prefix, and each may
321
- * be optional. `rest` contains the variadic tail types; a single-element
322
- * `rest` with no `elements` produces a plain `Array<T>`. `checks` holds
323
- * array-specific constraints, such as minLength, maxLength, and unique checks.
324
- *
325
- * @see {@link Element}
326
- * @see {@link ArraysMeta}
305
+ * A template literal representation.
327
306
  *
328
307
  * @category models
329
308
  * @since 4.0.0
330
309
  */
331
- export interface Arrays {
332
- readonly _tag: "Arrays"
333
- readonly annotations?: Schema.Annotations.Annotations | undefined
334
- readonly elements: ReadonlyArray<Element>
335
- readonly rest: ReadonlyArray<Representation>
336
- readonly checks: ReadonlyArray<Check<ArraysMeta>>
310
+ export interface TemplateLiteral extends Keyword<"TemplateLiteral"> {
311
+ readonly parts: ReadonlyArray<Representation>
337
312
  }
338
313
 
339
314
  /**
340
- * A positional element within an {@link Arrays} tuple.
341
- *
342
- * **Details**
343
- *
344
- * `isOptional` indicates whether this element can be absent. `type` is the
345
- * schema representation for this element's value.
346
- *
347
- * @see {@link Arrays}
315
+ * A tuple element.
348
316
  *
349
317
  * @category models
350
318
  * @since 4.0.0
@@ -356,39 +324,28 @@ export interface Element {
356
324
  }
357
325
 
358
326
  /**
359
- * An object/struct type with named properties and optional index signatures.
360
- *
361
- * **Details**
362
- *
363
- * `propertySignatures` are the explicitly named fields. `indexSignatures`
364
- * define catch-all key/value types, such as `Record<string, T>`. `checks`
365
- * holds object-specific constraints, such as minProperties and maxProperties.
366
- *
367
- * @see {@link PropertySignature}
368
- * @see {@link IndexSignature}
369
- * @see {@link ObjectsMeta}
327
+ * An array or tuple representation.
370
328
  *
371
329
  * @category models
372
330
  * @since 4.0.0
373
331
  */
374
- export interface Objects {
375
- readonly _tag: "Objects"
376
- readonly annotations?: Schema.Annotations.Annotations | undefined
377
- readonly propertySignatures: ReadonlyArray<PropertySignature>
378
- readonly indexSignatures: ReadonlyArray<IndexSignature>
379
- readonly checks: ReadonlyArray<Check<ObjectsMeta>>
332
+ export interface Arrays extends Keyword<"Arrays"> {
333
+ readonly elements: ReadonlyArray<Element>
334
+ readonly rest: ReadonlyArray<Representation>
380
335
  }
381
336
 
382
337
  /**
383
- * A named property within an {@link Objects} representation.
338
+ * A property signature.
384
339
  *
385
340
  * **Details**
386
341
  *
387
- * `name` is the property key, which can be a string, number, or symbol.
388
- * `isOptional` indicates whether the key can be absent. `isMutable` indicates
389
- * whether the property is mutable rather than readonly.
342
+ * The live representation stores the native property key. Persistent codecs
343
+ * add an explicit type discriminator when encoding it.
344
+ *
345
+ * **Gotchas**
390
346
  *
391
- * @see {@link Objects}
347
+ * Local symbols can be represented while the schema is live, but persistent
348
+ * codecs reject them because they cannot be reconstructed by identity.
392
349
  *
393
350
  * @category models
394
351
  * @since 4.0.0
@@ -402,15 +359,7 @@ export interface PropertySignature {
402
359
  }
403
360
 
404
361
  /**
405
- * An index signature, such as `[key: string]: number`, within an
406
- * {@link Objects}.
407
- *
408
- * **Details**
409
- *
410
- * `parameter` is the key type representation. `type` is the value type
411
- * representation.
412
- *
413
- * @see {@link Objects}
362
+ * An index signature.
414
363
  *
415
364
  * @category models
416
365
  * @since 4.0.0
@@ -421,34 +370,29 @@ export interface IndexSignature {
421
370
  }
422
371
 
423
372
  /**
424
- * A union of multiple representations.
425
- *
426
- * **Details**
373
+ * An object representation.
427
374
  *
428
- * `types` are the union members. `mode` controls JSON Schema output as either
429
- * `"anyOf"` (the default) or mutually exclusive `"oneOf"`.
375
+ * @category models
376
+ * @since 4.0.0
377
+ */
378
+ export interface Objects extends Keyword<"Objects"> {
379
+ readonly propertySignatures: ReadonlyArray<PropertySignature>
380
+ readonly indexSignatures: ReadonlyArray<IndexSignature>
381
+ }
382
+
383
+ /**
384
+ * A union representation.
430
385
  *
431
386
  * @category models
432
387
  * @since 4.0.0
433
388
  */
434
- export interface Union {
435
- readonly _tag: "Union"
436
- readonly annotations?: Schema.Annotations.Annotations | undefined
389
+ export interface Union extends Keyword<"Union"> {
437
390
  readonly types: ReadonlyArray<Representation>
438
391
  readonly mode: "anyOf" | "oneOf"
439
392
  }
440
393
 
441
394
  /**
442
- * The core tagged union of all supported schema shapes.
443
- *
444
- * **Details**
445
- *
446
- * Each variant has a `_tag` discriminator. Switch on `_tag` to handle each
447
- * shape. Most variants carry optional `annotations` and some carry `checks`
448
- * for validation constraints.
449
- *
450
- * @see {@link Document}
451
- * @see {@link fromAST}
395
+ * The structural schema representation.
452
396
  *
453
397
  * @category models
454
398
  * @since 4.0.0
@@ -478,3430 +422,785 @@ export type Representation =
478
422
  | Union
479
423
 
480
424
  /**
481
- * A validation constraint attached to a type. Either a single {@link Filter}
482
- * or a {@link FilterGroup} combining multiple checks.
483
- *
484
- * @see {@link Filter}
485
- * @see {@link FilterGroup}
425
+ * A structural check.
486
426
  *
487
427
  * @category models
488
428
  * @since 4.0.0
489
429
  */
490
- export type Check<M> = Filter<M> | FilterGroup<M>
430
+ export type Check = Filter | FilterGroup
491
431
 
492
432
  /**
493
- * A single validation constraint with typed metadata describing the check
494
- * (e.g. `{ _tag: "isMinLength", minLength: 3 }`).
495
- *
496
- * @see {@link Check}
433
+ * An opaque leaf check.
497
434
  *
498
435
  * @category models
499
436
  * @since 4.0.0
500
437
  */
501
- export interface Filter<M> {
438
+ export interface Filter {
502
439
  readonly _tag: "Filter"
503
- readonly annotations?: Schema.Annotations.Filter | undefined
504
- readonly meta: M
440
+ readonly representation?: CheckRepresentationAnnotation<Representation> | undefined
441
+ readonly annotations?: Schema.Annotations.Annotations | undefined
442
+ readonly aborted: boolean
505
443
  }
506
444
 
507
445
  /**
508
- * A group of validation constraints that are logically combined. Contains
509
- * at least one {@link Check}.
510
- *
511
- * @see {@link Check}
446
+ * A non-empty group of checks.
512
447
  *
513
448
  * @category models
514
449
  * @since 4.0.0
515
450
  */
516
- export interface FilterGroup<M> {
451
+ export interface FilterGroup {
517
452
  readonly _tag: "FilterGroup"
518
- readonly annotations?: Schema.Annotations.Filter | undefined
519
- readonly checks: readonly [Check<M>, ...Array<Check<M>>]
453
+ readonly representation?: CheckRepresentationAnnotation<Representation> | undefined
454
+ readonly annotations?: Schema.Annotations.Annotations | undefined
455
+ readonly checks: readonly [Check, ...Array<Check>]
520
456
  }
521
457
 
522
458
  /**
523
- * Metadata union for string-specific validation checks (minLength, maxLength,
524
- * pattern, UUID, trimmed, etc.).
525
- *
526
- * @see {@link String}
527
- * @see {@link Check}
459
+ * Named representation definitions.
528
460
  *
529
461
  * @category models
530
462
  * @since 4.0.0
531
463
  */
532
- export type StringMeta = Schema.Annotations.BuiltInMetaDefinitions[
533
- | "isStringFinite"
534
- | "isStringBigInt"
535
- | "isStringSymbol"
536
- | "isMinLength"
537
- | "isMaxLength"
538
- | "isPattern"
539
- | "isLengthBetween"
540
- | "isTrimmed"
541
- | "isUUID"
542
- | "isGUID"
543
- | "isULID"
544
- | "isBase64"
545
- | "isBase64Url"
546
- | "isStartsWith"
547
- | "isEndsWith"
548
- | "isIncludes"
549
- | "isUppercased"
550
- | "isLowercased"
551
- | "isCapitalized"
552
- | "isUncapitalized"
553
- ]
554
-
555
- /**
556
- * Metadata union for number-specific validation checks (int, finite,
557
- * min, max, multipleOf, between).
558
- *
559
- * @see {@link Number}
560
- * @see {@link Check}
464
+ export interface References {
465
+ readonly [$ref: string]: Representation
466
+ }
467
+
468
+ /**
469
+ * A single representation and its definitions.
561
470
  *
562
471
  * @category models
563
472
  * @since 4.0.0
564
473
  */
565
- export type NumberMeta = Schema.Annotations.BuiltInMetaDefinitions[
566
- | "isInt"
567
- | "isFinite"
568
- | "isMultipleOf"
569
- | "isGreaterThanOrEqualTo"
570
- | "isLessThanOrEqualTo"
571
- | "isGreaterThan"
572
- | "isLessThan"
573
- | "isBetween"
574
- ]
474
+ export interface Document {
475
+ readonly representation: Representation
476
+ readonly references: References
477
+ }
575
478
 
576
479
  /**
577
- * Metadata union for bigint-specific validation checks (min, max, between).
578
- *
579
- * @see {@link BigInt}
580
- * @see {@link Check}
480
+ * Multiple representations sharing definitions.
581
481
  *
582
482
  * @category models
583
483
  * @since 4.0.0
584
484
  */
585
- export type BigIntMeta = Schema.Annotations.BuiltInMetaDefinitions[
586
- | "isGreaterThanOrEqualToBigInt"
587
- | "isLessThanOrEqualToBigInt"
588
- | "isGreaterThanBigInt"
589
- | "isLessThanBigInt"
590
- | "isBetweenBigInt"
591
- ]
485
+ export interface MultiDocument {
486
+ readonly representations: readonly [Representation, ...Array<Representation>]
487
+ readonly references: References
488
+ }
592
489
 
593
490
  /**
594
- * Metadata union for array-specific validation checks (minLength, maxLength,
595
- * length, unique).
596
- *
597
- * @see {@link Arrays}
598
- * @see {@link Check}
491
+ * Live schemas reconstructed from a multi-document.
599
492
  *
600
493
  * @category models
601
494
  * @since 4.0.0
602
495
  */
603
- export type ArraysMeta = Schema.Annotations.BuiltInMetaDefinitions[
604
- | "isMinLength"
605
- | "isMaxLength"
606
- | "isLengthBetween"
607
- | "isUnique"
608
- ]
496
+ export interface SchemaMultiDocument {
497
+ readonly schemas: readonly [Schema.Top, ...Array<Schema.Top>]
498
+ readonly definitions: Readonly<Record<string, Schema.Top>>
499
+ }
609
500
 
610
501
  /**
611
- * Metadata union for object-specific validation checks (minProperties,
612
- * maxProperties, propertiesLength, propertyNames).
613
- *
614
- * @see {@link Objects}
615
- * @see {@link Check}
502
+ * Reviver for a declaration.
616
503
  *
617
504
  * @category models
618
505
  * @since 4.0.0
619
506
  */
620
- export type ObjectsMeta =
621
- | Schema.Annotations.BuiltInMetaDefinitions[
622
- | "isMinProperties"
623
- | "isMaxProperties"
624
- | "isPropertiesLengthBetween"
625
- ]
626
- | { readonly _tag: "isPropertyNames"; readonly propertyNames: Representation }
507
+ export interface DeclarationReviver<P> {
508
+ readonly id: string
509
+ readonly payloadSchema: Schema.Decoder<P>
510
+ readonly revive: (input: {
511
+ readonly payload: P
512
+ readonly typeParameters: ReadonlyArray<Schema.Top>
513
+ readonly annotations: Schema.Annotations.Annotations | undefined
514
+ }) => Schema.Top
515
+ }
627
516
 
628
517
  /**
629
- * Metadata union for Date-specific validation checks (valid, min, max, between).
630
- *
631
- * @see {@link Declaration}
632
- * @see {@link DeclarationMeta}
518
+ * Reviver for a leaf check.
633
519
  *
634
520
  * @category models
635
521
  * @since 4.0.0
636
522
  */
637
- export type DateMeta = Schema.Annotations.BuiltInMetaDefinitions[
638
- | "isDateValid"
639
- | "isGreaterThanDate"
640
- | "isGreaterThanOrEqualToDate"
641
- | "isLessThanDate"
642
- | "isLessThanOrEqualToDate"
643
- | "isBetweenDate"
644
- ]
523
+ export interface FilterReviver<P> {
524
+ readonly id: string
525
+ readonly payloadSchema: Schema.Decoder<P>
526
+ readonly revive: (input: {
527
+ readonly payload: P
528
+ readonly schemas: ReadonlyArray<Schema.Top>
529
+ readonly annotations: Schema.Annotations.Filter | undefined
530
+ }) => SchemaAST.Filter<any>
531
+ }
645
532
 
646
533
  /**
647
- * Metadata union for size-based validation checks (minSize, maxSize, size).
648
- * Used for collection types like `Set`, `Map`.
649
- *
650
- * @see {@link Declaration}
651
- * @see {@link DeclarationMeta}
534
+ * Reviver for a check group.
652
535
  *
653
536
  * @category models
654
537
  * @since 4.0.0
655
538
  */
656
- export type SizeMeta = Schema.Annotations.BuiltInMetaDefinitions[
657
- | "isMinSize"
658
- | "isMaxSize"
659
- | "isSizeBetween"
660
- ]
539
+ export interface FilterGroupReviver<P> {
540
+ readonly id: string
541
+ readonly payloadSchema: Schema.Decoder<P>
542
+ readonly revive: (input: {
543
+ readonly payload: P
544
+ readonly schemas: ReadonlyArray<Schema.Top>
545
+ readonly annotations: Schema.Annotations.Filter | undefined
546
+ }) => SchemaAST.FilterGroup<any>
547
+ }
661
548
 
662
549
  /**
663
- * Metadata union for {@link Declaration} checks — either {@link DateMeta}
664
- * or {@link SizeMeta}.
550
+ * A check reviver.
665
551
  *
666
552
  * @category models
667
553
  * @since 4.0.0
668
554
  */
669
- export type DeclarationMeta = DateMeta | SizeMeta
670
-
671
- /** @internal */
672
- export type Meta = StringMeta | NumberMeta | BigIntMeta | ArraysMeta | ObjectsMeta | DeclarationMeta
555
+ export type CheckReviver<P> = FilterReviver<P> | FilterGroupReviver<P>
673
556
 
674
557
  /**
675
- * A string-keyed map of named {@link Representation} definitions. Used by
676
- * {@link Document} and {@link MultiDocument} for `$ref` resolution (analogous
677
- * to JSON Schema `$defs`).
678
- *
679
- * @see {@link Reference}
680
- * @see {@link Document}
558
+ * A typed reviver.
681
559
  *
682
560
  * @category models
683
561
  * @since 4.0.0
684
562
  */
685
- export interface References {
686
- readonly [$ref: string]: Representation
687
- }
563
+ export type Reviver<P> = DeclarationReviver<P> | CheckReviver<P>
688
564
 
689
565
  /**
690
- * A single {@link Representation} together with its named {@link References}.
691
- *
692
- * **When to use**
693
- *
694
- * Use when representing a single Schema AST together with its named references
695
- * before reconstructing a runtime Schema, converting to JSON Schema, or
696
- * wrapping it as a {@link MultiDocument}.
697
- *
698
- * @see {@link MultiDocument}
699
- * @see {@link fromAST}
566
+ * A reviver erased only at collection boundaries.
700
567
  *
701
568
  * @category models
702
569
  * @since 4.0.0
703
570
  */
704
- export type Document = {
705
- readonly representation: Representation
706
- readonly references: References
707
- }
571
+ export type AnyReviver = Reviver<any>
708
572
 
709
573
  /**
710
- * One or more {@link Representation}s sharing a common {@link References} map.
711
- *
712
- * **When to use**
574
+ * Creates a declaration reviver while inferring its payload type from `payloadSchema`.
713
575
  *
714
- * Use when you use {@link fromASTs} to create this from multiple Schema ASTs,
715
- * {@link toCodeDocument} to generate TypeScript code, and
716
- * {@link toJsonSchemaMultiDocument} to convert to JSON Schema.
717
- *
718
- * @see {@link Document}
719
- * @see {@link fromASTs}
720
- *
721
- * @category models
576
+ * @category constructors
722
577
  * @since 4.0.0
723
578
  */
724
- export type MultiDocument = {
725
- readonly representations: readonly [Representation, ...Array<Representation>]
726
- readonly references: References
727
- }
728
-
729
- // -----------------------------------------------------------------------------
730
- // schemas
731
- // -----------------------------------------------------------------------------
732
-
733
- const Representation$ref = Schema.suspend(() => $Representation)
734
-
735
- const toJsonAnnotationsBlacklist: Set<string> = new Set([
736
- ...InternalRepresentation.fromASTBlacklist,
737
- "expected",
738
- "contentMediaType",
739
- "contentSchema"
740
- ])
579
+ export const makeDeclarationReviver: <P>(
580
+ id: string,
581
+ payloadSchema: Schema.Decoder<P>,
582
+ revive: DeclarationReviver<P>["revive"]
583
+ ) => DeclarationReviver<P> = InternalSchema.makeDeclarationReviver
741
584
 
742
585
  /**
743
- * A tree of primitive values used to serialize annotations to JSON.
586
+ * Creates a filter reviver while inferring its payload type from `payloadSchema`.
744
587
  *
745
- * @category Tree
588
+ * @category constructors
746
589
  * @since 4.0.0
747
590
  */
748
- export type PrimitiveTree = Schema.Tree<null | number | boolean | bigint | symbol | string>
591
+ export const makeFilterReviver: <P>(
592
+ id: string,
593
+ payloadSchema: Schema.Decoder<P>,
594
+ revive: FilterReviver<P>["revive"]
595
+ ) => FilterReviver<P> = InternalSchema.makeFilterReviver
749
596
 
750
597
  /**
751
- * Schema for {@link PrimitiveTree}.
752
- *
753
- * **When to use**
754
- *
755
- * Use to validate recursive annotation metadata trees whose leaves are `null`,
756
- * `number`, `boolean`, `bigint`, `symbol`, or `string`.
757
- *
758
- * @see {@link PrimitiveTree} for the recursive tree type accepted by this codec
759
- * @see {@link $Annotations} for the annotation codec that filters values through this codec
598
+ * Creates a filter group reviver while inferring its payload type from `payloadSchema`.
760
599
  *
761
- * @category schemas
600
+ * @category constructors
762
601
  * @since 4.0.0
763
602
  */
764
- export const $PrimitiveTree: Schema.Codec<PrimitiveTree> = Schema.Tree(
765
- Schema.Union([
766
- Schema.Null,
767
- Schema.Number, // allows NaN, Infinity, -Infinity
768
- Schema.Boolean,
769
- Schema.BigInt,
770
- Schema.Symbol,
771
- Schema.String
772
- ])
773
- )
774
-
775
- const isPrimitiveTree = Schema.is($PrimitiveTree)
603
+ export const makeFilterGroupReviver: <P>(
604
+ id: string,
605
+ payloadSchema: Schema.Decoder<P>,
606
+ revive: FilterGroupReviver<P>["revive"]
607
+ ) => FilterGroupReviver<P> = InternalSchema.makeFilterGroupReviver
776
608
 
777
609
  /**
778
- * Schema for serializing public `Schema.Annotations.Annotations` values. It
779
- * filters out internal annotation keys and non-primitive values during
780
- * encoding.
610
+ * Options for importing JSON Schema Draft 2020-12 documents.
781
611
  *
782
612
  * **When to use**
783
613
  *
784
- * Use to serialize schema annotations in representation schemas while retaining
785
- * only primitive-tree metadata.
614
+ * Use when each JSON Schema node must be transformed before it is translated.
786
615
  *
787
- * **Details**
788
- *
789
- * Decoding is passthrough. Encoding removes internal annotation keys and values
790
- * that are not accepted by `$PrimitiveTree`.
616
+ * **Gotchas**
791
617
  *
792
- * @see {@link $PrimitiveTree} for the codec used to filter annotation values
618
+ * `onEnter` must return a JSON Schema object. Its result is used directly, and exceptions raised by the callback pass through unchanged.
793
619
  *
794
- * @category schemas
620
+ * @category models
795
621
  * @since 4.0.0
796
622
  */
797
- export const $Annotations = Schema.Record(Schema.String, Schema.Unknown).pipe(
798
- Schema.encodeTo(Schema.Record(Schema.String, $PrimitiveTree), {
799
- decode: SchemaGetter.passthrough(),
800
- encode: SchemaGetter.transformOptional(Option.flatMap((r) => {
801
- const out: Record<string, typeof $PrimitiveTree["Type"]> = {}
802
- for (const [k, v] of Object.entries(r)) {
803
- if (!toJsonAnnotationsBlacklist.has(k) && isPrimitiveTree(v)) {
804
- out[k] = v
805
- }
806
- }
807
- return Rec.isEmptyRecord(out) ? Option.none() : Option.some(out)
808
- }))
809
- })
810
- ).annotate({ identifier: "Annotations" })
623
+ export interface FromJsonSchemaOptions {
624
+ readonly onEnter?: ((schema: JsonSchema.JsonSchema) => JsonSchema.JsonSchema) | undefined
625
+ }
811
626
 
812
627
  /**
813
- * Schema for the {@link Null} representation node.
628
+ * Runtime and TypeScript source generated for one schema.
814
629
  *
815
- * @category schemas
630
+ * @category models
816
631
  * @since 4.0.0
817
632
  */
818
- export const $Null = Schema.Struct({
819
- _tag: Schema.tag("Null"),
820
- annotations: Schema.optional($Annotations)
821
- }).annotate({ identifier: "Null" })
633
+ export interface Code {
634
+ readonly runtime: string
635
+ readonly Type: string
636
+ }
822
637
 
823
638
  /**
824
- * Schema for the {@link Undefined} representation node.
639
+ * Creates generated runtime and TypeScript source strings for a schema.
825
640
  *
826
- * @category schemas
641
+ * @category constructors
827
642
  * @since 4.0.0
828
643
  */
829
- export const $Undefined = Schema.Struct({
830
- _tag: Schema.tag("Undefined"),
831
- annotations: Schema.optional($Annotations)
832
- }).annotate({ identifier: "Undefined" })
644
+ export const makeCode: (runtime: string, Type: string) => Code = InternalToCodeDocument.makeCode
833
645
 
834
646
  /**
835
- * Schema for the {@link Void} representation node.
647
+ * Auxiliary source artifact emitted while generating schema code.
836
648
  *
837
- * @category schemas
649
+ * @category models
838
650
  * @since 4.0.0
839
651
  */
840
- export const $Void = Schema.Struct({
841
- _tag: Schema.tag("Void"),
842
- annotations: Schema.optional($Annotations)
843
- }).annotate({ identifier: "Void" })
652
+ export type Artifact =
653
+ | {
654
+ readonly _tag: "Symbol"
655
+ readonly identifier: string
656
+ readonly code: Code
657
+ }
658
+ | {
659
+ readonly _tag: "Enum"
660
+ readonly identifier: string
661
+ readonly code: Code
662
+ }
663
+ | {
664
+ readonly _tag: "Import"
665
+ readonly importDeclaration: string
666
+ }
844
667
 
845
668
  /**
846
- * Schema for the {@link Never} representation node.
669
+ * Generated schema code together with named references and auxiliary artifacts.
847
670
  *
848
- * @category schemas
671
+ * @category models
849
672
  * @since 4.0.0
850
673
  */
851
- export const $Never = Schema.Struct({
852
- _tag: Schema.tag("Never"),
853
- annotations: Schema.optional($Annotations)
854
- }).annotate({ identifier: "Never" })
855
-
856
- /**
857
- * Schema for the {@link Unknown} representation node.
858
- *
859
- * @category schemas
860
- * @since 4.0.0
861
- */
862
- export const $Unknown = Schema.Struct({
863
- _tag: Schema.tag("Unknown"),
864
- annotations: Schema.optional($Annotations)
865
- }).annotate({ identifier: "Unknown" })
674
+ export interface CodeDocument {
675
+ readonly codes: ReadonlyArray<Code>
676
+ readonly references: {
677
+ readonly nonRecursives: ReadonlyArray<{
678
+ readonly $ref: string
679
+ readonly code: Code
680
+ }>
681
+ readonly recursives: Readonly<Record<string, Code>>
682
+ }
683
+ readonly artifacts: ReadonlyArray<Artifact>
684
+ }
866
685
 
867
686
  /**
868
- * Schema for the {@link Any} representation node.
687
+ * Lowers the encoded side of an AST to a live representation document.
869
688
  *
870
- * @category schemas
689
+ * **Details**
690
+ *
691
+ * Apply `SchemaAST.toType` to the AST first to lower its type side instead.
692
+ *
693
+ * @category constructors
871
694
  * @since 4.0.0
872
695
  */
873
- export const $Any = Schema.Struct({
874
- _tag: Schema.tag("Any"),
875
- annotations: Schema.optional($Annotations)
876
- }).annotate({ identifier: "Any" })
877
-
878
- const $IsStringFinite = Schema.Struct({
879
- _tag: Schema.tag("isStringFinite"),
880
- regExp: Schema.RegExp
881
- }).annotate({ identifier: "IsStringFinite" })
882
-
883
- const $IsStringBigInt = Schema.Struct({
884
- _tag: Schema.tag("isStringBigInt"),
885
- regExp: Schema.RegExp
886
- }).annotate({ identifier: "IsStringBigInt" })
887
-
888
- const $IsStringSymbol = Schema.Struct({
889
- _tag: Schema.tag("isStringSymbol"),
890
- regExp: Schema.RegExp
891
- }).annotate({ identifier: "IsStringSymbol" })
892
-
893
- const $IsTrimmed = Schema.Struct({
894
- _tag: Schema.tag("isTrimmed"),
895
- regExp: Schema.RegExp
896
- }).annotate({ identifier: "IsTrimmed" })
897
-
898
- const $IsUUID = Schema.Struct({
899
- _tag: Schema.tag("isUUID"),
900
- regExp: Schema.RegExp,
901
- version: Schema.UndefinedOr(Schema.Literals([1, 2, 3, 4, 5, 6, 7, 8]))
902
- }).annotate({ identifier: "IsUUID" })
903
-
904
- const $IsGUID = Schema.Struct({
905
- _tag: Schema.tag("isGUID"),
906
- regExp: Schema.RegExp
907
- }).annotate({ identifier: "IsGUID" })
908
-
909
- const $IsULID = Schema.Struct({
910
- _tag: Schema.tag("isULID"),
911
- regExp: Schema.RegExp
912
- }).annotate({ identifier: "IsULID" })
913
-
914
- const $IsBase64 = Schema.Struct({
915
- _tag: Schema.tag("isBase64"),
916
- regExp: Schema.RegExp
917
- }).annotate({ identifier: "IsBase64" })
918
-
919
- const $IsBase64Url = Schema.Struct({
920
- _tag: Schema.tag("isBase64Url"),
921
- regExp: Schema.RegExp
922
- }).annotate({ identifier: "IsBase64Url" })
923
-
924
- const $IsStartsWith = Schema.Struct({
925
- _tag: Schema.tag("isStartsWith"),
926
- startsWith: Schema.String,
927
- regExp: Schema.RegExp
928
- }).annotate({ identifier: "IsStartsWith" })
929
-
930
- const $IsEndsWith = Schema.Struct({
931
- _tag: Schema.tag("isEndsWith"),
932
- endsWith: Schema.String,
933
- regExp: Schema.RegExp
934
- }).annotate({ identifier: "IsEndsWith" })
935
-
936
- const $IsIncludes = Schema.Struct({
937
- _tag: Schema.tag("isIncludes"),
938
- includes: Schema.String,
939
- regExp: Schema.RegExp
940
- }).annotate({ identifier: "IsIncludes" })
941
-
942
- const $IsUppercased = Schema.Struct({
943
- _tag: Schema.tag("isUppercased"),
944
- regExp: Schema.RegExp
945
- }).annotate({ identifier: "IsUppercased" })
946
-
947
- const $IsLowercased = Schema.Struct({
948
- _tag: Schema.tag("isLowercased"),
949
- regExp: Schema.RegExp
950
- }).annotate({ identifier: "IsLowercased" })
951
-
952
- const $IsCapitalized = Schema.Struct({
953
- _tag: Schema.tag("isCapitalized"),
954
- regExp: Schema.RegExp
955
- }).annotate({ identifier: "IsCapitalized" })
956
-
957
- const $IsUncapitalized = Schema.Struct({
958
- _tag: Schema.tag("isUncapitalized"),
959
- regExp: Schema.RegExp
960
- }).annotate({ identifier: "IsUncapitalized" })
961
-
962
- const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))
963
-
964
- const $IsMinLength = Schema.Struct({
965
- _tag: Schema.tag("isMinLength"),
966
- minLength: NonNegativeInt
967
- }).annotate({ identifier: "IsMinLength" })
968
-
969
- const $IsMaxLength = Schema.Struct({
970
- _tag: Schema.tag("isMaxLength"),
971
- maxLength: NonNegativeInt
972
- }).annotate({ identifier: "IsMaxLength" })
973
-
974
- const $IsLengthBetween = Schema.Struct({
975
- _tag: Schema.tag("isLengthBetween"),
976
- minimum: NonNegativeInt,
977
- maximum: NonNegativeInt
978
- }).annotate({ identifier: "IsLengthBetween" })
979
-
980
- const $IsPattern = Schema.Struct({
981
- _tag: Schema.tag("isPattern"),
982
- regExp: Schema.RegExp
983
- }).annotate({ identifier: "IsPattern" })
984
-
985
- /**
986
- * Schema for {@link StringMeta}.
987
- *
988
- * @category schemas
989
- * @since 4.0.0
990
- */
991
- export const $StringMeta = Schema.Union([
992
- $IsStringFinite,
993
- $IsStringBigInt,
994
- $IsStringSymbol,
995
- $IsTrimmed,
996
- $IsUUID,
997
- $IsGUID,
998
- $IsULID,
999
- $IsBase64,
1000
- $IsBase64Url,
1001
- $IsStartsWith,
1002
- $IsEndsWith,
1003
- $IsIncludes,
1004
- $IsUppercased,
1005
- $IsLowercased,
1006
- $IsCapitalized,
1007
- $IsUncapitalized,
1008
- $IsMinLength,
1009
- $IsMaxLength,
1010
- $IsPattern,
1011
- $IsLengthBetween
1012
- ]).annotate({ identifier: "StringMeta" })
1013
-
1014
- function makeCheck<T>(meta: Schema.Codec<T>, identifier: string) {
1015
- const Check$ref = Schema.suspend(() => Check)
1016
- const Check: Schema.Codec<Check<T>> = Schema.Union([
1017
- Schema.Struct({
1018
- _tag: Schema.tag("Filter"),
1019
- annotations: Schema.optional($Annotations),
1020
- meta
1021
- }).annotate({ identifier: `${identifier}Filter` }),
1022
- Schema.Struct({
1023
- _tag: Schema.tag("FilterGroup"),
1024
- annotations: Schema.optional($Annotations),
1025
- checks: Schema.NonEmptyArray(Check$ref)
1026
- }).annotate({ identifier: `${identifier}FilterGroup` })
1027
- ]).annotate({ identifier: `${identifier}Check` })
1028
- return Check
696
+ export function toRepresentation(ast: SchemaAST.AST): Document {
697
+ return InternalToRepresentation.toRepresentation(ast)
1029
698
  }
1030
699
 
1031
700
  /**
1032
- * Schema for the {@link String} representation node.
701
+ * Lowers one or more AST encoded sides in a shared reference environment.
1033
702
  *
1034
- * @category schemas
1035
- * @since 4.0.0
1036
- */
1037
- export const $String = Schema.Struct({
1038
- _tag: Schema.tag("String"),
1039
- annotations: Schema.optional($Annotations),
1040
- checks: Schema.Array(makeCheck($StringMeta, "String")),
1041
- contentMediaType: Schema.optional(Schema.String),
1042
- contentSchema: Schema.optional(Representation$ref)
1043
- }).annotate({ identifier: "String" })
1044
-
1045
- const $IsInt = Schema.Struct({
1046
- _tag: Schema.tag("isInt")
1047
- }).annotate({ identifier: "IsInt" })
1048
-
1049
- const $IsMultipleOf = Schema.Struct({
1050
- _tag: Schema.tag("isMultipleOf"),
1051
- divisor: Schema.Finite
1052
- }).annotate({ identifier: "IsMultipleOf" })
1053
-
1054
- const $IsFinite = Schema.Struct({
1055
- _tag: Schema.tag("isFinite")
1056
- }).annotate({ identifier: "IsFinite" })
1057
-
1058
- const $IsGreaterThan = Schema.Struct({
1059
- _tag: Schema.tag("isGreaterThan"),
1060
- exclusiveMinimum: Schema.Finite
1061
- }).annotate({ identifier: "IsGreaterThan" })
1062
-
1063
- const $IsGreaterThanOrEqualTo = Schema.Struct({
1064
- _tag: Schema.tag("isGreaterThanOrEqualTo"),
1065
- minimum: Schema.Finite
1066
- }).annotate({ identifier: "IsGreaterThanOrEqualTo" })
1067
-
1068
- const $IsLessThan = Schema.Struct({
1069
- _tag: Schema.tag("isLessThan"),
1070
- exclusiveMaximum: Schema.Finite
1071
- }).annotate({ identifier: "IsLessThan" })
1072
-
1073
- const $IsLessThanOrEqualTo = Schema.Struct({
1074
- _tag: Schema.tag("isLessThanOrEqualTo"),
1075
- maximum: Schema.Finite
1076
- }).annotate({ identifier: "IsLessThanOrEqualTo" })
1077
-
1078
- const $IsBetween = Schema.Struct({
1079
- _tag: Schema.tag("isBetween"),
1080
- minimum: Schema.Finite,
1081
- maximum: Schema.Finite,
1082
- exclusiveMinimum: Schema.optional(Schema.Boolean),
1083
- exclusiveMaximum: Schema.optional(Schema.Boolean)
1084
- }).annotate({ identifier: "IsBetween" })
1085
-
1086
- /**
1087
- * Schema for {@link NumberMeta}.
703
+ * **Details**
704
+ *
705
+ * Apply `SchemaAST.toType` to an AST first to lower its type side instead.
1088
706
  *
1089
- * @category schemas
707
+ * @category constructors
1090
708
  * @since 4.0.0
1091
709
  */
1092
- export const $NumberMeta = Schema.Union([
1093
- $IsInt,
1094
- $IsMultipleOf,
1095
- $IsFinite,
1096
- $IsGreaterThan,
1097
- $IsGreaterThanOrEqualTo,
1098
- $IsLessThan,
1099
- $IsLessThanOrEqualTo,
1100
- $IsBetween
1101
- ]).annotate({ identifier: "NumberMeta" })
710
+ export function toRepresentations(
711
+ asts: readonly [SchemaAST.AST, ...Array<SchemaAST.AST>]
712
+ ): MultiDocument {
713
+ return InternalToRepresentation.toRepresentations(asts)
714
+ }
1102
715
 
1103
716
  /**
1104
- * Schema for the {@link Number} representation node.
717
+ * Converts live schemas and their named definitions to a shared representation document.
718
+ *
719
+ * **When to use**
720
+ *
721
+ * Use when schemas with shared or unreachable definitions must be passed to representation compilers such as `toCodeDocument`.
722
+ *
723
+ * **Gotchas**
724
+ *
725
+ * Every schema is projected to its encoded side. Definitions are preserved even when no root reaches them.
1105
726
  *
1106
- * @category schemas
727
+ * @see {@link toRepresentations} for converting AST roots without an explicit definition map
728
+ * @see {@link toCodeDocument} for generating code from the result
729
+ *
730
+ * @category constructors
1107
731
  * @since 4.0.0
1108
732
  */
1109
- export const $Number = Schema.Struct({
1110
- _tag: Schema.tag("Number"),
1111
- annotations: Schema.optional($Annotations),
1112
- checks: Schema.Array(makeCheck($NumberMeta, "Number"))
1113
- }).annotate({ identifier: "Number" })
733
+ export function fromSchemaMultiDocument(document: SchemaMultiDocument): MultiDocument {
734
+ return InternalToRepresentation.fromSchemaMultiDocument(document)
735
+ }
1114
736
 
1115
737
  /**
1116
- * Schema for the {@link Boolean} representation node.
738
+ * Wraps a single representation document as a multi-document with one root.
739
+ *
740
+ * **When to use**
741
+ *
742
+ * Use when an API such as `toCodeDocument` requires a `MultiDocument`.
1117
743
  *
1118
- * @category schemas
744
+ * @category transforming
1119
745
  * @since 4.0.0
1120
746
  */
1121
- export const $Boolean = Schema.Struct({
1122
- _tag: Schema.tag("Boolean"),
1123
- annotations: Schema.optional($Annotations)
1124
- }).annotate({ identifier: "Boolean" })
1125
-
1126
- const $IsGreaterThanBigInt = Schema.Struct({
1127
- _tag: Schema.tag("isGreaterThanBigInt"),
1128
- exclusiveMinimum: Schema.BigInt
1129
- }).annotate({ identifier: "IsGreaterThanBigInt" })
1130
-
1131
- const $IsGreaterThanOrEqualToBigInt = Schema.Struct({
1132
- _tag: Schema.tag("isGreaterThanOrEqualToBigInt"),
1133
- minimum: Schema.BigInt
1134
- }).annotate({ identifier: "IsGreaterThanOrEqualToBigInt" })
1135
-
1136
- const $IsLessThanBigInt = Schema.Struct({
1137
- _tag: Schema.tag("isLessThanBigInt"),
1138
- exclusiveMaximum: Schema.BigInt
1139
- }).annotate({ identifier: "IsLessThanBigInt" })
1140
-
1141
- const $IsLessThanOrEqualToBigInt = Schema.Struct({
1142
- _tag: Schema.tag("isLessThanOrEqualToBigInt"),
1143
- maximum: Schema.BigInt
1144
- }).annotate({ identifier: "IsLessThanOrEqualToBigInt" })
1145
-
1146
- const $IsBetweenBigInt = Schema.Struct({
1147
- _tag: Schema.tag("isBetweenBigInt"),
1148
- minimum: Schema.BigInt,
1149
- maximum: Schema.BigInt,
1150
- exclusiveMinimum: Schema.optional(Schema.Boolean),
1151
- exclusiveMaximum: Schema.optional(Schema.Boolean)
1152
- }).annotate({ identifier: "IsBetweenBigInt" })
1153
-
1154
- const $BigIntMeta = Schema.Union([
1155
- $IsGreaterThanBigInt,
1156
- $IsGreaterThanOrEqualToBigInt,
1157
- $IsLessThanBigInt,
1158
- $IsLessThanOrEqualToBigInt,
1159
- $IsBetweenBigInt
1160
- ]).annotate({ identifier: "BigIntMeta" })
747
+ export function toMultiDocument(document: Document): MultiDocument {
748
+ return {
749
+ representations: [document.representation],
750
+ references: document.references
751
+ }
752
+ }
1161
753
 
1162
754
  /**
1163
- * Schema for the {@link BigInt} representation node.
755
+ * Compiles a live representation document to JSON Schema Draft 2020-12.
1164
756
  *
1165
757
  * **When to use**
1166
758
  *
1167
- * Use to encode, decode, or validate serialized `BigInt` representation nodes,
1168
- * not application `bigint` values.
759
+ * Use when you need JSON Schema output from a representation whose checks carry compiler annotations.
1169
760
  *
1170
- * **Details**
761
+ * **Gotchas**
1171
762
  *
1172
- * Accepts representation nodes with `_tag: "BigInt"`, optional annotations,
1173
- * and bigint-specific validation metadata in `checks`.
763
+ * Opaque declarations are represented by an unconstrained JSON Schema. Check callback results are used directly, and exceptions raised by a callback pass through unchanged.
1174
764
  *
1175
- * @see {@link BigIntMeta} for the metadata accepted by the `checks` array
765
+ * @see {@link toJsonSchemaMultiDocument} for multiple roots sharing definitions
1176
766
  *
1177
- * @category schemas
767
+ * @category transforming
1178
768
  * @since 4.0.0
1179
769
  */
1180
- export const $BigInt = Schema.Struct({
1181
- _tag: Schema.tag("BigInt"),
1182
- annotations: Schema.optional($Annotations),
1183
- checks: Schema.Array(makeCheck($BigIntMeta, "BigInt"))
1184
- }).annotate({ identifier: "BigInt" })
770
+ export function toJsonSchemaDocument(
771
+ document: Document,
772
+ options?: Schema.ToJsonSchemaOptions
773
+ ): JsonSchema.Document<"draft-2020-12"> {
774
+ return InternalToJsonSchemaDocument.toJsonSchemaDocument(document, options)
775
+ }
1185
776
 
1186
777
  /**
1187
- * Schema for the {@link Symbol} representation node.
778
+ * Compiles multiple live representations to a shared JSON Schema Draft 2020-12 document.
1188
779
  *
1189
- * @category schemas
1190
- * @since 4.0.0
1191
- */
1192
- export const $Symbol = Schema.Struct({
1193
- _tag: Schema.tag("Symbol"),
1194
- annotations: Schema.optional($Annotations)
1195
- }).annotate({ identifier: "Symbol" })
1196
-
1197
- /**
1198
- * Schema for the literal value types allowed in a {@link Literal} node
1199
- * (string, finite number, boolean, or bigint).
780
+ * **When to use**
1200
781
  *
1201
- * @category schemas
1202
- * @since 4.0.0
1203
- */
1204
- export const $LiteralValue = Schema.Union([
1205
- Schema.String,
1206
- Schema.Finite,
1207
- Schema.Boolean,
1208
- Schema.BigInt
1209
- ]).annotate({ identifier: "LiteralValue" })
1210
-
1211
- /**
1212
- * Schema for the {@link Literal} representation node.
782
+ * Use when several representation roots must share the same JSON Schema definitions.
1213
783
  *
1214
- * @category schemas
1215
- * @since 4.0.0
1216
- */
1217
- export const $Literal = Schema.Struct({
1218
- _tag: Schema.tag("Literal"),
1219
- annotations: Schema.optional($Annotations),
1220
- literal: $LiteralValue
1221
- }).annotate({ identifier: "Literal" })
1222
-
1223
- /**
1224
- * Schema for the {@link UniqueSymbol} representation node.
784
+ * **Gotchas**
1225
785
  *
1226
- * @category schemas
1227
- * @since 4.0.0
1228
- */
1229
- export const $UniqueSymbol = Schema.Struct({
1230
- _tag: Schema.tag("UniqueSymbol"),
1231
- annotations: Schema.optional($Annotations),
1232
- symbol: Schema.Symbol
1233
- }).annotate({ identifier: "UniqueSymbol" })
1234
-
1235
- /**
1236
- * Schema for the {@link ObjectKeyword} representation node.
786
+ * Every definition is compiled, including definitions that are not reachable from a root.
1237
787
  *
1238
- * @category schemas
1239
- * @since 4.0.0
1240
- */
1241
- export const $ObjectKeyword = Schema.Struct({
1242
- _tag: Schema.tag("ObjectKeyword"),
1243
- annotations: Schema.optional($Annotations)
1244
- }).annotate({ identifier: "ObjectKeyword" })
1245
-
1246
- /**
1247
- * Schema for the {@link Enum} representation node.
788
+ * @see {@link toJsonSchemaDocument} for a single root
1248
789
  *
1249
- * @category schemas
790
+ * @category transforming
1250
791
  * @since 4.0.0
1251
792
  */
1252
- export const $Enum = Schema.Struct({
1253
- _tag: Schema.tag("Enum"),
1254
- annotations: Schema.optional($Annotations),
1255
- enums: Schema.Array(
1256
- Schema.Tuple([
1257
- Schema.String,
1258
- Schema.Union([
1259
- Schema.String,
1260
- Schema.Number // NaN, Infinity, -Infinity are allowed enum values
1261
- ])
1262
- ])
1263
- )
1264
- }).annotate({ identifier: "Enum" })
793
+ export function toJsonSchemaMultiDocument(
794
+ document: MultiDocument,
795
+ options?: Schema.ToJsonSchemaOptions
796
+ ): JsonSchema.MultiDocument<"draft-2020-12"> {
797
+ return InternalToJsonSchemaDocument.toJsonSchemaMultiDocument(document, options)
798
+ }
1265
799
 
1266
800
  /**
1267
- * Schema for the {@link TemplateLiteral} representation node.
801
+ * Generates TypeScript source for live schema representations and their definitions.
1268
802
  *
1269
- * @category schemas
1270
- * @since 4.0.0
1271
- */
1272
- export const $TemplateLiteral = Schema.Struct({
1273
- _tag: Schema.tag("TemplateLiteral"),
1274
- annotations: Schema.optional($Annotations),
1275
- parts: Schema.Array(Representation$ref)
1276
- }).annotate({ identifier: "TemplateLiteral" })
1277
-
1278
- /**
1279
- * Schema for the {@link Element} type (positional tuple element).
803
+ * **When to use**
1280
804
  *
1281
- * @category schemas
1282
- * @since 4.0.0
1283
- */
1284
- export const $Element = Schema.Struct({
1285
- isOptional: Schema.Boolean,
1286
- type: Representation$ref,
1287
- annotations: Schema.optional($Annotations)
1288
- }).annotate({ identifier: "Element" })
1289
-
1290
- const $IsUnique = Schema.Struct({
1291
- _tag: Schema.tag("isUnique")
1292
- }).annotate({ identifier: "IsUnique" })
1293
-
1294
- const $ArraysMeta = Schema.Union([
1295
- $IsMinLength,
1296
- $IsMaxLength,
1297
- $IsLengthBetween,
1298
- $IsUnique
1299
- ]).annotate({ identifier: "ArraysMeta" })
1300
-
1301
- /**
1302
- * Schema for the {@link Arrays} representation node.
805
+ * Use when custom declarations and checks provide `toCode` callbacks and must be emitted without a central handler registry.
1303
806
  *
1304
- * @category schemas
1305
- * @since 4.0.0
1306
- */
1307
- export const $Arrays = Schema.Struct({
1308
- _tag: Schema.tag("Arrays"),
1309
- annotations: Schema.optional($Annotations),
1310
- elements: Schema.Array($Element),
1311
- rest: Schema.Array(Representation$ref),
1312
- checks: Schema.Array(makeCheck($ArraysMeta, "Arrays"))
1313
- }).annotate({ identifier: "Arrays" })
1314
-
1315
- /**
1316
- * Schema for the {@link PropertySignature} type.
807
+ * **Gotchas**
1317
808
  *
1318
- * @category schemas
1319
- * @since 4.0.0
1320
- */
1321
- export const $PropertySignature = Schema.Struct({
1322
- annotations: Schema.optional($Annotations),
1323
- name: Schema.PropertyKey,
1324
- type: Representation$ref,
1325
- isOptional: Schema.Boolean,
1326
- isMutable: Schema.Boolean
1327
- }).annotate({ identifier: "PropertySignature" })
1328
-
1329
- /**
1330
- * Schema for the {@link IndexSignature} type.
809
+ * Opaque declarations and leaf checks require `toCode` callbacks. Callback results are used directly, and exceptions raised by a callback pass through unchanged.
1331
810
  *
1332
- * @category schemas
811
+ * @category transforming
1333
812
  * @since 4.0.0
1334
813
  */
1335
- export const $IndexSignature = Schema.Struct({
1336
- parameter: Representation$ref,
1337
- type: Representation$ref
1338
- }).annotate({ identifier: "IndexSignature" })
814
+ export function toCodeDocument(document: MultiDocument): CodeDocument {
815
+ return InternalToCodeDocument.toCodeDocument(document)
816
+ }
1339
817
 
1340
- const $IsMinProperties = Schema.Struct({
1341
- _tag: Schema.tag("isMinProperties"),
1342
- minProperties: NonNegativeInt
1343
- }).annotate({ identifier: "IsMinProperties" })
818
+ const RepresentationSchema = Schema.suspend(
819
+ (): Schema.Codec<Representation, unknown> => RepresentationUnion
820
+ )
821
+ const RepresentationsSchema = Schema.Array(RepresentationSchema)
1344
822
 
1345
- const $IsMaxProperties = Schema.Struct({
1346
- _tag: Schema.tag("isMaxProperties"),
1347
- maxProperties: NonNegativeInt
1348
- }).annotate({ identifier: "IsMaxProperties" })
823
+ const RepresentationAnnotationSchema = Schema.Struct({
824
+ id: Schema.NonEmptyString,
825
+ payload: Schema.Json
826
+ })
1349
827
 
1350
- const $IsPropertiesLengthBetween = Schema.Struct({
1351
- _tag: Schema.tag("isPropertiesLengthBetween"),
1352
- minimum: NonNegativeInt,
1353
- maximum: NonNegativeInt
1354
- }).annotate({ identifier: "IsPropertiesLengthBetween" })
828
+ const CheckRepresentationAnnotationSchema = Schema.Struct({
829
+ ...RepresentationAnnotationSchema.fields,
830
+ schemas: Schema.optional(RepresentationsSchema)
831
+ })
1355
832
 
1356
- const $IsPropertyNames = Schema.Struct({
1357
- _tag: Schema.tag("isPropertyNames"),
1358
- propertyNames: Representation$ref
1359
- }).annotate({ identifier: "IsPropertyNames" })
833
+ const LiveAnnotationsSchema = Schema.Record(Schema.String, Schema.Unknown)
834
+ const JsonAnnotationsSchema = Schema.Record(Schema.String, Schema.Json)
1360
835
 
1361
- /**
1362
- * Schema for {@link ObjectsMeta}.
1363
- *
1364
- * @category schemas
1365
- * @since 4.0.0
1366
- */
1367
- export const $ObjectsMeta = Schema.Union([
1368
- $IsMinProperties,
1369
- $IsMaxProperties,
1370
- $IsPropertiesLengthBetween,
1371
- $IsPropertyNames
1372
- ]).annotate({ identifier: "ObjectsMeta" })
836
+ function pruneAnnotations(
837
+ annotations: Readonly<Record<string, unknown>>
838
+ ): Option.Option<Readonly<Record<string, Schema.Json>>> {
839
+ const out: Record<string, Schema.Json> = {}
840
+ for (const [key, value] of Object.entries(annotations)) {
841
+ if (SchemaAST.isJson(value)) {
842
+ InternalRecord.assignProperty(out, key, value)
843
+ }
844
+ }
845
+ return Object.keys(out).length === 0 ? Option.none() : Option.some(out)
846
+ }
1373
847
 
1374
- /**
1375
- * Schema for the {@link Objects} representation node.
1376
- *
1377
- * @category schemas
1378
- * @since 4.0.0
1379
- */
1380
- export const $Objects = Schema.Struct({
1381
- _tag: Schema.tag("Objects"),
1382
- annotations: Schema.optional($Annotations),
1383
- propertySignatures: Schema.Array($PropertySignature),
1384
- indexSignatures: Schema.Array($IndexSignature),
1385
- checks: Schema.Array(makeCheck($ObjectsMeta, "Objects"))
1386
- }).annotate({ identifier: "Objects" })
848
+ const AnnotationsSchema = Schema.optional(LiveAnnotationsSchema).pipe(
849
+ Schema.encodeTo(Schema.optionalKey(JsonAnnotationsSchema), {
850
+ decode: SchemaGetter.passthroughSubtype(),
851
+ encode: SchemaGetter.transformOptional((annotations) =>
852
+ Option.isNone(annotations) || annotations.value === undefined
853
+ ? Option.none()
854
+ : pruneAnnotations(annotations.value)
855
+ )
856
+ })
857
+ )
1387
858
 
1388
- /**
1389
- * Schema for the {@link Union} representation node.
1390
- *
1391
- * @category schemas
1392
- * @since 4.0.0
1393
- */
1394
- export const $Union = Schema.Struct({
859
+ const CheckSchema = Schema.suspend((): Schema.Codec<Check, unknown> => CheckUnion)
860
+ const ChecksSchema = Schema.Array(CheckSchema)
861
+ const KeywordFields = {
862
+ annotations: AnnotationsSchema,
863
+ checks: ChecksSchema
864
+ }
865
+ const FilterSchema = Schema.Struct({
866
+ _tag: Schema.tag("Filter"),
867
+ representation: CheckRepresentationAnnotationSchema,
868
+ annotations: AnnotationsSchema,
869
+ aborted: Schema.Boolean
870
+ })
871
+ const FilterGroupSchema = Schema.Struct({
872
+ _tag: Schema.tag("FilterGroup"),
873
+ representation: Schema.optional(CheckRepresentationAnnotationSchema),
874
+ annotations: AnnotationsSchema,
875
+ checks: Schema.NonEmptyArray(CheckSchema)
876
+ })
877
+ const CheckUnion = Schema.Union([FilterSchema, FilterGroupSchema])
878
+
879
+ function makeKeywordSchema<Tag extends Exclude<Representation["_tag"], "Reference">>(tag: Tag) {
880
+ return Schema.Struct({
881
+ _tag: Schema.tag(tag),
882
+ ...KeywordFields
883
+ })
884
+ }
885
+
886
+ const DeclarationSchema = Schema.Struct({
887
+ _tag: Schema.tag("Declaration"),
888
+ representation: RepresentationAnnotationSchema,
889
+ annotations: AnnotationsSchema,
890
+ typeParameters: RepresentationsSchema,
891
+ checks: ChecksSchema
892
+ })
893
+ const SuspendSchema = Schema.Struct({
894
+ _tag: Schema.tag("Suspend"),
895
+ annotations: AnnotationsSchema,
896
+ checks: Schema.Tuple([]),
897
+ thunk: RepresentationSchema
898
+ })
899
+ function makeValueSchema<Type extends string, Value>(type: Type, value: Schema.Codec<Value>) {
900
+ return value.pipe(
901
+ Schema.encodeTo(Schema.Struct({ type: Schema.tag(type), value }), {
902
+ decode: SchemaGetter.transform((encoded: { readonly type: Type; readonly value: Value }) => encoded.value),
903
+ encode: SchemaGetter.transform((value: Value) => ({ type, value }))
904
+ })
905
+ )
906
+ }
907
+ const StringValueCodec = makeValueSchema("string", Schema.String)
908
+ const NumberValueCodec = makeValueSchema("number", Schema.Number)
909
+ const LiteralSchema = Schema.Struct({
910
+ _tag: Schema.tag("Literal"),
911
+ ...KeywordFields,
912
+ literal: Schema.Union([
913
+ StringValueCodec,
914
+ makeValueSchema("number", Schema.Finite),
915
+ makeValueSchema("bigint", Schema.BigInt),
916
+ makeValueSchema("boolean", Schema.Boolean)
917
+ ])
918
+ })
919
+ const UniqueSymbolSchema = Schema.Struct({
920
+ _tag: Schema.tag("UniqueSymbol"),
921
+ ...KeywordFields,
922
+ symbol: Schema.Symbol
923
+ })
924
+ const EnumSchema = Schema.Struct({
925
+ _tag: Schema.tag("Enum"),
926
+ ...KeywordFields,
927
+ enums: Schema.Array(Schema.Tuple([
928
+ Schema.String,
929
+ Schema.Union([StringValueCodec, NumberValueCodec])
930
+ ]))
931
+ })
932
+ const TemplateLiteralSchema = Schema.Struct({
933
+ _tag: Schema.tag("TemplateLiteral"),
934
+ ...KeywordFields,
935
+ parts: RepresentationsSchema
936
+ })
937
+ const ElementSchema = Schema.Struct({
938
+ isOptional: Schema.Boolean,
939
+ type: RepresentationSchema,
940
+ annotations: AnnotationsSchema
941
+ })
942
+ const ArraysSchema = Schema.Struct({
943
+ _tag: Schema.tag("Arrays"),
944
+ ...KeywordFields,
945
+ elements: Schema.Array(ElementSchema),
946
+ rest: RepresentationsSchema
947
+ })
948
+ const PropertySignatureSchema = Schema.Struct({
949
+ name: Schema.Union([
950
+ StringValueCodec,
951
+ NumberValueCodec,
952
+ makeValueSchema("symbol", Schema.Symbol)
953
+ ]),
954
+ type: RepresentationSchema,
955
+ isOptional: Schema.Boolean,
956
+ isMutable: Schema.Boolean,
957
+ annotations: AnnotationsSchema
958
+ })
959
+ const IndexSignatureSchema = Schema.Struct({
960
+ parameter: RepresentationSchema,
961
+ type: RepresentationSchema
962
+ })
963
+ const ObjectsSchema = Schema.Struct({
964
+ _tag: Schema.tag("Objects"),
965
+ ...KeywordFields,
966
+ propertySignatures: Schema.Array(PropertySignatureSchema),
967
+ indexSignatures: Schema.Array(IndexSignatureSchema)
968
+ })
969
+ const UnionSchema = Schema.Struct({
1395
970
  _tag: Schema.tag("Union"),
1396
- annotations: Schema.optional($Annotations),
1397
- types: Schema.Array(Representation$ref),
971
+ ...KeywordFields,
972
+ types: RepresentationsSchema,
1398
973
  mode: Schema.Literals(["anyOf", "oneOf"])
1399
- }).annotate({ identifier: "Union" })
1400
-
1401
- /**
1402
- * Schema for the {@link Reference} representation node.
1403
- *
1404
- * @category schemas
1405
- * @since 4.0.0
1406
- */
1407
- export const $Reference = Schema.Struct({
974
+ })
975
+ const ReferenceSchema = Schema.Struct({
1408
976
  _tag: Schema.tag("Reference"),
1409
- $ref: Schema.String
1410
- }).annotate({ identifier: "Reference" })
1411
-
1412
- const $IsDateValid = Schema.Struct({
1413
- _tag: Schema.tag("isDateValid")
1414
- }).annotate({ identifier: "IsDateValid" })
1415
-
1416
- const $IsGreaterThanDate = Schema.Struct({
1417
- _tag: Schema.tag("isGreaterThanDate"),
1418
- exclusiveMinimum: Schema.Date
1419
- }).annotate({ identifier: "IsGreaterThanDate" })
1420
-
1421
- const $IsGreaterThanOrEqualToDate = Schema.Struct({
1422
- _tag: Schema.tag("isGreaterThanOrEqualToDate"),
1423
- minimum: Schema.Date
1424
- }).annotate({ identifier: "IsGreaterThanOrEqualToDate" })
1425
-
1426
- const $IsLessThanDate = Schema.Struct({
1427
- _tag: Schema.tag("isLessThanDate"),
1428
- exclusiveMaximum: Schema.Date
1429
- }).annotate({ identifier: "IsLessThanDate" })
1430
-
1431
- const $IsLessThanOrEqualToDate = Schema.Struct({
1432
- _tag: Schema.tag("isLessThanOrEqualToDate"),
1433
- maximum: Schema.Date
1434
- }).annotate({ identifier: "IsLessThanOrEqualToDate" })
1435
-
1436
- const $IsBetweenDate = Schema.Struct({
1437
- _tag: Schema.tag("isBetweenDate"),
1438
- minimum: Schema.Date,
1439
- maximum: Schema.Date,
1440
- exclusiveMinimum: Schema.optional(Schema.Boolean),
1441
- exclusiveMaximum: Schema.optional(Schema.Boolean)
1442
- }).annotate({ identifier: "IsBetweenDate" })
977
+ $ref: Schema.NonEmptyString
978
+ })
979
+
980
+ const RepresentationUnion = Schema.Union([
981
+ DeclarationSchema,
982
+ ReferenceSchema,
983
+ SuspendSchema,
984
+ makeKeywordSchema("Null"),
985
+ makeKeywordSchema("Undefined"),
986
+ makeKeywordSchema("Void"),
987
+ makeKeywordSchema("Never"),
988
+ makeKeywordSchema("Unknown"),
989
+ makeKeywordSchema("Any"),
990
+ makeKeywordSchema("String"),
991
+ makeKeywordSchema("Number"),
992
+ makeKeywordSchema("Boolean"),
993
+ makeKeywordSchema("BigInt"),
994
+ makeKeywordSchema("Symbol"),
995
+ makeKeywordSchema("ObjectKeyword"),
996
+ LiteralSchema,
997
+ UniqueSymbolSchema,
998
+ EnumSchema,
999
+ TemplateLiteralSchema,
1000
+ ArraysSchema,
1001
+ ObjectsSchema,
1002
+ UnionSchema
1003
+ ])
1443
1004
 
1444
- /**
1445
- * Schema for {@link DateMeta}.
1446
- *
1447
- * @category schemas
1448
- * @since 4.0.0
1449
- */
1450
- export const $DateMeta = Schema.Union([
1451
- $IsDateValid,
1452
- $IsGreaterThanDate,
1453
- $IsGreaterThanOrEqualToDate,
1454
- $IsLessThanDate,
1455
- $IsLessThanOrEqualToDate,
1456
- $IsBetweenDate
1457
- ]).annotate({ identifier: "DateMeta" })
1005
+ const ReferencesSchema = Schema.Record(Schema.String, RepresentationSchema)
1458
1006
 
1459
- const $IsMinSize = Schema.Struct({
1460
- _tag: Schema.tag("isMinSize"),
1461
- minSize: NonNegativeInt
1462
- }).annotate({ identifier: "IsMinSize" })
1007
+ const DocumentFromJson: Schema.Codec<Document, Schema.Json> = Schema.toCodecJson(
1008
+ Schema.Struct({
1009
+ representation: RepresentationSchema,
1010
+ references: ReferencesSchema
1011
+ })
1012
+ )
1463
1013
 
1464
- const $IsMaxSize = Schema.Struct({
1465
- _tag: Schema.tag("isMaxSize"),
1466
- maxSize: NonNegativeInt
1467
- }).annotate({ identifier: "IsMaxSize" })
1014
+ const MultiDocumentFromJson: Schema.Codec<MultiDocument, Schema.Json> = Schema.toCodecJson(
1015
+ Schema.Struct({
1016
+ representations: Schema.NonEmptyArray(RepresentationSchema),
1017
+ references: ReferencesSchema
1018
+ })
1019
+ )
1468
1020
 
1469
- const $IsSizeBetween = Schema.Struct({
1470
- _tag: Schema.tag("isSizeBetween"),
1471
- minimum: NonNegativeInt,
1472
- maximum: NonNegativeInt
1473
- }).annotate({ identifier: "IsSizeBetween" })
1021
+ const encodeDocument = Schema.encodeSync(DocumentFromJson)
1022
+ const encodeMultiDocument = Schema.encodeSync(MultiDocumentFromJson)
1023
+ const decodeDocument = Schema.decodeSync(DocumentFromJson)
1024
+ const decodeMultiDocument = Schema.decodeSync(MultiDocumentFromJson)
1474
1025
 
1475
1026
  /**
1476
- * Schema for {@link SizeMeta}.
1027
+ * Projects a live single-root representation document and encodes it as JSON.
1477
1028
  *
1478
- * @category schemas
1479
- * @since 4.0.0
1480
- */
1481
- export const $SizeMeta = Schema.Union([
1482
- $IsMinSize,
1483
- $IsMaxSize,
1484
- $IsSizeBetween
1485
- ]).annotate({ identifier: "SizeMeta" })
1486
-
1487
- /**
1488
- * Schema for {@link DeclarationMeta}.
1029
+ * **When to use**
1489
1030
  *
1490
- * @category schemas
1491
- * @since 4.0.0
1492
- */
1493
- export const $DeclarationMeta = Schema.Union([
1494
- $DateMeta,
1495
- $SizeMeta
1496
- ]).annotate({ identifier: "DeclarationMeta" })
1497
-
1498
- /**
1499
- * Schema for the {@link Declaration} representation node.
1031
+ * Use when you need a stable JSON value for storage or transport after calling `toRepresentation`.
1500
1032
  *
1501
- * @category schemas
1502
- * @since 4.0.0
1503
- */
1504
- export const $Declaration = Schema.Struct({
1505
- _tag: Schema.tag("Declaration"),
1506
- annotations: Schema.optional($Annotations),
1507
- typeParameters: Schema.Array(Representation$ref),
1508
- checks: Schema.Array(makeCheck($DeclarationMeta, "Declaration")),
1509
- encodedSchema: Representation$ref
1510
- }).annotate({ identifier: "Declaration" })
1511
-
1512
- /**
1513
- * Schema for the {@link Suspend} representation node.
1033
+ * **Gotchas**
1514
1034
  *
1515
- * @category schemas
1516
- * @since 4.0.0
1517
- */
1518
- export const $Suspend = Schema.Struct({
1519
- _tag: Schema.tag("Suspend"),
1520
- annotations: Schema.optional($Annotations),
1521
- checks: Schema.Tuple([]),
1522
- thunk: Representation$ref
1523
- }).annotate({ identifier: "Suspend" })
1524
-
1525
- /**
1526
- * Type-level helper for the recursive {@link $Representation} codec.
1035
+ * Generic annotations that are not JSON are omitted. Invalid persistence identities and unsupported structural values throw an `Error` containing their representation path.
1527
1036
  *
1528
- * @category schemas
1529
- * @since 4.0.0
1530
- */
1531
- export interface $Representation extends Schema.Codec<Representation> {}
1532
-
1533
- /**
1534
- * Schema for the full {@link Representation} union. It recursively validates
1535
- * and encodes any representation node.
1037
+ * @see {@link toRepresentation} for constructing the live document
1038
+ * @see {@link toJsonMultiDocument} for documents with multiple roots
1536
1039
  *
1537
- * @category schemas
1040
+ * @category encoding
1538
1041
  * @since 4.0.0
1539
1042
  */
1540
- export const $Representation: $Representation = Schema.Union([
1541
- $Null,
1542
- $Undefined,
1543
- $Void,
1544
- $Never,
1545
- $Unknown,
1546
- $Any,
1547
- $String,
1548
- $Number,
1549
- $Boolean,
1550
- $BigInt,
1551
- $Symbol,
1552
- $Literal,
1553
- $UniqueSymbol,
1554
- $ObjectKeyword,
1555
- $Enum,
1556
- $TemplateLiteral,
1557
- $Arrays,
1558
- $Objects,
1559
- $Union,
1560
- $Reference,
1561
- $Declaration,
1562
- $Suspend
1563
- ]).annotate({ identifier: "Schema" })
1043
+ export function toJson(document: Document): Schema.Json {
1044
+ return encodeDocument(document)
1045
+ }
1564
1046
 
1565
1047
  /**
1566
- * Schema for {@link Document}.
1048
+ * Projects a live multi-root representation document and encodes it as JSON.
1567
1049
  *
1568
1050
  * **When to use**
1569
1051
  *
1570
- * Use to validate or serialize a single schema representation document with
1571
- * `Schema.decodeUnknownSync` or `Schema.encodeSync`.
1052
+ * Use when you need one JSON value for multiple live roots that share a reference environment.
1572
1053
  *
1573
1054
  * **Gotchas**
1574
1055
  *
1575
- * This codec validates document structure but does not resolve `$ref` keys
1576
- * against `references`.
1577
- *
1578
- * @see {@link DocumentFromJson} for the JSON-string codec wrapper
1579
- * @see {@link $MultiDocument} for validating documents with multiple root representations
1056
+ * The root order and shared reference keys are preserved, while non-JSON generic annotations are omitted.
1580
1057
  *
1581
- * @category schemas
1582
- * @since 4.0.0
1583
- */
1584
- export const $Document = Schema.Struct({
1585
- representation: $Representation,
1586
- references: Schema.Record(Schema.String, $Representation)
1587
- }).annotate({ identifier: "Document" })
1588
-
1589
- /**
1590
- * Schema for {@link MultiDocument}.
1058
+ * @see {@link toRepresentations} for constructing the live multi-document
1059
+ * @see {@link toJson} for a single-root document
1591
1060
  *
1592
- * @category schemas
1061
+ * @category encoding
1593
1062
  * @since 4.0.0
1594
1063
  */
1595
- export const $MultiDocument = Schema.Struct({
1596
- representations: Schema.NonEmptyArray($Representation),
1597
- references: Schema.Record(Schema.String, $Representation)
1598
- }).annotate({ identifier: "MultiDocument" })
1599
-
1600
- // -----------------------------------------------------------------------------
1601
- // APIs
1602
- // -----------------------------------------------------------------------------
1064
+ export function toJsonMultiDocument(document: MultiDocument): Schema.Json {
1065
+ return encodeMultiDocument(document)
1066
+ }
1603
1067
 
1604
1068
  /**
1605
- * Converts a Schema AST into a {@link Document}.
1069
+ * Decodes a persisted single-root representation document from JSON.
1606
1070
  *
1607
1071
  * **When to use**
1608
1072
  *
1609
- * Use when you have a single Schema AST and need a schema representation
1610
- * document.
1611
- *
1612
- * **Details**
1613
- *
1614
- * Shared/recursive sub-schemas are extracted into the `references` map.
1615
- *
1616
- * **Example** (Converting a Schema to a Document)
1073
+ * Use when reading a representation document from storage or transport before inspecting it or passing it to `fromRepresentation`.
1617
1074
  *
1618
- * ```ts
1619
- * import { Schema, SchemaRepresentation } from "effect"
1620
- *
1621
- * const Person = Schema.Struct({
1622
- * name: Schema.String,
1623
- * age: Schema.Number
1624
- * })
1075
+ * **Gotchas**
1625
1076
  *
1626
- * const doc = SchemaRepresentation.fromAST(Person.ast)
1627
- * console.log(doc.representation._tag)
1628
- * // "Objects"
1629
- * ```
1077
+ * Invalid documents throw a schema decoding error. Decoding does not reconstruct runtime callbacks.
1630
1078
  *
1631
- * @see {@link Document}
1632
- * @see {@link fromASTs}
1079
+ * @see {@link toJson} for encoding a document
1080
+ * @see {@link fromRepresentation} for reconstructing a runtime schema
1081
+ * @see {@link fromJsonMultiDocument} for multiple roots sharing references
1633
1082
  *
1634
- * @category constructors
1083
+ * @category decoding
1635
1084
  * @since 4.0.0
1636
1085
  */
1637
- export const fromAST: (ast: SchemaAST.AST) => Document = InternalRepresentation.fromAST
1086
+ export function fromJson(input: Schema.Json): Document {
1087
+ return decodeDocument(input)
1088
+ }
1638
1089
 
1639
1090
  /**
1640
- * Converts one or more Schema ASTs into a {@link MultiDocument}.
1091
+ * Decodes a persisted multi-root representation document from JSON.
1641
1092
  *
1642
1093
  * **When to use**
1643
1094
  *
1644
- * Use when you have multiple Schema ASTs and need one schema representation
1645
- * `MultiDocument` with shared references.
1095
+ * Use when reading multiple representation roots that share references before inspecting them or passing them to `fromRepresentations`.
1646
1096
  *
1647
- * **Details**
1097
+ * **Gotchas**
1648
1098
  *
1649
- * All schemas share a single `references` map.
1099
+ * Invalid documents throw a schema decoding error. Decoding does not reconstruct runtime callbacks.
1650
1100
  *
1651
- * @see {@link MultiDocument}
1652
- * @see {@link fromAST}
1101
+ * @see {@link toJsonMultiDocument} for encoding a multi-document
1102
+ * @see {@link fromRepresentations} for reconstructing runtime schemas
1103
+ * @see {@link fromJson} for a single root
1653
1104
  *
1654
- * @category constructors
1105
+ * @category decoding
1655
1106
  * @since 4.0.0
1656
1107
  */
1657
- export const fromASTs: (asts: readonly [SchemaAST.AST, ...Array<SchemaAST.AST>]) => MultiDocument =
1658
- InternalRepresentation.fromASTs
1108
+ export function fromJsonMultiDocument(input: Schema.Json): MultiDocument {
1109
+ return decodeMultiDocument(input)
1110
+ }
1659
1111
 
1660
1112
  /**
1661
- * Schema that decodes a {@link Document} from JSON and encodes it back.
1113
+ * Reconstructs a runtime schema from a representation document.
1662
1114
  *
1663
1115
  * **When to use**
1664
1116
  *
1665
- * Use when you need a JSON codec for schema representation documents with
1666
- * `Schema.decodeUnknownSync` or `Schema.encodeSync`.
1117
+ * Use when you have decoded or constructed a document whose declaration and check annotations may require revivers.
1667
1118
  *
1668
- * **Example** (Round-tripping a Document through JSON)
1669
- *
1670
- * ```ts
1671
- * import { Schema, SchemaRepresentation } from "effect"
1119
+ * **Gotchas**
1672
1120
  *
1673
- * const doc = SchemaRepresentation.fromAST(Schema.String.ast)
1674
- * const json = Schema.encodeSync(SchemaRepresentation.DocumentFromJson)(doc)
1675
- * const back = Schema.decodeUnknownSync(SchemaRepresentation.DocumentFromJson)(json)
1676
- * ```
1121
+ * Revivers are resolved locally by `id`; none are installed implicitly. Reviver results are used directly, and exceptions raised by a reviver pass through unchanged.
1677
1122
  *
1678
- * @see {@link $Document}
1679
- * @see {@link MultiDocumentFromJson}
1123
+ * @see {@link fromJson} for decoding a persisted document
1124
+ * @see {@link fromRepresentations} for multiple roots sharing references
1680
1125
  *
1681
- * @category schemas
1126
+ * @category transforming
1682
1127
  * @since 4.0.0
1683
1128
  */
1684
- export const DocumentFromJson: Schema.Codec<Document, Schema.Json> = Schema.toCodecJson($Document)
1129
+ export function fromRepresentation(
1130
+ document: Document,
1131
+ options: { readonly revivers: ReadonlyArray<AnyReviver> }
1132
+ ): Schema.Top {
1133
+ return InternalFromRepresentation.fromRepresentation(document, options.revivers)
1134
+ }
1685
1135
 
1686
1136
  /**
1687
- * Schema for `MultiDocument` values encoded as JSON.
1137
+ * Reconstructs multiple runtime schemas and their shared definitions from a representation multi-document.
1688
1138
  *
1689
- * @see {@link $MultiDocument}
1690
- * @see {@link DocumentFromJson}
1139
+ * **When to use**
1691
1140
  *
1692
- * @category schemas
1693
- * @since 4.0.0
1694
- */
1695
- export const MultiDocumentFromJson: Schema.Codec<MultiDocument, Schema.Json> = Schema.toCodecJson($MultiDocument)
1696
-
1697
- /**
1698
- * Wraps a single {@link Document} as a {@link MultiDocument} with one
1699
- * representation.
1141
+ * Use when every root and named definition must be rebuilt in one shared reference environment.
1700
1142
  *
1701
- * **When to use**
1143
+ * **Gotchas**
1702
1144
  *
1703
- * Use when you need to pass a single schema representation `Document` where an
1704
- * API expects a `MultiDocument`.
1145
+ * Every definition is revived, including definitions not reachable from a root. Revivers are resolved locally by `id`; none are installed implicitly.
1705
1146
  *
1706
- * @see {@link Document}
1707
- * @see {@link MultiDocument}
1147
+ * @see {@link fromJsonMultiDocument} for decoding a persisted multi-document
1148
+ * @see {@link fromRepresentation} for a single root
1708
1149
  *
1709
1150
  * @category transforming
1710
1151
  * @since 4.0.0
1711
1152
  */
1712
- export function toMultiDocument(document: Document): MultiDocument {
1713
- return {
1714
- representations: [document.representation],
1715
- references: document.references
1716
- }
1153
+ export function fromRepresentations(
1154
+ document: MultiDocument,
1155
+ options: { readonly revivers: ReadonlyArray<AnyReviver> }
1156
+ ): SchemaMultiDocument {
1157
+ return InternalFromRepresentation.fromRepresentations(document, options.revivers)
1717
1158
  }
1718
1159
 
1719
1160
  /**
1720
- * A callback that handles {@link Declaration} nodes during reconstruction
1721
- * ({@link toSchema}) or code generation ({@link toCodeDocument}).
1161
+ * Imports a JSON Schema Draft 2020-12 document as a runtime schema.
1722
1162
  *
1723
- * **Details**
1163
+ * **When to use**
1724
1164
  *
1725
- * Return a value to handle the declaration. Return `undefined` to fall back to
1726
- * default behavior, which uses `encodedSchema` for `toSchema` or the
1727
- * `generation` annotation for `toCodeDocument`. `recur` processes child
1728
- * representations recursively.
1165
+ * Use when you need to validate or transform values described by an external JSON Schema document.
1729
1166
  *
1730
- * @see {@link toSchema}
1731
- * @see {@link toSchemaDefaultReviver}
1732
- * @see {@link toCodeDocument}
1167
+ * **Gotchas**
1733
1168
  *
1734
- * @category models
1735
- * @since 4.0.0
1736
- */
1737
- export type Reviver<T> = (declaration: Declaration, recur: (representation: Representation) => T) => T | undefined
1738
-
1739
- /**
1740
- * Default {@link Reviver} for {@link toSchema} that handles built-in Effect
1741
- * types, including Option, Result, Redacted, Cause, Exit, ReadonlyMap, HashMap,
1742
- * ReadonlySet, Date, Duration, URL, and RegExp.
1743
- *
1744
- * **When to use**
1745
- *
1746
- * Use when you need the default `options.reviver` for {@link toSchema} to
1747
- * reconstruct runtime schemas for built-in Effect declarations.
1748
- *
1749
- * **Details**
1750
- *
1751
- * The reviver returns `undefined` for unrecognized declarations, causing
1752
- * fallback to `encodedSchema`.
1753
- *
1754
- * @see {@link toSchema}
1755
- * @see {@link Reviver}
1756
- *
1757
- * @category transforming
1758
- * @since 4.0.0
1759
- */
1760
- export const toSchemaDefaultReviver: Reviver<Schema.Top> = (s, recur) => {
1761
- const typeConstructor = s.annotations?.typeConstructor
1762
- if (Predicate.isObject(typeConstructor) && typeof typeConstructor._tag === "string") {
1763
- const typeParameters = s.typeParameters.map(recur)
1764
- switch (typeConstructor._tag) {
1765
- // built-in types
1766
- case "Date":
1767
- return Schema.Date
1768
- case "Error":
1769
- return Schema.Error(typeConstructor.options as Schema.ErrorOptions | undefined)
1770
- case "File":
1771
- return Schema.File
1772
- case "FormData":
1773
- return Schema.FormData
1774
- case "ReadonlyMap":
1775
- return Schema.ReadonlyMap(typeParameters[0], typeParameters[1])
1776
- case "ReadonlySet":
1777
- return Schema.ReadonlySet(typeParameters[0])
1778
- case "RegExp":
1779
- return Schema.RegExp
1780
- case "Uint8Array":
1781
- return Schema.Uint8Array
1782
- case "URL":
1783
- return Schema.URL
1784
- case "URLSearchParams":
1785
- return Schema.URLSearchParams
1786
- // effect types
1787
- case "effect/Option":
1788
- return Schema.Option(typeParameters[0])
1789
- case "effect/Result":
1790
- return Schema.Result(typeParameters[0], typeParameters[1])
1791
- case "effect/Redacted":
1792
- return Schema.Redacted(typeParameters[0], typeConstructor.options as any)
1793
- case "effect/DateTime.TimeZone":
1794
- return Schema.TimeZone
1795
- case "effect/DateTime.TimeZone.Named":
1796
- return Schema.TimeZoneNamed
1797
- case "effect/DateTime.TimeZone.Offset":
1798
- return Schema.TimeZoneOffset
1799
- case "effect/DateTime.Utc":
1800
- return Schema.DateTimeUtc
1801
- case "effect/DateTime.Zoned":
1802
- return Schema.DateTimeZoned
1803
- case "effect/BigDecimal":
1804
- return Schema.BigDecimal
1805
- case "effect/Chunk":
1806
- return Schema.Chunk(typeParameters[0])
1807
- case "effect/Cause":
1808
- return Schema.Cause(typeParameters[0], typeParameters[1])
1809
- case "effect/Cause/Failure":
1810
- return Schema.CauseReason(typeParameters[0], typeParameters[1])
1811
- case "effect/Duration":
1812
- return Schema.Duration
1813
- case "effect/Exit":
1814
- return Schema.Exit(typeParameters[0], typeParameters[1], typeParameters[2])
1815
- case "effect/Json":
1816
- return Schema.Json
1817
- case "effect/MutableJson":
1818
- return Schema.MutableJson
1819
- case "effect/HashMap":
1820
- return Schema.HashMap(typeParameters[0], typeParameters[1])
1821
- case "effect/HashSet":
1822
- return Schema.HashSet(typeParameters[0])
1823
- }
1824
- }
1825
- }
1826
-
1827
- /**
1828
- * Creates a runtime Schema from a {@link Document}.
1829
- *
1830
- * **When to use**
1831
- *
1832
- * Use when you have a serialized or computed schema representation document and
1833
- * need a runtime Schema for decoding/encoding.
1834
- *
1835
- * **Details**
1836
- *
1837
- * Pass `options.reviver`, such as {@link toSchemaDefaultReviver}, to handle
1838
- * {@link Declaration} nodes for types like `Date` and `Option`. Without a
1839
- * reviver, declarations fall back to their `encodedSchema`. Circular references
1840
- * are handled via lazy `Schema.suspend`.
1841
- *
1842
- * **Gotchas**
1843
- *
1844
- * This throws if a `$ref` is not found in `document.references`.
1169
+ * Import is best-effort. Built-in declarations and checks are reconstructed with importer-owned revivers. Callback results are used directly, and exceptions raised by a callback pass through unchanged.
1845
1170
  *
1846
- * **Example** (Reconstructing a Schema)
1847
- *
1848
- * ```ts
1849
- * import { Schema, SchemaRepresentation } from "effect"
1850
- *
1851
- * const doc = SchemaRepresentation.fromAST(
1852
- * Schema.Struct({ name: Schema.String }).ast
1853
- * )
1854
- *
1855
- * const schema = SchemaRepresentation.toSchema(doc)
1856
- * console.log(JSON.stringify(Schema.toJsonSchemaDocument(schema), null, 2))
1857
- * ```
1858
- *
1859
- * @see {@link Document}
1860
- * @see {@link Reviver}
1861
- * @see {@link toSchemaDefaultReviver}
1862
- *
1863
- * @category Runtime Generation
1864
- * @since 4.0.0
1865
- */
1866
- export function toSchema<S extends Schema.Top = Schema.Top>(document: Document, options?: {
1867
- readonly reviver?: Reviver<Schema.Top> | undefined
1868
- }): S {
1869
- type Slot = {
1870
- // 0 = not started, 1 = building, 2 = done
1871
- state: 0 | 1 | 2
1872
- value: Schema.Top | undefined
1873
- ref: Schema.Top
1874
- }
1875
-
1876
- const slots = new Map<string, Slot>()
1877
-
1878
- return recur(document.representation) as S
1879
-
1880
- function recur(r: Representation): Schema.Top {
1881
- let out = on(r)
1882
- if ("annotations" in r && r.annotations) out = out.annotate(r.annotations)
1883
- out = toSchemaChecks(out, r)
1884
- return out
1885
- }
1886
-
1887
- function getSlot(identifier: string): Slot {
1888
- const existing = slots.get(identifier)
1889
- if (existing) return existing
1890
-
1891
- // Create the slot *before* resolving, so self-references can see it.
1892
- const slot: Slot = {
1893
- state: 0,
1894
- value: undefined,
1895
- ref: Schema.suspend(() => {
1896
- if (slot.value === undefined) {
1897
- return Schema.Unknown
1898
- }
1899
- return slot.value
1900
- })
1901
- }
1902
- slots.set(identifier, slot)
1903
- return slot
1904
- }
1905
-
1906
- function resolveReference($ref: string): Schema.Top {
1907
- const definition = document.references[$ref]
1908
- if (definition === undefined) {
1909
- throw new Error(`Reference ${$ref} not found`)
1910
- }
1911
-
1912
- const slot = getSlot($ref)
1913
-
1914
- if (slot.state === 2) {
1915
- // Already built: return the built schema directly
1916
- return slot.value!
1917
- }
1918
-
1919
- if (slot.state === 1) {
1920
- // Circular: we're currently building this identifier.
1921
- return slot.ref
1922
- }
1923
-
1924
- // First time: build it.
1925
- slot.state = 1
1926
- try {
1927
- slot.value = recur(definition)
1928
- slot.state = 2
1929
- return slot.value
1930
- } catch (e) {
1931
- // Leave the slot in a safe state so future thunks don't silently succeed.
1932
- slot.state = 0
1933
- slot.value = undefined
1934
- throw e
1935
- }
1936
- }
1937
-
1938
- function on(r: Representation): Schema.Top {
1939
- switch (r._tag) {
1940
- case "Declaration":
1941
- return options?.reviver?.(r, recur) ?? recur(r.encodedSchema)
1942
- case "Reference":
1943
- return resolveReference(r.$ref)
1944
- case "Suspend":
1945
- return recur(r.thunk)
1946
- case "Null":
1947
- return Schema.Null
1948
- case "Undefined":
1949
- return Schema.Undefined
1950
- case "Void":
1951
- return Schema.Void
1952
- case "Never":
1953
- return Schema.Never
1954
- case "Unknown":
1955
- return Schema.Unknown
1956
- case "Any":
1957
- return Schema.Any
1958
- case "String": {
1959
- const contentMediaType = r.contentMediaType
1960
- const contentSchema = r.contentSchema
1961
- if (contentMediaType === "application/json" && contentSchema !== undefined) {
1962
- return Schema.fromJsonString(recur(contentSchema))
1963
- }
1964
- return Schema.String
1965
- }
1966
- case "Number":
1967
- return Schema.Number
1968
- case "Boolean":
1969
- return Schema.Boolean
1970
- case "BigInt":
1971
- return Schema.BigInt
1972
- case "Symbol":
1973
- return Schema.Symbol
1974
- case "Literal":
1975
- return Schema.Literal(r.literal)
1976
- case "UniqueSymbol":
1977
- return Schema.UniqueSymbol(r.symbol)
1978
- case "ObjectKeyword":
1979
- return Schema.ObjectKeyword
1980
- case "Enum":
1981
- return Schema.Enum(Object.fromEntries(r.enums))
1982
- case "TemplateLiteral": {
1983
- const parts = r.parts.map(recur) as Schema.TemplateLiteral.Parts
1984
- return Schema.TemplateLiteral(parts)
1985
- }
1986
- case "Arrays": {
1987
- const elements = r.elements.map((e) => {
1988
- const s = recur(e.type)
1989
- return e.isOptional ? Schema.optionalKey(s) : s
1990
- })
1991
- const rest = r.rest.map(recur)
1992
- if (Arr.isArrayNonEmpty(rest)) {
1993
- if (r.elements.length === 0 && r.rest.length === 1) {
1994
- return Schema.Array(rest[0])
1995
- }
1996
- return Schema.TupleWithRest(Schema.Tuple(elements), rest)
1997
- }
1998
- return Schema.Tuple(elements)
1999
- }
2000
- case "Objects": {
2001
- const fields: Record<PropertyKey, Schema.Top> = {}
2002
-
2003
- for (const ps of r.propertySignatures) {
2004
- const s = recur(ps.type)
2005
- const withOptional = ps.isOptional ? Schema.optionalKey(s) : s
2006
- fields[ps.name] = ps.isMutable ? Schema.mutableKey(withOptional) : withOptional
2007
- }
2008
-
2009
- const indexSignatures = r.indexSignatures.map((is) =>
2010
- Schema.Record(recur(is.parameter) as Schema.Record.Key, recur(is.type))
2011
- )
2012
-
2013
- if (Arr.isArrayNonEmpty(indexSignatures)) {
2014
- if (r.propertySignatures.length === 0 && indexSignatures.length === 1) {
2015
- return indexSignatures[0]
2016
- }
2017
- return Schema.StructWithRest(Schema.Struct(fields), indexSignatures)
2018
- }
2019
-
2020
- return Schema.Struct(fields)
2021
- }
2022
- case "Union": {
2023
- if (r.types.length === 0) return Schema.Never
2024
- if (r.types.every((t) => t._tag === "Literal")) {
2025
- if (r.types.length === 1) {
2026
- return Schema.Literal(r.types[0].literal)
2027
- }
2028
- return Schema.Literals(r.types.map((t) => t.literal))
2029
- }
2030
- return Schema.Union(r.types.map(recur), { mode: r.mode })
2031
- }
2032
- }
2033
- }
2034
-
2035
- function toSchemaChecks(top: Schema.Top, schema: Representation): Schema.Top {
2036
- switch (schema._tag) {
2037
- default:
2038
- return top
2039
- case "String":
2040
- case "Number":
2041
- case "BigInt":
2042
- case "Arrays":
2043
- case "Objects":
2044
- case "Declaration": {
2045
- const checks = schema.checks.map(toSchemaCheck)
2046
- return Arr.isArrayNonEmpty(checks) ? top.check(...checks) : top
2047
- }
2048
- }
2049
- }
2050
-
2051
- function toSchemaCheck(check: Check<Meta>): SchemaAST.Check<any> {
2052
- switch (check._tag) {
2053
- case "Filter":
2054
- return toSchemaFilter(check)
2055
- case "FilterGroup": {
2056
- return Schema.makeFilterGroup(Arr.map(check.checks, toSchemaCheck), check.annotations)
2057
- }
2058
- }
2059
- }
2060
-
2061
- function toSchemaFilter(filter: Filter<Meta>): SchemaAST.Check<any> {
2062
- const a = filter.annotations
2063
- switch (filter.meta._tag) {
2064
- // String Meta
2065
- case "isStringFinite":
2066
- return Schema.isStringFinite(a)
2067
- case "isStringBigInt":
2068
- return Schema.isStringBigInt(a)
2069
- case "isStringSymbol":
2070
- return Schema.isStringSymbol(a)
2071
- case "isMinLength":
2072
- return Schema.isMinLength(filter.meta.minLength, a)
2073
- case "isMaxLength":
2074
- return Schema.isMaxLength(filter.meta.maxLength, a)
2075
- case "isLengthBetween":
2076
- return Schema.isLengthBetween(filter.meta.minimum, filter.meta.maximum, a)
2077
- case "isPattern":
2078
- return Schema.isPattern(filter.meta.regExp, a)
2079
- case "isTrimmed":
2080
- return Schema.isTrimmed(a)
2081
- case "isUUID":
2082
- return Schema.isUUID(filter.meta.version, a)
2083
- case "isGUID":
2084
- return Schema.isGUID(a)
2085
- case "isULID":
2086
- return Schema.isULID(a)
2087
- case "isBase64":
2088
- return Schema.isBase64(a)
2089
- case "isBase64Url":
2090
- return Schema.isBase64Url(a)
2091
- case "isStartsWith":
2092
- return Schema.isStartsWith(filter.meta.startsWith, a)
2093
- case "isEndsWith":
2094
- return Schema.isEndsWith(filter.meta.endsWith, a)
2095
- case "isIncludes":
2096
- return Schema.isIncludes(filter.meta.includes, a)
2097
- case "isUppercased":
2098
- return Schema.isUppercased(a)
2099
- case "isLowercased":
2100
- return Schema.isLowercased(a)
2101
- case "isCapitalized":
2102
- return Schema.isCapitalized(a)
2103
- case "isUncapitalized":
2104
- return Schema.isUncapitalized(a)
2105
-
2106
- // Number Meta
2107
- case "isFinite":
2108
- return Schema.isFinite(a)
2109
- case "isInt":
2110
- return Schema.isInt(a)
2111
- case "isMultipleOf":
2112
- return Schema.isMultipleOf(filter.meta.divisor, a)
2113
- case "isGreaterThan":
2114
- return Schema.isGreaterThan(filter.meta.exclusiveMinimum, a)
2115
- case "isGreaterThanOrEqualTo":
2116
- return Schema.isGreaterThanOrEqualTo(filter.meta.minimum, a)
2117
- case "isLessThan":
2118
- return Schema.isLessThan(filter.meta.exclusiveMaximum, a)
2119
- case "isLessThanOrEqualTo":
2120
- return Schema.isLessThanOrEqualTo(filter.meta.maximum, a)
2121
- case "isBetween":
2122
- return Schema.isBetween(filter.meta, a)
2123
-
2124
- // BigInt Meta
2125
- case "isGreaterThanBigInt":
2126
- return Schema.isGreaterThanBigInt(filter.meta.exclusiveMinimum, a)
2127
- case "isGreaterThanOrEqualToBigInt":
2128
- return Schema.isGreaterThanOrEqualToBigInt(filter.meta.minimum, a)
2129
- case "isLessThanBigInt":
2130
- return Schema.isLessThanBigInt(filter.meta.exclusiveMaximum, a)
2131
- case "isLessThanOrEqualToBigInt":
2132
- return Schema.isLessThanOrEqualToBigInt(filter.meta.maximum, a)
2133
- case "isBetweenBigInt":
2134
- return Schema.isBetweenBigInt(filter.meta, a)
2135
-
2136
- // Object Meta
2137
- case "isMinProperties":
2138
- return Schema.isMinProperties(filter.meta.minProperties, a)
2139
- case "isMaxProperties":
2140
- return Schema.isMaxProperties(filter.meta.maxProperties, a)
2141
- case "isPropertiesLengthBetween":
2142
- return Schema.isPropertiesLengthBetween(filter.meta.minimum, filter.meta.maximum, a)
2143
- case "isPropertyNames":
2144
- return Schema.isPropertyNames(recur(filter.meta.propertyNames) as Schema.Record.Key, a)
2145
-
2146
- // Arrays Meta
2147
- case "isUnique":
2148
- return Schema.isUnique(a)
2149
-
2150
- // Date Meta
2151
- case "isDateValid":
2152
- return Schema.isDateValid(a)
2153
- case "isGreaterThanDate":
2154
- return Schema.isGreaterThanDate(filter.meta.exclusiveMinimum, a)
2155
- case "isGreaterThanOrEqualToDate":
2156
- return Schema.isGreaterThanOrEqualToDate(filter.meta.minimum, a)
2157
- case "isLessThanDate":
2158
- return Schema.isLessThanDate(filter.meta.exclusiveMaximum, a)
2159
- case "isLessThanOrEqualToDate":
2160
- return Schema.isLessThanOrEqualToDate(filter.meta.maximum, a)
2161
- case "isBetweenDate":
2162
- return Schema.isBetweenDate(filter.meta, a)
2163
-
2164
- // Size Meta
2165
- case "isMinSize":
2166
- return Schema.isMinSize(filter.meta.minSize, a)
2167
- case "isMaxSize":
2168
- return Schema.isMaxSize(filter.meta.maxSize, a)
2169
- case "isSizeBetween":
2170
- return Schema.isSizeBetween(filter.meta.minimum, filter.meta.maximum, a)
2171
- }
2172
- }
2173
- }
2174
-
2175
- /**
2176
- * Converts a {@link Document} to a Draft 2020-12 JSON Schema document.
2177
- *
2178
- * **When to use**
2179
- *
2180
- * Use when you need to produce a standard JSON Schema document from a schema
2181
- * representation `Document`.
2182
- *
2183
- * **Gotchas**
2184
- *
2185
- * JSON Schema generation is best-effort. Some Effect schema representation
2186
- * semantics cannot be represented exactly in JSON Schema, and importing an
2187
- * emitted JSON Schema may produce an equivalent approximation rather than the
2188
- * original representation shape.
2189
- *
2190
- * **Example** (Generating JSON Schema)
2191
- *
2192
- * ```ts
2193
- * import { Schema, SchemaRepresentation } from "effect"
2194
- *
2195
- * const doc = SchemaRepresentation.fromAST(Schema.String.ast)
2196
- * const jsonSchema = SchemaRepresentation.toJsonSchemaDocument(doc)
2197
- * console.log(jsonSchema.schema.type)
2198
- * // "string"
2199
- * ```
2200
- *
2201
- * @see {@link Document}
2202
- * @see {@link toJsonSchemaMultiDocument}
2203
- * @see {@link fromJsonSchemaDocument}
2204
- *
2205
- * @category transforming
2206
- * @since 4.0.0
2207
- */
2208
- export const toJsonSchemaDocument: (
2209
- document: Document,
2210
- options?: Schema.ToJsonSchemaOptions
2211
- ) => JsonSchema.Document<"draft-2020-12"> = InternalRepresentation.toJsonSchemaDocument
2212
-
2213
- /**
2214
- * Converts a {@link MultiDocument} to a Draft 2020-12 JSON Schema
2215
- * multi-document.
2216
- *
2217
- * **When to use**
2218
- *
2219
- * Use when you need to export related schema representation documents together
2220
- * so shared definitions stay in multi-document JSON Schema form.
2221
- *
2222
- * **Gotchas**
2223
- *
2224
- * JSON Schema generation is best-effort. Some Effect schema representation
2225
- * semantics cannot be represented exactly in JSON Schema, and importing an
2226
- * emitted JSON Schema may produce equivalent approximations rather than the
2227
- * original representation shapes.
2228
- *
2229
- * @see {@link MultiDocument}
2230
- * @see {@link toJsonSchemaDocument}
2231
- * @see {@link fromJsonSchemaMultiDocument}
2232
- *
2233
- * @category transforming
2234
- * @since 4.0.0
2235
- */
2236
- export const toJsonSchemaMultiDocument: (
2237
- document: MultiDocument,
2238
- options?: Schema.ToJsonSchemaOptions
2239
- ) => JsonSchema.MultiDocument<"draft-2020-12"> = InternalRepresentation.toJsonSchemaMultiDocument
2240
-
2241
- /**
2242
- * A pair of TypeScript source strings for a schema: `runtime` is the
2243
- * executable Schema expression, `Type` is the corresponding TypeScript type.
2244
- *
2245
- * @see {@link makeCode}
2246
- * @see {@link CodeDocument}
2247
- *
2248
- * @category Code Generation
2249
- * @since 4.0.0
2250
- */
2251
- export type Code = {
2252
- readonly runtime: string
2253
- readonly Type: string
2254
- }
2255
-
2256
- /**
2257
- * Constructs a {@link Code} value from a runtime expression string and a
2258
- * TypeScript type string.
2259
- *
2260
- * @see {@link Code}
2261
- *
2262
- * @category Code Generation
2263
- * @since 4.0.0
2264
- */
2265
- export function makeCode(runtime: string, Type: string): Code {
2266
- return { runtime, Type }
2267
- }
2268
-
2269
- /**
2270
- * An auxiliary code artifact produced during code generation — a symbol
2271
- * declaration, an enum declaration, or an import statement.
2272
- *
2273
- * @see {@link CodeDocument}
2274
- * @see {@link toCodeDocument}
2275
- *
2276
- * @category Code Generation
2277
- * @since 4.0.0
2278
- */
2279
- export type Artifact =
2280
- | {
2281
- readonly _tag: "Symbol"
2282
- readonly identifier: string
2283
- readonly generation: Code
2284
- }
2285
- | {
2286
- readonly _tag: "Enum"
2287
- readonly identifier: string
2288
- readonly generation: Code
2289
- }
2290
- | {
2291
- readonly _tag: "Import"
2292
- readonly importDeclaration: string
2293
- }
2294
-
2295
- /**
2296
- * The output of {@link toCodeDocument}: generated TypeScript code for one or
2297
- * more schemas plus their shared references and auxiliary artifacts.
2298
- *
2299
- * **Details**
2300
- *
2301
- * `codes` contains one {@link Code} per input representation.
2302
- * `references.nonRecursives` contains topologically sorted non-recursive
2303
- * definitions. `references.recursives` contains definitions involved in cycles.
2304
- * `artifacts` contains symbols, enums, and import statements needed by the
2305
- * code.
2306
- *
2307
- * @see {@link toCodeDocument}
2308
- * @see {@link Code}
2309
- * @see {@link Artifact}
2310
- *
2311
- * @category Code Generation
2312
- * @since 4.0.0
2313
- */
2314
- export type CodeDocument = {
2315
- readonly codes: ReadonlyArray<Code>
2316
- readonly references: {
2317
- readonly nonRecursives: ReadonlyArray<{
2318
- readonly $ref: string
2319
- readonly code: Code
2320
- }>
2321
- readonly recursives: {
2322
- readonly [$ref: string]: Code
2323
- }
2324
- }
2325
- readonly artifacts: ReadonlyArray<Artifact>
2326
- }
2327
-
2328
- /**
2329
- * Generates TypeScript code strings from a {@link MultiDocument}.
2330
- *
2331
- * **When to use**
2332
- *
2333
- * Use when you need to produce source code for Effect Schema definitions from a
2334
- * schema representation `MultiDocument`.
2335
- *
2336
- * **Details**
2337
- *
2338
- * `options.reviver` can customize code generation for {@link Declaration}
2339
- * nodes. Return `undefined` to fall back to the default logic, which uses
2340
- * `generation` annotations or the encoded schema. References are
2341
- * topologically sorted so non-recursive definitions are emitted before their
2342
- * dependents. `$ref` keys are converted to sanitized JavaScript identifiers.
2343
- *
2344
- * **Example** (Generating TypeScript code)
2345
- *
2346
- * ```ts
2347
- * import { Schema, SchemaRepresentation } from "effect"
2348
- *
2349
- * const Person = Schema.Struct({
2350
- * name: Schema.String,
2351
- * age: Schema.Int
2352
- * })
2353
- *
2354
- * const multi = SchemaRepresentation.toMultiDocument(
2355
- * SchemaRepresentation.fromAST(Person.ast)
2356
- * )
2357
- * const codeDoc = SchemaRepresentation.toCodeDocument(multi)
2358
- * console.log(codeDoc.codes[0].runtime)
2359
- * // Schema.Struct({ ... })
2360
- * ```
2361
- *
2362
- * @see {@link CodeDocument}
2363
- * @see {@link MultiDocument}
2364
- * @see {@link Reviver}
2365
- *
2366
- * @category Code Generation
2367
- * @since 4.0.0
2368
- */
2369
- export function toCodeDocument(multiDocument: MultiDocument, options?: {
2370
- /**
2371
- * The reviver can return `undefined` to indicate that the generation should be generated by the default logic
2372
- */
2373
- readonly reviver?: Reviver<Code> | undefined
2374
- }): CodeDocument {
2375
- const artifacts: Array<Artifact> = []
2376
-
2377
- const ts = topologicalSort(multiDocument.references)
2378
-
2379
- // Phase 1: Build sanitization map with collision handling
2380
- const sanitizedReferenceMap = new Map<string, string>()
2381
- const uniqueSanitizedReferences = new Set<string>()
2382
- const referenceCount = new Map<string, number>()
2383
-
2384
- // Process all references first to build the map
2385
- const allRefs = [
2386
- ...ts.nonRecursives.map(({ $ref }) => $ref),
2387
- ...Object.keys(ts.recursives)
2388
- ]
2389
-
2390
- for (const ref of allRefs) {
2391
- ensureUniqueSanitized(ref)
2392
- }
2393
-
2394
- // Phase 2: Use the map when processing references
2395
- const nonRecursives = ts.nonRecursives.map(({ $ref, representation }) => ({
2396
- $ref: sanitizedReferenceMap.get($ref)!,
2397
- code: recur(representation)
2398
- }))
2399
- const recursives = Rec.mapEntries(ts.recursives, (representation, $ref) => [
2400
- sanitizedReferenceMap.get($ref)!,
2401
- recur(representation)
2402
- ])
2403
-
2404
- const codes = multiDocument.representations.map(recur)
2405
-
2406
- return {
2407
- codes,
2408
- references: {
2409
- nonRecursives: nonRecursives.filter(({ $ref }) => (referenceCount.get($ref) ?? 0) > 0),
2410
- recursives: Rec.filter(recursives, (_, $ref) => (referenceCount.get($ref) ?? 0) > 0)
2411
- },
2412
- artifacts
2413
- }
2414
-
2415
- function ensureUniqueSanitized(originalRef: string): string {
2416
- // Check if already mapped (consistency)
2417
- const sanitized = sanitizedReferenceMap.get(originalRef)
2418
- if (sanitized !== undefined) {
2419
- return sanitized
2420
- }
2421
-
2422
- // Find unique sanitized name
2423
- const seed = sanitizeJavaScriptIdentifier(originalRef)
2424
- let candidate = seed
2425
- let suffix = 0
2426
-
2427
- while (uniqueSanitizedReferences.has(candidate)) {
2428
- candidate = `${seed}${++suffix}`
2429
- }
2430
-
2431
- uniqueSanitizedReferences.add(candidate)
2432
- sanitizedReferenceMap.set(originalRef, candidate)
2433
- return candidate
2434
- }
2435
-
2436
- function addSymbol(s: symbol): string {
2437
- const identifier = ensureUniqueSanitized("_symbol")
2438
- const key = globalThis.Symbol.keyFor(s)
2439
- const description = s.description
2440
- const generation = key === undefined
2441
- ? makeCode(`Symbol(${description === undefined ? "" : format(description)})`, `typeof ${identifier}`)
2442
- : makeCode(`Symbol.for(${format(key)})`, `typeof ${identifier}`)
2443
- artifacts.push({ _tag: "Symbol", identifier, generation })
2444
- return identifier
2445
- }
2446
-
2447
- function addEnum(s: Enum): string {
2448
- const identifier = ensureUniqueSanitized("_Enum")
2449
- artifacts.push({
2450
- _tag: "Enum",
2451
- identifier,
2452
- generation: makeCode(
2453
- `enum ${identifier} { ${s.enums.map(([name, value]) => `${format(name)}: ${format(value)}`).join(", ")} }`,
2454
- `typeof ${identifier}`
2455
- )
2456
- })
2457
- return identifier
2458
- }
2459
-
2460
- function addImport(importDeclaration: string) {
2461
- if (!artifacts.some((a) => a._tag === "Import" && a.importDeclaration === importDeclaration)) {
2462
- artifacts.push({ _tag: "Import", importDeclaration })
2463
- }
2464
- }
2465
-
2466
- function recur(s: Representation): Code {
2467
- const g = on(s)
2468
- switch (s._tag) {
2469
- default:
2470
- return makeCode(
2471
- g.runtime + toRuntimeAnnotate(s.annotations) + toRuntimeBrand(s.annotations),
2472
- g.Type + toTypeBrand(s.annotations)
2473
- )
2474
- case "Reference":
2475
- return g
2476
- case "Declaration":
2477
- case "String":
2478
- case "Number":
2479
- case "BigInt":
2480
- case "Arrays":
2481
- case "Objects":
2482
- case "Suspend":
2483
- return makeCode(
2484
- g.runtime + toRuntimeAnnotate(s.annotations) + toRuntimeBrand(s.annotations) + toRuntimeChecks(s.checks),
2485
- g.Type + toTypeBrand(s.annotations) + toTypeChecks(s.checks)
2486
- )
2487
- }
2488
- }
2489
-
2490
- function on(s: Representation): Code {
2491
- switch (s._tag) {
2492
- case "Declaration": {
2493
- // if there is a reviver, use it to generate the generation
2494
- if (options?.reviver !== undefined) {
2495
- // the reviver can return `undefined` to indicate that the generation should be generated by the default logic
2496
- const out = options.reviver(s, recur)
2497
- if (out !== undefined) {
2498
- return out
2499
- }
2500
- }
2501
- // otherwise, use the generation from the annotations
2502
- const generation = s.annotations?.generation
2503
- if (
2504
- Predicate.isObject(generation) && typeof generation.runtime === "string" &&
2505
- typeof generation.Type === "string"
2506
- ) {
2507
- const typeParameters = s.typeParameters.map(recur)
2508
- if (typeof generation.importDeclaration === "string") {
2509
- addImport(generation.importDeclaration)
2510
- }
2511
- return makeCode(
2512
- replacePlaceholders(generation.runtime, typeParameters.map((p) => p.runtime)),
2513
- replacePlaceholders(generation.Type, typeParameters.map((p) => p.Type))
2514
- )
2515
- }
2516
- // otherwise, use the generation from the encoded schema
2517
- return recur(s.encodedSchema)
2518
- }
2519
- case "Reference": {
2520
- const sanitized = ensureUniqueSanitized(s.$ref)
2521
- referenceCount.set(sanitized, (referenceCount.get(sanitized) ?? 0) + 1)
2522
- return makeCode(sanitized, sanitized)
2523
- }
2524
- case "Suspend": {
2525
- const thunk = recur(s.thunk)
2526
- return makeCode(
2527
- `Schema.suspend((): Schema.Codec<${thunk.Type}> => ${thunk.runtime})`,
2528
- thunk.Type
2529
- )
2530
- }
2531
- case "Null":
2532
- return makeCode(`Schema.Null`, "null")
2533
- case "Undefined":
2534
- return makeCode(`Schema.Undefined`, "undefined")
2535
- case "Void":
2536
- return makeCode(`Schema.Void`, "void")
2537
- case "Never":
2538
- return makeCode(`Schema.Never`, "never")
2539
- case "Unknown":
2540
- return makeCode(`Schema.Unknown`, "unknown")
2541
- case "Any":
2542
- return makeCode(`Schema.Any`, "any")
2543
- case "Number":
2544
- return makeCode(`Schema.Number`, "number")
2545
- case "Boolean":
2546
- return makeCode(`Schema.Boolean`, "boolean")
2547
- case "BigInt":
2548
- return makeCode(`Schema.BigInt`, "bigint")
2549
- case "Symbol":
2550
- return makeCode(`Schema.Symbol`, "symbol")
2551
- case "String": {
2552
- const contentMediaType = s.contentMediaType
2553
- const contentSchema = s.contentSchema
2554
- if (contentMediaType === "application/json" && contentSchema !== undefined) {
2555
- return makeCode(`Schema.fromJsonString(${recur(contentSchema)})`, "string")
2556
- } else {
2557
- return makeCode(`Schema.String`, "string")
2558
- }
2559
- }
2560
- case "Literal": {
2561
- const literal = format(s.literal)
2562
- return makeCode(`Schema.Literal(${literal})`, literal)
2563
- }
2564
- case "UniqueSymbol": {
2565
- const identifier = addSymbol(s.symbol)
2566
- return makeCode(`Schema.UniqueSymbol(${identifier})`, `typeof ${identifier}`)
2567
- }
2568
- case "ObjectKeyword":
2569
- return makeCode(`Schema.ObjectKeyword`, "object")
2570
- case "Enum": {
2571
- const identifier = addEnum(s)
2572
- return makeCode(`Schema.Enum(${identifier})`, `typeof ${identifier}`)
2573
- }
2574
- case "TemplateLiteral": {
2575
- const parts = s.parts.map(recur)
2576
- const type = toTypeParts(s.parts).map((p) => "`" + p + "`").join(" | ")
2577
- return makeCode(`Schema.TemplateLiteral([${parts.map((p) => p.runtime).join(", ")}])`, type)
2578
- }
2579
- case "Arrays": {
2580
- const elements = s.elements.map((e) => {
2581
- return {
2582
- isOptional: e.isOptional,
2583
- type: recur(e.type),
2584
- annotations: e.annotations
2585
- }
2586
- })
2587
-
2588
- const rest = s.rest.map(recur)
2589
-
2590
- if (Arr.isArrayNonEmpty(rest)) {
2591
- const item = rest[0]
2592
- if (elements.length === 0 && rest.length === 1) {
2593
- return makeCode(
2594
- `Schema.Array(${item.runtime})`,
2595
- `ReadonlyArray<${item.Type}>`
2596
- )
2597
- }
2598
- const post = rest.slice(1)
2599
- return makeCode(
2600
- `Schema.TupleWithRest(Schema.Tuple([${
2601
- elements.map((e) =>
2602
- toRuntimeIsOptional(e.isOptional, e.type.runtime) + toRuntimeAnnotateKey(e.annotations)
2603
- ).join(", ")
2604
- }]), [${rest.map((r) => r.runtime).join(", ")}])`,
2605
- `readonly [${
2606
- elements.map((e) => toTypeIsOptional(e.isOptional, e.type.Type)).join(", ")
2607
- }, ...Array<${item.Type}>${post.length > 0 ? `, ${post.map((p) => p.Type).join(", ")}` : ""}]`
2608
- )
2609
- }
2610
- return makeCode(
2611
- `Schema.Tuple([${
2612
- elements.map((e) => toRuntimeIsOptional(e.isOptional, e.type.runtime) + toRuntimeAnnotateKey(e.annotations))
2613
- .join(", ")
2614
- }])`,
2615
- `readonly [${elements.map((e) => toTypeIsOptional(e.isOptional, e.type.Type)).join(", ")}]`
2616
- )
2617
- }
2618
- case "Objects": {
2619
- const pss = s.propertySignatures.map((p) => {
2620
- const isSymbol = typeof p.name === "symbol"
2621
- const name = isSymbol ? addSymbol(p.name) : formatPropertyKey(p.name)
2622
- const nameType = toTypeIsOptional(
2623
- p.isOptional,
2624
- toTypeIsMutable(p.isMutable, isSymbol ? `[typeof ${name}]` : name)
2625
- )
2626
- const type = recur(p.type)
2627
- return makeCode(
2628
- `${isSymbol ? `[${name}]` : name}: ${
2629
- toRuntimeIsOptional(p.isOptional, toRuntimeIsMutable(p.isMutable, type.runtime))
2630
- }` +
2631
- toRuntimeAnnotateKey(p.annotations),
2632
- `${nameType}: ${type.Type}`
2633
- )
2634
- })
2635
-
2636
- const iss = s.indexSignatures.map((is) => {
2637
- return {
2638
- parameter: recur(is.parameter),
2639
- type: recur(is.type)
2640
- }
2641
- })
2642
-
2643
- if (iss.length === 0) {
2644
- // 1) Only properties -> Struct
2645
- return makeCode(
2646
- `Schema.Struct({ ${pss.map((p) => p.runtime).join(", ")} })`,
2647
- `{ ${pss.map((p) => p.Type).join(", ")} }`
2648
- )
2649
- } else if (pss.length === 0 && iss.length === 1) {
2650
- // 2) Only one index signature and no properties -> Record
2651
- return makeCode(
2652
- `Schema.Record(${iss[0].parameter.runtime}, ${iss[0].type.runtime})`,
2653
- `{ readonly [x: ${iss[0].parameter.Type}]: ${iss[0].type.Type} }`
2654
- )
2655
- } else {
2656
- // 3) Properties + index signatures -> StructWithRest
2657
- return makeCode(
2658
- `Schema.StructWithRest(Schema.Struct({ ${pss.map((p) => p.runtime).join(", ")} }), [${
2659
- iss.map((is) => `Schema.Record(${is.parameter.runtime}, ${is.type.runtime})`).join(", ")
2660
- }])`,
2661
- `{ ${pss.map((p) => p.Type).join(", ")}, ${
2662
- iss.map((is) => `readonly [x: ${is.parameter.Type}]: ${is.type.Type}`).join(", ")
2663
- } }`
2664
- )
2665
- }
2666
- }
2667
- case "Union": {
2668
- if (s.types.length === 0) {
2669
- return makeCode("Schema.Never", "never")
2670
- }
2671
- if (s.types.every((t) => t._tag === "Literal")) {
2672
- const literals = s.types.map((l) => format(l.literal))
2673
- if (literals.length === 1) {
2674
- return makeCode(`Schema.Literal(${literals[0]})`, literals[0])
2675
- }
2676
- return makeCode(`Schema.Literals([${literals.join(", ")}])`, literals.join(" | "))
2677
- }
2678
- const mode = s.mode === "anyOf" ? "" : `, { mode: "oneOf" }`
2679
- const types = s.types.map((t) => recur(t))
2680
- return makeCode(
2681
- `Schema.Union([${types.map((t) => t.runtime).join(", ")}]${mode})`,
2682
- types.map((t) => t.Type).join(" | ")
2683
- )
2684
- }
2685
- }
2686
- }
2687
-
2688
- function toTypeBrand(annotations: Schema.Annotations.Annotations | undefined): string {
2689
- const brands = collectBrands(annotations)
2690
- if (brands.length === 0) return ""
2691
- addImport(`import type * as Brand from "effect/Brand"`)
2692
- return brands.map((b) => ` & Brand.Brand<${format(b)}>`).join("")
2693
- }
2694
-
2695
- function toTypeChecks(checks: ReadonlyArray<Check<Meta>>): string {
2696
- return checks.map((c) => toTypeCheck(c)).join("")
2697
- }
2698
-
2699
- function toTypeCheck(check: Check<Meta>): string {
2700
- switch (check._tag) {
2701
- case "Filter":
2702
- return toTypeBrand(check.annotations)
2703
- case "FilterGroup": {
2704
- return toTypeChecks(check.checks)
2705
- }
2706
- }
2707
- }
2708
-
2709
- function toRuntimeChecks(checks: ReadonlyArray<Check<Meta>>): string {
2710
- return checks.map((c) => `.check(${toRuntimeCheck(c)})` + toRuntimeBrand(c.annotations)).join("")
2711
- }
2712
-
2713
- function toRuntimeCheck(check: Check<Meta>): string {
2714
- switch (check._tag) {
2715
- case "Filter":
2716
- return toRuntimeFilter(check)
2717
- case "FilterGroup": {
2718
- const a = toRuntimeAnnotations(check.annotations)
2719
- const ca = a === "" ? "" : `, ${a}`
2720
- return `Schema.makeFilterGroup([${check.checks.map((c) => toRuntimeCheck(c)).join(", ")}]${ca})`
2721
- }
2722
- }
2723
- }
2724
-
2725
- function toRuntimeFilter(filter: Filter<Meta>): string {
2726
- const a = toRuntimeAnnotations(filter.annotations)
2727
- const ca = a === "" ? "" : `, ${a}`
2728
- switch (filter.meta._tag) {
2729
- case "isTrimmed":
2730
- case "isGUID":
2731
- case "isULID":
2732
- case "isBase64":
2733
- case "isBase64Url":
2734
- case "isUppercased":
2735
- case "isLowercased":
2736
- case "isCapitalized":
2737
- case "isUncapitalized":
2738
- case "isFinite":
2739
- case "isInt":
2740
- case "isUnique":
2741
- case "isDateValid":
2742
- return `Schema.${filter.meta._tag}(${a})`
2743
-
2744
- case "isStringFinite":
2745
- case "isStringBigInt":
2746
- case "isStringSymbol":
2747
- case "isPattern":
2748
- return `Schema.${filter.meta._tag}(${toRuntimeRegExp(filter.meta.regExp)}${ca})`
2749
-
2750
- case "isMinLength":
2751
- return `Schema.isMinLength(${filter.meta.minLength}${ca})`
2752
- case "isMaxLength":
2753
- return `Schema.isMaxLength(${filter.meta.maxLength}${ca})`
2754
- case "isLengthBetween":
2755
- return `Schema.isLengthBetween(${filter.meta.minimum}, ${filter.meta.maximum}${ca})`
2756
- case "isUUID":
2757
- return `Schema.isUUID(${filter.meta.version}${ca})`
2758
- case "isStartsWith":
2759
- return `Schema.isStartsWith(${format(filter.meta.startsWith)}${ca})`
2760
- case "isEndsWith":
2761
- return `Schema.isEndsWith(${format(filter.meta.endsWith)}${ca})`
2762
- case "isIncludes":
2763
- return `Schema.isIncludes(${format(filter.meta.includes)}${ca})`
2764
-
2765
- case "isGreaterThan":
2766
- case "isGreaterThanBigInt":
2767
- case "isGreaterThanDate":
2768
- return `Schema.${filter.meta._tag}(${toRuntimeValue(filter.meta.exclusiveMinimum)}${ca})`
2769
- case "isGreaterThanOrEqualTo":
2770
- case "isGreaterThanOrEqualToBigInt":
2771
- case "isGreaterThanOrEqualToDate":
2772
- return `Schema.${filter.meta._tag}(${toRuntimeValue(filter.meta.minimum)}${ca})`
2773
- case "isLessThan":
2774
- case "isLessThanBigInt":
2775
- case "isLessThanDate":
2776
- return `Schema.${filter.meta._tag}(${toRuntimeValue(filter.meta.exclusiveMaximum)}${ca})`
2777
- case "isLessThanOrEqualTo":
2778
- case "isLessThanOrEqualToBigInt":
2779
- case "isLessThanOrEqualToDate":
2780
- return `Schema.${filter.meta._tag}(${toRuntimeValue(filter.meta.maximum)}${ca})`
2781
- case "isBetween":
2782
- case "isBetweenBigInt":
2783
- case "isBetweenDate":
2784
- return `Schema.${filter.meta._tag}({ minimum: ${toRuntimeValue(filter.meta.minimum)}, maximum: ${
2785
- toRuntimeValue(filter.meta.maximum)
2786
- }, exclusiveMinimum: ${toRuntimeValue(filter.meta.exclusiveMinimum)}, exclusiveMaximum: ${
2787
- toRuntimeValue(filter.meta.exclusiveMaximum)
2788
- }${ca})`
2789
-
2790
- case "isMultipleOf":
2791
- return `Schema.isMultipleOf(${filter.meta.divisor}${ca})`
2792
-
2793
- case "isMinProperties":
2794
- return `Schema.isMinProperties(${filter.meta.minProperties}${ca})`
2795
- case "isMaxProperties":
2796
- return `Schema.isMaxProperties(${filter.meta.maxProperties}${ca})`
2797
- case "isPropertiesLengthBetween":
2798
- return `Schema.isPropertiesLengthBetween(${filter.meta.minimum}, ${filter.meta.maximum}${ca})`
2799
- case "isPropertyNames":
2800
- return `Schema.isPropertyNames(${recur(filter.meta.propertyNames).runtime}${ca})`
2801
-
2802
- case "isMinSize":
2803
- return `Schema.isMinSize(${filter.meta.minSize}${ca})`
2804
- case "isMaxSize":
2805
- return `Schema.isMaxSize(${filter.meta.maxSize}${ca})`
2806
- case "isSizeBetween":
2807
- return `Schema.isSizeBetween(${filter.meta.minimum}, ${filter.meta.maximum}${ca})`
2808
- }
2809
- }
2810
- }
2811
-
2812
- const VALID_ASCII_UPPER_JAVASCRIPT_IDENTIFIER_REGEXP = /^[A-Z_$][A-Za-z0-9_$]*$/
2813
-
2814
- /**
2815
- * Converts an arbitrary string into a valid (ASCII) JavaScript identifier
2816
- * starting with an uppercase letter, `$`, or `_`.
2817
- *
2818
- * - Replaces invalid identifier characters with `_`
2819
- * - Uppercases a leading ASCII letter
2820
- * - If the first character is a digit, prefixes `_`
2821
- * - Empty input becomes `_`
2822
- *
2823
- * @internal
2824
- */
2825
- export function sanitizeJavaScriptIdentifier(s: string): string {
2826
- if (s.length === 0) return "_"
2827
- if (VALID_ASCII_UPPER_JAVASCRIPT_IDENTIFIER_REGEXP.test(s)) return s
2828
-
2829
- const out: Array<string> = []
2830
- let needsPrefix = false
2831
- let i = 0
2832
-
2833
- for (const ch of s) {
2834
- if (i === 0) {
2835
- if (ch === "_" || ch === "$" || (ch >= "A" && ch <= "Z")) {
2836
- out.push(ch)
2837
- } else if (ch >= "a" && ch <= "z") {
2838
- out.push(ch.toUpperCase())
2839
- } else if (ch >= "0" && ch <= "9") {
2840
- out.push(ch)
2841
- needsPrefix = true
2842
- } else {
2843
- out.push("_")
2844
- }
2845
- } else {
2846
- out.push(isAsciiIdPart(ch) ? ch : "_")
2847
- }
2848
- i++
2849
- }
2850
-
2851
- return needsPrefix ? "_" + out.join("") : out.join("")
2852
- }
2853
-
2854
- function isAsciiIdStart(ch: string): boolean {
2855
- return (
2856
- ch === "_" ||
2857
- ch === "$" ||
2858
- (ch >= "A" && ch <= "Z") ||
2859
- (ch >= "a" && ch <= "z")
2860
- )
2861
- }
2862
-
2863
- function isAsciiIdPart(ch: string): boolean {
2864
- return isAsciiIdStart(ch) || (ch >= "0" && ch <= "9")
2865
- }
2866
-
2867
- function replacePlaceholders(template: string, items: ReadonlyArray<string>) {
2868
- let i = 0
2869
- return template.replace(/\?/g, () => items[i++]);
2870
- }
2871
-
2872
- function toTypeParts(parts: ReadonlyArray<Representation>): ReadonlyArray<string> {
2873
- if (parts.length === 0) {
2874
- return [""]
2875
- }
2876
- const [first, ...rest] = parts
2877
- const restPatterns = toTypeParts(rest)
2878
- return toTypePart(first).flatMap((f) => restPatterns.map((r) => f + r))
2879
- }
2880
-
2881
- function toTypePart(r: Representation): ReadonlyArray<string> {
2882
- switch (r._tag) {
2883
- case "Literal":
2884
- return [globalThis.String(r.literal)]
2885
- case "String":
2886
- return ["${string}"]
2887
- case "Number":
2888
- return ["${number}"]
2889
- case "BigInt":
2890
- return ["${bigint}"]
2891
- case "TemplateLiteral":
2892
- return toTypeParts(r.parts)
2893
- case "Union":
2894
- return r.types.flatMap(toTypePart)
2895
- default:
2896
- return []
2897
- }
2898
- }
2899
-
2900
- const toCodeAnnotationsBlacklist: Set<string> = new Set([
2901
- ...toJsonAnnotationsBlacklist,
2902
- "typeConstructor",
2903
- "generation",
2904
- "brands"
2905
- ])
2906
-
2907
- function toRuntimeAnnotations(annotations: Schema.Annotations.Annotations | undefined): string {
2908
- if (!annotations) return ""
2909
- const entries: Array<string> = []
2910
- for (const [key, value] of Object.entries(annotations)) {
2911
- if (toCodeAnnotationsBlacklist.has(key)) continue
2912
- entries.push(`${formatPropertyKey(key)}: ${format(value)}`)
2913
- }
2914
- if (entries.length === 0) return ""
2915
- return `{ ${entries.join(", ")} }`
2916
- }
2917
-
2918
- function toRuntimeBrand(annotations: Schema.Annotations.Annotations | undefined): string {
2919
- const brands = collectBrands(annotations)
2920
- return brands.length > 0 ? `.pipe(${brands.map((b) => `Schema.brand(${format(b)})`).join(", ")})` : ""
2921
- }
2922
-
2923
- function toRuntimeAnnotate(annotations: Schema.Annotations.Annotations | undefined): string {
2924
- const s = toRuntimeAnnotations(annotations)
2925
- return s === "" ? "" : `.annotate(${s})`
2926
- }
2927
-
2928
- function toRuntimeAnnotateKey(annotations: Schema.Annotations.Annotations | undefined): string {
2929
- const s = toRuntimeAnnotations(annotations)
2930
- return s === "" ? "" : `.annotateKey(${s})`
2931
- }
2932
-
2933
- function toRuntimeIsOptional(isOptional: boolean, runtime: string): string {
2934
- return isOptional ? `Schema.optionalKey(${runtime})` : runtime
2935
- }
2936
-
2937
- function toTypeIsOptional(isOptional: boolean, type: string): string {
2938
- return isOptional ? `${type}?` : type
2939
- }
2940
-
2941
- function toRuntimeIsMutable(isMutable: boolean, runtime: string): string {
2942
- return isMutable ? `Schema.mutableKey(${runtime})` : runtime
2943
- }
2944
-
2945
- function toTypeIsMutable(isMutable: boolean, type: string): string {
2946
- return isMutable ? type : `readonly ${type}`
2947
- }
2948
-
2949
- function toRuntimeValue(value: undefined | number | boolean | bigint | Date): string {
2950
- if (value instanceof Date) {
2951
- return `new Date(${value.getTime()})`
2952
- }
2953
- return format(value)
2954
- }
2955
-
2956
- function toRuntimeRegExp(regExp: RegExp): string {
2957
- const args = [format(regExp.source)]
2958
- const flags = regExp.flags.trim()
2959
- if (flags !== "") {
2960
- args.push(format(flags))
2961
- }
2962
- return `new RegExp(${args.join(", ")})`
2963
- }
2964
-
2965
- /**
2966
- * Parses a Draft 2020-12 JSON Schema document into a {@link Document}.
2967
- *
2968
- * **When to use**
2969
- *
2970
- * Use when you need to import a Draft 2020-12 JSON Schema document into the
2971
- * Effect schema representation system.
2972
- *
2973
- * **Details**
2974
- *
2975
- * `options.onEnter` is an optional hook called on each JSON Schema node before
2976
- * processing, allowing pre-transformation.
2977
- *
2978
- * **Gotchas**
2979
- *
2980
- * JSON Schema import is best-effort. Some JSON Schema constructs do not map
2981
- * exactly to Effect schema representations, and importing a schema previously
2982
- * emitted by `toJsonSchemaDocument` may produce an equivalent approximation
2983
- * rather than the original representation shape.
2984
- *
2985
- * This throws if a `$ref` cannot be resolved within the document's definitions.
2986
- * Circular `$ref`s are detected and cause an error.
2987
- *
2988
- * @see {@link Document}
2989
- * @see {@link toJsonSchemaDocument}
2990
- * @see {@link fromJsonSchemaMultiDocument}
1171
+ * @see {@link fromJsonSchemaMultiDocument} for multiple roots sharing definitions
1172
+ * @see {@link toRepresentation} for converting the result to a representation document
2991
1173
  *
2992
1174
  * @category constructors
2993
1175
  * @since 4.0.0
2994
1176
  */
2995
- export function fromJsonSchemaDocument(document: JsonSchema.Document<"draft-2020-12">, options?: {
2996
- readonly onEnter?: ((js: JsonSchema.JsonSchema) => JsonSchema.JsonSchema) | undefined
2997
- }): Document {
2998
- const { references, representations: schemas } = fromJsonSchemaMultiDocument({
2999
- dialect: document.dialect,
3000
- schemas: [document.schema],
3001
- definitions: document.definitions
3002
- }, options)
3003
- return {
3004
- representation: schemas[0],
3005
- references
3006
- }
1177
+ export function fromJsonSchemaDocument(
1178
+ document: JsonSchema.Document<"draft-2020-12">,
1179
+ options?: FromJsonSchemaOptions
1180
+ ): Schema.Top {
1181
+ return InternalFromJsonSchemaDocument.fromJsonSchemaDocument(document, options)
3007
1182
  }
3008
1183
 
3009
1184
  /**
3010
- * Parses a Draft 2020-12 JSON Schema multi-document into a
3011
- * {@link MultiDocument}.
1185
+ * Imports multiple JSON Schema Draft 2020-12 roots as runtime schemas with shared definitions.
3012
1186
  *
3013
1187
  * **When to use**
3014
1188
  *
3015
- * Use when you need to import a Draft 2020-12 JSON Schema multi-document whose
3016
- * schemas share definitions.
3017
- *
3018
- * **Details**
3019
- *
3020
- * `options.onEnter` is an optional hook called on each JSON Schema node before
3021
- * processing.
1189
+ * Use when multiple imported roots must preserve shared definitions, aliases, and recursion.
3022
1190
  *
3023
1191
  * **Gotchas**
3024
1192
  *
3025
- * JSON Schema import is best-effort. Some JSON Schema constructs do not map
3026
- * exactly to Effect schema representations, and importing schemas previously
3027
- * emitted by `toJsonSchemaMultiDocument` may produce equivalent approximations
3028
- * rather than the original representation shapes.
3029
- *
3030
- * This throws if a `$ref` cannot be resolved.
1193
+ * Every definition is translated, including definitions that no root references. Callback results are used directly, and exceptions raised by a callback pass through unchanged.
3031
1194
  *
3032
- * @see {@link MultiDocument}
3033
- * @see {@link toJsonSchemaMultiDocument}
3034
- * @see {@link fromJsonSchemaDocument}
1195
+ * @see {@link fromJsonSchemaDocument} for a single root
1196
+ * @see {@link fromSchemaMultiDocument} for converting the result to a representation document
3035
1197
  *
3036
1198
  * @category constructors
3037
1199
  * @since 4.0.0
3038
1200
  */
3039
- export function fromJsonSchemaMultiDocument(document: JsonSchema.MultiDocument<"draft-2020-12">, options?: {
3040
- readonly onEnter?: ((js: JsonSchema.JsonSchema) => JsonSchema.JsonSchema) | undefined
3041
- }): MultiDocument {
3042
- let definitionIdentifier: string | undefined
3043
- const references: Record<string, Representation> = {}
3044
-
3045
- type ResolvedReference = Exclude<Representation, { _tag: "Reference" }>
3046
- const resolvedReferences = new Map<string, ResolvedReference | null>()
3047
-
3048
- function resolveReference($ref: string): ResolvedReference {
3049
- const definition = document.definitions[$ref]
3050
- if (definition === undefined) {
3051
- throw new Error(`Reference ${$ref} not found`)
3052
- }
3053
-
3054
- const resolved = resolvedReferences.get($ref)
3055
- if (resolved === null) {
3056
- throw new Error(`Circular reference detected: ${$ref}`)
3057
- }
3058
- if (resolved !== undefined) return resolved
3059
-
3060
- resolvedReferences.set($ref, null)
3061
- const value = recur(definition)
3062
- const out = value._tag === "Reference" ? resolveReference(value.$ref) : value
3063
- resolvedReferences.set($ref, out)
3064
- return out
3065
- }
3066
-
3067
- for (const [identifier, definition] of Object.entries(document.definitions)) {
3068
- definitionIdentifier = identifier
3069
- references[identifier] = unknownToJson(recur(definition))
3070
- }
3071
-
3072
- definitionIdentifier = undefined
3073
- const representations = Arr.map(document.schemas, (schema) => unknownToJson(recur(schema)))
3074
- return {
3075
- representations,
3076
- references
3077
- }
3078
-
3079
- function recur(u: unknown): Representation {
3080
- if (u === false) return never
3081
- if (!Predicate.isObject(u)) return unknown
3082
-
3083
- let js: JsonSchema.JsonSchema = options?.onEnter?.(u) ?? u
3084
- if (Array.isArray(js.type)) {
3085
- if (js.type.every(isType)) {
3086
- const { type, ...rest } = js
3087
- js = {
3088
- anyOf: type.map((type) => ({ type })),
3089
- ...rest
3090
- }
3091
- } else {
3092
- js = {}
3093
- }
3094
- }
3095
-
3096
- let out = on(js)
3097
-
3098
- const annotations = collectAnnotations(js)
3099
- if (annotations !== undefined) {
3100
- out = combine(out, { _tag: "Unknown", annotations })
3101
- }
3102
-
3103
- if (Array.isArray(js.allOf)) {
3104
- out = js.allOf.reduce((acc, curr) => combine(acc, recur(curr)), out)
3105
- }
3106
- if (Array.isArray(js.anyOf)) {
3107
- out = combine({ _tag: "Union", types: js.anyOf.map((type) => recur(type)), mode: "anyOf" }, out)
3108
- }
3109
- if (Array.isArray(js.oneOf)) {
3110
- out = combine({ _tag: "Union", types: js.oneOf.map((type) => recur(type)), mode: "oneOf" }, out)
3111
- }
3112
-
3113
- return out
3114
- }
3115
-
3116
- function on(js: JsonSchema.JsonSchema): Representation {
3117
- if (typeof js.$ref === "string") {
3118
- const $ref = js.$ref.slice(2).split("/").at(-1)
3119
- if ($ref !== undefined) {
3120
- const reference: Reference = { _tag: "Reference", $ref: unescapeToken($ref) }
3121
- if (definitionIdentifier === $ref) {
3122
- return { _tag: "Suspend", thunk: reference, checks: [] }
3123
- } else {
3124
- return reference
3125
- }
3126
- }
3127
- } else if ("const" in js) {
3128
- if (isLiteralValue(js.const)) {
3129
- return { _tag: "Literal", literal: js.const }
3130
- } else if (js.const === null) {
3131
- return null_
3132
- }
3133
- } else if (Array.isArray(js.enum)) {
3134
- const types: Array<Representation> = []
3135
- for (const e of js.enum) {
3136
- if (isLiteralValue(e)) {
3137
- types.push({ _tag: "Literal", literal: e })
3138
- } else if (e === null) {
3139
- types.push(null_)
3140
- } else {
3141
- types.push(recur(e))
3142
- }
3143
- }
3144
- if (types.length === 1) {
3145
- return types[0]
3146
- } else {
3147
- return { _tag: "Union", types, mode: "anyOf" }
3148
- }
3149
- }
3150
-
3151
- const type = isType(js.type) ? js.type : getType(js)
3152
- if (type !== undefined) {
3153
- switch (type) {
3154
- case "null":
3155
- return null_
3156
- case "string": {
3157
- const checks = collectStringChecks(js)
3158
- if (checks.length > 0) {
3159
- return { ...string, checks }
3160
- }
3161
- return string
3162
- }
3163
- case "number":
3164
- return {
3165
- _tag: "Number",
3166
- checks: [{ _tag: "Filter", meta: { _tag: "isFinite" } }, ...collectNumberChecks(js)]
3167
- }
3168
- case "integer":
3169
- return {
3170
- _tag: "Number",
3171
- checks: [{ _tag: "Filter", meta: { _tag: "isInt" } }, ...collectNumberChecks(js)]
3172
- }
3173
- case "boolean":
3174
- return boolean
3175
- case "array": {
3176
- const minItems = typeof js.minItems === "number" ? js.minItems : 0
3177
-
3178
- const elements: Array<Element> = (Array.isArray(js.prefixItems) ? js.prefixItems : []).map((e, i) => ({
3179
- isOptional: i + 1 > minItems,
3180
- type: recur(e)
3181
- }))
3182
-
3183
- const rest: Array<Representation> = js.items !== undefined ?
3184
- [recur(js.items)]
3185
- : js.prefixItems !== undefined && typeof js.maxItems === "number"
3186
- ? []
3187
- : [unknown]
3188
-
3189
- return { _tag: "Arrays", elements, rest, checks: collectArraysChecks(js) }
3190
- }
3191
- case "object": {
3192
- return {
3193
- _tag: "Objects",
3194
- propertySignatures: collectProperties(js),
3195
- indexSignatures: collectIndexSignatures(js),
3196
- checks: collectObjectsChecks(js)
3197
- }
3198
- }
3199
- }
3200
- }
3201
-
3202
- return { _tag: "Unknown" }
3203
- }
3204
-
3205
- function collectObjectsChecks(js: JsonSchema.JsonSchema): Array<Check<ObjectsMeta>> {
3206
- const checks: Array<Check<ObjectsMeta>> = []
3207
- if (typeof js.minProperties === "number") {
3208
- checks.push({ _tag: "Filter", meta: { _tag: "isMinProperties", minProperties: js.minProperties } })
3209
- }
3210
- if (typeof js.maxProperties === "number") {
3211
- checks.push({ _tag: "Filter", meta: { _tag: "isMaxProperties", maxProperties: js.maxProperties } })
3212
- }
3213
- if (js.propertyNames !== undefined) {
3214
- const propertyNames = recur(js.propertyNames)
3215
- checks.push({ _tag: "Filter", meta: { _tag: "isPropertyNames", propertyNames } })
3216
- }
3217
- return checks
3218
- }
3219
-
3220
- function combine(a: Representation, b: Representation): Representation {
3221
- switch (a._tag) {
3222
- default:
3223
- return never
3224
- case "Reference":
3225
- return combine(resolveReference(a.$ref), b)
3226
- case "Never":
3227
- return a
3228
- case "Unknown": {
3229
- const resolved = b._tag === "Reference" ? resolveReference(b.$ref) : b
3230
- return { ...resolved, ...combineAnnotations(a.annotations, resolved.annotations) }
3231
- }
3232
- case "Null":
3233
- case "String":
3234
- case "Number":
3235
- case "Boolean":
3236
- case "Literal":
3237
- case "Arrays":
3238
- case "Objects":
3239
- case "Union":
3240
- break
3241
- }
3242
-
3243
- if (b._tag === "Reference") {
3244
- return combine(a, resolveReference(b.$ref))
3245
- }
3246
- if (b._tag === "Unknown") {
3247
- return { ...a, ...combineAnnotations(a.annotations, b.annotations) }
3248
- }
3249
- if (a._tag === "Union") {
3250
- const types = a.types.map((s) => combine(s, b)).filter((s) => s !== never)
3251
- if (types.length === 0) return never
3252
- return {
3253
- _tag: "Union",
3254
- types,
3255
- mode: a.mode,
3256
- ...makeAnnotations(a.annotations)
3257
- }
3258
- }
3259
- if (b._tag === "Union") {
3260
- return combine(b, a)
3261
- }
3262
-
3263
- switch (a._tag) {
3264
- case "Null":
3265
- return b._tag === "Null" ? { ...a, ...combineAnnotations(a.annotations, b.annotations) } : never
3266
- case "String": {
3267
- if (b._tag === "Literal") {
3268
- return satisfiesLiteral(a, b) ? { ...b, ...combineAnnotations(a.annotations, b.annotations) } : never
3269
- }
3270
- if (b._tag !== "String") return never
3271
- const checks = combineChecks(a.checks, b.checks, b.annotations)
3272
- return {
3273
- _tag: "String",
3274
- checks: checks ?? a.checks,
3275
- ...combineAnnotations(a.annotations, checks ? undefined : b.annotations)
3276
- }
3277
- }
3278
- case "Number": {
3279
- if (b._tag === "Literal") {
3280
- return satisfiesLiteral(a, b) ? { ...b, ...combineAnnotations(a.annotations, b.annotations) } : never
3281
- }
3282
- if (b._tag !== "Number") return never
3283
- const checks = combineNumberChecks(a.checks, b.checks, b.annotations)
3284
- return {
3285
- _tag: "Number",
3286
- checks: checks ?? a.checks,
3287
- ...combineAnnotations(a.annotations, checks ? undefined : b.annotations)
3288
- }
3289
- }
3290
- case "Boolean":
3291
- if (b._tag === "Boolean") {
3292
- return { _tag: "Boolean", ...combineAnnotations(a.annotations, b.annotations) }
3293
- }
3294
- return b._tag === "Literal" && typeof b.literal === "boolean"
3295
- ? { ...b, ...combineAnnotations(a.annotations, b.annotations) }
3296
- : never
3297
- case "Literal":
3298
- switch (b._tag) {
3299
- case "Literal":
3300
- return a.literal === b.literal
3301
- ? { ...a, ...combineAnnotations(a.annotations, b.annotations) }
3302
- : never
3303
- case "String":
3304
- case "Number":
3305
- return satisfiesLiteral(b, a) ? { ...a, ...combineAnnotations(a.annotations, b.annotations) } : never
3306
- case "Boolean":
3307
- return typeof a.literal === "boolean"
3308
- ? { ...a, ...combineAnnotations(a.annotations, b.annotations) }
3309
- : never
3310
- default:
3311
- return never
3312
- }
3313
- case "Arrays": {
3314
- if (b._tag !== "Arrays") return never
3315
- const arrays = combineArrays(a, b)
3316
- if (arrays === undefined) return never
3317
- const checks = combineArraysChecks(a.checks, b.checks, b.annotations)
3318
- return {
3319
- _tag: "Arrays",
3320
- elements: arrays.elements,
3321
- rest: arrays.rest,
3322
- checks: checks ?? a.checks,
3323
- ...combineAnnotations(a.annotations, checks ? undefined : b.annotations)
3324
- }
3325
- }
3326
- case "Objects": {
3327
- if (b._tag !== "Objects") return never
3328
- const checks = combineChecks(a.checks, b.checks, b.annotations)
3329
- return {
3330
- _tag: "Objects",
3331
- propertySignatures: combinePropertySignatures(a.propertySignatures, b.propertySignatures),
3332
- indexSignatures: combineIndexSignatures(a.indexSignatures, b.indexSignatures),
3333
- checks: checks ?? a.checks,
3334
- ...combineAnnotations(a.annotations, checks ? undefined : b.annotations)
3335
- }
3336
- }
3337
- default:
3338
- return never
3339
- }
3340
- }
3341
-
3342
- function satisfiesPrimitiveCheck(check: Check<Meta>, value: unknown): boolean {
3343
- if (check._tag === "FilterGroup") {
3344
- return check.checks.every((check) => satisfiesPrimitiveCheck(check, value))
3345
- }
3346
- const meta = check.meta
3347
- switch (meta._tag) {
3348
- case "isMinLength":
3349
- return typeof value === "string" && value.length >= meta.minLength
3350
- case "isMaxLength":
3351
- return typeof value === "string" && value.length <= meta.maxLength
3352
- case "isPattern":
3353
- return typeof value === "string" && meta.regExp.test(value)
3354
- case "isFinite":
3355
- return typeof value === "number" && globalThis.Number.isFinite(value)
3356
- case "isInt":
3357
- return typeof value === "number" && globalThis.Number.isSafeInteger(value)
3358
- case "isMultipleOf":
3359
- return typeof value === "number" && remainder(value, meta.divisor) === 0
3360
- case "isGreaterThan":
3361
- return typeof value === "number" && value > meta.exclusiveMinimum
3362
- case "isGreaterThanOrEqualTo":
3363
- return typeof value === "number" && value >= meta.minimum
3364
- case "isLessThan":
3365
- return typeof value === "number" && value < meta.exclusiveMaximum
3366
- case "isLessThanOrEqualTo":
3367
- return typeof value === "number" && value <= meta.maximum
3368
- default:
3369
- return false
3370
- }
3371
- }
3372
-
3373
- function satisfiesLiteral(type: String | Number, literal: Literal): boolean {
3374
- const value = literal.literal
3375
- if (type._tag === "String" ? typeof value !== "string" : typeof value !== "number") {
3376
- return false
3377
- }
3378
- return type.checks.every((check) => satisfiesPrimitiveCheck(check, value))
3379
- }
3380
-
3381
- function collectProperties(js: JsonSchema.JsonSchema): Array<PropertySignature> {
3382
- const properties: Record<string, unknown> = Predicate.isObject(js.properties) ? js.properties : {}
3383
- const required = Array.isArray(js.required) ? js.required : []
3384
- required.forEach((key) => {
3385
- if (!Object.hasOwn(properties, key)) {
3386
- properties[key] = {}
3387
- }
3388
- })
3389
- return Object.entries(properties).map(([key, v]) => ({
3390
- name: key,
3391
- type: recur(v),
3392
- isOptional: !required.includes(key),
3393
- isMutable: false
3394
- }))
3395
- }
3396
-
3397
- function collectIndexSignatures(js: JsonSchema.JsonSchema): Array<IndexSignature> {
3398
- const out: Array<IndexSignature> = []
3399
-
3400
- if (Predicate.isObject(js.patternProperties)) {
3401
- for (const [pattern, value] of Object.entries(js.patternProperties)) {
3402
- out.push({ parameter: recur({ pattern }), type: recur(value) })
3403
- }
3404
- }
3405
-
3406
- if (js.additionalProperties === undefined || js.additionalProperties === true) {
3407
- out.push({ parameter: string, type: unknown })
3408
- } else if (Predicate.isObject(js.additionalProperties)) {
3409
- out.push({ parameter: string, type: recur(js.additionalProperties) })
3410
- }
3411
-
3412
- return out
3413
- }
3414
-
3415
- function combineArrays(a: Arrays, b: Arrays): Pick<Arrays, "elements" | "rest"> | undefined {
3416
- const elements: Array<Element> = []
3417
- const len = Math.max(a.elements.length, b.elements.length)
3418
- for (let i = 0; i < len; i++) {
3419
- const ae = a.elements[i]
3420
- const be = b.elements[i]
3421
- const isOptional = ae?.isOptional !== false && be?.isOptional !== false
3422
- const at = ae?.type ?? a.rest[0]
3423
- const bt = be?.type ?? b.rest[0]
3424
- if (at === undefined || bt === undefined) {
3425
- return isOptional ? { elements, rest: [] } : undefined
3426
- }
3427
- const type = combine(at, bt)
3428
- if (type === never) {
3429
- return isOptional ? { elements, rest: [] } : undefined
3430
- }
3431
- elements.push({ isOptional, type })
3432
- }
3433
-
3434
- const ar = a.rest[0]
3435
- const br = b.rest[0]
3436
- if (ar === undefined || br === undefined) {
3437
- return { elements, rest: [] }
3438
- }
3439
- const rest = combine(ar, br)
3440
- return { elements, rest: rest === never ? [] : [rest] }
3441
- }
3442
-
3443
- function combinePropertySignatures(
3444
- a: ReadonlyArray<PropertySignature>,
3445
- b: ReadonlyArray<PropertySignature>
3446
- ): Array<PropertySignature> {
3447
- const propertySignatures: Array<PropertySignature> = []
3448
- const thatPropertiesMap: Record<PropertyKey, PropertySignature> = {}
3449
- for (const p of b) {
3450
- thatPropertiesMap[p.name] = p
3451
- }
3452
- const keys = new Set<PropertyKey>()
3453
- for (const p of a) {
3454
- keys.add(p.name)
3455
- const thatp = thatPropertiesMap[p.name]
3456
- if (thatp) {
3457
- propertySignatures.push(
3458
- {
3459
- name: p.name,
3460
- type: combine(p.type, thatp.type),
3461
- isOptional: p.isOptional && thatp.isOptional,
3462
- isMutable: p.isMutable
3463
- }
3464
- )
3465
- } else {
3466
- propertySignatures.push(p)
3467
- }
3468
- }
3469
- for (const p of b) {
3470
- if (!keys.has(p.name)) propertySignatures.push(p)
3471
- }
3472
- return propertySignatures
3473
- }
3474
-
3475
- function combineIndexSignatures(
3476
- a: ReadonlyArray<IndexSignature>,
3477
- b: ReadonlyArray<IndexSignature>
3478
- ): Array<IndexSignature> {
3479
- if (a.length === 0 || b.length === 0) return []
3480
- const out: Array<IndexSignature> = [...a]
3481
- for (const is of b) {
3482
- if (is.parameter === string) {
3483
- const i = a.findIndex((is) => is.parameter === string)
3484
- if (i !== -1) {
3485
- out[i] = { parameter: string, type: combine(a[i].type, is.type) }
3486
- } else {
3487
- out.push(is)
3488
- }
3489
- } else {
3490
- out.push(is)
3491
- }
3492
- }
3493
- return out
3494
- }
3495
-
3496
- function unknownToJson(representation: Representation): Representation {
3497
- switch (representation._tag) {
3498
- case "Unknown":
3499
- return representation.annotations === undefined ?
3500
- json :
3501
- {
3502
- ...json,
3503
- annotations: {
3504
- ...json.annotations,
3505
- ...representation.annotations
3506
- }
3507
- }
3508
- case "Suspend": {
3509
- const thunk = unknownToJson(representation.thunk)
3510
- return thunk === representation.thunk ? representation : { ...representation, thunk }
3511
- }
3512
- case "String": {
3513
- if (representation.contentSchema === undefined) return representation
3514
- const contentSchema = unknownToJson(representation.contentSchema)
3515
- return contentSchema === representation.contentSchema ? representation : { ...representation, contentSchema }
3516
- }
3517
- case "Arrays": {
3518
- const elements = SchemaAST.mapOrSame(representation.elements, (element) => {
3519
- const type = unknownToJson(element.type)
3520
- return type === element.type ? element : { ...element, type }
3521
- })
3522
- const rest = SchemaAST.mapOrSame(representation.rest, unknownToJson)
3523
- return elements === representation.elements && rest === representation.rest ?
3524
- representation :
3525
- { ...representation, elements, rest }
3526
- }
3527
- case "Objects": {
3528
- const propertySignatures = SchemaAST.mapOrSame(representation.propertySignatures, (propertySignature) => {
3529
- const type = unknownToJson(propertySignature.type)
3530
- return type === propertySignature.type ? propertySignature : { ...propertySignature, type }
3531
- })
3532
- const indexSignatures = SchemaAST.mapOrSame(representation.indexSignatures, (indexSignature) => {
3533
- const type = unknownToJson(indexSignature.type)
3534
- return type === indexSignature.type ? indexSignature : { ...indexSignature, type }
3535
- })
3536
- return propertySignatures === representation.propertySignatures &&
3537
- indexSignatures === representation.indexSignatures ?
3538
- representation :
3539
- { ...representation, propertySignatures, indexSignatures }
3540
- }
3541
- case "Union": {
3542
- const types = SchemaAST.mapOrSame(representation.types, unknownToJson)
3543
- return types === representation.types ? representation : { ...representation, types }
3544
- }
3545
- default:
3546
- return representation
3547
- }
3548
- }
3549
- }
3550
-
3551
- function asChecks<M>(
3552
- checks: ReadonlyArray<Check<M>>,
3553
- annotations: Schema.Annotations.Annotations | undefined
3554
- ): ReadonlyArray<Check<M>> | undefined {
3555
- if (Arr.isReadonlyArrayNonEmpty(checks)) {
3556
- if (annotations !== undefined) {
3557
- if (checks.length === 1) {
3558
- const check = checks[0]
3559
- if (check.annotations === undefined) {
3560
- return [{ ...check, annotations }]
3561
- } else {
3562
- return [{ _tag: "FilterGroup", checks, annotations }]
3563
- }
3564
- } else {
3565
- return [{ _tag: "FilterGroup", checks, annotations }]
3566
- }
3567
- }
3568
- return checks
3569
- }
3570
- }
3571
-
3572
- function combineChecks<M>(
3573
- a: ReadonlyArray<Check<M>>,
3574
- b: ReadonlyArray<Check<M>>,
3575
- annotations: Schema.Annotations.Annotations | undefined
3576
- ): Array<Check<M>> | undefined {
3577
- const checks = asChecks(b, annotations)
3578
- if (checks) {
3579
- return [...a, ...checks]
3580
- }
3581
- }
3582
-
3583
- function combineNumberChecks(
3584
- a: ReadonlyArray<Check<NumberMeta>>,
3585
- b: ReadonlyArray<Check<NumberMeta>>,
3586
- annotations: Schema.Annotations.Annotations | undefined
3587
- ): Array<Check<NumberMeta>> | undefined {
3588
- if (a.some((c) => c._tag === "Filter" && c.meta._tag === "isFinite")) {
3589
- b = b.filter((c) => c._tag !== "Filter" || c.meta._tag !== "isFinite")
3590
- }
3591
- if (a.some((c) => c._tag === "Filter" && c.meta._tag === "isInt")) {
3592
- b = b.filter((c) => c._tag !== "Filter" || c.meta._tag !== "isInt")
3593
- }
3594
- return combineChecks(a, b, annotations)
3595
- }
3596
-
3597
- function combineArraysChecks(
3598
- a: ReadonlyArray<Check<ArraysMeta>>,
3599
- b: ReadonlyArray<Check<ArraysMeta>>,
3600
- annotations: Schema.Annotations.Annotations | undefined
3601
- ): Array<Check<ArraysMeta>> | undefined {
3602
- if (a.some((c) => c._tag === "Filter" && c.meta._tag === "isUnique")) {
3603
- b = b.filter((c) => c._tag !== "Filter" || c.meta._tag !== "isUnique")
3604
- }
3605
- return combineChecks(a, b, annotations)
3606
- }
3607
-
3608
- function makeAnnotations(
3609
- annotations: Schema.Annotations.Annotations | undefined
3610
- ): { annotations: Schema.Annotations.Annotations } | undefined {
3611
- return annotations ? { annotations } : undefined
3612
- }
3613
-
3614
- function combineAnnotations(
3615
- a: Schema.Annotations.Annotations | undefined,
3616
- b: Schema.Annotations.Annotations | undefined
3617
- ): { annotations: Schema.Annotations.Annotations } | undefined {
3618
- if (a === undefined) return makeAnnotations(b)
3619
- if (b === undefined) return makeAnnotations(a)
3620
- return { annotations: { ...a, ...b } } // TODO: better merge
3621
- }
3622
-
3623
- function collectStringChecks(js: JsonSchema.JsonSchema): Array<Check<StringMeta>> {
3624
- const checks: Array<Check<StringMeta>> = []
3625
- if (typeof js.minLength === "number") {
3626
- checks.push({ _tag: "Filter", meta: { _tag: "isMinLength", minLength: js.minLength } })
3627
- }
3628
- if (typeof js.maxLength === "number") {
3629
- checks.push({ _tag: "Filter", meta: { _tag: "isMaxLength", maxLength: js.maxLength } })
3630
- }
3631
- if (typeof js.pattern === "string") {
3632
- checks.push({ _tag: "Filter", meta: { _tag: "isPattern", regExp: new RegExp(js.pattern) } })
3633
- }
3634
- return checks
3635
- }
3636
-
3637
- function collectNumberChecks(js: JsonSchema.JsonSchema): Array<Check<NumberMeta>> {
3638
- const checks: Array<Check<NumberMeta>> = []
3639
- if (typeof js.minimum === "number") {
3640
- checks.push({ _tag: "Filter", meta: { _tag: "isGreaterThanOrEqualTo", minimum: js.minimum } })
3641
- }
3642
- if (typeof js.maximum === "number") {
3643
- checks.push({ _tag: "Filter", meta: { _tag: "isLessThanOrEqualTo", maximum: js.maximum } })
3644
- }
3645
- if (typeof js.exclusiveMinimum === "number") {
3646
- checks.push({ _tag: "Filter", meta: { _tag: "isGreaterThan", exclusiveMinimum: js.exclusiveMinimum } })
3647
- }
3648
- if (typeof js.exclusiveMaximum === "number") {
3649
- checks.push({ _tag: "Filter", meta: { _tag: "isLessThan", exclusiveMaximum: js.exclusiveMaximum } })
3650
- }
3651
- if (typeof js.multipleOf === "number") {
3652
- checks.push({ _tag: "Filter", meta: { _tag: "isMultipleOf", divisor: js.multipleOf } })
3653
- }
3654
- return checks
3655
- }
3656
-
3657
- function collectArraysChecks(js: JsonSchema.JsonSchema): Array<Check<ArraysMeta>> {
3658
- const checks: Array<Check<ArraysMeta>> = []
3659
- if (js.prefixItems === undefined) {
3660
- if (typeof js.minItems === "number") {
3661
- checks.push({ _tag: "Filter", meta: { _tag: "isMinLength", minLength: js.minItems } })
3662
- }
3663
- if (typeof js.maxItems === "number") {
3664
- checks.push({ _tag: "Filter", meta: { _tag: "isMaxLength", maxLength: js.maxItems } })
3665
- }
3666
- }
3667
- if (typeof js.uniqueItems === "boolean") {
3668
- checks.push({ _tag: "Filter", meta: { _tag: "isUnique" } })
3669
- }
3670
- return checks
3671
- }
3672
-
3673
- const unknown: Unknown = { _tag: "Unknown" }
3674
- const json: Declaration = {
3675
- _tag: "Declaration",
3676
- annotations: {
3677
- expected: "JSON value",
3678
- generation: {
3679
- Type: "Schema.Json",
3680
- runtime: "Schema.Json"
3681
- },
3682
- typeConstructor: {
3683
- _tag: "effect/Json"
3684
- }
3685
- },
3686
- checks: [],
3687
- encodedSchema: unknown,
3688
- typeParameters: []
3689
- }
3690
- const never: Never = { _tag: "Never" }
3691
- const null_: Null = { _tag: "Null" }
3692
- const string: String = { _tag: "String", checks: [] }
3693
- const boolean: Boolean = { _tag: "Boolean" }
3694
-
3695
- function collectAnnotations(
3696
- schema: JsonSchema.JsonSchema
3697
- ): Schema.Annotations.Annotations | undefined {
3698
- const as: Record<string, unknown> = {}
3699
-
3700
- if (typeof schema.title === "string") as.title = schema.title
3701
- if (typeof schema.description === "string") as.description = schema.description
3702
- if (schema.default !== undefined) as.default = schema.default
3703
- if (Array.isArray(schema.examples)) as.examples = schema.examples
3704
- if (typeof schema.readOnly === "boolean") as.readOnly = schema.readOnly
3705
- if (typeof schema.writeOnly === "boolean") as.writeOnly = schema.writeOnly
3706
- if (typeof schema.format === "string") as.format = schema.format
3707
- if (typeof schema.contentEncoding === "string") as.contentEncoding = schema.contentEncoding
3708
- if (typeof schema.contentMediaType === "string") as.contentMediaType = schema.contentMediaType
3709
-
3710
- return Rec.isEmptyRecord(as) ? undefined : as
3711
- }
3712
-
3713
- function isLiteralValue(value: unknown): value is SchemaAST.LiteralValue {
3714
- return typeof value === "string" || typeof value === "number" || typeof value === "boolean"
3715
- }
3716
-
3717
- const stringKeys = ["minLength", "maxLength", "pattern", "format", "contentMediaType", "contentSchema"]
3718
- const numberKeys = ["minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "multipleOf"]
3719
- const objectKeys = [
3720
- "properties",
3721
- "required",
3722
- "additionalProperties",
3723
- "patternProperties",
3724
- "propertyNames",
3725
- "minProperties",
3726
- "maxProperties"
3727
- ]
3728
- const arrayKeys = ["items", "prefixItems", "additionalItems", "minItems", "maxItems", "uniqueItems"]
3729
-
3730
- function getType(js: JsonSchema.JsonSchema): JsonSchema.Type | undefined {
3731
- if (stringKeys.some((key) => js[key] !== undefined)) {
3732
- return "string"
3733
- }
3734
- if (numberKeys.some((key) => js[key] !== undefined)) {
3735
- return "number"
3736
- }
3737
- if (objectKeys.some((key) => js[key] !== undefined)) {
3738
- return "object"
3739
- }
3740
- if (arrayKeys.some((key) => js[key] !== undefined)) {
3741
- return "array"
3742
- }
3743
- }
3744
-
3745
- const types = ["null", "string", "number", "integer", "boolean", "object", "array"]
3746
-
3747
- function isType(type: unknown): type is JsonSchema.Type {
3748
- return typeof type === "string" && types.includes(type)
3749
- }
3750
-
3751
- /** @internal */
3752
- export type TopologicalSort = {
3753
- /**
3754
- * The definitions that are not recursive.
3755
- * The definitions that depends on other definitions are placed after the definitions they depend on
3756
- */
3757
- readonly nonRecursives: ReadonlyArray<{
3758
- readonly $ref: string
3759
- readonly representation: Representation
3760
- }>
3761
- /**
3762
- * The recursive definitions (with no particular order).
3763
- */
3764
- readonly recursives: {
3765
- readonly [$ref: string]: Representation
3766
- }
3767
- }
3768
-
3769
- /** @internal */
3770
- export function topologicalSort(references: References): TopologicalSort {
3771
- const identifiers = Object.keys(references)
3772
- const identifierSet = new Set(identifiers)
3773
-
3774
- const collectRefs = (root: Representation): Set<string> => {
3775
- const refs = new Set<string>()
3776
- const visited = new WeakSet<object>()
3777
- const stack: Array<Representation> = [root]
3778
-
3779
- while (stack.length > 0) {
3780
- const r = stack.pop()!
3781
- if (visited.has(r)) continue
3782
- visited.add(r)
3783
-
3784
- if (r._tag === "Reference") {
3785
- if (identifierSet.has(r.$ref)) {
3786
- refs.add(r.$ref)
3787
- }
3788
- }
3789
-
3790
- // Push nested Representation schemas onto the stack
3791
- switch (r._tag) {
3792
- case "Declaration":
3793
- for (const typeParam of r.typeParameters) stack.push(typeParam)
3794
- stack.push(r.encodedSchema)
3795
- break
3796
- case "Suspend":
3797
- stack.push(r.thunk)
3798
- break
3799
- case "String":
3800
- if (r.contentSchema !== undefined) stack.push(r.contentSchema)
3801
- break
3802
- case "TemplateLiteral":
3803
- for (const part of r.parts) stack.push(part)
3804
- break
3805
- case "Arrays":
3806
- for (const element of r.elements) stack.push(element.type)
3807
- for (const rest of r.rest) stack.push(rest)
3808
- break
3809
- case "Objects":
3810
- for (const propertySignature of r.propertySignatures) stack.push(propertySignature.type)
3811
- for (const indexSignature of r.indexSignatures) {
3812
- stack.push(indexSignature.parameter)
3813
- stack.push(indexSignature.type)
3814
- }
3815
- break
3816
- case "Union":
3817
- for (const type of r.types) stack.push(type)
3818
- break
3819
- }
3820
- }
3821
-
3822
- return refs
3823
- }
3824
-
3825
- // identifier -> internal identifiers it depends on
3826
- const dependencies = new Map<string, Set<string>>(
3827
- identifiers.map((id) => [id, collectRefs(references[id])])
3828
- )
3829
-
3830
- // Mark only nodes that are part of cycles
3831
- const recursive = new Set<string>()
3832
- const state = new Map<string, 0 | 1 | 2>() // 0 = new, 1 = visiting, 2 = done
3833
- const stack: Array<string> = []
3834
- const indexInStack = new Map<string, number>()
3835
-
3836
- const dfs = (id: string): void => {
3837
- const s = state.get(id) ?? 0
3838
- if (s === 1) {
3839
- const start = indexInStack.get(id)
3840
- if (start !== undefined) {
3841
- for (let i = start; i < stack.length; i++) {
3842
- recursive.add(stack[i])
3843
- }
3844
- }
3845
- return
3846
- }
3847
- if (s === 2) return
3848
-
3849
- state.set(id, 1)
3850
- indexInStack.set(id, stack.length)
3851
- stack.push(id)
3852
-
3853
- for (const dep of dependencies.get(id) ?? []) {
3854
- dfs(dep)
3855
- }
3856
-
3857
- stack.pop()
3858
- indexInStack.delete(id)
3859
- state.set(id, 2)
3860
- }
3861
-
3862
- for (const id of identifiers) dfs(id)
3863
-
3864
- // Topologically sort the non-recursive nodes (ignoring edges to recursive nodes)
3865
- const inDegree = new Map<string, number>()
3866
- const dependents = new Map<string, Set<string>>() // dep -> nodes that depend on it
3867
-
3868
- for (const id of identifiers) {
3869
- if (!recursive.has(id)) {
3870
- inDegree.set(id, 0)
3871
- dependents.set(id, new Set())
3872
- }
3873
- }
3874
-
3875
- for (const [id, deps] of dependencies) {
3876
- if (recursive.has(id)) continue
3877
- for (const dep of deps) {
3878
- if (recursive.has(dep)) continue
3879
- inDegree.set(id, (inDegree.get(id) ?? 0) + 1)
3880
- dependents.get(dep)?.add(id)
3881
- }
3882
- }
3883
-
3884
- const queue: Array<string> = []
3885
- for (const [id, deg] of inDegree) {
3886
- if (deg === 0) queue.push(id)
3887
- }
3888
-
3889
- const nonRecursives: Array<{ readonly $ref: string; readonly representation: Representation }> = []
3890
- for (let i = 0; i < queue.length; i++) {
3891
- const $ref = queue[i]
3892
- nonRecursives.push({ $ref, representation: references[$ref] })
3893
-
3894
- for (const next of dependents.get($ref) ?? []) {
3895
- const deg = (inDegree.get(next) ?? 0) - 1
3896
- inDegree.set(next, deg)
3897
- if (deg === 0) queue.push(next)
3898
- }
3899
- }
3900
-
3901
- const recursives: Record<string, Representation> = {}
3902
- for (const $ref of recursive) {
3903
- recursives[$ref] = references[$ref]
3904
- }
3905
-
3906
- return { nonRecursives, recursives }
1201
+ export function fromJsonSchemaMultiDocument(
1202
+ document: JsonSchema.MultiDocument<"draft-2020-12">,
1203
+ options?: FromJsonSchemaOptions
1204
+ ): SchemaMultiDocument {
1205
+ return InternalFromJsonSchemaDocument.fromJsonSchemaMultiDocument(document, options)
3907
1206
  }