experimental-ash 0.28.0 → 0.29.0

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 (345) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +1 -0
  3. package/dist/docs/internals/hooks.md +1 -1
  4. package/dist/docs/public/cli-build-and-debugging.md +2 -0
  5. package/dist/docs/public/getting-started.md +1 -0
  6. package/dist/src/channel/adapter.js +1 -1
  7. package/dist/src/channel/compiled-channel.js +1 -1
  8. package/dist/src/channel/http.js +1 -1
  9. package/dist/src/channel/schedule.js +1 -1
  10. package/dist/src/channel/send.js +1 -1
  11. package/dist/src/channel/session-callback.js +1 -1
  12. package/dist/src/channel/session.js +1 -1
  13. package/dist/src/cli/commands/channels.js +1 -1
  14. package/dist/src/cli/dev/environment.js +1 -1
  15. package/dist/src/cli/dev/input-requests.js +1 -1
  16. package/dist/src/cli/dev/repl.js +1 -1
  17. package/dist/src/cli/dev/terminal.js +1 -1
  18. package/dist/src/cli/dev/url.js +1 -1
  19. package/dist/src/cli/run.d.ts +9 -0
  20. package/dist/src/cli/run.js +1 -1
  21. package/dist/src/compiler/artifacts.js +1 -1
  22. package/dist/src/compiler/manifest.js +1 -1
  23. package/dist/src/compiler/model-catalog.js +1 -1
  24. package/dist/src/compiler/module-map.js +1 -1
  25. package/dist/src/compiler/normalize-subagent.js +1 -1
  26. package/dist/src/compiler/remote-agent-node.js +1 -1
  27. package/dist/src/compiler/workspace-resources.js +1 -1
  28. package/dist/src/context/accessors.js +1 -1
  29. package/dist/src/context/container.js +1 -1
  30. package/dist/src/context/hook-lifecycle.d.ts +3 -3
  31. package/dist/src/context/hook-lifecycle.js +1 -1
  32. package/dist/src/context/key.js +1 -1
  33. package/dist/src/context/keys.d.ts +31 -10
  34. package/dist/src/context/keys.js +1 -1
  35. package/dist/src/context/node.js +1 -1
  36. package/dist/src/context/providers/connection.js +1 -1
  37. package/dist/src/context/providers/sandbox.js +1 -1
  38. package/dist/src/context/providers/session.js +1 -1
  39. package/dist/src/context/run-step.js +1 -1
  40. package/dist/src/context/serialize.js +1 -1
  41. package/dist/src/discover/connections.js +1 -1
  42. package/dist/src/discover/diagnostics.js +1 -1
  43. package/dist/src/discover/discover-subagent.js +1 -1
  44. package/dist/src/discover/filesystem.js +1 -1
  45. package/dist/src/discover/grammar.js +1 -1
  46. package/dist/src/discover/lib.js +1 -1
  47. package/dist/src/discover/manifest.js +1 -1
  48. package/dist/src/discover/sandbox.js +1 -1
  49. package/dist/src/discover/schedules.js +1 -1
  50. package/dist/src/discover/skills.js +1 -1
  51. package/dist/src/evals/runner/discover.js +1 -1
  52. package/dist/src/evals/runner/execute-suite.js +1 -1
  53. package/dist/src/evals/runner/reporters/braintrust.js +1 -1
  54. package/dist/src/evals/scores/index.js +1 -1
  55. package/dist/src/execution/await-authorization-orchestrator.js +1 -1
  56. package/dist/src/execution/connection-auth-steps.js +1 -1
  57. package/dist/src/execution/runtime-context.d.ts +1 -1
  58. package/dist/src/execution/runtime-context.js +1 -1
  59. package/dist/src/execution/sandbox/bindings/local.js +1 -1
  60. package/dist/src/execution/sandbox/bindings/vercel.js +1 -1
  61. package/dist/src/execution/sandbox/glob-tool.js +1 -1
  62. package/dist/src/execution/sandbox/grep-tool.js +1 -1
  63. package/dist/src/execution/sandbox/prewarm.d.ts +12 -2
  64. package/dist/src/execution/sandbox/prewarm.js +1 -1
  65. package/dist/src/execution/sandbox/read-file-tool.js +1 -1
  66. package/dist/src/execution/sandbox/require-sandbox.js +1 -1
  67. package/dist/src/execution/sandbox/ripgrep-probe.js +1 -1
  68. package/dist/src/execution/sandbox/truncate-output.js +1 -1
  69. package/dist/src/execution/session-callback-step.js +1 -1
  70. package/dist/src/execution/session.js +1 -1
  71. package/dist/src/execution/subagent-adapter.js +1 -1
  72. package/dist/src/execution/tool-compaction.js +1 -1
  73. package/dist/src/execution/turn-workflow.js +1 -1
  74. package/dist/src/execution/web-fetch/html.js +1 -1
  75. package/dist/src/execution/web-fetch/tool.js +1 -1
  76. package/dist/src/execution/workflow-entry.js +1 -1
  77. package/dist/src/execution/workflow-runtime.js +1 -1
  78. package/dist/src/execution/workflow-steps.js +1 -1
  79. package/dist/src/harness/attachment-staging.js +1 -1
  80. package/dist/src/harness/compaction.js +2 -2
  81. package/dist/src/harness/emission.js +1 -1
  82. package/dist/src/harness/input-requests.js +1 -1
  83. package/dist/src/harness/instrumentation-config.js +1 -1
  84. package/dist/src/harness/model-call-error.js +1 -1
  85. package/dist/src/harness/otel-integration.js +1 -1
  86. package/dist/src/harness/prompt-cache.js +1 -1
  87. package/dist/src/harness/provider-tools.js +1 -1
  88. package/dist/src/harness/proxy-input-requests.js +1 -1
  89. package/dist/src/harness/runtime-actions.js +1 -1
  90. package/dist/src/harness/step-hooks.js +1 -1
  91. package/dist/src/harness/tool-loop.js +1 -1
  92. package/dist/src/harness/tool-result-pruning.js +1 -1
  93. package/dist/src/internal/application/cache-metadata.js +1 -1
  94. package/dist/src/internal/application/compiled-artifacts.js +1 -1
  95. package/dist/src/internal/application/import-specifier.js +1 -1
  96. package/dist/src/internal/application/package.js +1 -1
  97. package/dist/src/internal/attachments/refs.js +1 -1
  98. package/dist/src/internal/attachments/sandbox-refs.js +1 -1
  99. package/dist/src/internal/attachments/url-refs.js +1 -1
  100. package/dist/src/internal/authored-asset-import-plugin.js +1 -1
  101. package/dist/src/internal/authored-definition/connection.js +1 -1
  102. package/dist/src/internal/authored-module-loader.js +1 -1
  103. package/dist/src/internal/authored-package-tsconfig-paths.js +1 -1
  104. package/dist/src/internal/bundler/nitro-rolldown.js +1 -1
  105. package/dist/src/internal/helpers/markdown.js +2 -2
  106. package/dist/src/internal/json-schema.js +1 -1
  107. package/dist/src/internal/logging.js +1 -1
  108. package/dist/src/internal/nitro/host/channel-routes.js +1 -1
  109. package/dist/src/internal/nitro/host/compiled-sandbox-backend-prune-plugin.js +1 -1
  110. package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
  111. package/dist/src/internal/nitro/host/dev-authored-source-watcher.js +1 -1
  112. package/dist/src/internal/nitro/host/schedule-task-routes.js +1 -1
  113. package/dist/src/internal/nitro/host/server-external-packages.js +1 -1
  114. package/dist/src/internal/nitro/host/start-development-server.js +1 -1
  115. package/dist/src/internal/nitro/host/start-production-server.d.ts +8 -0
  116. package/dist/src/internal/nitro/host/start-production-server.js +3 -0
  117. package/dist/src/internal/nitro/host/types.d.ts +8 -0
  118. package/dist/src/internal/nitro/host.d.ts +2 -1
  119. package/dist/src/internal/nitro/host.js +1 -1
  120. package/dist/src/internal/nitro/routes/agent-info/load-agent-info-data.js +1 -1
  121. package/dist/src/internal/nitro/routes/index.js +3 -3
  122. package/dist/src/internal/nitro/routes/workflow-route-helpers.js +1 -1
  123. package/dist/src/internal/node-esm-compat-banner.js +1 -1
  124. package/dist/src/internal/package-name.js +1 -1
  125. package/dist/src/internal/vercel-agent-summary.js +1 -1
  126. package/dist/src/internal/workflow-bundle/ash-service-route-output.js +1 -1
  127. package/dist/src/internal/workflow-bundle/builder-support.js +1 -1
  128. package/dist/src/internal/workflow-bundle/builder.js +2 -2
  129. package/dist/src/internal/workflow-bundle/vercel-workflow-output.js +1 -1
  130. package/dist/src/internal/workflow-bundle/workflow-builders.js +1 -1
  131. package/dist/src/internal/workflow-bundle/workflow-core-shim.js +1 -1
  132. package/dist/src/internal/workflow-bundle/workflow-transformer.js +1 -1
  133. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/ajv.js +1 -1
  134. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/codegen/code.js +1 -1
  135. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/codegen/index.js +2 -2
  136. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/codegen/scope.js +1 -1
  137. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/errors.js +1 -1
  138. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/index.js +1 -1
  139. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/names.js +1 -1
  140. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/ref_error.js +1 -1
  141. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/resolve.js +1 -1
  142. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/rules.js +1 -1
  143. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/util.js +1 -1
  144. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/boolSchema.js +1 -1
  145. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/dataType.js +2 -2
  146. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/defaults.js +1 -1
  147. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/index.js +1 -1
  148. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/keyword.js +1 -1
  149. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/subschema.js +1 -1
  150. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/core.js +1 -1
  151. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/equal.js +1 -1
  152. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/uri.js +1 -1
  153. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js +1 -1
  154. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js +1 -1
  155. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/allOf.js +1 -1
  156. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/contains.js +1 -1
  157. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/dependencies.js +2 -2
  158. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/if.js +1 -1
  159. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/index.js +1 -1
  160. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/items.js +1 -1
  161. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/items2020.js +1 -1
  162. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/not.js +1 -1
  163. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/oneOf.js +1 -1
  164. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js +1 -1
  165. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js +1 -1
  166. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/properties.js +1 -1
  167. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js +1 -1
  168. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/thenElse.js +1 -1
  169. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/code.js +1 -1
  170. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/core/index.js +1 -1
  171. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/core/ref.js +1 -1
  172. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/discriminator/index.js +1 -1
  173. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/draft7.js +1 -1
  174. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/format/format.js +1 -1
  175. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/const.js +1 -1
  176. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/enum.js +1 -1
  177. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/index.js +1 -1
  178. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitItems.js +1 -1
  179. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitLength.js +1 -1
  180. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitNumber.js +1 -1
  181. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitProperties.js +1 -1
  182. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/multipleOf.js +1 -1
  183. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/pattern.js +1 -1
  184. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/required.js +1 -1
  185. package/dist/src/node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js +1 -1
  186. package/dist/src/node_modules/.pnpm/fast-uri@3.1.2/node_modules/fast-uri/index.js +1 -1
  187. package/dist/src/node_modules/.pnpm/fast-uri@3.1.2/node_modules/fast-uri/lib/schemes.js +1 -1
  188. package/dist/src/node_modules/.pnpm/fast-uri@3.1.2/node_modules/fast-uri/lib/utils.js +1 -1
  189. package/dist/src/node_modules/.pnpm/openai@6.39.0_ws@8.21.0_zod@3.25.76/node_modules/openai/_vendor/partial-json-parser/parser.js +2 -2
  190. package/dist/src/node_modules/.pnpm/openai@6.39.0_ws@8.21.0_zod@3.25.76/node_modules/openai/auth/workload-identity-auth.js +1 -1
  191. package/dist/src/node_modules/.pnpm/openai@6.39.0_ws@8.21.0_zod@3.25.76/node_modules/openai/azure.js +1 -1
  192. package/dist/src/node_modules/.pnpm/openai@6.39.0_ws@8.21.0_zod@3.25.76/node_modules/openai/client.js +2 -2
  193. package/dist/src/node_modules/.pnpm/openai@6.39.0_ws@8.21.0_zod@3.25.76/node_modules/openai/internal/detect-platform.js +1 -1
  194. package/dist/src/node_modules/.pnpm/openai@6.39.0_ws@8.21.0_zod@3.25.76/node_modules/openai/internal/errors.js +1 -1
  195. package/dist/src/node_modules/.pnpm/openai@6.39.0_ws@8.21.0_zod@3.25.76/node_modules/openai/internal/headers.js +1 -1
  196. package/dist/src/node_modules/.pnpm/openai@6.39.0_ws@8.21.0_zod@3.25.76/node_modules/openai/internal/qs/formats.js +1 -1
  197. package/dist/src/node_modules/.pnpm/openai@6.39.0_ws@8.21.0_zod@3.25.76/node_modules/openai/internal/qs/stringify.js +1 -1
  198. package/dist/src/node_modules/.pnpm/openai@6.39.0_ws@8.21.0_zod@3.25.76/node_modules/openai/internal/qs/utils.js +1 -1
  199. package/dist/src/node_modules/.pnpm/openai@6.39.0_ws@8.21.0_zod@3.25.76/node_modules/openai/internal/request-options.js +1 -1
  200. package/dist/src/node_modules/.pnpm/openai@6.39.0_ws@8.21.0_zod@3.25.76/node_modules/openai/internal/to-file.js +1 -1
  201. package/dist/src/node_modules/.pnpm/openai@6.39.0_ws@8.21.0_zod@3.25.76/node_modules/openai/internal/uploads.js +1 -1
  202. package/dist/src/node_modules/.pnpm/openai@6.39.0_ws@8.21.0_zod@3.25.76/node_modules/openai/internal/utils/base64.js +1 -1
  203. package/dist/src/node_modules/.pnpm/openai@6.39.0_ws@8.21.0_zod@3.25.76/node_modules/openai/internal/utils/bytes.js +1 -1
  204. package/dist/src/node_modules/.pnpm/openai@6.39.0_ws@8.21.0_zod@3.25.76/node_modules/openai/internal/utils/env.js +1 -1
  205. package/dist/src/node_modules/.pnpm/openai@6.39.0_ws@8.21.0_zod@3.25.76/node_modules/openai/internal/utils/log.js +1 -1
  206. package/dist/src/node_modules/.pnpm/openai@6.39.0_ws@8.21.0_zod@3.25.76/node_modules/openai/internal/utils/path.js +1 -1
  207. package/dist/src/node_modules/.pnpm/openai@6.39.0_ws@8.21.0_zod@3.25.76/node_modules/openai/internal/utils/sleep.js +1 -1
  208. package/dist/src/node_modules/.pnpm/openai@6.39.0_ws@8.21.0_zod@3.25.76/node_modules/openai/internal/utils/uuid.js +1 -1
  209. package/dist/src/node_modules/.pnpm/openai@6.39.0_ws@8.21.0_zod@3.25.76/node_modules/openai/internal/utils/values.js +1 -1
  210. package/dist/src/node_modules/.pnpm/openai@6.39.0_ws@8.21.0_zod@3.25.76/node_modules/openai/lib/AbstractChatCompletionRunner.js +1 -1
  211. package/dist/src/node_modules/.pnpm/openai@6.39.0_ws@8.21.0_zod@3.25.76/node_modules/openai/lib/Util.js +1 -1
  212. package/dist/src/node_modules/.pnpm/openai@6.39.0_ws@8.21.0_zod@3.25.76/node_modules/openai/lib/chatCompletionUtils.js +1 -1
  213. package/dist/src/node_modules/.pnpm/openai@6.39.0_ws@8.21.0_zod@3.25.76/node_modules/openai/version.js +1 -1
  214. package/dist/src/node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/Options.js +1 -1
  215. package/dist/src/node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/Refs.js +1 -1
  216. package/dist/src/node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/getRelativePath.js +1 -1
  217. package/dist/src/node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parseDef.js +1 -1
  218. package/dist/src/node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/catch.js +1 -1
  219. package/dist/src/node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/date.js +1 -1
  220. package/dist/src/node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js +1 -1
  221. package/dist/src/node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/optional.js +1 -1
  222. package/dist/src/node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js +1 -1
  223. package/dist/src/node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js +1 -1
  224. package/dist/src/node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/string.js +1 -1
  225. package/dist/src/node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/union.js +1 -1
  226. package/dist/src/node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/selectParser.js +1 -1
  227. package/dist/src/node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js +1 -1
  228. package/dist/src/node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/ZodError.js +1 -1
  229. package/dist/src/node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/errors.js +1 -1
  230. package/dist/src/node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js +1 -1
  231. package/dist/src/node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/util.js +1 -1
  232. package/dist/src/node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/locales/en.js +1 -1
  233. package/dist/src/node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/types.js +1 -1
  234. package/dist/src/packages/ash-scaffold/src/channels.js +2 -2
  235. package/dist/src/packages/ash-scaffold/src/module-files.js +1 -1
  236. package/dist/src/protocol/message.js +1 -1
  237. package/dist/src/protocol/routes.js +1 -1
  238. package/dist/src/public/channels/ash.js +2 -2
  239. package/dist/src/public/channels/auth.js +1 -1
  240. package/dist/src/public/channels/discord/api.js +1 -1
  241. package/dist/src/public/channels/discord/defaults.js +1 -1
  242. package/dist/src/public/channels/discord/discordChannel.js +1 -1
  243. package/dist/src/public/channels/discord/hitl.js +1 -1
  244. package/dist/src/public/channels/discord/inbound.js +1 -1
  245. package/dist/src/public/channels/discord/verify.js +1 -1
  246. package/dist/src/public/channels/discord/verifyInbound.js +1 -1
  247. package/dist/src/public/channels/slack/api.js +1 -1
  248. package/dist/src/public/channels/slack/attachments.js +1 -1
  249. package/dist/src/public/channels/slack/constants.js +1 -1
  250. package/dist/src/public/channels/slack/defaults.js +2 -2
  251. package/dist/src/public/channels/slack/hitl.js +1 -1
  252. package/dist/src/public/channels/slack/interactions.js +1 -1
  253. package/dist/src/public/channels/slack/limits.js +1 -1
  254. package/dist/src/public/channels/slack/mrkdwn.js +1 -1
  255. package/dist/src/public/channels/slack/slackChannel.js +1 -1
  256. package/dist/src/public/channels/slack/verify.js +1 -1
  257. package/dist/src/public/channels/teams/api.js +1 -1
  258. package/dist/src/public/channels/teams/attachments.js +1 -1
  259. package/dist/src/public/channels/teams/defaults.js +1 -1
  260. package/dist/src/public/channels/teams/hitl.js +1 -1
  261. package/dist/src/public/channels/teams/inbound.js +1 -1
  262. package/dist/src/public/channels/teams/limits.js +1 -1
  263. package/dist/src/public/channels/teams/teamsChannel.js +1 -1
  264. package/dist/src/public/channels/teams/verify.js +1 -1
  265. package/dist/src/public/channels/telegram/api.js +1 -1
  266. package/dist/src/public/channels/telegram/attachments.js +1 -1
  267. package/dist/src/public/channels/telegram/defaults.js +1 -1
  268. package/dist/src/public/channels/telegram/hitl.js +1 -1
  269. package/dist/src/public/channels/telegram/inbound.js +1 -1
  270. package/dist/src/public/channels/telegram/telegramChannel.js +1 -1
  271. package/dist/src/public/channels/telegram/verify.js +1 -1
  272. package/dist/src/public/channels/twilio/defaults.js +1 -1
  273. package/dist/src/public/channels/twilio/inbound.js +1 -1
  274. package/dist/src/public/channels/twilio/twilioChannel.js +1 -1
  275. package/dist/src/public/channels/twilio/verify.js +1 -1
  276. package/dist/src/public/channels/upload-policy.js +1 -1
  277. package/dist/src/public/definitions/channel.js +1 -1
  278. package/dist/src/public/definitions/tool.js +1 -1
  279. package/dist/src/public/next/index.js +1 -1
  280. package/dist/src/public/next/server.js +1 -1
  281. package/dist/src/public/next/vercel-json.js +1 -1
  282. package/dist/src/public/tool-result-narrowing.js +1 -1
  283. package/dist/src/public/tools/defaults.js +1 -1
  284. package/dist/src/react/use-ash-agent.js +1 -1
  285. package/dist/src/runtime/actions/types.js +1 -1
  286. package/dist/src/runtime/agent/bootstrap-model-utils.js +1 -1
  287. package/dist/src/runtime/agent/bootstrap-model.js +1 -1
  288. package/dist/src/runtime/agent/bootstrap.js +1 -1
  289. package/dist/src/runtime/agent/mock-model-adapter.js +1 -1
  290. package/dist/src/runtime/cache-key.js +1 -1
  291. package/dist/src/runtime/channels/registry.js +1 -1
  292. package/dist/src/runtime/connections/authorization-tokens.js +1 -1
  293. package/dist/src/runtime/connections/callback-route.js +1 -1
  294. package/dist/src/runtime/connections/principal-context.js +1 -1
  295. package/dist/src/runtime/connections/principal.js +1 -1
  296. package/dist/src/runtime/framework-channels/index.js +1 -1
  297. package/dist/src/runtime/framework-tools/ask-question.js +1 -1
  298. package/dist/src/runtime/framework-tools/bash.js +1 -1
  299. package/dist/src/runtime/framework-tools/connection-search.js +1 -1
  300. package/dist/src/runtime/framework-tools/file-state.js +1 -1
  301. package/dist/src/runtime/framework-tools/glob.js +1 -1
  302. package/dist/src/runtime/framework-tools/grep.js +1 -1
  303. package/dist/src/runtime/framework-tools/index.js +1 -1
  304. package/dist/src/runtime/framework-tools/pending-connection-tool-calls.js +1 -1
  305. package/dist/src/runtime/framework-tools/read-file.js +1 -1
  306. package/dist/src/runtime/framework-tools/skill.js +1 -1
  307. package/dist/src/runtime/framework-tools/todo.js +2 -2
  308. package/dist/src/runtime/framework-tools/web-fetch.js +1 -1
  309. package/dist/src/runtime/framework-tools/web-search.js +1 -1
  310. package/dist/src/runtime/framework-tools/write-file.js +1 -1
  311. package/dist/src/runtime/governance/auth/jwt-ecdsa.js +1 -1
  312. package/dist/src/runtime/governance/auth/oidc.js +1 -1
  313. package/dist/src/runtime/governance/auth/token-claims.js +1 -1
  314. package/dist/src/runtime/graph.js +1 -1
  315. package/dist/src/runtime/input/types.js +1 -1
  316. package/dist/src/runtime/loaders/bundled-artifacts.d.ts +12 -0
  317. package/dist/src/runtime/loaders/bundled-artifacts.js +1 -1
  318. package/dist/src/runtime/loaders/compile-metadata.js +1 -1
  319. package/dist/src/runtime/loaders/manifest.js +1 -1
  320. package/dist/src/runtime/loaders/module-map.js +1 -1
  321. package/dist/src/runtime/prompt/compose.js +2 -2
  322. package/dist/src/runtime/prompt/connections.js +1 -1
  323. package/dist/src/runtime/resolve-agent-graph.js +1 -1
  324. package/dist/src/runtime/resolve-hook.js +1 -1
  325. package/dist/src/runtime/sandbox/keys.js +1 -1
  326. package/dist/src/runtime/sandbox/registry.js +1 -1
  327. package/dist/src/runtime/schedules/register.js +1 -1
  328. package/dist/src/runtime/session-callback-route.js +1 -1
  329. package/dist/src/runtime/sessions/auth.js +1 -1
  330. package/dist/src/runtime/sessions/compiled-agent-cache.js +1 -1
  331. package/dist/src/runtime/sessions/runtime-context-keys.d.ts +11 -0
  332. package/dist/src/runtime/sessions/runtime-context-keys.js +1 -0
  333. package/dist/src/runtime/sessions/runtime-session.js +1 -1
  334. package/dist/src/runtime/skills/fragment-context.js +1 -1
  335. package/dist/src/runtime/skills/sandbox-access.js +1 -1
  336. package/dist/src/runtime/subagents/registry.js +1 -1
  337. package/dist/src/runtime/workspace/types.js +1 -1
  338. package/dist/src/services/dev-client/request-headers.js +1 -1
  339. package/dist/src/services/dev-client/vercel-auth-error.js +1 -1
  340. package/dist/src/shared/json-schemas.js +1 -1
  341. package/dist/src/shared/json.js +1 -1
  342. package/dist/src/shared/skill-package.js +1 -1
  343. package/package.json +1 -1
  344. package/dist/src/context/seed-keys.d.ts +0 -39
  345. package/dist/src/context/seed-keys.js +0 -1
