@acemarke/diffloupe 0.1.0 → 0.2.1

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 (60) hide show
  1. package/README.md +202 -135
  2. package/dist/index.js +599 -535
  3. package/dist/review-core/opencode/governor.ts +709 -0
  4. package/dist/review-core/opencode/tools.md +104 -0
  5. package/dist/review-core/system.md +52 -0
  6. package/dist/wasm/tree-sitter-cpp.wasm +0 -0
  7. package/dist/wasm/tree-sitter-tsx.wasm +0 -0
  8. package/dist/wasm/tree-sitter-typescript.wasm +0 -0
  9. package/dist/wasm/web-tree-sitter.wasm +0 -0
  10. package/dist/web/assets/arktype-bg7F_Ihs.js +34 -0
  11. package/dist/web/assets/diffs-D52k9AsX.js +157 -0
  12. package/dist/web/assets/index-BjtH6rIF.js +12 -0
  13. package/dist/web/assets/index-FlD9qnmN.css +1 -0
  14. package/dist/web/assets/langs/c-B7uRR5me.js +1 -0
  15. package/dist/web/assets/langs/cmake-Bj61d0ZC.js +1 -0
  16. package/dist/web/assets/langs/cpp-CsVjRphN.js +1 -0
  17. package/dist/web/assets/langs/css-C8fQr_0Q.js +1 -0
  18. package/dist/web/assets/langs/diff-woXpYk--.js +1 -0
  19. package/dist/web/assets/langs/docker-IyjqRm3v.js +1 -0
  20. package/dist/web/assets/langs/glsl-D4jN2Gfq.js +1 -0
  21. package/dist/web/assets/langs/go-rLFTqkRN.js +1 -0
  22. package/dist/web/assets/langs/graphql-CraUZO0h.js +1 -0
  23. package/dist/web/assets/langs/html-DA4kSGiR.js +1 -0
  24. package/dist/web/assets/langs/ini-B5eOa1yu.js +1 -0
  25. package/dist/web/assets/langs/java-BXcb2rRD.js +1 -0
  26. package/dist/web/assets/langs/javascript-BgS3c2Ky.js +1 -0
  27. package/dist/web/assets/langs/json-qhed-kSA.js +1 -0
  28. package/dist/web/assets/langs/json5-BR5RXkoi.js +1 -0
  29. package/dist/web/assets/langs/jsonc-CYpm1nAK.js +1 -0
  30. package/dist/web/assets/langs/jsx-Bz0zcwM4.js +1 -0
  31. package/dist/web/assets/langs/make-Dixweg8N.js +1 -0
  32. package/dist/web/assets/langs/markdown-BYOwaDjH.js +1 -0
  33. package/dist/web/assets/langs/objective-cpp-BsSzOQcm.js +1 -0
  34. package/dist/web/assets/langs/plain-text-BONI54VU.js +1 -0
  35. package/dist/web/assets/langs/postcss-BXeXVLqQ.js +1 -0
  36. package/dist/web/assets/langs/powershell-QtSnmXcu.js +1 -0
  37. package/dist/web/assets/langs/python-gzcpVVnB.js +1 -0
  38. package/dist/web/assets/langs/regexp-Cw_s_VJJ.js +1 -0
  39. package/dist/web/assets/langs/rust-DpiIf5JO.js +1 -0
  40. package/dist/web/assets/langs/scss-CHVQqdPx.js +1 -0
  41. package/dist/web/assets/langs/shellscript-CLZ0U2zV.js +1 -0
  42. package/dist/web/assets/langs/sql-CEbI0hMM.js +1 -0
  43. package/dist/web/assets/langs/svelte-CfPQtCMR.js +1 -0
  44. package/dist/web/assets/langs/toml-CcmNWLt0.js +1 -0
  45. package/dist/web/assets/langs/tsx-udAQXfEw.js +1 -0
  46. package/dist/web/assets/langs/typescript-bsJCZSQ-.js +1 -0
  47. package/dist/web/assets/langs/vue-DEcQttJD.js +1 -0
  48. package/dist/web/assets/langs/xml-D5JPTzE5.js +1 -0
  49. package/dist/web/assets/langs/yaml-rwi0_p6S.js +1 -0
  50. package/dist/web/assets/react-jlQz0HNM.js +9 -0
  51. package/dist/web/assets/rolldown-runtime-hePW80VL.js +1 -0
  52. package/dist/web/assets/router-DvNvfdSS.js +2 -0
  53. package/dist/web/assets/shiki-CbbI7yl6.js +153 -0
  54. package/dist/web/assets/state-a-GRkbSP.js +1 -0
  55. package/dist/web/assets/themes/pierre-dark-CpLgRqie.js +1 -0
  56. package/dist/web/assets/themes/pierre-light-CoaEpmwp.js +1 -0
  57. package/dist/web/assets/unused-C8e4aDKx.js +1 -0
  58. package/dist/web/assets/worker-uPqQ0MJ1.js +164 -0
  59. package/dist/web/index.html +26 -0
  60. package/package.json +34 -15
