@tslite/parser 1.9.0 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/LICENSE +55 -0
  2. package/NOTICE +14 -0
  3. package/dist/_namespaces/ts.d.ts +18 -0
  4. package/dist/_namespaces/ts.js +21 -0
  5. package/dist/_namespaces/ts.performance.d.ts +1 -0
  6. package/dist/_namespaces/ts.performance.js +2 -0
  7. package/dist/core.d.ts +450 -0
  8. package/dist/core.js +1394 -0
  9. package/dist/corePublic.d.ts +62 -0
  10. package/dist/corePublic.js +31 -0
  11. package/dist/debug.d.ts +74 -0
  12. package/dist/debug.js +326 -0
  13. package/dist/diagnosticInformationMap.generated.d.ts +1435 -0
  14. package/dist/diagnosticInformationMap.generated.js +1441 -0
  15. package/dist/factory.d.ts +78 -0
  16. package/dist/factory.js +622 -0
  17. package/dist/factoryPublic.d.ts +314 -0
  18. package/dist/factoryPublic.js +1796 -0
  19. package/dist/index.d.ts +1 -249
  20. package/dist/index.js +4 -6
  21. package/dist/parser.d.ts +59 -0
  22. package/dist/parser.js +5075 -0
  23. package/dist/path.d.ts +312 -0
  24. package/dist/path.js +475 -0
  25. package/dist/perfLogger.d.ts +4 -0
  26. package/dist/perfLogger.js +38 -0
  27. package/dist/performance.d.ts +20 -0
  28. package/dist/performance.js +49 -0
  29. package/dist/performanceTimestamp.d.ts +2 -0
  30. package/dist/performanceTimestamp.js +2 -0
  31. package/dist/scanner.d.ts +80 -0
  32. package/dist/scanner.js +1984 -0
  33. package/dist/shims/mapShim.d.ts +23 -0
  34. package/dist/shims/mapShim.js +156 -0
  35. package/dist/types.d.ts +2626 -0
  36. package/dist/types.js +1074 -0
  37. package/dist/utilities.d.ts +473 -0
  38. package/dist/utilities.js +2632 -0
  39. package/dist/utilitiesPublic.d.ts +274 -0
  40. package/dist/utilitiesPublic.js +1049 -0
  41. package/dist/visitor.d.ts +15 -0
  42. package/dist/visitor.js +64 -0
  43. package/dist/visitorPublic.d.ts +82 -0
  44. package/dist/visitorPublic.js +352 -0
  45. package/package.json +14 -42
  46. package/dist/index.cjs +0 -6
  47. package/dist/index.d.cts +0 -249