@@ -1 +1 @@
1
- import{ZodParsedType,getParsedType,util}from"./helpers/util.js";import{ZodError,ZodIssueCode}from"./ZodError.js";import errorMap from"./locales/en.js";import{getErrorMap}from"./errors.js";import{DIRTY,INVALID,OK,ParseStatus,addIssueToContext,isAborted,isAsync,isDirty,isValid,makeIssue}from"./helpers/parseUtil.js";import{errorUtil}from"./helpers/errorUtil.js";var ParseInputLazyPath=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},handleResult=(e,t)=>{if(isValid(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){if(this._error)return this._error;let t=new ZodError(e.common.issues);return this._error=t,this._error}}};function processCreateParams(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var ZodType=class{get description(){return this._def.description}_getType(e){return getParsedType(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(isAsync(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)};return handleResult(r,this._parseSync({data:e,path:r.path,parent:r}))}"~validate"(e){let n={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)};if(!this[`~standard`].async)try{let t=this._parseSync({data:e,path:[],parent:n});return isValid(t)?{value:t.value}:{issues:n.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(e=>isValid(e)?{value:e.value}:{issues:n.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},i=this._parse({data:e,path:r.path,parent:r});return handleResult(r,await(isAsync(i)?i:Promise.resolve(i)))}refine(e,t){let getIssueProperties=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,n)=>{let r=e(t),setError=()=>n.addIssue({code:ZodIssueCode.custom,...getIssueProperties(t)});return typeof Promise<`u`&&r instanceof Promise?r.then(e=>e?!0:(setError(),!1)):r?!0:(setError(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this)}promise(){return ZodPromise.create(this,this._def)}or(e){return ZodUnion.create([this,e],this._def)}and(e){return ZodIntersection.create(this,e,this._def)}transform(e){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:t,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:t,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ZodPipeline.create(this,e)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_emojiRegex=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,emojiRegex,ipv4Regex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4CidrRegex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6Regex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ipv6CidrRegex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegexSource=`((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`,dateRegex=RegExp(`^${dateRegexSource}$`);function timeRegexSource(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function timeRegex(e){return RegExp(`^${timeRegexSource(e)}$`)}function datetimeRegex(e){let t=`${dateRegexSource}T${timeRegexSource(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function isValidIP(e,t){return!!((t===`v4`||!t)&&ipv4Regex.test(e)||(t===`v6`||!t)&&ipv6Regex.test(e))}function isValidJWT(e,t){if(!jwtRegex.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function isValidCidr(e,t){return!!((t===`v4`||!t)&&ipv4CidrRegex.test(e)||(t===`v6`||!t)&&ipv6CidrRegex.test(e))}var ZodString=class ZodString extends ZodType{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==ZodParsedType.string){let n=this._getOrReturnCtx(t);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:n.parsedType}),INVALID}let r=new ParseStatus,a;for(let e of this._def.checks)if(e.kind===`min`)t.data.length<e.value&&(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{code:ZodIssueCode.too_small,minimum:e.value,type:`string`,inclusive:!0,exact:!1,message:e.message}),r.dirty());else if(e.kind===`max`)t.data.length>e.value&&(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{code:ZodIssueCode.too_big,maximum:e.value,type:`string`,inclusive:!0,exact:!1,message:e.message}),r.dirty());else if(e.kind===`length`){let n=t.data.length>e.value,o=t.data.length<e.value;(n||o)&&(a=this._getOrReturnCtx(t,a),n?addIssueToContext(a,{code:ZodIssueCode.too_big,maximum:e.value,type:`string`,inclusive:!0,exact:!0,message:e.message}):o&&addIssueToContext(a,{code:ZodIssueCode.too_small,minimum:e.value,type:`string`,inclusive:!0,exact:!0,message:e.message}),r.dirty())}else if(e.kind===`email`)emailRegex.test(t.data)||(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{validation:`email`,code:ZodIssueCode.invalid_string,message:e.message}),r.dirty());else if(e.kind===`emoji`)emojiRegex||=new RegExp(_emojiRegex,`u`),emojiRegex.test(t.data)||(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{validation:`emoji`,code:ZodIssueCode.invalid_string,message:e.message}),r.dirty());else if(e.kind===`uuid`)uuidRegex.test(t.data)||(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{validation:`uuid`,code:ZodIssueCode.invalid_string,message:e.message}),r.dirty());else if(e.kind===`nanoid`)nanoidRegex.test(t.data)||(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{validation:`nanoid`,code:ZodIssueCode.invalid_string,message:e.message}),r.dirty());else if(e.kind===`cuid`)cuidRegex.test(t.data)||(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{validation:`cuid`,code:ZodIssueCode.invalid_string,message:e.message}),r.dirty());else if(e.kind===`cuid2`)cuid2Regex.test(t.data)||(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{validation:`cuid2`,code:ZodIssueCode.invalid_string,message:e.message}),r.dirty());else if(e.kind===`ulid`)ulidRegex.test(t.data)||(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{validation:`ulid`,code:ZodIssueCode.invalid_string,message:e.message}),r.dirty());else if(e.kind===`url`)try{new URL(t.data)}catch{a=this._getOrReturnCtx(t,a),addIssueToContext(a,{validation:`url`,code:ZodIssueCode.invalid_string,message:e.message}),r.dirty()}else e.kind===`regex`?(e.regex.lastIndex=0,e.regex.test(t.data)||(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{validation:`regex`,code:ZodIssueCode.invalid_string,message:e.message}),r.dirty())):e.kind===`trim`?t.data=t.data.trim():e.kind===`includes`?t.data.includes(e.value,e.position)||(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{code:ZodIssueCode.invalid_string,validation:{includes:e.value,position:e.position},message:e.message}),r.dirty()):e.kind===`toLowerCase`?t.data=t.data.toLowerCase():e.kind===`toUpperCase`?t.data=t.data.toUpperCase():e.kind===`startsWith`?t.data.startsWith(e.value)||(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{code:ZodIssueCode.invalid_string,validation:{startsWith:e.value},message:e.message}),r.dirty()):e.kind===`endsWith`?t.data.endsWith(e.value)||(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{code:ZodIssueCode.invalid_string,validation:{endsWith:e.value},message:e.message}),r.dirty()):e.kind===`datetime`?datetimeRegex(e).test(t.data)||(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{code:ZodIssueCode.invalid_string,validation:`datetime`,message:e.message}),r.dirty()):e.kind===`date`?dateRegex.test(t.data)||(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{code:ZodIssueCode.invalid_string,validation:`date`,message:e.message}),r.dirty()):e.kind===`time`?timeRegex(e).test(t.data)||(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{code:ZodIssueCode.invalid_string,validation:`time`,message:e.message}),r.dirty()):e.kind===`duration`?durationRegex.test(t.data)||(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{validation:`duration`,code:ZodIssueCode.invalid_string,message:e.message}),r.dirty()):e.kind===`ip`?isValidIP(t.data,e.version)||(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{validation:`ip`,code:ZodIssueCode.invalid_string,message:e.message}),r.dirty()):e.kind===`jwt`?isValidJWT(t.data,e.alg)||(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{validation:`jwt`,code:ZodIssueCode.invalid_string,message:e.message}),r.dirty()):e.kind===`cidr`?isValidCidr(t.data,e.version)||(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{validation:`cidr`,code:ZodIssueCode.invalid_string,message:e.message}),r.dirty()):e.kind===`base64`?base64Regex.test(t.data)||(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{validation:`base64`,code:ZodIssueCode.invalid_string,message:e.message}),r.dirty()):e.kind===`base64url`?base64urlRegex.test(t.data)||(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{validation:`base64url`,code:ZodIssueCode.invalid_string,message:e.message}),r.dirty()):util.assertNever(e);return{status:r.value,value:t.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(n)})}_addCheck(e){return new ZodString({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:`email`,...errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...errorUtil.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...errorUtil.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...errorUtil.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...errorUtil.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...errorUtil.errToObj(t)})}nonempty(e){return this.min(1,errorUtil.errToObj(e))}trim(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};ZodString.create=e=>new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:e?.coerce??!1,...processCreateParams(e)});function floatSafeRemainder(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}var ZodNumber=class ZodNumber extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==ZodParsedType.number){let n=this._getOrReturnCtx(t);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:n.parsedType}),INVALID}let r,a=new ParseStatus;for(let e of this._def.checks)e.kind===`int`?util.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:`integer`,received:`float`,message:e.message}),a.dirty()):e.kind===`min`?(e.inclusive?t.data<e.value:t.data<=e.value)&&(r=this._getOrReturnCtx(t,r),addIssueToContext(r,{code:ZodIssueCode.too_small,minimum:e.value,type:`number`,inclusive:e.inclusive,exact:!1,message:e.message}),a.dirty()):e.kind===`max`?(e.inclusive?t.data>e.value:t.data>=e.value)&&(r=this._getOrReturnCtx(t,r),addIssueToContext(r,{code:ZodIssueCode.too_big,maximum:e.value,type:`number`,inclusive:e.inclusive,exact:!1,message:e.message}),a.dirty()):e.kind===`multipleOf`?floatSafeRemainder(t.data,e.value)!==0&&(r=this._getOrReturnCtx(t,r),addIssueToContext(r,{code:ZodIssueCode.not_multiple_of,multipleOf:e.value,message:e.message}),a.dirty()):e.kind===`finite`?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),addIssueToContext(r,{code:ZodIssueCode.not_finite,message:e.message}),a.dirty()):util.assertNever(e);return{status:a.value,value:t.data}}gte(e,t){return this.setLimit(`min`,e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,errorUtil.toString(t))}setLimit(e,t,n,r){return new ZodNumber({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:errorUtil.toString(r)}]})}_addCheck(e){return new ZodNumber({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:`int`,message:errorUtil.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:errorUtil.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:errorUtil.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:errorUtil.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:errorUtil.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&util.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks){if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}};ZodNumber.create=e=>new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:e?.coerce||!1,...processCreateParams(e)});var ZodBigInt=class ZodBigInt extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==ZodParsedType.bigint)return this._getInvalidInput(t);let r,a=new ParseStatus;for(let e of this._def.checks)e.kind===`min`?(e.inclusive?t.data<e.value:t.data<=e.value)&&(r=this._getOrReturnCtx(t,r),addIssueToContext(r,{code:ZodIssueCode.too_small,type:`bigint`,minimum:e.value,inclusive:e.inclusive,message:e.message}),a.dirty()):e.kind===`max`?(e.inclusive?t.data>e.value:t.data>=e.value)&&(r=this._getOrReturnCtx(t,r),addIssueToContext(r,{code:ZodIssueCode.too_big,type:`bigint`,maximum:e.value,inclusive:e.inclusive,message:e.message}),a.dirty()):e.kind===`multipleOf`?t.data%e.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),addIssueToContext(r,{code:ZodIssueCode.not_multiple_of,multipleOf:e.value,message:e.message}),a.dirty()):util.assertNever(e);return{status:a.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:n.parsedType}),INVALID}gte(e,t){return this.setLimit(`min`,e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,errorUtil.toString(t))}setLimit(e,t,n,r){return new ZodBigInt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:errorUtil.toString(r)}]})}_addCheck(e){return new ZodBigInt({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:errorUtil.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};ZodBigInt.create=e=>new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:e?.coerce??!1,...processCreateParams(e)});var ZodBoolean=class extends ZodType{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==ZodParsedType.boolean){let n=this._getOrReturnCtx(t);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:n.parsedType}),INVALID}return OK(t.data)}};ZodBoolean.create=e=>new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:e?.coerce||!1,...processCreateParams(e)});var ZodDate=class ZodDate extends ZodType{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==ZodParsedType.date){let n=this._getOrReturnCtx(t);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:n.parsedType}),INVALID}if(Number.isNaN(t.data.getTime()))return addIssueToContext(this._getOrReturnCtx(t),{code:ZodIssueCode.invalid_date}),INVALID;let r=new ParseStatus,a;for(let e of this._def.checks)e.kind===`min`?t.data.getTime()<e.value&&(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{code:ZodIssueCode.too_small,message:e.message,inclusive:!0,exact:!1,minimum:e.value,type:`date`}),r.dirty()):e.kind===`max`?t.data.getTime()>e.value&&(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{code:ZodIssueCode.too_big,message:e.message,inclusive:!0,exact:!1,maximum:e.value,type:`date`}),r.dirty()):util.assertNever(e);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(e){return new ZodDate({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:errorUtil.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};ZodDate.create=e=>new ZodDate({checks:[],coerce:e?.coerce||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(e)});var ZodSymbol=class extends ZodType{_parse(t){if(this._getType(t)!==ZodParsedType.symbol){let n=this._getOrReturnCtx(t);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:n.parsedType}),INVALID}return OK(t.data)}};ZodSymbol.create=e=>new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(e)});var ZodUndefined=class extends ZodType{_parse(t){if(this._getType(t)!==ZodParsedType.undefined){let n=this._getOrReturnCtx(t);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:n.parsedType}),INVALID}return OK(t.data)}};ZodUndefined.create=e=>new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(e)});var ZodNull=class extends ZodType{_parse(t){if(this._getType(t)!==ZodParsedType.null){let n=this._getOrReturnCtx(t);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:n.parsedType}),INVALID}return OK(t.data)}};ZodNull.create=e=>new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(e)});var ZodAny=class extends ZodType{constructor(){super(...arguments),this._any=!0}_parse(e){return OK(e.data)}};ZodAny.create=e=>new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(e)});var ZodUnknown=class extends ZodType{constructor(){super(...arguments),this._unknown=!0}_parse(e){return OK(e.data)}};ZodUnknown.create=e=>new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(e)});var ZodNever=class extends ZodType{_parse(t){let n=this._getOrReturnCtx(t);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:n.parsedType}),INVALID}};ZodNever.create=e=>new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(e)});var ZodVoid=class extends ZodType{_parse(t){if(this._getType(t)!==ZodParsedType.undefined){let n=this._getOrReturnCtx(t);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:n.parsedType}),INVALID}return OK(t.data)}};ZodVoid.create=e=>new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(e)});var ZodArray=class ZodArray extends ZodType{_parse(t){let{ctx:n,status:r}=this._processInputParams(t),a=this._def;if(n.parsedType!==ZodParsedType.array)return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:n.parsedType}),INVALID;if(a.exactLength!==null){let e=n.data.length>a.exactLength.value,t=n.data.length<a.exactLength.value;(e||t)&&(addIssueToContext(n,{code:e?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:t?a.exactLength.value:void 0,maximum:e?a.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:a.exactLength.message}),r.dirty())}if(a.minLength!==null&&n.data.length<a.minLength.value&&(addIssueToContext(n,{code:ZodIssueCode.too_small,minimum:a.minLength.value,type:`array`,inclusive:!0,exact:!1,message:a.minLength.message}),r.dirty()),a.maxLength!==null&&n.data.length>a.maxLength.value&&(addIssueToContext(n,{code:ZodIssueCode.too_big,maximum:a.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:a.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((e,t)=>a.type._parseAsync(new ParseInputLazyPath(n,e,n.path,t)))).then(e=>ParseStatus.mergeArray(r,e));let o=[...n.data].map((e,t)=>a.type._parseSync(new ParseInputLazyPath(n,e,n.path,t)));return ParseStatus.mergeArray(r,o)}get element(){return this._def.type}min(e,t){return new ZodArray({...this._def,minLength:{value:e,message:errorUtil.toString(t)}})}max(e,t){return new ZodArray({...this._def,maxLength:{value:e,message:errorUtil.toString(t)}})}length(e,t){return new ZodArray({...this._def,exactLength:{value:e,message:errorUtil.toString(t)}})}nonempty(e){return this.min(1,e)}};ZodArray.create=(e,t)=>new ZodArray({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(t)});function deepPartialify(e){if(e instanceof ZodObject){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=ZodOptional.create(deepPartialify(r))}return new ZodObject({...e._def,shape:()=>t})}else if(e instanceof ZodArray)return new ZodArray({...e._def,type:deepPartialify(e.element)});else if(e instanceof ZodOptional)return ZodOptional.create(deepPartialify(e.unwrap()));else if(e instanceof ZodNullable)return ZodNullable.create(deepPartialify(e.unwrap()));else if(e instanceof ZodTuple)return ZodTuple.create(e.items.map(e=>deepPartialify(e)));else return e}var ZodObject=class ZodObject extends ZodType{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=util.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(t){if(this._getType(t)!==ZodParsedType.object){let n=this._getOrReturnCtx(t);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:n.parsedType}),INVALID}let{status:n,ctx:r}=this._processInputParams(t),{shape:a,keys:o}=this._getCached(),s=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys===`strip`))for(let e in r.data)o.includes(e)||s.push(e);let c=[];for(let e of o){let t=a[e],n=r.data[e];c.push({key:{status:`valid`,value:e},value:t._parse(new ParseInputLazyPath(r,n,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof ZodNever){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of s)c.push({key:{status:`valid`,value:e},value:{status:`valid`,value:r.data[e]}});else if(e===`strict`)s.length>0&&(addIssueToContext(r,{code:ZodIssueCode.unrecognized_keys,keys:s}),n.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of s){let n=r.data[t];c.push({key:{status:`valid`,value:t},value:e._parse(new ParseInputLazyPath(r,n,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of c){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>ParseStatus.mergeObjectSync(n,e)):ParseStatus.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return errorUtil.errToObj,new ZodObject({...this._def,unknownKeys:`strict`,...e===void 0?{}:{errorMap:(t,n)=>{let r=this._def.errorMap?.(t,n).message??n.defaultError;return t.code===`unrecognized_keys`?{message:errorUtil.errToObj(e).message??r}:{message:r}}}})}strip(){return new ZodObject({...this._def,unknownKeys:`strip`})}passthrough(){return new ZodObject({...this._def,unknownKeys:`passthrough`})}extend(e){return new ZodObject({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ZodObject({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ZodObject({...this._def,catchall:e})}pick(e){let t={};for(let r of util.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new ZodObject({...this._def,shape:()=>t})}omit(e){let t={};for(let r of util.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new ZodObject({...this._def,shape:()=>t})}deepPartial(){return deepPartialify(this)}partial(e){let t={};for(let r of util.objectKeys(this.shape)){let n=this.shape[r];e&&!e[r]?t[r]=n:t[r]=n.optional()}return new ZodObject({...this._def,shape:()=>t})}required(e){let t={};for(let r of util.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof ZodOptional;)e=e._def.innerType;t[r]=e}return new ZodObject({...this._def,shape:()=>t})}keyof(){return createZodEnum(util.objectKeys(this.shape))}};ZodObject.create=(e,t)=>new ZodObject({shape:()=>e,unknownKeys:`strip`,catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)}),ZodObject.strictCreate=(e,t)=>new ZodObject({shape:()=>e,unknownKeys:`strict`,catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)}),ZodObject.lazycreate=(e,t)=>new ZodObject({shape:e,unknownKeys:`strip`,catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)});var ZodUnion=class extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function handleResults(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new ZodError(e.ctx.common.issues));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:n}),INVALID}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(handleResults);{let e,a=[];for(let r of n){let n={...t,common:{...t.common,issues:[]},parent:null},i=r._parseSync({data:t.data,path:t.path,parent:n});if(i.status===`valid`)return i;i.status===`dirty`&&!e&&(e={result:i,ctx:n}),n.common.issues.length&&a.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let o=a.map(e=>new ZodError(e));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:o}),INVALID}}get options(){return this._def.options}};ZodUnion.create=(e,t)=>new ZodUnion({options:e,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(t)});var getDiscriminator=e=>e instanceof ZodLazy?getDiscriminator(e.schema):e instanceof ZodEffects?getDiscriminator(e.innerType()):e instanceof ZodLiteral?[e.value]:e instanceof ZodEnum?e.options:e instanceof ZodNativeEnum?util.objectValues(e.enum):e instanceof ZodDefault?getDiscriminator(e._def.innerType):e instanceof ZodUndefined?[void 0]:e instanceof ZodNull?[null]:e instanceof ZodOptional?[void 0,...getDiscriminator(e.unwrap())]:e instanceof ZodNullable?[null,...getDiscriminator(e.unwrap())]:e instanceof ZodBranded||e instanceof ZodReadonly?getDiscriminator(e.unwrap()):e instanceof ZodCatch?getDiscriminator(e._def.innerType):[],ZodDiscriminatedUnion=class ZodDiscriminatedUnion extends ZodType{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==ZodParsedType.object)return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:n.parsedType}),INVALID;let r=this.discriminator,a=n.data[r],o=this.optionsMap.get(a);return o?n.common.async?o._parseAsync({data:n.data,path:n.path,parent:n}):o._parseSync({data:n.data,path:n.path,parent:n}):(addIssueToContext(n,{code:ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let r=new Map;for(let n of t){let t=getDiscriminator(n.shape[e]);if(!t.length)throw Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let i of t){if(r.has(i))throw Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);r.set(i,n)}}return new ZodDiscriminatedUnion({typeName:ZodFirstPartyTypeKind.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:r,...processCreateParams(n)})}};function mergeValues(r,i){let a=getParsedType(r),o=getParsedType(i);if(r===i)return{valid:!0,data:r};if(a===ZodParsedType.object&&o===ZodParsedType.object){let e=util.objectKeys(i),t=util.objectKeys(r).filter(t=>e.indexOf(t)!==-1),a={...r,...i};for(let e of t){let t=mergeValues(r[e],i[e]);if(!t.valid)return{valid:!1};a[e]=t.data}return{valid:!0,data:a}}else if(a===ZodParsedType.array&&o===ZodParsedType.array){if(r.length!==i.length)return{valid:!1};let e=[];for(let t=0;t<r.length;t++){let n=r[t],a=i[t],o=mergeValues(n,a);if(!o.valid)return{valid:!1};e.push(o.data)}return{valid:!0,data:e}}else if(a===ZodParsedType.date&&o===ZodParsedType.date&&+r==+i)return{valid:!0,data:r};else return{valid:!1}}var ZodIntersection=class extends ZodType{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),handleParsed=(e,r)=>{if(isAborted(e)||isAborted(r))return INVALID;let a=mergeValues(e.value,r.value);return a.valid?((isDirty(e)||isDirty(r))&&t.dirty(),{status:t.value,value:a.data}):(addIssueToContext(n,{code:ZodIssueCode.invalid_intersection_types}),INVALID)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>handleParsed(e,t)):handleParsed(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};ZodIntersection.create=(e,t,n)=>new ZodIntersection({left:e,right:t,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams(n)});var ZodTuple=class ZodTuple extends ZodType{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==ZodParsedType.array)return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:r.parsedType}),INVALID;if(r.data.length<this._def.items.length)return addIssueToContext(r,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),INVALID;!this._def.rest&&r.data.length>this._def.items.length&&(addIssueToContext(r,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),n.dirty());let a=[...r.data].map((e,t)=>{let n=this._def.items[t]||this._def.rest;return n?n._parse(new ParseInputLazyPath(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(a).then(e=>ParseStatus.mergeArray(n,e)):ParseStatus.mergeArray(n,a)}get items(){return this._def.items}rest(e){return new ZodTuple({...this._def,rest:e})}};ZodTuple.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new ZodTuple({items:e,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(t)})};var ZodRecord=class ZodRecord extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==ZodParsedType.object)return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:r.parsedType}),INVALID;let a=[],o=this._def.keyType,s=this._def.valueType;for(let e in r.data)a.push({key:o._parse(new ParseInputLazyPath(r,e,r.path,e)),value:s._parse(new ParseInputLazyPath(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?ParseStatus.mergeObjectAsync(n,a):ParseStatus.mergeObjectSync(n,a)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof ZodType?new ZodRecord({keyType:e,valueType:t,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(n)}):new ZodRecord({keyType:ZodString.create(),valueType:e,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(t)})}},ZodMap=class extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==ZodParsedType.map)return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:r.parsedType}),INVALID;let a=this._def.keyType,o=this._def.valueType,s=[...r.data.entries()].map(([e,t],n)=>({key:a._parse(new ParseInputLazyPath(r,e,r.path,[n,`key`])),value:o._parse(new ParseInputLazyPath(r,t,r.path,[n,`value`]))}));if(r.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let t of s){let r=await t.key,i=await t.value;if(r.status===`aborted`||i.status===`aborted`)return INVALID;(r.status===`dirty`||i.status===`dirty`)&&n.dirty(),e.set(r.value,i.value)}return{status:n.value,value:e}})}else{let e=new Map;for(let t of s){let r=t.key,i=t.value;if(r.status===`aborted`||i.status===`aborted`)return INVALID;(r.status===`dirty`||i.status===`dirty`)&&n.dirty(),e.set(r.value,i.value)}return{status:n.value,value:e}}}};ZodMap.create=(e,t,n)=>new ZodMap({valueType:t,keyType:e,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams(n)});var ZodSet=class ZodSet extends ZodType{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==ZodParsedType.set)return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:r.parsedType}),INVALID;let a=this._def;a.minSize!==null&&r.data.size<a.minSize.value&&(addIssueToContext(r,{code:ZodIssueCode.too_small,minimum:a.minSize.value,type:`set`,inclusive:!0,exact:!1,message:a.minSize.message}),n.dirty()),a.maxSize!==null&&r.data.size>a.maxSize.value&&(addIssueToContext(r,{code:ZodIssueCode.too_big,maximum:a.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:a.maxSize.message}),n.dirty());let o=this._def.valueType;function finalizeSet(e){let t=new Set;for(let r of e){if(r.status===`aborted`)return INVALID;r.status===`dirty`&&n.dirty(),t.add(r.value)}return{status:n.value,value:t}}let s=[...r.data.values()].map((e,t)=>o._parse(new ParseInputLazyPath(r,e,r.path,t)));return r.common.async?Promise.all(s).then(e=>finalizeSet(e)):finalizeSet(s)}min(e,t){return new ZodSet({...this._def,minSize:{value:e,message:errorUtil.toString(t)}})}max(e,t){return new ZodSet({...this._def,maxSize:{value:e,message:errorUtil.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};ZodSet.create=(e,t)=>new ZodSet({valueType:e,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(t)});var ZodFunction=class ZodFunction extends ZodType{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==ZodParsedType.function)return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.function,received:n.parsedType}),INVALID;function makeArgsIssue(e,t){return makeIssue({data:e,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,getErrorMap(),errorMap].filter(e=>!!e),issueData:{code:ZodIssueCode.invalid_arguments,argumentsError:t}})}function makeReturnsIssue(e,t){return makeIssue({data:e,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,getErrorMap(),errorMap].filter(e=>!!e),issueData:{code:ZodIssueCode.invalid_return_type,returnTypeError:t}})}let s={errorMap:n.common.contextualErrorMap},l=n.data;if(this._def.returns instanceof ZodPromise){let e=this;return OK(async function(...t){let n=new ZodError([]),i=await e._def.args.parseAsync(t,s).catch(e=>{throw n.addIssue(makeArgsIssue(t,e)),n}),a=await Reflect.apply(l,this,i);return await e._def.returns._def.type.parseAsync(a,s).catch(e=>{throw n.addIssue(makeReturnsIssue(a,e)),n})})}else{let e=this;return OK(function(...t){let n=e._def.args.safeParse(t,s);if(!n.success)throw new ZodError([makeArgsIssue(t,n.error)]);let i=Reflect.apply(l,this,n.data),a=e._def.returns.safeParse(i,s);if(!a.success)throw new ZodError([makeReturnsIssue(i,a.error)]);return a.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new ZodFunction({...this._def,args:ZodTuple.create(e).rest(ZodUnknown.create())})}returns(e){return new ZodFunction({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new ZodFunction({args:e||ZodTuple.create([]).rest(ZodUnknown.create()),returns:t||ZodUnknown.create(),typeName:ZodFirstPartyTypeKind.ZodFunction,...processCreateParams(n)})}},ZodLazy=class extends ZodType{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};ZodLazy.create=(e,t)=>new ZodLazy({getter:e,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(t)});var ZodLiteral=class extends ZodType{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:`valid`,value:e.data}}get value(){return this._def.value}};ZodLiteral.create=(e,t)=>new ZodLiteral({value:e,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(t)});function createZodEnum(e,t){return new ZodEnum({values:e,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(t)})}var ZodEnum=class ZodEnum extends ZodType{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),r=this._def.values;return addIssueToContext(t,{expected:util.joinValues(r),received:t.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_enum_value,options:n}),INVALID}return OK(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return ZodEnum.create(e,{...this._def,...t})}exclude(e,t=this._def){return ZodEnum.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}};ZodEnum.create=createZodEnum;var ZodNativeEnum=class extends ZodType{_parse(t){let r=util.getValidEnumValues(this._def.values),a=this._getOrReturnCtx(t);if(a.parsedType!==ZodParsedType.string&&a.parsedType!==ZodParsedType.number){let e=util.objectValues(r);return addIssueToContext(a,{expected:util.joinValues(e),received:a.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||=new Set(util.getValidEnumValues(this._def.values)),!this._cache.has(t.data)){let e=util.objectValues(r);return addIssueToContext(a,{received:a.data,code:ZodIssueCode.invalid_enum_value,options:e}),INVALID}return OK(t.data)}get enum(){return this._def.values}};ZodNativeEnum.create=(e,t)=>new ZodNativeEnum({values:e,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(t)});var ZodPromise=class extends ZodType{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);return n.parsedType!==ZodParsedType.promise&&n.common.async===!1?(addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:n.parsedType}),INVALID):OK((n.parsedType===ZodParsedType.promise?n.data:Promise.resolve(n.data)).then(e=>this._def.type.parseAsync(e,{path:n.path,errorMap:n.common.contextualErrorMap})))}};ZodPromise.create=(e,t)=>new ZodPromise({type:e,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(t)});var ZodEffects=class extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),i=this._def.effect||null,a={addIssue:e=>{addIssueToContext(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(a.addIssue=a.addIssue.bind(a),i.type===`preprocess`){let e=i.transform(r.data,a);if(r.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return INVALID;let n=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return n.status===`aborted`?INVALID:n.status===`dirty`||t.value===`dirty`?DIRTY(n.value):n});{if(t.value===`aborted`)return INVALID;let n=this._def.schema._parseSync({data:e,path:r.path,parent:r});return n.status===`aborted`?INVALID:n.status===`dirty`||t.value===`dirty`?DIRTY(n.value):n}}if(i.type===`refinement`){let executeRefinement=e=>{let t=i.refinement(e,a);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(r.common.async===!1){let e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return e.status===`aborted`?INVALID:(e.status===`dirty`&&t.dirty(),executeRefinement(e.value),{status:t.value,value:e.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>e.status===`aborted`?INVALID:(e.status===`dirty`&&t.dirty(),executeRefinement(e.value).then(()=>({status:t.value,value:e.value}))))}if(i.type===`transform`)if(r.common.async===!1){let e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!isValid(e))return INVALID;let n=i.transform(e.value,a);if(n instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:n}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>isValid(e)?Promise.resolve(i.transform(e.value,a)).then(e=>({status:t.value,value:e})):INVALID);util.assertNever(i)}};ZodEffects.create=(e,t,n)=>new ZodEffects({schema:e,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:t,...processCreateParams(n)}),ZodEffects.createWithPreprocess=(e,t,n)=>new ZodEffects({schema:t,effect:{type:`preprocess`,transform:e},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams(n)});var ZodOptional=class extends ZodType{_parse(t){return this._getType(t)===ZodParsedType.undefined?OK(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};ZodOptional.create=(e,t)=>new ZodOptional({innerType:e,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(t)});var ZodNullable=class extends ZodType{_parse(t){return this._getType(t)===ZodParsedType.null?OK(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};ZodNullable.create=(e,t)=>new ZodNullable({innerType:e,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(t)});var ZodDefault=class extends ZodType{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===ZodParsedType.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};ZodDefault.create=(e,t)=>new ZodDefault({innerType:e,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...processCreateParams(t)});var ZodCatch=class extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return isAsync(i)?i.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new ZodError(n.common.issues)},input:n.data})})):{status:`valid`,value:i.status===`valid`?i.value:this._def.catchValue({get error(){return new ZodError(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};ZodCatch.create=(e,t)=>new ZodCatch({innerType:e,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...processCreateParams(t)});var ZodNaN=class extends ZodType{_parse(t){if(this._getType(t)!==ZodParsedType.nan){let n=this._getOrReturnCtx(t);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:n.parsedType}),INVALID}return{status:`valid`,value:t.data}}};ZodNaN.create=e=>new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(e)});var BRAND=Symbol(`zod_brand`),ZodBranded=class extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},ZodPipeline=class ZodPipeline extends ZodType{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?INVALID:e.status===`dirty`?(t.dirty(),DIRTY(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?INVALID:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(e,t){return new ZodPipeline({in:e,out:t,typeName:ZodFirstPartyTypeKind.ZodPipeline})}},ZodReadonly=class extends ZodType{_parse(e){let t=this._def.innerType._parse(e),freeze=e=>(isValid(e)&&(e.value=Object.freeze(e.value)),e);return isAsync(t)?t.then(e=>freeze(e)):freeze(t)}unwrap(){return this._def.innerType}};ZodReadonly.create=(e,t)=>new ZodReadonly({innerType:e,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(t)});function cleanParams(e,t){let n=typeof e==`function`?e(t):typeof e==`string`?{message:e}:e;return typeof n==`string`?{message:n}:n}function custom(e,t={},n){return e?ZodAny.create().superRefine((r,i)=>{let a=e(r);if(a instanceof Promise)return a.then(e=>{if(!e){let e=cleanParams(t,r),a=e.fatal??n??!0;i.addIssue({code:`custom`,...e,fatal:a})}});if(!a){let e=cleanParams(t,r),a=e.fatal??n??!0;i.addIssue({code:`custom`,...e,fatal:a})}}):ZodAny.create()}var late={object:ZodObject.lazycreate},ZodFirstPartyTypeKind;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(ZodFirstPartyTypeKind||={});var instanceOfType=(e,t={message:`Input not instance of ${e.name}`})=>custom(t=>t instanceof e,t),stringType=ZodString.create,numberType=ZodNumber.create,nanType=ZodNaN.create,bigIntType=ZodBigInt.create,booleanType=ZodBoolean.create,dateType=ZodDate.create,symbolType=ZodSymbol.create,undefinedType=ZodUndefined.create,nullType=ZodNull.create,anyType=ZodAny.create,unknownType=ZodUnknown.create,neverType=ZodNever.create,voidType=ZodVoid.create,arrayType=ZodArray.create,objectType=ZodObject.create,strictObjectType=ZodObject.strictCreate,unionType=ZodUnion.create,discriminatedUnionType=ZodDiscriminatedUnion.create,intersectionType=ZodIntersection.create,tupleType=ZodTuple.create,recordType=ZodRecord.create,mapType=ZodMap.create,setType=ZodSet.create,functionType=ZodFunction.create,lazyType=ZodLazy.create,literalType=ZodLiteral.create,enumType=ZodEnum.create,nativeEnumType=ZodNativeEnum.create,promiseType=ZodPromise.create,effectsType=ZodEffects.create,optionalType=ZodOptional.create,nullableType=ZodNullable.create,preprocessType=ZodEffects.createWithPreprocess,pipelineType=ZodPipeline.create,ostring=()=>stringType().optional(),onumber=()=>numberType().optional(),oboolean=()=>booleanType().optional(),coerce={string:(e=>ZodString.create({...e,coerce:!0})),number:(e=>ZodNumber.create({...e,coerce:!0})),boolean:(e=>ZodBoolean.create({...e,coerce:!0})),bigint:(e=>ZodBigInt.create({...e,coerce:!0})),date:(e=>ZodDate.create({...e,coerce:!0}))},NEVER=INVALID;export{BRAND,NEVER,ZodAny,ZodArray,ZodBigInt,ZodBoolean,ZodBranded,ZodCatch,ZodDate,ZodDefault,ZodDiscriminatedUnion,ZodEffects,ZodEnum,ZodFirstPartyTypeKind,ZodFunction,ZodIntersection,ZodLazy,ZodLiteral,ZodMap,ZodNaN,ZodNativeEnum,ZodNever,ZodNull,ZodNullable,ZodNumber,ZodObject,ZodOptional,ZodPipeline,ZodPromise,ZodReadonly,ZodRecord,ZodSet,ZodString,ZodSymbol,ZodTuple,ZodType,ZodUndefined,ZodUnion,ZodUnknown,ZodVoid,anyType,arrayType,bigIntType,booleanType,coerce,custom,dateType,datetimeRegex,discriminatedUnionType,effectsType,enumType,functionType,instanceOfType,intersectionType,late,lazyType,literalType,mapType,nanType,nativeEnumType,neverType,nullType,nullableType,numberType,objectType,oboolean,onumber,optionalType,ostring,pipelineType,preprocessType,promiseType,recordType,setType,strictObjectType,stringType,symbolType,tupleType,undefinedType,unionType,unknownType,voidType};
1
+ import{ZodParsedType,getParsedType,util}from"./helpers/util.js";import{ZodError,ZodIssueCode}from"./ZodError.js";import errorMap from"./locales/en.js";import{getErrorMap}from"./errors.js";import{DIRTY,INVALID,OK,ParseStatus,addIssueToContext,isAborted,isAsync,isDirty,isValid,makeIssue}from"./helpers/parseUtil.js";import{errorUtil}from"./helpers/errorUtil.js";var ParseInputLazyPath=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}};const handleResult=(e,t)=>{if(isValid(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){if(this._error)return this._error;let t=new ZodError(e.common.issues);return this._error=t,this._error}}};function processCreateParams(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var ZodType=class{get description(){return this._def.description}_getType(e){return getParsedType(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(isAsync(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)};return handleResult(r,this._parseSync({data:e,path:r.path,parent:r}))}"~validate"(e){let n={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)};if(!this[`~standard`].async)try{let t=this._parseSync({data:e,path:[],parent:n});return isValid(t)?{value:t.value}:{issues:n.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(e=>isValid(e)?{value:e.value}:{issues:n.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},i=this._parse({data:e,path:r.path,parent:r});return handleResult(r,await(isAsync(i)?i:Promise.resolve(i)))}refine(e,t){let getIssueProperties=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,n)=>{let r=e(t),setError=()=>n.addIssue({code:ZodIssueCode.custom,...getIssueProperties(t)});return typeof Promise<`u`&&r instanceof Promise?r.then(e=>e?!0:(setError(),!1)):r?!0:(setError(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this)}promise(){return ZodPromise.create(this,this._def)}or(e){return ZodUnion.create([this,e],this._def)}and(e){return ZodIntersection.create(this,e,this._def)}transform(e){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:t,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:t,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ZodPipeline.create(this,e)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let emojiRegex;const ipv4Regex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4CidrRegex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6Regex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ipv6CidrRegex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegexSource=`((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`,dateRegex=RegExp(`^${dateRegexSource}$`);function timeRegexSource(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function timeRegex(e){return RegExp(`^${timeRegexSource(e)}$`)}function datetimeRegex(e){let t=`${dateRegexSource}T${timeRegexSource(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function isValidIP(e,t){return!!((t===`v4`||!t)&&ipv4Regex.test(e)||(t===`v6`||!t)&&ipv6Regex.test(e))}function isValidJWT(e,t){if(!jwtRegex.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function isValidCidr(e,t){return!!((t===`v4`||!t)&&ipv4CidrRegex.test(e)||(t===`v6`||!t)&&ipv6CidrRegex.test(e))}var ZodString=class ZodString extends ZodType{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==ZodParsedType.string){let n=this._getOrReturnCtx(t);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:n.parsedType}),INVALID}let r=new ParseStatus,a;for(let e of this._def.checks)if(e.kind===`min`)t.data.length<e.value&&(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{code:ZodIssueCode.too_small,minimum:e.value,type:`string`,inclusive:!0,exact:!1,message:e.message}),r.dirty());else if(e.kind===`max`)t.data.length>e.value&&(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{code:ZodIssueCode.too_big,maximum:e.value,type:`string`,inclusive:!0,exact:!1,message:e.message}),r.dirty());else if(e.kind===`length`){let n=t.data.length>e.value,o=t.data.length<e.value;(n||o)&&(a=this._getOrReturnCtx(t,a),n?addIssueToContext(a,{code:ZodIssueCode.too_big,maximum:e.value,type:`string`,inclusive:!0,exact:!0,message:e.message}):o&&addIssueToContext(a,{code:ZodIssueCode.too_small,minimum:e.value,type:`string`,inclusive:!0,exact:!0,message:e.message}),r.dirty())}else if(e.kind===`email`)emailRegex.test(t.data)||(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{validation:`email`,code:ZodIssueCode.invalid_string,message:e.message}),r.dirty());else if(e.kind===`emoji`)emojiRegex||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),emojiRegex.test(t.data)||(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{validation:`emoji`,code:ZodIssueCode.invalid_string,message:e.message}),r.dirty());else if(e.kind===`uuid`)uuidRegex.test(t.data)||(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{validation:`uuid`,code:ZodIssueCode.invalid_string,message:e.message}),r.dirty());else if(e.kind===`nanoid`)nanoidRegex.test(t.data)||(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{validation:`nanoid`,code:ZodIssueCode.invalid_string,message:e.message}),r.dirty());else if(e.kind===`cuid`)cuidRegex.test(t.data)||(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{validation:`cuid`,code:ZodIssueCode.invalid_string,message:e.message}),r.dirty());else if(e.kind===`cuid2`)cuid2Regex.test(t.data)||(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{validation:`cuid2`,code:ZodIssueCode.invalid_string,message:e.message}),r.dirty());else if(e.kind===`ulid`)ulidRegex.test(t.data)||(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{validation:`ulid`,code:ZodIssueCode.invalid_string,message:e.message}),r.dirty());else if(e.kind===`url`)try{new URL(t.data)}catch{a=this._getOrReturnCtx(t,a),addIssueToContext(a,{validation:`url`,code:ZodIssueCode.invalid_string,message:e.message}),r.dirty()}else e.kind===`regex`?(e.regex.lastIndex=0,e.regex.test(t.data)||(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{validation:`regex`,code:ZodIssueCode.invalid_string,message:e.message}),r.dirty())):e.kind===`trim`?t.data=t.data.trim():e.kind===`includes`?t.data.includes(e.value,e.position)||(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{code:ZodIssueCode.invalid_string,validation:{includes:e.value,position:e.position},message:e.message}),r.dirty()):e.kind===`toLowerCase`?t.data=t.data.toLowerCase():e.kind===`toUpperCase`?t.data=t.data.toUpperCase():e.kind===`startsWith`?t.data.startsWith(e.value)||(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{code:ZodIssueCode.invalid_string,validation:{startsWith:e.value},message:e.message}),r.dirty()):e.kind===`endsWith`?t.data.endsWith(e.value)||(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{code:ZodIssueCode.invalid_string,validation:{endsWith:e.value},message:e.message}),r.dirty()):e.kind===`datetime`?datetimeRegex(e).test(t.data)||(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{code:ZodIssueCode.invalid_string,validation:`datetime`,message:e.message}),r.dirty()):e.kind===`date`?dateRegex.test(t.data)||(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{code:ZodIssueCode.invalid_string,validation:`date`,message:e.message}),r.dirty()):e.kind===`time`?timeRegex(e).test(t.data)||(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{code:ZodIssueCode.invalid_string,validation:`time`,message:e.message}),r.dirty()):e.kind===`duration`?durationRegex.test(t.data)||(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{validation:`duration`,code:ZodIssueCode.invalid_string,message:e.message}),r.dirty()):e.kind===`ip`?isValidIP(t.data,e.version)||(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{validation:`ip`,code:ZodIssueCode.invalid_string,message:e.message}),r.dirty()):e.kind===`jwt`?isValidJWT(t.data,e.alg)||(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{validation:`jwt`,code:ZodIssueCode.invalid_string,message:e.message}),r.dirty()):e.kind===`cidr`?isValidCidr(t.data,e.version)||(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{validation:`cidr`,code:ZodIssueCode.invalid_string,message:e.message}),r.dirty()):e.kind===`base64`?base64Regex.test(t.data)||(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{validation:`base64`,code:ZodIssueCode.invalid_string,message:e.message}),r.dirty()):e.kind===`base64url`?base64urlRegex.test(t.data)||(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{validation:`base64url`,code:ZodIssueCode.invalid_string,message:e.message}),r.dirty()):util.assertNever(e);return{status:r.value,value:t.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(n)})}_addCheck(e){return new ZodString({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:`email`,...errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...errorUtil.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...errorUtil.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...errorUtil.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...errorUtil.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...errorUtil.errToObj(t)})}nonempty(e){return this.min(1,errorUtil.errToObj(e))}trim(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};ZodString.create=e=>new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:e?.coerce??!1,...processCreateParams(e)});function floatSafeRemainder(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}var ZodNumber=class ZodNumber extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==ZodParsedType.number){let n=this._getOrReturnCtx(t);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:n.parsedType}),INVALID}let r,a=new ParseStatus;for(let e of this._def.checks)e.kind===`int`?util.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:`integer`,received:`float`,message:e.message}),a.dirty()):e.kind===`min`?(e.inclusive?t.data<e.value:t.data<=e.value)&&(r=this._getOrReturnCtx(t,r),addIssueToContext(r,{code:ZodIssueCode.too_small,minimum:e.value,type:`number`,inclusive:e.inclusive,exact:!1,message:e.message}),a.dirty()):e.kind===`max`?(e.inclusive?t.data>e.value:t.data>=e.value)&&(r=this._getOrReturnCtx(t,r),addIssueToContext(r,{code:ZodIssueCode.too_big,maximum:e.value,type:`number`,inclusive:e.inclusive,exact:!1,message:e.message}),a.dirty()):e.kind===`multipleOf`?floatSafeRemainder(t.data,e.value)!==0&&(r=this._getOrReturnCtx(t,r),addIssueToContext(r,{code:ZodIssueCode.not_multiple_of,multipleOf:e.value,message:e.message}),a.dirty()):e.kind===`finite`?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),addIssueToContext(r,{code:ZodIssueCode.not_finite,message:e.message}),a.dirty()):util.assertNever(e);return{status:a.value,value:t.data}}gte(e,t){return this.setLimit(`min`,e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,errorUtil.toString(t))}setLimit(e,t,n,r){return new ZodNumber({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:errorUtil.toString(r)}]})}_addCheck(e){return new ZodNumber({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:`int`,message:errorUtil.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:errorUtil.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:errorUtil.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:errorUtil.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:errorUtil.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&util.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks){if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}};ZodNumber.create=e=>new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:e?.coerce||!1,...processCreateParams(e)});var ZodBigInt=class ZodBigInt extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==ZodParsedType.bigint)return this._getInvalidInput(t);let r,a=new ParseStatus;for(let e of this._def.checks)e.kind===`min`?(e.inclusive?t.data<e.value:t.data<=e.value)&&(r=this._getOrReturnCtx(t,r),addIssueToContext(r,{code:ZodIssueCode.too_small,type:`bigint`,minimum:e.value,inclusive:e.inclusive,message:e.message}),a.dirty()):e.kind===`max`?(e.inclusive?t.data>e.value:t.data>=e.value)&&(r=this._getOrReturnCtx(t,r),addIssueToContext(r,{code:ZodIssueCode.too_big,type:`bigint`,maximum:e.value,inclusive:e.inclusive,message:e.message}),a.dirty()):e.kind===`multipleOf`?t.data%e.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),addIssueToContext(r,{code:ZodIssueCode.not_multiple_of,multipleOf:e.value,message:e.message}),a.dirty()):util.assertNever(e);return{status:a.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:n.parsedType}),INVALID}gte(e,t){return this.setLimit(`min`,e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,errorUtil.toString(t))}setLimit(e,t,n,r){return new ZodBigInt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:errorUtil.toString(r)}]})}_addCheck(e){return new ZodBigInt({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:errorUtil.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};ZodBigInt.create=e=>new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:e?.coerce??!1,...processCreateParams(e)});var ZodBoolean=class extends ZodType{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==ZodParsedType.boolean){let n=this._getOrReturnCtx(t);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:n.parsedType}),INVALID}return OK(t.data)}};ZodBoolean.create=e=>new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:e?.coerce||!1,...processCreateParams(e)});var ZodDate=class ZodDate extends ZodType{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==ZodParsedType.date){let n=this._getOrReturnCtx(t);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:n.parsedType}),INVALID}if(Number.isNaN(t.data.getTime()))return addIssueToContext(this._getOrReturnCtx(t),{code:ZodIssueCode.invalid_date}),INVALID;let r=new ParseStatus,a;for(let e of this._def.checks)e.kind===`min`?t.data.getTime()<e.value&&(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{code:ZodIssueCode.too_small,message:e.message,inclusive:!0,exact:!1,minimum:e.value,type:`date`}),r.dirty()):e.kind===`max`?t.data.getTime()>e.value&&(a=this._getOrReturnCtx(t,a),addIssueToContext(a,{code:ZodIssueCode.too_big,message:e.message,inclusive:!0,exact:!1,maximum:e.value,type:`date`}),r.dirty()):util.assertNever(e);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(e){return new ZodDate({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:errorUtil.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};ZodDate.create=e=>new ZodDate({checks:[],coerce:e?.coerce||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(e)});var ZodSymbol=class extends ZodType{_parse(t){if(this._getType(t)!==ZodParsedType.symbol){let n=this._getOrReturnCtx(t);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:n.parsedType}),INVALID}return OK(t.data)}};ZodSymbol.create=e=>new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(e)});var ZodUndefined=class extends ZodType{_parse(t){if(this._getType(t)!==ZodParsedType.undefined){let n=this._getOrReturnCtx(t);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:n.parsedType}),INVALID}return OK(t.data)}};ZodUndefined.create=e=>new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(e)});var ZodNull=class extends ZodType{_parse(t){if(this._getType(t)!==ZodParsedType.null){let n=this._getOrReturnCtx(t);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:n.parsedType}),INVALID}return OK(t.data)}};ZodNull.create=e=>new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(e)});var ZodAny=class extends ZodType{constructor(){super(...arguments),this._any=!0}_parse(e){return OK(e.data)}};ZodAny.create=e=>new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(e)});var ZodUnknown=class extends ZodType{constructor(){super(...arguments),this._unknown=!0}_parse(e){return OK(e.data)}};ZodUnknown.create=e=>new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(e)});var ZodNever=class extends ZodType{_parse(t){let n=this._getOrReturnCtx(t);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:n.parsedType}),INVALID}};ZodNever.create=e=>new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(e)});var ZodVoid=class extends ZodType{_parse(t){if(this._getType(t)!==ZodParsedType.undefined){let n=this._getOrReturnCtx(t);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:n.parsedType}),INVALID}return OK(t.data)}};ZodVoid.create=e=>new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(e)});var ZodArray=class ZodArray extends ZodType{_parse(t){let{ctx:n,status:r}=this._processInputParams(t),a=this._def;if(n.parsedType!==ZodParsedType.array)return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:n.parsedType}),INVALID;if(a.exactLength!==null){let e=n.data.length>a.exactLength.value,t=n.data.length<a.exactLength.value;(e||t)&&(addIssueToContext(n,{code:e?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:t?a.exactLength.value:void 0,maximum:e?a.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:a.exactLength.message}),r.dirty())}if(a.minLength!==null&&n.data.length<a.minLength.value&&(addIssueToContext(n,{code:ZodIssueCode.too_small,minimum:a.minLength.value,type:`array`,inclusive:!0,exact:!1,message:a.minLength.message}),r.dirty()),a.maxLength!==null&&n.data.length>a.maxLength.value&&(addIssueToContext(n,{code:ZodIssueCode.too_big,maximum:a.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:a.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((e,t)=>a.type._parseAsync(new ParseInputLazyPath(n,e,n.path,t)))).then(e=>ParseStatus.mergeArray(r,e));let o=[...n.data].map((e,t)=>a.type._parseSync(new ParseInputLazyPath(n,e,n.path,t)));return ParseStatus.mergeArray(r,o)}get element(){return this._def.type}min(e,t){return new ZodArray({...this._def,minLength:{value:e,message:errorUtil.toString(t)}})}max(e,t){return new ZodArray({...this._def,maxLength:{value:e,message:errorUtil.toString(t)}})}length(e,t){return new ZodArray({...this._def,exactLength:{value:e,message:errorUtil.toString(t)}})}nonempty(e){return this.min(1,e)}};ZodArray.create=(e,t)=>new ZodArray({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(t)});function deepPartialify(e){if(e instanceof ZodObject){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=ZodOptional.create(deepPartialify(r))}return new ZodObject({...e._def,shape:()=>t})}else if(e instanceof ZodArray)return new ZodArray({...e._def,type:deepPartialify(e.element)});else if(e instanceof ZodOptional)return ZodOptional.create(deepPartialify(e.unwrap()));else if(e instanceof ZodNullable)return ZodNullable.create(deepPartialify(e.unwrap()));else if(e instanceof ZodTuple)return ZodTuple.create(e.items.map(e=>deepPartialify(e)));else return e}var ZodObject=class ZodObject extends ZodType{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=util.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(t){if(this._getType(t)!==ZodParsedType.object){let n=this._getOrReturnCtx(t);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:n.parsedType}),INVALID}let{status:n,ctx:r}=this._processInputParams(t),{shape:a,keys:o}=this._getCached(),s=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys===`strip`))for(let e in r.data)o.includes(e)||s.push(e);let c=[];for(let e of o){let t=a[e],n=r.data[e];c.push({key:{status:`valid`,value:e},value:t._parse(new ParseInputLazyPath(r,n,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof ZodNever){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of s)c.push({key:{status:`valid`,value:e},value:{status:`valid`,value:r.data[e]}});else if(e===`strict`)s.length>0&&(addIssueToContext(r,{code:ZodIssueCode.unrecognized_keys,keys:s}),n.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of s){let n=r.data[t];c.push({key:{status:`valid`,value:t},value:e._parse(new ParseInputLazyPath(r,n,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of c){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>ParseStatus.mergeObjectSync(n,e)):ParseStatus.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return errorUtil.errToObj,new ZodObject({...this._def,unknownKeys:`strict`,...e===void 0?{}:{errorMap:(t,n)=>{let r=this._def.errorMap?.(t,n).message??n.defaultError;return t.code===`unrecognized_keys`?{message:errorUtil.errToObj(e).message??r}:{message:r}}}})}strip(){return new ZodObject({...this._def,unknownKeys:`strip`})}passthrough(){return new ZodObject({...this._def,unknownKeys:`passthrough`})}extend(e){return new ZodObject({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ZodObject({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ZodObject({...this._def,catchall:e})}pick(e){let t={};for(let r of util.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new ZodObject({...this._def,shape:()=>t})}omit(e){let t={};for(let r of util.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new ZodObject({...this._def,shape:()=>t})}deepPartial(){return deepPartialify(this)}partial(e){let t={};for(let r of util.objectKeys(this.shape)){let n=this.shape[r];e&&!e[r]?t[r]=n:t[r]=n.optional()}return new ZodObject({...this._def,shape:()=>t})}required(e){let t={};for(let r of util.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof ZodOptional;)e=e._def.innerType;t[r]=e}return new ZodObject({...this._def,shape:()=>t})}keyof(){return createZodEnum(util.objectKeys(this.shape))}};ZodObject.create=(e,t)=>new ZodObject({shape:()=>e,unknownKeys:`strip`,catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)}),ZodObject.strictCreate=(e,t)=>new ZodObject({shape:()=>e,unknownKeys:`strict`,catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)}),ZodObject.lazycreate=(e,t)=>new ZodObject({shape:e,unknownKeys:`strip`,catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)});var ZodUnion=class extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function handleResults(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new ZodError(e.ctx.common.issues));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:n}),INVALID}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(handleResults);{let e,a=[];for(let r of n){let n={...t,common:{...t.common,issues:[]},parent:null},i=r._parseSync({data:t.data,path:t.path,parent:n});if(i.status===`valid`)return i;i.status===`dirty`&&!e&&(e={result:i,ctx:n}),n.common.issues.length&&a.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let o=a.map(e=>new ZodError(e));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:o}),INVALID}}get options(){return this._def.options}};ZodUnion.create=(e,t)=>new ZodUnion({options:e,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(t)});const getDiscriminator=e=>e instanceof ZodLazy?getDiscriminator(e.schema):e instanceof ZodEffects?getDiscriminator(e.innerType()):e instanceof ZodLiteral?[e.value]:e instanceof ZodEnum?e.options:e instanceof ZodNativeEnum?util.objectValues(e.enum):e instanceof ZodDefault?getDiscriminator(e._def.innerType):e instanceof ZodUndefined?[void 0]:e instanceof ZodNull?[null]:e instanceof ZodOptional?[void 0,...getDiscriminator(e.unwrap())]:e instanceof ZodNullable?[null,...getDiscriminator(e.unwrap())]:e instanceof ZodBranded||e instanceof ZodReadonly?getDiscriminator(e.unwrap()):e instanceof ZodCatch?getDiscriminator(e._def.innerType):[];var ZodDiscriminatedUnion=class ZodDiscriminatedUnion extends ZodType{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==ZodParsedType.object)return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:n.parsedType}),INVALID;let r=this.discriminator,a=n.data[r],o=this.optionsMap.get(a);return o?n.common.async?o._parseAsync({data:n.data,path:n.path,parent:n}):o._parseSync({data:n.data,path:n.path,parent:n}):(addIssueToContext(n,{code:ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let r=new Map;for(let n of t){let t=getDiscriminator(n.shape[e]);if(!t.length)throw Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let i of t){if(r.has(i))throw Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);r.set(i,n)}}return new ZodDiscriminatedUnion({typeName:ZodFirstPartyTypeKind.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:r,...processCreateParams(n)})}};function mergeValues(r,i){let a=getParsedType(r),o=getParsedType(i);if(r===i)return{valid:!0,data:r};if(a===ZodParsedType.object&&o===ZodParsedType.object){let e=util.objectKeys(i),t=util.objectKeys(r).filter(t=>e.indexOf(t)!==-1),a={...r,...i};for(let e of t){let t=mergeValues(r[e],i[e]);if(!t.valid)return{valid:!1};a[e]=t.data}return{valid:!0,data:a}}else if(a===ZodParsedType.array&&o===ZodParsedType.array){if(r.length!==i.length)return{valid:!1};let e=[];for(let t=0;t<r.length;t++){let n=r[t],a=i[t],o=mergeValues(n,a);if(!o.valid)return{valid:!1};e.push(o.data)}return{valid:!0,data:e}}else if(a===ZodParsedType.date&&o===ZodParsedType.date&&+r==+i)return{valid:!0,data:r};else return{valid:!1}}var ZodIntersection=class extends ZodType{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),handleParsed=(e,r)=>{if(isAborted(e)||isAborted(r))return INVALID;let a=mergeValues(e.value,r.value);return a.valid?((isDirty(e)||isDirty(r))&&t.dirty(),{status:t.value,value:a.data}):(addIssueToContext(n,{code:ZodIssueCode.invalid_intersection_types}),INVALID)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>handleParsed(e,t)):handleParsed(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};ZodIntersection.create=(e,t,n)=>new ZodIntersection({left:e,right:t,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams(n)});var ZodTuple=class ZodTuple extends ZodType{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==ZodParsedType.array)return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:r.parsedType}),INVALID;if(r.data.length<this._def.items.length)return addIssueToContext(r,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),INVALID;!this._def.rest&&r.data.length>this._def.items.length&&(addIssueToContext(r,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),n.dirty());let a=[...r.data].map((e,t)=>{let n=this._def.items[t]||this._def.rest;return n?n._parse(new ParseInputLazyPath(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(a).then(e=>ParseStatus.mergeArray(n,e)):ParseStatus.mergeArray(n,a)}get items(){return this._def.items}rest(e){return new ZodTuple({...this._def,rest:e})}};ZodTuple.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new ZodTuple({items:e,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(t)})};var ZodRecord=class ZodRecord extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==ZodParsedType.object)return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:r.parsedType}),INVALID;let a=[],o=this._def.keyType,s=this._def.valueType;for(let e in r.data)a.push({key:o._parse(new ParseInputLazyPath(r,e,r.path,e)),value:s._parse(new ParseInputLazyPath(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?ParseStatus.mergeObjectAsync(n,a):ParseStatus.mergeObjectSync(n,a)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof ZodType?new ZodRecord({keyType:e,valueType:t,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(n)}):new ZodRecord({keyType:ZodString.create(),valueType:e,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(t)})}},ZodMap=class extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==ZodParsedType.map)return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:r.parsedType}),INVALID;let a=this._def.keyType,o=this._def.valueType,s=[...r.data.entries()].map(([e,t],n)=>({key:a._parse(new ParseInputLazyPath(r,e,r.path,[n,`key`])),value:o._parse(new ParseInputLazyPath(r,t,r.path,[n,`value`]))}));if(r.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let t of s){let r=await t.key,i=await t.value;if(r.status===`aborted`||i.status===`aborted`)return INVALID;(r.status===`dirty`||i.status===`dirty`)&&n.dirty(),e.set(r.value,i.value)}return{status:n.value,value:e}})}else{let e=new Map;for(let t of s){let r=t.key,i=t.value;if(r.status===`aborted`||i.status===`aborted`)return INVALID;(r.status===`dirty`||i.status===`dirty`)&&n.dirty(),e.set(r.value,i.value)}return{status:n.value,value:e}}}};ZodMap.create=(e,t,n)=>new ZodMap({valueType:t,keyType:e,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams(n)});var ZodSet=class ZodSet extends ZodType{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==ZodParsedType.set)return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:r.parsedType}),INVALID;let a=this._def;a.minSize!==null&&r.data.size<a.minSize.value&&(addIssueToContext(r,{code:ZodIssueCode.too_small,minimum:a.minSize.value,type:`set`,inclusive:!0,exact:!1,message:a.minSize.message}),n.dirty()),a.maxSize!==null&&r.data.size>a.maxSize.value&&(addIssueToContext(r,{code:ZodIssueCode.too_big,maximum:a.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:a.maxSize.message}),n.dirty());let o=this._def.valueType;function finalizeSet(e){let t=new Set;for(let r of e){if(r.status===`aborted`)return INVALID;r.status===`dirty`&&n.dirty(),t.add(r.value)}return{status:n.value,value:t}}let s=[...r.data.values()].map((e,t)=>o._parse(new ParseInputLazyPath(r,e,r.path,t)));return r.common.async?Promise.all(s).then(e=>finalizeSet(e)):finalizeSet(s)}min(e,t){return new ZodSet({...this._def,minSize:{value:e,message:errorUtil.toString(t)}})}max(e,t){return new ZodSet({...this._def,maxSize:{value:e,message:errorUtil.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};ZodSet.create=(e,t)=>new ZodSet({valueType:e,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(t)});var ZodFunction=class ZodFunction extends ZodType{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==ZodParsedType.function)return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.function,received:n.parsedType}),INVALID;function makeArgsIssue(e,t){return makeIssue({data:e,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,getErrorMap(),errorMap].filter(e=>!!e),issueData:{code:ZodIssueCode.invalid_arguments,argumentsError:t}})}function makeReturnsIssue(e,t){return makeIssue({data:e,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,getErrorMap(),errorMap].filter(e=>!!e),issueData:{code:ZodIssueCode.invalid_return_type,returnTypeError:t}})}let s={errorMap:n.common.contextualErrorMap},l=n.data;if(this._def.returns instanceof ZodPromise){let e=this;return OK(async function(...t){let n=new ZodError([]),i=await e._def.args.parseAsync(t,s).catch(e=>{throw n.addIssue(makeArgsIssue(t,e)),n}),a=await Reflect.apply(l,this,i);return await e._def.returns._def.type.parseAsync(a,s).catch(e=>{throw n.addIssue(makeReturnsIssue(a,e)),n})})}else{let e=this;return OK(function(...t){let n=e._def.args.safeParse(t,s);if(!n.success)throw new ZodError([makeArgsIssue(t,n.error)]);let i=Reflect.apply(l,this,n.data),a=e._def.returns.safeParse(i,s);if(!a.success)throw new ZodError([makeReturnsIssue(i,a.error)]);return a.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new ZodFunction({...this._def,args:ZodTuple.create(e).rest(ZodUnknown.create())})}returns(e){return new ZodFunction({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new ZodFunction({args:e||ZodTuple.create([]).rest(ZodUnknown.create()),returns:t||ZodUnknown.create(),typeName:ZodFirstPartyTypeKind.ZodFunction,...processCreateParams(n)})}},ZodLazy=class extends ZodType{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};ZodLazy.create=(e,t)=>new ZodLazy({getter:e,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(t)});var ZodLiteral=class extends ZodType{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:`valid`,value:e.data}}get value(){return this._def.value}};ZodLiteral.create=(e,t)=>new ZodLiteral({value:e,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(t)});function createZodEnum(e,t){return new ZodEnum({values:e,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(t)})}var ZodEnum=class ZodEnum extends ZodType{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),r=this._def.values;return addIssueToContext(t,{expected:util.joinValues(r),received:t.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_enum_value,options:n}),INVALID}return OK(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return ZodEnum.create(e,{...this._def,...t})}exclude(e,t=this._def){return ZodEnum.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}};ZodEnum.create=createZodEnum;var ZodNativeEnum=class extends ZodType{_parse(t){let r=util.getValidEnumValues(this._def.values),a=this._getOrReturnCtx(t);if(a.parsedType!==ZodParsedType.string&&a.parsedType!==ZodParsedType.number){let e=util.objectValues(r);return addIssueToContext(a,{expected:util.joinValues(e),received:a.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||=new Set(util.getValidEnumValues(this._def.values)),!this._cache.has(t.data)){let e=util.objectValues(r);return addIssueToContext(a,{received:a.data,code:ZodIssueCode.invalid_enum_value,options:e}),INVALID}return OK(t.data)}get enum(){return this._def.values}};ZodNativeEnum.create=(e,t)=>new ZodNativeEnum({values:e,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(t)});var ZodPromise=class extends ZodType{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);return n.parsedType!==ZodParsedType.promise&&n.common.async===!1?(addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:n.parsedType}),INVALID):OK((n.parsedType===ZodParsedType.promise?n.data:Promise.resolve(n.data)).then(e=>this._def.type.parseAsync(e,{path:n.path,errorMap:n.common.contextualErrorMap})))}};ZodPromise.create=(e,t)=>new ZodPromise({type:e,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(t)});var ZodEffects=class extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),i=this._def.effect||null,a={addIssue:e=>{addIssueToContext(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(a.addIssue=a.addIssue.bind(a),i.type===`preprocess`){let e=i.transform(r.data,a);if(r.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return INVALID;let n=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return n.status===`aborted`?INVALID:n.status===`dirty`||t.value===`dirty`?DIRTY(n.value):n});{if(t.value===`aborted`)return INVALID;let n=this._def.schema._parseSync({data:e,path:r.path,parent:r});return n.status===`aborted`?INVALID:n.status===`dirty`||t.value===`dirty`?DIRTY(n.value):n}}if(i.type===`refinement`){let executeRefinement=e=>{let t=i.refinement(e,a);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(r.common.async===!1){let e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return e.status===`aborted`?INVALID:(e.status===`dirty`&&t.dirty(),executeRefinement(e.value),{status:t.value,value:e.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>e.status===`aborted`?INVALID:(e.status===`dirty`&&t.dirty(),executeRefinement(e.value).then(()=>({status:t.value,value:e.value}))))}if(i.type===`transform`)if(r.common.async===!1){let e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!isValid(e))return INVALID;let n=i.transform(e.value,a);if(n instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:n}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>isValid(e)?Promise.resolve(i.transform(e.value,a)).then(e=>({status:t.value,value:e})):INVALID);util.assertNever(i)}};ZodEffects.create=(e,t,n)=>new ZodEffects({schema:e,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:t,...processCreateParams(n)}),ZodEffects.createWithPreprocess=(e,t,n)=>new ZodEffects({schema:t,effect:{type:`preprocess`,transform:e},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams(n)});var ZodOptional=class extends ZodType{_parse(t){return this._getType(t)===ZodParsedType.undefined?OK(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};ZodOptional.create=(e,t)=>new ZodOptional({innerType:e,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(t)});var ZodNullable=class extends ZodType{_parse(t){return this._getType(t)===ZodParsedType.null?OK(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};ZodNullable.create=(e,t)=>new ZodNullable({innerType:e,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(t)});var ZodDefault=class extends ZodType{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===ZodParsedType.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};ZodDefault.create=(e,t)=>new ZodDefault({innerType:e,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...processCreateParams(t)});var ZodCatch=class extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return isAsync(i)?i.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new ZodError(n.common.issues)},input:n.data})})):{status:`valid`,value:i.status===`valid`?i.value:this._def.catchValue({get error(){return new ZodError(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};ZodCatch.create=(e,t)=>new ZodCatch({innerType:e,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...processCreateParams(t)});var ZodNaN=class extends ZodType{_parse(t){if(this._getType(t)!==ZodParsedType.nan){let n=this._getOrReturnCtx(t);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:n.parsedType}),INVALID}return{status:`valid`,value:t.data}}};ZodNaN.create=e=>new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(e)});const BRAND=Symbol(`zod_brand`);var ZodBranded=class extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},ZodPipeline=class ZodPipeline extends ZodType{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?INVALID:e.status===`dirty`?(t.dirty(),DIRTY(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?INVALID:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(e,t){return new ZodPipeline({in:e,out:t,typeName:ZodFirstPartyTypeKind.ZodPipeline})}},ZodReadonly=class extends ZodType{_parse(e){let t=this._def.innerType._parse(e),freeze=e=>(isValid(e)&&(e.value=Object.freeze(e.value)),e);return isAsync(t)?t.then(e=>freeze(e)):freeze(t)}unwrap(){return this._def.innerType}};ZodReadonly.create=(e,t)=>new ZodReadonly({innerType:e,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(t)});function cleanParams(e,t){let n=typeof e==`function`?e(t):typeof e==`string`?{message:e}:e;return typeof n==`string`?{message:n}:n}function custom(e,t={},n){return e?ZodAny.create().superRefine((r,i)=>{let a=e(r);if(a instanceof Promise)return a.then(e=>{if(!e){let e=cleanParams(t,r),a=e.fatal??n??!0;i.addIssue({code:`custom`,...e,fatal:a})}});if(!a){let e=cleanParams(t,r),a=e.fatal??n??!0;i.addIssue({code:`custom`,...e,fatal:a})}}):ZodAny.create()}const late={object:ZodObject.lazycreate};var ZodFirstPartyTypeKind;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(ZodFirstPartyTypeKind||={});const instanceOfType=(e,t={message:`Input not instance of ${e.name}`})=>custom(t=>t instanceof e,t),stringType=ZodString.create,numberType=ZodNumber.create,nanType=ZodNaN.create,bigIntType=ZodBigInt.create,booleanType=ZodBoolean.create,dateType=ZodDate.create,symbolType=ZodSymbol.create,undefinedType=ZodUndefined.create,nullType=ZodNull.create,anyType=ZodAny.create,unknownType=ZodUnknown.create,neverType=ZodNever.create,voidType=ZodVoid.create,arrayType=ZodArray.create,objectType=ZodObject.create,strictObjectType=ZodObject.strictCreate,unionType=ZodUnion.create,discriminatedUnionType=ZodDiscriminatedUnion.create,intersectionType=ZodIntersection.create,tupleType=ZodTuple.create,recordType=ZodRecord.create,mapType=ZodMap.create,setType=ZodSet.create,functionType=ZodFunction.create,lazyType=ZodLazy.create,literalType=ZodLiteral.create,enumType=ZodEnum.create,nativeEnumType=ZodNativeEnum.create,promiseType=ZodPromise.create,effectsType=ZodEffects.create,optionalType=ZodOptional.create,nullableType=ZodNullable.create,preprocessType=ZodEffects.createWithPreprocess,pipelineType=ZodPipeline.create,ostring=()=>stringType().optional(),onumber=()=>numberType().optional(),oboolean=()=>booleanType().optional(),coerce={string:(e=>ZodString.create({...e,coerce:!0})),number:(e=>ZodNumber.create({...e,coerce:!0})),boolean:(e=>ZodBoolean.create({...e,coerce:!0})),bigint:(e=>ZodBigInt.create({...e,coerce:!0})),date:(e=>ZodDate.create({...e,coerce:!0}))},NEVER=INVALID;export{BRAND,NEVER,ZodAny,ZodArray,ZodBigInt,ZodBoolean,ZodBranded,ZodCatch,ZodDate,ZodDefault,ZodDiscriminatedUnion,ZodEffects,ZodEnum,ZodFirstPartyTypeKind,ZodFunction,ZodIntersection,ZodLazy,ZodLiteral,ZodMap,ZodNaN,ZodNativeEnum,ZodNever,ZodNull,ZodNullable,ZodNumber,ZodObject,ZodOptional,ZodPipeline,ZodPromise,ZodReadonly,ZodRecord,ZodSet,ZodString,ZodSymbol,ZodTuple,ZodType,ZodUndefined,ZodUnion,ZodUnknown,ZodVoid,anyType,arrayType,bigIntType,booleanType,coerce,custom,dateType,datetimeRegex,discriminatedUnionType,effectsType,enumType,functionType,instanceOfType,intersectionType,late,lazyType,literalType,mapType,nanType,nativeEnumType,neverType,nullType,nullableType,numberType,objectType,oboolean,onumber,optionalType,ostring,pipelineType,preprocessType,promiseType,recordType,setType,strictObjectType,stringType,symbolType,tupleType,undefinedType,unionType,unknownType,voidType};
@@ -1,7 +1,7 @@
1
- import{getSupportedModuleBaseName,matchesSupportedModuleBaseName}from"./module-files.js";import{pathExists,writeTextFile}from"./files.js";import"./project.js";import{patchPackageJson}from"./package-json.js";import{basename,join,resolve}from"node:path";import{readFile,readdir}from"node:fs/promises";var SLACK_CHANNEL_DEFAULT_ROUTE=`/ash/v1/slack`,DEFAULT_SLACK_CONNECTOR_SLUG=`my-agent`,DEFAULT_CONNECT_PACKAGE_VERSION=`0.0.6-alpha.1`,CONNECT_PACKAGE_NAME=`@vercel/connect`,USER_AUTHORED_CHANNEL_DIR=`agent/channels`;function toSlackConnectorSlug(e){return e}function isJsonObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function readDependencyVersion(e,t){let n=JSON.parse(await readFile(e,`utf8`));if(!isJsonObject(n)||!isJsonObject(n.dependencies))return;let r=n.dependencies[t];return typeof r==`string`?r:void 0}async function ensurePackageDependency(e,t,r){return!await pathExists(e)||await readDependencyVersion(e,t)===r?[]:(await patchPackageJson(e,{dependencies:{[t]:r}}),[{path:e,dependencies:[t]}])}function normalizeSlackConnectorSlug(e){return toSlackConnectorSlug((e.trim().replace(/^@/,``).split(`/`).at(-1)??``).toLowerCase().replace(/[^a-z0-9_-]+/g,`-`).replace(/^[^a-z0-9]+/,``).replace(/[^a-z0-9]+$/,``).slice(0,100).replace(/[^a-z0-9]+$/,``)||`my-agent`)}async function deriveSlackConnectorSlug(e,t){if(t!==void 0&&t.length>0&&t!==`.`)return normalizeSlackConnectorSlug(t);try{let t=await readFile(join(e,`package.json`),`utf8`),n=JSON.parse(t);if(typeof n.name==`string`&&n.name.length>0)return normalizeSlackConnectorSlug(n.name)}catch{}return normalizeSlackConnectorSlug(basename(resolve(e))||`my-agent`)}function buildSlackTemplate(e){return`import { connectSlackCredentials } from "@vercel/connect/ash";
1
+ import{getSupportedModuleBaseName,matchesSupportedModuleBaseName}from"./module-files.js";import{pathExists,writeTextFile}from"./files.js";import"./project.js";import{patchPackageJson}from"./package-json.js";import{basename,join,resolve}from"node:path";import{readFile,readdir}from"node:fs/promises";const SLACK_CHANNEL_DEFAULT_ROUTE=`/ash/v1/slack`,DEFAULT_SLACK_CONNECTOR_SLUG=`my-agent`;function toSlackConnectorSlug(e){return e}function isJsonObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function readDependencyVersion(e,t){let n=JSON.parse(await readFile(e,`utf8`));if(!isJsonObject(n)||!isJsonObject(n.dependencies))return;let r=n.dependencies[t];return typeof r==`string`?r:void 0}async function ensurePackageDependency(e,t,r){return!await pathExists(e)||await readDependencyVersion(e,t)===r?[]:(await patchPackageJson(e,{dependencies:{[t]:r}}),[{path:e,dependencies:[t]}])}function normalizeSlackConnectorSlug(e){return toSlackConnectorSlug((e.trim().replace(/^@/,``).split(`/`).at(-1)??``).toLowerCase().replace(/[^a-z0-9_-]+/g,`-`).replace(/^[^a-z0-9]+/,``).replace(/[^a-z0-9]+$/,``).slice(0,100).replace(/[^a-z0-9]+$/,``)||`my-agent`)}async function deriveSlackConnectorSlug(e,t){if(t!==void 0&&t.length>0&&t!==`.`)return normalizeSlackConnectorSlug(t);try{let t=await readFile(join(e,`package.json`),`utf8`),n=JSON.parse(t);if(typeof n.name==`string`&&n.name.length>0)return normalizeSlackConnectorSlug(n.name)}catch{}return normalizeSlackConnectorSlug(basename(resolve(e))||`my-agent`)}function buildSlackTemplate(e){return`import { connectSlackCredentials } from "@vercel/connect/ash";
2
2
  import { slackChannel } from "experimental-ash/channels/slack";
3
3
 
4
4
  export default slackChannel({
5
5
  credentials: connectSlackCredentials("slack/${e}"),
6
6
  });
7
- `}function assertStampedVersion(e,t){if(t.startsWith(`__`))throw Error(`Channel scaffold received unstamped version token (${e}=${t}). Build @vercel/ash-scaffold before using its dist entrypoint.`)}async function ensureChannel(e){switch(e.kind){case`slack`:return ensureSlackChannel(e)}}async function ensureSlackChannel(e){let t=join(e.projectRoot,`agent/channels/slack.ts`),i=await pathExists(t);if(!e.force&&i)return{kind:`slack`,action:`skipped`,filesWritten:[],filesSkipped:[t],packageJsonUpdated:[]};let a=e.connectPackageVersion??DEFAULT_CONNECT_PACKAGE_VERSION;assertStampedVersion(`connectPackageVersion`,a);let o=await ensurePackageDependency(join(e.projectRoot,`package.json`),CONNECT_PACKAGE_NAME,a),s=e.slackConnectorSlug??await deriveSlackConnectorSlug(e.projectRoot);return await writeTextFile(t,buildSlackTemplate(s),{force:e.force}),{kind:`slack`,action:i?`overwritten`:`created`,filesWritten:[t],filesSkipped:[],packageJsonUpdated:o,slackConnectorSlug:s}}async function listAuthoredChannels(n){let r=join(n,USER_AUTHORED_CHANNEL_DIR),i;try{i=await readdir(r,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)return[];throw e}let a=[];for(let n of i){if(n.isFile()){let t=getSupportedModuleBaseName(n.name);t!==null&&a.push(t);continue}if(n.isDirectory())try{(await readdir(join(r,n.name))).some(e=>matchesSupportedModuleBaseName(e,`connection`))&&a.push(n.name)}catch{}}return a.sort()}export{DEFAULT_SLACK_CONNECTOR_SLUG,SLACK_CHANNEL_DEFAULT_ROUTE,deriveSlackConnectorSlug,ensureChannel,listAuthoredChannels,normalizeSlackConnectorSlug};
7
+ `}function assertStampedVersion(e,t){if(t.startsWith(`__`))throw Error(`Channel scaffold received unstamped version token (${e}=${t}). Build @vercel/ash-scaffold before using its dist entrypoint.`)}async function ensureChannel(e){switch(e.kind){case`slack`:return ensureSlackChannel(e)}}async function ensureSlackChannel(e){let t=join(e.projectRoot,`agent/channels/slack.ts`),i=await pathExists(t);if(!e.force&&i)return{kind:`slack`,action:`skipped`,filesWritten:[],filesSkipped:[t],packageJsonUpdated:[]};let a=e.connectPackageVersion??`0.0.6-alpha.1`;assertStampedVersion(`connectPackageVersion`,a);let o=await ensurePackageDependency(join(e.projectRoot,`package.json`),`@vercel/connect`,a),s=e.slackConnectorSlug??await deriveSlackConnectorSlug(e.projectRoot);return await writeTextFile(t,buildSlackTemplate(s),{force:e.force}),{kind:`slack`,action:i?`overwritten`:`created`,filesWritten:[t],filesSkipped:[],packageJsonUpdated:o,slackConnectorSlug:s}}async function listAuthoredChannels(n){let r=join(n,`agent/channels`),i;try{i=await readdir(r,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)return[];throw e}let a=[];for(let n of i){if(n.isFile()){let t=getSupportedModuleBaseName(n.name);t!==null&&a.push(t);continue}if(n.isDirectory())try{(await readdir(join(r,n.name))).some(e=>matchesSupportedModuleBaseName(e,`connection`))&&a.push(n.name)}catch{}}return a.sort()}export{DEFAULT_SLACK_CONNECTOR_SLUG,SLACK_CHANNEL_DEFAULT_ROUTE,deriveSlackConnectorSlug,ensureChannel,listAuthoredChannels,normalizeSlackConnectorSlug};
@@ -1 +1 @@
1
- var SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS=[`.cts`,`.mts`,`.cjs`,`.mjs`,`.ts`,`.js`];function getSupportedModuleBaseName(t){for(let n of SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS)if(t.endsWith(n)&&t.length>n.length)return t.slice(0,-n.length);return null}function matchesSupportedModuleBaseName(e,t){return getSupportedModuleBaseName(e)===t}export{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS,getSupportedModuleBaseName,matchesSupportedModuleBaseName};
1
+ const SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS=[`.cts`,`.mts`,`.cjs`,`.mjs`,`.ts`,`.js`];function getSupportedModuleBaseName(t){for(let n of SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS)if(t.endsWith(n)&&t.length>n.length)return t.slice(0,-n.length);return null}function matchesSupportedModuleBaseName(e,t){return getSupportedModuleBaseName(e)===t}export{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS,getSupportedModuleBaseName,matchesSupportedModuleBaseName};
@@ -1,2 +1,2 @@
1
- var ASH_SESSION_ID_HEADER=`x-ash-session-id`,ASH_STREAM_FORMAT_HEADER=`x-ash-stream-format`,ASH_STREAM_VERSION_HEADER=`x-ash-stream-version`,ASH_MESSAGE_STREAM_CONTENT_TYPE=`application/x-ndjson; charset=utf-8`,ASH_MESSAGE_STREAM_FORMAT=`ndjson`,ASH_MESSAGE_STREAM_VERSION=`14`,textEncoder=new TextEncoder;function isCurrentTurnBoundaryEvent(e){return e.type===`session.completed`||e.type===`session.failed`||e.type===`session.waiting`}function createSessionStartedEvent(e){let t={};return e?.invocation!==void 0&&(t.invocation=e.invocation),e?.runtime!==void 0&&(t.runtime=e.runtime),{data:t,type:`session.started`}}function createTurnStartedEvent(e){return{data:{sequence:e.sequence,turnId:e.turnId},type:`turn.started`}}function createMessageReceivedEvent(e){return{data:{message:summarizeUserContent(e.message),sequence:e.sequence,turnId:e.turnId},type:`message.received`}}function summarizeUserContent(e){if(typeof e==`string`)return e;let t=[];for(let n of e)if(n.type===`text`)t.push(n.text);else if(n.type===`file`){let e=n.filename??n.mediaType;t.push(`[file: ${e} (${n.mediaType})]`)}else n.type===`image`&&t.push(`[image: ${n.mediaType??`image`}]`);return t.join(`
1
+ const ASH_SESSION_ID_HEADER=`x-ash-session-id`,ASH_STREAM_FORMAT_HEADER=`x-ash-stream-format`,ASH_STREAM_VERSION_HEADER=`x-ash-stream-version`,ASH_MESSAGE_STREAM_CONTENT_TYPE=`application/x-ndjson; charset=utf-8`,ASH_MESSAGE_STREAM_FORMAT=`ndjson`,ASH_MESSAGE_STREAM_VERSION=`14`,textEncoder=new TextEncoder;function isCurrentTurnBoundaryEvent(e){return e.type===`session.completed`||e.type===`session.failed`||e.type===`session.waiting`}function createSessionStartedEvent(e){let t={};return e?.invocation!==void 0&&(t.invocation=e.invocation),e?.runtime!==void 0&&(t.runtime=e.runtime),{data:t,type:`session.started`}}function createTurnStartedEvent(e){return{data:{sequence:e.sequence,turnId:e.turnId},type:`turn.started`}}function createMessageReceivedEvent(e){return{data:{message:summarizeUserContent(e.message),sequence:e.sequence,turnId:e.turnId},type:`message.received`}}function summarizeUserContent(e){if(typeof e==`string`)return e;let t=[];for(let n of e)if(n.type===`text`)t.push(n.text);else if(n.type===`file`){let e=n.filename??n.mediaType;t.push(`[file: ${e} (${n.mediaType})]`)}else n.type===`image`&&t.push(`[image: ${n.mediaType??`image`}]`);return t.join(`
2
2
  `)}function createActionsRequestedEvent(e){return{data:{actions:e.actions,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`actions.requested`}}function createConnectionAuthorizationRequiredEvent(e){let t={connectionName:e.connectionName,description:e.description,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId};return e.authorization!==void 0&&(t.authorization=e.authorization),e.webhookUrl!==void 0&&(t.webhookUrl=e.webhookUrl),{data:t,type:`connection.authorization_required`}}function createConnectionAuthorizationPendingEvent(e){return{data:{connectionNames:e.connectionNames,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`connection.authorization_pending`}}function createConnectionAuthorizationCompletedEvent(e){let t={connectionName:e.connectionName,outcome:e.outcome,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId};return e.reason!==void 0&&(t.reason=e.reason),{data:t,type:`connection.authorization_completed`}}function createInputRequestedEvent(e){return{data:{requests:e.requests,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`input.requested`}}function createActionResultEvent(e){let t=normalizeActionResultOutcome(e.result);return{data:{error:t.error,result:e.result,sequence:e.sequence,stepIndex:e.stepIndex,status:t.status,turnId:e.turnId},type:`action.result`}}function createSubagentCalledEvent(e){return{data:{callId:e.callId,childSessionId:e.childSessionId,sessionId:e.sessionId,sequence:e.sequence,name:e.name,remote:e.remote,toolName:e.toolName,turnId:e.turnId,workflowId:e.workflowId},type:`subagent.called`}}function createMessageAppendedEvent(e){return{data:{messageDelta:e.messageDelta,messageSoFar:e.messageSoFar,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`message.appended`}}function createReasoningAppendedEvent(e){return{data:{reasoningDelta:e.reasoningDelta,reasoningSoFar:e.reasoningSoFar,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`reasoning.appended`}}function createMessageCompletedEvent(e){return{data:{finishReason:e.finishReason??`stop`,message:e.message,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`message.completed`}}function createReasoningCompletedEvent(e){return{data:{reasoning:e.reasoning,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`reasoning.completed`}}function createStepStartedEvent(e){return{data:{sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`step.started`}}function createStepCompletedEvent(e){let t={finishReason:e.finishReason,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId};return e.usage!==void 0&&(t.usage=e.usage),{data:t,type:`step.completed`}}function createStepFailedEvent(e){return{data:{code:e.code,details:e.details,message:e.message,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`step.failed`}}function createTurnCompletedEvent(e){return{data:{sequence:e.sequence,turnId:e.turnId},type:`turn.completed`}}function createTurnFailedEvent(e){return{data:{code:e.code,details:e.details,message:e.message,sequence:e.sequence,turnId:e.turnId},type:`turn.failed`}}function createCompactionRequestedEvent(e){return{data:{modelId:e.modelId,sequence:e.sequence,sessionId:e.sessionId,turnId:e.turnId,usageInputTokens:e.usageInputTokens??null},type:`compaction.requested`}}function createCompactionCompletedEvent(e){return{data:{modelId:e.modelId,sequence:e.sequence,sessionId:e.sessionId,turnId:e.turnId},type:`compaction.completed`}}function createSessionWaitingEvent(){return{data:{wait:`next-user-message`},type:`session.waiting`}}function createSessionFailedEvent(e){return{data:{code:e.code,details:e.details,message:e.message,sessionId:e.sessionId},type:`session.failed`}}function createSessionCompletedEvent(){return{type:`session.completed`}}function timestampHandleMessageStreamEvent(e,t=new Date().toISOString()){return{...e,meta:{at:t}}}function encodeMessageStreamEvent(e){return textEncoder.encode(`${JSON.stringify(e)}\n`)}function normalizeActionResultOutcome(e){if(e.isError===!0)return{error:buildActionResultError(e),status:`failed`};let t=readActionResultOutputError(e.output);return t===void 0?{status:`completed`}:{error:t,status:`failed`}}function buildActionResultError(e){let t=readActionResultOutputError(e.output);return t===void 0?{code:`ACTION_RESULT_FAILED`,message:formatActionResultOutput(e.output)}:t}function readActionResultOutputError(e){let t=parseActionResultOutputRecord(e);if(t===void 0)return;let n=typeof t.code==`string`&&t.code.length>0?t.code:void 0,r=typeof t.message==`string`&&t.message.length>0?t.message:void 0;if(!(n===void 0||r===void 0))return{code:n,message:r}}function parseActionResultOutputRecord(e){if(typeof e==`object`&&e)return e;if(typeof e!=`string`)return;let t=e.trim();if(t.length!==0)try{let e=JSON.parse(t);if(typeof e==`object`&&e)return e}catch{return}}function formatActionResultOutput(e){if(typeof e==`string`)return e;let t=JSON.stringify(e);return typeof t==`string`&&t.length>0?t:`Action failed.`}export{ASH_MESSAGE_STREAM_CONTENT_TYPE,ASH_MESSAGE_STREAM_FORMAT,ASH_MESSAGE_STREAM_VERSION,ASH_SESSION_ID_HEADER,ASH_STREAM_FORMAT_HEADER,ASH_STREAM_VERSION_HEADER,createActionResultEvent,createActionsRequestedEvent,createCompactionCompletedEvent,createCompactionRequestedEvent,createConnectionAuthorizationCompletedEvent,createConnectionAuthorizationPendingEvent,createConnectionAuthorizationRequiredEvent,createInputRequestedEvent,createMessageAppendedEvent,createMessageCompletedEvent,createMessageReceivedEvent,createReasoningAppendedEvent,createReasoningCompletedEvent,createSessionCompletedEvent,createSessionFailedEvent,createSessionStartedEvent,createSessionWaitingEvent,createStepCompletedEvent,createStepFailedEvent,createStepStartedEvent,createSubagentCalledEvent,createTurnCompletedEvent,createTurnFailedEvent,createTurnStartedEvent,encodeMessageStreamEvent,isCurrentTurnBoundaryEvent,timestampHandleMessageStreamEvent};
@@ -1 +1 @@
1
- var ASH_ROUTE_PREFIX=`/ash/v1`,ASH_HEALTH_ROUTE_PATH=`${ASH_ROUTE_PREFIX}/health`,ASH_INFO_ROUTE_PATH=`${ASH_ROUTE_PREFIX}/info`,ASH_CREATE_SESSION_ROUTE_PATH=`${ASH_ROUTE_PREFIX}/session`,ASH_CONTINUE_SESSION_ROUTE_PATTERN=`${ASH_ROUTE_PREFIX}/session/:sessionId`,ASH_MESSAGE_STREAM_ROUTE_PATTERN=`${ASH_ROUTE_PREFIX}/session/:sessionId/stream`,ASH_CONNECTION_CALLBACK_ROUTE_PATTERN=`${ASH_ROUTE_PREFIX}/connections/:name/callback/:token`,ASH_CALLBACK_ROUTE_PATTERN=`${ASH_ROUTE_PREFIX}/callback/:token`;function createAshMessageStreamRoutePath(e){return`${ASH_ROUTE_PREFIX}/session/${encodeURIComponent(e)}/stream`}function createAshContinueSessionRoutePath(e){return`${ASH_ROUTE_PREFIX}/session/${encodeURIComponent(e)}`}function createAshConnectionCallbackRoutePath(e,t){return`${ASH_ROUTE_PREFIX}/connections/${encodeURIComponent(e)}/callback/${encodeURIComponent(t)}`}function createAshCallbackRoutePath(e){return`${ASH_ROUTE_PREFIX}/callback/${encodeURIComponent(e)}`}export{ASH_CALLBACK_ROUTE_PATTERN,ASH_CONNECTION_CALLBACK_ROUTE_PATTERN,ASH_CONTINUE_SESSION_ROUTE_PATTERN,ASH_CREATE_SESSION_ROUTE_PATH,ASH_HEALTH_ROUTE_PATH,ASH_INFO_ROUTE_PATH,ASH_MESSAGE_STREAM_ROUTE_PATTERN,ASH_ROUTE_PREFIX,createAshCallbackRoutePath,createAshConnectionCallbackRoutePath,createAshContinueSessionRoutePath,createAshMessageStreamRoutePath};
1
+ const ASH_ROUTE_PREFIX=`/ash/v1`,ASH_HEALTH_ROUTE_PATH=`${ASH_ROUTE_PREFIX}/health`,ASH_INFO_ROUTE_PATH=`${ASH_ROUTE_PREFIX}/info`,ASH_CREATE_SESSION_ROUTE_PATH=`${ASH_ROUTE_PREFIX}/session`,ASH_CONTINUE_SESSION_ROUTE_PATTERN=`${ASH_ROUTE_PREFIX}/session/:sessionId`,ASH_MESSAGE_STREAM_ROUTE_PATTERN=`${ASH_ROUTE_PREFIX}/session/:sessionId/stream`,ASH_CONNECTION_CALLBACK_ROUTE_PATTERN=`${ASH_ROUTE_PREFIX}/connections/:name/callback/:token`,ASH_CALLBACK_ROUTE_PATTERN=`${ASH_ROUTE_PREFIX}/callback/:token`;function createAshMessageStreamRoutePath(e){return`${ASH_ROUTE_PREFIX}/session/${encodeURIComponent(e)}/stream`}function createAshContinueSessionRoutePath(e){return`${ASH_ROUTE_PREFIX}/session/${encodeURIComponent(e)}`}function createAshConnectionCallbackRoutePath(e,t){return`${ASH_ROUTE_PREFIX}/connections/${encodeURIComponent(e)}/callback/${encodeURIComponent(t)}`}function createAshCallbackRoutePath(e){return`${ASH_ROUTE_PREFIX}/callback/${encodeURIComponent(e)}`}export{ASH_CALLBACK_ROUTE_PATTERN,ASH_CONNECTION_CALLBACK_ROUTE_PATTERN,ASH_CONTINUE_SESSION_ROUTE_PATTERN,ASH_CREATE_SESSION_ROUTE_PATH,ASH_HEALTH_ROUTE_PATH,ASH_INFO_ROUTE_PATH,ASH_MESSAGE_STREAM_ROUTE_PATTERN,ASH_ROUTE_PREFIX,createAshCallbackRoutePath,createAshConnectionCallbackRoutePath,createAshContinueSessionRoutePath,createAshMessageStreamRoutePath};
@@ -1,2 +1,2 @@
1
- import{ASH_MESSAGE_STREAM_CONTENT_TYPE,ASH_MESSAGE_STREAM_FORMAT,ASH_MESSAGE_STREAM_VERSION,ASH_SESSION_ID_HEADER,ASH_STREAM_FORMAT_HEADER,ASH_STREAM_VERSION_HEADER}from"#protocol/message.js";import{isInputResponse}from"#runtime/input/types.js";import{parseJsonObject}from"#shared/json.js";import"ai";import{parseSessionCallback}from"#channel/session-callback.js";import{createUnauthorizedResponse}from"#public/channels/auth.js";import{collectUploadPolicyViolations,formatUploadPolicyViolation,mergeUploadPolicy}from"#public/channels/upload-policy.js";import{GET,POST,defineChannel}from"#public/definitions/defineChannel.js";function ashChannel(o){let s=mergeUploadPolicy(o.uploadPolicy);return defineChannel({routes:[POST(`/ash/v1/session`,async(e,{send:t})=>{let n=await runRouteAuth(o.auth,e);if(n instanceof Response)return n;let i=n,a;try{a=await e.json()}catch{return Response.json({error:`Invalid JSON body.`,ok:!1},{status:400})}if(typeof a!=`object`||!a)return Response.json({error:`Expected a JSON object.`,ok:!1},{status:400});let c=parseCreateBody(a);if(c instanceof Response)return c;let l=checkUploadPolicy(c,s);if(l!==null)return l;let u=`ash:${crypto.randomUUID()}`,d=await t(createSendPayload(c),{auth:i,callback:c.callback,continuationToken:u,mode:c.mode});return Response.json({continuationToken:d.continuationToken,ok:!0,sessionId:d.id},{headers:{"cache-control":`no-store`,[ASH_SESSION_ID_HEADER]:d.id},status:202})}),POST(`/ash/v1/session/:sessionId`,async(e,{send:t,getSession:n,params:i})=>{let a=await runRouteAuth(o.auth,e);if(a instanceof Response)return a;let c=a,l=i.sessionId;if(!l)return Response.json({error:`Missing session id.`,ok:!1},{status:400});try{n(l)}catch{return Response.json({error:`Session not found.`,ok:!1},{status:404})}let u;try{u=await e.json()}catch{return Response.json({error:`Invalid JSON body.`,ok:!1},{status:400})}if(typeof u!=`object`||!u)return Response.json({error:`Expected a JSON object.`,ok:!1},{status:400});let d=parseContinueBody(u);if(d instanceof Response)return d;let f=checkUploadPolicy(d,s);if(f!==null)return f;let p=await t({inputResponses:d.inputResponses,message:d.message,modelContext:d.modelContext},{auth:c,continuationToken:d.continuationToken});return Response.json({ok:!0,sessionId:p.id},{headers:{"cache-control":`no-store`,[ASH_SESSION_ID_HEADER]:p.id},status:200})}),GET(`/ash/v1/session/:sessionId/stream`,async(s,{getSession:c,params:l})=>{let u=await runRouteAuth(o.auth,s);if(u instanceof Response)return u;let d=l.sessionId;if(!d)return Response.json({error:`Missing session id.`,ok:!1},{status:400});let f=parseStartIndex(s);if(f instanceof Response)return f;try{let o=serializeAsNdjson(await c(d).getEventStream({startIndex:f}));return new Response(o,{headers:{"cache-control":`no-store`,"content-type":ASH_MESSAGE_STREAM_CONTENT_TYPE,[ASH_SESSION_ID_HEADER]:d,[ASH_STREAM_FORMAT_HEADER]:ASH_MESSAGE_STREAM_FORMAT,[ASH_STREAM_VERSION_HEADER]:ASH_MESSAGE_STREAM_VERSION}})}catch{return Response.json({error:`Session not found.`,ok:!1},{status:404})}})]})}async function runRouteAuth(e,t){let n=await e(t);return n===null?createUnauthorizedResponse({challenges:[{scheme:`Bearer`}]}):n??null}function parseCreateBody(e){let t=parseMessageField(e.message);if(t instanceof Response)return t;let n=parseClientContextField(e.clientContext);if(n instanceof Response)return n;let r=parseCallbackField(e.callback);if(r instanceof Response)return r;let i=parseModeField(e.mode);return i instanceof Response?i:t===void 0?Response.json({error:`Missing or empty 'message' field.`,ok:!1},{status:400}):{callback:r,message:t,mode:i,modelContext:n}}function parseContinueBody(e){let t=typeof e.continuationToken==`string`&&e.continuationToken.length>0?e.continuationToken:void 0;if(t===void 0)return Response.json({error:`Missing or empty 'continuationToken' field.`,ok:!1},{status:400});let n=parseMessageField(e.message);if(n instanceof Response)return n;let r=parseInputResponses(e.inputResponses);if(r instanceof Response)return r;let i=parseClientContextField(e.clientContext);return i instanceof Response?i:n===void 0&&r===void 0?Response.json({error:`Expected a non-empty 'message', a non-empty 'inputResponses' array, or both.`,ok:!1},{status:400}):{message:n,continuationToken:t,inputResponses:r,modelContext:i}}function createSendPayload(e){return e.modelContext===void 0?e.message:{message:e.message,modelContext:e.modelContext}}function parseCallbackField(e){if(e===void 0)return;let t=parseSessionCallback(e);return t.ok?t.callback:Response.json({error:t.message,ok:!1},{status:400})}function parseModeField(e){if(e!==void 0)return e===`conversation`||e===`task`?e:Response.json({error:`Expected 'mode' to be either 'conversation' or 'task'.`,ok:!1},{status:400})}function parseMessageField(e){if(e===void 0)return;if(typeof e==`string`)return e.length>0?e:void 0;if(!Array.isArray(e))return Response.json({error:`Expected 'message' to be a string or an array of text/file parts.`,ok:!1},{status:400});if(e.length===0)return;let t=[];for(let n of e){let e=parseMessagePart(n);if(e instanceof Response)return e;t.push(e)}return t}function parseMessagePart(e){if(typeof e!=`object`||!e)return Response.json({error:`Expected each message part to be an object.`,ok:!1},{status:400});let t=e;if(t.type===`text`)return typeof t.text!=`string`||t.text.length===0?Response.json({error:`Text parts require a non-empty 'text' string.`,ok:!1},{status:400}):{type:`text`,text:t.text};if(t.type===`file`){if(typeof t.mediaType!=`string`||t.mediaType.length===0)return Response.json({error:`File parts require a non-empty 'mediaType' string.`,ok:!1},{status:400});if(typeof t.data!=`string`)return Response.json({error:`File parts require a 'data' string (base64, data URL, or URL).`,ok:!1},{status:400});let e={type:`file`,mediaType:t.mediaType,data:t.data};return typeof t.filename==`string`&&t.filename.length>0&&(e.filename=t.filename),e}return Response.json({error:`Unsupported message part type "${String(t.type)}". Use 'text' or 'file'.`,ok:!1},{status:400})}function checkUploadPolicy(e,t){if(!e.message)return null;let n=collectUploadPolicyViolations(e.message,t);if(n.length===0)return null;let[r]=n;if(!r)return null;let i=r.kind===`too-large`?413:415;return Response.json({error:formatUploadPolicyViolation(r),ok:!1,violations:n.map(e=>e.kind===`too-large`?{byteLength:e.byteLength,filename:e.filename,kind:e.kind,limit:e.limit,mediaType:e.mediaType}:{allowedMediaTypes:e.allowedMediaTypes,filename:e.filename,kind:e.kind,mediaType:e.mediaType})},{status:i})}function parseInputResponses(e){if(e===void 0)return;if(!Array.isArray(e)||e.length===0)return Response.json({error:`Expected 'inputResponses' to be a non-empty array.`,ok:!1},{status:400});let t=e.filter(isInputResponse);return t.length===e.length?t:Response.json({error:`Expected every 'inputResponses' entry to match the HITL response schema.`,ok:!1},{status:400})}var CLIENT_CONTEXT_PREFIX=`Ephemeral client context:
2
- `;function parseClientContextField(e){if(e!==void 0){if(typeof e==`string`)return e.length>0?[toClientContextMessage(e)]:void 0;if(Array.isArray(e))return e.length===0?void 0:e.every(e=>typeof e==`string`&&e.length>0)?e.map(e=>toClientContextMessage(e)):Response.json({error:`Expected 'clientContext' array entries to be non-empty strings.`,ok:!1},{status:400});if(typeof e!=`object`||!e)return Response.json({error:`Expected 'clientContext' to be a string, string array, or JSON object.`,ok:!1},{status:400});try{let t=parseJsonObject(e);return[toClientContextMessage(JSON.stringify(t))]}catch{return Response.json({error:`Expected 'clientContext' to be a JSON-serializable object.`,ok:!1},{status:400})}}}function toClientContextMessage(e){return{role:`user`,content:`${CLIENT_CONTEXT_PREFIX}${e}`}}function parseStartIndex(e){let t=new URL(e.url).searchParams.get(`startIndex`);if(t===null)return;let n=Number.parseInt(t,10);return!Number.isSafeInteger(n)||n<0?Response.json({error:`Expected startIndex to be a non-negative integer.`,ok:!1},{status:400}):n}function serializeAsNdjson(e){let t=new TextEncoder;return e.pipeThrough(new TransformStream({transform(e,n){n.enqueue(t.encode(`${JSON.stringify(e)}\n`))}}))}export{ashChannel};
1
+ import{ASH_MESSAGE_STREAM_CONTENT_TYPE,ASH_MESSAGE_STREAM_FORMAT,ASH_MESSAGE_STREAM_VERSION,ASH_SESSION_ID_HEADER,ASH_STREAM_FORMAT_HEADER,ASH_STREAM_VERSION_HEADER}from"#protocol/message.js";import{isInputResponse}from"#runtime/input/types.js";import{parseJsonObject}from"#shared/json.js";import"ai";import{parseSessionCallback}from"#channel/session-callback.js";import{createUnauthorizedResponse}from"#public/channels/auth.js";import{collectUploadPolicyViolations,formatUploadPolicyViolation,mergeUploadPolicy}from"#public/channels/upload-policy.js";import{GET,POST,defineChannel}from"#public/definitions/defineChannel.js";function ashChannel(o){let s=mergeUploadPolicy(o.uploadPolicy);return defineChannel({routes:[POST(`/ash/v1/session`,async(e,{send:t})=>{let n=await runRouteAuth(o.auth,e);if(n instanceof Response)return n;let i=n,a;try{a=await e.json()}catch{return Response.json({error:`Invalid JSON body.`,ok:!1},{status:400})}if(typeof a!=`object`||!a)return Response.json({error:`Expected a JSON object.`,ok:!1},{status:400});let c=parseCreateBody(a);if(c instanceof Response)return c;let l=checkUploadPolicy(c,s);if(l!==null)return l;let u=`ash:${crypto.randomUUID()}`,d=await t(createSendPayload(c),{auth:i,callback:c.callback,continuationToken:u,mode:c.mode});return Response.json({continuationToken:d.continuationToken,ok:!0,sessionId:d.id},{headers:{"cache-control":`no-store`,[ASH_SESSION_ID_HEADER]:d.id},status:202})}),POST(`/ash/v1/session/:sessionId`,async(e,{send:t,getSession:n,params:i})=>{let a=await runRouteAuth(o.auth,e);if(a instanceof Response)return a;let c=a,l=i.sessionId;if(!l)return Response.json({error:`Missing session id.`,ok:!1},{status:400});try{n(l)}catch{return Response.json({error:`Session not found.`,ok:!1},{status:404})}let u;try{u=await e.json()}catch{return Response.json({error:`Invalid JSON body.`,ok:!1},{status:400})}if(typeof u!=`object`||!u)return Response.json({error:`Expected a JSON object.`,ok:!1},{status:400});let d=parseContinueBody(u);if(d instanceof Response)return d;let f=checkUploadPolicy(d,s);if(f!==null)return f;let p=await t({inputResponses:d.inputResponses,message:d.message,modelContext:d.modelContext},{auth:c,continuationToken:d.continuationToken});return Response.json({ok:!0,sessionId:p.id},{headers:{"cache-control":`no-store`,[ASH_SESSION_ID_HEADER]:p.id},status:200})}),GET(`/ash/v1/session/:sessionId/stream`,async(s,{getSession:c,params:l})=>{let u=await runRouteAuth(o.auth,s);if(u instanceof Response)return u;let d=l.sessionId;if(!d)return Response.json({error:`Missing session id.`,ok:!1},{status:400});let f=parseStartIndex(s);if(f instanceof Response)return f;try{let o=serializeAsNdjson(await c(d).getEventStream({startIndex:f}));return new Response(o,{headers:{"cache-control":`no-store`,"content-type":ASH_MESSAGE_STREAM_CONTENT_TYPE,[ASH_SESSION_ID_HEADER]:d,[ASH_STREAM_FORMAT_HEADER]:ASH_MESSAGE_STREAM_FORMAT,[ASH_STREAM_VERSION_HEADER]:ASH_MESSAGE_STREAM_VERSION}})}catch{return Response.json({error:`Session not found.`,ok:!1},{status:404})}})]})}async function runRouteAuth(e,t){let n=await e(t);return n===null?createUnauthorizedResponse({challenges:[{scheme:`Bearer`}]}):n??null}function parseCreateBody(e){let t=parseMessageField(e.message);if(t instanceof Response)return t;let n=parseClientContextField(e.clientContext);if(n instanceof Response)return n;let r=parseCallbackField(e.callback);if(r instanceof Response)return r;let i=parseModeField(e.mode);return i instanceof Response?i:t===void 0?Response.json({error:`Missing or empty 'message' field.`,ok:!1},{status:400}):{callback:r,message:t,mode:i,modelContext:n}}function parseContinueBody(e){let t=typeof e.continuationToken==`string`&&e.continuationToken.length>0?e.continuationToken:void 0;if(t===void 0)return Response.json({error:`Missing or empty 'continuationToken' field.`,ok:!1},{status:400});let n=parseMessageField(e.message);if(n instanceof Response)return n;let r=parseInputResponses(e.inputResponses);if(r instanceof Response)return r;let i=parseClientContextField(e.clientContext);return i instanceof Response?i:n===void 0&&r===void 0?Response.json({error:`Expected a non-empty 'message', a non-empty 'inputResponses' array, or both.`,ok:!1},{status:400}):{message:n,continuationToken:t,inputResponses:r,modelContext:i}}function createSendPayload(e){return e.modelContext===void 0?e.message:{message:e.message,modelContext:e.modelContext}}function parseCallbackField(e){if(e===void 0)return;let t=parseSessionCallback(e);return t.ok?t.callback:Response.json({error:t.message,ok:!1},{status:400})}function parseModeField(e){if(e!==void 0)return e===`conversation`||e===`task`?e:Response.json({error:`Expected 'mode' to be either 'conversation' or 'task'.`,ok:!1},{status:400})}function parseMessageField(e){if(e===void 0)return;if(typeof e==`string`)return e.length>0?e:void 0;if(!Array.isArray(e))return Response.json({error:`Expected 'message' to be a string or an array of text/file parts.`,ok:!1},{status:400});if(e.length===0)return;let t=[];for(let n of e){let e=parseMessagePart(n);if(e instanceof Response)return e;t.push(e)}return t}function parseMessagePart(e){if(typeof e!=`object`||!e)return Response.json({error:`Expected each message part to be an object.`,ok:!1},{status:400});let t=e;if(t.type===`text`)return typeof t.text!=`string`||t.text.length===0?Response.json({error:`Text parts require a non-empty 'text' string.`,ok:!1},{status:400}):{type:`text`,text:t.text};if(t.type===`file`){if(typeof t.mediaType!=`string`||t.mediaType.length===0)return Response.json({error:`File parts require a non-empty 'mediaType' string.`,ok:!1},{status:400});if(typeof t.data!=`string`)return Response.json({error:`File parts require a 'data' string (base64, data URL, or URL).`,ok:!1},{status:400});let e={type:`file`,mediaType:t.mediaType,data:t.data};return typeof t.filename==`string`&&t.filename.length>0&&(e.filename=t.filename),e}return Response.json({error:`Unsupported message part type "${String(t.type)}". Use 'text' or 'file'.`,ok:!1},{status:400})}function checkUploadPolicy(e,t){if(!e.message)return null;let n=collectUploadPolicyViolations(e.message,t);if(n.length===0)return null;let[r]=n;if(!r)return null;let i=r.kind===`too-large`?413:415;return Response.json({error:formatUploadPolicyViolation(r),ok:!1,violations:n.map(e=>e.kind===`too-large`?{byteLength:e.byteLength,filename:e.filename,kind:e.kind,limit:e.limit,mediaType:e.mediaType}:{allowedMediaTypes:e.allowedMediaTypes,filename:e.filename,kind:e.kind,mediaType:e.mediaType})},{status:i})}function parseInputResponses(e){if(e===void 0)return;if(!Array.isArray(e)||e.length===0)return Response.json({error:`Expected 'inputResponses' to be a non-empty array.`,ok:!1},{status:400});let t=e.filter(isInputResponse);return t.length===e.length?t:Response.json({error:`Expected every 'inputResponses' entry to match the HITL response schema.`,ok:!1},{status:400})}function parseClientContextField(e){if(e!==void 0){if(typeof e==`string`)return e.length>0?[toClientContextMessage(e)]:void 0;if(Array.isArray(e))return e.length===0?void 0:e.every(e=>typeof e==`string`&&e.length>0)?e.map(e=>toClientContextMessage(e)):Response.json({error:`Expected 'clientContext' array entries to be non-empty strings.`,ok:!1},{status:400});if(typeof e!=`object`||!e)return Response.json({error:`Expected 'clientContext' to be a string, string array, or JSON object.`,ok:!1},{status:400});try{let t=parseJsonObject(e);return[toClientContextMessage(JSON.stringify(t))]}catch{return Response.json({error:`Expected 'clientContext' to be a JSON-serializable object.`,ok:!1},{status:400})}}}function toClientContextMessage(e){return{role:`user`,content:`Ephemeral client context:
2
+ ${e}`}}function parseStartIndex(e){let t=new URL(e.url).searchParams.get(`startIndex`);if(t===null)return;let n=Number.parseInt(t,10);return!Number.isSafeInteger(n)||n<0?Response.json({error:`Expected startIndex to be a non-negative integer.`,ok:!1},{status:400}):n}function serializeAsNdjson(e){let t=new TextEncoder;return e.pipeThrough(new TransformStream({transform(e,n){n.enqueue(t.encode(`${JSON.stringify(e)}\n`))}}))}export{ashChannel};
@@ -1 +1 @@
1
- import{createLogger}from"#internal/logging.js";import{decodeJwt}from"#compiled/jose/index.js";import{authenticateHttpBasicStrategy}from"#runtime/governance/auth/http-basic.js";import{authenticateJwtEcdsaStrategy}from"#runtime/governance/auth/jwt-ecdsa.js";import{authenticateJwtHmacStrategy}from"#runtime/governance/auth/jwt-hmac.js";import{authenticateOidcStrategy}from"#runtime/governance/auth/oidc.js";import{createRuntimeSessionAuthContext}from"#runtime/governance/auth/types.js";import{createRuntimeIpAllowList,isRuntimeIpAllowed}from"#runtime/governance/network/ip-allow-list.js";var vercelOidcLog=createLogger(`auth.vercel-oidc`);function verifyHttpBasic(e,t){if(e===null)return{ok:!1};let r=authenticateHttpBasicStrategy({authorization:e,strategy:{kind:`http-basic`,password:t.password,username:t.username}});return r.kind===`authenticated`?{ok:!0,sessionAuth:createRuntimeSessionAuthContext(r.principal)}:{ok:!1}}async function verifyJwtHmac(e,t){if(e===null||e.length===0)return{ok:!1};let n=await authenticateJwtHmacStrategy({strategy:{algorithm:t.algorithm,audiences:[...t.audiences],clockSkewSeconds:t.clockSkewSeconds??30,issuer:t.issuer,kind:`jwt-hmac`,secret:t.secret,...t.claims===void 0?{}:{claims:t.claims},...t.subjects===void 0?{}:{subjects:t.subjects}},token:e});return n.kind===`authenticated`?{ok:!0,sessionAuth:createRuntimeSessionAuthContext(n.principal)}:{ok:!1}}async function verifyJwtEcdsa(e,t){if(e===null||e.length===0)return{ok:!1};let n=await authenticateJwtEcdsaStrategy({strategy:{algorithm:t.algorithm,audiences:[...t.audiences],clockSkewSeconds:t.clockSkewSeconds??30,issuer:t.issuer,kind:`jwt-ecdsa`,publicKey:t.publicKey,...t.claims===void 0?{}:{claims:t.claims},...t.subjects===void 0?{}:{subjects:t.subjects}},token:e});return n.kind===`authenticated`?{ok:!0,sessionAuth:createRuntimeSessionAuthContext(n.principal)}:{ok:!1}}async function verifyOidc(e,t){let n=await runOidcVerification(e,{...t,acceptCurrentVercelProject:!1});return n.kind===`authenticated`?{ok:!0,sessionAuth:createRuntimeSessionAuthContext(n.principal)}:{ok:!1}}async function runOidcVerification(e,t){return e===null||e.length===0?{kind:`not-authenticated`}:await authenticateOidcStrategy({strategy:{acceptCurrentVercelProject:t.acceptCurrentVercelProject,audiences:[...t.audiences],clockSkewSeconds:t.clockSkewSeconds??30,discoveryUrl:t.discoveryUrl??`${t.issuer.replace(/\/$/,``)}/.well-known/openid-configuration`,issuer:t.issuer,kind:`oidc`,...t.claims===void 0?{}:{claims:t.claims},...t.subjects===void 0?{}:{subjects:t.subjects}},token:e})}function extractBearerToken(e){if(e===null)return null;let t=/^Bearer\s+(.+)$/i.exec(e)?.[1]?.trim();return t===void 0||t.length===0?null:t}function createIpAllowList(e){return createRuntimeIpAllowList(e)}function isIpAllowed(e,t){return e===null?!1:isRuntimeIpAllowed(e,t)}function createUnauthorizedResponse(e={}){let t=e.status??401,n=e.code??(t===403?`forbidden`:`unauthorized`),r=e.message??(t===403?`Forbidden.`:`Authorization is required for this route.`),i=e.challenges??[],a=new Headers({"cache-control":`no-store`});for(let e of i)a.append(`www-authenticate`,formatChallenge(e));return Response.json({code:n,error:r,ok:!1},{headers:a,status:t})}function formatChallenge(e){if(e.parameters===void 0||Object.keys(e.parameters).length===0)return e.scheme;let t=Object.entries(e.parameters).map(([e,t])=>`${e}="${escapeChallengeValue(t)}"`).join(`, `);return`${e.scheme} ${t}`}function escapeChallengeValue(e){return e.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`)}function none(){return()=>void 0}var VERCEL_OIDC_ISSUER_PREFIX=`https://oidc.vercel.com/`;async function verifyVercelOidc(e,t={}){if(e===null||e.length===0)return vercelOidcLog.debug(`Rejected request without a bearer token.`),{ok:!1};let n=decodeUnverifiedJwtClaims(e);if(n===null)return vercelOidcLog.debug(`Rejected token that failed to decode as a JWT.`),{ok:!1};if(!n.issuer.startsWith(VERCEL_OIDC_ISSUER_PREFIX))return vercelOidcLog.debug(`Rejected token whose issuer is not a Vercel OIDC issuer.`,{issuer:n.issuer}),{ok:!1};if(n.audiences.length===0)return vercelOidcLog.debug(`Rejected token with no audience claim.`,{issuer:n.issuer}),{ok:!1};let r=await runOidcVerification(e,{acceptCurrentVercelProject:!0,audiences:n.audiences,issuer:n.issuer,subjects:t.subjects??[]});return r.kind===`authenticated`?(vercelOidcLog.debug(`Accepted Vercel OIDC token.`,{issuer:n.issuer,principalType:r.principal.principalType,subject:r.principal.subject}),{ok:!0,sessionAuth:createRuntimeSessionAuthContext(r.principal)}):(vercelOidcLog.debug(`Rejected Vercel OIDC token after verification.`,{audiences:n.audiences,issuer:n.issuer,reason:r.kind,subjectsConfigured:(t.subjects??[]).length>0,...r.kind===`misconfigured`?{detail:r.message}:{}}),{ok:!1})}function vercelSubject(e){assertVercelSubjectSegment(`teamSlug`,e.teamSlug),assertVercelSubjectSegment(`projectName`,e.projectName);let t=e.environment??`production`;if(t!==`production`&&t!==`preview`&&t!==`development`&&t!==`*`)throw Error(`vercelSubject: invalid environment ${JSON.stringify(t)}; expected "production", "preview", "development", or "*".`);return`owner:${e.teamSlug}:project:${e.projectName}:environment:${t}`}function assertVercelSubjectSegment(e,t){if(t.length===0)throw Error(`vercelSubject: ${e} must be a non-empty string.`);if(t.includes(`*`)||t.includes(`:`))throw Error(`vercelSubject: ${e} ${JSON.stringify(t)} may not contain ${t.includes(`:`)?`':'`:`'*'`}. Hand-write the subject string when wildcards are intentional.`)}function vercelOidc(e={}){return async t=>{let n=await verifyVercelOidc(extractBearerToken(t.headers.get(`authorization`)),e);return n.ok?n.sessionAuth:null}}function httpBasic(e){return t=>{let n=verifyHttpBasic(t.headers.get(`authorization`),e);return n.ok?n.sessionAuth:null}}function jwtHmac(e){return async t=>{let n=await verifyJwtHmac(extractBearerToken(t.headers.get(`authorization`)),e);return n.ok?n.sessionAuth:null}}function jwtEcdsa(e){return async t=>{let n=await verifyJwtEcdsa(extractBearerToken(t.headers.get(`authorization`)),e);return n.ok?n.sessionAuth:null}}function oidc(e){return async t=>{let n=await verifyOidc(extractBearerToken(t.headers.get(`authorization`)),e);return n.ok?n.sessionAuth:null}}function decodeUnverifiedJwtClaims(e){let n;try{n=decodeJwt(e)}catch{return null}return typeof n.iss!=`string`||n.iss.length===0?null:{audiences:typeof n.aud==`string`?[n.aud]:Array.isArray(n.aud)?n.aud.filter(e=>typeof e==`string`):[],issuer:n.iss}}export{createIpAllowList,createUnauthorizedResponse,extractBearerToken,httpBasic,isIpAllowed,jwtEcdsa,jwtHmac,none,oidc,vercelOidc,vercelSubject,verifyHttpBasic,verifyJwtEcdsa,verifyJwtHmac,verifyOidc,verifyVercelOidc};
1
+ import{createLogger}from"#internal/logging.js";import{decodeJwt}from"#compiled/jose/index.js";import{authenticateHttpBasicStrategy}from"#runtime/governance/auth/http-basic.js";import{authenticateJwtEcdsaStrategy}from"#runtime/governance/auth/jwt-ecdsa.js";import{authenticateJwtHmacStrategy}from"#runtime/governance/auth/jwt-hmac.js";import{authenticateOidcStrategy}from"#runtime/governance/auth/oidc.js";import{createRuntimeSessionAuthContext}from"#runtime/governance/auth/types.js";import{createRuntimeIpAllowList,isRuntimeIpAllowed}from"#runtime/governance/network/ip-allow-list.js";const vercelOidcLog=createLogger(`auth.vercel-oidc`);function verifyHttpBasic(e,t){if(e===null)return{ok:!1};let r=authenticateHttpBasicStrategy({authorization:e,strategy:{kind:`http-basic`,password:t.password,username:t.username}});return r.kind===`authenticated`?{ok:!0,sessionAuth:createRuntimeSessionAuthContext(r.principal)}:{ok:!1}}async function verifyJwtHmac(e,t){if(e===null||e.length===0)return{ok:!1};let n=await authenticateJwtHmacStrategy({strategy:{algorithm:t.algorithm,audiences:[...t.audiences],clockSkewSeconds:t.clockSkewSeconds??30,issuer:t.issuer,kind:`jwt-hmac`,secret:t.secret,...t.claims===void 0?{}:{claims:t.claims},...t.subjects===void 0?{}:{subjects:t.subjects}},token:e});return n.kind===`authenticated`?{ok:!0,sessionAuth:createRuntimeSessionAuthContext(n.principal)}:{ok:!1}}async function verifyJwtEcdsa(e,t){if(e===null||e.length===0)return{ok:!1};let n=await authenticateJwtEcdsaStrategy({strategy:{algorithm:t.algorithm,audiences:[...t.audiences],clockSkewSeconds:t.clockSkewSeconds??30,issuer:t.issuer,kind:`jwt-ecdsa`,publicKey:t.publicKey,...t.claims===void 0?{}:{claims:t.claims},...t.subjects===void 0?{}:{subjects:t.subjects}},token:e});return n.kind===`authenticated`?{ok:!0,sessionAuth:createRuntimeSessionAuthContext(n.principal)}:{ok:!1}}async function verifyOidc(e,t){let n=await runOidcVerification(e,{...t,acceptCurrentVercelProject:!1});return n.kind===`authenticated`?{ok:!0,sessionAuth:createRuntimeSessionAuthContext(n.principal)}:{ok:!1}}async function runOidcVerification(e,t){return e===null||e.length===0?{kind:`not-authenticated`}:await authenticateOidcStrategy({strategy:{acceptCurrentVercelProject:t.acceptCurrentVercelProject,audiences:[...t.audiences],clockSkewSeconds:t.clockSkewSeconds??30,discoveryUrl:t.discoveryUrl??`${t.issuer.replace(/\/$/,``)}/.well-known/openid-configuration`,issuer:t.issuer,kind:`oidc`,...t.claims===void 0?{}:{claims:t.claims},...t.subjects===void 0?{}:{subjects:t.subjects}},token:e})}function extractBearerToken(e){if(e===null)return null;let t=/^Bearer\s+(.+)$/i.exec(e)?.[1]?.trim();return t===void 0||t.length===0?null:t}function createIpAllowList(e){return createRuntimeIpAllowList(e)}function isIpAllowed(e,t){return e===null?!1:isRuntimeIpAllowed(e,t)}function createUnauthorizedResponse(e={}){let t=e.status??401,n=e.code??(t===403?`forbidden`:`unauthorized`),r=e.message??(t===403?`Forbidden.`:`Authorization is required for this route.`),i=e.challenges??[],a=new Headers({"cache-control":`no-store`});for(let e of i)a.append(`www-authenticate`,formatChallenge(e));return Response.json({code:n,error:r,ok:!1},{headers:a,status:t})}function formatChallenge(e){if(e.parameters===void 0||Object.keys(e.parameters).length===0)return e.scheme;let t=Object.entries(e.parameters).map(([e,t])=>`${e}="${escapeChallengeValue(t)}"`).join(`, `);return`${e.scheme} ${t}`}function escapeChallengeValue(e){return e.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`)}function none(){return()=>void 0}async function verifyVercelOidc(e,t={}){if(e===null||e.length===0)return vercelOidcLog.debug(`Rejected request without a bearer token.`),{ok:!1};let n=decodeUnverifiedJwtClaims(e);if(n===null)return vercelOidcLog.debug(`Rejected token that failed to decode as a JWT.`),{ok:!1};if(!n.issuer.startsWith(`https://oidc.vercel.com/`))return vercelOidcLog.debug(`Rejected token whose issuer is not a Vercel OIDC issuer.`,{issuer:n.issuer}),{ok:!1};if(n.audiences.length===0)return vercelOidcLog.debug(`Rejected token with no audience claim.`,{issuer:n.issuer}),{ok:!1};let r=await runOidcVerification(e,{acceptCurrentVercelProject:!0,audiences:n.audiences,issuer:n.issuer,subjects:t.subjects??[]});return r.kind===`authenticated`?(vercelOidcLog.debug(`Accepted Vercel OIDC token.`,{issuer:n.issuer,principalType:r.principal.principalType,subject:r.principal.subject}),{ok:!0,sessionAuth:createRuntimeSessionAuthContext(r.principal)}):(vercelOidcLog.debug(`Rejected Vercel OIDC token after verification.`,{audiences:n.audiences,issuer:n.issuer,reason:r.kind,subjectsConfigured:(t.subjects??[]).length>0,...r.kind===`misconfigured`?{detail:r.message}:{}}),{ok:!1})}function vercelSubject(e){assertVercelSubjectSegment(`teamSlug`,e.teamSlug),assertVercelSubjectSegment(`projectName`,e.projectName);let t=e.environment??`production`;if(t!==`production`&&t!==`preview`&&t!==`development`&&t!==`*`)throw Error(`vercelSubject: invalid environment ${JSON.stringify(t)}; expected "production", "preview", "development", or "*".`);return`owner:${e.teamSlug}:project:${e.projectName}:environment:${t}`}function assertVercelSubjectSegment(e,t){if(t.length===0)throw Error(`vercelSubject: ${e} must be a non-empty string.`);if(t.includes(`*`)||t.includes(`:`))throw Error(`vercelSubject: ${e} ${JSON.stringify(t)} may not contain ${t.includes(`:`)?`':'`:`'*'`}. Hand-write the subject string when wildcards are intentional.`)}function vercelOidc(e={}){return async t=>{let n=await verifyVercelOidc(extractBearerToken(t.headers.get(`authorization`)),e);return n.ok?n.sessionAuth:null}}function httpBasic(e){return t=>{let n=verifyHttpBasic(t.headers.get(`authorization`),e);return n.ok?n.sessionAuth:null}}function jwtHmac(e){return async t=>{let n=await verifyJwtHmac(extractBearerToken(t.headers.get(`authorization`)),e);return n.ok?n.sessionAuth:null}}function jwtEcdsa(e){return async t=>{let n=await verifyJwtEcdsa(extractBearerToken(t.headers.get(`authorization`)),e);return n.ok?n.sessionAuth:null}}function oidc(e){return async t=>{let n=await verifyOidc(extractBearerToken(t.headers.get(`authorization`)),e);return n.ok?n.sessionAuth:null}}function decodeUnverifiedJwtClaims(e){let n;try{n=decodeJwt(e)}catch{return null}return typeof n.iss!=`string`||n.iss.length===0?null:{audiences:typeof n.aud==`string`?[n.aud]:Array.isArray(n.aud)?n.aud.filter(e=>typeof e==`string`):[],issuer:n.iss}}export{createIpAllowList,createUnauthorizedResponse,extractBearerToken,httpBasic,isIpAllowed,jwtEcdsa,jwtHmac,none,oidc,vercelOidc,vercelSubject,verifyHttpBasic,verifyJwtEcdsa,verifyJwtHmac,verifyOidc,verifyVercelOidc};
@@ -1,2 +1,2 @@
1
- import{isObject}from"#shared/guards.js";import{parseJsonObject}from"#shared/json.js";import{resolveDiscordPublicKey}from"#public/channels/discord/verify.js";var DISCORD_NO_MENTIONS={parse:[]},DISCORD_MESSAGE_CONTENT_MAX_LENGTH=2e3;function discordContinuationToken(e,t){return`${e}:${t??``}`}async function resolveDiscordApplicationId(e){let t=e??process.env.DISCORD_APPLICATION_ID;if(!t)throw Error(`DISCORD_APPLICATION_ID is required.`);return typeof t==`function`?await t():t}async function resolveDiscordBotToken(e){let t=e??process.env.DISCORD_BOT_TOKEN;if(!t)throw Error(`DISCORD_BOT_TOKEN is required.`);return typeof t==`function`?await t():t}async function callDiscordApi(e){let n=e.fetch??fetch,r=new Headers;if(r.set(`content-type`,`application/json; charset=utf-8`),e.botToken!==void 0){let t=await resolveDiscordBotToken(e.botToken);r.set(`authorization`,`Bot ${t}`)}let i={headers:r,method:e.method??`POST`};e.body!==void 0&&(i.body=JSON.stringify(parseJsonObject(e.body)));let a=await n(`${e.apiBaseUrl??`https://discord.com/api/v10`}${e.path}`,i);return{body:await parseResponseBody(a),ok:a.ok,status:a.status}}async function sendDiscordChannelMessage(e){let t=await callDiscordApi({apiBaseUrl:e.apiBaseUrl,body:normalizeMessageBody(e.body),botToken:e.credentials?.botToken,fetch:e.fetch,path:`/channels/${encodeURIComponent(e.channelId)}/messages`});if(!t.ok)throw Error(`Discord create message failed with HTTP ${t.status}.`);return toPostedMessage(t.body)}async function triggerDiscordTypingIndicator(e){let t=await callDiscordApi({apiBaseUrl:e.apiBaseUrl,botToken:e.credentials?.botToken,fetch:e.fetch,path:`/channels/${encodeURIComponent(e.channelId)}/typing`});if(!t.ok)throw Error(`Discord typing indicator failed with HTTP ${t.status}.`)}async function editDiscordOriginalResponse(e){let t=await resolveDiscordApplicationId(e.credentials?.applicationId),n=await callDiscordApi({apiBaseUrl:e.apiBaseUrl,body:normalizeMessageBody(e.body),fetch:e.fetch,method:`PATCH`,path:`/webhooks/${encodeURIComponent(t)}/${encodeURIComponent(e.interactionToken)}/messages/@original`});if(!n.ok)throw Error(`Discord edit original response failed with HTTP ${n.status}.`);return toPostedMessage(n.body)}async function createDiscordFollowupMessage(e){let t=await resolveDiscordApplicationId(e.credentials?.applicationId),n=await callDiscordApi({apiBaseUrl:e.apiBaseUrl,body:normalizeMessageBody(e.body),fetch:e.fetch,path:`/webhooks/${encodeURIComponent(t)}/${encodeURIComponent(e.interactionToken)}`});if(!n.ok)throw Error(`Discord followup message failed with HTTP ${n.status}.`);return toPostedMessage(n.body)}function splitDiscordMessageContent(e){if(e.length<=2e3)return[e];let t=[],n=e;for(;n.length>DISCORD_MESSAGE_CONTENT_MAX_LENGTH;){let e=n.lastIndexOf(`
1
+ import{isObject}from"#shared/guards.js";import{parseJsonObject}from"#shared/json.js";import{resolveDiscordPublicKey}from"#public/channels/discord/verify.js";const DISCORD_NO_MENTIONS={parse:[]},DISCORD_MESSAGE_CONTENT_MAX_LENGTH=2e3;function discordContinuationToken(e,t){return`${e}:${t??``}`}async function resolveDiscordApplicationId(e){let t=e??process.env.DISCORD_APPLICATION_ID;if(!t)throw Error(`DISCORD_APPLICATION_ID is required.`);return typeof t==`function`?await t():t}async function resolveDiscordBotToken(e){let t=e??process.env.DISCORD_BOT_TOKEN;if(!t)throw Error(`DISCORD_BOT_TOKEN is required.`);return typeof t==`function`?await t():t}async function callDiscordApi(e){let n=e.fetch??fetch,r=new Headers;if(r.set(`content-type`,`application/json; charset=utf-8`),e.botToken!==void 0){let t=await resolveDiscordBotToken(e.botToken);r.set(`authorization`,`Bot ${t}`)}let i={headers:r,method:e.method??`POST`};e.body!==void 0&&(i.body=JSON.stringify(parseJsonObject(e.body)));let a=await n(`${e.apiBaseUrl??`https://discord.com/api/v10`}${e.path}`,i);return{body:await parseResponseBody(a),ok:a.ok,status:a.status}}async function sendDiscordChannelMessage(e){let t=await callDiscordApi({apiBaseUrl:e.apiBaseUrl,body:normalizeMessageBody(e.body),botToken:e.credentials?.botToken,fetch:e.fetch,path:`/channels/${encodeURIComponent(e.channelId)}/messages`});if(!t.ok)throw Error(`Discord create message failed with HTTP ${t.status}.`);return toPostedMessage(t.body)}async function triggerDiscordTypingIndicator(e){let t=await callDiscordApi({apiBaseUrl:e.apiBaseUrl,botToken:e.credentials?.botToken,fetch:e.fetch,path:`/channels/${encodeURIComponent(e.channelId)}/typing`});if(!t.ok)throw Error(`Discord typing indicator failed with HTTP ${t.status}.`)}async function editDiscordOriginalResponse(e){let t=await resolveDiscordApplicationId(e.credentials?.applicationId),n=await callDiscordApi({apiBaseUrl:e.apiBaseUrl,body:normalizeMessageBody(e.body),fetch:e.fetch,method:`PATCH`,path:`/webhooks/${encodeURIComponent(t)}/${encodeURIComponent(e.interactionToken)}/messages/@original`});if(!n.ok)throw Error(`Discord edit original response failed with HTTP ${n.status}.`);return toPostedMessage(n.body)}async function createDiscordFollowupMessage(e){let t=await resolveDiscordApplicationId(e.credentials?.applicationId),n=await callDiscordApi({apiBaseUrl:e.apiBaseUrl,body:normalizeMessageBody(e.body),fetch:e.fetch,path:`/webhooks/${encodeURIComponent(t)}/${encodeURIComponent(e.interactionToken)}`});if(!n.ok)throw Error(`Discord followup message failed with HTTP ${n.status}.`);return toPostedMessage(n.body)}function splitDiscordMessageContent(e){if(e.length<=2e3)return[e];let t=[],n=e;for(;n.length>DISCORD_MESSAGE_CONTENT_MAX_LENGTH;){let e=n.lastIndexOf(`
2
2
  `,DISCORD_MESSAGE_CONTENT_MAX_LENGTH);e<=0&&(e=n.lastIndexOf(` `,DISCORD_MESSAGE_CONTENT_MAX_LENGTH)),e<=0&&(e=DISCORD_MESSAGE_CONTENT_MAX_LENGTH),t.push(n.slice(0,e).trimEnd()),n=n.slice(e).trimStart()}return t.push(n),t}function normalizeMessageBody(e){let n={...e};return n.allowed_mentions===void 0&&(n.allowed_mentions=DISCORD_NO_MENTIONS),parseJsonObject(n)}function toPostedMessage(e){let t=parseMaybeObject(e);return{channelId:typeof t.channel_id==`string`?t.channel_id:void 0,id:typeof t.id==`string`?t.id:``,raw:e}}function parseMaybeObject(t){return isObject(t)?t:{}}async function parseResponseBody(e){let t=await e.text();if(!t)return null;try{return JSON.parse(t)}catch{return t}}export{DISCORD_MESSAGE_CONTENT_MAX_LENGTH,DISCORD_NO_MENTIONS,callDiscordApi,createDiscordFollowupMessage,discordContinuationToken,editDiscordOriginalResponse,resolveDiscordApplicationId,resolveDiscordBotToken,resolveDiscordPublicKey,sendDiscordChannelMessage,splitDiscordMessageContent,triggerDiscordTypingIndicator};
@@ -1,3 +1,3 @@
1
- import{extractErrorId,formatErrorHint}from"#internal/logging.js";import{splitDiscordMessageContent}from"#public/channels/discord/api.js";import{renderInputRequestComponents}from"#public/channels/discord/hitl.js";function defaultDiscordAuth(e){let t={channel_id:e.channelId,interaction_id:e.id,user_id:e.user.id,username:e.user.username};return e.guildId!==void 0&&(t.guild_id=e.guildId),e.member?.nick!==void 0&&(t.member_nick=e.member.nick),{attributes:t,authenticator:`discord-interaction`,issuer:e.guildId?`discord:${e.guildId}`:`discord`,principalId:e.guildId?`discord:${e.guildId}:${e.user.id}`:`discord:${e.user.id}`,principalType:e.user.isBot?`service`:`user`}}function defaultOnCommand(e,t){return{auth:defaultDiscordAuth(t)}}var defaultEvents={async"turn.started"(e,t){await t.discord.startTyping()},async"actions.requested"(e,t){await t.discord.startTyping()},async"input.requested"(e,t){for(let i of e.requests){let e=splitDiscordMessageContent(i.prompt)[0]??i.prompt;await t.discord.post({components:renderInputRequestComponents(i),content:e})}},async"message.completed"(e,t){e.finishReason===`tool-calls`||!e.message||await t.discord.post(e.message)},async"session.failed"(n,r){let i=formatErrorHint(n),a=extractErrorId(n.details);await r.discord.post([`This session could not recover from an error${i}.`,``,`Start a new command to continue.`,...a?[``,`Error id: ${a}`]:[]].join(`
1
+ import{extractErrorId,formatErrorHint}from"#internal/logging.js";import{splitDiscordMessageContent}from"#public/channels/discord/api.js";import{renderInputRequestComponents}from"#public/channels/discord/hitl.js";function defaultDiscordAuth(e){let t={channel_id:e.channelId,interaction_id:e.id,user_id:e.user.id,username:e.user.username};return e.guildId!==void 0&&(t.guild_id=e.guildId),e.member?.nick!==void 0&&(t.member_nick=e.member.nick),{attributes:t,authenticator:`discord-interaction`,issuer:e.guildId?`discord:${e.guildId}`:`discord`,principalId:e.guildId?`discord:${e.guildId}:${e.user.id}`:`discord:${e.user.id}`,principalType:e.user.isBot?`service`:`user`}}function defaultOnCommand(e,t){return{auth:defaultDiscordAuth(t)}}const defaultEvents={async"turn.started"(e,t){await t.discord.startTyping()},async"actions.requested"(e,t){await t.discord.startTyping()},async"input.requested"(e,t){for(let i of e.requests){let e=splitDiscordMessageContent(i.prompt)[0]??i.prompt;await t.discord.post({components:renderInputRequestComponents(i),content:e})}},async"message.completed"(e,t){e.finishReason===`tool-calls`||!e.message||await t.discord.post(e.message)},async"session.failed"(n,r){let i=formatErrorHint(n),a=extractErrorId(n.details);await r.discord.post([`This session could not recover from an error${i}.`,``,`Start a new command to continue.`,...a?[``,`Error id: ${a}`]:[]].join(`
2
2
  `))},async"turn.failed"(n,r){let i=formatErrorHint(n),a=extractErrorId(n.details);await r.discord.post([`I hit an error while handling your request${i}.`,``,`Please try again, rephrase, or reach out if it keeps failing.`,...a?[``,`Error id: ${a}`]:[]].join(`
3
3
  `))}};export{defaultDiscordAuth,defaultEvents,defaultOnCommand};
@@ -1 +1 @@
1
- import{createLogger}from"#internal/logging.js";import{parseJsonObject}from"#shared/json.js";import{POST,defineChannel}from"#public/definitions/defineChannel.js";import"#public/channels/discord/verify.js";import{callDiscordApi,createDiscordFollowupMessage,discordContinuationToken,editDiscordOriginalResponse,sendDiscordChannelMessage,splitDiscordMessageContent,triggerDiscordTypingIndicator}from"#public/channels/discord/api.js";import{buildFreeformModalResponse,deriveComponentInputResponses,deriveModalInputResponses,isDiscordFreeformComponent}from"#public/channels/discord/hitl.js";import{defaultEvents,defaultOnCommand}from"#public/channels/discord/defaults.js";import{DISCORD_INTERACTION_RESPONSE_TYPE,DISCORD_INTERACTION_TYPE,commandInteractionMessage,parseDiscordInteraction,prependDiscordContext}from"#public/channels/discord/inbound.js";import{discordDeferredJson,discordJson,discordJsonBody,readMessageContent}from"#public/channels/discord/responses.js";import{verifyDiscordInbound}from"#public/channels/discord/verifyInbound.js";var log=createLogger(`discord.channel`);function discordChannel(e={}){let i=e.onCommand??defaultOnCommand,a={...defaultEvents,...e.events};return defineChannel({kindHint:`discord`,state:initialDiscordState(),context(t,n){return rebuildDiscordContext(t,n,e)},routes:[POST(e.route??`/ash/v1/discord`,async(n,{send:r,waitUntil:a})=>{let o=await verifyDiscordInbound(n,e.credentials);if(o===null)return new Response(`unauthorized`,{status:401});let s;try{s=parseJsonObject(JSON.parse(o))}catch(e){return log.warn(`inbound Discord body is not valid JSON`,{error:e}),discordJson({content:`invalid request`,ephemeral:!0})}if(s.type===DISCORD_INTERACTION_TYPE.PING)return discordJson({type:DISCORD_INTERACTION_RESPONSE_TYPE.PONG});let c=parseDiscordInteraction(s);return c===null?discordJson({content:`Unsupported Discord interaction.`,ephemeral:!0}):handleInteraction({config:e,interaction:c,onCommand:i,send:r,waitUntil:a})})],async receive(t,{send:n}){let r=t.args,i=readString(r.channelId);if(!i)throw Error(`discordChannel().receive requires args.channelId.`);let a=readString(r.conversationId),s=r.initialMessage;if(s!==void 0&&a!==void 0)throw Error("discordChannel().receive: `conversationId` and `initialMessage` are mutually exclusive.");let c=a??``,l=a!==void 0;if(s!==void 0){let t=await buildDiscordHandle({config:e,state:{...initialDiscordState(),channelId:i}}).sendChannelMessage(s);c=t.id,l=t.id.length>0}return n(t.message,{auth:t.auth,continuationToken:discordContinuationToken(i,c),state:{applicationId:null,channelId:i,conversationId:c||null,guildId:null,hasMessageAnchor:l,initialResponseSent:!0,interactionToken:null}})},events:a})}function rebuildDiscordContext(e,t,n){return{discord:buildDiscordHandle({config:n,session:t,state:e}),session:t,state:e}}function buildDiscordHandle(e){let t=e.config.api,n=e.state,r=mergeCredentials(e.config.credentials,n);function anchor(t){!t.id||n.hasMessageAnchor||(n.conversationId=t.id,n.hasMessageAnchor=!0,n.channelId&&e.session?.setContinuationToken(discordContinuationToken(n.channelId,t.id)))}async function sendViaChannel(e){let i=n.channelId??``;if(!i)throw Error(`discordChannel: missing channel id for outbound message.`);let a=await sendDiscordChannelMessage({apiBaseUrl:t?.apiBaseUrl,body:normalizePostInput(e),credentials:r,fetch:t?.fetch,channelId:i});return anchor(a),a}async function editOriginal(e){let i=n.interactionToken??``;if(!i)throw Error(`discordChannel: missing interaction token for original response edit.`);let a=await editDiscordOriginalResponse({apiBaseUrl:t?.apiBaseUrl,body:normalizePostInput(e),credentials:r,fetch:t?.fetch,interactionToken:i});return n.initialResponseSent=!0,anchor(a),a}async function followup(e){let i=n.interactionToken??``;if(!i)throw Error(`discordChannel: missing interaction token for followup message.`);let o=await createDiscordFollowupMessage({apiBaseUrl:t?.apiBaseUrl,body:normalizePostInput(e),credentials:r,fetch:t?.fetch,interactionToken:i});return anchor(o),o}async function startTyping(){let e=n.channelId??``;if(e)try{await triggerDiscordTypingIndicator({apiBaseUrl:t?.apiBaseUrl,credentials:r,fetch:t?.fetch,channelId:e})}catch(e){log.debug(`Discord typing indicator failed — swallowed`,{error:e})}}return{applicationId:n.applicationId??void 0,channelId:n.channelId??``,conversationId:n.conversationId??``,guildId:n.guildId??void 0,interactionToken:n.interactionToken??void 0,request(e,n,a){return callDiscordApi({apiBaseUrl:t?.apiBaseUrl,body:n,botToken:a?.botAuth===!0?r.botToken:void 0,fetch:t?.fetch,method:a?.method,path:e})},async post(e){let t=expandPostBodies(normalizePostInput(e)),r;for(let e of t){let t=await postOne({body:e,editOriginal,followup,sendViaChannel,state:n});r===void 0&&(r=t)}return r??{id:``,raw:null}},editOriginalResponse:editOriginal,followup,sendChannelMessage:sendViaChannel,startTyping}}async function postOne(e){if(e.state.interactionToken&&e.state.applicationId)try{return e.state.initialResponseSent?await e.followup(e.body):await e.editOriginal(e.body)}catch(e){log.warn(`Discord interaction-token delivery failed, falling back to channel message`,{error:e})}return e.sendViaChannel(e.body)}async function handleInteraction(e){return e.interaction.type===DISCORD_INTERACTION_TYPE.APPLICATION_COMMAND?handleCommandInteraction({config:e.config,interaction:e.interaction,onCommand:e.onCommand,send:e.send,waitUntil:e.waitUntil}):e.interaction.type===DISCORD_INTERACTION_TYPE.MESSAGE_COMPONENT?handleComponentInteraction({interaction:e.interaction,send:e.send,waitUntil:e.waitUntil}):handleModalSubmitInteraction({interaction:e.interaction,send:e.send,waitUntil:e.waitUntil})}async function handleCommandInteraction(e){let t=stateFromInteraction(e.interaction,{conversationId:e.interaction.id,hasMessageAnchor:!1,initialResponseSent:!1}),n={discord:buildDiscordHandle({config:e.config,state:t})},r;try{r=await e.onCommand(n,e.interaction)}catch(e){return log.error(`command handler failed`,{error:e}),discordJson({content:`The Discord command handler failed.`,ephemeral:!0})}return r==null?discordJson({content:`Command ignored.`,ephemeral:!0}):(e.waitUntil(dispatchCommand({interaction:e.interaction,result:r,send:e.send,state:t})),discordDeferredJson(r.ephemeral===!0))}function handleComponentInteraction(e){if(isDiscordFreeformComponent(e.interaction.customId)){let t=readMessageContent(e.interaction.raw);return discordJsonBody(buildFreeformModalResponse({customId:e.interaction.customId,prompt:t}))}let t=deriveComponentInputResponses(e.interaction);return t.length>0&&e.waitUntil(dispatchInputResponses({conversationId:e.interaction.messageId,inputResponses:t,interaction:e.interaction,send:e.send})),discordJsonBody({type:DISCORD_INTERACTION_RESPONSE_TYPE.DEFERRED_UPDATE_MESSAGE})}function handleModalSubmitInteraction(e){let t=deriveModalInputResponses(e.interaction);return t.length>0&&e.waitUntil(dispatchInputResponses({conversationId:e.interaction.messageId??e.interaction.id,inputResponses:t,interaction:e.interaction,send:e.send})),discordJson({content:`Answer received.`,ephemeral:!0})}async function dispatchCommand(e){let t=prependDiscordContext(commandInteractionMessage(e.interaction),{channelId:e.interaction.channelId,commandName:e.interaction.commandName,guildId:e.interaction.guildId,interactionId:e.interaction.id,userId:e.interaction.user.id,username:e.interaction.user.username});try{await e.send({message:t,modelContext:e.result.modelContext},{auth:e.result.auth,continuationToken:discordContinuationToken(e.interaction.channelId,e.interaction.id),state:e.state})}catch(e){log.error(`command delivery failed`,{error:e})}}async function dispatchInputResponses(e){try{await e.send({inputResponses:e.inputResponses},{auth:null,continuationToken:discordContinuationToken(e.interaction.channelId,e.conversationId),state:stateFromInteraction(e.interaction,{conversationId:e.conversationId,hasMessageAnchor:!0,initialResponseSent:!0})})}catch(e){log.error(`interaction response delivery failed`,{error:e})}}function stateFromInteraction(e,t){return{applicationId:e.applicationId,channelId:e.channelId,conversationId:t.conversationId,guildId:e.guildId??null,hasMessageAnchor:t.hasMessageAnchor,initialResponseSent:t.initialResponseSent,interactionToken:e.token}}function initialDiscordState(){return{applicationId:null,channelId:null,conversationId:null,guildId:null,hasMessageAnchor:!1,initialResponseSent:!1,interactionToken:null}}function mergeCredentials(e,t){return{applicationId:t.applicationId??e?.applicationId,botToken:e?.botToken,publicKey:e?.publicKey,webhookVerifier:e?.webhookVerifier}}function normalizePostInput(e){return typeof e==`string`?{content:e}:e}function expandPostBodies(e){return typeof e.content==`string`?splitDiscordMessageContent(e.content).map((t,n)=>n===0?{...e,content:t}:{allowed_mentions:e.allowed_mentions,content:t}):[e]}function readString(e){return typeof e==`string`&&e.length>0?e:void 0}export{discordChannel};
1
+ import{createLogger}from"#internal/logging.js";import{parseJsonObject}from"#shared/json.js";import{POST,defineChannel}from"#public/definitions/defineChannel.js";import"#public/channels/discord/verify.js";import{callDiscordApi,createDiscordFollowupMessage,discordContinuationToken,editDiscordOriginalResponse,sendDiscordChannelMessage,splitDiscordMessageContent,triggerDiscordTypingIndicator}from"#public/channels/discord/api.js";import{buildFreeformModalResponse,deriveComponentInputResponses,deriveModalInputResponses,isDiscordFreeformComponent}from"#public/channels/discord/hitl.js";import{defaultEvents,defaultOnCommand}from"#public/channels/discord/defaults.js";import{DISCORD_INTERACTION_RESPONSE_TYPE,DISCORD_INTERACTION_TYPE,commandInteractionMessage,parseDiscordInteraction,prependDiscordContext}from"#public/channels/discord/inbound.js";import{discordDeferredJson,discordJson,discordJsonBody,readMessageContent}from"#public/channels/discord/responses.js";import{verifyDiscordInbound}from"#public/channels/discord/verifyInbound.js";const log=createLogger(`discord.channel`);function discordChannel(e={}){let i=e.onCommand??defaultOnCommand,a={...defaultEvents,...e.events};return defineChannel({kindHint:`discord`,state:initialDiscordState(),context(t,n){return rebuildDiscordContext(t,n,e)},routes:[POST(e.route??`/ash/v1/discord`,async(n,{send:r,waitUntil:a})=>{let o=await verifyDiscordInbound(n,e.credentials);if(o===null)return new Response(`unauthorized`,{status:401});let s;try{s=parseJsonObject(JSON.parse(o))}catch(e){return log.warn(`inbound Discord body is not valid JSON`,{error:e}),discordJson({content:`invalid request`,ephemeral:!0})}if(s.type===DISCORD_INTERACTION_TYPE.PING)return discordJson({type:DISCORD_INTERACTION_RESPONSE_TYPE.PONG});let c=parseDiscordInteraction(s);return c===null?discordJson({content:`Unsupported Discord interaction.`,ephemeral:!0}):handleInteraction({config:e,interaction:c,onCommand:i,send:r,waitUntil:a})})],async receive(t,{send:n}){let r=t.args,i=readString(r.channelId);if(!i)throw Error(`discordChannel().receive requires args.channelId.`);let a=readString(r.conversationId),s=r.initialMessage;if(s!==void 0&&a!==void 0)throw Error("discordChannel().receive: `conversationId` and `initialMessage` are mutually exclusive.");let c=a??``,l=a!==void 0;if(s!==void 0){let t=await buildDiscordHandle({config:e,state:{...initialDiscordState(),channelId:i}}).sendChannelMessage(s);c=t.id,l=t.id.length>0}return n(t.message,{auth:t.auth,continuationToken:discordContinuationToken(i,c),state:{applicationId:null,channelId:i,conversationId:c||null,guildId:null,hasMessageAnchor:l,initialResponseSent:!0,interactionToken:null}})},events:a})}function rebuildDiscordContext(e,t,n){return{discord:buildDiscordHandle({config:n,session:t,state:e}),session:t,state:e}}function buildDiscordHandle(e){let t=e.config.api,n=e.state,r=mergeCredentials(e.config.credentials,n);function anchor(t){!t.id||n.hasMessageAnchor||(n.conversationId=t.id,n.hasMessageAnchor=!0,n.channelId&&e.session?.setContinuationToken(discordContinuationToken(n.channelId,t.id)))}async function sendViaChannel(e){let i=n.channelId??``;if(!i)throw Error(`discordChannel: missing channel id for outbound message.`);let a=await sendDiscordChannelMessage({apiBaseUrl:t?.apiBaseUrl,body:normalizePostInput(e),credentials:r,fetch:t?.fetch,channelId:i});return anchor(a),a}async function editOriginal(e){let i=n.interactionToken??``;if(!i)throw Error(`discordChannel: missing interaction token for original response edit.`);let a=await editDiscordOriginalResponse({apiBaseUrl:t?.apiBaseUrl,body:normalizePostInput(e),credentials:r,fetch:t?.fetch,interactionToken:i});return n.initialResponseSent=!0,anchor(a),a}async function followup(e){let i=n.interactionToken??``;if(!i)throw Error(`discordChannel: missing interaction token for followup message.`);let o=await createDiscordFollowupMessage({apiBaseUrl:t?.apiBaseUrl,body:normalizePostInput(e),credentials:r,fetch:t?.fetch,interactionToken:i});return anchor(o),o}async function startTyping(){let e=n.channelId??``;if(e)try{await triggerDiscordTypingIndicator({apiBaseUrl:t?.apiBaseUrl,credentials:r,fetch:t?.fetch,channelId:e})}catch(e){log.debug(`Discord typing indicator failed — swallowed`,{error:e})}}return{applicationId:n.applicationId??void 0,channelId:n.channelId??``,conversationId:n.conversationId??``,guildId:n.guildId??void 0,interactionToken:n.interactionToken??void 0,request(e,n,a){return callDiscordApi({apiBaseUrl:t?.apiBaseUrl,body:n,botToken:a?.botAuth===!0?r.botToken:void 0,fetch:t?.fetch,method:a?.method,path:e})},async post(e){let t=expandPostBodies(normalizePostInput(e)),r;for(let e of t){let t=await postOne({body:e,editOriginal,followup,sendViaChannel,state:n});r===void 0&&(r=t)}return r??{id:``,raw:null}},editOriginalResponse:editOriginal,followup,sendChannelMessage:sendViaChannel,startTyping}}async function postOne(e){if(e.state.interactionToken&&e.state.applicationId)try{return e.state.initialResponseSent?await e.followup(e.body):await e.editOriginal(e.body)}catch(e){log.warn(`Discord interaction-token delivery failed, falling back to channel message`,{error:e})}return e.sendViaChannel(e.body)}async function handleInteraction(e){return e.interaction.type===DISCORD_INTERACTION_TYPE.APPLICATION_COMMAND?handleCommandInteraction({config:e.config,interaction:e.interaction,onCommand:e.onCommand,send:e.send,waitUntil:e.waitUntil}):e.interaction.type===DISCORD_INTERACTION_TYPE.MESSAGE_COMPONENT?handleComponentInteraction({interaction:e.interaction,send:e.send,waitUntil:e.waitUntil}):handleModalSubmitInteraction({interaction:e.interaction,send:e.send,waitUntil:e.waitUntil})}async function handleCommandInteraction(e){let t=stateFromInteraction(e.interaction,{conversationId:e.interaction.id,hasMessageAnchor:!1,initialResponseSent:!1}),n={discord:buildDiscordHandle({config:e.config,state:t})},r;try{r=await e.onCommand(n,e.interaction)}catch(e){return log.error(`command handler failed`,{error:e}),discordJson({content:`The Discord command handler failed.`,ephemeral:!0})}return r==null?discordJson({content:`Command ignored.`,ephemeral:!0}):(e.waitUntil(dispatchCommand({interaction:e.interaction,result:r,send:e.send,state:t})),discordDeferredJson(r.ephemeral===!0))}function handleComponentInteraction(e){if(isDiscordFreeformComponent(e.interaction.customId)){let t=readMessageContent(e.interaction.raw);return discordJsonBody(buildFreeformModalResponse({customId:e.interaction.customId,prompt:t}))}let t=deriveComponentInputResponses(e.interaction);return t.length>0&&e.waitUntil(dispatchInputResponses({conversationId:e.interaction.messageId,inputResponses:t,interaction:e.interaction,send:e.send})),discordJsonBody({type:DISCORD_INTERACTION_RESPONSE_TYPE.DEFERRED_UPDATE_MESSAGE})}function handleModalSubmitInteraction(e){let t=deriveModalInputResponses(e.interaction);return t.length>0&&e.waitUntil(dispatchInputResponses({conversationId:e.interaction.messageId??e.interaction.id,inputResponses:t,interaction:e.interaction,send:e.send})),discordJson({content:`Answer received.`,ephemeral:!0})}async function dispatchCommand(e){let t=prependDiscordContext(commandInteractionMessage(e.interaction),{channelId:e.interaction.channelId,commandName:e.interaction.commandName,guildId:e.interaction.guildId,interactionId:e.interaction.id,userId:e.interaction.user.id,username:e.interaction.user.username});try{await e.send({message:t,modelContext:e.result.modelContext},{auth:e.result.auth,continuationToken:discordContinuationToken(e.interaction.channelId,e.interaction.id),state:e.state})}catch(e){log.error(`command delivery failed`,{error:e})}}async function dispatchInputResponses(e){try{await e.send({inputResponses:e.inputResponses},{auth:null,continuationToken:discordContinuationToken(e.interaction.channelId,e.conversationId),state:stateFromInteraction(e.interaction,{conversationId:e.conversationId,hasMessageAnchor:!0,initialResponseSent:!0})})}catch(e){log.error(`interaction response delivery failed`,{error:e})}}function stateFromInteraction(e,t){return{applicationId:e.applicationId,channelId:e.channelId,conversationId:t.conversationId,guildId:e.guildId??null,hasMessageAnchor:t.hasMessageAnchor,initialResponseSent:t.initialResponseSent,interactionToken:e.token}}function initialDiscordState(){return{applicationId:null,channelId:null,conversationId:null,guildId:null,hasMessageAnchor:!1,initialResponseSent:!1,interactionToken:null}}function mergeCredentials(e,t){return{applicationId:t.applicationId??e?.applicationId,botToken:e?.botToken,publicKey:e?.publicKey,webhookVerifier:e?.webhookVerifier}}function normalizePostInput(e){return typeof e==`string`?{content:e}:e}function expandPostBodies(e){return typeof e.content==`string`?splitDiscordMessageContent(e.content).map((t,n)=>n===0?{...e,content:t}:{allowed_mentions:e.allowed_mentions,content:t}):[e]}function readString(e){return typeof e==`string`&&e.length>0?e:void 0}export{discordChannel};
@@ -1 +1 @@
1
- import{DISCORD_INTERACTION_RESPONSE_TYPE}from"#public/channels/discord/inbound.js";var DISCORD_COMPONENT_TYPE={ACTION_ROW:1,BUTTON:2,STRING_SELECT:3,TEXT_INPUT:4},DISCORD_HITL_CUSTOM_ID_PREFIX=`ash_input:`,DISCORD_HITL_FREEFORM_CUSTOM_ID_PREFIX=`ash_input_freeform:`,DISCORD_HITL_FREEFORM_TEXT_INPUT_ID=`ash_freeform_text`,DISCORD_CUSTOM_ID_MAX_LENGTH=100,DISCORD_LABEL_MAX_LENGTH=80,DISCORD_SELECT_OPTION_TEXT_MAX_LENGTH=100,DISCORD_MODAL_TITLE_MAX_LENGTH=45,DISCORD_ACTION_ROW_LIMIT=5,DISCORD_SELECT_OPTION_LIMIT=25;function renderInputRequestComponents(e){let i=e.options,a=e.allowFreeform===!0||!i||i.length===0;return i&&i.length>0&&e.display===`select`?[{components:[{custom_id:encodeHitlCustomId(DISCORD_HITL_CUSTOM_ID_PREFIX,{requestId:e.requestId}),options:i.slice(0,DISCORD_SELECT_OPTION_LIMIT).map(e=>{let t={label:truncate(e.label,DISCORD_SELECT_OPTION_TEXT_MAX_LENGTH),value:truncate(e.id,DISCORD_SELECT_OPTION_TEXT_MAX_LENGTH)};return e.description!==void 0&&(t.description=truncate(e.description,DISCORD_SELECT_OPTION_TEXT_MAX_LENGTH)),t}),placeholder:`Choose an option`,type:DISCORD_COMPONENT_TYPE.STRING_SELECT}],type:DISCORD_COMPONENT_TYPE.ACTION_ROW}]:i&&i.length>0?chunk(i.slice(0,DISCORD_ACTION_ROW_LIMIT*DISCORD_ACTION_ROW_LIMIT),5).map(r=>({components:r.map(r=>({custom_id:encodeHitlCustomId(DISCORD_HITL_CUSTOM_ID_PREFIX,{optionId:r.id,requestId:e.requestId}),label:truncate(r.label,DISCORD_LABEL_MAX_LENGTH),style:toDiscordButtonStyle(r.style),type:DISCORD_COMPONENT_TYPE.BUTTON})),type:DISCORD_COMPONENT_TYPE.ACTION_ROW})):a?[{components:[{custom_id:encodeHitlCustomId(DISCORD_HITL_FREEFORM_CUSTOM_ID_PREFIX,{requestId:e.requestId}),label:`Type your answer`,style:1,type:DISCORD_COMPONENT_TYPE.BUTTON}],type:DISCORD_COMPONENT_TYPE.ACTION_ROW}]:[]}function buildFreeformModalResponse(n){let a=decodeHitlCustomId(n.customId,DISCORD_HITL_FREEFORM_CUSTOM_ID_PREFIX);if(!a)throw Error(`discordChannel: freeform custom_id is malformed.`);return{data:{components:[{components:[{custom_id:DISCORD_HITL_FREEFORM_TEXT_INPUT_ID,label:`Answer`,max_length:4e3,min_length:1,placeholder:`Type your answer here...`,required:!0,style:2,type:DISCORD_COMPONENT_TYPE.TEXT_INPUT}],type:DISCORD_COMPONENT_TYPE.ACTION_ROW}],custom_id:encodeHitlCustomId(DISCORD_HITL_FREEFORM_CUSTOM_ID_PREFIX,{requestId:a.requestId}),title:truncate(n.prompt??`Your answer`,DISCORD_MODAL_TITLE_MAX_LENGTH)},type:DISCORD_INTERACTION_RESPONSE_TYPE.MODAL}}function isDiscordFreeformComponent(e){return decodeHitlCustomId(e,DISCORD_HITL_FREEFORM_CUSTOM_ID_PREFIX)!==null}function deriveComponentInputResponses(e){let t=decodeHitlCustomId(e.customId,DISCORD_HITL_CUSTOM_ID_PREFIX);if(!t)return[];if(t.optionId!==void 0)return[{optionId:t.optionId,requestId:t.requestId}];let r=e.values[0];return r===void 0?[]:[{optionId:r,requestId:t.requestId}]}function deriveModalInputResponses(e){let t=decodeHitlCustomId(e.customId,DISCORD_HITL_FREEFORM_CUSTOM_ID_PREFIX),n=e.textInputs[DISCORD_HITL_FREEFORM_TEXT_INPUT_ID];return!t||n===void 0?[]:[{requestId:t.requestId,text:n}]}function encodeHitlCustomId(e,t){let n=`${e}${Buffer.from(JSON.stringify(t),`utf8`).toString(`base64url`)}`;if(n.length>DISCORD_CUSTOM_ID_MAX_LENGTH)throw Error(`discordChannel: HITL custom_id exceeded Discord's 100-character limit.`);return n}function decodeHitlCustomId(e,t){if(!e.startsWith(t))return null;try{let n=Buffer.from(e.slice(t.length),`base64url`).toString(`utf8`),r=JSON.parse(n);if(typeof r.requestId!=`string`||r.requestId.length===0)return null;let i={requestId:r.requestId};return typeof r.optionId==`string`?{...i,optionId:r.optionId}:i}catch{return null}}function toDiscordButtonStyle(e){return e===`primary`?1:e===`danger`?4:2}function truncate(e,t){if(e.length<=t)return e;let n=Math.max(0,t-3);return`${e.slice(0,n).trimEnd()}...`}function chunk(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}export{DISCORD_COMPONENT_TYPE,DISCORD_HITL_CUSTOM_ID_PREFIX,DISCORD_HITL_FREEFORM_CUSTOM_ID_PREFIX,DISCORD_HITL_FREEFORM_TEXT_INPUT_ID,buildFreeformModalResponse,deriveComponentInputResponses,deriveModalInputResponses,isDiscordFreeformComponent,renderInputRequestComponents};
1
+ import{DISCORD_INTERACTION_RESPONSE_TYPE}from"#public/channels/discord/inbound.js";const DISCORD_COMPONENT_TYPE={ACTION_ROW:1,BUTTON:2,STRING_SELECT:3,TEXT_INPUT:4},DISCORD_HITL_CUSTOM_ID_PREFIX=`ash_input:`,DISCORD_HITL_FREEFORM_CUSTOM_ID_PREFIX=`ash_input_freeform:`,DISCORD_HITL_FREEFORM_TEXT_INPUT_ID=`ash_freeform_text`;function renderInputRequestComponents(e){let i=e.options,a=e.allowFreeform===!0||!i||i.length===0;return i&&i.length>0&&e.display===`select`?[{components:[{custom_id:encodeHitlCustomId(DISCORD_HITL_CUSTOM_ID_PREFIX,{requestId:e.requestId}),options:i.slice(0,25).map(e=>{let t={label:truncate(e.label,100),value:truncate(e.id,100)};return e.description!==void 0&&(t.description=truncate(e.description,100)),t}),placeholder:`Choose an option`,type:DISCORD_COMPONENT_TYPE.STRING_SELECT}],type:DISCORD_COMPONENT_TYPE.ACTION_ROW}]:i&&i.length>0?chunk(i.slice(0,25),5).map(r=>({components:r.map(r=>({custom_id:encodeHitlCustomId(DISCORD_HITL_CUSTOM_ID_PREFIX,{optionId:r.id,requestId:e.requestId}),label:truncate(r.label,80),style:toDiscordButtonStyle(r.style),type:DISCORD_COMPONENT_TYPE.BUTTON})),type:DISCORD_COMPONENT_TYPE.ACTION_ROW})):a?[{components:[{custom_id:encodeHitlCustomId(DISCORD_HITL_FREEFORM_CUSTOM_ID_PREFIX,{requestId:e.requestId}),label:`Type your answer`,style:1,type:DISCORD_COMPONENT_TYPE.BUTTON}],type:DISCORD_COMPONENT_TYPE.ACTION_ROW}]:[]}function buildFreeformModalResponse(n){let a=decodeHitlCustomId(n.customId,DISCORD_HITL_FREEFORM_CUSTOM_ID_PREFIX);if(!a)throw Error(`discordChannel: freeform custom_id is malformed.`);return{data:{components:[{components:[{custom_id:DISCORD_HITL_FREEFORM_TEXT_INPUT_ID,label:`Answer`,max_length:4e3,min_length:1,placeholder:`Type your answer here...`,required:!0,style:2,type:DISCORD_COMPONENT_TYPE.TEXT_INPUT}],type:DISCORD_COMPONENT_TYPE.ACTION_ROW}],custom_id:encodeHitlCustomId(DISCORD_HITL_FREEFORM_CUSTOM_ID_PREFIX,{requestId:a.requestId}),title:truncate(n.prompt??`Your answer`,45)},type:DISCORD_INTERACTION_RESPONSE_TYPE.MODAL}}function isDiscordFreeformComponent(e){return decodeHitlCustomId(e,DISCORD_HITL_FREEFORM_CUSTOM_ID_PREFIX)!==null}function deriveComponentInputResponses(e){let t=decodeHitlCustomId(e.customId,DISCORD_HITL_CUSTOM_ID_PREFIX);if(!t)return[];if(t.optionId!==void 0)return[{optionId:t.optionId,requestId:t.requestId}];let r=e.values[0];return r===void 0?[]:[{optionId:r,requestId:t.requestId}]}function deriveModalInputResponses(e){let t=decodeHitlCustomId(e.customId,DISCORD_HITL_FREEFORM_CUSTOM_ID_PREFIX),n=e.textInputs[DISCORD_HITL_FREEFORM_TEXT_INPUT_ID];return!t||n===void 0?[]:[{requestId:t.requestId,text:n}]}function encodeHitlCustomId(e,t){let n=`${e}${Buffer.from(JSON.stringify(t),`utf8`).toString(`base64url`)}`;if(n.length>100)throw Error(`discordChannel: HITL custom_id exceeded Discord's 100-character limit.`);return n}function decodeHitlCustomId(e,t){if(!e.startsWith(t))return null;try{let n=Buffer.from(e.slice(t.length),`base64url`).toString(`utf8`),r=JSON.parse(n);if(typeof r.requestId!=`string`||r.requestId.length===0)return null;let i={requestId:r.requestId};return typeof r.optionId==`string`?{...i,optionId:r.optionId}:i}catch{return null}}function toDiscordButtonStyle(e){return e===`primary`?1:e===`danger`?4:2}function truncate(e,t){if(e.length<=t)return e;let n=Math.max(0,t-3);return`${e.slice(0,n).trimEnd()}...`}function chunk(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}export{DISCORD_COMPONENT_TYPE,DISCORD_HITL_CUSTOM_ID_PREFIX,DISCORD_HITL_FREEFORM_CUSTOM_ID_PREFIX,DISCORD_HITL_FREEFORM_TEXT_INPUT_ID,buildFreeformModalResponse,deriveComponentInputResponses,deriveModalInputResponses,isDiscordFreeformComponent,renderInputRequestComponents};
@@ -1,2 +1,2 @@
1
- import{isNonEmptyString,isObject}from"#shared/guards.js";var DISCORD_INTERACTION_TYPE={APPLICATION_COMMAND:2,MESSAGE_COMPONENT:3,MODAL_SUBMIT:5,PING:1},DISCORD_INTERACTION_RESPONSE_TYPE={CHANNEL_MESSAGE_WITH_SOURCE:4,DEFERRED_CHANNEL_MESSAGE_WITH_SOURCE:5,DEFERRED_UPDATE_MESSAGE:6,MODAL:9,PONG:1},DISCORD_EPHEMERAL_MESSAGE_FLAG=64,DISCORD_RESPONSE_INSTRUCTIONS=`Reply for Discord in concise Markdown. Avoid mass mentions, long tables, and messages that need more than a few short posts.`;function parseDiscordInteraction(e){if(!isObject(e))return null;let r=e.type;return r===DISCORD_INTERACTION_TYPE.APPLICATION_COMMAND?parseCommandInteraction(e):r===DISCORD_INTERACTION_TYPE.MESSAGE_COMPONENT?parseComponentInteraction(e):r===DISCORD_INTERACTION_TYPE.MODAL_SUBMIT?parseModalSubmitInteraction(e):null}function commandInteractionMessage(e){let t=findOptionValue(e.options,`message`);if(typeof t==`string`&&t.trim().length>0)return t;let n=formatCommandOptions(e.options);return n?`/${e.commandName} ${n}`:`/${e.commandName}`}function formatDiscordContextBlock(e){return[`<discord_context>`,`response_medium: discord`,`response_instructions: ${DISCORD_RESPONSE_INSTRUCTIONS}`,`user_id: ${e.userId}`,...e.username?[`username: ${e.username}`]:[],`channel_id: ${e.channelId}`,...e.guildId?[`guild_id: ${e.guildId}`]:[],`interaction_id: ${e.interactionId}`,...e.commandName?[`command_name: ${e.commandName}`]:[],`</discord_context>`].join(`
1
+ import{isNonEmptyString,isObject}from"#shared/guards.js";const DISCORD_INTERACTION_TYPE={APPLICATION_COMMAND:2,MESSAGE_COMPONENT:3,MODAL_SUBMIT:5,PING:1},DISCORD_INTERACTION_RESPONSE_TYPE={CHANNEL_MESSAGE_WITH_SOURCE:4,DEFERRED_CHANNEL_MESSAGE_WITH_SOURCE:5,DEFERRED_UPDATE_MESSAGE:6,MODAL:9,PONG:1},DISCORD_EPHEMERAL_MESSAGE_FLAG=64;function parseDiscordInteraction(e){if(!isObject(e))return null;let r=e.type;return r===DISCORD_INTERACTION_TYPE.APPLICATION_COMMAND?parseCommandInteraction(e):r===DISCORD_INTERACTION_TYPE.MESSAGE_COMPONENT?parseComponentInteraction(e):r===DISCORD_INTERACTION_TYPE.MODAL_SUBMIT?parseModalSubmitInteraction(e):null}function commandInteractionMessage(e){let t=findOptionValue(e.options,`message`);if(typeof t==`string`&&t.trim().length>0)return t;let n=formatCommandOptions(e.options);return n?`/${e.commandName} ${n}`:`/${e.commandName}`}function formatDiscordContextBlock(e){return[`<discord_context>`,`response_medium: discord`,`response_instructions: Reply for Discord in concise Markdown. Avoid mass mentions, long tables, and messages that need more than a few short posts.`,`user_id: ${e.userId}`,...e.username?[`username: ${e.username}`]:[],`channel_id: ${e.channelId}`,...e.guildId?[`guild_id: ${e.guildId}`]:[],`interaction_id: ${e.interactionId}`,...e.commandName?[`command_name: ${e.commandName}`]:[],`</discord_context>`].join(`
2
2
  `)}function prependDiscordContext(e,t){let n=formatDiscordContextBlock(t);return typeof e==`string`?e.length>0?`${n}\n\n${e}`:n:[{type:`text`,text:n},...e]}function parseCommandInteraction(r){let i=parseInteractionBase(r),a=isObject(r.data)?r.data:null;return!i||!a||!isNonEmptyString(a.name)?null:{...i,commandId:isNonEmptyString(a.id)?a.id:void 0,commandName:a.name,options:parseOptions(a.options),type:DISCORD_INTERACTION_TYPE.APPLICATION_COMMAND}}function parseComponentInteraction(r){let i=parseInteractionBase(r),a=isObject(r.data)?r.data:null,o=isObject(r.message)?r.message:null;if(!i||!a||!isNonEmptyString(a.custom_id))return null;let s=isNonEmptyString(o?.id)?o.id:``;return s?{...i,componentType:typeof a.component_type==`number`?a.component_type:0,customId:a.custom_id,messageId:s,type:DISCORD_INTERACTION_TYPE.MESSAGE_COMPONENT,values:Array.isArray(a.values)?a.values.filter(e=>typeof e==`string`):[]}:null}function parseModalSubmitInteraction(r){let i=parseInteractionBase(r),a=isObject(r.data)?r.data:null;if(!i||!a||!isNonEmptyString(a.custom_id))return null;let o=isObject(r.message)?r.message:null;return{...i,customId:a.custom_id,messageId:isNonEmptyString(o?.id)?o.id:void 0,textInputs:parseTextInputs(a.components),type:DISCORD_INTERACTION_TYPE.MODAL_SUBMIT}}function parseInteractionBase(t){if(!isNonEmptyString(t.id)||!isNonEmptyString(t.application_id)||!isNonEmptyString(t.channel_id)||!isNonEmptyString(t.token))return null;let n=parseInteractionUser(t);return n?{applicationId:t.application_id,channelId:t.channel_id,guildId:isNonEmptyString(t.guild_id)?t.guild_id:void 0,id:t.id,member:parseMember(t.member),raw:t,token:t.token,user:n}:null}function parseInteractionUser(e){return parseUser(e.user)||(parseMember(e.member)?.user??null)}function parseMember(n){if(!isObject(n))return;let r=parseUser(n.user);if(r)return{nick:isNonEmptyString(n.nick)?n.nick:void 0,roles:Array.isArray(n.roles)?n.roles.filter(e=>typeof e==`string`):[],user:r}}function parseUser(n){return!isObject(n)||!isNonEmptyString(n.id)||!isNonEmptyString(n.username)?null:{avatar:isNonEmptyString(n.avatar)?n.avatar:void 0,discriminator:isNonEmptyString(n.discriminator)?n.discriminator:void 0,globalName:isNonEmptyString(n.global_name)?n.global_name:void 0,id:n.id,isBot:n.bot===!0,username:n.username}}function parseOptions(n){if(!Array.isArray(n))return[];let r=[];for(let i of n){if(!isObject(i)||!isNonEmptyString(i.name))continue;let n={name:i.name,options:parseOptions(i.options),value:parseOptionValue(i.value)};r.push(n)}return r}function parseOptionValue(e){if(typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e}function parseTextInputs(n){let r={};if(!Array.isArray(n))return r;for(let i of n)if(!(!isObject(i)||!Array.isArray(i.components)))for(let n of i.components)isObject(n)&&isNonEmptyString(n.custom_id)&&typeof n.value==`string`&&(r[n.custom_id]=n.value);return r}function findOptionValue(e,t){for(let n of e){if(n.name===t&&n.value!==void 0)return n.value;let e=findOptionValue(n.options,t);if(e!==void 0)return e}}function formatCommandOptions(e){return e.map(formatOption).filter(e=>e.length>0).join(` `)}function formatOption(e){if(e.value!==void 0)return`${e.name}:${String(e.value)}`;let t=formatCommandOptions(e.options);return t?`${e.name} ${t}`:e.name}export{DISCORD_EPHEMERAL_MESSAGE_FLAG,DISCORD_INTERACTION_RESPONSE_TYPE,DISCORD_INTERACTION_TYPE,commandInteractionMessage,formatDiscordContextBlock,parseDiscordInteraction,prependDiscordContext};
@@ -1 +1 @@
1
- import{createLogger}from"#internal/logging.js";import{createPublicKey,verify}from"node:crypto";var log=createLogger(`discord.verify`),ED25519_SPKI_PREFIX=Buffer.from(`302a300506032b6570032100`,`hex`);async function resolveDiscordPublicKey(e){let t=e??process.env.DISCORD_PUBLIC_KEY;if(!t)throw Error(`DISCORD_PUBLIC_KEY is required.`);return typeof t==`function`?await t():t}async function verifyDiscordRequest(e,t){let n=await e.text();if(t.webhookVerifier!==void 0){let r=await t.webhookVerifier(e,n);if(!r)throw Error(`discordChannel: inbound webhook verifier rejected the request.`);return typeof r==`string`?r:n}let r=await resolveDiscordPublicKey(t.publicKey),i=e.headers.get(`x-signature-ed25519`)??``,a=e.headers.get(`x-signature-timestamp`)??``;if(!i||!a)throw Error(`discordChannel: inbound request missing Discord signature headers.`);let o=Number(a);if(!Number.isFinite(o))throw Error(`discordChannel: inbound request has malformed timestamp.`);let s=t.maxSkewSeconds??300,c=Math.floor(Date.now()/1e3);if(Math.abs(c-o)>s)throw Error(`discordChannel: inbound request timestamp outside allowed skew.`);if(!verifyDiscordSignature({body:n,publicKey:r,signature:i,timestamp:a}))throw Error(`discordChannel: inbound request signature mismatch.`);return n}function verifyDiscordSignature(e){try{let r=Buffer.from(e.publicKey,`hex`),a=Buffer.from(e.signature,`hex`);if(r.length!==32||a.length!==64)return!1;let o=createPublicKey({format:`der`,key:Buffer.concat([ED25519_SPKI_PREFIX,r]),type:`spki`});return verify(null,Buffer.from(`${e.timestamp}${e.body}`),o,a)}catch(e){return log.debug(`Discord signature verification threw`,{error:e}),!1}}export{resolveDiscordPublicKey,verifyDiscordRequest,verifyDiscordSignature};
1
+ import{createLogger}from"#internal/logging.js";import{createPublicKey,verify}from"node:crypto";const log=createLogger(`discord.verify`),ED25519_SPKI_PREFIX=Buffer.from(`302a300506032b6570032100`,`hex`);async function resolveDiscordPublicKey(e){let t=e??process.env.DISCORD_PUBLIC_KEY;if(!t)throw Error(`DISCORD_PUBLIC_KEY is required.`);return typeof t==`function`?await t():t}async function verifyDiscordRequest(e,t){let n=await e.text();if(t.webhookVerifier!==void 0){let r=await t.webhookVerifier(e,n);if(!r)throw Error(`discordChannel: inbound webhook verifier rejected the request.`);return typeof r==`string`?r:n}let r=await resolveDiscordPublicKey(t.publicKey),i=e.headers.get(`x-signature-ed25519`)??``,a=e.headers.get(`x-signature-timestamp`)??``;if(!i||!a)throw Error(`discordChannel: inbound request missing Discord signature headers.`);let o=Number(a);if(!Number.isFinite(o))throw Error(`discordChannel: inbound request has malformed timestamp.`);let s=t.maxSkewSeconds??300,c=Math.floor(Date.now()/1e3);if(Math.abs(c-o)>s)throw Error(`discordChannel: inbound request timestamp outside allowed skew.`);if(!verifyDiscordSignature({body:n,publicKey:r,signature:i,timestamp:a}))throw Error(`discordChannel: inbound request signature mismatch.`);return n}function verifyDiscordSignature(e){try{let r=Buffer.from(e.publicKey,`hex`),a=Buffer.from(e.signature,`hex`);if(r.length!==32||a.length!==64)return!1;let o=createPublicKey({format:`der`,key:Buffer.concat([ED25519_SPKI_PREFIX,r]),type:`spki`});return verify(null,Buffer.from(`${e.timestamp}${e.body}`),o,a)}catch(e){return log.debug(`Discord signature verification threw`,{error:e}),!1}}export{resolveDiscordPublicKey,verifyDiscordRequest,verifyDiscordSignature};
@@ -1 +1 @@
1
- import{createLogger}from"#internal/logging.js";import{verifyDiscordRequest}from"#public/channels/discord/verify.js";var log=createLogger(`discord.channel`);async function verifyDiscordInbound(e,t){try{return await verifyDiscordRequest(e,{publicKey:t?.webhookVerifier?void 0:t?.publicKey,webhookVerifier:t?.webhookVerifier})}catch(e){return log.warn(`discord inbound verification failed`,{error:e}),null}}export{verifyDiscordInbound};
1
+ import{createLogger}from"#internal/logging.js";import{verifyDiscordRequest}from"#public/channels/discord/verify.js";const log=createLogger(`discord.channel`);async function verifyDiscordInbound(e,t){try{return await verifyDiscordRequest(e,{publicKey:t?.webhookVerifier?void 0:t?.publicKey,webhookVerifier:t?.webhookVerifier})}catch(e){return log.warn(`discord inbound verification failed`,{error:e}),null}}export{verifyDiscordInbound};