@@ -0,0 +1,104 @@
1
+ ## Reading the code
2
+
3
+ Read every file the diff changes, in full, before you judge any part of it. A
4
+ changed file is small enough to read end to end, and the defects that matter
5
+ are the ones visible only when the whole file is in front of you: a validation
6
+ helper that contradicts the new optional flag, an initializer that never calls
7
+ the assertion, a second branch that the change forgot. Sampling line ranges out
8
+ of a file you are reviewing is how those get missed. Read it whole, once, then
9
+ work from what you read.
10
+
11
+ Reading a changed file means `tilth_tilth_read` with `mode: "full"`. Its
12
+ default view outlines anything large, and an outline of the file under review
13
+ is not a review of it. Pass every changed file at once in `paths`.
14
+
15
+ Unchanged files are different. There you are answering a specific question —
16
+ does this caller handle the case, is this symbol registered elsewhere — so go
17
+ to the symbol with `tilth_tilth_grok` and let the default view keep it short.
18
+
19
+ ## Tools
20
+
21
+ | Need | Use |
22
+ |---|---|
23
+ | Read files | `tilth_tilth_read` — `paths` for a batch, `mode: "full"` for anything changed, `sections` for ranges of a file you have already read |
24
+ | Understand one symbol: definition, body, callers, callees, tests | `tilth_tilth_grok` with `target` |
25
+ | Find a definition or every call site | `tilth_tilth_search` with `kind` of `symbol`, `content`, `regex` or `callers` |
26
+ | Find files by name or extension | `tilth_tilth_files` with `pattern` |
27
+ | What imports a file, and what imports it | `tilth_tilth_deps` with `path` |
28
+ | What changed, function by function | `tilth_tilth_diff` |
29
+
30
+ Paths are relative to the checkout you started in, which is the one under
31
+ review. Do not pass `scope` on a first search — it restricts the search to a
32
+ subdirectory, and the default already covers the repository.
33
+
34
+ ## Bounding the search before you start it
35
+
36
+ Most review questions fan out. "Does anything break if this value goes
37
+ missing" turns into every consumer of the value, every consumer of those, and
38
+ every place each of them runs. Tracing that outward from the change is the
39
+ expensive direction, and most of what you trace turns out to be fine.
40
+
41
+ Look first for the thing that limits the answer, and let it tell you which
42
+ branches are worth walking. When a change moves values into configuration or
43
+ the environment, the deployment wiring is that limit: the chart, the deploy
44
+ script, the workflow file that lists what actually gets provided. Read it
45
+ early. It is usually one file, and it converts "which of these twenty values
46
+ have a problem" into a short list. Then trace only the short list. The same
47
+ shape holds elsewhere — a schema for a data change, a router for a handler
48
+ change, an export list for an API change.
49
+
50
+ Batch your lookups. `tilth_tilth_search` takes up to five comma-separated
51
+ symbols in one call, and one call asking about five names costs a fraction of
52
+ five calls asking about one. When you are enumerating — every consumer of these
53
+ secrets, every caller of these helpers — enumerate in groups.
54
+
55
+ Follow an import chain only while it is still answering your question. Reaching
56
+ the file where the value is actually used is the point; the file that imports
57
+ that file rarely adds anything, and the one after it never does.
58
+
59
+ ## Shell
60
+
61
+ The `shell` tool is for running commands: `git log`, `git blame`, a build, a test. It is
62
+ not a file reader and not a search engine. `rg`, `grep`, `find`, `cat`, `sed
63
+ -n`, `head` and `tail` all have a tool above that returns the same information
64
+ with structure attached and at a fraction of the tokens. A review assembled
65
+ from `sed` fragments misses the defects that span a file, which are the ones
66
+ worth reporting.
67
+
68
+ Do not `cd` into the checkout. You are already in it.
69
+
70
+ ## What is not on disk
71
+
72
+ The checkout is a bare copy of the branch and nothing else. Dependencies are
73
+ not installed, there is no `node_modules`, nothing is built, and no build or
74
+ test command will run. Nothing outside the checkout is yours either.
75
+
76
+ So when a question turns on how a third-party library behaves — whether
77
+ `createClient("")` throws or returns something broken, whether a validator
78
+ rejects an empty string — you cannot go and read that library, and searching
79
+ the filesystem for it will cost you a minute and find nothing. Answer it the
80
+ ways that are open to you: the version in `package.json`, how the rest of this
81
+ repository already calls it, what the types say. If it still is not settled,
82
+ say so in the finding. "This depends on whether `createClient` rejects an empty
83
+ key, which I could not verify" is a useful sentence. Hunting for the file is
84
+ not.
85
+
86
+ ## The orientation map
87
+
88
+ The task names a repository map file. Read it with `tilth_tilth_read` before
89
+ you start exploring — it gives you the layout, the symbols in each changed
90
+ file, and which other files touch them, and it will save you many more tool
91
+ calls than it costs.
92
+
93
+ Read it as an index, not as a reading list. Its "Related files" section can run
94
+ to dozens of entries, one for every file that imports something the diff
95
+ touched. That is a lookup table for questions you already have, not a queue of
96
+ files to work through. Opening one is worth it when a specific doubt about the
97
+ changed code points there — this caller may pass the value the change made
98
+ optional, this consumer may assume the field is set. Opening one because it
99
+ appeared in the list is how a two-file review turns into a forty-file crawl
100
+ that reports nothing the first two files would not have told you.
101
+
102
+ Your findings are about the code the diff changed. A related file earns a tool
103
+ call by answering a question about that code, and is otherwise not your
104
+ concern.
@@ -0,0 +1,52 @@
1
+ You are a senior engineer reviewing a pull request in the {{repo}} repository. You have read-only access to a full checkout at the PR's head commit.
2
+
3
+ You produce findings, not prose. You do not summarize the diff. You do not praise the change. You do not restate what the code does.
4
+
5
+ ## Evidence rule
6
+
7
+ If you cannot cite a specific file and line as evidence for a claim, do not make the claim. Inability to cite a location is the signal that you do not have evidence, not a reason to hedge the wording.
8
+
9
+ Before asserting that something is broken, go read the code that would disprove you. A guard clause, an existing helper, a caller that already handles the case, a sibling registration — these live in files the diff does not touch. Fetch them.
10
+
11
+ ## Output contract
12
+
13
+ When you are done, write your findings as JSON to the exact path given in the task, using your file-write tool. The file must contain a single JSON object:
14
+
15
+ {
16
+ "findings": [
17
+ {
18
+ "file": "src/path/to/file.ts",
19
+ "line": 123,
20
+ "end_line": 126,
21
+ "severity": "blocker" | "should-fix" | "question" | "nice-to-have",
22
+ "category": "bug" | "race" | "edge-case" | "resource-leak" | "invariant" | "architecture" | "duplication" | "performance" | "security" | "other",
23
+ "title": "one line",
24
+ "impact": "one or two sentences: what goes wrong as a result",
25
+ "explanation": "why this is a problem",
26
+ "evidence": "the specific file:line facts you verified, including files outside the diff",
27
+ "confidence": "high" | "medium" | "low",
28
+ "effort": "quick" | "moderate" | "involved",
29
+ "cross_file_refs": ["src/other/file.ts:88"],
30
+ "suggestion": "concrete fix",
31
+ "suggested_code": "replacement source for the cited lines, if a mechanical fix exists"
32
+ }
33
+ ],
34
+ "checked": [
35
+ "`releaseWalkWaiters` (`src/processor/linker/branch-cache.ts:590`) runs on both the trunk-finished and crash paths, so no waiter is left pending"
36
+ ]
37
+ }
38
+
39
+ Rules for the object:
40
+ - `impact` is the only field shown without the reader expanding anything. One or two sentences on what actually goes wrong, in plain terms. Do not restate the title, do not list files, do not explain your reasoning — that is what `explanation` is for.
41
+ - `evidence` names the locations that decide the question, with each citation written as `path:line` in backticks. Three sentences at most. It is not a log of everything you read — `cross_file_refs` already records that. Cite the line that proves the claim and the line that would have disproved it.
42
+ - `explanation` carries the full argument. Do not repeat the evidence citations here in prose; the reader can expand them.
43
+ - Every line number you write, in any field, refers to the file **as it exists in the current checkout** — the post-change state. Diff hunk headers look like `@@ -350,7 +380,9 @@`: the `-350` is the old file and must never be cited, the `+380` is the current one. If you are citing a line you have not read directly in this checkout, read it first rather than deriving it from the diff.
44
+ - In prose, lead with the symbol and let the line follow it: "`parseConfig` (`src/config/parse.ts:57`)". A reader who has to correct one of your line numbers can still find the code by name.
45
+ - `cross_file_refs` lists locations outside the diff that you read to support the finding. Empty array if the finding is entirely diff-local.
46
+ - `effort` is how much work the fix is, judged from the code and not from how much it matters: `quick` for a change confined to the lines you cited, `moderate` for one that touches a few call sites, `involved` for one that needs a design decision or a change to an interface other code depends on. It is what lets a reader pick which findings to clear before merging.
47
+ - `line` is the first line the comment applies to. Set `end_line` only for a multi-line span; omit it otherwise.
48
+ - `severity: "question"` is for a discrepancy you investigated and could not resolve from the code alone, where the author's intent settles it. State both sides in `explanation`.
49
+ - `suggested_code` must be the literal replacement text for lines `line` through `end_line`, with correct indentation and no diff markers. Omit it unless the fix is mechanical.
50
+ - `checked` lists two to four specific things you verified in the code and found correct: a risk the change could have had and the `path:line` that rules it out. Each names a symbol and a location. Do not restate what the diff does, and do not list something you did not actually read. These are shown to the author when the review has few findings, as the evidence that the change was examined.
51
+ - An empty `findings` array is a valid and acceptable answer.
52
+ - Write the file even if `findings` is empty. Writing this file is the last thing you do.
Binary file
Binary file
Binary file
@@ -0,0 +1,34 @@
1
+ var e=e=>Array.isArray(e)?e:[e],t=(e,t)=>{let n=[[],[]];for(let r of e)t(r)?n[0].push(r):n[1].push(r);return n},n=Array,r=(e,t)=>e.includes(t),i=(e,t=0)=>[...Array(e)].map((e,n)=>n+t),a=(e,t,n)=>e===void 0?t===void 0?[]:Array.isArray(t)?t:[t]:(n?.prepend?Array.isArray(t)?e.unshift(...t):e.unshift(t):Array.isArray(t)?e.push(...t):e.push(t),e),o=(t,n)=>n==null?t??[]:t==null?e(n):t.concat(n),s=(...e)=>e.reduce(o,[]),c=(t,n,r)=>{if(t===void 0)return Array.isArray(n)?n:[n];let i=r?.isEqual??((e,t)=>e===t);for(let r of e(n))t.some(e=>i(e,r))||t.push(r);return t},l=(e,t)=>e.reduce((e,n)=>{let r=n[t];return e[r]=a(e[r],n),e},{}),u=(e,t,n)=>e.length===t.length&&e.every(n?.isEqual?(e,r)=>n.isEqual(e,t[r]):(e,n)=>e===t[n]),d=(e,t)=>f(e)===t,f=e=>{let t=typeof e;return t===`object`?e===null?`null`:`object`:t===`function`?`object`:t},p={boolean:`boolean`,null:`null`,undefined:`undefined`,bigint:`a bigint`,number:`a number`,object:`an object`,string:`a string`,symbol:`a symbol`},ee={...p,function:`a function`},te=class extends Error{},m=e=>ne(e,te),ne=(e,t=Error)=>{throw new t(e)},re=class extends Error{name=`ParseError`},h=e=>ne(e,re),g=e=>` ${e}`,_=(e,t)=>{let n={},r=Array.isArray(e),i=!1;for(let[o,s]of Object.entries(e).entries()){let e=r?t(o,s[1]):t(...s,o);i||=typeof e[0]==`number`;let c=Array.isArray(e[0])||e.length===0?e:[e];for(let[e,t]of c)typeof e==`object`?n[e.group]=a(n[e.group],t):n[e]=t}return i?Object.values(n):n},ie=Object.entries,v=(e,t)=>e in t,ae=(e,t)=>t in e,oe=class{constructor(e){Object.assign(this,e)}},se=class{},ce=class extends se{},le=(e,t)=>{let n={},r={},i;for(i in e)i in t?n[i]=e[i]:r[i]=e[i];return[n,r]},ue=(e,t)=>le(e,t)[1],de=e=>Object.keys(e).length===0,fe=e=>[...Object.entries(e),...Object.getOwnPropertySymbols(e).map(t=>[t,e[t]])],pe=(e,t)=>Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)),me=e=>{let t=Object.keys(e).sort(),n={};for(let r=0;r<t.length;r++)n[t[r]]=e[t[r]];return n},y=g(`unset​`),he=e=>Object.values(e).filter(t=>typeof t==`number`||typeof e[t]!=`number`),ge={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},_e=globalThis.File??Blob,ve={ArrayBuffer,Blob,File:_e,FormData,Headers,Request,Response,URL},ye={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},be={...ge,...ve,...ye,String,Number,Boolean},xe=e=>{let t=Object.getPrototypeOf(e);for(;t?.constructor&&(!v(t.constructor.name,be)||!(e instanceof be[t.constructor.name]));)t=Object.getPrototypeOf(t);let n=t?.constructor?.name;if(n!==void 0&&n!==`Object`)return n},Se=e=>typeof e==`object`&&e?xe(e)??`object`:f(e),b=Array.isArray,Ce={Array:`an array`,Function:`a function`,Date:`a Date`,RegExp:`a RegExp`,Error:`an Error`,Map:`a Map`,Set:`a Set`,String:`a String object`,Number:`a Number object`,Boolean:`a Boolean object`,Promise:`a Promise`,WeakMap:`a WeakMap`,WeakSet:`a WeakSet`},we={ArrayBuffer:`an ArrayBuffer instance`,Blob:`a Blob instance`,File:`a File instance`,FormData:`a FormData instance`,Headers:`a Headers instance`,Request:`a Request instance`,Response:`a Response instance`,URL:`a URL instance`},Te={Int8Array:`an Int8Array`,Uint8Array:`a Uint8Array`,Uint8ClampedArray:`a Uint8ClampedArray`,Int16Array:`an Int16Array`,Uint16Array:`a Uint16Array`,Int32Array:`an Int32Array`,Uint32Array:`a Uint32Array`,Float32Array:`a Float32Array`,Float64Array:`a Float64Array`,BigInt64Array:`a BigInt64Array`,BigUint64Array:`a BigUint64Array`},Ee={...Ce,...we,...Te},De=e=>{let t=Object(e).name??null;return t&&v(t,be)&&be[t]===e?t:null},Oe=(e,t)=>{let n=e.prototype;for(;n!==null;){if(n===t.prototype)return!0;n=Object.getPrototypeOf(n)}return!1},ke=e=>Ae(e,new Map),Ae=(e,t)=>{if(typeof e!=`object`||!e)return e;if(t?.has(e))return t.get(e);let n=De(e.constructor);if(n===`Date`)return new Date(e.getTime());if(n&&n!==`Array`)return e;let r=Array.isArray(e)?e.slice():Object.create(Object.getPrototypeOf(e)),i=Object.getOwnPropertyDescriptors(e);if(t){t.set(e,r);for(let e in i){let n=i[e];`get`in n||`set`in n||(n.value=Ae(n.value,t))}}return Object.defineProperties(r,i),r},je=e=>{let t=y;return()=>t===y?t=e():t},Me=e=>typeof e==`function`&&e.length===0,Ne=class extends Function{constructor(...e){let t=e.slice(0,-1),n=e[e.length-1];try{super(...t,n)}catch(t){return m(`Encountered an unexpected error while compiling your definition:
2
+ Message: ${t}
3
+ Source: (${e.slice(0,-1)}) => {
4
+ ${e[e.length-1]}
5
+ }`)}}},x=class{constructor(e,...[t]){return Object.assign(Object.setPrototypeOf(e.bind(t?.bind??this),this.constructor.prototype),t?.attach)}},Pe=je(()=>{try{return Function(`return false`)()}catch{return!0}});g(`brand`),g(`arkInferred`),g(`args`);var S=class{constructor(){}},Fe={fileName:()=>{try{return((Error().stack?.split(`
6
+ `)[2]?.trim()||``).match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||`unknown`).replace(/^file:\/\//,``)}catch{return`unknown`}},env:{}},Ie=e=>e[0].toUpperCase()+e.slice(1),Le=e=>e[0].toLowerCase()+e.slice(1),Re=e=>new RegExp(ze(e),typeof e==`string`?``:e.flags),ze=e=>`^(?:${typeof e==`string`?e:e.source})$`,C={negativeLookahead:e=>`(?!${e})`,nonCapturingGroup:e=>`(?:${e})`},Be={" ":1,"\n":1," ":1},Ve=`^-0\\.?0*$`,He=`[1-9]\\d*`,Ue=`\\.\\d+`,We=`\\.\\d*[1-9]`,Ge=e=>Re(C.negativeLookahead(Ve)+C.nonCapturingGroup(`-?`+C.nonCapturingGroup(C.nonCapturingGroup(`0|`+He)+C.nonCapturingGroup(e.decimalPattern)+`?`)+(e.allowDecimalOnly?`|`+e.decimalPattern:``)+`?`)),Ke=Ge({decimalPattern:We,allowDecimalOnly:!1}),qe=Ke.test.bind(Ke),Je=Ge({decimalPattern:Ue,allowDecimalOnly:!0});Je.test.bind(Je);var Ye=/^-?\d*\.?\d*$/,Xe=e=>e.length!==0&&Ye.test(e),Ze=Re(C.negativeLookahead(`^-0$`)+`-?`+C.nonCapturingGroup(C.nonCapturingGroup(`0|`+He))),Qe=Ze.test.bind(Ze),$e=/^-?\d+$/,et=$e.test.bind($e),tt={number:`a number`,bigint:`a bigint`,integer:`an integer`},nt=(e,t)=>`'${e}' was parsed as ${tt[t]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,rt=(e,t)=>t===`number`?qe(e):Qe(e),it=(e,t)=>t===`number`?Number(e):Number.parseInt(e),at=(e,t)=>t===`number`?Xe(e):et(e),ot=(e,t)=>lt(e,`number`,t),st=(e,t)=>lt(e,`number`,{...t,strict:!0}),ct=(e,t)=>lt(e,`integer`,t),lt=(e,t,n)=>{let r=it(e,t);return!Number.isNaN(r)&&at(e,t)?n?.strict?rt(e,t)?r:h(nt(e,t)):r:n?.errorOnFail?h(n?.errorOnFail===!0?`Failed to parse ${tt[t]} from '${e}'`:n?.errorOnFail):void 0},ut=e=>{if(e[e.length-1]!==`n`)return;let t=e.slice(0,-1),n;try{n=BigInt(t)}catch{return}if(Ze.test(t))return n;if($e.test(t))return h(nt(e,`bigint`))},dt={version:`0.56.0`,filename:Fe.fileName(),FileConstructor:_e},ft=new Map,pt=Object.create(null),mt=e=>{let t=ft.get(e);if(t)return t;let n=gt(e);return pt[n]?n=`${n}${pt[n]++}`:pt[n]=1,dt[n]=e,ft.set(e,n),n},ht=e=>/^[$A-Z_a-z][\w$]*$/.test(e),gt=e=>{switch(typeof e){case`object`:{if(e===null)break;let t=xe(e)??`object`;return t[0].toLowerCase()+t.slice(1)}case`function`:return ht(e.name)?e.name:`fn`;case`symbol`:return e.description&&ht(e.description)?e.description:`symbol`}return m(`Unexpected attempt to register serializable value of type ${f(e)}`)},_t=e=>typeof e==`string`?JSON.stringify(e):typeof e==`bigint`?`${e}n`:`${e}`,vt=(e,t={})=>xt(e,{onUndefined:`$ark.undefined`,onBigInt:e=>`$ark.bigint-${e}`,...t},[]),w=(e,t)=>{switch(f(e)){case`object`:let n=e,r=n.constructor?.name??`Object`;return r===`Object`||r===`Array`?t?.quoteKeys===!1?yt(n,t?.indent??0,``):JSON.stringify(xt(n,bt,[]),null,t?.indent):yt(n,t?.indent??0,``);case`symbol`:return bt.onSymbol(e);default:return _t(e)}},yt=(e,t,n)=>{if(typeof e==`function`)return bt.onFunction(e);if(typeof e!=`object`||!e)return _t(e);let r=n+` `.repeat(t);if(Array.isArray(e)){if(e.length===0)return`[]`;let i=e.map(e=>yt(e,t,r)).join(`,
7
+ `+r);return t?`[\n${r}${i}\n${n}]`:`[${i}]`}let i=e.constructor?.name??`Object`;if(i===`Object`){let i=fe(e).map(([e,n])=>{let i=typeof e==`symbol`?bt.onSymbol(e):ht(e)?e:JSON.stringify(e),a=yt(n,t,r);return`${r}${i}: ${a}`});return i.length===0?`{}`:t?`{\n${i.join(`,
8
+ `)}\n${n}}`:`{${i.join(`, `)}}`}return e instanceof Date?St(e):`expression`in e&&typeof e.expression==`string`?e.expression:i},bt={onCycle:()=>`(cycle)`,onSymbol:e=>`Symbol(${mt(e)})`,onFunction:e=>`Function(${mt(e)})`},xt=(e,t,n)=>{switch(f(e)){case`object`:{let r=e;if(`toJSON`in r&&typeof r.toJSON==`function`)return r.toJSON();if(typeof r==`function`)return bt.onFunction(r);if(n.includes(r))return`(cycle)`;let i=[...n,r];if(Array.isArray(r))return r.map(e=>xt(e,t,i));if(r instanceof Date)return r.toDateString();let a={};for(let e in r)a[e]=xt(r[e],t,i);for(let e of Object.getOwnPropertySymbols(r))a[t.onSymbol?.(e)??e.toString()]=xt(r[e],t,i);return a}case`symbol`:return bt.onSymbol(e);case`bigint`:return t.onBigInt?.(e)??`${e}n`;case`undefined`:return t.onUndefined??`undefined`;case`string`:return e.replace(/\\/g,`\\\\`);default:return e}},St=e=>{let t=e.getFullYear(),n=e.getMonth(),r=e.getDate(),i=e.getHours(),a=e.getMinutes(),o=e.getSeconds(),s=e.getMilliseconds();if(n===0&&r===1&&i===0&&a===0&&o===0&&s===0)return`${t}`;let c=`${Ct[n]} ${r}, ${t}`;if(i===0&&a===0&&o===0&&s===0)return c;let l=e.toLocaleTimeString(),u=l.endsWith(` AM`)||l.endsWith(` PM`)?l.slice(-3):``;return u&&(l=l.slice(0,-u.length)),s?l+=`.${Tt(s,3)}`:wt.test(l)&&(l=l.slice(0,-3)),`${l+u}, ${c}`},Ct=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],wt=/:\d\d:00$/,Tt=(e,t)=>String(e).padStart(t,`0`),Et=(e,t,...[n])=>{let r=n?.stringifySymbol??w,i=e;switch(typeof t){case`string`:i=ht(t)?e===``?t:`${e}.${t}`:`${e}[${JSON.stringify(t)}]`;break;case`number`:i=`${e}[${t}]`;break;case`symbol`:i=`${e}[${r(t)}]`;break;default:n?.stringifyNonKey?i=`${e}[${n.stringifyNonKey(t)}]`:h(`${w(t)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return i},Dt=(e,...t)=>e.reduce((e,n)=>Et(e,n,...t),``),Ot=class extends n{cache={};constructor(...e){super(),this.push(...e)}toJSON(){if(this.cache.json)return this.cache.json;this.cache.json=[];for(let e=0;e<this.length;e++)this.cache.json.push(typeof this[e]==`symbol`?w(this[e]):this[e]);return this.cache.json}stringify(){return this.cache.stringify?this.cache.stringify:this.cache.stringify=Dt(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let e=``,t=[e];for(let n of this)e=Et(e,n),t.push(e);return this.cache.stringifyAncestors=t}},kt=class{chars;i;def;constructor(e){this.def=e,this.chars=[...e],this.i=0}shift(){return this.chars[this.i++]??``}get lookahead(){return this.chars[this.i]??``}get nextLookahead(){return this.chars[this.i+1]??``}get length(){return this.chars.length}shiftUntil(e){let t=``;for(;this.lookahead&&!e(this,t);)t+=this.shift();return t}shiftUntilEscapable(e){let t=``;for(;this.lookahead;)if(this.lookahead===`\\`)this.shift(),e(this,t)||this.lookahead===`\\`?t+=this.shift():t+=`\\${this.shift()}`;else if(e(this,t))break;else t+=this.shift();return t}shiftUntilLookahead(e){return typeof e==`string`?this.shiftUntil(t=>t.lookahead===e):this.shiftUntil(t=>t.lookahead in e)}shiftUntilNonWhitespace(){return this.shiftUntil(()=>!(this.lookahead in Be))}jumpToIndex(e){this.i=e<0?this.length+e:e}jumpForward(e){this.i+=e}get location(){return this.i}get unscanned(){return this.chars.slice(this.i,this.length).join(``)}get scanned(){return this.chars.slice(0,this.i).join(``)}sliceChars(e,t){return this.chars.slice(e,t).join(``)}lookaheadIs(e){return this.lookahead===e}lookaheadIsIn(e){return this.lookahead in e}},At=(e,t)=>`Unmatched ${e}${t===``?``:` before ${t}`}`,jt=e=>`Missing ${e}`;g(`implementedTraits`);for(var Mt=`$ark`,Nt=2;Mt in globalThis;)Mt=`$ark${Nt++}`;var Pt=Mt;globalThis[Pt]=dt;var T=dt,Ft=e=>`${Pt}.${e}`,E=e=>Ft(mt(e)),It=class extends ce{argNames;body=``;constructor(...e){super(),this.argNames=e;for(let t of e){if(t in this)throw Error(`Arg name '${t}' would overwrite an existing property on FunctionBody`);this[t]=t}}indentation=0;indent(){return this.indentation+=4,this}dedent(){return this.indentation-=4,this}prop(e,t=!1){return Lt(e,t)}index(e,t=!1){return zt(`${e}`,t)}line(e){return this.body+=`${` `.repeat(this.indentation)}${e}\n`,this}const(e,t){return this.line(`const ${e} = ${t}`),this}let(e,t){return this.line(`let ${e} = ${t}`)}set(e,t){return this.line(`${e} = ${t}`)}if(e,t){return this.block(`if (${e})`,t)}elseIf(e,t){return this.block(`else if (${e})`,t)}else(e){return this.block(`else`,e)}for(e,t,n=0){return this.block(`for (let i = ${n}; ${e}; i++)`,t)}forIn(e,t){return this.block(`for (const k in ${e})`,t)}block(e,t,n=``){return this.line(`${e} {`),this.indent(),t(this),this.dedent(),this.line(`}${n}`)}return(e=``){return this.line(`return ${e}`)}write(e=`anonymous`,t=0){return`${e}(${this.argNames.join(`, `)}) { ${t?this.body.split(`
9
+ `).map(e=>` `.repeat(t)+`${e}`).join(`
10
+ `):this.body} }`}compile(){return new Ne(...this.argNames,this.body)}},D=e=>d(e,`object`)||typeof e==`symbol`?E(e):_t(e),Lt=(e,t=!1)=>typeof e==`string`&&ht(e)?`${t?`?`:``}.${e}`:zt(Rt(e),t),Rt=e=>typeof e==`symbol`?E(e):JSON.stringify(e),zt=(e,t=!1)=>`${t?`?.`:``}[${e}]`,Bt=class extends It{traversalKind;optimistic;constructor(e){super(`data`,`ctx`),this.traversalKind=e.kind,this.optimistic=e.optimistic===!0}invoke(e,t){let n=t?.arg??this.data,r=typeof e==`string`||this.requiresContextFor(e),i=typeof e==`string`?e:e.id;return r?`${this.referenceToId(i,t)}(${n}, ${this.ctx})`:`${this.referenceToId(i,t)}(${n})`}referenceToId(e,t){let n=`this.${e}${t?.kind??this.traversalKind}`;return t?.bind?`${n}.bind(${t?.bind})`:n}requiresContextFor(e){return this.traversalKind===`Apply`||e.allowsRequiresContext}initializeErrorCount(){return this.const(`errorCount`,`ctx.currentErrorCount`)}returnIfFail(){return this.if(`ctx.currentErrorCount > errorCount`,()=>this.return())}returnIfFailFast(){return this.if(`ctx.failFast && ctx.currentErrorCount > errorCount`,()=>this.return())}traverseKey(e,t,n){let r=this.requiresContextFor(n);return r&&this.line(`${this.ctx}.path.push(${e})`),this.check(n,{arg:t}),r&&this.line(`${this.ctx}.path.pop()`),this}check(e,t){return this.traversalKind===`Allows`?this.if(`!${this.invoke(e,t)}`,()=>this.return(!1)):this.line(this.invoke(e,t))}},Vt=e=>_(e,(e,t)=>[e,b(t)?[...t]:t]),O=g(`arkKind`),k=(e,t)=>e?.[O]===t,A=e=>k(e,`root`)||k(e,`constraint`),Ht=[`unit`,`proto`,`domain`],Ut=[`required`,`optional`,`index`,`sequence`],Wt=[`pattern`,`divisor`,`exactLength`,`max`,`min`,`maxLength`,`minLength`,`before`,`after`],Gt=[...Wt,`structure`,`predicate`],Kt=[...Gt,...Ut],qt=[`alias`,`union`,`morph`,`unit`,`intersection`,`proto`,`domain`],Jt=[...qt,...Kt],Yt=_(Kt,(e,t)=>[t,1]),Xt=_([...Ut,`undeclared`],(e,t)=>[t,1]),Zt=_(Jt,(e,t)=>[t,e]),Qt=e=>typeof e==`string`&&e in Zt,$t=e=>Zt[e],en=e=>qt.slice($t(e)+1);[...en(`union`)],[...en(`morph`)];var j=e=>typeof e==`string`||typeof e==`boolean`||e===null?e:typeof e==`number`?Number.isNaN(e)?`NaN`:e===1/0?`Infinity`:e===-1/0?`-Infinity`:e:D(e),tn=e=>{let t=`{ `;for(let[n,r]of Object.entries(e))t+=`${n}: ${D(r)}, `;return t+` }`},M=e=>{let t=e;return t.hasAssociatedError&&(t.defaults.expected??=e=>`description`in e?e.description:t.defaults.description(e),t.defaults.actual??=e=>w(e),t.defaults.problem??=e=>`must be ${e.expected}${e.actual?` (was ${e.actual})`:``}`,t.defaults.message??=e=>{if(e.path.length===0)return e.problem;let t=`${e.propString} ${e.problem}`;return t[0]===`[`?`value at ${t}`:t}),t},N={Error:class extends Error{name=`ToJsonSchemaError`;code;context;constructor(e,t){super(w(t,{quoteKeys:!1,indent:4})),this.code=e,this.context=t}hasCode(e){return this.code===e}},throw:(...e)=>{throw new N.Error(...e)},throwInternalOperandError:(e,t)=>m(`Unexpected JSON Schema input for ${e}: ${w(t)}`),defaultConfig:{target:`draft-2020-12`,dialect:`https://json-schema.org/draft/2020-12/schema`,useRefs:!1,fallback:{arrayObject:e=>N.throw(`arrayObject`,e),arrayPostfix:e=>N.throw(`arrayPostfix`,e),defaultValue:e=>N.throw(`defaultValue`,e),domain:e=>N.throw(`domain`,e),morph:e=>N.throw(`morph`,e),patternIntersection:e=>N.throw(`patternIntersection`,e),predicate:e=>N.throw(`predicate`,e),proto:e=>N.throw(`proto`,e),symbolKey:e=>N.throw(`symbolKey`,e),unit:e=>N.throw(`unit`,e),date:e=>N.throw(`date`,e)}}};T.config??={};var nn=(e,t)=>{if(!t)return e;let n={...e},r;for(r in t){let i={...e.keywords};if(r===`keywords`){for(let e in t[r]){let n=t.keywords[e];n!==void 0&&(i[e]=typeof n==`string`?{description:n}:n)}n.keywords=i}else r===`toJsonSchema`?n[r]=an(e.toJsonSchema,t.toJsonSchema):Qt(r)?n[r]={...e[r],...t[r]}:n[r]=t[r]}return n},rn={"draft-2020-12":`https://json-schema.org/draft/2020-12/schema`,"draft-07":`http://json-schema.org/draft-07/schema#`},an=((e,t)=>{if(!e)return on(t??{},void 0);if(!t)return e;let n={...e},r;for(r in t)r===`fallback`?n.fallback=sn(e.fallback,t.fallback):n[r]=t[r];return on(n,t)}),on=(e,t)=>t?.dialect===void 0?t?.target===void 0?e:{...e,dialect:rn[t.target]}:e,sn=(e,t)=>{e=cn(e),t=cn(t);let n={},r;for(r in N.defaultConfig.fallback)n[r]=t[r]??t.default??e[r]??e.default??N.defaultConfig.fallback[r];return n},cn=e=>typeof e==`function`?{default:e}:e??{},ln=class e extends ce{[O]=`error`;path;data;nodeConfig;input;ctx;constructor({prefixPath:e,relativePath:t,...n},r){super(),this.input=n,this.ctx=r,pe(this,n);let i=r.data;n.code===`union`&&(n.errors=n.errors.flatMap(n=>{let r=n.hasCode(`union`)?n.errors:[n];return!e&&!t?r:r.map(n=>n.transform(n=>({...n,path:s(e,n.path,t)})))})),this.nodeConfig=r.config[this.code];let a=[...n.path??r.path];t&&a.push(...t),e&&a.unshift(...e),this.path=new Ot(...a),this.data=`data`in n?n.data:i}transform(t){return new e(t({data:this.data,path:this.path,...this.input}),this.ctx)}hasCode(e){return this.code===e}get propString(){return Dt(this.path)}get expected(){if(this.input.expected)return this.input.expected;let e=this.meta?.expected??this.nodeConfig.expected;return typeof e==`function`?e(this.input):e}get actual(){if(this.input.actual)return this.input.actual;let e=this.meta?.actual??this.nodeConfig.actual;return typeof e==`function`?e(this.data):e}get problem(){if(this.input.problem)return this.input.problem;let e=this.meta?.problem??this.nodeConfig.problem;return typeof e==`function`?e(this):e}get message(){if(this.input.message)return this.input.message;let e=this.meta?.message??this.nodeConfig.message;return typeof e==`function`?e(this):e}get flat(){return this.hasCode(`intersection`)?[...this.errors]:[this]}toJSON(){return{data:this.data,path:this.path,...this.input,expected:this.expected,actual:this.actual,problem:this.problem,message:this.message}}toString(){return this.message}throw(){throw this}},un=class e extends n{[O]=`errors`;ctx;constructor(e){super(),this.ctx=e}byPath=Object.create(null);get flatByPath(){return _(this.byPath,(e,t)=>[e,t.flat])}get flatProblemsByPath(){return _(this.byPath,(e,t)=>[e,t.flat.map(e=>e.problem)])}byAncestorPath=Object.create(null);count=0;mutable=this;throw(){throw this.toTraversalError()}toTraversalError(){return new dn(this)}add(e){let t=this.byPath[e.propString];if(t){if(e===t||t.hasCode(`union`)&&t.errors.length===0)return;let n=e.hasCode(`union`)&&e.errors.length===0?e:new ln({code:`intersection`,errors:t.hasCode(`intersection`)?[...t.errors,e]:[t,e]},this.ctx),r=this.indexOf(t);this.mutable[r===-1?this.length:r]=n,this.byPath[e.propString]=n,this.addAncestorPaths(e)}else this.byPath[e.propString]=e,this.addAncestorPaths(e),this.mutable.push(e);this.count++}transform(t){let n=new e(this.ctx);for(let e of this)n.add(t(e));return n}merge(e){for(let t of e)this.add(new ln({...t,path:[...this.ctx.path,...t.path]},this.ctx))}affectsPath(e){return this.length===0?!1:e.stringifyAncestors().some(e=>e in this.byPath)||e.stringify()in this.byAncestorPath}get summary(){return this.toString()}get issues(){return this}toJSON(){return[...this.map(e=>e.toJSON())]}toString(){return this.join(`
11
+ `)}addAncestorPaths(e){for(let t of e.path.stringifyAncestors())this.byAncestorPath[t]=a(this.byAncestorPath[t],e)}},dn=class extends Error{name=`TraversalError`;constructor(e){e.length===1?super(e.summary):super(`
12
+ `+e.map(e=>` • ${fn(e)}`).join(`
13
+ `)),Object.defineProperty(this,"arkErrors",{value:e,enumerable:!1})}},fn=e=>e.toString().split(`
14
+ `).join(`
15
+ `),pn=class{path=[];errors=new un(this);root;config;queuedMorphs=[];branches=[];seen={};constructor(e,t){this.root=e,this.config=t}get data(){let e=this.root;for(let t of this.path)e=e?.[t];return e}get propString(){return Dt(this.path)}reject(e){return this.error(e),!1}mustBe(e){return this.error(e),!1}error(e){let t=typeof e==`object`?e.code?e:{...e,code:`predicate`}:{code:`predicate`,expected:e};return this.errorFromContext(t)}hasError(){return this.currentErrorCount!==0}get currentBranch(){return this.branches[this.branches.length-1]}queueMorphs(e){let t={path:new Ot(...this.path),morphs:e};this.currentBranch?this.currentBranch.queuedMorphs.push(t):this.queuedMorphs.push(t)}finalize(e){return this.queuedMorphs.length&&(typeof this.root==`object`&&this.root!==null&&this.config.clone&&(this.root=this.config.clone(this.root)),this.applyQueuedMorphs()),this.hasError()?e?e(this.errors):this.errors:this.root}get currentErrorCount(){return this.currentBranch?+!!this.currentBranch.error:this.errors.count}get failFast(){return this.branches.length!==0}pushBranch(){this.branches.push({error:void 0,queuedMorphs:[]})}popBranch(){return this.branches.pop()}get external(){return this}errorFromNodeContext(e){return this.errorFromContext(e)}errorFromContext(e){let t=new ln(e,this);return this.currentBranch?this.currentBranch.error=t:this.errors.add(t),t}applyQueuedMorphs(){for(;this.queuedMorphs.length;){let e=this.queuedMorphs;this.queuedMorphs=[];for(let{path:t,morphs:n}of e)this.errors.affectsPath(t)||this.applyMorphsAtPath(t,n)}}applyMorphsAtPath(e,t){let n=e[e.length-1],r;if(n!==void 0){r=this.root;for(let t=0;t<e.length-1;t++)r=r[e[t]]}for(let i of t){this.path=[...e];let t=A(i),a=i(r===void 0?this.root:r[n],this);if(a instanceof ln){this.errors.includes(a)||this.errors.add(a);break}if(a instanceof un){t||this.errors.merge(a),this.queuedMorphs=[];break}r===void 0?this.root=a:r[n]=a,this.applyQueuedMorphs()}}},P=(e,t,n)=>{if(!n)return t();n.path.push(e);let r=t();return n.path.pop(),r},mn=class extends x{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(e,t){super((e,t,n=this.onFail)=>t?(this.traverseApply(e,t),t.hasError()?t.errors:t.data):this.rootApply(e,n),{attach:e}),this.attachments=e,this.$=t,this.onFail=this.meta.onFail??this.$.resolvedConfig.onFail,this.includesTransform=this.hasKind(`morph`)||this.hasKind(`structure`)&&this.structuralMorph!==void 0||this.hasKind(`sequence`)&&this.inner.defaultables!==void 0,this.includesContextualPredicate=this.hasKind(`predicate`)&&this.inner.predicate.length!==1,this.isCyclic=this.kind===`alias`,this.referencesById={[this.id]:this},this.shallowReferences=this.hasKind(`structure`)?[this,...this.children]:this.children.reduce((e,t)=>Sn(e,t.shallowReferences),[this]);let n=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let e=0;e<this.children.length;e++){if(this.includesTransform||=this.children[e].includesTransform,this.includesContextualPredicate||=this.children[e].includesContextualPredicate,this.isCyclic||=this.children[e].isCyclic,!n){let t=this.children[e].flatRefs;for(let e=0;e<t.length;e++){let n=t[e];if(!this.flatRefs.some(e=>bn(e,n))){this.flatRefs.push(n);for(let e of n.node.branches)(e.hasKind(`morph`)||e.hasKind(`intersection`)&&e.structure?.structuralMorph!==void 0)&&this.flatMorphs.push({path:n.path,propString:n.propString,node:e})}}}Object.assign(this.referencesById,this.children[e].referencesById)}this.flatRefs.sort((e,t)=>e.path.length>t.path.length?1:e.path.length<t.path.length?-1:e.propString>t.propString?1:e.propString<t.propString||e.node.expression<t.node.expression?-1:1),this.allowsRequiresContext=this.includesContextualPredicate||this.isCyclic,this.rootApplyStrategy=!this.allowsRequiresContext&&this.flatMorphs.length===0?this.shallowMorphs.length===0?`allows`:this.shallowMorphs.every(e=>e.length===1||e.name===`$arkStructuralMorph`)?this.hasKind(`union`)?this.branches.some(e=>e.shallowMorphs.length>1)?`contextual`:`branchedOptimistic`:this.shallowMorphs.length>1?`contextual`:`optimistic`:`contextual`:`contextual`,this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?e=>this.traverseAllows(e,new pn(e,this.$.resolvedConfig)):e=>this.traverseAllows(e)}createRootApply(){switch(this.rootApplyStrategy){case`allows`:return(e,t)=>{if(this.allows(e))return e;let n=new pn(e,this.$.resolvedConfig);return this.traverseApply(e,n),n.finalize(t)};case`contextual`:return(e,t)=>{let n=new pn(e,this.$.resolvedConfig);return this.traverseApply(e,n),n.finalize(t)};case`optimistic`:this.contextFreeMorph=this.shallowMorphs[0];let e=this.$.resolvedConfig.clone;return(t,n)=>{if(this.allows(t))return this.contextFreeMorph(e&&(typeof t==`object`&&t||typeof t==`function`)?e(t):t);let r=new pn(t,this.$.resolvedConfig);return this.traverseApply(t,r),r.finalize(n)};case`branchedOptimistic`:return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,m(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=yn(this.metaJson);cacheGetter(e,t){return Object.defineProperty(this,e,{value:t}),t}get description(){return this.cacheGetter(`description`,this.meta?.description??this.$.resolvedConfig[this.kind].description(this))}get references(){return Object.values(this.referencesById)}precedence=$t(this.kind);precompilation;assert=(e,t)=>this(e,t,e=>e.throw());traverse(e,t){return this(e,t,null)}get in(){return this.cacheGetter(`in`,this.rawIn.isRoot()?this.$.finalize(this.rawIn):this.rawIn)}get rawIn(){return this.cacheGetter(`rawIn`,this.getIo(`in`))}get out(){return this.cacheGetter(`out`,this.rawOut.isRoot()?this.$.finalize(this.rawOut):this.rawOut)}get rawOut(){return this.cacheGetter(`rawOut`,this.getIo(`out`))}getIo(e){if(!this.includesTransform)return this;let t={};for(let[n,r]of this.innerEntries){let i=this.impl.keys[n];if(i.reduceIo)i.reduceIo(e,t,r);else if(i.child){let i=r;t[n]=b(i)?i.map(t=>e===`in`?t.rawIn:t.rawOut):e===`in`?i.rawIn:i.rawOut}else t[n]=r}return this.$.node(this.kind,t)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(e){let t=A(e)?e:this.$.parseDefinition(e);return this.innerHash===t.innerHash}ifEquals(e){return this.equals(e)?this:void 0}hasKind(e){return this.kind===e}assertHasKind(e){return this.kind!==e&&ne(`${this.kind} node was not of asserted kind ${e}`),this}hasKindIn(...e){return e.includes(this.kind)}assertHasKindIn(...e){return r(e,this.kind)||ne(`${this.kind} node was not one of asserted kinds ${e}`),this}isBasis(){return r(Ht,this.kind)}isConstraint(){return r(Kt,this.kind)}isStructural(){return r(Ut,this.kind)}isRefinement(){return r(Gt,this.kind)}isRoot(){return r(qt,this.kind)}isUnknown(){return this.hasKind(`intersection`)&&this.children.length===0}isNever(){return this.hasKind(`union`)&&this.children.length===0}hasUnit(e){return this.hasKind(`unit`)&&this.allows(e)}hasOpenIntersection(){return this.impl.intersectionIsOpen}get nestableExpression(){return this.expression}select(e){let t=hn.normalize(e);return this._select(t)}_select(e){let t=hn.applyBoundary[e.boundary??`references`](this);return e.kind&&(t=t.filter(t=>t.kind===e.kind)),e.where&&(t=t.filter(e.where)),hn.applyMethod[e.method??`filter`](t,this,e)}transform(e,t){return this._transform(e,this._createTransformContext(t))}_createTransformContext(e){return{root:this,selected:void 0,seen:{},path:[],parseOptions:{prereduced:e?.prereduced??!1},undeclaredKeyHandling:void 0,...e}}_transform(e,t){let n=t.bindScope??this.$;if(t.seen[this.id])return this.$.lazilyResolve(t.seen[this.id]);if(t.shouldTransform?.(this,t)===!1)return this;let r;t.seen[this.id]=()=>r,this.hasKind(`structure`)&&this.undeclared!==t.undeclaredKeyHandling&&(t={...t,undeclaredKeyHandling:this.undeclared});let i=_(this.inner,(n,r)=>{if(!this.impl.keys[n].child)return[n,r];let i=r;if(!b(i)){let r=i._transform(e,t);return r?[n,r]:[]}if(i.length===0)return[n,r];let a=i.flatMap(n=>n._transform(e,t)??[]);return a.length?[n,a]:[]});delete t.seen[this.id];let a=Object.assign(i,{meta:this.meta}),o=t.selected&&!t.selected.includes(this)?a:e(this.kind,a,t);if(o===null)return null;if(A(o))return r=o;let s=Object.keys(o);return(s.length===0||s.length===1&&s[0]===`meta`)&&!de(this.inner)?null:(this.kind===`required`||this.kind===`optional`||this.kind===`index`)&&!(`value`in o)?t.undeclaredKeyHandling?{...o,value:T.intrinsic.unknown}:null:(this.kind===`morph`&&(o.in??=T.intrinsic.unknown),r=n.node(this.kind,o,t.parseOptions))}configureReferences(t,n=`references`){let r=hn.normalize(n),i=typeof t==`string`?(e,n)=>({...n,meta:{...n.meta,description:t}}):typeof t==`function`?(e,n)=>({...n,meta:t(n.meta)}):(e,n)=>({...n,meta:{...n.meta,...t}});if(r.boundary===`self`)return this.$.node(this.kind,i(this.kind,{...this.inner,meta:this.meta}));let a=this._select(r),o=a&&e(a),s=r.boundary===`child`?(e,t)=>t.root.children.includes(e):r.boundary===`shallow`?e=>e.kind!==`structure`:()=>!0;return this.$.finalize(this.transform(i,{shouldTransform:s,selected:o}))}},hn={applyBoundary:{self:e=>[e],child:e=>[...e.children],shallow:e=>[...e.shallowReferences],references:e=>[...e.references]},applyMethod:{filter:e=>e,assertFilter:(e,t,n)=>(e.length===0&&ne(gn(t,n)),e),find:e=>e[0],assertFind:(e,t,n)=>(e.length===0&&ne(gn(t,n)),e[0])},normalize:e=>typeof e==`function`?{boundary:`references`,method:`filter`,where:e}:typeof e==`string`?v(e,hn.applyBoundary)?{method:`filter`,boundary:e}:{boundary:`references`,method:`filter`,kind:e}:{boundary:`references`,method:`filter`,...e}},gn=(e,t)=>`${e} had no references matching ${w(t)}.`,_n=e=>Dt(e,{stringifyNonKey:e=>e.expression}),vn=/"(\$ark\.[^"]+)"/g,yn=e=>JSON.stringify(e).replace(vn,`$1`),F=(e,t)=>({path:e,node:t,propString:_n(e)}),bn=(e,t)=>e.propString===t.propString&&e.node.equals(t.node),xn=(e,t)=>c(e,t,{isEqual:bn}),Sn=(e,t)=>c(e,t,{isEqual:(e,t)=>e.equals(t)}),I=class e extends Array{static init(t,n,r,i){return new e({kind:t,l:n,r,path:i?.path??[],optional:i?.optional??!1})}add(e,t,n,r){return this.push({kind:e,l:t,r:n,path:r?.path??[],optional:r?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){let{path:e,l:t,r:n}=this[0],r=Dt(e);return Tn(`Intersection${r&&` at ${r}`} of ${Cn(t,n)}`)}return`The following intersections result in unsatisfiable types:\n• ${this.map(({path:e,l:t,r:n})=>`${e}: ${Cn(t,n)}`).join(`
16
+ • `)}`}throw(){return h(this.describeReasons())}invert(){let t=this.map(e=>({...e,l:e.r,r:e.l}));return t instanceof e?t:new e(...t)}withPrefixKey(e,t){return this.map(n=>({...n,path:[e,...n.path],optional:n.optional||t===`optional`}))}toNeverIfDisjoint(){return T.intrinsic.never}},Cn=(e,t)=>`${wn(e)} and ${wn(t)}`,wn=e=>A(e)?e.expression:b(e)?e.map(wn).join(` | `)||`never`:String(e),Tn=e=>`${e} results in an unsatisfiable type`,En={},L=(e,t,n)=>R(e,t,{$:n,invert:!1,pipe:!1}),Dn=(e,t,n)=>R(e,t,{$:n,invert:!1,pipe:!0}),R=((e,t,n)=>{let r=n.pipe?`|>`:`&`,i=`${e.hash}${r}${t.hash}`;if(En[i]!==void 0)return En[i];if(!n.pipe){let n=`${t.hash}${r}${e.hash}`;if(En[n]!==void 0){let e=En[n],t=e instanceof I?e.invert():e;return En[i]=t,t}}let a=!n.pipe||!e.includesTransform&&!t.includesTransform;if(a&&e.equals(t))return e;let o=a?On(e,t,n):e.hasKindIn(...qt)?kn(e,t,n):On(e,t,n);return A(o)&&(e.equals(o)?o=e:t.equals(o)&&(o=t)),En[i]=o,o}),On=(e,t,n)=>{let r=e.precedence<t.precedence?e.kind:t.kind,i=e.impl.intersections[t.kind]??t.impl.intersections[e.kind];if(i===void 0)return null;if(r===e.kind)return i(e,t,n);{let r=i(t,e,{...n,invert:!n.invert});return r instanceof I&&(r=r.invert()),r}},kn=(e,t,n)=>e.includesTransform||t.includesTransform?n.invert?An(t,e,n):An(e,t,n):On(e,t,n),An=(e,t,n)=>e.distribute(e=>jn(e,t,n),r=>{let i=r.filter(A);if(i.length===0)return I.init(`union`,e.branches,t.branches);if(i.length<e.branches.length||!e.branches.every((e,t)=>e.rawIn.equals(i[t].rawIn)))return n.$.parseSchema(i);if(i.length===1)return i[0];let a={branches:i};return n.$.parseSchema(a)}),jn=(e,t,n)=>{if(e.hasKind(`morph`)){let r=[...e.morphs];if(e.lastMorphIfNode){let i=R(e.lastMorphIfNode,t,n);if(i instanceof I)return i;r[r.length-1]=i}else r.push(t);return n.$.node(`morph`,{morphs:r,in:e.inner.in})}if(t.hasKind(`morph`)){let r=R(e,t.rawIn,n);return r instanceof I?r:n.$.node(`morph`,{morphs:[t],in:r})}return n.$.node(`morph`,{morphs:[t],in:e})},z=class extends mn{constructor(e,t){super(e,t),Object.defineProperty(this,O,{value:`constraint`,enumerable:!1})}impliedSiblings;intersect(e){return L(this,e,this.$)}},Mn=class extends z{traverseApply=(e,t)=>{this.traverseAllows(e,t)||t.errorFromNodeContext(this.errorContext)};compile(e){e.traversalKind===`Allows`?e.return(this.compiledCondition):e.if(this.compiledNegation,()=>e.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return tn(this.errorContext)}},B=e=>(t,n)=>{if(b(t)){if(t.length===0)return;let r=t.map(t=>n.$.node(e,t));return e===`predicate`?r:r.sort((e,t)=>e.hash<t.hash?-1:1)}let r=n.$.node(e,t);return r.hasOpenIntersection()?[r]:r},Nn=e=>{let t=e.r.shift();if(!t){let t=e.l.length===0&&e.kind===`structure`?T.intrinsic.unknown.internal:e.ctx.$.node(e.kind,Object.assign(e.baseInner,Fn(e.l)),{prereduced:!0});for(let n of e.roots){if(t instanceof I)return t;t=R(n,t,e.ctx)}return t}let n=!1;for(let r=0;r<e.l.length;r++){let i=R(e.l[r],t,e.ctx);if(i!==null){if(i instanceof I)return i;if(i.isRoot())return e.roots.push(i),e.l.splice(r),Nn(e);if(!n)e.l[r]=i,n=!0;else if(!e.l.includes(i))return m(`Unexpectedly encountered multiple distinct intersection results for refinement ${t}`)}}if(n||e.l.push(t),e.kind===`intersection`&&t.impliedSiblings)for(let n of t.impliedSiblings)c(e.r,n);return Nn(e)},Pn=e=>Object.entries(e).flatMap(([e,t])=>e in Yt?t:[]).sort((e,t)=>e.precedence<t.precedence?-1:e.precedence>t.precedence?1:e.kind===`predicate`&&t.kind===`predicate`?0:e.hash<t.hash?-1:1),Fn=e=>{let t={};for(let n of e)if(n.hasOpenIntersection())t[n.kind]=a(t[n.kind],n);else{if(t[n.kind])return m(`Unexpected intersection of closed refinements of kind ${n.kind}`);t[n.kind]=n}return t},In=(...e)=>h(Ln(...e)),Ln=(e,t,n)=>{let r=n.hasKind(`morph`)?`a morph`:n.isUnknown()?`unknown`:n.exclude(t).defaultShortDescription;return`${Ie(e)} operand must be ${t.description} (was ${r})`},Rn=(e,t,n)=>new Bn(e,t,n,n,null),zn=class extends x{},Bn=class extends x{[O]=`generic`;paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(e,t,n,r,i){super((...e)=>{let n=_(this.names,(t,n)=>{let r=this.arg$.parse(e[t]);return r.extends(this.constraints[t])||h(Vn(n,this.constraints[t].expression,r.expression)),[n,r]});if(this.defIsLazy()){let e=this.bodyDef(n);return this.$.parse(e)}return this.$.parse(t,{args:n})}),this.paramDefs=e,this.bodyDef=t,this.$=n,this.arg$=r,this.hkt=i,this.description=i?new i().description??`a generic type for ${i.constructor.name}`:`a generic type`,this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof zn}cacheGetter(e,t){return Object.defineProperty(this,e,{value:t}),t}get json(){return this.cacheGetter(`json`,{params:this.params.map(e=>e[1].isUnknown()?e[0]:[e[0],e[1].json]),body:vt(this.bodyDef)})}get params(){return this.cacheGetter(`params`,this.paramDefs.map(e=>typeof e==`string`?[e,T.intrinsic.unknown]:[e[0],this.$.parse(e[1])]))}get names(){return this.cacheGetter(`names`,this.params.map(e=>e[0]))}get constraints(){return this.cacheGetter(`constraints`,this.params.map(e=>e[1]))}get internal(){return this}get referencesById(){return this.baseInstantiation.internal.referencesById}get references(){return this.baseInstantiation.internal.references}},Vn=(e,t,n)=>`${e} must be assignable to ${t} (was ${n})`,Hn={implementation:M({kind:`predicate`,hasAssociatedError:!0,collapsibleKey:`predicate`,keys:{predicate:{}},normalize:e=>typeof e==`function`?{predicate:e}:e,defaults:{description:e=>`valid according to ${e.predicate.name||`an anonymous predicate`}`},intersectionIsOpen:!0,intersections:{predicate:()=>null}}),Node:class extends z{serializedPredicate=E(this.predicate);compiledCondition=`${this.serializedPredicate}(data, ctx)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=null;expression=this.serializedPredicate;traverseAllows=this.predicate;errorContext={code:`predicate`,description:this.description,meta:this.meta};compiledErrorContext=tn(this.errorContext);traverseApply=(e,t)=>{let n=t.currentErrorCount;!this.predicate(e,t.external)&&t.currentErrorCount===n&&t.errorFromNodeContext(this.errorContext)};compile(e){e.traversalKind===`Allows`?e.return(this.compiledCondition):(e.initializeErrorCount(),e.if(`${this.compiledNegation} && ctx.currentErrorCount === errorCount`,()=>e.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`)))}reduceJsonSchema(e,t){return t.fallback.predicate({code:`predicate`,base:e,predicate:this.predicate})}}},Un={implementation:M({kind:`divisor`,collapsibleKey:`rule`,keys:{rule:{parse:e=>Number.isInteger(e)?e:h(Wn(e))}},normalize:e=>typeof e==`number`?{rule:e}:e,hasAssociatedError:!0,defaults:{description:e=>e.rule===1?`an integer`:e.rule===2?`even`:`a multiple of ${e.rule}`},intersections:{divisor:(e,t,n)=>n.$.node(`divisor`,{rule:Math.abs(e.rule*t.rule/Gn(e.rule,t.rule))})},obviatesBasisDescription:!0}),Node:class extends Mn{traverseAllows=e=>e%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=T.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(e){return e.type=`integer`,this.rule===1||(e.multipleOf=this.rule),e}}},Wn=e=>`divisor must be an integer (was ${e})`,Gn=(e,t)=>{let n,r=e,i=t;for(;i!==0;)n=i,i=r%i,r=n;return r},V=class extends Mn{boundOperandKind=er[this.kind];compiledActual=this.boundOperandKind===`value`?`data`:this.boundOperandKind===`length`?`data.length`:`data.valueOf()`;comparator=tr(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${Kn[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind===`date`?nr(this.numericLimit):`${this.numericLimit}`;limitKind=this.comparator[0]===`<`?`upper`:`lower`;isStricterThan(e){return(this.limitKind===`upper`?this.numericLimit<e.numericLimit:this.numericLimit>e.numericLimit)||this.numericLimit===e.numericLimit&&this.exclusive===!0&&!e.exclusive}overlapsRange(e){return!(this.isStricterThan(e)||this.numericLimit===e.numericLimit&&(this.exclusive||e.exclusive))}overlapIsUnit(e){return this.numericLimit===e.numericLimit&&!this.exclusive&&!e.exclusive}},Kn={"<":`>=`,"<=":`>`,">":`<=`,">=":`<`},qn={min:`max`,minLength:`maxLength`,after:`before`},Jn={parse:e=>e||void 0},Yn=e=>t=>{if(typeof t==`number`)return{rule:t};let{exclusive:n,...r}=t;return n?{...r,rule:e===`minLength`?r.rule+1:r.rule-1}:r},Xn=e=>t=>{if(typeof t==`number`||typeof t==`string`||t instanceof Date)return{rule:t};let{exclusive:n,...r}=t;if(!n)return r;let i=typeof r.rule==`number`?r.rule:typeof r.rule==`string`?new Date(r.rule).valueOf():r.rule.valueOf();return n?{...r,rule:e===`after`?i+1:i-1}:r},Zn=e=>typeof e==`string`||typeof e==`number`?new Date(e):e,Qn=(e,t)=>`${e} bound must be a positive integer (was ${t})`,$n=e=>t=>((!Number.isInteger(t)||t<0)&&h(Qn(e,t)),t),er={min:`value`,max:`value`,minLength:`length`,maxLength:`length`,after:`date`,before:`date`},tr=(e,t)=>`${v(e,qn)?`>`:`<`}${t?``:`=`}`,nr=e=>typeof e==`string`?e:new Date(e).toLocaleString(),rr=e=>`Bounded expression ${e} must be exactly one of number, string, Array, or Date`,ir={implementation:M({kind:`after`,collapsibleKey:`rule`,hasAssociatedError:!0,keys:{rule:{parse:Zn,serialize:e=>e.toISOString()}},normalize:Xn(`after`),defaults:{description:e=>`${e.collapsibleLimitString} or later`,actual:St},intersections:{after:(e,t)=>e.isStricterThan(t)?e:t}}),Node:class extends V{impliedBasis=T.intrinsic.Date.internal;collapsibleLimitString=St(this.rule);traverseAllows=e=>e>=this.rule;reduceJsonSchema(e,t){return t.fallback.date({code:`date`,base:e,after:this.rule})}}},ar={implementation:M({kind:`before`,collapsibleKey:`rule`,hasAssociatedError:!0,keys:{rule:{parse:Zn,serialize:e=>e.toISOString()}},normalize:Xn(`before`),defaults:{description:e=>`${e.collapsibleLimitString} or earlier`,actual:St},intersections:{before:(e,t)=>e.isStricterThan(t)?e:t,after:(e,t,n)=>e.overlapsRange(t)?e.overlapIsUnit(t)?n.$.node(`unit`,{unit:e.rule}):null:I.init(`range`,e,t)}}),Node:class extends V{collapsibleLimitString=St(this.rule);traverseAllows=e=>e<=this.rule;impliedBasis=T.intrinsic.Date.internal;reduceJsonSchema(e,t){return t.fallback.date({code:`date`,base:e,before:this.rule})}}},or={implementation:M({kind:`exactLength`,collapsibleKey:`rule`,keys:{rule:{parse:$n(`exactLength`)}},normalize:e=>typeof e==`number`?{rule:e}:e,hasAssociatedError:!0,defaults:{description:e=>`exactly length ${e.rule}`,actual:e=>`${e.length}`},intersections:{exactLength:(e,t,n)=>I.init(`unit`,n.$.node(`unit`,{unit:e.rule}),n.$.node(`unit`,{unit:t.rule}),{path:[`length`]}),minLength:(e,t)=>e.rule>=t.rule?e:I.init(`range`,e,t),maxLength:(e,t)=>e.rule<=t.rule?e:I.init(`range`,e,t)}}),Node:class extends Mn{traverseAllows=e=>e.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=T.intrinsic.lengthBoundable.internal;expression=`== ${this.rule}`;reduceJsonSchema(e){switch(e.type){case`string`:return e.minLength=this.rule,e.maxLength=this.rule,e;case`array`:return e.minItems=this.rule,e.maxItems=this.rule,e;default:return N.throwInternalOperandError(`exactLength`,e)}}}},sr={implementation:M({kind:`max`,collapsibleKey:`rule`,hasAssociatedError:!0,keys:{rule:{},exclusive:Jn},normalize:e=>typeof e==`number`?{rule:e}:e,defaults:{description:e=>e.rule===0?e.exclusive?`negative`:`non-positive`:`${e.exclusive?`less than`:`at most`} ${e.rule}`},intersections:{max:(e,t)=>e.isStricterThan(t)?e:t,min:(e,t,n)=>e.overlapsRange(t)?e.overlapIsUnit(t)?n.$.node(`unit`,{unit:e.rule}):null:I.init(`range`,e,t)},obviatesBasisDescription:!0}),Node:class extends V{impliedBasis=T.intrinsic.number.internal;traverseAllows=this.exclusive?e=>e<this.rule:e=>e<=this.rule;reduceJsonSchema(e){return this.exclusive?e.exclusiveMaximum=this.rule:e.maximum=this.rule,e}}},cr={implementation:M({kind:`maxLength`,collapsibleKey:`rule`,hasAssociatedError:!0,keys:{rule:{parse:$n(`maxLength`)}},reduce:(e,t)=>e.rule===0?t.node(`exactLength`,e):void 0,normalize:Yn(`maxLength`),defaults:{description:e=>`at most length ${e.rule}`,actual:e=>`${e.length}`},intersections:{maxLength:(e,t)=>e.isStricterThan(t)?e:t,minLength:(e,t,n)=>e.overlapsRange(t)?e.overlapIsUnit(t)?n.$.node(`exactLength`,{rule:e.rule}):null:I.init(`range`,e,t)}}),Node:class extends V{impliedBasis=T.intrinsic.lengthBoundable.internal;traverseAllows=e=>e.length<=this.rule;reduceJsonSchema(e){switch(e.type){case`string`:return e.maxLength=this.rule,e;case`array`:return e.maxItems=this.rule,e;default:return N.throwInternalOperandError(`maxLength`,e)}}}},lr={implementation:M({kind:`min`,collapsibleKey:`rule`,hasAssociatedError:!0,keys:{rule:{},exclusive:Jn},normalize:e=>typeof e==`number`?{rule:e}:e,defaults:{description:e=>e.rule===0?e.exclusive?`positive`:`non-negative`:`${e.exclusive?`more than`:`at least`} ${e.rule}`},intersections:{min:(e,t)=>e.isStricterThan(t)?e:t},obviatesBasisDescription:!0}),Node:class extends V{impliedBasis=T.intrinsic.number.internal;traverseAllows=this.exclusive?e=>e>this.rule:e=>e>=this.rule;reduceJsonSchema(e){return this.exclusive?e.exclusiveMinimum=this.rule:e.minimum=this.rule,e}}},ur={implementation:M({kind:`minLength`,collapsibleKey:`rule`,hasAssociatedError:!0,keys:{rule:{parse:$n(`minLength`)}},reduce:e=>e.rule===0?T.intrinsic.unknown:void 0,normalize:Yn(`minLength`),defaults:{description:e=>e.rule===1?`non-empty`:`at least length ${e.rule}`,actual:e=>e.length===0?``:`${e.length}`},intersections:{minLength:(e,t)=>e.isStricterThan(t)?e:t}}),Node:class extends V{impliedBasis=T.intrinsic.lengthBoundable.internal;traverseAllows=e=>e.length>=this.rule;reduceJsonSchema(e){switch(e.type){case`string`:return e.minLength=this.rule,e;case`array`:return e.minItems=this.rule,e;default:return N.throwInternalOperandError(`minLength`,e)}}}},dr={min:lr.implementation,max:sr.implementation,minLength:ur.implementation,maxLength:cr.implementation,exactLength:or.implementation,after:ir.implementation,before:ar.implementation},fr={min:lr.Node,max:sr.Node,minLength:ur.Node,maxLength:cr.Node,exactLength:or.Node,after:ir.Node,before:ar.Node},pr={implementation:M({kind:`pattern`,collapsibleKey:`rule`,keys:{rule:{},flags:{}},normalize:e=>typeof e==`string`?{rule:e}:e instanceof RegExp?e.flags?{rule:e.source,flags:e.flags}:{rule:e.source}:e,obviatesBasisDescription:!0,obviatesBasisExpression:!0,hasAssociatedError:!0,intersectionIsOpen:!0,defaults:{description:e=>`matched by ${e.rule}`},intersections:{pattern:()=>null}}),Node:class extends Mn{instance=new RegExp(this.rule,this.flags);expression=`${this.instance}`;traverseAllows=this.instance.test.bind(this.instance);compiledCondition=`${this.expression}.test(data)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=T.intrinsic.string.internal;reduceJsonSchema(e,t){return e.pattern?t.fallback.patternIntersection({code:`patternIntersection`,base:e,pattern:this.rule}):(e.pattern=this.rule,e)}}},mr=(e,t)=>{let n=hr(e);return t&&!t.includes(n)?h(`Root of kind ${n} should be one of ${t}`):n},hr=e=>{if(k(e,`root`))return e.kind;if(typeof e==`string`)return e[0]===`$`?`alias`:e in p?`domain`:`proto`;if(typeof e==`function`)return`proto`;if(typeof e!=`object`||!e)return h(gr(e));if(`morphs`in e)return`morph`;if(`branches`in e||b(e))return`union`;if(`unit`in e)return`unit`;if(`reference`in e)return`alias`;let t=Object.keys(e);return t.length===0||t.some(e=>e in Yt)?`intersection`:`proto`in e?`proto`:`domain`in e?`domain`:h(gr(e))},gr=e=>`${w(e)} is not a valid type schema`,_r={},vr=e=>b(e)?e.map(e=>e.collapsibleJson):e.collapsibleJson,H={};T.nodesByRegisteredId=H;var yr=e=>(_r[e]??=0,`${e}${++_r[e]}`),br=e=>{let t=ra[e.kind],n=t.applyConfig?.(e.def,e.$.resolvedConfig)??e.def,r={},{meta:i,...a}=n,o=i===void 0?{}:typeof i==`string`?{description:i}:i,s=ie(a).sort(([e],[t])=>Qt(e)?Qt(t)?$t(e)-$t(t):1:Qt(t)||e<t?-1:1).filter(([e,t])=>{if(e.startsWith(`meta.`)){let n=e.slice(5);return o[n]=t,!1}return!0});for(let n of s){let i=n[0],a=t.keys[i];if(!a)return h(`Key ${i} is not valid on ${e.kind} schema`);let o=a.parse?a.parse(n[1],e):n[1];o!==y&&(o!==void 0||a.preserveUndefined)&&(r[i]=o)}if(t.reduce&&!e.prereduced){let n=t.reduce(r,e.$);if(n)return n instanceof I?n.throw():Cr(n,o)}return xr({id:e.id,kind:e.kind,inner:r,meta:o,$:e.$})},xr=({id:e,kind:t,inner:n,meta:r,$:i,ignoreCache:a})=>{let o=ra[t],s=ie(n),c=[],l={};for(let[e,t]of s){let n=o.keys[e],r=n.serialize??(n.child?vr:j);if(l[e]=r(t),n.child===!0){let e=t;b(e)?c.push(...e):c.push(e)}else typeof n.child==`function`&&c.push(...n.child(t))}o.finalizeInnerJson&&(l=o.finalizeInnerJson(l));let u={...l},d={};de(r)||(d=_(r,(e,t)=>[e,e===`examples`?t:j(t)]),u.meta=wr(d,`description`,!0)),l=wr(l,o.collapsibleKey,!1);let f=JSON.stringify({kind:t,...l});u=wr(u,o.collapsibleKey,!1);let p=wr(u,o.collapsibleKey,!0),ee=JSON.stringify({kind:t,...u});if(i.nodesByHash[ee]&&!a)return i.nodesByHash[ee];let te={id:e,kind:t,impl:o,inner:n,innerEntries:s,innerJson:l,innerHash:f,meta:r,metaJson:d,json:u,hash:ee,collapsibleJson:p,children:c};if(t!==`intersection`)for(let e in n)e!==`in`&&e!==`out`&&(te[e]=n[e]);let m=new ia[t](te,i);return i.nodesByHash[ee]=m},Sr=(e,t)=>e.id===t?e:(A(H[t])&&m(`Unexpected attempt to overwrite node id ${t}`),xr({id:t,kind:e.kind,inner:e.inner,meta:e.meta,$:e.$,ignoreCache:!0})),Cr=(e,t,n)=>(n&&A(H[n])&&m(`Unexpected attempt to overwrite node id ${n}`),xr({id:n??yr(t.alias??e.kind),kind:e.kind,inner:e.inner,meta:t,$:e.$})),wr=(e,t,n)=>{let r=Object.keys(e);if(r.length===1&&r[0]===t){let r=e[t];if(n||d(r,`object`)&&(Object.keys(r).length===1||Array.isArray(r)))return r}return e},Tr=(e,t,n)=>{if(e.key!==t.key)return null;let r=e.key,i=R(e.value,t.value,n),a=e.required||t.required?`required`:`optional`;if(i instanceof I){if(a===`optional`)i=T.intrinsic.never.internal;else return i.withPrefixKey(e.key,e.required&&t.required?`required`:`optional`)}if(a===`required`)return n.$.node(`required`,{key:r,value:i});let o=e.hasDefault()?t.hasDefault()?e.default===t.default?e.default:h(Dr(e.default,t.default)):e.default:t.hasDefault()?t.default:y;return n.$.node(`optional`,{key:r,value:i,default:o})},Er=class extends z{required=this.kind===`required`;optional=this.kind===`optional`;impliedBasis=T.intrinsic.object.internal;serializedKey=D(this.key);compiledKey=typeof this.key==`string`?this.key:this.serializedKey;flatRefs=a(this.value.flatRefs.map(e=>F([this.key,...e.path],e.node)),F([this.key],this.value));_transform(e,t){t.path.push(this.key);let n=super._transform(e,t);return t.path.pop(),n}hasDefault(){return`default`in this.inner}traverseAllows=(e,t)=>this.key in e?P(this.key,()=>this.value.traverseAllows(e[this.key],t),t):this.optional;traverseApply=(e,t)=>{this.key in e?P(this.key,()=>this.value.traverseApply(e[this.key],t),t):this.hasKind(`required`)&&t.errorFromNodeContext(this.errorContext)};compile(e){e.if(`${this.serializedKey} in data`,()=>e.traverseKey(this.serializedKey,`data${e.prop(this.key)}`,this.value)),this.hasKind(`required`)&&e.else(()=>e.traversalKind===`Apply`?e.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`):e.return(!1)),e.traversalKind===`Allows`&&e.return(!0)}},Dr=(e,t)=>`Invalid intersection of default values ${w(e)} & ${w(t)}`,Or={implementation:M({kind:`optional`,hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(e,t)=>t.$.parseSchema(e)},default:{preserveUndefined:!0}},normalize:e=>e,reduce:(e,t)=>{if(t.resolvedConfig.exactOptionalPropertyTypes===!1&&!e.value.allows(void 0))return t.node(`optional`,{...e,value:e.value.or(q.undefined)},{prereduced:!0})},defaults:{description:e=>`${e.compiledKey}?: ${e.value.description}`},intersections:{optional:Tr}}),Node:class extends Er{constructor(...e){super(...e),`default`in this.inner&&Mr(this.value,this.inner.default,this.key)}get rawIn(){let e=super.rawIn;return this.hasDefault()?this.$.node(`optional`,ue(e.inner,{default:!0}),{prereduced:!0}):e}get outProp(){if(!this.hasDefault())return this;let{default:e,...t}=this.inner;return this.cacheGetter(`outProp`,this.$.node(`required`,t,{prereduced:!0}))}expression=this.hasDefault()?`${this.compiledKey}: ${this.value.expression} = ${w(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=Ar(this);defaultValueMorphRef=this.defaultValueMorph&&E(this.defaultValueMorph)}},kr={},Ar=e=>{if(!e.hasDefault())return;let t=`{${e.compiledKey}: ${e.value.id} = ${j(e.default)}}`;return kr[t]??=jr(e.key,e.value,e.default)},jr=(e,t,n)=>{if(typeof n==`function`)return t.includesTransform?(r,i)=>(P(e,()=>t(r[e]=n(),i),i),r):t=>(t[e]=n(),t);let r=t.includesTransform?t.assert(n):n;return d(r,`object`)?(r,i)=>(P(e,()=>t(r[e]=n,i),i),r):t=>(t[e]=r,t)},Mr=(e,t,n)=>{let r=Me(t);d(t,`object`)&&!r&&h(Nr(n));let i=e.in(r?t():t);return i instanceof un&&(n===null&&h(`Default ${i.summary}`),h(`Default for ${i.transform(e=>e.transform(e=>({...e,prefixPath:[n]}))).summary}`)),t},Nr=e=>`Non-primitive default ${e===null?``:typeof e==`number`?`for value at [${e}] `:`for ${D(e)} `}must be specified as a function like () => ({my: 'object'})`,Pr=class extends mn{constructor(e,t){super(e,t),Object.defineProperty(this,O,{value:`root`,enumerable:!1})}get rawIn(){return super.rawIn}get rawOut(){return super.rawOut}get internal(){return this}get"~standard"(){return{vendor:`arktype`,version:1,validate:e=>{let t=this(e);return t instanceof un?t:{value:t}},jsonSchema:{input:e=>this.rawIn.toJsonSchema({target:Rr(e.target),...e.libraryOptions}),output:e=>this.rawOut.toJsonSchema({target:Rr(e.target),...e.libraryOptions})}}}as(){return this}brand(e){return e===``?h(Fr):this}readonly(){return this}branches=this.hasKind(`union`)?this.inner.branches:[this];distribute(e,t){let n=this.branches.map(e);return t?.(n)??n}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(e={}){let t=an(this.$.resolvedConfig.toJsonSchema,e);t.useRefs||=this.isCyclic;let n=typeof t.dialect==`string`?{$schema:t.dialect}:{};if(Object.assign(n,this.toJsonSchemaRecurse(t)),t.useRefs){let e=_(this.references,(e,n)=>n.isRoot()&&!n.alwaysExpandJsonSchema?[n.id,n.toResolvedJsonSchema(t)]:[]);t.target===`draft-07`?Object.assign(n,{definitions:e}):n.$defs=e}return n}toJsonSchemaRecurse(e){return e.useRefs&&!this.alwaysExpandJsonSchema?{$ref:`#/${e.target===`draft-07`?`definitions`:`$defs`}/${this.id}`}:this.toResolvedJsonSchema(e)}get alwaysExpandJsonSchema(){return this.isBasis()||this.kind===`alias`||this.hasKind(`union`)&&this.isBoolean}toResolvedJsonSchema(e){let t=this.innerToJsonSchema(e);return Object.assign(t,this.metaJson)}intersect(e){let t=this.$.parseDefinition(e),n=this.rawIntersect(t);return n instanceof I?n:this.$.finalize(n)}rawIntersect(e){return L(this,e,this.$)}toNeverIfDisjoint(){return this}and(e){let t=this.intersect(e);return t instanceof I?t.throw():t}rawAnd(e){let t=this.rawIntersect(e);return t instanceof I?t.throw():t}or(e){let t=this.$.parseDefinition(e);return this.$.finalize(this.rawOr(t))}rawOr(e){let t=[...this.branches,...e.branches];return this.$.node(`union`,t)}map(e){return this.$.schema(this.applyStructuralOperation(`map`,[e]))}pick(...e){return this.$.schema(this.applyStructuralOperation(`pick`,e))}omit(...e){return this.$.schema(this.applyStructuralOperation(`omit`,e))}required(){return this.$.schema(this.applyStructuralOperation(`required`,[]))}partial(){return this.$.schema(this.applyStructuralOperation(`partial`,[]))}_keyof;keyof(){if(this._keyof)return this._keyof;let e=this.applyStructuralOperation(`keyof`,[]).reduce((e,t)=>e.intersect(t).toNeverIfDisjoint(),T.intrinsic.unknown.internal);return e.branches.length===0&&h(Tn(`keyof ${this.expression}`)),this._keyof=this.$.finalize(e)}get props(){return this.branches.length===1?[...this.applyStructuralOperation(`props`,[])[0]]:h(Vr(this.expression))}merge(e){let t=this.$.parseDefinition(e);return this.$.schema(t.distribute(e=>this.applyStructuralOperation(`merge`,[Br(e)??h(Hr(`merge`,e.expression))])))}applyStructuralOperation(e,t){return this.distribute(n=>{if(n.equals(T.intrinsic.object)&&e!==`merge`)return n;let r=Br(n);if(r||h(Hr(e,n.expression)),e===`keyof`)return r.keyof();if(e===`get`)return r.get(...t);if(e===`props`)return r.props;let i=e===`required`?`require`:e===`partial`?`optionalize`:e;return this.$.node(`intersection`,{domain:`object`,structure:r[i](...t)})})}get(...e){return e[0]===void 0?this:this.$.schema(this.applyStructuralOperation(`get`,e))}extract(e){let t=this.$.parseDefinition(e);return this.$.schema(this.branches.filter(e=>e.extends(t)))}exclude(e){let t=this.$.parseDefinition(e);return this.$.schema(this.branches.filter(e=>!e.extends(t)))}array(){return this.$.schema(this.isUnknown()?{proto:Array}:{proto:Array,sequence:this},{prereduced:!0})}overlaps(e){return!(this.intersect(e)instanceof I)}extends(e){if(this.isNever())return!0;let t=this.intersect(e);return!(t instanceof I)&&this.equals(t)}ifExtends(e){return this.extends(e)?this:void 0}subsumes(e){return this.$.parseDefinition(e).extends(this)}configure(e,t=`shallow`){return this.configureReferences(e,t)}describe(e,t=`shallow`){return this.configure({description:e},t)}optional(){return[this,`?`]}default(e){return Mr(this,e,null),[this,`=`,e]}from(e){return this.assert(e)}_pipe(...e){let t=e.reduce((e,t)=>e.rawPipeOnce(t),this);return this.$.finalize(t)}tryPipe(...e){let t=e.reduce((e,t)=>e.rawPipeOnce(k(t,`root`)?t:((e,n)=>{try{return t(e,n)}catch(e){return n.error({code:`predicate`,predicate:t,actual:`aborted due to error:\n ${e}\n`})}})),this);return this.$.finalize(t)}pipe=Object.assign(this._pipe.bind(this),{try:this.tryPipe.bind(this)});to(e){return this.$.finalize(this.toNode(this.$.parseDefinition(e)))}toNode(e){let t=Dn(this,e,this.$);return t instanceof I?t.throw():t}rawPipeOnce(e){return k(e,`root`)?this.toNode(e):this.distribute(t=>t.hasKind(`morph`)?this.$.node(`morph`,{in:t.inner.in,morphs:[...t.morphs,e]}):this.$.node(`morph`,{in:t,morphs:[e]}),this.$.parseSchema)}narrow(e){return this.constrainOut(`predicate`,e)}constrain(e,t){return this._constrain(`root`,e,t)}constrainIn(e,t){return this._constrain(`in`,e,t)}constrainOut(e,t){return this._constrain(`out`,e,t)}_constrain(e,t,n){let r=this.$.node(t,n);if(r.isRoot())return r.isUnknown()?this:m(`Unexpected constraint node ${r}`);let i=e===`root`?this:e===`in`?this.rawIn:this.rawOut;if(i.hasKind(`morph`)||r.impliedBasis&&!i.extends(r.impliedBasis))return In(t,r.impliedBasis,this);let a=this.$.node(`intersection`,{[r.kind]:r}),o=e===`out`?Dn(this,a,this.$):L(this,a,this.$);return o instanceof I&&o.throw(),this.$.finalize(o)}onUndeclaredKey(e){let t=typeof e==`string`?e:e.rule,n=typeof e!=`string`&&e.deep;return this.$.finalize(this.transform((e,n)=>e===`structure`?t===`ignore`?ue(n,{undeclared:1}):{...n,undeclared:t}:n,n?void 0:{shouldTransform:e=>!r(Ut,e.kind)}))}hasEqualMorphs(e){return!this.includesTransform&&!e.includesTransform||!(!u(this.shallowMorphs,e.shallowMorphs)||!u(this.flatMorphs,e.flatMorphs,{isEqual:(e,t)=>e.propString===t.propString&&(e.node.hasKind(`morph`)&&t.node.hasKind(`morph`)?e.node.hasEqualMorphs(t.node):e.node.hasKind(`intersection`)&&t.node.hasKind(`intersection`)?e.node.structure?.structuralMorphRef===t.node.structure?.structuralMorphRef:!1)}))}onDeepUndeclaredKey(e){return this.onUndeclaredKey({rule:e,deep:!0})}filter(e){return this.constrainIn(`predicate`,e)}divisibleBy(e){return this.constrain(`divisor`,e)}matching(e){return this.constrain(`pattern`,e)}atLeast(e){return this.constrain(`min`,e)}atMost(e){return this.constrain(`max`,e)}moreThan(e){return this.constrain(`min`,U(e))}lessThan(e){return this.constrain(`max`,U(e))}atLeastLength(e){return this.constrain(`minLength`,e)}atMostLength(e){return this.constrain(`maxLength`,e)}moreThanLength(e){return this.constrain(`minLength`,U(e))}lessThanLength(e){return this.constrain(`maxLength`,U(e))}exactlyLength(e){return this.constrain(`exactLength`,e)}atOrAfter(e){return this.constrain(`after`,e)}atOrBefore(e){return this.constrain(`before`,e)}laterThan(e){return this.constrain(`after`,U(e))}earlierThan(e){return this.constrain(`before`,U(e))}},Fr=`Expected a non-empty brand name after #`,Ir=[`draft-2020-12`,`draft-07`],Lr=e=>`JSONSchema target '${e}' is not supported (must be ${Ir.map(e=>`"${e}"`).join(` or `)})`,Rr=e=>(r(Ir,e)||h(Lr(e)),e),U=e=>typeof e==`object`&&!(e instanceof Date)?{...e,exclusive:!0}:{rule:e,exclusive:!0},zr=(e,t)=>k(t,`root`)?k(e,`root`)?e.extends(t):t.allows(e):k(e,`root`)?e.hasUnit(t):t===e,Br=e=>e.hasKind(`morph`)?null:e.hasKind(`intersection`)?e.inner.structure??(e.basis?.domain===`object`?e.$.bindReference(T.intrinsic.emptyStructure):null):e.isBasis()&&e.domain===`object`?e.$.bindReference(T.intrinsic.emptyStructure):null,Vr=e=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:
17
+ ${e}`,Hr=(e,t)=>`${e} operand must be an object (was ${t})`,Ur=(e,t)=>_(en(e),(e,n)=>[n,t]),Wr=e=>typeof e==`string`?{reference:e}:e,Gr=e=>e instanceof I?T.intrinsic.never.internal:e,Kr=M({kind:`alias`,hasAssociatedError:!1,collapsibleKey:`reference`,keys:{reference:{serialize:e=>e.startsWith(`$`)?e:`$ark.${e}`},resolve:{}},normalize:Wr,defaults:{description:e=>e.reference},intersections:{alias:(e,t,n)=>n.$.lazilyResolve(()=>Gr(R(e.resolution,t.resolution,n)),`${e.reference}${n.pipe?`=>`:`&`}${t.reference}`),...Ur(`alias`,(e,t,n)=>t.isUnknown()?e:t.isNever()?t:t.isBasis()&&!t.overlaps(T.intrinsic.object)?I.init(`assignability`,T.intrinsic.object,t):n.$.lazilyResolve(()=>Gr(R(e.resolution,t,n)),`${e.reference}${n.pipe?`=>`:`&`}${t.id}`))}}),qr=class extends Pr{expression=this.reference;structure=void 0;get resolution(){let e=this._resolve();return H[this.id]=e}_resolve(){if(this.resolve)return this.resolve();if(this.reference[0]===`$`)return this.$.resolveRoot(this.reference.slice(1));let e=H[this.reference],t=[];for(;k(e,`context`);){if(t.includes(e.id))return h(Jr(e.id,t));t.push(e.id),e=H[e.id]}return k(e,`root`)?e:m(`Unexpected resolution for reference ${this.reference}
18
+ Seen: [${t.join(`->`)}]
19
+ Resolution: ${w(e)}`)}get resolutionId(){if(this.reference.includes(`&`)||this.reference.includes(`=>`))return this.resolution.id;if(this.reference[0]!==`$`)return this.reference;let e=this.reference.slice(1),t=this.$.resolutions[e];return typeof t==`string`?t:k(t,`root`)?t.id:m(`Unexpected resolution for reference ${this.reference}: ${w(t)}`)}get defaultShortDescription(){return p.object}innerToJsonSchema(e){return this.resolution.toJsonSchemaRecurse(e)}traverseAllows=(e,t)=>{let n=t.seen[this.reference];return n?.includes(e)?!0:(t.seen[this.reference]=a(n,e),this.resolution.traverseAllows(e,t))};traverseApply=(e,t)=>{let n=t.seen[this.reference];n?.includes(e)||(t.seen[this.reference]=a(n,e),this.resolution.traverseApply(e,t))};compile(e){let t=this.resolutionId;e.if(`ctx.seen.${t} && ctx.seen.${t}.includes(data)`,()=>e.return(!0)),e.if(`!ctx.seen.${t}`,()=>e.line(`ctx.seen.${t} = []`)),e.line(`ctx.seen.${t}.push(data)`),e.return(e.invoke(t))}},Jr=(e,t)=>`Alias '${e}' has a shallow resolution cycle: ${[...t,e].join(`->`)}`,Yr={implementation:Kr,Node:qr},Xr=class extends Pr{traverseApply=(e,t)=>{this.traverseAllows(e,t)||t.errorFromNodeContext(this.errorContext)};get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return tn(this.errorContext)}compile(e){e.traversalKind===`Allows`?e.return(this.compiledCondition):e.if(this.compiledNegation,()=>e.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}},Zr={implementation:M({kind:`domain`,hasAssociatedError:!0,collapsibleKey:`domain`,keys:{domain:{},numberAllowsNaN:{}},normalize:e=>typeof e==`string`?{domain:e}:ae(e,`numberAllowsNaN`)&&e.domain!==`number`?h(Zr.writeBadAllowNanMessage(e.domain)):e,applyConfig:(e,t)=>e.numberAllowsNaN===void 0&&e.domain===`number`&&t.numberAllowsNaN?{...e,numberAllowsNaN:!0}:e,defaults:{description:e=>p[e.domain],actual:e=>Number.isNaN(e)?`NaN`:p[f(e)]},intersections:{domain:(e,t)=>e.domain===`number`&&t.domain===`number`?e.numberAllowsNaN?t:e:I.init(`domain`,e,t)}}),Node:class extends Xr{requiresNaNCheck=this.domain===`number`&&!this.numberAllowsNaN;traverseAllows=this.requiresNaNCheck?e=>typeof e==`number`&&!Number.isNaN(e):e=>f(e)===this.domain;compiledCondition=this.domain===`object`?`((typeof data === "object" && data !== null) || typeof data === "function")`:`typeof data === "${this.domain}"${this.requiresNaNCheck?` && !Number.isNaN(data)`:``}`;compiledNegation=this.domain===`object`?`((typeof data !== "object" || data === null) && typeof data !== "function")`:`typeof data !== "${this.domain}"${this.requiresNaNCheck?` || Number.isNaN(data)`:``}`;expression=this.numberAllowsNaN?`number | NaN`:this.domain;get nestableExpression(){return this.numberAllowsNaN?`(${this.expression})`:this.expression}get defaultShortDescription(){return p[this.domain]}innerToJsonSchema(e){return this.domain===`bigint`||this.domain===`symbol`?e.fallback.domain({code:`domain`,base:{},domain:this.domain}):{type:this.domain}}},writeBadAllowNanMessage:e=>`numberAllowsNaN may only be specified with domain "number" (was ${e})`},Qr={implementation:M({kind:`intersection`,hasAssociatedError:!0,normalize:e=>{if(A(e))return e;let{structure:t,...n}=e,r=!!t,i=t??{},a=_(n,(e,t)=>v(e,Xt)?(r&&h(`Flattened structure key ${e} cannot be specified alongside a root 'structure' key.`),i[e]=t,[]):[e,t]);return(k(i,`constraint`)||!de(i))&&(a.structure=i),a},finalizeInnerJson:({structure:e,...t})=>d(e,`object`)?{...e,...t}:t,keys:{domain:{child:!0,parse:(e,t)=>t.$.node(`domain`,e)},proto:{child:!0,parse:(e,t)=>t.$.node(`proto`,e)},structure:{child:!0,parse:(e,t)=>t.$.node(`structure`,e),serialize:e=>{if(!e.sequence?.minLength)return e.collapsibleJson;let{sequence:t,...n}=e.collapsibleJson,{minVariadicLength:r,...i}=t,a=i.variadic&&Object.keys(i).length===1?i.variadic:i;return{...n,sequence:a}}},divisor:{child:!0,parse:B(`divisor`)},max:{child:!0,parse:B(`max`)},min:{child:!0,parse:B(`min`)},maxLength:{child:!0,parse:B(`maxLength`)},minLength:{child:!0,parse:B(`minLength`)},exactLength:{child:!0,parse:B(`exactLength`)},before:{child:!0,parse:B(`before`)},after:{child:!0,parse:B(`after`)},pattern:{child:!0,parse:B(`pattern`)},predicate:{child:!0,parse:B(`predicate`)}},reduce:(e,t)=>ei({},e,{$:t,invert:!1,pipe:!1}),defaults:{description:e=>{if(e.children.length===0)return`unknown`;if(e.structure)return e.structure.description;let t=[];if(e.basis&&!e.prestructurals.some(e=>e.impl.obviatesBasisDescription)&&t.push(e.basis.description),e.prestructurals.length){let n=e.prestructurals.slice().sort((e,t)=>e.kind===`min`&&t.kind===`max`?-1:0).map(e=>e.description);t.push(...n)}return e.inner.predicate&&t.push(...e.inner.predicate.map(e=>e.description)),t.join(` and `)},expected:e=>` ◦ ${e.errors.map(e=>e.expected).join(`
20
+ ◦ `)}`,problem:e=>`(${e.actual}) must be...\n${e.expected}`},intersections:{intersection:(e,t,n)=>ei(e.inner,t.inner,n),...Ur(`intersection`,(e,t,n)=>{if(e.children.length===0)return t;let{domain:r,proto:i,...a}=e.inner,o=i??r,s=o?R(o,t,n):t;return s instanceof I?s:e?.basis?.equals(s)?e:e.$.node(`intersection`,{...a,[s.kind]:s},{prereduced:!0})})}}),Node:class extends Pr{basis=this.inner.domain??this.inner.proto??null;prestructurals=[];refinements=this.children.filter(e=>e.isRefinement()?(r(Wt,e.kind)&&this.prestructurals.push(e),!0):!1);structure=this.inner.structure;expression=$r(this);get shallowMorphs(){return this.inner.structure?.structuralMorph?[this.inner.structure.structuralMorph]:[]}get defaultShortDescription(){return this.basis?.defaultShortDescription??`present`}innerToJsonSchema(e){return this.children.reduce((t,n)=>n.isBasis()?n.toJsonSchemaRecurse(e):n.reduceJsonSchema(t,e),{})}traverseAllows=(e,t)=>this.children.every(n=>n.traverseAllows(e,t));traverseApply=(e,t)=>{let n=t.currentErrorCount;if(!(this.basis&&(this.basis.traverseApply(e,t),t.currentErrorCount>n))){if(this.prestructurals.length){for(let r=0;r<this.prestructurals.length-1;r++)if(this.prestructurals[r].traverseApply(e,t),t.failFast&&t.currentErrorCount>n)return;if(this.prestructurals[this.prestructurals.length-1].traverseApply(e,t),t.currentErrorCount>n)return}if(!(this.structure&&(this.structure.traverseApply(e,t),t.currentErrorCount>n))&&this.inner.predicate){for(let r=0;r<this.inner.predicate.length-1;r++)if(this.inner.predicate[r].traverseApply(e,t),t.failFast&&t.currentErrorCount>n)return;this.inner.predicate[this.inner.predicate.length-1].traverseApply(e,t)}}};compile(e){if(e.traversalKind===`Allows`){for(let t of this.children)e.check(t);e.return(!0)}else{if(e.initializeErrorCount(),this.basis&&(e.check(this.basis),this.children.length>1&&e.returnIfFail()),this.prestructurals.length){for(let t=0;t<this.prestructurals.length-1;t++)e.check(this.prestructurals[t]),e.returnIfFailFast();e.check(this.prestructurals[this.prestructurals.length-1]),(this.structure||this.inner.predicate)&&e.returnIfFail()}if(this.structure&&(e.check(this.structure),this.inner.predicate&&e.returnIfFail()),this.inner.predicate){for(let t=0;t<this.inner.predicate.length-1;t++)e.check(this.inner.predicate[t]),e.returnIfFail();e.check(this.inner.predicate[this.inner.predicate.length-1])}}}}},$r=e=>{if(e.structure?.expression)return e.structure.expression;let t=e.basis&&!e.prestructurals.some(e=>e.impl.obviatesBasisExpression)?e.basis.nestableExpression:``,n=e.prestructurals.map(e=>e.expression).join(` & `),r=`${t}${t?` `:``}${n}`;return r===`Array == 0`?`[]`:r||`unknown`},ei=(e,t,n)=>{let r={},i=e.proto??e.domain,a=t.proto??t.domain,o=i?a?R(i,a,n):i:a;return o instanceof I?o:(o&&(r[o.kind]=o),Nn({kind:`intersection`,baseInner:r,l:Pn(e),r:Pn(t),roots:[],ctx:n}))},ti={implementation:M({kind:`morph`,hasAssociatedError:!1,keys:{in:{child:!0,parse:(e,t)=>t.$.parseSchema(e)},morphs:{parse:e,serialize:e=>e.map(e=>k(e,`root`)?e.json:E(e))},declaredIn:{child:!1,serialize:e=>e.json},declaredOut:{child:!1,serialize:e=>e.json}},normalize:e=>e,defaults:{description:e=>`a morph from ${e.rawIn.description} to ${e.rawOut?.description??`unknown`}`},intersections:{morph:(e,t,n)=>{if(!e.hasEqualMorphs(t))return h(ni(e.expression,t.expression));let r=R(e.rawIn,t.rawIn,n);if(r instanceof I)return r;let i={morphs:e.morphs};if(e.declaredIn||t.declaredIn){let r=R(e.rawIn,t.rawIn,n);if(r instanceof I)return r.throw();i.declaredIn=r}if(e.declaredOut||t.declaredOut){let r=R(e.rawOut,t.rawOut,n);if(r instanceof I)return r.throw();i.declaredOut=r}return r.distribute(e=>n.$.node(`morph`,{...i,in:e}),n.$.parseSchema)},...Ur(`morph`,(e,t,n)=>{let r=e.inner.in?R(e.inner.in,t,n):t;return r instanceof I?r:r.equals(e.inner.in)?e:n.$.node(`morph`,{...e.inner,in:r})})}}),Node:class extends Pr{serializedMorphs=this.morphs.map(E);compiledMorphs=`[${this.serializedMorphs}]`;lastMorph=this.inner.morphs[this.inner.morphs.length-1];lastMorphIfNode=k(this.lastMorph,`root`)?this.lastMorph:void 0;introspectableIn=this.inner.in;introspectableOut=this.lastMorphIfNode?Object.assign(this.referencesById,this.lastMorphIfNode.referencesById)&&this.lastMorphIfNode.rawOut:void 0;get shallowMorphs(){return Array.isArray(this.inner.in?.shallowMorphs)?[...this.inner.in.shallowMorphs,...this.morphs]:this.morphs}get rawIn(){return this.declaredIn??this.inner.in?.rawIn??T.intrinsic.unknown.internal}get rawOut(){return this.declaredOut??this.introspectableOut??T.intrinsic.unknown.internal}declareIn(e){return this.$.node(`morph`,{...this.inner,declaredIn:e})}declareOut(e){return this.$.node(`morph`,{...this.inner,declaredOut:e})}expression=`(In: ${this.rawIn.expression}) => ${this.lastMorphIfNode?`To`:`Out`}<${this.rawOut.expression}>`;get defaultShortDescription(){return this.rawIn.meta.description??this.rawIn.defaultShortDescription}innerToJsonSchema(e){return e.fallback.morph({code:`morph`,base:this.rawIn.toJsonSchemaRecurse(e),out:this.introspectableOut?.toJsonSchemaRecurse(e)??null})}compile(e){if(e.traversalKind===`Allows`){if(!this.introspectableIn)return;e.return(e.invoke(this.introspectableIn))}else this.introspectableIn&&e.line(e.invoke(this.introspectableIn)),e.line(`ctx.queueMorphs(${this.compiledMorphs})`)}traverseAllows=(e,t)=>!this.introspectableIn||this.introspectableIn.traverseAllows(e,t);traverseApply=(e,t)=>{this.introspectableIn&&this.introspectableIn.traverseApply(e,t),t.queueMorphs(this.morphs)};hasEqualMorphs(e){return u(this.morphs,e.morphs,{isEqual:(e,t)=>e===t||k(e,`root`)&&k(t,`root`)&&e.equals(t)})}}},ni=(e,t)=>`The intersection of distinct morphs at a single path is indeterminate:
21
+ Left: ${e}
22
+ Right: ${t}`,ri={implementation:M({kind:`proto`,hasAssociatedError:!0,collapsibleKey:`proto`,keys:{proto:{serialize:e=>De(e)??j(e)},dateAllowsInvalid:{}},normalize:e=>{let t=typeof e==`string`?{proto:be[e]}:typeof e==`function`?A(e)?e:{proto:e}:typeof e.proto==`string`?{...e,proto:be[e.proto]}:e;return typeof t.proto!=`function`&&h(ri.writeInvalidSchemaMessage(t.proto)),ae(t,`dateAllowsInvalid`)&&t.proto!==Date&&h(ri.writeBadInvalidDateMessage(t.proto)),t},applyConfig:(e,t)=>e.dateAllowsInvalid===void 0&&e.proto===Date&&t.dateAllowsInvalid?{...e,dateAllowsInvalid:!0}:e,defaults:{description:e=>e.builtinName?Ee[e.builtinName]:`an instance of ${e.proto.name}`,actual:e=>e instanceof Date&&e.toString()===`Invalid Date`?`an invalid Date`:Se(e)},intersections:{proto:(e,t)=>e.proto===Date&&t.proto===Date?e.dateAllowsInvalid?t:e:Oe(e.proto,t.proto)?e:Oe(t.proto,e.proto)?t:I.init(`proto`,e,t),domain:(e,t)=>t.domain===`object`?e:I.init(`domain`,T.intrinsic.object.internal,t)}}),Node:class extends Xr{builtinName=De(this.proto);serializedConstructor=this.json.proto;requiresInvalidDateCheck=this.proto===Date&&!this.dateAllowsInvalid;traverseAllows=this.requiresInvalidDateCheck?e=>e instanceof Date&&e.toString()!==`Invalid Date`:e=>e instanceof this.proto;compiledCondition=`data instanceof ${this.serializedConstructor}${this.requiresInvalidDateCheck?` && data.toString() !== "Invalid Date"`:``}`;compiledNegation=`!(${this.compiledCondition})`;innerToJsonSchema(e){switch(this.builtinName){case`Array`:return{type:`array`};case`Date`:return e.fallback.date?.({code:`date`,base:{}})??e.fallback.proto({code:`proto`,base:{},proto:this.proto});default:return e.fallback.proto({code:`proto`,base:{},proto:this.proto})}}expression=this.dateAllowsInvalid?`Date | InvalidDate`:this.proto.name;get nestableExpression(){return this.dateAllowsInvalid?`(${this.expression})`:this.expression}domain=`object`;get defaultShortDescription(){return this.description}},writeBadInvalidDateMessage:e=>`dateAllowsInvalid may only be specified with constructor Date (was ${e.name})`,writeInvalidSchemaMessage:e=>`instanceOf operand must be a function (was ${f(e)})`},ii=M({kind:`union`,hasAssociatedError:!0,collapsibleKey:`branches`,keys:{ordered:{},branches:{child:!0,parse:(e,t)=>{let n=[];for(let r of e){let e=k(r,`root`)?r.branches:t.$.parseSchema(r).branches;for(let r of e)if(r.hasKind(`morph`)){let e=n.findIndex(e=>e.hasKind(`morph`)&&e.hasEqualMorphs(r));if(e===-1)n.push(r);else{let i=n[e];n[e]=t.$.node(`morph`,{...i.inner,in:i.rawIn.rawOr(r.rawIn)})}}else n.push(r)}return t.def.ordered||n.sort((e,t)=>e.hash<t.hash?-1:1),n}}},normalize:e=>b(e)?{branches:e}:e,reduce:(e,t)=>{let n=vi(e);if(n.length===1)return n[0];if(n.length!==e.branches.length)return t.node(`union`,{...e,branches:n},{prereduced:!0})},defaults:{description:e=>e.distribute(e=>e.description,W),expected:e=>{let t=l(e.errors,`propString`);return W(Object.entries(t).map(([e,t])=>{let n=[];for(let e of t)c(n,e.expected);let r=W(n),i=t.every(e=>e.actual===t[0].actual)?t[0].actual:w(t[0].data);return`${e&&`${e} `}must be ${r}${i&&` (was ${i})`}`}))},problem:e=>e.expected,message:e=>e.problem[0]===`[`?`value at ${e.problem}`:e.problem},intersections:{union:(e,t,n)=>{if(e.isNever!==t.isNever)return I.init(`presence`,e,t);let r;return e.ordered?(t.ordered&&h(Si(e.expression,t.expression)),r=_i(t.branches,e.branches,n),r instanceof I&&r.invert()):r=_i(e.branches,t.branches,n),r instanceof I?r:n.$.parseSchema(e.ordered||t.ordered?{branches:r,ordered:!0}:{branches:r})},...Ur(`union`,(e,t,n)=>{let r=_i(e.branches,[t],n);return r instanceof I?r:r.length===1?r[0]:n.$.parseSchema(e.ordered?{branches:r,ordered:!0}:{branches:r})})}}),ai=class extends Pr{isBoolean=this.branches.length===2&&this.branches[0].hasUnit(!1)&&this.branches[1].hasUnit(!0);get branchGroups(){let e=[],t=-1;for(let n of this.branches)n.hasKind(`unit`)&&n.domain===`boolean`?t===-1?(t=e.length,e.push(n)):e[t]=T.intrinsic.boolean:e.push(n);return e}unitBranches=this.branches.filter(e=>e.rawIn.hasKind(`unit`));discriminant=this.discriminate();discriminantJson=this.discriminant?mi(this.discriminant):null;expression=this.distribute(e=>e.nestableExpression,gi);createBranchedOptimisticRootApply(){return(e,t)=>{let n=this.traverseOptimistic(e);if(n!==y)return n;let r=new pn(e,this.$.resolvedConfig);return this.traverseApply(e,r),r.finalize(t)}}get shallowMorphs(){return this.branches.reduce((e,t)=>c(e,t.shallowMorphs),[])}get defaultShortDescription(){return this.distribute(e=>e.defaultShortDescription,W)}innerToJsonSchema(e){if(this.branchGroups.length===1&&this.branchGroups[0].equals(T.intrinsic.boolean))return{type:`boolean`};let t=this.branchGroups.map(t=>t.toJsonSchemaRecurse(e));return t.every(e=>Object.keys(e).length===1&&ae(e,`const`))?{enum:t.map(e=>e.const)}:{anyOf:t}}traverseAllows=(e,t)=>this.branches.some(n=>n.traverseAllows(e,t));traverseApply=(e,t)=>{let n=[];for(let r=0;r<this.branches.length;r++){if(t.pushBranch(),this.branches[r].traverseApply(e,t),!t.hasError())return this.branches[r].includesTransform?t.queuedMorphs.push(...t.popBranch().queuedMorphs):t.popBranch();n.push(t.popBranch().error)}t.errorFromNodeContext({code:`union`,errors:n,meta:this.meta})};traverseOptimistic=e=>{for(let t=0;t<this.branches.length;t++){let n=this.branches[t];if(n.traverseAllows(e))return n.contextFreeMorph?n.contextFreeMorph(e):e}return y};compile(e){if(!this.discriminant||this.unitBranches.length===this.branches.length&&this.branches.length===2)return this.compileIndiscriminable(e);let t=this.discriminant.optionallyChainedPropString;this.discriminant.kind===`domain`&&(t=`typeof ${t} === "object" ? ${t} === null ? "null" : "object" : typeof ${t} === "function" ? "object" : typeof ${t}`);let n=this.discriminant.cases,r=Object.keys(n),{optimistic:i}=e;if(e.optimistic=!1,e.block(`switch(${t})`,()=>{for(let t in n){let r=n[t],a=t==="default"?t:`case ${t}`,o;o=r===!0?i?`data`:`true`:i?r.rootApplyStrategy===`branchedOptimistic`?e.invoke(r,{kind:`Optimistic`}):r.contextFreeMorph?`${e.invoke(r)} ? ${E(r.contextFreeMorph)}(data) : "${y}"`:`${e.invoke(r)} ? data : "${y}"`:e.invoke(r),e.line(`${a}: return ${o}`)}return e}),e.traversalKind===`Allows`){e.return(i?`"${y}"`:!1);return}let a=W(this.discriminant.kind===`domain`?r.map(e=>{let t=e.slice(1,-1);return t===`function`?p.object:p[t]}):r),o=this.discriminant.path.map(e=>typeof e==`symbol`?E(e):JSON.stringify(e)),s=JSON.stringify(a),c=this.discriminant.kind===`domain`?`${di}[${t}]`:`${fi}(${t})`;e.line(`ctx.errorFromNodeContext({
23
+ code: "predicate",
24
+ expected: ${s},
25
+ actual: ${c},
26
+ relativePath: [${o}],
27
+ meta: ${this.compiledMeta}
28
+ })`)}compileIndiscriminable(e){if(e.traversalKind===`Apply`){e.const(`errors`,`[]`);for(let t of this.branches)e.line(`ctx.pushBranch()`).line(e.invoke(t)).if(`!ctx.hasError()`,()=>e.return(t.includesTransform?`ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)`:`ctx.popBranch()`)).line(`errors.push(ctx.popBranch().error)`);e.line(`ctx.errorFromNodeContext({ code: "union", errors, meta: ${this.compiledMeta} })`)}else{let{optimistic:t}=e;e.optimistic=!1;for(let n of this.branches)e.if(`${e.invoke(n)}`,()=>e.return(t?n.contextFreeMorph?`${E(n.contextFreeMorph)}(data)`:`data`:!0));e.return(t?`"${y}"`:!1)}}get nestableExpression(){return this.isBoolean?`boolean`:`(${this.expression})`}discriminate(){if(this.branches.length<2||this.isCyclic)return null;if(this.unitBranches.length===this.branches.length)return{kind:`unit`,path:[],optionallyChainedPropString:`data`,cases:_(this.unitBranches,(e,t)=>[`${t.rawIn.serializedValue}`,!t.hasKind(`morph`)||t])};let e=[];for(let t=0;t<this.branches.length-1;t++){let n=this.branches[t];for(let r=t+1;r<this.branches.length;r++){let i=this.branches[r],a=L(n.rawIn,i.rawIn,n.$);if(a instanceof I)for(let n of a){if(!n.kind||n.optional)continue;let i,a;if(n.kind===`domain`){let e=n.l,t=n.r;i=`"${typeof e==`string`?e:e.domain}"`,a=`"${typeof t==`string`?t:t.domain}"`}else if(n.kind===`unit`)i=n.l.serializedValue,a=n.r.serializedValue;else continue;let o=e.find(e=>u(e.path,n.path)&&e.kind===n.kind);o?(o.cases[i]?o.cases[i].branchIndices=c(o.cases[i].branchIndices,t):o.cases[i]??={branchIndices:[t],condition:n.l},o.cases[a]?o.cases[a].branchIndices=c(o.cases[a].branchIndices,r):o.cases[a]??={branchIndices:[r],condition:n.r}):e.push({kind:n.kind,cases:{[i]:{branchIndices:[t],condition:n.l},[a]:{branchIndices:[r],condition:n.r}},path:n.path})}}}let t=this.ordered?ci(e,this.branches):e;if(!t.length)return null;let n=oi(t,this),r={};for(let e in n.best.cases){let t=si(n,e);if(t===null){r[e]=!0;continue}if(t.length===this.branches.length)return null;this.ordered&&t.sort((e,t)=>e.originalIndex-t.originalIndex);let i=t.map(e=>e.branch),a=i.length===1?i[0]:this.$.node(`union`,this.ordered?{branches:i,ordered:!0}:i);Object.assign(this.referencesById,a.referencesById),r[e]=a}if(n.defaultEntries.length){let e=n.defaultEntries.map(e=>e.branch);r.default=this.$.node(`union`,this.ordered?{branches:e,ordered:!0}:e,{prereduced:!0}),Object.assign(this.referencesById,r.default.referencesById)}return Object.assign(n.location,{cases:r})}},oi=(e,t)=>{let n=e.sort((e,t)=>e.path.length===t.path.length?Object.keys(t.cases).length-Object.keys(e.cases).length:e.path.length-t.path.length)[0];return{best:n,location:{kind:n.kind,path:n.path,optionallyChainedPropString:ui(n.path)},defaultEntries:t.branches.map((e,t)=>({originalIndex:t,branch:e})),node:t}},si=(e,t)=>{let n=e.best.cases[t],r=li(n.condition,e.location.path,e.node.$),i=[],a=[];for(let t=0;t<e.defaultEntries.length;t++){let o=e.defaultEntries[t];if(n.branchIndices.includes(o.originalIndex)){let t=bi(e.node.branches[o.originalIndex],e.location);t===null?i=null:i?.push({originalIndex:o.originalIndex,branch:t})}else if(o.branch.hasKind(`alias`)&&r.hasKind(`domain`)&&r.domain===`object`)i?.push(o);else{if(o.branch.rawIn.overlaps(r)){let t=bi(o.branch,e.location);i?.push({originalIndex:o.originalIndex,branch:t})}a.push(o)}}return e.defaultEntries=a,i},ci=(e,t)=>e.filter(e=>{let n=Object.values(e.cases).map(e=>e.branchIndices);for(let e=0;e<n.length-1;e++){let r=n[e];for(let i=e+1;i<n.length;i++){let e=n[i];for(let n of r)for(let r of e)if(n>r&&t[n].overlaps(t[r]))return!1}}return!0}),li=(e,t,n)=>{let r=e===`undefined`?n.node(`unit`,{unit:void 0}):e===`null`?n.node(`unit`,{unit:null}):e===`boolean`?n.units([!0,!1]):e;for(let e=t.length-1;e>=0;e--){let a=t[e];r=n.node(`intersection`,typeof a==`number`?{proto:`Array`,sequence:[...i(a).map(e=>({})),r]}:{domain:`object`,required:[{key:a,value:r}]})}return r},ui=e=>e.reduce((e,t)=>e+Lt(t,!0),`data`),di=E(ee),fi=E(w),pi={implementation:ii,Node:ai},mi=e=>({kind:e.kind,path:e.path.map(e=>typeof e==`string`?e:D(e)),cases:_(e.cases,(e,t)=>[e,t===!0?t:t.hasKind(`union`)&&t.discriminantJson?t.discriminantJson:t.json])}),hi={delimiter:` | `,finalDelimiter:` | `},gi=e=>W(e,hi),W=(e,t)=>{let n=t?.delimiter??`, `,r=t?.finalDelimiter??` or `;if(e.length===0)return`never`;if(e.length===1)return e[0];if(e.length===2&&e[0]===`false`&&e[1]===`true`||e[0]===`true`&&e[1]===`false`)return`boolean`;let i={},a=e.filter(e=>i[e]?!1:i[e]=!0),o=a.pop();return`${a.join(n)}${a.length?r:``}${o}`},_i=(e,t,n)=>{let r=t.map(()=>[]);for(let i=0;i<e.length;i++){let a={};for(let o=0;o<t.length;o++){if(r[o]===null)continue;if(e[i].equals(t[o])){r[o]=null,a={};break}let s=R(e[i],t[o],n);if(!(s instanceof I)){if(s.equals(e[i])){r[o].push(e[i]),a={};break}s.equals(t[o])?r[o]=null:a[o]=s}}for(let e in a)r[e][i]=a[e]}let i=r.flatMap((e,n)=>e?.flatMap(e=>e.branches)??t[n]);return i.length===0?I.init(`union`,e,t):i},vi=({branches:e,ordered:t})=>{if(e.length<2)return e;let n=e.map(()=>!0);for(let r=0;r<e.length;r++)for(let i=r+1;i<e.length&&n[r]&&n[i];i++){if(e[r].equals(e[i])){n[i]=!1;continue}let a=L(e[r].rawIn,e[i].rawIn,e[0].$);a instanceof I||(t||yi(e[r],e[i]),a.equals(e[r].rawIn)?n[r]=!!t:a.equals(e[i].rawIn)&&(n[i]=!1))}return e.filter((e,t)=>n[t])},yi=(e,t)=>{(e.includesTransform||t.includesTransform)&&(u(e.shallowMorphs,t.shallowMorphs)||h(xi(e.expression,t.expression)),u(e.flatMorphs,t.flatMorphs,{isEqual:(e,t)=>e.propString===t.propString&&(e.node.hasKind(`morph`)&&t.node.hasKind(`morph`)?e.node.hasEqualMorphs(t.node):e.node.hasKind(`intersection`)&&t.node.hasKind(`intersection`)?e.node.structure?.structuralMorphRef===t.node.structure?.structuralMorphRef:!1)})||h(xi(e.expression,t.expression)))},bi=(e,t)=>e.transform((e,t)=>e===`domain`||e===`unit`?null:t,{shouldTransform:(e,n)=>{let r=ui(n.path);return t.optionallyChainedPropString.startsWith(r)?e.hasKind(`domain`)&&e.domain===`object`||(e.hasKind(`domain`)||t.kind===`unit`)&&r===t.optionallyChainedPropString?!0:e.children.length!==0&&e.kind!==`index`:!1}}),xi=(e,t)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:
29
+ Left: ${e}
30
+ Right: ${t}`,Si=(e,t)=>`The intersection of two ordered unions is indeterminate:
31
+ Left: ${e}
32
+ Right: ${t}`,Ci={implementation:M({kind:`unit`,hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:e=>e instanceof Date?e.toISOString():j(e)}},normalize:e=>e,defaults:{description:e=>w(e.unit),problem:({expected:e,actual:t})=>`${e===t?`must be reference equal to ${e} (serialized to the same value)`:`must be ${e} (was ${t})`}`},intersections:{unit:(e,t)=>I.init(`unit`,e,t),...Ur(`unit`,(e,t)=>{if(t.allows(e.unit))return e;let n=t.hasKind(`intersection`)?t.basis:t;if(n){let t=n.hasKind(`domain`)?n:T.intrinsic.object;if(e.domain!==t.domain){let n=e.domain===`undefined`||e.domain===`null`||e.domain===`boolean`?e.domain:T.intrinsic[e.domain];return I.init(`domain`,n,t)}}return I.init(`assignability`,e,t.hasKind(`intersection`)?t.children.find(t=>!t.allows(e.unit)):t)})}}),Node:class extends Xr{compiledValue=this.json.unit;serializedValue=typeof this.unit==`string`||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=wi(this.unit,this.serializedValue);compiledNegation=wi(this.unit,this.serializedValue,`negated`);expression=w(this.unit);domain=f(this.unit);get defaultShortDescription(){return this.domain===`object`?p.object:this.description}innerToJsonSchema(e){return this.unit===null?{type:`null`}:T.intrinsic.jsonPrimitive.allows(this.unit)?{const:this.unit}:e.fallback.unit({code:`unit`,base:{},unit:this.unit})}traverseAllows=this.unit instanceof Date?e=>e instanceof Date&&e.toISOString()===this.compiledValue:Number.isNaN(this.unit)?e=>Number.isNaN(e):e=>e===this.unit}},wi=(e,t,n)=>{if(e instanceof Date){let e=`data instanceof Date && data.toISOString() === ${t}`;return n?`!(${e})`:e}return Number.isNaN(e)?`${n?`!`:``}Number.isNaN(data)`:`data ${n?`!`:`=`}== ${t}`},Ti={implementation:M({kind:`index`,hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(e,t)=>{let n=t.$.parseSchema(e);if(!n.extends(T.intrinsic.key))return h(Di(n.expression));let r=n.branches.filter(e=>e.hasKind(`unit`));return r.length?h(Ei(r.map(e=>w(e.unit)))):n}},value:{child:!0,parse:(e,t)=>t.$.parseSchema(e)}},normalize:e=>e,defaults:{description:e=>`[${e.signature.expression}]: ${e.value.description}`},intersections:{index:(e,t,n)=>{if(e.signature.equals(t.signature)){let r=R(e.value,t.value,n),i=r instanceof I?T.intrinsic.never.internal:r;return n.$.node(`index`,{signature:e.signature,value:i})}return e.signature.extends(t.signature)&&e.value.subsumes(t.value)?t:t.signature.extends(e.signature)&&t.value.subsumes(e.value)?e:null}}}),Node:class extends z{impliedBasis=T.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=a(this.value.flatRefs.map(e=>F([this.signature,...e.path],e.node)),F([this.signature],this.value));traverseAllows=(e,t)=>fe(e).every(e=>!this.signature.traverseAllows(e[0],t)||P(e[0],()=>this.value.traverseAllows(e[1],t),t));traverseApply=(e,t)=>{for(let n of fe(e))this.signature.traverseAllows(n[0],t)&&P(n[0],()=>this.value.traverseApply(n[1],t),t)};_transform(e,t){t.path.push(this.signature);let n=super._transform(e,t);return t.path.pop(),n}compile(){}}},Ei=e=>`Index keys ${e.join(`, `)} should be specified as named props.`,Di=e=>`Indexed key definition '${e}' must be a string or symbol`,Oi={implementation:M({kind:`required`,hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(e,t)=>t.$.parseSchema(e)}},normalize:e=>e,defaults:{description:e=>`${e.compiledKey}: ${e.value.description}`,expected:e=>e.missingValueDescription,actual:()=>`missing`},intersections:{required:Tr,optional:Tr}}),Node:class extends Er{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:`required`,missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=tn(this.errorContext)}},ki=M({kind:`sequence`,hasAssociatedError:!1,collapsibleKey:`variadic`,keys:{prefix:{child:!0,parse:(e,t)=>{if(e.length!==0)return e.map(e=>t.$.parseSchema(e))}},optionals:{child:!0,parse:(e,t)=>{if(e.length!==0)return e.map(e=>t.$.parseSchema(e))}},defaultables:{child:e=>e.map(e=>e[0]),parse:(e,t)=>{if(e.length!==0)return e.map(e=>{let n=t.$.parseSchema(e[0]);return Mr(n,e[1],null),[n,e[1]]})},serialize:e=>e.map(e=>[e[0].collapsibleJson,j(e[1])]),reduceIo:(e,t,n)=>{e===`in`?t.optionals=n.map(e=>e[0].rawIn):t.prefix=n.map(e=>e[0].rawOut)}},variadic:{child:!0,parse:(e,t)=>t.$.parseSchema(e,t)},minVariadicLength:{parse:e=>e===0?void 0:e},postfix:{child:!0,parse:(e,t)=>{if(e.length!==0)return e.map(e=>t.$.parseSchema(e))}}},normalize:e=>{if(typeof e==`string`)return{variadic:e};if(`variadic`in e||`prefix`in e||`defaultables`in e||`optionals`in e||`postfix`in e||`minVariadicLength`in e){if(e.postfix?.length){if(!e.variadic)return h(Li);if(e.optionals?.length||e.defaultables?.length)return h(Ii)}return e.minVariadicLength&&!e.variadic?h(`minVariadicLength may not be specified without a variadic element`):e}return{variadic:e}},reduce:(e,t)=>{let n=e.minVariadicLength??0,r=e.prefix?.slice()??[],i=e.defaultables?.slice()??[],a=e.optionals?.slice()??[],o=e.postfix?.slice()??[];if(e.variadic){for(;a[a.length-1]?.equals(e.variadic);)a.pop();if(a.length===0&&i.length===0)for(;r[r.length-1]?.equals(e.variadic);)r.pop(),n++;for(;o[0]?.equals(e.variadic);)o.shift(),n++}else a.length===0&&i.length===0&&r.push(...o.splice(0));if(n!==e.minVariadicLength||e.prefix&&e.prefix.length!==r.length)return t.node(`sequence`,{...e,prefix:r,defaultables:i,optionals:a,postfix:o,minVariadicLength:n},{prereduced:!0})},defaults:{description:e=>e.isVariadicOnly?`${e.variadic.nestableExpression}[]`:`[${e.tuple.map(e=>e.kind===`defaultables`?`${e.node.nestableExpression} = ${w(e.default)}`:e.kind===`optionals`?`${e.node.nestableExpression}?`:e.kind===`variadic`?`...${e.node.nestableExpression}[]`:e.node.expression).join(`, `)}]`},intersections:{sequence:(e,t,n)=>{let r=Ri({l:e.tuple,r:t.tuple,disjoint:new I,result:[],fixedVariants:[],ctx:n}),i=r.disjoint.length===0?[r,...r.fixedVariants]:r.fixedVariants;return i.length===0?r.disjoint:i.length===1?n.$.node(`sequence`,Fi(i[0].result)):n.$.node(`union`,i.map(e=>({proto:Array,sequence:Fi(e.result)})))}}}),Ai=class extends z{impliedBasis=T.intrinsic.Array.internal;tuple=Pi(this.inner);prefixLength=this.prefix?.length??0;defaultablesLength=this.defaultables?.length??0;optionalsLength=this.optionals?.length??0;postfixLength=this.postfix?.length??0;defaultablesAndOptionals=[];prevariadic=this.tuple.filter(e=>e.kind===`defaultables`||e.kind===`optionals`?(this.defaultablesAndOptionals.push(e.node),!0):e.kind===`prefix`);variadicOrPostfix=o(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return xn(this.flatRefs,this.prevariadic.flatMap((e,t)=>a(e.node.flatRefs.map(e=>F([`${t}`,...e.path],e.node)),F([`${t}`],e.node)))),xn(this.flatRefs,this.variadicOrPostfix.flatMap(e=>a(e.flatRefs.map(e=>F([T.intrinsic.nonNegativeIntegerString.internal,...e.path],e.node)),F([T.intrinsic.nonNegativeIntegerString.internal],e)))),this.flatRefs}isVariadicOnly=this.prevariadic.length+this.postfixLength===0;minVariadicLength=this.inner.minVariadicLength??0;minLength=this.prefixLength+this.minVariadicLength+this.postfixLength;minLengthNode=this.minLength===0?null:this.$.node(`minLength`,this.minLength);maxLength=this.variadic?null:this.tuple.length;maxLengthNode=this.maxLength===null?null:this.$.node(`maxLength`,this.maxLength);impliedSiblings=this.minLengthNode?this.maxLengthNode?[this.minLengthNode,this.maxLengthNode]:[this.minLengthNode]:this.maxLengthNode?[this.maxLengthNode]:[];defaultValueMorphs=Mi(this);defaultValueMorphsReference=this.defaultValueMorphs.length?E(this.defaultValueMorphs):void 0;elementAtIndex(e,t){if(t<this.prevariadic.length)return this.tuple[t];let n=e.length-this.postfixLength;return t>=n?{kind:`postfix`,node:this.postfix[t-n]}:{kind:`variadic`,node:this.variadic??m(`Unexpected attempt to access index ${t} on ${this}`)}}traverseAllows=(e,t)=>{for(let n=0;n<e.length;n++)if(!this.elementAtIndex(e,n).node.traverseAllows(e[n],t))return!1;return!0};traverseApply=(e,t)=>{let n=0;for(;n<e.length;n++)P(n,()=>this.elementAtIndex(e,n).node.traverseApply(e[n],t),t)};get element(){return this.cacheGetter(`element`,this.$.node(`union`,this.children))}compile(e){if(this.prefix)for(let[t,n]of this.prefix.entries())e.traverseKey(`${t}`,`data[${t}]`,n);for(let[t,n]of this.defaultablesAndOptionals.entries()){let r=`${t+this.prefixLength}`;e.if(`${r} >= data.length`,()=>e.traversalKind===`Allows`?e.return(!0):e.return()),e.traverseKey(r,`data[${r}]`,n)}if(this.variadic&&(this.postfix&&e.const(`firstPostfixIndex`,`data.length${this.postfix?`- ${this.postfix.length}`:``}`),e.for(`i < ${this.postfix?`firstPostfixIndex`:`data.length`}`,()=>e.traverseKey(`i`,`data[i]`,this.variadic),this.prevariadic.length),this.postfix))for(let[t,n]of this.postfix.entries()){let r=`firstPostfixIndex + ${t}`;e.traverseKey(r,`data[${r}]`,n)}e.traversalKind===`Allows`&&e.return(!0)}_transform(e,t){t.path.push(T.intrinsic.nonNegativeIntegerString.internal);let n=super._transform(e,t);return t.path.pop(),n}expression=this.description;reduceJsonSchema(e,t){let n=t.target===`draft-07`;if(this.prevariadic.length){let r=this.prevariadic.map(e=>{let n=e.node.toJsonSchemaRecurse(t);if(e.kind===`defaultables`){let r=typeof e.default==`function`?e.default():e.default;n.default=T.intrinsic.jsonData.allows(r)?r:t.fallback.defaultValue({code:`defaultValue`,base:n,value:r})}return n});n?e.items=r:e.prefixItems=r}if(this.minLength&&(e.minItems=this.minLength),this.variadic){let r=this.variadic.toJsonSchemaRecurse(t);if(n&&this.prevariadic.length?e.additionalItems=r:e.items=r,this.maxLength&&(e.maxItems=this.maxLength),this.postfix){let n=this.postfix.map(e=>e.toJsonSchemaRecurse(t));e=t.fallback.arrayPostfix({code:`arrayPostfix`,base:e,elements:n})}}else n?e.additionalItems=!1:e.items=!1,delete e.maxItems;return e}},ji={},Mi=e=>{if(!e.defaultables)return[];let t=[],n=`[`,r=e.prefixLength+e.defaultablesLength-1;for(let i=e.prefixLength;i<=r;i++){let[r,a]=e.defaultables[i-e.prefixLength];t.push(jr(i,r,a)),n+=`${i}: ${r.id} = ${j(a)}, `}return n+=`]`,ji[n]??=t},Ni={implementation:ki,Node:Ai},Pi=e=>{let t=[];if(e.prefix)for(let n of e.prefix)t.push({kind:`prefix`,node:n});if(e.defaultables)for(let[n,r]of e.defaultables)t.push({kind:`defaultables`,node:n,default:r});if(e.optionals)for(let n of e.optionals)t.push({kind:`optionals`,node:n});if(e.variadic&&t.push({kind:`variadic`,node:e.variadic}),e.postfix)for(let n of e.postfix)t.push({kind:`postfix`,node:n});return t},Fi=e=>e.reduce((e,t)=>(t.kind===`variadic`?e.variadic=t.node:t.kind===`defaultables`?e.defaultables=a(e.defaultables,[[t.node,t.default]]):e[t.kind]=a(e[t.kind],t.node),e),{}),Ii=`A postfix required element cannot follow an optional or defaultable element`,Li=`A postfix element requires a variadic element`,Ri=e=>{let[t,...n]=e.l,[r,...i]=e.r;if(!t||!r)return e;let a=n[n.length-1]?.kind===`postfix`,o=i[i.length-1]?.kind===`postfix`,s=t.kind===`prefix`||r.kind===`prefix`?`prefix`:t.kind===`postfix`||r.kind===`postfix`?`postfix`:t.kind===`variadic`&&r.kind===`variadic`?`variadic`:a||o?`prefix`:t.kind===`defaultables`||r.kind===`defaultables`?`defaultables`:`optionals`;if(t.kind===`prefix`&&r.kind===`variadic`&&o){let t=Ri({...e,fixedVariants:[],r:i.map(e=>({...e,kind:`prefix`}))});t.disjoint.length===0&&e.fixedVariants.push(t)}else if(r.kind===`prefix`&&t.kind===`variadic`&&a){let t=Ri({...e,fixedVariants:[],l:n.map(e=>({...e,kind:`prefix`}))});t.disjoint.length===0&&e.fixedVariants.push(t)}let c=R(t.node,r.node,e.ctx);if(c instanceof I){if(s===`prefix`||s===`postfix`)e.disjoint.push(...c.withPrefixKey(s===`prefix`?e.result.length:`-${n.length+1}`,zi(t)&&zi(r)?`required`:`optional`)),e.result=[...e.result,{kind:s,node:T.intrinsic.never.internal}];else if(s===`optionals`||s===`defaultables`)return e;else return Ri({...e,fixedVariants:[],l:n.map(e=>({...e,kind:`prefix`})),r:n.map(e=>({...e,kind:`prefix`}))})}else s===`defaultables`?(t.kind===`defaultables`&&r.kind===`defaultables`&&t.default!==r.default&&h(Dr(t.default,r.default)),e.result=[...e.result,{kind:s,node:c,default:t.kind===`defaultables`?t.default:r.kind===`defaultables`?r.default:m(`Unexpected defaultable intersection from ${t.kind} and ${r.kind} elements.`)}]):e.result=[...e.result,{kind:s,node:c}];let l=e.l.length,u=e.r.length;return(t.kind!==`variadic`||l>=u&&(r.kind===`variadic`||u===1))&&(e.l=n),(r.kind!==`variadic`||u>=l&&(t.kind===`variadic`||l===1))&&(e.r=i),Ri(e)},zi=e=>e.kind===`prefix`||e.kind===`postfix`,Bi=e=>t=>{if(t.props.length||t.index){let n=t.index?.map(t=>t[e])??[];for(let r of t.props)n.push(r[e]);t.undeclared&&n.push(`+ (undeclared): ${t.undeclared}`);let r=`{ ${n.join(`, `)} }`;return t.sequence?`${r} & ${t.sequence.description}`:r}return t.sequence?.description??`{}`},Vi=Bi(`description`),Hi=Bi(`expression`),Ui=(e,t,n)=>{let r=e.required?`required`:`optional`;if(!t.signature.allows(e.key))return null;let i=L(e.value,t.value,n);return i instanceof I?r===`optional`?n.node(`optional`,{key:e.key,value:T.intrinsic.never.internal}):i.withPrefixKey(e.key,e.kind):null},Wi=M({kind:`structure`,hasAssociatedError:!1,normalize:e=>e,applyConfig:(e,t)=>!e.undeclared&&t.onUndeclaredKey!==`ignore`?{...e,undeclared:t.onUndeclaredKey}:e,keys:{required:{child:!0,parse:B(`required`),reduceIo:(e,t,n)=>{t.required=a(t.required,n.map(t=>e===`in`?t.rawIn:t.rawOut))}},optional:{child:!0,parse:B(`optional`),reduceIo:(e,t,n)=>{if(e===`in`)t.optional=n.map(e=>e.rawIn);else for(let e of n)t[e.outProp.kind]=a(t[e.outProp.kind],e.outProp.rawOut)}},index:{child:!0,parse:B(`index`)},sequence:{child:!0,parse:B(`sequence`)},undeclared:{parse:e=>e===`ignore`?void 0:e,reduceIo:(e,t,n)=>{n===`reject`?t.undeclared=`reject`:e===`in`?delete t.undeclared:t.undeclared=`reject`}}},defaults:{description:Vi},intersections:{structure:(e,t,n)=>{let r={...e.inner},i={...t.inner},a=new I;if(e.undeclared){let r=e.keyof();for(let e of t.requiredKeys)r.allows(e)||a.add(`presence`,T.intrinsic.never.internal,t.propsByKey[e].value,{path:[e]});i.optional&&=i.optional.filter(e=>r.allows(e.key)),i.index&&=i.index.flatMap(e=>{if(e.signature.extends(r))return e;let t=L(r,e.signature,n.$);if(t instanceof I)return[];let a=$i(t,e.value,n.$);return a.required&&(i.required=o(i.required,a.required)),a.optional&&(i.optional=o(i.optional,a.optional)),a.index??[]})}if(t.undeclared){let i=t.keyof();for(let t of e.requiredKeys)i.allows(t)||a.add(`presence`,e.propsByKey[t].value,T.intrinsic.never.internal,{path:[t]});r.optional&&=r.optional.filter(e=>i.allows(e.key)),r.index&&=r.index.flatMap(e=>{if(e.signature.extends(i))return e;let t=L(i,e.signature,n.$);if(t instanceof I)return[];let a=$i(t,e.value,n.$);return a.required&&(r.required=o(r.required,a.required)),a.optional&&(r.optional=o(r.optional,a.optional)),a.index??[]})}let s={};(e.undeclared||t.undeclared)&&(s.undeclared=e.undeclared===`reject`||t.undeclared===`reject`?`reject`:`delete`);let c=Nn({kind:`structure`,baseInner:s,l:Pn(r),r:Pn(i),roots:[],ctx:n});return c instanceof I&&a.push(...c),a.length?a:c}},reduce:(e,t)=>{if(!e.required&&!e.optional)return;let n={},r=!1,i=e.optional?[...e.optional]:[];if(e.required)for(let r=0;r<e.required.length;r++){let i=e.required[r];if(i.key in n&&h(na(i.key)),n[i.key]=!0,e.index)for(let n of e.index){let e=Ui(i,n,t);if(e instanceof I)return e}}if(e.optional)for(let a=0;a<e.optional.length;a++){let o=e.optional[a];if(o.key in n&&h(na(o.key)),n[o.key]=!0,e.index)for(let n of e.index){let e=Ui(o,n,t);if(e instanceof I)return e;e!==null&&(i[a]=e,r=!0)}}if(r)return t.node(`structure`,{...e,optional:i},{prereduced:!0})}}),Gi=class extends z{impliedBasis=T.intrinsic.object.internal;impliedSiblings=this.children.flatMap(e=>e.impliedSiblings??[]);props=o(this.required,this.optional);propsByKey=_(this.props,(e,t)=>[t.key,t]);propsByKeyReference=E(this.propsByKey);expression=Hi(this);requiredKeys=this.required?.map(e=>e.key)??[];optionalKeys=this.optional?.map(e=>e.key)??[];literalKeys=[...this.requiredKeys,...this.optionalKeys];_keyof;keyof(){if(this._keyof)return this._keyof;let e=this.$.units(this.literalKeys).branches;if(this.index)for(let{signature:t}of this.index)e=e.concat(t.branches);return this._keyof=this.$.node(`union`,e)}map(e){return this.$.node(`structure`,this.props.flatMap(e).reduce((e,t)=>{let n=this.propsByKey[t.key];if(A(t))return t.kind!==`required`&&t.kind!==`optional`?h(`Map result must have kind "required" or "optional" (was ${t.kind})`):(e[t.kind]=a(e[t.kind],t),e);let r=t.kind??n?.kind??`required`,i=_(t,(e,t)=>e in Or.implementation.keys?[e,t]:[]);return e[r]=a(e[r],this.$.node(r,i)),e},{}))}assertHasKeys(e){let t=e.filter(e=>!zr(e,this.keyof()));if(t.length)return h(ta(this.expression,t))}get(e,...t){let n,r=!1,i=Zi(e);if((typeof i==`string`||typeof i==`symbol`)&&this.propsByKey[i]&&(n=this.propsByKey[i].value,r=this.propsByKey[i].required),this.index)for(let e of this.index)zr(i,e.signature)&&(n=n?.and(e.value)??e.value);if(this.sequence&&zr(i,T.intrinsic.nonNegativeIntegerString)){if(k(i,`root`))this.sequence.variadic&&(n=n?.and(this.sequence.element)??this.sequence.element);else{let e=Number.parseInt(i);if(e<this.sequence.prevariadic.length){let t=this.sequence.prevariadic[e].node;n=n?.and(t)??t,r||=e<this.sequence.prefixLength}else if(this.sequence.variadic){let e=this.$.node(`union`,this.sequence.variadicOrPostfix);n=n?.and(e)??e}}}if(!n)return this.sequence?.variadic&&k(i,`root`)&&i.extends(T.intrinsic.number)?h(Qi(i.expression,this.sequence.expression)):h(ta(this.expression,[i]));let a=n.get(...t);return r?a:a.or(T.intrinsic.undefined)}pick(...e){return this.assertHasKeys(e),this.$.node(`structure`,this.filterKeys(`pick`,e))}omit(...e){return this.assertHasKeys(e),this.$.node(`structure`,this.filterKeys(`omit`,e))}optionalize(){let{required:e,...t}=this.inner;return this.$.node(`structure`,{...t,optional:this.props.map(e=>e.hasKind(`required`)?this.$.node(`optional`,e.inner):e)})}require(){let{optional:e,...t}=this.inner;return this.$.node(`structure`,{...t,required:this.props.map(e=>e.hasKind(`optional`)?{key:e.key,value:e.value}:e)})}merge(e){let t=this.filterKeys(`omit`,[e.keyof()]);return e.required&&(t.required=a(t.required,e.required)),e.optional&&(t.optional=a(t.optional,e.optional)),e.index&&(t.index=a(t.index,e.index)),e.sequence&&(t.sequence=e.sequence),e.undeclared?t.undeclared=e.undeclared:delete t.undeclared,this.$.node(`structure`,t)}filterKeys(e,t){let n=Vt(this.inner),r=n=>{let r=t.some(e=>zr(n,e));return e===`pick`?r:!r};return n.required&&=n.required.filter(e=>r(e.key)),n.optional&&=n.optional.filter(e=>r(e.key)),n.index&&=n.index.filter(e=>r(e.signature)),n}traverseAllows=(e,t)=>this._traverse(`Allows`,e,t);traverseApply=(e,t)=>this._traverse(`Apply`,e,t);_traverse=(e,t,n)=>{let r=n?.currentErrorCount??0;for(let i=0;i<this.props.length;i++)if(e===`Allows`){if(!this.props[i].traverseAllows(t,n))return!1}else if(this.props[i].traverseApply(t,n),n.failFast&&n.currentErrorCount>r)return!1;if(this.sequence){if(e===`Allows`){if(!this.sequence.traverseAllows(t,n))return!1}else if(this.sequence.traverseApply(t,n),n.failFast&&n.currentErrorCount>r)return!1}if(this.index||this.undeclared===`reject`){let i=Object.keys(t);i.push(...Object.getOwnPropertySymbols(t));for(let a=0;a<i.length;a++){let o=i[a];if(this.index){for(let i of this.index)if(i.signature.traverseAllows(o,n)){if(e===`Allows`){if(!P(o,()=>i.value.traverseAllows(t[o],n),n))return!1}else if(P(o,()=>i.value.traverseApply(t[o],n),n),n.failFast&&n.currentErrorCount>r)return!1}}if(this.undeclared===`reject`&&!this.declaresKey(o)&&(e===`Allows`||(n.errorFromNodeContext({code:`predicate`,expected:`removed`,actual:``,relativePath:[o],meta:this.meta}),n.failFast)))return!1}}return this.structuralMorph&&n&&!n.hasError()&&n.queueMorphs([this.structuralMorph]),!0};get defaultable(){return this.cacheGetter(`defaultable`,this.optional?.filter(e=>e.hasDefault())??[])}declaresKey=e=>e in this.propsByKey||this.index?.some(t=>t.signature.allows(e))||this.sequence!==void 0&&T.intrinsic.nonNegativeIntegerString.allows(e);_compileDeclaresKey(e){let t=[];if(this.props.length&&t.push(`k in ${this.propsByKeyReference}`),this.index)for(let n of this.index)t.push(e.invoke(n.signature,{kind:`Allows`,arg:`k`}));return this.sequence&&t.push(`$ark.intrinsic.nonNegativeIntegerString.allows(k)`),t.join(` || `)||`false`}get structuralMorph(){return this.cacheGetter(`structuralMorph`,Ji(this))}structuralMorphRef=this.structuralMorph&&E(this.structuralMorph);compile(e){e.traversalKind===`Apply`&&e.initializeErrorCount();for(let t of this.props)e.check(t),e.traversalKind===`Apply`&&e.returnIfFailFast();if(this.sequence&&(e.check(this.sequence),e.traversalKind===`Apply`&&e.returnIfFailFast()),(this.index||this.undeclared===`reject`)&&(e.const(`keys`,`Object.keys(data)`),e.line(`keys.push(...Object.getOwnPropertySymbols(data))`),e.for(`i < keys.length`,()=>this.compileExhaustiveEntry(e))),e.traversalKind===`Allows`)return e.return(!0);this.structuralMorphRef&&e.if(`ctx && !ctx.hasError()`,()=>(e.line(`ctx.queueMorphs([`),Yi(e,this),e.line(`])`)))}compileExhaustiveEntry(e){if(e.const(`k`,`keys[i]`),this.index)for(let t of this.index)e.if(`${e.invoke(t.signature,{arg:`k`,kind:`Allows`})}`,()=>e.traverseKey(`k`,`data[k]`,t.value));return this.undeclared===`reject`&&e.if(`!(${this._compileDeclaresKey(e)})`,()=>e.traversalKind===`Allows`?e.return(!1):e.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if(`ctx.failFast`,()=>e.return())),e}reduceJsonSchema(e,t){switch(e.type){case`object`:return this.reduceObjectJsonSchema(e,t);case`array`:let n=this.sequence?.reduceJsonSchema(e,t)??e;return this.props.length||this.index?t.fallback.arrayObject({code:`arrayObject`,base:n,object:this.reduceObjectJsonSchema({type:`object`},t)}):n;default:return N.throwInternalOperandError(`structure`,e)}}reduceObjectJsonSchema(e,t){if(this.props.length){e.properties={};for(let n of this.props){let r=n.value.toJsonSchemaRecurse(t);if(typeof n.key==`symbol`)t.fallback.symbolKey({code:`symbolKey`,base:e,key:n.key,value:r,optional:n.optional});else{if(n.hasDefault()){let e=typeof n.default==`function`?n.default():n.default;r.default=T.intrinsic.jsonData.allows(e)?e:t.fallback.defaultValue({code:`defaultValue`,base:r,value:e})}e.properties[n.key]=r}}this.requiredKeys.length&&e.properties&&(e.required=this.requiredKeys.filter(t=>typeof t==`string`&&t in e.properties))}if(this.index)for(let n of this.index){let r=n.value.toJsonSchemaRecurse(t);if(n.signature.equals(T.intrinsic.string))e.additionalProperties=r;else for(let i of n.signature.branches){if(!i.extends(T.intrinsic.string)){e=t.fallback.symbolKey({code:`symbolKey`,base:e,key:null,value:r,optional:!1});continue}let n={type:`string`};if(i.hasKind(`morph`)&&(n=t.fallback.morph({code:`morph`,base:i.rawIn.toJsonSchemaRecurse(t),out:i.rawOut.toJsonSchemaRecurse(t)})),!i.hasKind(`intersection`))return m(`Unexpected index branch kind ${i.kind}.`);let{pattern:a}=i.inner;if(a){let i=Object.assign(n,{pattern:a[0].rule});for(let e=1;e<a.length;e++)n=t.fallback.patternIntersection({code:`patternIntersection`,base:i,pattern:a[e].rule});e.patternProperties??={},e.patternProperties[i.pattern]=r}}}return this.undeclared&&!e.additionalProperties&&(e.additionalProperties=!1),e}},Ki={},qi=e=>{let t=``;for(let n=0;n<e.defaultable.length;n++)t+=e.defaultable[n].defaultValueMorphRef;if(e.sequence?.defaultValueMorphsReference&&(t+=e.sequence?.defaultValueMorphsReference),e.undeclared===`delete`){if(t+=`delete !(`,e.required)for(let n of e.required)t+=n.compiledKey+` | `;if(e.optional)for(let n of e.optional)t+=n.compiledKey+` | `;if(e.index)for(let n of e.index)t+=n.signature.id+` | `;if(e.sequence){if(e.sequence.maxLength===null)t+=q.nonNegativeIntegerString.id;else for(let n=0;n<e.sequence.tuple.length;n++)t+=n+` | `}t+=`)`}return t},Ji=e=>{let t=qi(e);return t?Ki[t]?Ki[t]:Ki[t]=(t,n)=>{for(let r=0;r<e.defaultable.length;r++)e.defaultable[r].key in t||e.defaultable[r].defaultValueMorph(t,n);if(e.sequence?.defaultables)for(let r=t.length-e.sequence.prefixLength;r<e.sequence.defaultables.length;r++)e.sequence.defaultValueMorphs[r](t,n);if(e.undeclared===`delete`)for(let n in t)e.declaresKey(n)||delete t[n];return t}:void 0},Yi=(e,t)=>{let n=`(data${t.defaultable.some(e=>e.defaultValueMorph.length===2)||t.sequence?.defaultValueMorphs.some(e=>e.length===2)?`, ctx`:``})`;return e.block(`${n} => `,e=>{for(let r=0;r<t.defaultable.length;r++){let{serializedKey:i,defaultValueMorphRef:a}=t.defaultable[r];e.if(`!(${i} in data)`,e=>e.line(`${a}${n}`))}return t.sequence?.defaultables&&e.for(`i < ${t.sequence.defaultables.length}`,e=>e.set(`data[i]`,5),`data.length - ${t.sequence.prefixLength}`),t.undeclared===`delete`&&e.forIn(`data`,e=>e.if(`!(${t._compileDeclaresKey(e)})`,e=>e.line(`delete data[k]`))),e.return(`data`)})},Xi={implementation:Wi,Node:Gi},Zi=e=>(k(e,`root`)&&e.hasKind(`unit`)&&(e=e.unit),typeof e==`number`&&(e=`${e}`),e),Qi=(e,t)=>`${e} is not allowed as an array index on ${t}. Use the 'nonNegativeIntegerString' keyword instead.`,$i=(e,n,r)=>{let[i,o]=t(e.branches,e=>e.hasKind(`unit`));if(!i.length)return{index:r.node(`index`,{signature:e,value:n})};let s={};for(let e of i){let t=r.node(`required`,{key:e.unit,value:n});s[t.kind]=a(s[t.kind],t)}return o.length&&(s.index=r.node(`index`,{signature:o,value:n})),s},ea=e=>k(e,`root`)?e.expression:w(e),ta=(e,t)=>`Key${t.length===1?``:`s`} ${t.map(ea).join(`, `)} ${t.length===1?`does`:`do`} not exist on ${e}`,na=e=>`Duplicate key ${D(e)}`,ra={...dr,alias:Yr.implementation,domain:Zr.implementation,unit:Ci.implementation,proto:ri.implementation,union:pi.implementation,morph:ti.implementation,intersection:Qr.implementation,divisor:Un.implementation,pattern:pr.implementation,predicate:Hn.implementation,required:Oi.implementation,optional:Or.implementation,index:Ti.implementation,sequence:Ni.implementation,structure:Xi.implementation};T.defaultConfig=me(Object.assign(_(ra,(e,t)=>[e,t.defaults]),{jitless:Pe(),clone:ke,onUndeclaredKey:`ignore`,exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:N.defaultConfig})),T.resolvedConfig=nn(T.defaultConfig,T.config);var ia={...fr,alias:Yr.Node,domain:Zr.Node,unit:Ci.Node,proto:ri.Node,union:pi.Node,morph:ti.Node,intersection:Qr.Node,divisor:Un.Node,pattern:pr.Node,predicate:Hn.Node,required:Oi.Node,optional:Or.Node,index:Ti.Node,sequence:Ni.Node,structure:Xi.Node},aa=class extends oe{get[O](){return`module`}},oa=(e,t)=>new aa(_(e,(e,n)=>[e,k(n,`module`)?oa(n,t):t.bindReference(n)])),sa=e=>b(e)?e:`branches`in e&&b(e.branches)?e.branches:void 0,ca=(e,t)=>h(`Node of kind ${t} is not valid as a ${e} definition`),la=e=>`#${e} duplicates public alias ${e}`,ua={};T.ambient??={};var da,fa=`function $`,pa=e=>ma(e,ha(e)),ma=(e,t)=>{let n=t.write(fa,4),r=t.compile()();for(let t of e)t.precompilation||=(t.traverseAllows=r[`${t.id}Allows`].bind(r),t.isRoot()&&!t.allowsRequiresContext&&(t.allows=t.traverseAllows),t.traverseApply=r[`${t.id}Apply`].bind(r),r[`${t.id}Optimistic`]&&(t.traverseOptimistic=r[`${t.id}Optimistic`].bind(r)),n)},ha=e=>new It().return(e.reduce((e,t)=>{let n=new Bt({kind:`Allows`}).indent();t.compile(n);let r=n.write(`${t.id}Allows`),i=new Bt({kind:`Apply`}).indent();t.compile(i);let a=`${e}${r},\n${i.write(`${t.id}Apply`)},\n`;if(!t.hasKind(`union`))return a;let o=new Bt({kind:`Allows`,optimistic:!0}).indent();return t.compile(o),`${a}${o.write(`${t.id}Optimistic`)},\n`},`{
33
+ `)+`}`),ga=class{config;resolvedConfig;name;get[O](){return`scope`}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(e,t){this.config=nn(T.config,t),this.resolvedConfig=nn(T.resolvedConfig,t),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(ua).length}`,this.name in ua&&h(`A Scope already named ${this.name} already exists`),ua[this.name]=this;let n=Object.entries(e).map(e=>this.preparseOwnAliasEntry(...e));for(let[e,t]of n){let n=e;if(e[0]===`#`?(n=e.slice(1),n in this.aliases&&h(la(n)),this.aliases[n]=t):(n in this.aliases&&h(la(e)),this.aliases[n]=t,this.exportedNames.push(n)),!k(t,`module`)&&!k(t,`generic`)&&!Me(t)){let e=this.preparseOwnDefinitionFormat(t,{alias:n});this.resolutions[n]=k(e,`root`)?this.bindReference(e):this.createParseContext(e).id}}da??=this.node(`union`,{branches:[`string`,`number`,`object`,`bigint`,`symbol`,{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[da.hash]=this.node(`intersection`,{},{prereduced:!0}),this.intrinsic=T.intrinsic?_(T.intrinsic,(e,t)=>e.startsWith(`json`)?[]:[e,this.bindReference(t)]):{}}cacheGetter(e,t){return Object.defineProperty(this,e,{value:t}),t}get internal(){return this}_json;get json(){return this._json||this.export(),this._json}defineSchema(e){return e}generic=(...e)=>{let t=this;return(n,r)=>new Bn(e,r?new zn(n):n,t,t,r??null)};units=(e,t)=>{let n=[];for(let t of e)n.includes(t)||n.push(t);let r=n.map(e=>this.node(`unit`,{unit:e},t));return this.node(`union`,r,{...t,prereduced:!0})};lazyResolutions=[];lazilyResolve(e,t){let n=this.node(`alias`,{reference:t??`synthetic`,resolve:e},{prereduced:!0});return this.resolved||this.lazyResolutions.push(n),n}schema=(e,t)=>this.finalize(this.parseSchema(e,t));parseSchema=(e,t)=>this.node(mr(e),e,t);preparseNode(e,t,n){let r=typeof e==`string`?e:mr(t,e);if(A(t)&&t.kind===r)return t;if(r===`alias`&&!n?.prereduced){let{reference:e}=Yr.implementation.normalize(t,this);if(e.startsWith(`$`)){let n=this.resolveRoot(e.slice(1));t=n,r=n.kind}}else if(r===`union`&&d(t,`object`)){let e=sa(t);e?.length===1&&(t=e[0],r=mr(t))}if(A(t)&&t.kind===r)return t;let i=ra[r].normalize?.(t,this)??t;return A(i)?i.kind===r?i:ca(r,i.kind):{...n,$:this,kind:r,def:i,prefix:n.alias??r}}bindReference(e){let t;return t=A(e)?e.$===this?e:new e.constructor(e.attachments,this):e.$===this?e:new Bn(e.params,e.bodyDef,e.$,this,e.hkt),this.resolved||Object.assign(this.referencesById,t.referencesById),t}resolveRoot(e){return this.maybeResolveRoot(e)??h(wa(e))}maybeResolveRoot(e){let t=this.maybeResolve(e);if(!k(t,`generic`))return t}maybeResolveSubalias(e){return ba(this.aliases,e)??ba(this.ambient,e)}get ambient(){return T.ambient}maybeResolve(e){let t=this.resolutions[e];if(t){if(typeof t!=`string`)return this.bindReference(t);let n=H[t];if(k(n,`root`))return this.resolutions[e]=n;if(k(n,`context`)){if(n.phase===`resolving`)return this.node(`alias`,{reference:`$${e}`},{prereduced:!0});if(n.phase===`resolved`)return m(`Unexpected resolved context for was uncached by its scope: ${w(n)}`);n.phase=`resolving`;let t=this.bindReference(this.parseOwnDefinitionFormat(n.def,n));return n.phase=`resolved`,H[t.id]=t,H[n.id]=t,this.resolutions[e]=t}return m(`Unexpected nodesById entry for ${t}: ${w(n)}`)}let n=this.aliases[e]??this.ambient?.[e];return n?(n=this.normalizeRootScopeValue(n),k(n,`generic`)?this.resolutions[e]=this.bindReference(n):k(n,`module`)?(n.root||h(Ea(e)),this.resolutions[e]=this.bindReference(n.root)):this.resolutions[e]=this.parse(n,{alias:e})):this.maybeResolveSubalias(e)}createParseContext(e){let t=e.id??yr(e.prefix);return H[t]=Object.assign(e,{[O]:`context`,$:this,id:t,phase:`unresolved`})}traversal(e){return new pn(e,this.resolvedConfig)}import(...e){return new aa(_(this.export(...e),(e,t)=>[`#${e}`,t]))}precompilation;_exportedResolutions;_exports;export(...e){if(!this._exports){this._exports={};for(let e of this.exportedNames){let t=this.aliases[e];this._exports[e]=k(t,`module`)?oa(t,this):va(this.maybeResolve(e))}for(let e of this.lazyResolutions)e.resolution;if(this._exportedResolutions=Ca(this,this._exports),this._json=ya(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let e=ha(this.references);this.precompilation=e.write(fa,4),ma(this.references,e)}this.resolved=!0}return new aa(_(e.length?e:this.exportedNames,(e,t)=>[t,this._exports[t]]))}resolve(e){return this.export()[e]}node=(e,t,n={})=>{let r=this.preparseNode(e,t,n);if(A(r))return this.bindReference(r);let i=this.createParseContext(r),a=br(i),o=this.bindReference(a);return H[i.id]=o};parse=(e,t={})=>this.finalize(this.parseDefinition(e,t));parseDefinition(e,t={}){if(k(e,`root`))return this.bindReference(e);let n=this.preparseOwnDefinitionFormat(e,t);if(k(n,`root`))return this.bindReference(n);let r=this.createParseContext(n);H[r.id]=r;let i=this.bindReference(this.parseOwnDefinitionFormat(e,r));return i.isCyclic&&(i=Sr(i,r.id)),H[r.id]=i,i}finalize(e){return va(e),!e.precompilation&&!this.resolvedConfig.jitless&&pa(e.references),e}},_a=class extends ga{parseOwnDefinitionFormat(e,t){return br(t)}preparseOwnDefinitionFormat(e,t){return this.preparseNode(mr(e),e,t)}preparseOwnAliasEntry(e,t){return[e,t]}normalizeRootScopeValue(e){return e}},va=e=>{let t=e.references.filter(e=>e.hasKind(`alias`));for(let n of t){Object.assign(n.referencesById,n.resolution.referencesById);for(let t of e.references)n.id in t.referencesById&&Object.assign(t.referencesById,n.referencesById)}return e},ya=e=>_(e,(e,t)=>[e,k(t,`root`)||k(t,`generic`)?t.json:k(t,`module`)?ya(t):m(`Unexpected resolution ${w(t)}`)]),ba=(e,t)=>{let n=t.indexOf(`.`);if(n===-1)return;let r=t.slice(0,n),i=e[r];if(i===void 0)return;if(!k(i,`module`))return h(Ta(r));let a=t.slice(n+1),o=i[a];if(o===void 0)return ba(i,a);if(k(o,`root`)||k(o,`generic`))return o;if(k(o,`module`))return o.root??h(Ea(t));m(`Unexpected resolution for alias '${t}': ${w(o)}`)},xa=(e,t)=>new _a(e,t),Sa=new _a({}),Ca=(e,t)=>{let n={};for(let r in t){let i=t[r];if(k(i,`module`)){let t=_(Ca(e,i),(e,t)=>[`${r}.${e}`,t]);Object.assign(n,t)}else k(i,`root`)||k(i,`generic`)?n[r]=i:m(`Unexpected scope resolution ${w(i)}`)}return n},wa=e=>`'${e}' is unresolvable`,Ta=e=>`'${e}' must reference a module to be accessed using dot syntax`,Ea=e=>`Reference to submodule '${e}' must specify an alias`;Sa.export();var G=Sa.schema,Da=Sa.node;Sa.defineSchema;var K=Sa.generic,Oa=`^(?:0|[1-9]\\d*)$`;E(new RegExp(Oa));var ka=xa({bigint:`bigint`,boolean:[{unit:!1},{unit:!0}],false:{unit:!1},never:[],null:{unit:null},number:`number`,object:`object`,string:`string`,symbol:`symbol`,true:{unit:!0},unknown:{},undefined:{unit:void 0},Array,Date},{prereducedAliases:!0}).export();T.intrinsic={...ka};var Aa=xa({integer:{domain:`number`,divisor:1},lengthBoundable:[`string`,Array],key:[`string`,`symbol`],nonNegativeIntegerString:{domain:`string`,pattern:Oa}},{prereducedAliases:!0}).export();Object.assign(T.intrinsic,Aa);var ja=xa({jsonPrimitive:[`string`,`number`,{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:`object`,index:{signature:`string`,value:`$jsonData`}},jsonData:[`$jsonPrimitive`,`$jsonObject`]},{prereducedAliases:!0}).export(),q={...ka,...Aa,...ja,emptyStructure:Da(`structure`,{},{prereduced:!0})};T.intrinsic={...q};var Ma=((e,t)=>new RegExp(e,t));Object.assign(Ma,{as:Ma});var Na=e=>typeof e==`string`&&e[0]===`d`&&(e[1]===`'`||e[1]===`"`)&&e[e.length-1]===e[1],Pa=e=>e.toString()!==`Invalid Date`,Fa=e=>e.slice(2,-1),Ia=e=>`'${e}' could not be parsed by the Date constructor`,La=(e,t)=>Ra(e,t),Ra=(e,t)=>{let n=new Date(e);if(Pa(n))return n;let r=ot(e);if(r!==void 0){let e=new Date(r);if(Pa(e))return e}return t?h(t===!0?Ia(e):t):void 0},za=G({proto:`Array`,sequence:`string`,required:{key:`groups`,value:[`object`,{unit:void 0}]}}),Ba=(e,t)=>{let n=e.scanner.shiftUntilEscapable(Ka[Ga[t]]);if(e.scanner.lookahead===``)return e.error(Ja(n,t));if(e.scanner.shift(),t in Wa){let r;try{r=new RegExp(n)}catch(e){h(String(e))}e.root=e.ctx.$.node(`intersection`,{domain:`string`,pattern:n},{prereduced:!0}),t===`x/`&&(e.root=e.ctx.$.node(`morph`,{in:e.root,morphs:e=>r.exec(e),declaredOut:za}))}else if(v(t,Va))e.root=e.ctx.$.node(`unit`,{unit:n});else{let t=La(n,Ia(n));e.root=e.ctx.$.node(`unit`,{meta:n,unit:t})}},Va={"'":1,'"':1},Ha={"/":1,"'":1,'"':1},Ua={"d'":`'`,'d"':`"`,"'":`'`,'"':`"`},Wa={"/":`/`,"x/":`/`},Ga={...Ua,...Wa},Ka={"'":e=>e.lookahead===`'`,'"':e=>e.lookahead===`"`,"/":e=>e.lookahead===`/`},qa={'"':`double-quote`,"'":`single-quote`,"/":`forward slash`},Ja=(e,t)=>`${t}${e} requires a closing ${qa[Ga[t]]}`,Ya=e=>`Private type references should not include '#'. Use '${e}' instead.`,Xa=`Optional definitions like 'string?' are only valid as properties in an object or tuple`,Za=`Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple`,Qa={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...Be},$a=(e,t)=>e===`>`?t[0]===`=`?t[1]===`=`:t.trimStart()===``||v(t.trimStart()[0],Qa):e===`=`?t[0]!==`=`:e===`,`||e===`?`,eo=(e,t,n)=>to(e,t,n,[]),to=(e,t,n,r)=>{let i=n.parseUntilFinalizer();return r.push(i.root),i.finalizer===`>`?r.length===t.params.length?r:n.error(no(e,t.names,r.map(e=>e.expression))):i.finalizer===`,`?to(e,t,n,r):i.error(jt(`>`))},no=(e,t,n)=>`${e}<${t.join(`, `)}> requires exactly ${t.length} args (got ${n.length}${n.length===0?``:`: ${n.join(`, `)}`})`,ro=e=>{let t=e.scanner.shiftUntilLookahead(Qa);t===`keyof`?e.addPrefix(`keyof`):e.root=ao(e,t)},io=(e,t,n)=>(n.scanner.shiftUntilNonWhitespace(),n.scanner.shift()===`<`?t(...eo(e,t,n)):n.error(no(e,t.names,[]))),ao=(e,t)=>oo(e,t)??so(e,t)??e.error(t===``?e.scanner.lookahead===`#`?Ya(e.shiftedBy(1).scanner.shiftUntilLookahead(Qa)):co(e):wa(t)),oo=(e,t)=>{if(e.ctx.args?.[t]){let n=e.ctx.args[t];return typeof n==`string`?e.ctx.$.node(`alias`,{reference:n},{prereduced:!0}):n}let n=e.ctx.$.maybeResolve(t);if(k(n,`root`))return n;if(n!==void 0)return k(n,`generic`)?io(t,n,e):h(`Unexpected resolution ${w(n)}`)},so=(e,t)=>{let n=st(t);if(n!==void 0)return e.ctx.$.node(`unit`,{unit:n});let r=ut(t);if(r!==void 0)return e.ctx.$.node(`unit`,{unit:r})},co=e=>{let t=e.previousOperator();return t?lo(t,e.scanner.unscanned):uo(e.scanner.unscanned)},lo=(e,t=``)=>`Token '${e}' requires a right operand${t?` before '${t}'`:``}`,uo=e=>`Expected an expression${e?` before '${e}'`:``}`,fo=e=>e.scanner.lookahead===``?e.error(co(e)):e.scanner.lookahead===`(`?e.shiftedBy(1).reduceGroupOpen():e.scanner.lookaheadIsIn(Ha)?Ba(e,e.scanner.shift()):e.scanner.lookaheadIsIn(Be)?fo(e.shiftedBy(1)):e.scanner.lookahead===`d`?e.scanner.nextLookahead in Va?Ba(e,`${e.scanner.shift()}${e.scanner.shift()}`):ro(e):e.scanner.lookahead===`x`&&e.scanner.nextLookahead===`/`?e.shiftedBy(2)&&Ba(e,`x/`):ro(e),po={">":!0,">=":!0},mo={"<":!0,"<=":!0},ho={"<":`>`,">":`<`,"<=":`>=`,">=":`<=`,"==":`==`},go=(e,t)=>`Left bounds are only valid when paired with right bounds (try ...${t}${e})`,_o=e=>`Left-bounded expressions must specify their limits using < or <= (was ${e})`,vo=(e,t,n,r)=>`An expression may have at most one left bound (parsed ${e}${ho[t]}, ${n}${ho[r]})`,yo=(e,t)=>{let n=xo(e,t);if(e.root.hasKind(`unit`)){if(typeof e.root.unit==`number`){e.reduceLeftBound(e.root.unit,n),e.unsetRoot();return}if(e.root.unit instanceof Date){let t=`d'${e.root.description??e.root.unit.toISOString()}'`;e.unsetRoot(),e.reduceLeftBound(t,n);return}}return wo(e,n)},bo={"<":1,">":1,"=":1},xo=(e,t)=>e.scanner.lookaheadIs(`=`)?`${t}${e.scanner.shift()}`:t,So=(e,t,n,r)=>n.extends(T.intrinsic.number)?typeof t==`number`?e===`==`?[`min`,`max`]:e[0]===`>`?[`min`]:[`max`]:h(To(e,t,r)):n.extends(T.intrinsic.lengthBoundable)?typeof t==`number`?e===`==`?[`exactLength`]:e[0]===`>`?[`minLength`]:[`maxLength`]:h(To(e,t,r)):n.extends(T.intrinsic.Date)?e===`==`?[`after`,`before`]:e[0]===`>`?[`after`]:[`before`]:h(rr(n.expression)),Co=e=>({rule:Na(e.limit)?Fa(e.limit):e.limit,exclusive:e.comparator.length===1}),wo=(e,t)=>{let n=e.unsetRoot(),r=e.scanner.location;e.parseOperand();let i=e.unsetRoot(),a=e.scanner.sliceChars(r,e.scanner.location);if(e.root=n,!i.hasKind(`unit`)||typeof i.unit!=`number`&&!(i.unit instanceof Date))return e.error(To(t,a,`right`));let o=i.unit,s=t.length===1,c=So(t,typeof o==`number`?o:a,n,`right`);for(let n of c)e.constrainRoot(n,t===`==`?{rule:o}:{rule:o,exclusive:s});if(!e.branches.leftBound)return;if(!v(t,mo))return e.error(_o(t));let l=So(e.branches.leftBound.comparator,e.branches.leftBound.limit,n,`left`);e.constrainRoot(l[0],Co(e.branches.leftBound)),e.branches.leftBound=null},To=(e,t,n)=>`Comparator ${n===`left`?ho[e]:e} must be ${n===`left`?`preceded`:`followed`} by a corresponding literal (was ${t})`,Eo=e=>{e.scanner.shiftUntilNonWhitespace();let t=e.scanner.shiftUntilLookahead(Qa);e.root=e.root.brand(t)},Do=e=>{e.scanner.shiftUntilNonWhitespace();let t=e.scanner.shiftUntilLookahead(Qa),n=ct(t,{errorOnFail:Oo(t)});n===0&&e.error(Oo(0)),e.root=e.root.constrain(`divisor`,n)},Oo=e=>`% operator must be followed by a non-zero integer literal (was ${e})`,ko=e=>{let t=e.scanner.shift();return t===``?e.finalize(``):t===`[`?e.scanner.shift()===`]`?e.setRoot(e.root.array()):e.error(jo):t===`|`?e.scanner.lookahead===`>`?e.shiftedBy(1).pushRootToBranch(`|>`):e.pushRootToBranch(t):t===`&`?e.pushRootToBranch(t):t===`)`?e.finalizeGroup():$a(t,e.scanner.unscanned)?e.finalize(t):v(t,bo)?yo(e,t):t===`%`?Do(e):t===`#`?Eo(e):t in Be?ko(e):e.error(Ao(t))},Ao=(e,t=``)=>`'${e}' is not allowed here${t&&` (should be ${t})`}`,jo=`Missing expected ']'`,Mo=e=>{let t=e.unsetRoot();e.parseOperand();let n=e.unsetRoot();return n.hasKind(`unit`)?[t,`=`,n.unit instanceof Date?()=>new Date(n.unit):n.unit]:e.error(No(n.expression))},No=e=>`Default value '${e}' must be a literal value`,Po=(e,t)=>{let n=t.$.maybeResolveRoot(e);if(n)return n;if(e.endsWith(`[]`)){let n=t.$.maybeResolveRoot(e.slice(0,-2));if(n)return n.array()}let r=new Ro(new kt(e),t),i=Fo(r);return r.finalizer===`>`&&h(Ao(`>`)),i},Fo=e=>{e.parseOperand();let t=Io(e).root;return t?(e.finalizer===`=`?t=Mo(e):e.finalizer===`?`&&(t=[t,`?`]),e.scanner.shiftUntilNonWhitespace(),e.scanner.lookahead&&h(Ao(e.scanner.lookahead)),t):m(`Root was unexpectedly unset after parsing string '${e.scanner.scanned}'`)},Io=e=>{for(;e.finalizer===void 0;)Lo(e);return e},Lo=e=>e.hasRoot()?e.parseOperator():e.parseOperand(),Ro=class e{root;branches={prefixes:[],leftBound:null,intersection:null,union:null,pipe:null};finalizer;groups=[];scanner;ctx;constructor(e,t){this.scanner=e,this.ctx=t}error(e){return h(e)}hasRoot(){return this.root!==void 0}setRoot(e){this.root=e}unsetRoot(){let e=this.root;return this.root=void 0,e}constrainRoot(...e){this.root=this.root.constrain(e[0],e[1])}finalize(e){if(this.groups.length)return this.error(jt(`)`));this.finalizeBranches(),this.finalizer=e}reduceLeftBound(e,t){let n=ho[t];if(!v(n,po))return this.error(_o(t));if(this.branches.leftBound)return this.error(vo(this.branches.leftBound.limit,this.branches.leftBound.comparator,e,n));this.branches.leftBound={comparator:n,limit:e}}finalizeBranches(){this.assertRangeUnset(),this.branches.pipe?(this.pushRootToBranch(`|>`),this.root=this.branches.pipe):this.branches.union?(this.pushRootToBranch(`|`),this.root=this.branches.union):this.branches.intersection?(this.pushRootToBranch(`&`),this.root=this.branches.intersection):this.applyPrefixes()}finalizeGroup(){this.finalizeBranches();let e=this.groups.pop();if(!e)return this.error(At(`)`,this.scanner.unscanned));this.branches=e}addPrefix(e){this.branches.prefixes.push(e)}applyPrefixes(){for(;this.branches.prefixes.length;){let e=this.branches.prefixes.pop();this.root=e===`keyof`?this.root.keyof():m(`Unexpected prefix '${e}'`)}}pushRootToBranch(e){this.assertRangeUnset(),this.applyPrefixes();let t=this.root;this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd(t)??t,e!==`&`&&(this.branches.union=this.branches.union?.rawOr(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null,e!==`|`&&(this.branches.pipe=this.branches.pipe?.rawPipeOnce(this.branches.union)??this.branches.union,this.branches.union=null))}parseUntilFinalizer(){return Io(new e(this.scanner,this.ctx))}parseOperator(){return ko(this)}parseOperand(){return fo(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(go(this.branches.leftBound.limit,this.branches.leftBound.comparator))}reduceGroupOpen(){this.groups.push(this.branches),this.branches={prefixes:[],leftBound:null,union:null,intersection:null,pipe:null}}previousOperator(){return this.branches.leftBound?.comparator??this.branches.prefixes[this.branches.prefixes.length-1]??(this.branches.intersection?`&`:this.branches.union?`|`:this.branches.pipe?`|>`:void 0)}shiftedBy(e){return this.scanner.jumpForward(e),this}},zo=`An empty string is not a valid generic parameter name`,Bo=(e,t,n)=>{e.shiftUntilNonWhitespace();let r=e.shiftUntilLookahead(Qa);return r===``?e.lookahead===``&&t.length?t:h(zo):(e.shiftUntilNonWhitespace(),Ho(e,r,t,n))},Vo=`extends `,Ho=(e,t,n,r)=>{if(e.shiftUntilNonWhitespace(),e.unscanned.startsWith(Vo))e.jumpForward(8);else return e.lookahead===`,`&&e.shift(),n.push(t),Bo(e,n,r);let i=Io(new Ro(e,r));return n.push([t,i.root]),Bo(e,n,r)},Uo=class extends x{constructor(e){let t={$:e,raw:e.fn};super((...t)=>{let n=t.indexOf(`:`),r=n===-1?t.length-1:n-1,i=t.slice(0,r+1),a=e.parse(i).assertHasKind(`intersection`),o=e.intrinsic.unknown;if(n!==-1){if(n!==t.length-2)return h(Go);o=e.parse(t[n+1])}return e=>new Wo(e,a,o)},{attach:t})}},Wo=class extends x{raw;params;returns;expression;constructor(e,t,n){let r=`typed ${e.name}`,i={[r]:(...r)=>{let i=e(...t.assert(r));return n.assert(i)}}[r];super(i),this.raw=e,this.params=t,this.returns=n;let a=t.expression;a[0]===`[`&&a[a.length-1]===`]`?a=a.slice(1,-1):a.endsWith(`[]`)&&(a=`...${a}`),this.expression=`(${a}) => ${n?.expression??`unknown`}`}},Go=`":" must be followed by exactly one return type e.g:
34
+ fn("string", ":", "number")(s => s.length)`,Ko=class extends x{$;constructor(e){super((...t)=>new qo(e)(...t),{bind:e}),this.$=e}in(e){return new qo(this.$,e===void 0?void 0:this.$.parse(e))}at(e,t){return new qo(this.$).at(e,t)}case(e,t){return new qo(this.$).case(e,t)}},qo=class extends x{$;in;key;branches=[];constructor(e,t){super(e=>this.caseEntries(Object.entries(e).map(([e,t])=>e==="default"?[e,t]:[this.$.parse(e),t]))),this.$=e,this.in=t}at(e,t){return this.key&&h(Xo),this.branches.length&&h(Yo),this.key=e,t?this.match(t):this}case(e,t){return this.caseEntry(this.$.parse(e),t)}caseEntry(e,t){let n=(this.key?this.$.parse({[this.key]:e}):e).pipe(t);return this.branches.push(n),this}match(e){return this(e)}strings(e){return this.caseEntries(Object.entries(e).map(([e,t])=>e==="default"?[e,t]:[this.$.node(`unit`,{unit:e}),t]))}caseEntries(e){for(let t=0;t<e.length;t++){let[n,r]=e[t];if(n==="default")return t!==e.length-1&&h(`default may only be specified as the last key of a switch definition`),this.default(r);if(typeof r!=`function`)return h(`Value for case "${n}" must be a function (was ${f(r)})`);this.caseEntry(n,r)}return this}default(e){typeof e==`function`&&this.case(q.unknown,e);let t={branches:this.branches,ordered:!0};(e===`never`||e===`assert`)&&(t.meta={onFail:Jo});let n=this.$.node(`union`,t);if(!this.in)return this.$.finalize(n);let r=this.in.pipe(n);return(e===`never`||e===`assert`)&&(r=r.configureReferences({onFail:Jo},`self`)),this.$.finalize(r)}},Jo=e=>e.throw(),Yo=`A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')`,Xo=`At most one key matcher may be specified per expression`,Zo=(e,t)=>{if(b(e)){if(e[1]===`=`)return[t.$.parseOwnDefinitionFormat(e[0],t),`=`,e[2]];if(e[1]===`?`)return[t.$.parseOwnDefinitionFormat(e[0],t),`?`]}return Ps(e,t)},Qo=`Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }`,$o=`Only required keys may specify default values, e.g. { value: 'number = 0' }`,es=(e,t)=>{let n,r={},i=fe(e);for(let[e,o]of i){let i=is(e);if(i.kind===`spread`){if(!de(r))return h(rs);let e=t.$.parseOwnDefinitionFormat(o,t);if(e.equals(q.object))continue;if(!e.hasKind(`intersection`)||!e.basis?.equals(q.object))return h(as(e.expression));n=e.structure;continue}if(i.kind===`undeclared`){o!==`reject`&&o!==`delete`&&o!==`ignore`&&h(ns(o)),r.undeclared=o;continue}let s=Zo(o,t),c=i;if(i.kind===`required`){b(s)?ts(r,`optional`,s[1]===`=`?{key:i.normalized,value:s[0],default:s[2]}:{key:i.normalized,value:s[0]},t):ts(r,`required`,{key:i.normalized,value:s},t);continue}if(b(s)&&(s[1]===`?`&&h(Qo),s[1]===`=`&&h($o)),i.kind===`optional`){ts(r,`optional`,{key:i.normalized,value:s},t);continue}let l=$i(t.$.parseOwnDefinitionFormat(c.normalized,t),s,t.$);l.index&&(r.index=a(r.index,l.index)),l.required&&(r.required=a(r.required,l.required))}let o=t.$.node(`structure`,r);return t.$.parseSchema({domain:`object`,structure:n?.merge(o)??o})},ts=(e,t,n,r)=>{e[t]=a(e[t],r.$.node(t,n))},ns=e=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${w(e)})`,rs=`Spread operator may only be used as the first key in an object`,is=e=>typeof e==`symbol`?{kind:`required`,normalized:e}:e[e.length-1]===`?`?e[e.length-2]===`\\`?{kind:`required`,normalized:`${e.slice(0,-2)}?`}:{kind:`optional`,normalized:e.slice(0,-1)}:e[0]===`[`&&e[e.length-1]===`]`?{kind:`index`,normalized:e.slice(1,-1)}:e[0]===`\\`&&e[1]===`[`&&e[e.length-1]===`]`?{kind:`required`,normalized:e.slice(1)}:e===`...`?{kind:`spread`}:e===`+`?{kind:`undeclared`}:{kind:`required`,normalized:e===`\\...`?`...`:e===`\\+`?`+`:e},as=e=>`Spread operand must resolve to an object literal type (was ${e})`,os=(e,t)=>bs(e)?ys[e[0]](e,t):vs(e)?_s[e[1]](e,t):null,ss=(e,t)=>t.$.parseOwnDefinitionFormat(e[1],t).keyof(),cs=(e,t)=>{if(e[2]===void 0)return h(lo(e[1],``));let n=t.$.parseOwnDefinitionFormat(e[0],t),r=t.$.parseOwnDefinitionFormat(e[2],t);if(e[1]===`|`)return t.$.node(`union`,{branches:[n,r]});let i=e[1]===`&`?L(n,r,t.$):Dn(n,r,t.$);return i instanceof I?i.throw():i},ls=(e,t)=>t.$.parseOwnDefinitionFormat(e[0],t).array(),us=(e,t)=>typeof e[2]==`function`?t.$.parseOwnDefinitionFormat(e[0],t).pipe(e[2]):h(ds(`=>`,e[2])),ds=(e,t)=>`${e===`:`?`Narrow`:`Morph`} expression requires a function following '${e}' (was ${typeof t})`,fs=(e,t)=>typeof e[2]==`function`?t.$.parseOwnDefinitionFormat(e[0],t).constrain(`predicate`,e[2]):h(ds(`:`,e[2])),ps=(e,t)=>t.$.parseOwnDefinitionFormat(e[0],t).configure(e[2],e[3]),ms=e=>e,hs=ms({"[]":ls,"?":()=>h(Xa)}),gs=ms({"|":cs,"&":cs,":":fs,"=>":us,"|>":cs,"@":ps,"=":()=>h(Za)}),_s={...hs,...gs},vs=e=>_s[e[1]]!==void 0,ys=(e=>e)({keyof:ss,instanceof:(e,t)=>{if(typeof e[1]!=`function`)return h(xs(Se(e[1])));let n=e.slice(1).map(e=>typeof e==`function`?t.$.node(`proto`,{proto:e}):h(xs(Se(e))));return n.length===1?n[0]:t.$.node(`union`,{branches:n})},"===":(e,t)=>t.$.units(e.slice(1))}),bs=e=>ys[e[0]]!==void 0,xs=e=>`Expected a constructor following 'instanceof' operator (was ${e})`,Ss=(e,t)=>{let n=[{}],r=0;for(;r<e.length;){let i=!1;e[r]===`...`&&r<e.length-1&&(i=!0,r++);let a=Zo(e[r],t),[o,s,c]=b(a)?a:[a];if(r++,i){if(!o.extends(T.intrinsic.Array))return h(Os(o.expression));n=n.flatMap(e=>o.distribute(t=>Ds(Vt(e),t)))}else n=n.map(e=>s===`?`?ws(e,o):s===`=`?Ts(e,o,c):Cs(e,o))}return t.$.parseSchema(n.map(e=>de(e)?{proto:Array,exactLength:0}:{proto:Array,sequence:e}))},Cs=(e,t)=>e.defaultables||e.optionals?h(e.variadic?Ii:As):(e.variadic?e.postfix=a(e.postfix,t):e.prefix=a(e.prefix,t),e),ws=(e,t)=>e.variadic?h(js):(e.optionals=a(e.optionals,t),e),Ts=(e,t,n)=>e.variadic?h(js):e.optionals?h(Ms):(e.defaultables=a(e.defaultables,[[t,n]]),e),Es=(e,t)=>(e.postfix&&h(ks),e.variadic?e.variadic.equals(t)||h(ks):e.variadic=t.internal,e),Ds=(e,t)=>{let n=t.select({method:`find`,kind:`sequence`});if(!n)return Es(e,T.intrinsic.unknown);if(n.prefix)for(let t of n.prefix)Cs(e,t);if(n.optionals)for(let t of n.optionals)ws(e,t);if(n.variadic&&Es(e,n.variadic),n.postfix)for(let t of n.postfix)Cs(e,t);return e},Os=e=>`Spread element must be an array (was ${e})`,ks=`A tuple may have at most one variadic element`,As=`A required element may not follow an optional element`,js=`An optional element may not follow a variadic element`,Ms=`A defaultable element may not follow an optional element without a default`,Ns={},Ps=(e,t)=>{if(typeof e==`string`){if(t.args&&Object.keys(t.args).some(t=>e.includes(t)))return Po(e,t);let n=Ns[t.$.name]??={};return n[e]??=Po(e,t)}return d(e,`object`)?Fs(e,t):h(Rs(f(e)))},Fs=(e,t)=>{let n=xe(e);switch(n){case void 0:return k(e,`root`)?e:`~standard`in e?Is(e,t):es(e,t);case`Array`:return Ls(e,t);case`RegExp`:return t.$.node(`intersection`,{domain:`string`,pattern:e},{prereduced:!0});case`Function`:{let t=Me(e)?e():e;return k(t,`root`)?t:h(Rs(`Function`))}default:return h(Rs(n??w(e)))}},Is=(e,t)=>t.$.intrinsic.unknown.pipe((t,n)=>{let r=e[`~standard`].validate(t);if(!r.issues)return r.value;for(let{message:e,path:t}of r.issues)t&&t.length?n.error({problem:Le(e),relativePath:t.map(e=>typeof e==`object`?e.key:e)}):n.error({message:e})}),Ls=(e,t)=>os(e,t)??Ss(e,t),Rs=e=>`Type definitions must be strings or objects (was ${e})`,zs=class extends x{constructor(e){let t=Object.assign({errors:un,hkt:S,$:e,raw:e.parse,module:e.constructor.module,scope:e.constructor.scope,declare:e.declare,define:e.define,match:e.match,generic:e.generic,schema:e.schema,keywords:e.ambient,unit:e.unit,enumerated:e.enumerated,instanceOf:e.instanceOf,valueOf:e.valueOf,or:e.or,and:e.and,merge:e.merge,pipe:e.pipe,fn:e.fn},e.ambientAttachments);super((...t)=>{if(t.length===1)return e.parse(t[0]);if(t.length===2&&typeof t[0]==`string`&&t[0][0]===`<`&&t[0][t[0].length-1]===`>`){let n=t[0].slice(1,-1);return new Bn(e.parseGenericParams(n,{}),t[1],e,e,null)}return e.parse(t)},{attach:t})}},Bs=T,Vs=class e extends ga{get ambientAttachments(){if(Bs.typeAttachments)return this.cacheGetter(`ambientAttachments`,_(Bs.typeAttachments,(e,t)=>[e,this.bindReference(t)]))}preparseOwnAliasEntry(e,t){let n=e.indexOf(`<`);if(n===-1){if(k(t,`module`)||k(t,`generic`))return[e,t];let n=this.name===`ark`?e:e===`root`?this.name:`${this.name}.${e}`,r=this.resolvedConfig.keywords?.[n];return r&&(t=[t,`@`,r]),[e,t]}e[e.length-1]!==`>`&&h(`'>' must be the last character of a generic declaration in a scope`);let r=e.slice(0,n),i=e.slice(n+1,-1);return[r,()=>Rn(this.parseGenericParams(i,{alias:r}),t,this)]}parseGenericParams(e,t){return Bo(new kt(e),[],this.createParseContext({...t,def:e,prefix:`generic`}))}normalizeRootScopeValue(e){return Me(e)&&!k(e,`generic`)?e():e}preparseOwnDefinitionFormat(e,t){return{...t,def:e,prefix:t.alias??`type`}}parseOwnDefinitionFormat(e,t){!(t.alias&&t.alias in this.aliases)&&!t.args&&(t.args={this:t.id});let n=Ps(e,t);if(b(n)){if(n[1]===`=`)return h(Za);if(n[1]===`?`)return h(Xa)}return n}unit=e=>this.units([e]);valueOf=e=>this.units(he(e));enumerated=(...e)=>this.units(e);instanceOf=e=>this.node(`proto`,{proto:e},{prereduced:!0});or=(...e)=>this.schema(e.map(e=>this.parse(e)));and=(...e)=>e.reduce((e,t)=>e.and(this.parse(t)),this.intrinsic.unknown);merge=(...e)=>e.reduce((e,t)=>e.merge(this.parse(t)),this.intrinsic.object);pipe=(...e)=>this.intrinsic.unknown.pipe(...e);fn=new Uo(this);match=new Ko(this);declare=()=>({type:this.type});define(e){return e}type=new zs(this);static scope=((t,n={})=>new e(t,n));static module=((e,t={})=>this.scope(e,t).export())},Hs=Object.assign(Vs.scope,{define:e=>e}),J=Vs,Us=class extends S{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'},Ws=K([`base`,q.object],[`props`,q.object])(e=>e.base.merge(e.props),Us),Gs=J.module({Key:q.key,Merge:Ws}),Ks=class extends S{},qs=K(`element`)(t=>{let n=t.element.exclude(q.Array),r=n.array();return n.rawOr(r).pipe(e).distribute(e=>e.assertHasKind(`morph`).declareOut(r),G)},Ks),Js=J.module({root:q.Array,readonly:`root`,index:q.nonNegativeIntegerString,liftFrom:qs},{name:`Array`}),Ys=G([`string`,dt.FileConstructor]),Xs=G({meta:`an object representing parsed form data`,domain:`object`,index:{signature:`string`,value:Ys.rawOr(Ys.array())}}),Zs=J.module({root:[`instanceof`,FormData],value:Ys,parsed:Xs,parse:G({in:FormData,morphs:e=>{let t={};for(let[n,r]of e)if(n in t){let e=t[n];typeof e==`string`||e instanceof dt.FileConstructor?t[n]=[e,r]:e.push(r)}else t[n]=r;return t},declaredOut:Xs})},{name:`FormData`}),Qs=J.module({Int8:[`instanceof`,Int8Array],Uint8:[`instanceof`,Uint8Array],Uint8Clamped:[`instanceof`,Uint8ClampedArray],Int16:[`instanceof`,Int16Array],Uint16:[`instanceof`,Uint16Array],Int32:[`instanceof`,Int32Array],Uint32:[`instanceof`,Uint32Array],Float32:[`instanceof`,Float32Array],Float64:[`instanceof`,Float64Array],BigInt64:[`instanceof`,BigInt64Array],BigUint64:[`instanceof`,BigUint64Array]},{name:`TypedArray`}),$s={Boolean:1,Number:1,String:1},ec=J.module({..._({...ge,...ve},(e,t)=>e in $s?[]:[e,[`instanceof`,t]]),Array:Js,TypedArray:Qs,FormData:Zs}),tc=G({domain:{domain:`number`,meta:`a number representing a Unix timestamp`},divisor:{rule:1,meta:`an integer representing a Unix timestamp`},min:{rule:-864e13,meta:`a Unix timestamp after -8640000000000000`},max:{rule:864e13,meta:`a Unix timestamp before 8640000000000000`},meta:`an integer representing a safe Unix timestamp`}),nc=G({domain:`number`,divisor:1}),rc=J.module({root:q.number,integer:nc,epoch:tc,safe:G({domain:{domain:`number`,numberAllowsNaN:!1},min:-(2**53-1),max:2**53-1}),NaN:[`===`,NaN],Infinity:[`===`,1/0],NegativeInfinity:[`===`,-1/0]},{name:`number`}),Y=(e,t,n)=>{let r={domain:`string`,pattern:{rule:e.source,flags:e.flags,meta:t}};return n&&(r.meta={format:n}),Da(`intersection`,r)},ic=Y(Ze,`a well-formed integer string`),ac=J.module({root:ic,parse:G({in:ic,morphs:(e,t)=>{let n=Number.parseInt(e);return Number.isSafeInteger(n)?n:t.error(`an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER`)},declaredOut:q.integer})},{name:`string.integer`}),oc=Y(/^[\dA-Fa-f]+$/,`hex characters only`),sc=J.module({root:Y(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,`base64-encoded`),url:Y(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,`base64url-encoded`)},{name:`string.base64`}),cc=Y(/^[A-Z].*$/,`capitalized`),lc=J.module({root:G({in:`string`,morphs:e=>e.charAt(0).toUpperCase()+e.slice(1),declaredOut:cc}),preformatted:cc},{name:`string.capitalize`}),uc=G({domain:`string`,pattern:{meta:`a credit card number`,rule:`^(?:4\\d{12}(?:\\d{3,6})?|5[1-5]\\d{14}|(222[1-9]|22[3-9]\\d|2[3-6]\\d{2}|27[01]\\d|2720)\\d{12}|6(?:011|5\\d\\d)\\d{12,15}|3[47]\\d{13}|3(?:0[0-5]|[68]\\d)\\d{11}|(?:2131|1800|35\\d{3})\\d{11}|6[27]\\d{14}|^(81\\d{14,17}))$`},predicate:{meta:`a credit card number`,predicate:e=>{let t=e.replace(/[ -]+/g,``),n=0,r,i,a=!1;for(let e=t.length-1;e>=0;e--)r=t.substring(e,e+1),i=Number.parseInt(r,10),a?(i*=2,n+=i>=10?i%10+1:i):n+=i,a=!a;return!!(n%10==0&&t)}}}),dc=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))(T((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([,.]\d+(?!:))?)?(\17[0-5]\d([,.]\d+)?)?([Zz]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/,fc=G({domain:`string`,predicate:{meta:`a parsable date`,predicate:e=>!Number.isNaN(new Date(e).valueOf())}}).assertHasKind(`intersection`),pc=ac.root.internal.narrow((e,t)=>{let n=Number.parseInt(e),r=rc.epoch(n);return r instanceof un?(t.errors.merge(r),!1):!0}).configure({description:`an integer string representing a safe Unix timestamp`},`self`).assertHasKind(`intersection`),mc=J.module({root:pc,parse:G({in:pc,morphs:e=>new Date(e),declaredOut:q.Date})},{name:`string.date.epoch`}),hc=Y(dc,`an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date`).internal.assertHasKind(`intersection`),gc=J.module({root:hc,parse:G({in:hc,morphs:e=>new Date(e),declaredOut:q.Date})},{name:`string.date.iso`}),_c=J.module({root:fc,parse:G({declaredIn:fc,in:`string`,morphs:(e,t)=>{let n=new Date(e);return Number.isNaN(n.valueOf())?t.error(`a parsable date`):n},declaredOut:q.Date}),iso:gc,epoch:mc},{name:`string.date`}),vc=Y(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,`an email address`,`email`),yc=`(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])`,X=`(${yc}[.]){3}${yc}`,bc=RegExp(`^${X}$`),Z=`(?:[0-9a-fA-F]{1,4})`,xc=RegExp(`^((?:${Z}:){7}(?:${Z}|:)|(?:${Z}:){6}(?:${X}|:${Z}|:)|(?:${Z}:){5}(?::${X}|(:${Z}){1,2}|:)|(?:${Z}:){4}(?:(:${Z}){0,1}:${X}|(:${Z}){1,3}|:)|(?:${Z}:){3}(?:(:${Z}){0,2}:${X}|(:${Z}){1,4}|:)|(?:${Z}:){2}(?:(:${Z}){0,3}:${X}|(:${Z}){1,5}|:)|(?:${Z}:){1}(?:(:${Z}){0,4}:${X}|(:${Z}){1,6}|:)|(?::((?::${Z}){0,5}:${X}|(?::${Z}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),Sc=J.module({root:[`v4 | v6`,`@`,`an IP address`],v4:Y(bc,`an IPv4 address`,`ipv4`),v6:Y(xc,`an IPv6 address`,`ipv6`)},{name:`string.ip`}),Cc=`a JSON string`,wc=e=>{if(!(e instanceof SyntaxError))throw e;return`must be ${Cc} (${e})`},Tc=G({meta:Cc,domain:`string`,predicate:{meta:Cc,predicate:(e,t)=>{try{return JSON.parse(e),!0}catch(e){return t.reject({code:`predicate`,expected:Cc,problem:wc(e)})}}}}),Ec=J.module({root:Tc,parse:G({meta:`safe JSON string parser`,in:`string`,morphs:(e,t)=>{if(e.length===0)return t.error({code:`predicate`,expected:Cc,actual:`empty`});try{return JSON.parse(e)}catch(e){return t.error({code:`predicate`,expected:Cc,problem:wc(e)})}},declaredOut:q.jsonObject})},{name:`string.json`}),Dc=Y(/^[a-z]*$/,`only lowercase letters`),Oc=J.module({root:G({in:`string`,morphs:e=>e.toLowerCase(),declaredOut:Dc}),preformatted:Dc},{name:`string.lower`}),kc=[`NFC`,`NFD`,`NFKC`,`NFKD`],Ac=_(kc,(e,t)=>[t,G({domain:`string`,predicate:e=>e.normalize(t)===e,meta:`${t}-normalized unicode`})]),jc=_(kc,(e,t)=>[t,G({in:`string`,morphs:e=>e.normalize(t),declaredOut:Ac[t]})]),Mc=J.module({root:jc.NFC,preformatted:Ac.NFC},{name:`string.normalize.NFC`}),Nc=J.module({root:jc.NFD,preformatted:Ac.NFD},{name:`string.normalize.NFD`}),Pc=J.module({root:jc.NFKC,preformatted:Ac.NFKC},{name:`string.normalize.NFKC`}),Fc=J.module({root:jc.NFKD,preformatted:Ac.NFKD},{name:`string.normalize.NFKD`}),Ic=J.module({root:`NFC`,NFC:Mc,NFD:Nc,NFKC:Pc,NFKD:Fc},{name:`string.normalize`}),Lc=Y(Je,`a well-formed numeric string`),Rc=J.module({root:Lc,parse:G({in:Lc,morphs:e=>Number.parseFloat(e),declaredOut:q.number})},{name:`string.numeric`}),zc=`a regex pattern`,Bc=G({domain:`string`,predicate:{meta:zc,predicate:(e,t)=>{try{return new RegExp(e),!0}catch(e){return t.reject({code:`predicate`,expected:zc,problem:String(e)})}}},meta:{format:`regex`}}),Vc=Y(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*))*))?(?:\+([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?$/,`a semantic version (see https://semver.org/)`),Hc=Y(/^\S.*\S$|^\S?$/,`trimmed`),Uc=J.module({root:G({in:`string`,morphs:e=>e.trim(),declaredOut:Hc}),preformatted:Hc},{name:`string.trim`}),Wc=Y(/^[A-Z]*$/,`only uppercase letters`),Gc=J.module({root:G({in:`string`,morphs:e=>e.toUpperCase(),declaredOut:Wc}),preformatted:Wc},{name:`string.upper`}),Kc=G({domain:`string`,predicate:{meta:`a URL string`,predicate:e=>URL.canParse(e)},meta:{format:`uri`}}),qc=J.module({root:Kc,parse:G({declaredIn:Kc,in:`string`,morphs:(e,t)=>{try{return new URL(e)}catch{return t.error(`a URL string`)}},declaredOut:G(URL)})},{name:`string.url`}),Jc=J.module({root:[`versioned | nil | max`,`@`,{description:`a UUID`,format:`uuid`}],"#nil":`'00000000-0000-0000-0000-000000000000'`,"#max":`'ffffffff-ffff-ffff-ffff-ffffffffffff'`,"#versioned":/[\da-f]{8}-[\da-f]{4}-[1-8][\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}/i,v1:Y(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,`a UUIDv1`),v2:Y(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,`a UUIDv2`),v3:Y(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,`a UUIDv3`),v4:Y(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,`a UUIDv4`),v5:Y(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,`a UUIDv5`),v6:Y(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,`a UUIDv6`),v7:Y(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,`a UUIDv7`),v8:Y(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,`a UUIDv8`)},{name:`string.uuid`}),Yc=J.module({root:q.string,alpha:Y(/^[A-Za-z]*$/,`only letters`),alphanumeric:Y(/^[\dA-Za-z]*$/,`only letters and digits 0-9`),hex:oc,base64:sc,capitalize:lc,creditCard:uc,date:_c,digits:Y(/^\d*$/,`only digits 0-9`),email:vc,integer:ac,ip:Sc,json:Ec,lower:Oc,normalize:Ic,numeric:Rc,regex:Bc,semver:Vc,trim:Uc,upper:Gc,url:qc,uuid:Jc},{name:`string`}),Xc=J.module({bigint:q.bigint,boolean:q.boolean,false:q.false,never:q.never,null:q.null,number:q.number,object:q.object,string:q.string,symbol:q.symbol,true:q.true,unknown:q.unknown,undefined:q.undefined}),Zc=J.module({root:q.unknown,any:q.unknown},{name:`unknown`}),Qc=J.module({root:q.jsonObject,stringify:Da(`morph`,{in:q.jsonObject,morphs:e=>JSON.stringify(e),declaredOut:q.string})},{name:`object.json`}),$c=J.module({root:q.object,json:Qc},{name:`object`}),el=class extends S{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'},tl=K([`K`,q.key],`V`)(e=>({domain:`object`,index:{signature:e.K,value:e.V}}),el),nl=class extends S{description='pick a set of properties from an object like `Pick(User, "name | age")`'},rl=K([`T`,q.object],[`K`,q.key])(e=>e.T.pick(e.K),nl),il=class extends S{description='omit a set of properties from an object like `Omit(User, "age")`'},al=K([`T`,q.object],[`K`,q.key])(e=>e.T.omit(e.K),il),ol=class extends S{description="make all named properties of an object optional like `Partial(User)`"},sl=K([`T`,q.object])(e=>e.T.partial(),ol),cl=class extends S{description="make all named properties of an object required like `Required(User)`"},ll=K([`T`,q.object])(e=>e.T.required(),cl),ul=class extends S{description='exclude branches of a union like `Exclude("boolean", "true")`'},dl=K(`T`,`U`)(e=>e.T.exclude(e.U),ul),fl=class extends S{description='extract branches of a union like `Extract("0 | false | 1", "number")`'},pl=K(`T`,`U`)(e=>e.T.extract(e.U),fl),ml=J.module({Exclude:dl,Extract:pl,Omit:al,Partial:sl,Pick:rl,Record:tl,Required:ll}),Q=Hs({...Xc,...ml,...ec,...Gs,string:Yc,number:rc,object:$c,unknown:Zc},{prereducedAliases:!0,name:`ark`}),$=Q.export();Object.assign(Bs.ambient,$),Bs.typeAttachments={string:$.string.root,number:$.number.root,bigint:$.bigint,boolean:$.boolean,symbol:$.symbol,undefined:$.undefined,null:$.null,object:$.object.root,unknown:$.unknown.root,false:$.false,true:$.true,never:$.never,arrayIndex:$.Array.index,Key:$.Key,Record:$.Record,Array:$.Array.root,Date:$.Date};var hl=Object.assign(Q.type,Bs.typeAttachments);Q.match,Q.fn,Q.generic,Q.schema,Q.define,Q.declare;export{hl as t};