@tslite/printer 0.5.7 → 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.
package/dist/index.d.ts CHANGED
@@ -1,64 +1 @@
1
- import { BaseNode, TSLite } from '@tslite/core';
2
- import { CapabilityProfile } from '@tslite/capability';
3
-
4
- type PrintInput = BaseNode | BaseNode[] | (BaseNode | null)[] | null | undefined;
5
- declare const print: (node: PrintInput) => string;
6
- /**
7
- * Printer **sob-contrato** (D37): emite só o que o `profile` permite e **recusa o
8
- * resto** (lança `node-not-allowed`). É o limite hard do lado JIT — simétrico ao
9
- * `evaluate(ast, env, { profile })` do interpret. O `print` padrão (standalone)
10
- * segue emitindo qualquer nó.
11
- */
12
- declare const printWithProfile: (ast: PrintInput, profile: CapabilityProfile) => string;
13
- /**
14
- * Uma expressão é PRIMÁRIA em posição de membro/callee? (isto é: reparsa certo
15
- * ali, sem parênteses)
16
- *
17
- * **Fonte única.** O `@tslite/format` faz a mesma pergunta ao imprimir a callee
18
- * de uma chamada, e derivá-la duas vezes já custou um defeito: o formatador
19
- * emitia `() => { … }()`, que o TSLite reparsa mas o **TypeScript recusa** — e a
20
- * promessa da plataforma é ser um subset PURO de TS.
21
- */
22
- declare function isPrimaryOperand(node: BaseNode): boolean;
23
- /** Operando que começa com unário/`await` (à esquerda de `**` exige parênteses). */
24
- declare const unaryLike: (node: BaseNode) => boolean;
25
- declare const mixesCoalesce: (parentOp: string, child: BaseNode) => boolean;
26
- /**
27
- * Returns the operator precedence of an expression node.
28
- * Higher value = binds tighter. Returns Infinity for atoms (Identifier, Literal, etc).
29
- */
30
- /** A precedência efetiva de uma expressão (erasure de `as`); `Infinity` = primária. */
31
- declare const getExpressionPrecedence: (node: BaseNode) => number;
32
- /**
33
- * Wraps a child node in parentheses when its precedence is lower than
34
- * the parent's, respecting left/right associativity rules.
35
- *
36
- * For left-associative operators (most):
37
- * - left child: parens when childPrec < parentPrec
38
- * - right child: parens when childPrec <= parentPrec
39
- *
40
- * For right-associative operators (**):
41
- * - left child: parens when childPrec <= parentPrec
42
- * - right child: parens when childPrec < parentPrec
43
- */
44
- /**
45
- * A DECISÃO de parentizar um operando pela precedência — exportada para quem
46
- * imprime por outra via (o `@tslite/emit` renderiza `Doc`, não texto) tomar a
47
- * mesma decisão, em vez de manter uma segunda máquina de precedência.
48
- */
49
- declare const needsParens: (node: BaseNode, parentPrec: number, isRight: boolean, rightAssociative?: boolean) => boolean;
50
-
51
- /**
52
- * Prints the hybrid JSON form (a value with `#expr` islands) as JS source.
53
- *
54
- * Static data is emitted as an object/array literal; each `#expr` island is
55
- * handed back to `print()` — the same `#expr` boundary the type layer walks.
56
- *
57
- * ```ts
58
- * printJson({ name: "John", init: { "#expr": "CallExpression", ... } })
59
- * // '{ name: "John", init: setup() }'
60
- * ```
61
- */
62
- declare function printJson(node: TSLite): string;
63
-
64
- export { getExpressionPrecedence, isPrimaryOperand, mixesCoalesce, needsParens, print, printJson, printWithProfile, unaryLike };
1
+ export * from "./_namespaces/ts.js";
package/dist/index.js CHANGED
@@ -1 +1,4 @@
1
- import {BinaryPrecedence,Precedence,TSLiteError,desugarJSX,isExprMarker,EXPR_MARKER,VALID_OBJECT_KEY}from'@tslite/core';import {compileProfile,nodeViolation}from'@tslite/capability';import {assertSafe,HERMETIC_POLICY}from'@tslite/sanitize';var L=t=>VALID_OBJECT_KEY.test(t);function m(t){let e=n=>{if(typeof n=="string")return `"${n}"`;if(typeof n!="object")return String(n);if(n===null)return "null";if(Array.isArray(n))return `[${n.map(e).join(",")}]`;let s=n;if(isExprMarker(s)){let{[EXPR_MARKER]:i,...y}=s,N={type:i,...y};return r(N)}return `{ ${Object.entries(s).map(([i,y])=>`${L(i)?i:`"${i}"`}: ${e(y)}`).join(", ")} }`};return e(t)}var u=", ",l=null,r=t=>{if(t==null)return "";if(Array.isArray(t))return t.filter(Boolean).map(r).join(u);if(typeof t!="object")return String(t);if(!t.type)return JSON.stringify(t);if(t.type in T){if(l){let e=nodeViolation(t,l);if(e)throw new TSLiteError("node-not-allowed",`'${e}' is not allowed by the active capability profile.`,{type:t.type})}return T[t.type](t)}throw Error("Unknown type: "+t.type)},W=(t,e)=>{t&&typeof t=="object"&&!Array.isArray(t)&&assertSafe(t,e.sanitize==="hermetic"?HERMETIC_POLICY:void 0);let n=l;l=compileProfile(e);try{return r(t)}finally{l=n;}},c=t=>`(${t})`;function b(t){if(_.has(t.type))return true;if(t.type!=="Literal")return false;let e=t;return !(typeof e.value=="number"||e.bigint!=null)}var _=new Set(["Identifier","ThisExpression","ArrayExpression","MemberExpression","CallExpression","TemplateLiteral"]),x=t=>{if(t.type==="TSAsExpression")return x(t.expression);let e=r(t);return b(t)?e:c(e)},M=t=>`[${r(t.elements)}]`,U=t=>`[${t.elements.map(n=>n?r(n):"").join(", ")}]`,q=t=>{let e=r(t.params),n=r(t.body),s=t.body.type!=="BlockStatement"&&n.startsWith("{"),o=t.body.type=="AssignmentExpression"||t.body.type=="BinaryExpression"||t.body.type=="ObjectExpression"||t.body.type=="JsonExpression"||s?c(n):n;return `${t.async?"async ":""}(${e}) => ${o}`},V=t=>{let e=r(t.left),n=r(t.right);return `${e} ${t.operator} ${n}`},X=t=>"await "+p(t.argument,Precedence.Await,false),$=t=>t.type==="TSAsExpression"?$(t.expression):t,w=t=>{let e=$(t);return e.type==="UnaryExpression"||e.type==="AwaitExpression"},A=(t,e)=>{let n=$(e);if(n.type!=="LogicalExpression")return false;let s=n.operator;return t==="??"?s==="||"||s==="&&":t==="||"||t==="&&"?s==="??":false},K=t=>{let e=BinaryPrecedence[t.operator]??1/0,n=t.operator==="**",s=p(t.left,e,false,n),o=n&&(w(t.left)||s[0]==="-"||s[0]==="+")?c(s):s,i=p(t.right,e,true,n);return `${o} ${t.operator} ${i}`},z=t=>{let e=t.body.map(E).filter(Boolean).join(" ");return `{ ${e?e+" ":""}}`},Y=t=>t.label?`break ${r(t.label)}`:"break",H=t=>{let e=x(t.callee),n=t.optional?"?.":"";return `${e}${n}(${r(t.arguments)})`},G=t=>r(t.expression),S=t=>t.type==="BinaryExpression"||t.type==="LogicalExpression"?BinaryPrecedence[t.operator]??1/0:t.type==="ConditionalExpression"?Precedence.Conditional:t.type==="AssignmentExpression"?Precedence.Assignment:t.type==="ArrowFunctionExpression"?Precedence.ArrowFunction:t.type==="AwaitExpression"?Precedence.Await:t.type==="SequenceExpression"?Precedence.Sequence:t.type==="TSAsExpression"?S(t.expression):1/0,B=(t,e,n,s=false)=>{let o=S(t);return n?s?o<e:o<=e:s?o<=e:o<e},p=(t,e,n,s=false)=>{let o=r(t);return B(t,e,n,s)?c(o):o},Q=t=>`${p(t.test,Precedence.Conditional,false,true)} ? ${r(t.consequent)} : ${r(t.alternate)}`,Z=t=>t.label?`continue ${r(t.label)}`:"continue",d=t=>{let e=r(t.expression);return e[0]==="{"||e.startsWith("function")||e.startsWith("class")?c(e):e},tt=t=>";",et=t=>`do ${r(t.body)} while (${r(t.test)})`,rt=t=>`for (${r(t.left)} in ${r(t.right)}) ${r(t.body)}`,nt=t=>`for${t.await?" await":""} (${r(t.left)} of ${r(t.right)}) ${r(t.body)}`,st=t=>{let e=r(t.init),n=r(t.test),s=r(t.update);return `for (${e};${n?` ${n}`:""};${s?` ${s}`:""}) ${r(t.body)}`},ot=t=>{let e=t.params.map(P).join(u);return `${t.async?"async ":""}function ${r(t.id)}(${e}) ${r(t.body)}`},it=t=>{let e=r(t.params);return `${t.async?"async ":""}function ${r(t.id)}(${e}) ${r(t.body)}`},P=t=>t.name,at=t=>{throw new TSLiteError("incomplete-tree","Cannot print a tree with a Placeholder (hole) \u2014 fill the holes first.",{type:t.type})},pt=t=>`if (${r(t.test)}) ${r(t.consequent)}${t.alternate?` else ${r(t.alternate)}`:""}`,ct=t=>m(t.body),lt=t=>t.raw?t.raw:t.value===void 0?"undefined":t.value===null?"null":typeof t.value=="string"?JSON.stringify(t.value):typeof t.value=="boolean"?String(t.value):t.bigint?t.bigint+"n":t.regex?`/${t.regex.pattern}/${t.regex.flags}`:(t.value instanceof RegExp,String(t.value)),ut=t=>{let e=BinaryPrecedence[t.operator]??1/0,n=(s,o)=>A(t.operator,s)?c(r(s)):p(s,e,o);return `${n(t.left,false)} ${t.operator} ${n(t.right,true)}`},yt=t=>{let e=[x(t.object)];return t.optional&&e.push(t.computed?"?.":"?"),e.push(t.computed?"[":"."),e.push(r(t.property)),t.computed&&e.push("]"),e.join("")},mt=t=>{let e=t.properties.map(r).join(", ");return e.length==0?"{}":`{ ${e} }`},ft=t=>{let e=t.properties.map(r).join(", ");return e.length==0?"{ }":`{ ${e} }`},xt=new Set(["FunctionDeclaration","IfStatement","ForStatement","ForInStatement","ForOfStatement","WhileStatement","TryStatement","SwitchStatement","ClassDeclaration","BlockStatement"]),E=t=>{let e=r(t);return !e||e===";"?"":xt.has(t.type)?e:e+";"},$t=t=>t.body.map(E).filter(Boolean).join(" "),St=t=>t.shorthand?r(t.value):`${t.computed?`[${r(t.key)}]`:r(t.key)}: ${r(t.value)}`,Et=t=>`${r(t.left)} = ${r(t.right)}`,Tt=t=>"return "+r(t.argument),gt=t=>{let e=t.test?`case ${r(t.test)}:`:"default:",n=t.consequent.map(E).filter(Boolean).join(" ");return n?`${e} ${n}`:e},ht=t=>`switch (${r(t.discriminant)}) { ${t.cases.map(r).join(" ")} }`,bt=t=>t.value.raw,wt=t=>"`"+t.quasis.map((e,n)=>r(e)+(e.tail?"":"${"+r(t.expressions[n])+"}")).join("")+"`",At=t=>"throw "+r(t.argument),Bt=t=>{let e=`try ${r(t.block)}`;if(t.handler){let n=t.handler.param;e+=n?` catch (${r(n)}) ${r(t.handler.body)}`:` catch ${r(t.handler.body)}`;}return e+(t.finalizer?` finally ${r(t.finalizer)}`:"")},Pt=t=>{let e=p(t.argument,Precedence.Unary,false),n=t.operator.length>1||(t.operator==="+"||t.operator==="-")&&e[0]===t.operator?" ":"";return t.operator+n+e},It=t=>t.prefix==true?t.operator+r(t.argument):r(t.argument)+t.operator,jt=t=>`${t.kind} ${t.declarations.map(I).join(", ")}`,I=t=>t.init?`${r(t.id)} = ${r(t.init)}`:r(t.id),Ct=t=>`while (${r(t.test)}) ${r(t.body)}`,Nt=t=>{if(t.importKind==="type")return "";let e=r(t.source);if(t.specifiers.length==0)return `import ${e}`;let n=t.specifiers.find(i=>i.type==="ImportDefaultSpecifier"||i.type==="ImportNamespaceSpecifier"),s=t.specifiers.filter(i=>i.type==="ImportSpecifier"&&i.importKind!=="type");if(!n&&s.length===0)return "";let o=[];return n&&o.push(r(n)),s.length&&o.push(`{ ${s.map(j).join(u)} }`),`import ${o.join(u)} from ${e}`},Dt=t=>r(t.local),kt=t=>`* as ${r(t.local)}`,j=t=>t.imported.name===t.local.name?`${r(t.local)}`:`${r(t.imported)} as ${r(t.local)}`,Ft=t=>{if(t.declaration){let n=r(t.declaration);return n?`export ${n}`:""}return `export { ${t.specifiers.map(C).join(u)} }`},Lt=t=>`export default ${r(t.declaration)}`,C=t=>t.local.name===t.exported.name?`${r(t.local)}`:`${r(t.local)} as ${r(t.exported)}`,vt=t=>`...${r(t.argument)}`,Ot=t=>`...${r(t.argument)}`,Jt=()=>"",Rt=t=>r(t.expression),Wt=t=>r(desugarJSX(t)),_t=t=>r(desugarJSX(t)),T={print:r,JSXElement:Wt,JSXFragment:_t,ArrayExpression:M,ArrayPattern:U,ArrowFunctionExpression:q,AssignmentExpression:V,AssignmentPattern:Et,AwaitExpression:X,BinaryExpression:K,BlockStatement:z,BreakStatement:Y,CallExpression:H,ChainExpression:G,ConditionalExpression:Q,ContinueStatement:Z,DoWhileStatement:et,EmptyStatement:tt,ExpressionStatement:d,ForInStatement:rt,ForOfStatement:nt,ForStatement:st,FunctionDeclaration:ot,FunctionExpression:it,Identifier:P,Placeholder:at,IfStatement:pt,ImportDeclaration:Nt,ImportDefaultSpecifier:Dt,ImportNamespaceSpecifier:kt,ImportSpecifier:j,ExportNamedDeclaration:Ft,ExportDefaultDeclaration:Lt,ExportSpecifier:C,JsonExpression:ct,Literal:lt,LogicalExpression:ut,MemberExpression:yt,ObjectExpression:mt,ObjectPattern:ft,Program:$t,Property:St,ReturnStatement:Tt,SwitchCase:gt,SwitchStatement:ht,TemplateElement:bt,TemplateLiteral:wt,ThrowStatement:At,TryStatement:Bt,UnaryExpression:Pt,UpdateExpression:It,VariableDeclaration:jt,VariableDeclarator:I,WhileStatement:Ct,SpreadElement:vt,RestElement:Ot,TSTypeAliasDeclaration:Jt,TSAsExpression:Rt};export{S as getExpressionPrecedence,b as isPrimaryOperand,A as mixesCoalesce,B as needsParens,r as print,m as printJson,W as printWithProfile,w as unaryLike};
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,197 @@
1
+ import type { CompilerOptions, EmitHint, ModuleDeclaration, NewLineKind, Node, NodeArray, SourceFile, Symbol, SymbolFlags, SyntaxKind } from "./_namespaces/ts.js";
2
+ interface SymbolWriter extends SymbolTracker {
3
+ writeKeyword(text: string): void;
4
+ writeOperator(text: string): void;
5
+ writePunctuation(text: string): void;
6
+ writeSpace(text: string): void;
7
+ writeStringLiteral(text: string): void;
8
+ writeParameter(text: string): void;
9
+ writeProperty(text: string): void;
10
+ writeSymbol(text: string, symbol: Symbol): void;
11
+ writeLine(force?: boolean): void;
12
+ increaseIndent(): void;
13
+ decreaseIndent(): void;
14
+ clear(): void;
15
+ }
16
+ export interface Printer {
17
+ /**
18
+ * Imprime o nó e a subárvore dele como estão. O `hint` diz o papel do nó (um `Identifier` numa expressão, ou como
19
+ * nome de uma declaração); para a maior parte dos nós, `Unspecified`. O `sourceFile` dá o texto de onde saem os
20
+ * literais e os identificadores como foram escritos, e os nomes do arquivo, com que os nomes gerados não colidem.
21
+ */
22
+ printNode(hint: EmitHint, node: Node, sourceFile: SourceFile): string;
23
+ /** Imprime uma lista de nós com o formato pedido. */
24
+ printList<T extends Node>(format: ListFormat, list: NodeArray<T>, sourceFile: SourceFile): string;
25
+ /** Imprime um arquivo como está, com os comentários (a menos que `removeComments`). */
26
+ printFile(sourceFile: SourceFile): string;
27
+ /** Escreve o nó e a subárvore dele no `writer`, como estão (o checker imprime assim os tipos das mensagens). */
28
+ writeNode(hint: EmitHint, node: Node, sourceFile: SourceFile | undefined, writer: EmitTextWriter): void;
29
+ writeList<T extends Node>(format: ListFormat, list: NodeArray<T> | undefined, sourceFile: SourceFile | undefined, writer: EmitTextWriter): void;
30
+ writeFile(sourceFile: SourceFile, writer: EmitTextWriter): void;
31
+ }
32
+ export interface PrintHandlers {
33
+ /**
34
+ * A hook used by the Printer when generating unique names to avoid collisions with
35
+ * globally defined names that exist outside of the current source file.
36
+ */
37
+ hasGlobalName?(name: string): boolean;
38
+ /**
39
+ * A hook used by the Printer to provide notifications prior to emitting a node. A
40
+ * compatible implementation **must** invoke `emitCallback` with the provided `hint` and
41
+ * `node` values.
42
+ * @param hint A hint indicating the intended purpose of the node.
43
+ * @param node The node to emit.
44
+ * @param emitCallback A callback that, when invoked, will emit the node.
45
+ * @example
46
+ * ```ts
47
+ * var printer = createPrinter(printerOptions, {
48
+ * onEmitNode(hint, node, emitCallback) {
49
+ * // set up or track state prior to emitting the node...
50
+ * emitCallback(hint, node);
51
+ * // restore state after emitting the node...
52
+ * }
53
+ * });
54
+ * ```
55
+ */
56
+ onEmitNode?(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void;
57
+ /**
58
+ * A hook used to check if an emit notification is required for a node.
59
+ * @param node The node to emit.
60
+ */
61
+ isEmitNotificationEnabled?(node: Node | undefined): boolean;
62
+ /**
63
+ * A hook used by the Printer to perform just-in-time substitution of a node. This is
64
+ * primarily used by node transformations that need to substitute one node for another,
65
+ * such as replacing `myExportedVar` with `exports.myExportedVar`.
66
+ * @param hint A hint indicating the intended purpose of the node.
67
+ * @param node The node to emit.
68
+ * @example
69
+ * ```ts
70
+ * var printer = createPrinter(printerOptions, {
71
+ * substituteNode(hint, node) {
72
+ * // perform substitution if necessary...
73
+ * return node;
74
+ * }
75
+ * });
76
+ * ```
77
+ */
78
+ substituteNode?(hint: EmitHint, node: Node): Node;
79
+ onEmitSourceMapOfNode?: (hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void) => void;
80
+ onEmitSourceMapOfToken?: (node: Node | undefined, token: SyntaxKind, writer: (s: string) => void, pos: number, emitCallback: (token: SyntaxKind, writer: (s: string) => void, pos: number) => number) => number;
81
+ onEmitSourceMapOfPosition?: (pos: number) => void;
82
+ onSetSourceFile?: (node: SourceFile) => void;
83
+ onBeforeEmitNodeArray?: (nodes: NodeArray<any> | undefined) => void;
84
+ onAfterEmitNodeArray?: (nodes: NodeArray<any> | undefined) => void;
85
+ onBeforeEmitToken?: (node: Node) => void;
86
+ onAfterEmitToken?: (node: Node) => void;
87
+ }
88
+ export interface PrinterOptions {
89
+ removeComments?: boolean;
90
+ newLine?: NewLineKind;
91
+ omitTrailingSemicolon?: boolean;
92
+ noEmitHelpers?: boolean;
93
+ module?: CompilerOptions["module"];
94
+ target?: CompilerOptions["target"];
95
+ sourceMap?: boolean;
96
+ inlineSourceMap?: boolean;
97
+ inlineSources?: boolean;
98
+ extendedDiagnostics?: boolean;
99
+ onlyPrintJsDocStyle?: boolean;
100
+ neverAsciiEscape?: boolean;
101
+ writeBundleFileInfo?: boolean;
102
+ recordInternalSection?: boolean;
103
+ stripInternal?: boolean;
104
+ preserveSourceNewlines?: boolean;
105
+ relativeToBuildInfo?: (path: string) => string;
106
+ }
107
+ export interface EmitTextWriter extends SymbolWriter {
108
+ write(s: string): void;
109
+ writeTrailingSemicolon(text: string): void;
110
+ writeComment(text: string): void;
111
+ getText(): string;
112
+ rawWrite(s: string): void;
113
+ writeLiteral(s: string): void;
114
+ getTextPos(): number;
115
+ getLine(): number;
116
+ getColumn(): number;
117
+ getIndent(): number;
118
+ isAtStartOfLine(): boolean;
119
+ hasTrailingComment(): boolean;
120
+ hasTrailingWhitespace(): boolean;
121
+ getTextPosWithWriteLine?(): number;
122
+ }
123
+ /** O que o cálculo de um specifier pergunta: o diretório corrente e a comparação dos nomes de arquivo. */
124
+ export interface ModuleSpecifierResolutionHost {
125
+ useCaseSensitiveFileNames?(): boolean;
126
+ getCurrentDirectory(): string;
127
+ }
128
+ export interface SymbolTracker {
129
+ trackSymbol?(symbol: Symbol, enclosingDeclaration: Node | undefined, meaning: SymbolFlags): void;
130
+ reportInaccessibleThisError?(): void;
131
+ reportInaccessibleUniqueSymbolError?(): void;
132
+ reportCyclicStructureError?(): void;
133
+ reportLikelyUnsafeImportRequiredError?(specifier: string): void;
134
+ moduleResolverHost?: ModuleSpecifierResolutionHost;
135
+ trackReferencedAmbientModule?(decl: ModuleDeclaration, symbol: Symbol): void;
136
+ trackExternalModuleSymbolOfImportTypeNode?(symbol: Symbol): void;
137
+ reportNonlocalAugmentation?(containingFile: SourceFile, parentSymbol: Symbol, augmentingSymbol: Symbol): void;
138
+ }
139
+ export declare enum ListFormat {
140
+ None = 0,
141
+ SingleLine = 0,// Prints the list on a single line (default).
142
+ MultiLine = 1,// Prints the list on multiple lines.
143
+ PreserveLines = 2,// Prints the list using line preservation if possible.
144
+ LinesMask = 3,
145
+ NotDelimited = 0,// There is no delimiter between list items (default).
146
+ BarDelimited = 4,// Each list item is space-and-bar (" |") delimited.
147
+ AmpersandDelimited = 8,// Each list item is space-and-ampersand (" &") delimited.
148
+ CommaDelimited = 16,// Each list item is comma (",") delimited.
149
+ DelimitersMask = 28,
150
+ AllowTrailingComma = 64,// Write a trailing comma (",") if present.
151
+ Indented = 128,// The list should be indented.
152
+ SpaceBetweenBraces = 256,// Inserts a space after the opening brace and before the closing brace.
153
+ SpaceBetweenSiblings = 512,// Inserts a space between each sibling node.
154
+ Braces = 1024,// The list is surrounded by "{" and "}".
155
+ Parenthesis = 2048,// The list is surrounded by "(" and ")".
156
+ AngleBrackets = 4096,// The list is surrounded by "<" and ">".
157
+ SquareBrackets = 8192,// The list is surrounded by "[" and "]".
158
+ BracketsMask = 15360,
159
+ OptionalIfUndefined = 16384,// Do not emit brackets if the list is undefined.
160
+ OptionalIfEmpty = 32768,// Do not emit brackets if the list is empty.
161
+ Optional = 49152,
162
+ PreferNewLine = 65536,// Prefer adding a LineTerminator between synthesized nodes.
163
+ NoTrailingNewLine = 131072,// Do not emit a trailing NewLine for a MultiLine list.
164
+ NoInterveningComments = 262144,// Do not emit comments between each node
165
+ NoSpaceIfEmpty = 524288,// If the literal is empty, do not add spaces between braces.
166
+ SingleElement = 1048576,
167
+ SpaceAfterList = 2097152,// Add space after list
168
+ Modifiers = 262656,
169
+ SingleLineTypeLiteralMembers = 768,
170
+ MultiLineTypeLiteralMembers = 32897,
171
+ TupleTypeElements = 528,
172
+ UnionTypeConstituents = 516,
173
+ IntersectionTypeConstituents = 520,
174
+ ObjectBindingPatternElements = 525136,
175
+ ArrayBindingPatternElements = 524880,
176
+ ObjectLiteralExpressionProperties = 526226,
177
+ ArrayLiteralExpressionElements = 8914,
178
+ CommaListElements = 528,
179
+ CallExpressionArguments = 2576,
180
+ TemplateExpressionSpans = 262144,
181
+ SingleLineBlockStatements = 768,
182
+ MultiLineBlockStatements = 129,
183
+ VariableDeclarationList = 528,
184
+ SingleLineFunctionBodyStatements = 768,
185
+ MultiLineFunctionBodyStatements = 1,
186
+ CaseBlockClauses = 129,
187
+ NamedImportsOrExportsElements = 525136,
188
+ JsxElementOrFragmentChildren = 262144,
189
+ JsxElementAttributes = 262656,
190
+ CaseOrDefaultClauseStatements = 163969,
191
+ SourceFileStatements = 131073,
192
+ TypeArguments = 53776,
193
+ TypeParameters = 53776,
194
+ Parameters = 2576,
195
+ IndexSignatureParameters = 8848
196
+ }
197
+ export {};
package/dist/types.js ADDED
@@ -0,0 +1,65 @@
1
+ export var ListFormat;
2
+ (function (ListFormat) {
3
+ ListFormat[ListFormat["None"] = 0] = "None";
4
+ // Line separators
5
+ ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine";
6
+ ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine";
7
+ ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines";
8
+ ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask";
9
+ // Delimiters
10
+ ListFormat[ListFormat["NotDelimited"] = 0] = "NotDelimited";
11
+ ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited";
12
+ ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited";
13
+ ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited";
14
+ ListFormat[ListFormat["DelimitersMask"] = 28] = "DelimitersMask";
15
+ ListFormat[ListFormat["AllowTrailingComma"] = 64] = "AllowTrailingComma";
16
+ // Whitespace
17
+ ListFormat[ListFormat["Indented"] = 128] = "Indented";
18
+ ListFormat[ListFormat["SpaceBetweenBraces"] = 256] = "SpaceBetweenBraces";
19
+ ListFormat[ListFormat["SpaceBetweenSiblings"] = 512] = "SpaceBetweenSiblings";
20
+ // Brackets/Braces
21
+ ListFormat[ListFormat["Braces"] = 1024] = "Braces";
22
+ ListFormat[ListFormat["Parenthesis"] = 2048] = "Parenthesis";
23
+ ListFormat[ListFormat["AngleBrackets"] = 4096] = "AngleBrackets";
24
+ ListFormat[ListFormat["SquareBrackets"] = 8192] = "SquareBrackets";
25
+ ListFormat[ListFormat["BracketsMask"] = 15360] = "BracketsMask";
26
+ ListFormat[ListFormat["OptionalIfUndefined"] = 16384] = "OptionalIfUndefined";
27
+ ListFormat[ListFormat["OptionalIfEmpty"] = 32768] = "OptionalIfEmpty";
28
+ ListFormat[ListFormat["Optional"] = 49152] = "Optional";
29
+ // Other
30
+ ListFormat[ListFormat["PreferNewLine"] = 65536] = "PreferNewLine";
31
+ ListFormat[ListFormat["NoTrailingNewLine"] = 131072] = "NoTrailingNewLine";
32
+ ListFormat[ListFormat["NoInterveningComments"] = 262144] = "NoInterveningComments";
33
+ ListFormat[ListFormat["NoSpaceIfEmpty"] = 524288] = "NoSpaceIfEmpty";
34
+ ListFormat[ListFormat["SingleElement"] = 1048576] = "SingleElement";
35
+ ListFormat[ListFormat["SpaceAfterList"] = 2097152] = "SpaceAfterList";
36
+ // Precomputed Formats
37
+ ListFormat[ListFormat["Modifiers"] = 262656] = "Modifiers";
38
+ ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 768] = "SingleLineTypeLiteralMembers";
39
+ ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 32897] = "MultiLineTypeLiteralMembers";
40
+ ListFormat[ListFormat["TupleTypeElements"] = 528] = "TupleTypeElements";
41
+ ListFormat[ListFormat["UnionTypeConstituents"] = 516] = "UnionTypeConstituents";
42
+ ListFormat[ListFormat["IntersectionTypeConstituents"] = 520] = "IntersectionTypeConstituents";
43
+ ListFormat[ListFormat["ObjectBindingPatternElements"] = 525136] = "ObjectBindingPatternElements";
44
+ ListFormat[ListFormat["ArrayBindingPatternElements"] = 524880] = "ArrayBindingPatternElements";
45
+ ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 526226] = "ObjectLiteralExpressionProperties";
46
+ ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 8914] = "ArrayLiteralExpressionElements";
47
+ ListFormat[ListFormat["CommaListElements"] = 528] = "CommaListElements";
48
+ ListFormat[ListFormat["CallExpressionArguments"] = 2576] = "CallExpressionArguments";
49
+ ListFormat[ListFormat["TemplateExpressionSpans"] = 262144] = "TemplateExpressionSpans";
50
+ ListFormat[ListFormat["SingleLineBlockStatements"] = 768] = "SingleLineBlockStatements";
51
+ ListFormat[ListFormat["MultiLineBlockStatements"] = 129] = "MultiLineBlockStatements";
52
+ ListFormat[ListFormat["VariableDeclarationList"] = 528] = "VariableDeclarationList";
53
+ ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 768] = "SingleLineFunctionBodyStatements";
54
+ ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements";
55
+ ListFormat[ListFormat["CaseBlockClauses"] = 129] = "CaseBlockClauses";
56
+ ListFormat[ListFormat["NamedImportsOrExportsElements"] = 525136] = "NamedImportsOrExportsElements";
57
+ ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 262144] = "JsxElementOrFragmentChildren";
58
+ ListFormat[ListFormat["JsxElementAttributes"] = 262656] = "JsxElementAttributes";
59
+ ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 163969] = "CaseOrDefaultClauseStatements";
60
+ ListFormat[ListFormat["SourceFileStatements"] = 131073] = "SourceFileStatements";
61
+ ListFormat[ListFormat["TypeArguments"] = 53776] = "TypeArguments";
62
+ ListFormat[ListFormat["TypeParameters"] = 53776] = "TypeParameters";
63
+ ListFormat[ListFormat["Parameters"] = 2576] = "Parameters";
64
+ ListFormat[ListFormat["IndexSignatureParameters"] = 8848] = "IndexSignatureParameters";
65
+ })(ListFormat || (ListFormat = {}));
@@ -0,0 +1,24 @@
1
+ import type { CommentRange, CompilerOptions, EmitHint, EmitTextWriter, Node, PrintHandlers, PrinterOptions, SourceFile, TextRange } from "./_namespaces/ts.js";
2
+ export declare function usingSingleLineStringWriter(action: (writer: EmitTextWriter) => void): string;
3
+ /**
4
+ * Returns a value indicating whether a name is unique globally or within the current file.
5
+ * Note: This does not consider whether a name appears as a free identifier or not, so at the expression `x.y` this includes both `x` and `y`.
6
+ */
7
+ export declare function isFileLevelUniqueName(sourceFile: SourceFile, name: string, hasGlobalName?: PrintHandlers["hasGlobalName"]): boolean;
8
+ export declare function createTextWriter(newLine: string): EmitTextWriter;
9
+ export declare function getTrailingSemicolonDeferringWriter(writer: EmitTextWriter): EmitTextWriter;
10
+ export declare function emitNewLineBeforeLeadingComments(lineMap: readonly number[], writer: EmitTextWriter, node: TextRange, leadingComments: readonly CommentRange[] | undefined): void;
11
+ export declare function emitNewLineBeforeLeadingCommentsOfPosition(lineMap: readonly number[], writer: EmitTextWriter, pos: number, leadingComments: readonly CommentRange[] | undefined): void;
12
+ export declare function emitNewLineBeforeLeadingCommentOfPosition(lineMap: readonly number[], writer: EmitTextWriter, pos: number, commentPos: number): void;
13
+ export declare function emitComments(text: string, lineMap: readonly number[], writer: EmitTextWriter, comments: readonly CommentRange[] | undefined, leadingSeparator: boolean, trailingSeparator: boolean, newLine: string, writeComment: (text: string, lineMap: readonly number[], writer: EmitTextWriter, commentPos: number, commentEnd: number, newLine: string) => void): void;
14
+ /**
15
+ * Detached comment is a comment at the top of file or function body that is separated from
16
+ * the next statement by space.
17
+ */
18
+ export declare function emitDetachedComments(text: string, lineMap: readonly number[], writer: EmitTextWriter, writeComment: (text: string, lineMap: readonly number[], writer: EmitTextWriter, commentPos: number, commentEnd: number, newLine: string) => void, node: TextRange, newLine: string, removeComments: boolean): {
19
+ nodePos: number;
20
+ detachedCommentEndPos: number;
21
+ } | undefined;
22
+ export declare function writeCommentRange(text: string, lineMap: readonly number[], writer: EmitTextWriter, commentPos: number, commentEnd: number, newLine: string): void;
23
+ export declare function getNewLineCharacter(options: CompilerOptions | PrinterOptions, getNewLine?: () => string): string;
24
+ export declare function noEmitNotification(hint: EmitHint, node: Node, callback: (hint: EmitHint, node: Node) => void): void;