package/dist/index.d.ts CHANGED
@@ -1,249 +1 @@
1
- import { TSLiteError, types } from '@tslite/ast';
2
-
3
- /** Code dos erros lançados pelo parser/tokenizer. */
4
- type ParserErrorCode = "lex-error" | "parse-error";
5
- /** Posição num ponto da fonte (linha 1-based, coluna 0-based). */
6
- interface Position {
7
- readonly line: number;
8
- readonly column: number;
9
- }
10
- /** Intervalo de posições de um token/nó. */
11
- interface SourceLocation {
12
- readonly start: Position;
13
- readonly end: Position;
14
- }
15
- type TokenType = "Identifier" | "Keyword" | "Number" | "String" | "Template" | "TemplateHead" | "TemplateMiddle" | "TemplateTail" | "Punctuator" | "JSXText" | "Unknown" | "EOF";
16
- interface Token {
17
- readonly type: TokenType;
18
- /** O lexema cru, como aparece na fonte (sem decodificar escapes). */
19
- readonly value: string;
20
- /** Offset absoluto de início (inclusivo) e fim (exclusivo). */
21
- readonly start: number;
22
- readonly end: number;
23
- readonly loc: SourceLocation;
24
- }
25
- /**
26
- * Um comentário coletado. É TRIVIA — o parser não o vê como `Token` (não muda a
27
- * gramática); vai por um canal LATERAL (`onComment`), no modelo do acorn. O
28
- * `value` é o texto SEM os delimitadores (ESTree): `// foo` → `" foo"`, e o bloco com
29
- * ` foo ` entre os delimitadores → `" foo "`. Carrega `start`/`end`/`loc` como os nós do
30
- * parser.
31
- */
32
- interface CommentToken {
33
- readonly type: "Line" | "Block";
34
- readonly value: string;
35
- readonly start: number;
36
- readonly end: number;
37
- readonly loc: SourceLocation;
38
- }
39
- /** Coletor de comentários passado ao `tokenize` (canal lateral, opt-in). */
40
- type OnComment = (comment: CommentToken) => void;
41
- /**
42
- * Um erro de léxico como DADO (o `onError` do scanner do tsc, que também não
43
- * lança). Mesma forma que o `ParseDiagnostic` do parser, para viajarem juntos.
44
- */
45
- interface LexDiagnostic {
46
- readonly message: string;
47
- readonly position: Position;
48
- readonly index: number;
49
- readonly loc: SourceLocation;
50
- readonly end: number;
51
- }
52
- /**
53
- * Coletor de erros de léxico (opt-in). PRESENTE → o tokenizer RECUPERA (emite um
54
- * token `Unknown`, ou o token parcial, e segue), como o scanner do tsc. AUSENTE →
55
- * o tokenizer LANÇA `LexError` no primeiro erro (o contrato estrito de sempre).
56
- */
57
- type OnLexError = (diagnostic: LexDiagnostic) => void;
58
- /** Erro de léxico, com a posição onde ocorreu. */
59
- declare class LexError extends TSLiteError<"lex-error"> {
60
- readonly position: Position;
61
- readonly index: number;
62
- /**
63
- * RANGE do caractere culpado (mínimo: 1 char) — para o editor sublinhar em
64
- * vez de marcar um ponto. `position`/`index` seguem sendo o início (compat).
65
- */
66
- readonly loc?: SourceLocation | undefined;
67
- /** Offset absoluto do fim (exclusivo). */
68
- readonly end?: number | undefined;
69
- constructor(message: string, position: Position, index: number,
70
- /**
71
- * RANGE do caractere culpado (mínimo: 1 char) — para o editor sublinhar em
72
- * vez de marcar um ponto. `position`/`index` seguem sendo o início (compat).
73
- */
74
- loc?: SourceLocation | undefined,
75
- /** Offset absoluto do fim (exclusivo). */
76
- end?: number | undefined);
77
- }
78
- /** Palavras reservadas. As permitidas e as proibidas — o parser decide. */
79
- declare const KEYWORDS: Set<string>;
80
- /**
81
- * Tokeniza a fonte. Devolve a lista de tokens, terminada por um `EOF`.
82
- *
83
- * `onComment` (opcional) recebe cada comentário conforme é pulado — canal
84
- * lateral, sem entrar no stream de tokens.
85
- *
86
- * `onError` (opcional) liga a RECUPERAÇÃO: com ele, um erro de léxico é
87
- * REGISTRADO (não lançado) e o tokenizer segue — char inesperado vira token
88
- * `Unknown`, string/template/número mal-formados viram o token parcial. Sem ele,
89
- * o comportamento é o estrito de sempre: o primeiro erro **lança** `LexError`.
90
- */
91
- declare function tokenize(source: string, onComment?: OnComment, onError?: OnLexError): Token[];
92
-
93
- /** Erro de sintaxe, com a posição onde ocorreu. */
94
- declare class ParseError extends TSLiteError<"parse-error"> {
95
- readonly position: Position;
96
- readonly index: number;
97
- /**
98
- * O RANGE completo do token culpado (`start`+`end`) — o que um editor precisa
99
- * para SUBLINHAR o trecho, em vez de marcar um ponto. `position`/`index`
100
- * seguem sendo o início (compat).
101
- */
102
- readonly loc?: SourceLocation | undefined;
103
- /** Offset absoluto do fim (exclusivo) do token culpado. */
104
- readonly end?: number | undefined;
105
- constructor(message: string, position: Position, index: number,
106
- /**
107
- * O RANGE completo do token culpado (`start`+`end`) — o que um editor precisa
108
- * para SUBLINHAR o trecho, em vez de marcar um ponto. `position`/`index`
109
- * seguem sendo o início (compat).
110
- */
111
- loc?: SourceLocation | undefined,
112
- /** Offset absoluto do fim (exclusivo) do token culpado. */
113
- end?: number | undefined);
114
- }
115
- /**
116
- * Um erro de sintaxe como **DADO** (não exceção) — o modelo do tsc, cujo parser
117
- * não lança: ele empurra em `parseDiagnostics` e segue (`parser.ts:2149`). Carrega
118
- * o mesmo que o `ParseError`, para que o parse estrito possa relançá-lo idêntico.
119
- */
120
- interface ParseDiagnostic {
121
- /** De qual fase veio — o `parse` estrito relança a classe certa, e o editor
122
- * distingue as duas. */
123
- readonly code: ParserErrorCode;
124
- readonly message: string;
125
- readonly position: Position;
126
- readonly index: number;
127
- readonly loc: SourceLocation;
128
- readonly end: number;
129
- }
130
- /**
131
- * O nó é FALTANTE (sintético, criado na recuperação de erro)? Marcado pela própria
132
- * posição — largura zero —, exatamente como o `nodeIsMissing` do tsc
133
- * (`utilities.ts:1079`: `node.pos === node.end`). Um buraco no texto vira um nó
134
- * bem-formado de largura zero, em vez de derrubar a árvore inteira.
135
- */
136
- declare const nodeIsMissing: (node: unknown) => boolean;
137
- /** O resultado do parse TOLERANTE: a árvore (talvez com buracos) + os erros. */
138
- interface ParseResult {
139
- /** A árvore. `undefined` só quando nem o léxico passou (erro de `tokenize`). */
140
- readonly ast: types.Program | undefined;
141
- /** Os erros de sintaxe como DADO, em ordem de ocorrência. */
142
- readonly diagnostics: readonly ParseDiagnostic[];
143
- }
144
- /**
145
- * Parse **tolerante**: nunca lança por erro de sintaxe. Devolve a árvore — com
146
- * nós FALTANTES (largura zero, ver {@link nodeIsMissing}) onde o texto tinha
147
- * buracos — e os diagnósticos ao lado. É o que um EDITOR consome: completion e
148
- * hover precisam de árvore justamente enquanto o código está incompleto.
149
- *
150
- * É o modo único do tsc (o parser dele nunca lança); aqui ele convive com o
151
- * {@link parse} estrito, que é o contrato de quem VALIDA.
152
- */
153
- declare function parseTolerant(source: string): ParseResult;
154
- /**
155
- * Faz o parse de uma fonte completa num `Program` (ESTree, com `loc`).
156
- *
157
- * Contrato **estrito** (o de sempre): o primeiro erro de sintaxe **lança**. Quem
158
- * valida quer tudo-ou-nada — rodar o checker sobre uma árvore com buracos só
159
- * produziria cascata. Quem precisa da árvore parcial usa o {@link parseTolerant}.
160
- */
161
- declare function parse(source: string): types.Program;
162
- /**
163
- * Conveniência: faz o parse de uma **única expressão** (ex.: célula de regra).
164
- * Entra direto na gramática de expressão — então `{ … }` é objeto, não bloco.
165
- */
166
- declare function parseExpression(source: string): types.Expression;
167
- /**
168
- * Parse **tolerante** de uma única expressão: o par de {@link parseExpression} que
169
- * o {@link parseTolerant} é de `parse`. Nunca lança por sintaxe — devolve o nó (com
170
- * buracos de largura zero onde faltava) + os diagnósticos ao lado. Um `!eof` vira
171
- * diagnóstico (`Unexpected token after expression`), não exceção.
172
- *
173
- * Existe porque um consumidor de expressão (o editor, o `@tslite/template`) precisa
174
- * do mesmo contrato tolerante que o `parseTolerant` dá pra Program — sem ele, só o
175
- * `parseExpression` estrito, que lança e perde o resto.
176
- */
177
- declare function parseExpressionTolerant(source: string): {
178
- readonly ast: types.Expression | undefined;
179
- readonly diagnostics: readonly ParseDiagnostic[];
180
- };
181
-
182
- /** O mínimo que o algoritmo precisa de um nó: posição e os baldes de comentário. */
183
- interface Positioned {
184
- type: string;
185
- start: number;
186
- end: number;
187
- loc: {
188
- start: {
189
- line: number;
190
- };
191
- end: {
192
- line: number;
193
- };
194
- };
195
- leadingComments?: CommentToken[];
196
- trailingComments?: CommentToken[];
197
- innerComments?: CommentToken[];
198
- [key: string]: unknown;
199
- }
200
- /**
201
- * Ancora os `comments` (a lista lateral do `Program`, em ordem de fonte) aos nós
202
- * de `root`. Mutação IN-PLACE: adiciona `leadingComments`/`trailingComments`/
203
- * `innerComments` onde couber. A lista `Program.comments` é preservada (é o
204
- * índice canônico ESTree); o attach só acrescenta referências nos nós.
205
- *
206
- * `source` é consultada só para o caso `remaining` (comentário encravado entre
207
- * dois nós na mesma linha): o próximo caractere real decide de que lado ele está.
208
- */
209
- declare function attachComments(root: Positioned, comments: readonly CommentToken[], source?: string): void;
210
-
211
- /** Schema cru (espelha o `Schema` de @tslite/checker; aqui é POJO). */
212
- type TSchema = {
213
- t: string;
214
- [k: string]: unknown;
215
- };
216
- /**
217
- * Uma REFERÊNCIA a tipo nomeado, com posição — a tabela lateral que permite
218
- * "ir para a definição" e hover sobre um nome de tipo.
219
- *
220
- * Por que lateral e não `loc` no `Schema`: o `Schema` é dado imutável e os caches
221
- * do `@tslite/types` são **por referência** (TC17). Pendurar posição faria dois tipos
222
- * estruturalmente iguais passarem a diferir, quebrando dedup e cache em silêncio.
223
- * Mesmo movimento do overlay: informação AO LADO, não dentro.
224
- */
225
- type TypeRef = {
226
- /** O nome como foi escrito — qualificado, se foi (`state.Config`). */
227
- readonly name: string;
228
- readonly loc: SourceLocation;
229
- /** Os argumentos de tipo escritos (`F<number, string>` → dois `Schema`; `F` → `[]`).
230
- * É o que deixa o checker cobrar aridade e bound na referência (TS2314/TS2344). */
231
- readonly args: readonly TSchema[];
232
- /** O namespace em que a referência foi escrita (`"app.router"`), ausente no topo. Um
233
- * nome resolve primeiro nele e depois nos de fora — o `resolveName` do tsc subindo os
234
- * contêineres —, e quem resolve é o checker. */
235
- readonly namespace?: string;
236
- /** Cada segmento de um nome qualificado, com a posição dele (`state.Config` → `state`
237
- * e `Config`), ausente num nome simples. O erro de um nome qualificado pousa no
238
- * segmento que falhou: o namespace que não existe (TS2503) ou o membro que ele não tem
239
- * (TS2694). */
240
- readonly segments?: readonly {
241
- readonly name: string;
242
- readonly loc: SourceLocation;
243
- }[];
244
- };
245
-
246
- /** A versão deste package, a do módulo de fato carregado. */
247
- declare const version = "1.9.0";
248
-
249
- export { type CommentToken, KEYWORDS, type LexDiagnostic, LexError, type OnComment, type OnLexError, type ParseDiagnostic, ParseError, type ParseResult, type ParserErrorCode, type Position, type SourceLocation, type Token, type TokenType, type TypeRef, attachComments, nodeIsMissing, parse, parseExpression, parseExpressionTolerant, parseTolerant, tokenize, version };
1
+ export * from "./_namespaces/ts.js";
package/dist/index.js CHANGED
@@ -1,6 +1,4 @@
1
- import {TSLiteError}from'@tslite/ast';var ie=class extends TSLiteError{constructor(s,a,y,m,E){super("lex-error",`${s} (${a.line}:${a.column})`,{position:a,index:y,loc:m,end:E});this.position=a;this.index=y;this.loc=m;this.end=E;this.name="LexError";}},qe=new Set(["const","if","else","return","async","await","true","false","null","typeof","let","var","function","class","new","for","while","do","this","throw","try","catch","finally","switch","case","break","continue","default","void","delete","instanceof","in","yield","import","export","extends","super","debugger","with","enum","interface"]),Rt=["...","===","!==","=>","?.","??=","&&=","||=","**=","??","==","!=","<=",">=","&&","||","|","&","++","--","+=","-=","*=","/=","%=","**","<<","+","-","*","/","%","<",">","!","?",":",".",",",";","=","^","~","(",")","[","]","{","}"],be=n=>n>="a"&&n<="z"||n>="A"&&n<="Z"||n==="_"||n==="$",ve=n=>be(n)||n>="0"&&n<="9",ae=n=>n>="0"&&n<="9",Ve=n=>ae(n)||n>="a"&&n<="f"||n>="A"&&n<="F",Lt=n=>ve(n)||n==="-",ye=n=>n===`
2
- `||n==="\r"||n==="\u2028"||n==="\u2029",Te=(n,c)=>{let s=c;for(;;){let a=n[s]??"";if(a===" "||a===" "||a==="\f"||a==="\v"||ye(a))s++;else if(a==="/"&&n[s+1]==="/")for(s+=2;s<n.length&&!ye(n[s]??"");)s++;else if(a==="/"&&n[s+1]==="*"){for(s+=2;s<n.length&&!(n[s]==="*"&&n[s+1]==="/");)s++;s+=2;}else return s}},jt=(n,c)=>{if(!be(n[c]??""))return c;let s=c+1;for(;ve(n[s]??"");)s++;return s},Ge=(n,c,s)=>n.startsWith(s,c)&&!ve(n[c+s.length]??""),At=(n,c)=>{let s=Te(n,c);Ge(n,s,"const")&&(s=Te(n,s+5));let a=jt(n,s);if(a===s)return false;if(s=Te(n,a),Ge(n,s,"extends")){let y=Te(n,s+7),m=n[y]??"";return !(m==="="||m===">"||m==="/")}return n[s]===","?true:n[s]==="="&&n[s+1]!==">"},Ot=new Set(["(","[","{",",",";",":","?","=>","...","=","+","-","*","/","%","<","<=",">",">=","==","===","!=","!==","&&","||","??","!","+=","-=","*=","/=","%=","??=","&&=","||=","**="]),Dt=new Set(["return","typeof","await","delete","void","in","instanceof","else","case","yield","throw"]);function Jt(n,c,s){return Ie(n,c,s).scan()}function Ie(n,c,s){let a=[],y=0,m=1,E=0,X=()=>({line:m,column:E}),h=(k=0)=>n[y+k]??"",_=k=>{let x=X(),K={start:x,end:{line:m,column:E+1}};if(s){s({message:k,position:x,index:y,loc:K,end:y+1});return}throw new ie(k,x,y,K,y+1)},P=()=>{let k=n[y++];return k==="\r"?(n[y]===`
3
- `&&y++,m++,E=0):k===`
4
- `||k==="\u2028"||k==="\u2029"?(m++,E=0):E++,k},W=()=>{for(;;){let k=h();if(k===" "||k===" "||k==="\f"||k==="\v"||ye(k))P();else if(k==="/"&&h(1)==="/"){let x=y,K=X();P(),P();let i=y;for(;y<n.length&&!ye(h());)P();c?.({type:"Line",value:n.slice(i,y),start:x,end:y,loc:{start:K,end:X()}});}else if(k==="/"&&h(1)==="*"){let x=y,K=X();P(),P();let i=y,p=y;for(;;){if(y>=n.length){_("Unterminated block comment"),p=y;break}if(h()==="*"&&h(1)==="/"){p=y,P(),P();break}P();}c?.({type:"Block",value:n.slice(i,p),start:x,end:y,loc:{start:K,end:X()}});}else break}},A=(k,x,K,i)=>{a.push({type:k,value:x,start:K,end:y,loc:{start:i,end:X()}}),u=k==="Punctuator"?Ot.has(x):k==="Keyword"?Dt.has(x):k==="TemplateHead"||k==="TemplateMiddle";},Q=k=>{for(P();y<n.length;){let x=h();if(x===k)return P(),n.slice(C,y);if(ye(x))return _("Unterminated string literal"),n.slice(C,y);if(x==="\\"){if(P(),y>=n.length)return _("Unterminated string literal"),n.slice(C,y);P();continue}P();}return _("Unterminated string literal"),n.slice(C,y)},v=()=>{if(h()==="0"&&(h(1)==="x"||h(1)==="X")){if(P(),P(),!Ve(h()))return _("Invalid hexadecimal literal");for(;Ve(h());)P();return}if(h()==="0"&&(h(1)==="b"||h(1)==="B")){if(P(),P(),h()!=="0"&&h()!=="1")return _("Invalid binary literal");for(;h()==="0"||h()==="1";)P();return}if(h()==="0"&&(h(1)==="o"||h(1)==="O")){if(P(),P(),!(h()>="0"&&h()<="7"))return _("Invalid octal literal");for(;h()>="0"&&h()<="7";)P();return}for(;ae(h());)P();if(h()===".")for(P();ae(h());)P();if(h()==="e"||h()==="E"){if(P(),(h()==="+"||h()==="-")&&P(),!ae(h()))return _("Invalid exponent");for(;ae(h());)P();}},o=()=>{let k=y;for(;y<n.length;){let x=h();if(x==="`"){let K=n.slice(k,y);return P(),{raw:K,interp:false}}if(x==="$"&&h(1)==="{"){let K=n.slice(k,y);return P(),P(),{raw:K,interp:true}}if(x==="\\"){if(P(),y>=n.length)break;P();continue}P();}return _("Unterminated template literal"),{raw:n.slice(k,y),interp:false}},C=0,G=0,$=[],u=true,w="js",B=[],j=[],Y=new Map,ee=-1,re=()=>({i:y,line:m,col:E,mode:w,braceDepth:G,tmplStack:[...$],jsxParent:[...B],jsxExpr:j.map(k=>({...k}))}),N=k=>{y=k.i,m=k.line,E=k.col,w=k.mode,G=k.braceDepth,$=[...k.tmplStack],B=[...k.jsxParent],j=k.jsxExpr.map(x=>({...x}));},O=()=>(a=[],g(),a),g=()=>{for(;;){if(w==="jsxChildren"){C=y;let i=X();if(y>=n.length){A("EOF","",C,i);break}let p=h();if(p==="<"){h(1)==="/"?(P(),P(),A("Punctuator","</",C,i),w="jsxCloseTag"):(P(),A("Punctuator","<",C,i),B.push("jsxChildren"),w="jsxOpenTag");continue}if(p==="{"){P(),A("Punctuator","{",C,i),j.push({level:G,restore:"jsxChildren"}),w="js";continue}for(;y<n.length&&h()!=="<"&&h()!=="{";)P();A("JSXText",n.slice(C,y),C,i);continue}if(w==="jsxOpenTag"||w==="jsxCloseTag"){W(),C=y;let i=X();if(y>=n.length){A("EOF","",C,i);break}let p=h();if(be(p)){for(P();Lt(h());)P();A("Identifier",n.slice(C,y),C,i);continue}if(p==="/"&&h(1)===">"){P(),P(),A("Punctuator","/>",C,i),w=B.pop()??"js";continue}if(p===">"){P(),A("Punctuator",">",C,i),w=w==="jsxCloseTag"?B.pop()??"js":"jsxChildren";continue}if(p==="{"){P(),A("Punctuator","{",C,i),j.push({level:G,restore:w}),w="js";continue}if(p==='"'||p==="'"){A("String",Q(p),C,i);continue}if(p==="="||p==="."||p===":"){P(),A("Punctuator",p,C,i);continue}if(p==="<"&&w==="jsxOpenTag"){P(),A("Punctuator","<",C,i),B.push("jsxOpenTag");continue}_(`Unexpected character '${p}' in JSX tag`),P(),A("Unknown",p,C,i);continue}W(),C=y;let k=X();if(y>=n.length){A("EOF","",C,k);break}let x=h();if(be(x)){for(;ve(h());)P();let i=n.slice(C,y);A(qe.has(i)?"Keyword":"Identifier",i,C,k);continue}if(ae(x)||x==="."&&ae(h(1))){v(),A("Number",n.slice(C,y),C,k);continue}if(x==='"'||x==="'"){let i=Q(x);A("String",i,C,k);continue}if(x==="`"){P();let{raw:i,interp:p}=o();p?(A("TemplateHead",i,C,k),$.push(G)):A("Template",i,C,k);continue}if(x==="<"&&y===ee){ee=-1,P(),A("Punctuator","<",C,k);continue}if(x==="<"&&u&&!At(n,y+1)){Y.set(y,re()),P(),A("Punctuator","<",C,k),B.push("js"),w="jsxOpenTag";continue}if(x==="{"){P(),A("Punctuator","{",C,k),G++;continue}if(x==="}"){if($.length>0&&G===$[$.length-1]){$.pop(),P();let{raw:i,interp:p}=o();A(p?"TemplateMiddle":"TemplateTail",i,C,k),p&&$.push(G);continue}if(j.length>0&&G===j[j.length-1].level){let{restore:i}=j.pop();P(),A("Punctuator","}",C,k),w=i;continue}P(),A("Punctuator","}",C,k),G--;continue}if(x==="?"&&h(1)==="."&&ae(h(2))){P(),A("Punctuator","?",C,k);continue}let K=Rt.find(i=>n.startsWith(i,y));if(K){for(let i=0;i<K.length;i++)P();A("Punctuator",K,C,k);continue}_(`Unexpected character '${x}'`),P(),A("Unknown",x,C,k);}};return {scan:O,opensJsx:k=>Y.has(k),rescanLessThan:k=>{let x=Y.get(k);return x?(N(x),ee=k,O()):null}}}var Ft=new Set(["leadingComments","trailingComments","innerComments","comments"]),ze=n=>typeof n=="object"&&n!==null&&typeof n.type=="string"&&n.loc!=null&&typeof n.start=="number",We=new WeakMap;function Xt(n){let c=We.get(n);if(c)return c;let s=[];for(let a of Object.keys(n)){if(Ft.has(a))continue;let y=n[a];if(ze(y))s.push(y);else if(Array.isArray(y))for(let m of y)ze(m)&&s.push(m);}return s.sort((a,y)=>a.start-y.start),We.set(n,s),s}function Kt(n,c){let s=n,a,y;for(;;){let m=Xt(s);a=void 0,y=void 0;let E;for(let X of m){if(X.start<=c.start&&c.end<=X.end){E=X;break}if(X.end<=c.start)a=X;else if(c.end<=X.start){y=X;break}}if(!E)break;s=E;}return {enclosing:s,preceding:a,following:y}}var Ce=(n,c)=>{(n.leadingComments??(n.leadingComments=[])).push(c);},xe=(n,c)=>{(n.trailingComments??(n.trailingComments=[])).push(c);},Re=(n,c)=>{(n.innerComments??(n.innerComments=[])).push(c);};function Mt(n,c){for(let s=c;s<n.length;s++){let a=n[s];if(a!==" "&&a!==" "&&a!=="\r"&&a!==`
5
- `&&a!=="\f")return a}return ""}var Ut=new Set([")","]","}",","]);function Le(n,c,s=""){for(let a of c){let{enclosing:y,preceding:m,following:E}=Kt(n,a),X=m==null||m.loc.end.line<a.loc.start.line,h=!X&&(E==null||a.loc.end.line<E.loc.start.line);if(X)E?Ce(E,a):m?xe(m,a):Re(y,a);else if(h)m?xe(m,a):E?Ce(E,a):Re(y,a);else {let _=Ut.has(Mt(s,a.end));m&&_?xe(m,a):E?Ce(E,a):m?xe(m,a):Re(y,a);}}}var $t=Object.prototype.hasOwnProperty,Se=(n,c)=>$t.call(n,c)?n[c]:void 0;function He(n,c,s){c==="__proto__"?Object.defineProperty(n,c,{value:s,enumerable:true,writable:true,configurable:true}):n[c]=s;}var Bt=(n=[])=>({vars:new Set(n),bounds:new Map,noCond:false,inferSink:null}),ue=(n,c)=>{let s=new Set(n.vars),a=new Map(n.bounds);for(let y of c)s.add(y.name),y.bound?a.set(y.name,{bound:y.bound}):a.delete(y.name);return {vars:s,bounds:a,noCond:n.noCond,inferSink:n.inferSink}},je=n=>({t:"var",name:n.name,...n.bound?{bound:n.bound}:{},...n.default?{default:n.default}:{}}),_t=(n,c)=>{let s=n.bounds.get(c)?.bound;return s?{t:"var",name:c,bound:s}:{t:"var",name:c}},Qe=n=>{let{peek:c,next:s,isP:a,isK:y,expectP:m,fail:E,unescape:X}=n,h=(i,p)=>{let d=n.tokens[n.pos()-1]??p;return Object.assign(i,{start:p.start,end:d.end,loc:{start:p.loc.start,end:d.loc.end}})},_=()=>{let i=n.pos(),p=n.tokens[i],d=n.tokens[i-1];return !!d&&!!p&&p.loc.start.line>d.loc.end.line},P=()=>{let i=b=>n.tokens[n.pos()+b],p=(b,...S)=>b?.type==="Punctuator"&&S.includes(b.value),d=i(1);if(p(d,")","..."))return true;if(d?.type!=="Identifier")return false;let T=i(2);return p(T,":",",","?","=")?true:p(T,")")&&p(i(3),"=>")},W=()=>{let i=n.tokens,p=[],d=0,T=false;for(let b=n.pos();b<i.length;b++){let S=i[b];if(S.type==="EOF")break;if(S.type==="Punctuator"){if(S.value==="<")d++,d===1&&(T=true);else if(S.value===">"){if(d--,d===0)break}else S.value==="("||S.value==="["||S.value==="{"?(d++,T=false):S.value===")"||S.value==="]"||S.value==="}"?(d--,T=false):S.value===","&&d===1?T=true:T=false;continue}if(d===1&&T){if(S.type==="Keyword"&&S.value==="const")continue;if(S.type==="Identifier"){p.push(S.value),T=false;continue}}T=false;}return p},A=i=>{let p=ue(i,W().map(T=>({name:T})));m("<");let d=[];for(;!a(">");){let T=c();y("const")&&E("'const' type parameters are not supported in this language; a constraint keeps the literal: '<T extends string>'");let b=c();b.type!=="Identifier"&&E("Expected type parameter name"),s();let S,D;if(y("extends")){s();let I=o(p);S=I.schema,D=I.node;}let F,M;if(a("=")){s();let I=o(p);F=I.schema,M=I.node;}d.push(h({type:"TSTypeParameter",name:b.value,...S?{bound:S}:{},...D?{boundNode:D}:{},...F?{default:F}:{},...M?{defaultNode:M}:{}},T)),a(">")||m(",");}return m(">"),d},Q=i=>{n.splitShiftLeft(),m("<");let p=[];for(;!a(">");)p.push(o(i)),a(">")||m(",");return m(">"),p},v=i=>{let p=c();return p.type==="Identifier"&&p.value===i},o=i=>{let p=c(),d=C(i);if(i.noCond||!y("extends")||_())return d;s();let T=[],b=C({...i,noCond:true,inferSink:T});m("?");let S=ue(i,T.map(M=>({name:M}))),D=o(S);m(":");let F=o(S);return {node:h({type:"TSConditionalType",checkType:d.node,extendsType:b.node,trueType:D.node,falseType:F.node},p),schema:{t:"conditional",check:d.schema,extends:b.schema,then:D.schema,else:F.schema,...T.length?{infer:T.map(M=>je({name:M}))}:{}}}},C=i=>{let p=c();a("|")&&s();let d=G(i);if(!a("|"))return d;let T=[d.node],b=[d.schema];for(;a("|");){s();let S=G(i);T.push(S.node),b.push(S.schema);}return {node:h({type:"TSUnionType",types:T},p),schema:{t:"union",of:b}}},G=i=>{let p=c();a("&")&&s();let d=$(i);if(!a("&"))return d;let T=[d.node],b=[d.schema];for(;a("&");){s();let S=$(i);T.push(S.node),b.push(S.schema);}return {node:h({type:"TSIntersectionType",types:T},p),schema:{t:"intersection",of:b}}},$=i=>{let p=c();if(v("keyof")){s();let d=$(i);return {node:h({type:"TSTypeOperator",operator:"keyof",typeAnnotation:d.node},p),schema:{t:"keyof",of:d.schema}}}if(v("readonly")){s();let d=$(i);return d.schema.t!=="array"&&d.schema.t!=="tuple"&&E("'readonly' only applies to array and tuple types"),{node:h({...d.node,readonly:true},p),schema:{...d.schema,readonly:true}}}if(v("infer")){s();let d=c();d.type!=="Identifier"&&E("Expected 'infer' variable name"),s();let T=i.inferSink;return T?(T.push(d.value),{node:h({type:"TSInferType",name:d.value},p),schema:{t:"var",name:d.value}}):E("'infer' is only allowed in the 'extends' clause of a conditional")}return u(i)},u=i=>{let p=c(),d=Y(i);for(;a("[")&&!_();)if(s(),a("]"))s(),d={node:h({type:"TSArrayType",elementType:d.node},p),schema:{t:"array",items:d.schema}};else {let T=o(i);m("]"),d={node:h({type:"TSIndexedAccessType",objectType:d.node,indexType:T.node},p),schema:{t:"index",obj:d.schema,key:T.schema}};}return d},w=(i,p,d)=>({node:h({type:"TSKeywordType",kind:p},i),schema:d}),B=i=>{let p=n.namespace?.()??null;n.typeRefs?.push(p===null?i:{...i,namespace:p});},j=(i,p,d)=>{let T=[{name:i.value,loc:i.loc}];for(;a(".");){s();let I=c();I.type!=="Identifier"&&I.type!=="Keyword"&&E("Expected a name after '.' in a qualified type name"),s(),T.push({name:I.value,loc:I.loc});}let b=T.map(I=>I.name).join("."),S=a("<")||a("<<")?Q(d):[],D=S.map(I=>I.schema),F=h({type:"TSTypeReference",typeName:b,...S.length?{typeArguments:S.map(I=>I.node)}:{}},p),M=T[T.length-1];return B({name:b,loc:{start:i.loc.start,end:M.loc.end},args:D,segments:T}),{node:F,schema:{t:"apply",name:b,args:D}}},Y=i=>{let p=c();if(y("typeof")){s();let b=c();b.type!=="Identifier"&&E("Expected a name after 'typeof' in type position"),s();let S=[b.value];for(;a(".");){s();let D=c();D.type!=="Identifier"&&D.type!=="Keyword"&&E("Expected a property name after '.' in 'typeof'"),s(),S.push(D.value);}return {node:h({type:"TSTypeQuery",exprName:S},p),schema:{t:"typeQuery",path:S}}}if(a("<")){n.rescanTypeLessThan();let b=A(i),S=ue(i,b);return N(S,p,b)}if(a("(")){if(P())return N(i,p);s();let b=o(i.noCond?{...i,noCond:false}:i);return m(")"),b}if(a("{"))return g()?k(i):x(i);if(a("["))return O(i);let d=c();if(d.type==="String"){s();let b=X(d.value.slice(1,-1));return {node:h({type:"TSLiteralType",literal:b},p),schema:{t:"literal",value:b}}}if(d.type==="Number"){s();let b=Number(d.value);return {node:h({type:"TSLiteralType",literal:b},p),schema:{t:"literal",value:b}}}if(y("true"))return s(),{node:h({type:"TSLiteralType",literal:true},p),schema:{t:"literal",value:true}};if(y("false"))return s(),{node:h({type:"TSLiteralType",literal:false},p),schema:{t:"literal",value:false}};if(y("null"))return s(),w(p,"null",{t:"null"});if(y("void"))return s(),w(p,"void",{t:"void"});if(d.type==="Identifier"){if(s(),a("."))return j(d,p,i);switch(d.value){case "string":return w(p,"string",{t:"string"});case "number":return w(p,"number",{t:"number"});case "boolean":return w(p,"boolean",{t:"boolean"});case "any":return w(p,"any",{t:"any"});case "unknown":return w(p,"unknown",{t:"unknown"});case "undefined":return w(p,"undefined",{t:"undefined"});case "never":return w(p,"never",{t:"union",of:[]});case "object":return w(p,"object",{t:"nonPrimitive"})}let b=a("<")||a("<<")?Q(i):[],S=b.map(M=>M.schema),D=b.length?b.map(M=>M.node):void 0,F=h({type:"TSTypeReference",typeName:d.value,...D?{typeArguments:D}:{}},p);return i.vars.has(d.value)&&S.length===0?{node:F,schema:_t(i,d.value)}:(B({name:d.value,loc:d.loc,args:S}),{node:F,schema:{t:"apply",name:d.value,args:S}})}n.recordError(`Expected a type but got '${d.value||d.type}'`,d);let T=n.createMissingNode({type:"TSTypeReference",typeName:""},d);return B({name:"",loc:T.loc,args:[]}),{node:T,schema:{t:"unknown"}}},ee=i=>{m("(");let p=[];for(;!a(")");){let d=c(),T=a("...");T&&s();let b=c();b.type!=="Identifier"&&E("Expected parameter name in function type"),s();let S=!T&&a("?");S&&s(),m(":");let D=o(i),F=h({type:"Identifier",name:b.value,typeAnnotationNode:D.node,...S?{optional:true}:{}},b);p.push({node:T?h({type:"RestElement",argument:F},d):F,schema:{name:b.value,type:D.schema,...S?{optional:true}:{},...T?{variadic:true}:{}}}),T&&!a(")")&&E("A rest parameter must be last in a parameter list"),a(")")||m(",");}return m(")"),p},re=(i,p)=>{let d=c(),T=n.tokens[n.pos()+1];if(!(d.type==="Identifier"&&T?.type==="Identifier"&&T.value==="is"))return o(i);let S=p.indexOf(d.value);S<0&&E(`Cannot find parameter '${d.value}' for the type predicate`),s(),s();let D=o(i);return {node:h({type:"TSTypePredicate",parameterName:d.value,typeAnnotation:D.node},d),schema:{t:"boolean"},guard:{param:S,type:D.schema}}},N=(i,p,d)=>{let T=ee(i);m("=>");let b=re(i,T.map(S=>S.schema.name));return {node:h({type:"TSFunctionType",params:T.map(S=>S.node),returnType:b.node,...d?.length?{typeParameters:[...d]}:{}},p),schema:{t:"fn",params:T.map(S=>S.schema),returns:b.schema,...b.guard?{guard:b.guard}:{},...d?.length?{typeParams:d.map(je)}:{}}}},O=i=>{let p=c();m("[");let d=[],T=[],b=[],S=[],D=()=>{let I=n.tokens[n.pos()],J=n.tokens[n.pos()+1],V=n.tokens[n.pos()+2];if(I?.type==="Identifier"&&J?.type==="Punctuator"&&(J.value===":"||J.value==="?"&&V?.type==="Punctuator"&&V.value===":"))return s(),I.value};for(;!a("]");){if(b[b.length-1]==="rest"&&E("A rest element must be last in a tuple type"),a("...")){s();let I=D();I!==void 0&&m(":"),S.push(I);let J=o(i);J.schema.t!=="array"&&E("A rest element type must be written as an array type ('...T[]')"),T.push(J.schema.items),d.push(J.node.elementType),b.push("rest");}else {let I=D(),J=false;I!==void 0&&(a("?")&&(s(),J=true),m(":")),S.push(I);let V=o(i);!J&&a("?")&&(s(),J=true),T.push(V.schema),d.push(V.node),b.push(J?"optional":"req");}a("]")||m(",");}m("]");let F=b.some(I=>I!=="req"),M=S.some(I=>I!==void 0);return {node:h({type:"TSTupleType",elementTypes:d,...F?{flags:b}:{},...M?{labels:S}:{}},p),schema:F?{t:"tuple",elements:T,flags:b}:{t:"tuple",elements:T}}},g=()=>{let i=n.tokens,p=n.pos()+1;return i[p]?.type==="Punctuator"&&(i[p]?.value==="+"||i[p]?.value==="-")&&(p++,!(i[p]?.type==="Identifier"&&i[p]?.value==="readonly"))?false:(i[p]?.type==="Identifier"&&i[p]?.value==="readonly"&&p++,i[p]?.type==="Punctuator"&&i[p]?.value==="["&&i[p+1]?.type==="Identifier"&&i[p+2]?.type==="Keyword"&&i[p+2]?.value==="in")},k=i=>{let p=c();m("{");let d=a("+")||a("-")?s().value:null,T;v("readonly")&&(s(),T=d==="+"?"+":d==="-"?"-":true),m("[");let b=c();b.type!=="Identifier"&&E("Expected mapped type key name"),s(),y("in")||E("Expected 'in' in mapped type"),s();let S=o(i);v("as")&&E("Key remapping ('as') in mapped types is not supported"),m("]");let D=a("+")||a("-")?s().value:null,F;D!==null&&!a("?")&&E("'?' expected"),a("?")&&(s(),F=D==="+"?"+":D==="-"?"-":true),m(":");let M=o(ue(i,[{name:b.value}]));return (a(";")||a(","))&&s(),m("}"),{node:h({type:"TSMappedType",key:b.value,constraint:S.node,typeAnnotation:M.node,...T!==void 0?{readonly:T}:{},...F!==void 0?{optional:F}:{}},p),schema:{t:"mapped",key:b.value,over:S.schema,body:M.schema,...F===true||F==="+"?{optional:true}:{},...F==="-"?{excludeOptional:true}:{},...T===true||T==="+"?{readonly:true}:{},...T==="-"?{excludeReadonly:true}:{}}}},x=i=>{let p=c();m("{");let d=[],T={},b,S=[];for(;!a("}");){let F=c(),M=v("readonly")&&n.tokens[n.pos()+1]?.value==="[";if(M&&s(),!M&&(a("(")||a("<"))){a("<")&&n.rescanTypeLessThan();let I=a("<")?A(i):[],J=I.length?ue(i,I):i,V=ee(J);m(":");let H=re(J,V.map(Z=>Z.schema.name));S.push({t:"fn",params:V.map(Z=>Z.schema),returns:H.schema,...H.guard?{guard:H.guard}:{},...I.length?{typeParams:I.map(je)}:{}}),d.push(h({type:"TSCallSignatureDeclaration",params:V.map(Z=>Z.node),returnType:H.node,...I.length?{typeParameters:I}:{}},F));}else if(a("[")){s(),c().type!=="Identifier"&&E("Expected index signature parameter name"),s(),m(":");let I=c();(I.type!=="Identifier"||I.value!=="string"&&I.value!=="number")&&E("Index signature parameter type must be 'string' or 'number'"),s(),m("]"),m(":");let J=o(i);b={key:I.value,value:J.schema,...M?{readonly:true}:{}},d.push(h({type:"TSIndexSignature",keyType:I.value,typeAnnotation:J.node,...M?{readonly:true}:{}},F));}else {let I=false;if(v("readonly")){let ce=n.tokens[n.pos()+1];ce&&(ce.type==="Identifier"||ce.type==="Keyword"||ce.type==="String"||ce.type==="Number")&&(s(),I=true);}let J=c(),V;if(J.type==="Identifier"||J.type==="Keyword")s(),V=J.value;else if(J.type==="String")s(),V=X(J.value.slice(1,-1));else if(J.type==="Number")s(),V=J.value;else return E("Expected property name in object type");let H=a("?");H&&s(),m(":");let Z=o(i);He(T,V,{type:Z.schema,...H?{optional:true}:{},...I?{readonly:true}:{}}),d.push(h({type:"TSPropertySignature",key:V,typeAnnotation:Z.node,...H?{optional:true}:{},...I?{readonly:true}:{}},F));}if(a(";")||a(","))s();else break}m("}");let D=h({type:"TSTypeLiteral",members:d},p);return S.length>0?Object.keys(T).length>0||b?E("Callable object types (call signatures mixed with members) are not supported"):{node:D,schema:S.length===1?S[0]:{t:"overload",signatures:S}}:{node:D,schema:{t:"object",props:T,...b?{index:b}:{}}}},K=Bt();return {parseType:()=>o(K),parseReturnType:i=>re(K,i),parseTypeParamList:()=>A(K),parseTypeInScope:i=>o(ue(K,i)),withTypeParams:(i,p)=>{let d=K;K=ue(d,i);try{return p()}finally{K=d;}}}};var le=class extends TSLiteError{constructor(s,a,y,m,E){super("parse-error",`${s} (${a.line}:${a.column})`,{position:a,index:y,loc:m,end:E});this.position=a;this.index=y;this.loc=m;this.end=E;this.name="ParseError";}},Gt=n=>{let c=n;return c!=null&&typeof c.start=="number"&&c.start===c.end&&c.start>=0},Ye=(n,c)=>Object.assign(n,{start:c.start,end:c.start,loc:{start:c.loc.start,end:c.loc.start}}),qt={"??":1,"||":2,"&&":3,"|":4,"^":5,"&":6,"==":7,"===":7,"!=":7,"!==":7,"<":8,"<=":8,">":8,">=":8,in:8,as:8,satisfies:8,"<<":9,">>":9,">>>":9,"+":10,"-":10,"*":11,"/":11,"%":11,"**":12},zt=new Set(["??","||","&&"]),Wt=new Set(["class","debugger","with","enum","interface"]),Ht={enum:'use a union of literals (`type T = "a" | "b"`) \u2014 it is serializable',interface:"use a type alias (`type X = { \u2026 }`)",module:"write it as `namespace X { \u2026 }` \u2014 the same declaration",declare:"declare the shape via the DI env, or with a `type` alias",abstract:"classes are not part of the language \u2014 model with objects + functions"},Qt={module:(n,c)=>n.type==="Identifier"&&c.type==="Punctuator"&&c.value==="{",declare:n=>n.type==="Keyword"&&["const","let","var","function","class","enum","interface"].includes(n.value)||n.type==="Identifier"&&["type","module"].includes(n.value),abstract:n=>n.type==="Keyword"&&n.value==="class"},Yt=new Set(["=","+=","-=","*=","/=","%=","**=","??=","&&=","||="]),Ze=(n,c)=>{let s=0;for(let a of n)c(a)&&(n[s++]=a);n.length=s;};function Ae(n){let c=[],s=[],a=[],y=Ie(n,e=>a.push(e),e=>c.push({code:"lex-error",...e})),m=y.scan(),E=0,X=[],h=e=>{for(;X.length>e;)X.pop()();},_=(e=E)=>{let t=m[e];if(t?.type!=="Punctuator"||t.value!=="<"||!y.opensJsx(t.start))return;let r=m.slice(e),l=c.slice(),f=a.slice();Ze(c,L=>L.code!=="lex-error"||L.index<t.start),Ze(a,L=>L.start<t.start);let R=y.rescanLessThan(t.start);m.splice(e,m.length-e,...R),X.push(()=>{m.splice(e,m.length-e,...r),c.splice(0,c.length,...l),a.splice(0,a.length,...f);});},P=()=>{let e=m[E];if(e?.type!=="Punctuator"||e.value!=="<<")return;let t={line:e.loc.start.line,column:e.loc.start.column+1},r=E;m.splice(r,1,{...e,value:"<",end:e.start+1,loc:{start:e.loc.start,end:t}},{...e,value:"<",start:e.start+1,loc:{start:t,end:e.loc.end}}),X.push(()=>m.splice(r,2,e));},W=[],A=[],Q=false,v=(e=0)=>m[Math.min(E+e,m.length-1)],o=()=>m[E++],C=()=>m[E-1],G=()=>{let e=m[E],t=m[E-1];return !!e&&!!t&&e.loc.start.line>t.loc.end.line},$=()=>v().type==="EOF",u=e=>v().type==="Punctuator"&&v().value===e,w=e=>v().type==="Keyword"&&v().value===e,B=e=>v().type==="Identifier"&&v().value===e,j=(e,t=v())=>{throw Y(e,t),new le(e,t.loc.start,t.start,t.loc,t.end)},Y=(e,t=v())=>{let r=c[c.length-1];r&&r.index===t.start||c.push({code:"parse-error",message:e,position:t.loc.start,index:t.start,loc:t.loc,end:t.end});},ee=(e,t)=>{s.push({code:"parse-error",message:e,position:t.loc.start,index:t.start,loc:t.loc,end:t.end});},re=()=>{c.length||c.push(...s),s.length=0;},N=e=>(u(e)||j(`Expected '${e}' but got '${v().value||v().type}'`),o()),O=(e,t)=>{let r=C()??t;return Object.assign(e,{start:t.start,end:r.end,loc:{start:t.loc.start,end:r.loc.end}})},g=(e,t,r)=>Object.assign(e,{start:t.start,end:r.end,loc:{start:t.loc.start,end:r.loc.end}}),k=e=>{let t="";for(let r=0;r<e.length;r++){if(e[r]!=="\\"){t+=e[r];continue}let l=e[++r];switch(l){case "n":t+=`
6
- `;break;case "t":t+=" ";break;case "r":t+="\r";break;case "b":t+="\b";break;case "f":t+="\f";break;case "v":t+="\v";break;case "0":t+="\0";break;case "x":t+=String.fromCharCode(parseInt(e.slice(r+1,r+3),16)),r+=2;break;case "u":if(e[r+1]==="{"){let f=e.indexOf("}",r);t+=String.fromCodePoint(parseInt(e.slice(r+2,f),16)),r=f;}else t+=String.fromCharCode(parseInt(e.slice(r+1,r+5),16)),r+=4;break;default:t+=l;}}return t},x=(e=false)=>K(e),K=(e=false)=>{let t=i(e),r=v();if(r.type==="Punctuator"&&Yt.has(r.value)){o();let l=K();return g({type:"AssignmentExpression",operator:r.value,left:t,right:l},t,l)}return t},i=(e=false)=>{let t=d(0,e);if(!u("?"))return t;o();let r=x();N(":");let l=x();return g({type:"ConditionalExpression",test:t,consequent:r,alternate:l},t,l)},p=()=>{let e=v();if(e.type==="Keyword")return e.value==="in"?{op:"in",consume:1}:null;if(e.type==="Identifier")return e.value==="as"?{op:"as",consume:1}:e.value==="satisfies"?{op:"satisfies",consume:1}:null;if(e.type!=="Punctuator")return null;if(e.value===">"){let t=v(1);if(t.type==="Punctuator"&&t.value===">"&&e.end===t.start){let r=v(2);return r.type==="Punctuator"&&r.value===">"&&t.end===r.start?{op:">>>",consume:3}:{op:">>",consume:2}}return {op:">",consume:1}}return {op:e.value,consume:1}},d=(e,t=false)=>{let r=T();for(;;){let l=p();if(!l)break;let{op:f,consume:R}=l;if(f==="in"&&t)break;let L=Se(qt,f);if(!L||L<=e)break;if(f==="satisfies"){if(G())break;j("'satisfies' is not supported in this language \u2014 a type annotation (`const x: T = \u2026`) also checks compatibility, but it declares the type as T, while 'satisfies' keeps the inferred one");}if(f==="as"){if(G())break;o();let U=ge();r=g({type:"TSAsExpression",expression:r,typeAnnotation:U.schema,typeAnnotationNode:U.node},r,C());continue}for(let U=0;U<R;U++)o();let q=d(f==="**"?L-1:L,t);r=g({type:zt.has(f)?"LogicalExpression":"BinaryExpression",operator:f,left:r,right:q},r,q);}return r},T=()=>{let e=v();return e.type==="Punctuator"&&(e.value==="++"||e.value==="--")?(o(),O({type:"UpdateExpression",operator:e.value,prefix:true,argument:T()},e)):w("await")?(o(),O({type:"AwaitExpression",argument:T()},e)):w("typeof")||w("void")||w("delete")||e.type==="Punctuator"&&(e.value==="!"||e.value==="-"||e.value==="+"||e.value==="~")?b(e):D()},b=e=>{o();let t=T();return u("**")&&j(`An unary expression with the '${e.value}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses.`),O({type:"UnaryExpression",operator:e.value,prefix:true,argument:t},e)},S=()=>{let e=E,t=X.length,r=c.length,l=W.length,f=()=>(h(t),E=e,c.length=r,W.length=l,void 0);try{if(P(),o(),u(">"))return f();let R=[];for(;R.push(ge().schema),!!u(",");)o();return u(">")?(o(),u("(")?R:f()):f()}catch{return f()}},D=()=>{let e=pt(),t=false;for(;;)if((v().type==="Template"||v().type==="TemplateHead")&&j("Tagged templates are not supported in this language"),u("?."))if(o(),t=true,u("(")){let{args:r,close:l}=F();e=g({type:"CallExpression",callee:e,arguments:r,optional:true},e,l);}else if(u("[")){o();let r=x(),l=N("]");e=g({type:"MemberExpression",object:e,property:r,computed:true,optional:true},e,l);}else {let r=v();r.type!=="Identifier"&&r.type!=="Keyword"&&j("Expected property name after '?.'"),o();let l=O({type:"Identifier",name:r.value},r);e=g({type:"MemberExpression",object:e,property:l,computed:false,optional:true},e,l);}else if(u(".")){o();let r=v(),l;r.type==="Identifier"||r.type==="Keyword"?(o(),l=O({type:"Identifier",name:r.value},r)):(Y("Expected property name"),l=Ye({type:"Identifier",name:""},r)),e=g({type:"MemberExpression",object:e,property:l,computed:false,optional:false},e,l);}else if(u("[")){o();let r=x(),l=N("]");e=g({type:"MemberExpression",object:e,property:r,computed:true,optional:false},e,l);}else if(u("(")){let{args:r,close:l}=F();e=g({type:"CallExpression",callee:e,arguments:r,optional:false},e,l);}else if(u("<")||u("<<")){let r=S();if(!r)break;let{args:l,close:f}=F();e=g({type:"CallExpression",callee:e,arguments:l,optional:false,typeArguments:r},e,f);}else if(u("++")||u("--")){let r=o();e=g({type:"UpdateExpression",operator:r.value,prefix:false,argument:e},e,r);}else break;return t?g({type:"ChainExpression",expression:e},e,e):e},F=()=>{N("(");let e=[];for(;!u(")");)e.push(M()),u(")")||N(",");return {args:e,close:N(")")}},M=()=>{if(u("...")){let e=o(),t=x();return g({type:"SpreadElement",argument:t},e,t)}return x()},I=()=>{let e=v();return e.type!=="Identifier"&&j("Expected identifier"),o(),O({type:"Identifier",name:e.value},e)},J=(e=false)=>{let t=u("{")?V():u("[")?H():I();if(e&&u("?")&&(t.type!=="Identifier"&&j("A binding pattern parameter cannot be optional"),o(),t.optional=true),u(":")){o();let r=ge();t.typeAnnotation=r.schema,t.typeAnnotationNode=r.node;}return t},V=()=>{let e=N("{"),t=[];for(;!u("}");){if(u("...")){let l=o(),f=J();t.push(g({type:"RestElement",argument:f},l,f));}else {let l=I(),f,R=false;if(u(":")?(o(),f=J()):(f={...l},R=true),u("=")){o();let L=x();f=g({type:"AssignmentPattern",left:f,right:L},f,L);}t.push(g({type:"Property",key:l,value:f,kind:"init",shorthand:R,computed:false},l,f));}u("}")||N(",");}let r=N("}");return g({type:"ObjectPattern",properties:t},e,r)},H=()=>{let e=N("["),t=[];for(;!u("]");){if(u(",")){t.push(null),o();continue}if(u("...")){let l=o(),f=J();t.push(g({type:"RestElement",argument:f},l,f));}else {let l=J();if(u("=")){o();let f=x();l=g({type:"AssignmentPattern",left:l,right:f},l,f);}t.push(l);}u("]")||N(",");}let r=N("]");return g({type:"ArrayPattern",elements:t},e,r)},Z=()=>{let e=X.length,t=ce();return t||h(e),t},ce=()=>{let e=0,t="name";for(let r=E;r<m.length;r++){let l=m[r];if(l.type==="EOF")return false;if(l.type==="Punctuator"){if(l.value==="<"&&t==="type"){_(r);continue}if(e===1&&l.value===":"&&t==="name"?t="type":e===1&&l.value==="="?t="default":e===1&&l.value===","&&(t="name"),l.value==="("||l.value==="["||l.value==="{")e++;else if((l.value===")"||l.value==="]"||l.value==="}")&&(e--,e===0)){let f=m[r+1];return !f||f.type!=="Punctuator"?false:f.value==="=>"?true:f.value===":"?tt(r+2):false}}}return false},tt=e=>{let t=0;for(let r=e;r<m.length;r++){let l=m[r];if(l.type==="EOF")return false;if(l.type==="Punctuator")if(l.value==="<"&&_(r),["(","[","{","<"].includes(l.value))t++;else if([")","]","}",">"].includes(l.value)){if(t===0)return false;t--;}else {if(t===0&&l.value==="=>")return true;if(t===0&&(l.value===";"||l.value===","))return false}}return false},nt=()=>{N("(");let e=[];for(;!u(")");){if(u("...")){let t=o(),r=J();e.push(g({type:"RestElement",argument:r},t,r));}else {let t=J(true);if(u("=")){t.optional&&j("Parameter cannot have question mark and initializer"),o();let r=x();t=g({type:"AssignmentPattern",left:t,right:r},t,r);}e.push(t);}u(")")||N(",");}return N(")"),e},rt=e=>{if(e.type==="Identifier")return e.name;let t=e.left;return e.type==="AssignmentPattern"&&t?.type==="Identifier"?t.name:null},me=(e,t,r=[])=>ft(r,()=>ot(e,t,r)),ot=(e,t,r)=>{let l=u("(")?nt():[I()],f,R,L;if(u(":")){o();let U=ut(l.map(rt));f=U.schema,R=U.node,L=U.guard;}N("=>");let q=u("{")?fe():x();return O({type:"ArrowFunctionExpression",params:l,body:q,async:e,expression:q.type!=="BlockStatement",generator:false,...f?{returnType:f,returnTypeNode:R}:{},...L?{returnGuard:L}:{},...r.length?{typeParameters:[...r]}:{}},t)},st=()=>{let e=N("["),t=[];for(;!u("]");){if(u(",")){o(),t.push(null);continue}t.push(M()),u("]")||N(",");}return g({type:"ArrayExpression",elements:t},e,N("]"))},at=()=>{let e=N("{"),t=[];for(;!u("}");){if(u("...")){let r=o(),l=x();t.push(g({type:"SpreadElement",argument:l},r,l));}else {let r=v(),l,f=false;if(u("["))f=true,o(),l=x(),N("]");else if(r.type==="String")o(),l=O({type:"Literal",value:k(r.value.slice(1,-1)),raw:r.value},r);else if(r.type==="Number")o(),l=O({type:"Literal",value:Number(r.value),raw:r.value},r);else if(r.type==="Identifier"||r.type==="Keyword")o(),l=O({type:"Identifier",name:r.value},r);else return j("Invalid property key");if(u(":")){o();let R=x();t.push(g({type:"Property",key:l,value:R,kind:"init",shorthand:false,computed:f},r,R));}else t.push(g({type:"Property",key:l,value:l,kind:"init",shorthand:true,computed:false},r,l));}u("}")||N(",");}return g({type:"ObjectExpression",properties:t},e,N("}"))},he=(e,t)=>({type:"TemplateElement",value:{raw:e,cooked:k(e)},tail:t}),it=e=>{o();let t=[he(e.value,false)],r=[];for(;;){r.push(x());let l=v();if(l.type==="TemplateMiddle")o(),t.push(he(l.value,false));else if(l.type==="TemplateTail"){o(),t.push(he(l.value,true));break}else j("Expected `}` to close template interpolation");}return O({type:"TemplateLiteral",quasis:t,expressions:r},e)},de=()=>{let e=v();return e.type!=="Identifier"&&j(`Expected JSX identifier but got '${e.value||e.type}'`),O({type:"JSXIdentifier",name:o().value},e)},Oe=()=>{let e=de();if(u(":")){o();let t=de();return g({type:"JSXNamespacedName",namespace:e,name:t},e,t)}for(;u(".");){o();let t=de();e=g({type:"JSXMemberExpression",object:e,property:t},e,t);}return e},oe=e=>e.type==="JSXIdentifier"?e.name:e.type==="JSXNamespacedName"?`${oe(e.namespace)}:${oe(e.name)}`:`${oe(e.object)}.${oe(e.property)}`,lt=()=>{let e=v();if(e.type==="String")return o(),O({type:"Literal",value:k(e.value.slice(1,-1)),raw:e.value},e);if(u("{")){let t=o(),r=K(),l=N("}");return g({type:"JSXExpressionContainer",expression:r},t,l)}return u("<")?ke():j(`Invalid JSX attribute value '${e.value||e.type}'`)},ct=()=>{let e=[];for(;!u(">")&&!u("/>")&&!$();){if(u("{")){let l=o();N("...");let f=K(),R=N("}");e.push(g({type:"JSXSpreadAttribute",argument:f},l,R));continue}let t=de();if(u(":")){o();let l=de();t=g({type:"JSXNamespacedName",namespace:t,name:l},t,l);}let r=null;u("=")&&(o(),r=lt()),e.push(g({type:"JSXAttribute",name:t,value:r},t,r??t));}return e},De=()=>{let e=[];for(;!(u("</")||$());){let t=v();if(t.type==="JSXText")o(),e.push(O({type:"JSXText",value:t.value,raw:t.value},t));else if(u("{")){let r=o();if(u("}")){let l=o(),f=O({type:"JSXEmptyExpression"},r);e.push(g({type:"JSXExpressionContainer",expression:f},r,l));}else if(u("...")){o();let l=K(),f=N("}");e.push(g({type:"JSXSpreadChild",expression:l},r,f));}else {let l=K(),f=N("}");e.push(g({type:"JSXExpressionContainer",expression:l},r,f));}}else u("<")?e.push(ke()):j(`Unexpected token in JSX children '${t.value||t.type}'`);}return e},ke=()=>{let e=N("<");if(u(">")){let ne=o(),pe=g({type:"JSXOpeningFragment"},e,ne),Nt=De(),Et=N("</"),_e=N(">"),It=g({type:"JSXClosingFragment"},Et,_e);return g({type:"JSXFragment",openingFragment:pe,children:Nt,closingFragment:It},e,_e)}let t=Oe(),r=ct();if(u("/>")){let ne=o(),pe=g({type:"JSXOpeningElement",name:t,attributes:r,selfClosing:true},e,ne);return g({type:"JSXElement",openingElement:pe,children:[],closingElement:null},e,ne)}let l=N(">"),f=g({type:"JSXOpeningElement",name:t,attributes:r,selfClosing:false},e,l),R=De(),L=N("</"),q=v(),U=Oe();oe(U)!==oe(t)&&j(`JSX closing tag </${oe(U)}> does not match opening <${oe(t)}>`,q);let z=N(">"),te=g({type:"JSXClosingElement",name:U},L,z);return g({type:"JSXElement",openingElement:f,children:R,closingElement:te},e,z)},pt=()=>{let e=v();if(w("async")){let t=v(1);if(t.value==="("||t.type==="Identifier")return o(),me(true,e);if(t.value==="<"){o();let r=Je(e,true);if(r)return r}return j("Unexpected 'async'")}if(u("(")&&Z()||e.type==="Identifier"&&v(1).type==="Punctuator"&&v(1).value==="=>")return me(false,e);if(e.type==="Number")return o(),O({type:"Literal",value:Number(e.value),raw:e.value},e);if(e.type==="String")return o(),O({type:"Literal",value:k(e.value.slice(1,-1)),raw:e.value},e);if(e.type==="Template")return o(),O({type:"TemplateLiteral",expressions:[],quasis:[he(e.value,true)]},e);if(e.type==="TemplateHead")return it(e);if(e.type==="Keyword")return e.value==="true"?(o(),O({type:"Literal",value:true,raw:"true"},e)):e.value==="false"?(o(),O({type:"Literal",value:false,raw:"false"},e)):e.value==="null"?(o(),O({type:"Literal",value:null,raw:"null"},e)):e.value==="new"?j("'new' is not supported \u2014 the language has no constructors (FP / portable IR). Use a factory function provided via DI (e.g. `now()` instead of `new Date()`)."):e.value==="function"?j("Anonymous functions are not supported \u2014 use an arrow function"):j(`'${e.value}' is not supported in this language`);if(e.type==="Identifier")return o(),O({type:"Identifier",name:e.value},e);if(u("(")){o();let t=x();return N(")"),t}return u("[")?st():u("{")?at():u("<")?Je(e)??ke():j(`Unexpected token '${e.value||e.type}'`)},Je=(e,t=false)=>{let r=E,l=X.length,f=c.length,R=s.length,L=W.length,q=()=>(h(l),E=r,c.length=f,s.length=R,W.length=L,void 0),U=v(1);U.type==="Keyword"&&U.value==="const"&&we();try{let z=we();return !z.length||!u("(")?q():me(t,e,z)}catch{return q()}},{parseType:ge,parseReturnType:ut,parseTypeParamList:we,parseTypeInScope:dt,withTypeParams:ft}=Qe({rescanTypeLessThan:_,splitShiftLeft:P,tokens:m,pos:()=>E,peek:v,next:o,isP:u,isK:w,expectP:N,fail:j,recordError:Y,createMissingNode:Ye,unescape:k,typeRefs:W,namespace:()=>A.length?A.join("."):null}),Fe=()=>{let e=o(),t=I(),r=[];u("<")&&(r=we()),N("=");let l=dt(r),f=g({type:"TSTypeAliasDeclaration",id:t,...r.length?{typeParameters:[...r]}:{},typeAnnotation:l.schema,typeNode:l.node},e,C());return u(";")&&o(),f},Xe=(e,t)=>t.loc.start.line===e.loc.end.line,Pe=(e=0)=>v(e).type==="Identifier"&&v(e).value==="namespace"&&v(e+1).type==="Identifier"&&Xe(v(e),v(e+1)),Ke=()=>B("declare")&&Xe(v(),v(1))&&Pe(1),Me=()=>{let e=v(),t=B("declare");return t&&o(),o(),Ue(e,t)},Ue=(e,t)=>{let r=I();A.push(r.name);let l=Q;t&&(Q=true);try{let f;if(u("."))o(),f=Ue(v(),!1);else {let R=N("{"),L=Ee(()=>u("}"));f=g({type:"TSModuleBlock",body:L},R,N("}"));}return g({type:"TSModuleDeclaration",id:r,body:f,...t?{declare:!0}:{}},e,f)}finally{Q=l,A.pop();}},se=()=>{let e=v();if(e.type==="Identifier"&&e.value==="type"&&v(1).type==="Identifier"&&v(2).type==="Punctuator"&&(v(2).value==="="||v(2).value==="<"))return Fe();if(Pe()||Ke())return Me();if(w("const")||w("let")||w("var")){let f=$e();return u(";")&&o(),f}if(w("if"))return xt();if(w("for"))return gt();if(w("while"))return vt();if(w("do"))return Tt();if(w("break")||w("continue"))return bt();if(w("return"))return St();if(w("throw"))return kt();if(w("try"))return wt();if(w("switch"))return Pt();if(w("import"))return mt();if(w("export"))return ht();if(u("{"))return fe();if((w("function")||w("async")&&v(1).type==="Keyword"&&v(1).value==="function")&&j("Function declarations are not supported \u2014 use 'const fn = () => \u2026'"),u(";"))return o(),O({type:"EmptyStatement"},e);if(e.type==="Keyword"&&Wt.has(e.value)||e.type==="Identifier"&&Se(Qt,e.value)?.(v(1),v(2))===true){let f=Se(Ht,e.value);j(`'${e.value}' is not supported in this language`+(f?` \u2014 ${f}`:""));}let r=x(),l=u(";")?o():C();return g({type:"ExpressionStatement",expression:r},r,l)},$e=()=>{let e=o(),t=e.value,r=()=>{let f=J(),R=null;return u("=")?(o(),R=x()):t==="const"&&!Q&&ee("'const' declarations must be initialized",f),g({type:"VariableDeclarator",id:f,init:R},f,R??f)},l=[r()];for(;u(",");)o(),l.push(r());return g({type:"VariableDeclaration",kind:t,declarations:l},e,l[l.length-1])},yt=()=>{let e=v();return e.type!=="String"&&j("Expected module specifier string"),o(),O({type:"Literal",value:k(e.value.slice(1,-1)),raw:e.value},e)},mt=()=>{let e=o(),t=[],r;if(B("type")){let f=v(1);(f.type==="Punctuator"&&(f.value==="{"||f.value==="*")||f.type==="Identifier"&&f.value!=="from")&&(o(),r="type");}if(v().type!=="String"){if(v().type==="Identifier"){let f=I();t.push(g({type:"ImportDefaultSpecifier",local:f},f,f)),u(",")&&o();}if(u("*")){let f=o();B("as")||j("Expected 'as' after '*' in import"),o();let R=I();t.push(g({type:"ImportNamespaceSpecifier",local:R},f,R));}else if(u("{")){for(o();!u("}")&&!$();){let f;B("type")&&v(1).type==="Identifier"&&v(1).value!=="as"&&(o(),f="type");let R=I(),L=R;if(B("as")&&(o(),L=I()),t.push(g({type:"ImportSpecifier",imported:R,local:L,...f?{importKind:f}:{}},R,L)),u(","))o();else break}N("}");}B("from")||j("Expected 'from' in import declaration"),o();}let l=yt();return u(";")&&o(),O({type:"ImportDeclaration",specifiers:t,source:l,...r?{importKind:r}:{}},e)},ht=()=>{let e=o();if(B("type")&&v(1).type==="Identifier"){let t=Fe();return O({type:"ExportNamedDeclaration",declaration:t,specifiers:[],source:null},e)}if(Pe()||Ke()){let t=Me();return O({type:"ExportNamedDeclaration",declaration:t,specifiers:[],source:null},e)}if(w("default")){o();let t=x();return u(";")&&o(),O({type:"ExportDefaultDeclaration",declaration:t},e)}if(w("const")||w("let")||w("var")){let t=$e();return u(";")&&o(),O({type:"ExportNamedDeclaration",declaration:t,specifiers:[],source:null},e)}if(u("{")){o();let t=[];for(;!u("}")&&!$();){let r=I(),l=r;if(B("as")&&(o(),l=I()),t.push(g({type:"ExportSpecifier",local:r,exported:l},r,l)),u(","))o();else break}return N("}"),u(";")&&o(),O({type:"ExportNamedDeclaration",declaration:null,specifiers:t,source:null},e)}return j("Expected 'const', 'type', 'namespace', '{', or 'default' after 'export'")},Be=()=>v().type==="Identifier"&&v().value==="of",Ne=()=>w("in"),gt=()=>{let e=o();N("(");let t=null,r=null;if(!u(";"))if(w("const")||w("let")||w("var")){let L=o(),q=()=>{let z=I();if(u(":")){o();let te=ge();z.typeAnnotation=te.schema,z.typeAnnotationNode=te.node;}return z},U=q();if(Be()||Ne()){let z=g({type:"VariableDeclarator",id:U,init:null},U,U);r=g({type:"VariableDeclaration",kind:L.value,declarations:[z]},L,U);}else {let z=ne=>{let pe=null;return u("=")?(o(),pe=x(true)):L.value==="const"&&ee("'const' declarations must be initialized",ne),g({type:"VariableDeclarator",id:ne,init:pe},ne,pe??ne)},te=[z(U)];for(;u(",");)o(),te.push(z(q()));t=g({type:"VariableDeclaration",kind:L.value,declarations:te},L,te[te.length-1]);}}else {let L=x(true);Be()||Ne()?r=L:t=L;}if(r){let L=Ne();o();let q=x();N(")");let U=se();return g(L?{type:"ForInStatement",left:r,right:q,body:U}:{type:"ForOfStatement",left:r,right:q,body:U,await:false},e,U)}N(";");let l=u(";")?null:x();N(";");let f=u(")")?null:x();N(")");let R=se();return g({type:"ForStatement",init:t,test:l,update:f,body:R},e,R)},Tt=()=>{let e=o(),t=se();w("while")||j("Expected 'while' after the 'do' body"),o(),N("(");let r=x(),l=N(")");return u(";")&&o(),g({type:"DoWhileStatement",body:t,test:r},e,l)},bt=()=>{let e=o(),t=e.value==="break"?"BreakStatement":"ContinueStatement",r=u(";")?o():C();return g({type:t,label:null},e,r)},vt=()=>{let e=o();N("(");let t=x();N(")");let r=se();return g({type:"WhileStatement",test:t,body:r},e,r)},xt=()=>{let e=o();N("(");let t=x();N(")");let r=se(),l=null;return w("else")&&(o(),l=se()),g({type:"IfStatement",test:t,consequent:r,alternate:l},e,l??r)},St=()=>{let e=o(),t=null;!u(";")&&!u("}")&&!$()&&(t=x());let r=u(";")?o():C();return g({type:"ReturnStatement",argument:t},e,r)},kt=()=>{let e=o(),t=x(),r=u(";")?o():C();return g({type:"ThrowStatement",argument:t},e,r)},wt=()=>{let e=o(),t=fe(),r=null,l=null;if(w("catch")){let f=o(),R=null;u("(")&&(o(),R=I(),N(")"));let L=fe();r=g({type:"CatchClause",param:R,body:L},f,L);}return w("finally")&&(o(),l=fe()),!r&&!l&&j("'try' requires a 'catch' or 'finally' clause"),g({type:"TryStatement",block:t,handler:r,finalizer:l},e,l??r??t)},Pt=()=>{let e=o();N("(");let t=x();N(")"),N("{");let r=[];for(;!u("}")&&!$();){let f=v(),R=null;w("case")?(o(),R=x()):w("default")?o():j("Expected 'case' or 'default' in switch"),N(":");let L=[];for(;!u("}")&&!w("case")&&!w("default")&&!$();)L.push(se());r.push(g({type:"SwitchCase",test:R,consequent:L},f,C()??f));}let l=N("}");return g({type:"SwitchStatement",discriminant:t,cases:r},e,l)},fe=()=>{let e=N("{"),t=Ee(()=>u("}"));return g({type:"BlockStatement",body:t},e,N("}"))},Ee=e=>{let t=[];for(;!e()&&!$();){if(v().type==="Unknown"){o();continue}try{t.push(se());}catch(r){if(!(r instanceof le))throw r;$()||o();}}return t};return {parseExpr:x,parseProgram:()=>{let e=v(),t=Ee(()=>false);return re(),g({type:"Program",sourceType:"module",body:t,...W.length?{typeRefs:W}:{},...a.length?{comments:a}:{},...c.length?{parseDiagnostics:c}:{}},e,C()??e)},eof:$,fail:j,recordError:Y,settleGrammar:re,diagnostics:c}}function et(n){let c=Ae(n),s=c.parseProgram(),a=s.comments;return a?.length&&Le(s,a,n),{ast:s,diagnostics:c.diagnostics}}function Zt(n){let{ast:c,diagnostics:s}=et(n),a=s[0];if(a){let y=a.code==="lex-error"?ie:le;throw new y(a.message,a.position,a.index,a.loc,a.end)}return c}function en(n){let c=Ae(n),s=c.parseExpr();c.eof()||c.fail("Unexpected token after expression"),c.settleGrammar();let a=c.diagnostics[0];if(a){let y=a.code==="lex-error"?ie:le;throw new y(a.message,a.position,a.index,a.loc,a.end)}return s}function tn(n){let c=Ae(n),s;try{s=c.parseExpr(),c.eof()||c.recordError("Unexpected token after expression");}catch(a){if(!(a instanceof le)&&!(a instanceof ie))throw a}return c.settleGrammar(),{ast:s,diagnostics:c.diagnostics}}var nn="1.9.0";export{qe as KEYWORDS,ie as LexError,le as ParseError,Le as attachComments,Gt as nodeIsMissing,Zt as parse,en as parseExpression,tn as parseExpressionTolerant,et as parseTolerant,Jt as tokenize,nn as version};
1
+ // A entrada dos testes deste pacote: reexporta o barril, que é a entrada do pacote (o `exports` do `package.json`). O
2
+ // barril avalia os arquivos na ordem do outFile da tag, e um import direto de um arquivo avaliaria os outros noutra
3
+ // ordem.
4
+ export * from "./_namespaces/ts.js";
@@ -0,0 +1,59 @@
1
+ import { ScriptKind, ScriptTarget, SyntaxKind } from "./_namespaces/ts.js";
2
+ import type { AmdDependency, CheckJsDirective, DiagnosticMessage, EntityName, FileReference, JsxTagNameExpression, Node, NodeArray, PragmaMap, SourceFile, TextChangeRange } from "./_namespaces/ts.js";
3
+ export declare function createNode(kind: SyntaxKind, pos?: number, end?: number): Node;
4
+ /**
5
+ * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes
6
+ * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise,
7
+ * embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns
8
+ * a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned.
9
+ *
10
+ * @param node a given node to visit its children
11
+ * @param cbNode a callback to be invoked for all child nodes
12
+ * @param cbNodes a callback to be invoked for embedded array
13
+ *
14
+ * @remarks `forEachChild` must visit the children of a node in the order
15
+ * that they appear in the source code. The language service depends on this property to locate nodes by position.
16
+ */
17
+ export declare function forEachChild<T>(node: Node, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray<Node>) => T | undefined): T | undefined;
18
+ /**
19
+ * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes
20
+ * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; additionally,
21
+ * unlike `forEachChild`, embedded arrays are flattened and the 'cbNode' callback is invoked for each element.
22
+ * If a callback returns a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned.
23
+ *
24
+ * @param node a given node to visit its children
25
+ * @param cbNode a callback to be invoked for all child nodes
26
+ * @param cbNodes a callback to be invoked for embedded array
27
+ *
28
+ * @remarks Unlike `forEachChild`, `forEachChildRecursively` handles recursively invoking the traversal on each child node found,
29
+ * and while doing so, handles traversing the structure without relying on the callstack to encode the tree structure.
30
+ */
31
+ export declare function forEachChildRecursively<T>(rootNode: Node, cbNode: (node: Node, parent: Node) => T | "skip" | undefined, cbNodes?: (nodes: NodeArray<Node>, parent: Node) => T | "skip" | undefined): T | undefined;
32
+ export declare function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile;
33
+ export declare function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName | undefined;
34
+ /**
35
+ * O texto como uma expressão só (CK-72): um `SourceFile` com um statement, o da expressão, e os erros de parse; o que
36
+ * sobra depois da expressão é o `Unexpected token.` (TS1012). É a pergunta "este texto é uma expressão?" respondida pelo
37
+ * parser, no molde do `parseJsonText` da tag. A variante da linguagem (o JSX) vem do nome do arquivo, como no
38
+ * `createSourceFile`.
39
+ */
40
+ export declare function parseIsolatedExpression(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean): SourceFile;
41
+ export declare function isExternalModule(file: SourceFile): boolean;
42
+ export declare function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile;
43
+ export declare function isDeclarationFileName(fileName: string): boolean;
44
+ export interface PragmaContext {
45
+ languageVersion: ScriptTarget;
46
+ pragmas?: PragmaMap;
47
+ checkJsDirective?: CheckJsDirective;
48
+ referencedFiles: FileReference[];
49
+ typeReferenceDirectives: FileReference[];
50
+ libReferenceDirectives: FileReference[];
51
+ amdDependencies: AmdDependency[];
52
+ hasNoDefaultLib?: boolean;
53
+ moduleName?: string;
54
+ }
55
+ export declare function processCommentPragmas(context: PragmaContext, sourceText: string): void;
56
+ type PragmaDiagnosticReporter = (pos: number, length: number, message: DiagnosticMessage) => void;
57
+ export declare function processPragmasIntoFields(context: PragmaContext, reportDiagnostic: PragmaDiagnosticReporter): void;
58
+ export declare function tagNamesAreEquivalent(lhs: JsxTagNameExpression, rhs: JsxTagNameExpression): boolean;
59
+ export {};