@remotex-labs/xmap 2.0.4 → 3.0.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/README.md +23 -27
- package/dist/cjs/formatter.component.js +5 -0
- package/dist/cjs/formatter.component.js.map +8 -0
- package/dist/cjs/highlighter.component.js +2 -0
- package/dist/cjs/highlighter.component.js.map +8 -0
- package/dist/cjs/index.js +3 -7
- package/dist/cjs/index.js.map +5 -5
- package/dist/cjs/parser.component.js +3 -0
- package/dist/cjs/parser.component.js.map +8 -0
- package/dist/components/base64.component.d.ts +58 -14
- package/dist/components/formatter.component.d.ts +37 -35
- package/dist/components/highlighter.component.d.ts +228 -74
- package/dist/components/interfaces/{formatter.interface.d.ts → formatter-component.interface.d.ts} +27 -9
- package/dist/components/interfaces/highlighter-component.interface.d.ts +94 -0
- package/dist/components/interfaces/parse-component.interface.d.ts +52 -0
- package/dist/components/parser.component.d.ts +216 -5
- package/dist/esm/formatter.component.js +5 -0
- package/dist/esm/formatter.component.js.map +8 -0
- package/dist/esm/highlighter.component.js +2 -0
- package/dist/esm/highlighter.component.js.map +8 -0
- package/dist/esm/index.js +3 -7
- package/dist/esm/index.js.map +5 -5
- package/dist/esm/parser.component.js +3 -0
- package/dist/esm/parser.component.js.map +8 -0
- package/dist/index.d.ts +3 -9
- package/dist/providers/interfaces/mapping-provider.interface.d.ts +141 -0
- package/dist/providers/mapping.provider.d.ts +258 -174
- package/dist/services/interfaces/source-service.interface.d.ts +139 -0
- package/dist/services/source.service.d.ts +96 -97
- package/package.json +37 -11
- package/dist/components/interfaces/highlighter.interface.d.ts +0 -48
- package/dist/components/interfaces/parse.interface.d.ts +0 -31
- package/dist/providers/interfaces/mapping.interface.d.ts +0 -52
- package/dist/services/interfaces/source.interface.d.ts +0 -53
package/README.md
CHANGED
|
@@ -27,6 +27,8 @@ You can create an instance of `SourceService` using either a `SourceMapInterface
|
|
|
27
27
|
a JSON string representing the source map, or an existing `SourceService` instance.
|
|
28
28
|
Example:
|
|
29
29
|
```typescript
|
|
30
|
+
import { SourceService } from '@remotex-labs/xmap';
|
|
31
|
+
|
|
30
32
|
const sourceMapJSON = `
|
|
31
33
|
{
|
|
32
34
|
"version": 3,
|
|
@@ -80,31 +82,22 @@ console.log(sourceService.sources); // Updated source paths
|
|
|
80
82
|
```
|
|
81
83
|
|
|
82
84
|
## Parsing Error Stack Traces
|
|
83
|
-
The parseErrorStack function parses an error stack trace and returns an array of stack entries.
|
|
84
|
-
Each entry contains information about the function call, file, line number, column number,
|
|
85
|
-
|
|
86
|
-
```typescript
|
|
87
|
-
import { parseErrorStack } from '@remotex-labs/xmap';
|
|
88
|
-
|
|
89
|
-
// Example stack trace string
|
|
90
|
-
const stackTrace = `
|
|
91
|
-
Error: Example error
|
|
92
|
-
at Object.<anonymous> (/path/to/file.js:10:15)
|
|
93
|
-
at Module._compile (node:internal/modules/cjs/loader:1217:14)
|
|
94
|
-
at node:internal/modules/cjs/loader:1308:14
|
|
95
|
-
at node:internal/modules/cjs/loader:1425:5
|
|
96
|
-
at node:internal/modules/cjs/loader:1425:5
|
|
97
|
-
at node:internal/modules/cjs/loader:1483:3
|
|
98
|
-
at node:internal/modules/cjs/loader:1700:8
|
|
99
|
-
at node:internal/modules/cjs/loader:1760:3
|
|
100
|
-
at /path/to/file.js:10:15
|
|
101
|
-
at Object.<anonymous> (/path/to/file.js:10:15)
|
|
102
|
-
at eval (eval at <anonymous> (/path/to/file.js:10:15), <anonymous>:1:1)
|
|
103
|
-
`;
|
|
85
|
+
The parseErrorStack function parses an error stack trace and returns an array of stack entries.
|
|
86
|
+
Each entry contains information about the function call, file, line number, column number,
|
|
87
|
+
and if applicable, details about the eval context.
|
|
104
88
|
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
89
|
+
### Example:
|
|
90
|
+
```typescript
|
|
91
|
+
import { parseErrorStack } from '@remotex-labs/xmap/parser.component';
|
|
92
|
+
|
|
93
|
+
// Example with Error object
|
|
94
|
+
try {
|
|
95
|
+
throw new Error('Example error');
|
|
96
|
+
} catch (error) {
|
|
97
|
+
// Parsing the stack trace from an Error object
|
|
98
|
+
const parsedStack = parseErrorStack(error);
|
|
99
|
+
console.log(parsedStack);
|
|
100
|
+
}
|
|
108
101
|
```
|
|
109
102
|
|
|
110
103
|
## highlightCode
|
|
@@ -114,7 +107,7 @@ and applies syntax highlighting according to the given schema.
|
|
|
114
107
|
|
|
115
108
|
Example:
|
|
116
109
|
```typescript
|
|
117
|
-
import { highlightCode } from '@remotex-labs/xmap';
|
|
110
|
+
import { highlightCode } from '@remotex-labs/xmap/highlighter.component';
|
|
118
111
|
|
|
119
112
|
// TypeScript code to be highlighted
|
|
120
113
|
const codeToHighlight = `
|
|
@@ -147,7 +140,8 @@ This utility is useful for displaying code snippets in a user-friendly manner, p
|
|
|
147
140
|
|
|
148
141
|
Example:
|
|
149
142
|
```typescript
|
|
150
|
-
import { formatCode
|
|
143
|
+
import { formatCode } from '@remotex-labs/xmap/formatter.component';
|
|
144
|
+
import { highlightCode } from '@remotex-labs/xmap/highlighter.component';
|
|
151
145
|
|
|
152
146
|
const code = `
|
|
153
147
|
function greet(name: string) {
|
|
@@ -178,7 +172,9 @@ applying special highlighting to indicate where the error occurred. This functio
|
|
|
178
172
|
as it helps to visually identify issues in the source code.
|
|
179
173
|
|
|
180
174
|
```typescript
|
|
181
|
-
import {
|
|
175
|
+
import { SourceService } from '@remotex-labs/xmap';
|
|
176
|
+
import { highlightCode } from '@remotex-labs/xmap/highlighter.component';
|
|
177
|
+
import { formatErrorCode } from '@remotex-labs/xmap/formatter.component';
|
|
182
178
|
|
|
183
179
|
const sourceMapJSON = `
|
|
184
180
|
{
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
"use strict";var s=Object.defineProperty;var $=Object.getOwnPropertyDescriptor;var g=Object.getOwnPropertyNames;var I=Object.prototype.hasOwnProperty;var C=(r,e)=>{for(var n in e)s(r,n,{get:e[n],enumerable:!0})},L=(r,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of g(e))!I.call(r,t)&&t!==n&&s(r,t,{get:()=>e[t],enumerable:!(o=$(e,t))||o.enumerable});return r};var x=r=>L(s({},"__esModule",{value:!0}),r);var b={};C(b,{formatCode:()=>d,formatErrorCode:()=>h});module.exports=x(b);function d(r,e={}){let n=r.split(`
|
|
2
|
+
`),o=e.padding??10,t=e.startLine??0;return n.map((f,i)=>{let c=i+t+1,a=`${`${c} | `.padStart(o)}${f}`;return e.action&&c===e.action.triggerLine?e.action.callback(a,o,c):a}).join(`
|
|
3
|
+
`)}function h(r,e){let{code:n,line:o,column:t,startLine:f}=r;if(o<f||t<1)throw new Error("Invalid line or column number.");return d(n,{startLine:f,action:{triggerLine:o,callback:(i,c,m)=>{let a="^",l=c-1,p=">";e&&(a=`${e.color}${a}${e.reset}`,l+=e.color.length+e.reset.length,p=`${e.color}>${e.reset}`);let u=" | ".padStart(c)+" ".repeat(t-1)+`${a}`;return i=`${p} ${m} |`.padStart(l)+i.split("|")[1],i+`
|
|
4
|
+
${u}`}}})}0&&(module.exports={formatCode,formatErrorCode});
|
|
5
|
+
//# sourceMappingURL=formatter.component.js.map
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/components/formatter.component.ts"],
|
|
4
|
+
"sourceRoot": "https://github.com/remotex-lab/xmap/tree/v3.0.0/",
|
|
5
|
+
"sourcesContent": ["/**\n * Export interfaces\n */\nexport type { AnsiOptionInterface, FormatCodeInterface } from '@components/interfaces/formatter-component.interface';\n/**\n * Import will remove at compile time\n */\nimport type { PositionWithCodeInterface } from '@services/interfaces/source-service.interface';\nimport type { AnsiOptionInterface, FormatCodeInterface } from '@components/interfaces/formatter-component.interface';\n/**\n * Formats a code snippet with optional line padding and custom actions\n *\n * @param code - The source code | stack to be formatted\n * @param options - Configuration options for formatting the code\n * @returns A formatted string of the code snippet with applied padding and custom actions\n *\n * @remarks\n * This function takes a code string and an options object to format the code snippet.\n * It applies padding to line numbers and can trigger custom actions for specific lines.\n * Options include padding (default 10), startLine (default 0), and custom actions for specific lines.\n *\n * @example\n * ```ts\n * const formattedCode = formatCode(code, {\n * padding: 8,\n * startLine: 5,\n * action: {\n * triggerLine: 7,\n * callback: (lineString, padding, lineNumber) => {\n * return `Custom formatting for line ${lineNumber}: ${lineString}`;\n * }\n * }\n * });\n * ```\n *\n * @since 1.0.0\n */\nexport function formatCode(code: string, options: FormatCodeInterface = {}): string {\n const lines = code.split('\\n');\n const padding = options.padding ?? 10;\n const startLine = options.startLine ?? 0;\n return lines.map((lineContent, index) => {\n const currentLineNumber = index + startLine + 1;\n const prefix = `${currentLineNumber} | `;\n const string = `${prefix.padStart(padding)}${lineContent}`;\n if (options.action && currentLineNumber === options.action.triggerLine) {\n return options.action.callback(string, padding, currentLineNumber);\n }\n return string;\n }).join('\\n');\n}\n/**\n * Formats a code snippet around an error location with special highlighting\n *\n * @param sourcePosition - An object containing information about the source code and error location\n * @param ansiOption - Optional configuration for ANSI color codes\n * @returns A formatted string representing the relevant code snippet with error highlighting\n *\n * @throws Error - If the provided sourcePosition object has invalid line or column numbers\n *\n * @remarks\n * This function takes a sourcePosition object with code content and error location information,\n * then uses formatCode to format and highlight the relevant code snippet around the error.\n * The sourcePosition object should contain code (string), line (number), column (number),\n * and optional startLine (number, defaults to 1).\n *\n * @example\n * ```ts\n * const formattedErrorCode = formatErrorCode({\n * code: \"const x = 1;\\nconst y = x.undefined;\\n\",\n * line: 2,\n * column: 15,\n * startLine: 1\n * });\n * ```\n *\n * @see formatCode - The underlying function used for basic code formatting\n *\n * @since 1.0.0\n */\nexport function formatErrorCode(sourcePosition: PositionWithCodeInterface, ansiOption?: AnsiOptionInterface): string {\n const { code, line: errorLine, column: errorColumn, startLine } = sourcePosition;\n // Validate line and column numbers\n if (errorLine < startLine || errorColumn < 1) {\n throw new Error('Invalid line or column number.');\n }\n return formatCode(code, {\n startLine,\n action: {\n triggerLine: errorLine,\n callback: (lineString, padding, line) => {\n let pointer = '^';\n let ansiPadding = padding - 1; // 1 size of the char we added\n let prefixPointer = '>';\n if (ansiOption) {\n pointer = `${ansiOption.color}${pointer}${ansiOption.reset}`;\n ansiPadding += (ansiOption.color.length + ansiOption.reset.length);\n prefixPointer = `${ansiOption.color}>${ansiOption.reset}`;\n }\n const errorMarker = ' | '.padStart(padding) + ' '.repeat(errorColumn - 1) + `${pointer}`;\n lineString = `${prefixPointer} ${line} |`.padStart(ansiPadding) + lineString.split('|')[1];\n return lineString + `\\n${errorMarker}`;\n }\n }\n });\n}\n"],
|
|
6
|
+
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,gBAAAE,EAAA,oBAAAC,IAAA,eAAAC,EAAAJ,GAqCO,SAASE,EAAWG,EAAcC,EAA+B,CAAC,EAAW,CAChF,IAAMC,EAAQF,EAAK,MAAM;AAAA,CAAI,EACvBG,EAAUF,EAAQ,SAAW,GAC7BG,EAAYH,EAAQ,WAAa,EACvC,OAAOC,EAAM,IAAI,CAACG,EAAaC,IAAU,CACrC,IAAMC,EAAoBD,EAAQF,EAAY,EAExCI,EAAS,GADA,GAAGD,CAAiB,MACV,SAASJ,CAAO,CAAC,GAAGE,CAAW,GACxD,OAAIJ,EAAQ,QAAUM,IAAsBN,EAAQ,OAAO,YAChDA,EAAQ,OAAO,SAASO,EAAQL,EAASI,CAAiB,EAE9DC,CACX,CAAC,EAAE,KAAK;AAAA,CAAI,CAChB,CA8BO,SAASV,EAAgBW,EAA2CC,EAA0C,CACjH,GAAM,CAAE,KAAAV,EAAM,KAAMW,EAAW,OAAQC,EAAa,UAAAR,CAAU,EAAIK,EAElE,GAAIE,EAAYP,GAAaQ,EAAc,EACvC,MAAM,IAAI,MAAM,gCAAgC,EAEpD,OAAOf,EAAWG,EAAM,CACpB,UAAAI,EACA,OAAQ,CACJ,YAAaO,EACb,SAAU,CAACE,EAAYV,EAASW,IAAS,CACrC,IAAIC,EAAU,IACVC,EAAcb,EAAU,EACxBc,EAAgB,IAChBP,IACAK,EAAU,GAAGL,EAAW,KAAK,GAAGK,CAAO,GAAGL,EAAW,KAAK,GAC1DM,GAAgBN,EAAW,MAAM,OAASA,EAAW,MAAM,OAC3DO,EAAgB,GAAGP,EAAW,KAAK,IAAIA,EAAW,KAAK,IAE3D,IAAMQ,EAAc,MAAM,SAASf,CAAO,EAAI,IAAI,OAAOS,EAAc,CAAC,EAAI,GAAGG,CAAO,GACtF,OAAAF,EAAa,GAAGI,CAAa,IAAIH,CAAI,KAAK,SAASE,CAAW,EAAIH,EAAW,MAAM,GAAG,EAAE,CAAC,EAClFA,EAAa;AAAA,EAAKK,CAAW,EACxC,CACJ,CACJ,CAAC,CACL",
|
|
7
|
+
"names": ["formatter_component_exports", "__export", "formatCode", "formatErrorCode", "__toCommonJS", "code", "options", "lines", "padding", "startLine", "lineContent", "index", "currentLineNumber", "string", "sourcePosition", "ansiOption", "errorLine", "errorColumn", "lineString", "line", "pointer", "ansiPadding", "prefixPointer", "errorMarker"]
|
|
8
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var u=Object.create;var h=Object.defineProperty;var y=Object.getOwnPropertyDescriptor;var x=Object.getOwnPropertyNames;var C=Object.getPrototypeOf,K=Object.prototype.hasOwnProperty;var f=(a,e)=>{for(var t in e)h(a,t,{get:e[t],enumerable:!0})},m=(a,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of x(e))!K.call(a,i)&&i!==t&&h(a,i,{get:()=>e[i],enumerable:!(s=y(e,i))||s.enumerable});return a};var b=(a,e,t)=>(t=a!=null?u(C(a)):{},m(e||!a||!a.__esModule?h(t,"default",{value:a,enumerable:!0}):t,a)),v=a=>m(h({},"__esModule",{value:!0}),a);var T={};f(T,{CodeHighlighter:()=>d,Colors:()=>S,highlightCode:()=>w});module.exports=v(T);var r=b(require("typescript"),1),l=require("typescript"),S=(o=>(o.reset="\x1B[0m",o.gray="\x1B[38;5;243m",o.darkGray="\x1B[38;5;238m",o.lightCoral="\x1B[38;5;203m",o.lightOrange="\x1B[38;5;215m",o.oliveGreen="\x1B[38;5;149m",o.burntOrange="\x1B[38;5;208m",o.lightGoldenrodYellow="\x1B[38;5;221m",o.lightYellow="\x1B[38;5;230m",o.canaryYellow="\x1B[38;5;227m",o.deepOrange="\x1B[38;5;166m",o.lightGray="\x1B[38;5;252m",o.brightPink="\x1B[38;5;197m",o))(S||{}),E={enumColor:"\x1B[38;5;208m",typeColor:"\x1B[38;5;221m",classColor:"\x1B[38;5;215m",stringColor:"\x1B[38;5;149m",keywordColor:"\x1B[38;5;203m",commentColor:"\x1B[38;5;238m",functionColor:"\x1B[38;5;215m",variableColor:"\x1B[38;5;208m",interfaceColor:"\x1B[38;5;221m",parameterColor:"\x1B[38;5;166m",getAccessorColor:"\x1B[38;5;230m",numericLiteralColor:"\x1B[38;5;252m",methodSignatureColor:"\x1B[38;5;208m",regularExpressionColor:"\x1B[38;5;149m",propertyAssignmentColor:"\x1B[38;5;227m",propertyAccessExpressionColor:"\x1B[38;5;230m",expressionWithTypeArgumentsColor:"\x1B[38;5;215m"},d=class{constructor(e,t,s){this.sourceFile=e;this.code=t;this.schema=s}segments=new Map;parseNode(e){this.processComments(e),this.processKeywords(e),this.processNode(e)}highlight(){let e=0,t,s=[];return Array.from(this.segments.values()).sort((n,c)=>n.start-c.start||n.end-c.end).forEach(n=>{if(t&&n.start<t.end){let c=s.pop();if(!c)return;let g=this.getSegmentSource(n.start,n.end),p=`${n.color}${g}${t.color}`;s.push(c.replace(g,p));return}s.push(this.getSegmentSource(e,n.start)),s.push(`${n.color}${this.getSegmentSource(n.start,n.end)}${n.reset}`),e=n.end,t=n}),s.join("")+this.getSegmentSource(e)}getSegmentSource(e,t){return this.code.slice(e,t)}addSegment(e,t,s,i="\x1B[0m"){let n=`${e}-${t}`;this.segments.set(n,{start:e,end:t,color:s,reset:i})}processComments(e){[...r.getTrailingCommentRanges(this.sourceFile.getFullText(),e.getFullStart())||[],...r.getLeadingCommentRanges(this.sourceFile.getFullText(),e.getFullStart())||[]].forEach(s=>this.addSegment(s.pos,s.end,this.schema.commentColor))}processKeywords(e){if([l.SyntaxKind.NullKeyword,l.SyntaxKind.VoidKeyword,l.SyntaxKind.StringKeyword,l.SyntaxKind.NumberKeyword,l.SyntaxKind.BooleanKeyword,l.SyntaxKind.UndefinedKeyword].includes(e.kind))return this.addSegment(e.getStart(),e.getEnd(),this.schema.typeColor);e&&e.kind>=r.SyntaxKind.FirstKeyword&&e.kind<=r.SyntaxKind.LastKeyword&&this.addSegment(e.getStart(),e.getEnd(),this.schema.keywordColor)}processIdentifier(e){let t=e.getEnd(),s=e.getStart();switch(e.parent.kind){case r.SyntaxKind.EnumMember:return this.addSegment(s,t,this.schema.enumColor);case r.SyntaxKind.CallExpression:case r.SyntaxKind.EnumDeclaration:case r.SyntaxKind.PropertySignature:case r.SyntaxKind.ModuleDeclaration:return this.addSegment(s,t,this.schema.variableColor);case r.SyntaxKind.InterfaceDeclaration:return this.addSegment(s,t,this.schema.interfaceColor);case r.SyntaxKind.GetAccessor:return this.addSegment(s,t,this.schema.getAccessorColor);case r.SyntaxKind.PropertyAssignment:return this.addSegment(s,t,this.schema.propertyAssignmentColor);case r.SyntaxKind.MethodSignature:return this.addSegment(s,t,this.schema.methodSignatureColor);case r.SyntaxKind.MethodDeclaration:case r.SyntaxKind.FunctionDeclaration:return this.addSegment(s,t,this.schema.functionColor);case r.SyntaxKind.ClassDeclaration:return this.addSegment(s,t,this.schema.classColor);case r.SyntaxKind.Parameter:return this.addSegment(s,t,this.schema.parameterColor);case r.SyntaxKind.VariableDeclaration:return this.addSegment(s,t,this.schema.variableColor);case r.SyntaxKind.PropertyDeclaration:return this.addSegment(s,t,this.schema.variableColor);case r.SyntaxKind.PropertyAccessExpression:return e.parent.getChildAt(0).getText()===e.getText()?this.addSegment(s,t,this.schema.variableColor):this.addSegment(s,t,this.schema.propertyAccessExpressionColor);case r.SyntaxKind.ExpressionWithTypeArguments:return this.addSegment(s,t,this.schema.expressionWithTypeArgumentsColor);case r.SyntaxKind.BreakStatement:case r.SyntaxKind.ShorthandPropertyAssignment:case r.SyntaxKind.BindingElement:return this.addSegment(s,t,this.schema.variableColor);case r.SyntaxKind.BinaryExpression:case r.SyntaxKind.SwitchStatement:case r.SyntaxKind.TemplateSpan:return this.addSegment(s,t,this.schema.variableColor);case r.SyntaxKind.TypeReference:case r.SyntaxKind.TypeAliasDeclaration:return this.addSegment(s,t,this.schema.typeColor);case r.SyntaxKind.NewExpression:return this.addSegment(s,t,this.schema.variableColor)}}processTemplateExpression(e){let t=e.head.getStart(),s=e.head.getEnd();this.addSegment(t,s,this.schema.stringColor),e.templateSpans.forEach(i=>{let n=i.literal.getStart(),c=i.literal.getEnd();this.addSegment(n,c,this.schema.stringColor)})}processNode(e){let t=e.getStart(),s=e.getEnd();switch(e.kind){case r.SyntaxKind.TypeParameter:return this.addSegment(t,t+e.name.text.length,this.schema.typeColor);case r.SyntaxKind.TypeReference:return this.addSegment(t,s,this.schema.typeColor);case r.SyntaxKind.StringLiteral:case r.SyntaxKind.NoSubstitutionTemplateLiteral:return this.addSegment(t,s,this.schema.stringColor);case r.SyntaxKind.RegularExpressionLiteral:return this.addSegment(t,s,this.schema.regularExpressionColor);case r.SyntaxKind.TemplateExpression:return this.processTemplateExpression(e);case r.SyntaxKind.Identifier:return this.processIdentifier(e);case r.SyntaxKind.BigIntLiteral:case r.SyntaxKind.NumericLiteral:return this.addSegment(t,s,this.schema.numericLiteralColor)}}};function w(a,e={}){let t=r.createSourceFile("temp.ts",a,r.ScriptTarget.Latest,!0,r.ScriptKind.TS),s=new d(t,a,Object.assign(E,e));function i(n){s.parseNode(n);for(let c=0;c<n.getChildCount();c++)i(n.getChildAt(c))}return r.forEachChild(t,i),s.highlight()}0&&(module.exports={CodeHighlighter,Colors,highlightCode});
|
|
2
|
+
//# sourceMappingURL=highlighter.component.js.map
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/components/highlighter.component.ts"],
|
|
4
|
+
"sourceRoot": "https://github.com/remotex-lab/xmap/tree/v3.0.0/",
|
|
5
|
+
"sourcesContent": ["/**\n * Export interfaces\n */\nexport type { HighlightSchemeInterface, HighlightNodeSegmentInterface } from '@components/interfaces/highlighter-component.interface';\n/**\n * Import will remove at compile time\n */\nimport type { HighlightSchemeInterface, HighlightNodeSegmentInterface } from '@components/interfaces/highlighter-component.interface';\n/**\n * Imports\n */\nimport * as ts from 'typescript';\nimport { SyntaxKind } from 'typescript';\n/**\n * An enum containing ANSI escape sequences for various colors\n *\n * @remarks\n * This enum is primarily intended for terminal output and won't work directly in JavaScript for web development.\n * It defines color codes for various colors and a reset code to return to the default text color.\n *\n * @example\n * ```ts\n * console.log(`${Colors.red}This text will be red in the terminal.${Colors.reset}`);\n * ```\n *\n * @since 1.0.0\n */\nexport const enum Colors {\n reset = '\\x1b[0m',\n gray = '\\x1b[38;5;243m',\n darkGray = '\\x1b[38;5;238m',\n lightCoral = '\\x1b[38;5;203m',\n lightOrange = '\\x1b[38;5;215m',\n oliveGreen = '\\x1b[38;5;149m',\n burntOrange = '\\x1b[38;5;208m',\n lightGoldenrodYellow = '\\x1b[38;5;221m',\n lightYellow = '\\x1b[38;5;230m',\n canaryYellow = '\\x1b[38;5;227m',\n deepOrange = '\\x1b[38;5;166m',\n lightGray = '\\x1b[38;5;252m',\n brightPink = '\\x1b[38;5;197m'\n}\n/**\n * Default color scheme for semantic highlighting\n *\n * @remarks\n * This scheme defines colors for different code elements to be used for syntax highlighting.\n *\n * @example\n * ```ts\n * const scheme = defaultScheme;\n * console.log(scheme.typeColor); // Outputs: the color code for types\n * ```\n *\n * @see HighlightSchemeInterface\n * @see Colors\n *\n * @since 1.0.0\n */\nconst defaultScheme: HighlightSchemeInterface = {\n enumColor: Colors.burntOrange,\n typeColor: Colors.lightGoldenrodYellow,\n classColor: Colors.lightOrange,\n stringColor: Colors.oliveGreen,\n keywordColor: Colors.lightCoral,\n commentColor: Colors.darkGray,\n functionColor: Colors.lightOrange,\n variableColor: Colors.burntOrange,\n interfaceColor: Colors.lightGoldenrodYellow,\n parameterColor: Colors.deepOrange,\n getAccessorColor: Colors.lightYellow,\n numericLiteralColor: Colors.lightGray,\n methodSignatureColor: Colors.burntOrange,\n regularExpressionColor: Colors.oliveGreen,\n propertyAssignmentColor: Colors.canaryYellow,\n propertyAccessExpressionColor: Colors.lightYellow,\n expressionWithTypeArgumentsColor: Colors.lightOrange\n};\n/**\n * Class responsible for applying semantic highlighting to a source code string based on a given color scheme\n *\n * @remarks\n * Processes TypeScript AST nodes and applies color formatting to different code elements\n * according to the provided color scheme.\n *\n * @example\n * ```ts\n * const sourceFile = ts.createSourceFile('example.ts', code, ts.ScriptTarget.Latest);\n * const highlighter = new CodeHighlighter(sourceFile, code, customScheme);\n * highlighter.parseNode(sourceFile);\n * const highlightedCode = highlighter.highlight();\n * ```\n *\n * @since 1.0.0\n */\nexport class CodeHighlighter {\n /**\n * A Map of segments where the key is a combination of start and end positions.\n *\n * @remarks\n * This structure ensures unique segments and allows for fast lookups and updates.\n *\n * @see HighlightNodeSegmentInterface\n * @since 1.0.0\n */\n private segments: Map<string, HighlightNodeSegmentInterface> = new Map();\n /**\n * Creates an instance of the CodeHighlighter class.\n *\n * @param sourceFile - The TypeScript AST node representing the source file\n * @param code - The source code string to be highlighted\n * @param schema - The color scheme used for highlighting different elements in the code\n *\n * @since 1.0.0\n */\n constructor(private sourceFile: ts.Node, private code: string, private schema: HighlightSchemeInterface) {\n }\n /**\n * Parses a TypeScript AST node and processes its comments to identify segments that need highlighting.\n *\n * @param node - The TypeScript AST node to be parsed\n *\n * @since 1.0.0\n */\n parseNode(node: ts.Node): void {\n this.processComments(node);\n this.processKeywords(node);\n this.processNode(node);\n }\n /**\n * Generates a string with highlighted code segments based on the provided color scheme.\n *\n * @returns The highlighted code as a string, with ANSI color codes applied to the segments\n *\n * @remarks\n * This method processes the stored segments, applies the appropriate colors to each segment,\n * and returns the resulting highlighted code as a single string.\n *\n * @since 1.0.0\n */\n highlight(): string {\n let previousSegmentEnd = 0;\n let parent: HighlightNodeSegmentInterface | undefined;\n const result: Array<string> = [];\n const segments = Array.from(this.segments.values()).sort((a, b) => a.start - b.start || a.end - b.end);\n segments.forEach((segment) => {\n if (parent && segment.start < parent.end) {\n const lastSegment = result.pop();\n if (!lastSegment)\n return;\n const source = this.getSegmentSource(segment.start, segment.end);\n const combinedSource = `${segment.color}${source}${parent.color}`;\n result.push(lastSegment.replace(source, combinedSource));\n return;\n }\n result.push(this.getSegmentSource(previousSegmentEnd, segment.start));\n result.push(`${segment.color}${this.getSegmentSource(segment.start, segment.end)}${segment.reset}`);\n previousSegmentEnd = segment.end;\n parent = segment;\n });\n return result.join('') + this.getSegmentSource(previousSegmentEnd);\n }\n /**\n * Extracts a text segment from the source code using position indices.\n *\n * @param start - The starting index position in the source text\n * @param end - The ending index position in the source text (optional)\n * @returns The substring of source text between the start and end positions\n *\n * @remarks\n * This utility method provides access to specific portions of the source code\n * based on character positions. When the end parameter is omitted, the extraction\n * will continue to the end of the source text.\n *\n * This method is typically used during the highlighting process to access the\n * actual text content that corresponds to syntax nodes or other text ranges\n * before applying formatting.\n *\n * @example\n * ```ts\n * // Extract a variable name\n * const variableName = this.getSegmentSource(10, 15);\n *\n * // Extract from a position to the end of source\n * const remaining = this.getSegmentSource(100);\n * ```\n *\n * @see addSegment\n * @see highlight\n *\n * @since 1.0.0\n */\n private getSegmentSource(start: number, end?: number): string {\n return this.code.slice(start, end);\n }\n /**\n * Registers a text segment for syntax highlighting with specified style information.\n *\n * @param start - The starting position of the segment in the source text\n * @param end - The ending position of the segment in the source text\n * @param color - The color code to apply to this segment\n * @param reset - The color reset code to apply after the segment (defaults to the standard reset code)\n *\n * @remarks\n * This method creates a unique key for each segment based on its position and stores the segment information in a map.\n * Each segment contains its position information, styling code,\n * and reset code which will later be used during the highlighting process.\n *\n * If multiple segments are added with the same positions, the later additions will\n * overwrite earlier ones due to the map's key-based storage.\n *\n * @example\n * ```ts\n * // Highlight a variable name in red\n * this.addSegment(10, 15, Colors.red);\n *\n * // Highlight a keyword with custom color and reset\n * this.addSegment(20, 26, Colors.blue, Colors.customReset);\n * ```\n *\n * @see Colors\n * @see processNode\n *\n * @since 1.0.0\n */\n private addSegment(start: number, end: number, color: string, reset: string = Colors.reset) {\n const key = `${start}-${end}`;\n this.segments.set(key, { start, end, color, reset });\n }\n /**\n * Processes and highlights comments associated with a TypeScript AST node.\n *\n * @param node - The TypeScript AST node whose comments are to be processed\n *\n * @remarks\n * This method identifies both leading and trailing comments associated with the given node\n * and adds them to the highlighting segments.\n * The comments are extracted from the full source text using TypeScript's utility functions\n * and are highlighted using the color specified\n * in the schema's commentColor property.\n *\n * Leading comments appear before the node, while trailing comments appear after it.\n * Both types are processed with the same highlighting style.\n *\n * @example\n * ```ts\n * // For a node that might have comments like:\n * // This is a leading comment\n * const x = 5; // This is a trailing comment\n *\n * this.processComments(someNode);\n * // Both comments will be added to segments with the comment color\n * ```\n *\n * @see addSegment\n * @see ts.getLeadingCommentRanges\n * @see ts.getTrailingCommentRanges\n *\n * @since 1.0.0\n */\n private processComments(node: ts.Node): void {\n const comments = [\n ...ts.getTrailingCommentRanges(this.sourceFile.getFullText(), node.getFullStart()) || [],\n ...ts.getLeadingCommentRanges(this.sourceFile.getFullText(), node.getFullStart()) || []\n ];\n comments.forEach(comment => this.addSegment(comment.pos, comment.end, this.schema.commentColor));\n }\n /**\n * Processes TypeScript keywords and primitive type references in an AST node for syntax highlighting.\n *\n * @param node - The TypeScript AST node to be processed for keywords\n *\n * @remarks\n * This method handles two categories of tokens that require special highlighting:\n *\n * 1. Primitive type references: Highlights references to built-in types like `null`,\n * `void`, `string`, `number`, `boolean`, and `undefined` using the type color.\n *\n * 2. TypeScript keywords: Identifies any node whose kind falls within the TypeScript\n * keyword range (between FirstKeyword and LastKeyword) and highlights it using\n * the keyword color.\n *\n * Each identified token is added to the segments collection with appropriate position\n * and color information.\n *\n * @example\n * ```ts\n * // Inside syntax highlighting process\n * this.processKeywords(someNode);\n * // If the node represents a keyword like 'const' or a primitive type like 'string',\n * // it will be added to the segments with the appropriate color\n * ```\n *\n * @see addSegment\n * @see ts.SyntaxKind\n *\n * @since 1.0.0\n */\n private processKeywords(node: ts.Node): void {\n if ([\n SyntaxKind.NullKeyword,\n SyntaxKind.VoidKeyword,\n SyntaxKind.StringKeyword,\n SyntaxKind.NumberKeyword,\n SyntaxKind.BooleanKeyword,\n SyntaxKind.UndefinedKeyword\n ].includes(node.kind)) {\n return this.addSegment(node.getStart(), node.getEnd(), this.schema.typeColor);\n }\n if (node && node.kind >= ts.SyntaxKind.FirstKeyword && node.kind <= ts.SyntaxKind.LastKeyword) {\n this.addSegment(node.getStart(), node.getEnd(), this.schema.keywordColor);\n }\n }\n /**\n * Processes identifier nodes and applies appropriate syntax highlighting based on their context.\n *\n * @param node - The TypeScript AST node representing the identifier to be processed\n *\n * @remarks\n * This method determines the appropriate color for an identifier by examining its parent node's kind.\n * Different colors are applied based on the identifier's role in the code:\n * - Enum members use enumColor\n * - Interface names use interfaceColor\n * - Class names use classColor\n * - Function and method names use functionColor\n * - Parameters use parameterColor\n * - Variables and properties use variableColor\n * - Types use typeColor\n * - And more specialized cases for other syntax kinds\n *\n * Special handling is applied to property access expressions to differentiate between\n * the object being accessed and the property being accessed.\n *\n * @example\n * ```ts\n * // Inside the CodeHighlighter class\n * const identifierNode = getIdentifierNode(); // Get some identifier node\n * this.processIdentifier(identifierNode);\n * // The identifier is now added to segments with appropriate color based on its context\n * ```\n *\n * @see addSegment\n * @see HighlightSchemeInterface\n *\n * @since 1.0.0\n */\n private processIdentifier(node: ts.Node): void {\n const end = node.getEnd();\n const start = node.getStart();\n switch (node.parent.kind) {\n case ts.SyntaxKind.EnumMember:\n return this.addSegment(start, end, this.schema.enumColor);\n case ts.SyntaxKind.CallExpression:\n case ts.SyntaxKind.EnumDeclaration:\n case ts.SyntaxKind.PropertySignature:\n case ts.SyntaxKind.ModuleDeclaration:\n return this.addSegment(start, end, this.schema.variableColor);\n case ts.SyntaxKind.InterfaceDeclaration:\n return this.addSegment(start, end, this.schema.interfaceColor);\n case ts.SyntaxKind.GetAccessor:\n return this.addSegment(start, end, this.schema.getAccessorColor);\n case ts.SyntaxKind.PropertyAssignment:\n return this.addSegment(start, end, this.schema.propertyAssignmentColor);\n case ts.SyntaxKind.MethodSignature:\n return this.addSegment(start, end, this.schema.methodSignatureColor);\n case ts.SyntaxKind.MethodDeclaration:\n case ts.SyntaxKind.FunctionDeclaration:\n return this.addSegment(start, end, this.schema.functionColor);\n case ts.SyntaxKind.ClassDeclaration:\n return this.addSegment(start, end, this.schema.classColor);\n case ts.SyntaxKind.Parameter:\n return this.addSegment(start, end, this.schema.parameterColor);\n case ts.SyntaxKind.VariableDeclaration:\n return this.addSegment(start, end, this.schema.variableColor);\n case ts.SyntaxKind.PropertyDeclaration:\n return this.addSegment(start, end, this.schema.variableColor);\n case ts.SyntaxKind.PropertyAccessExpression: {\n if (node.parent.getChildAt(0).getText() === node.getText()) {\n return this.addSegment(start, end, this.schema.variableColor);\n }\n return this.addSegment(start, end, this.schema.propertyAccessExpressionColor);\n }\n case ts.SyntaxKind.ExpressionWithTypeArguments:\n return this.addSegment(start, end, this.schema.expressionWithTypeArgumentsColor);\n case ts.SyntaxKind.BreakStatement:\n case ts.SyntaxKind.ShorthandPropertyAssignment:\n case ts.SyntaxKind.BindingElement:\n return this.addSegment(start, end, this.schema.variableColor);\n case ts.SyntaxKind.BinaryExpression:\n case ts.SyntaxKind.SwitchStatement:\n case ts.SyntaxKind.TemplateSpan:\n return this.addSegment(start, end, this.schema.variableColor);\n case ts.SyntaxKind.TypeReference:\n case ts.SyntaxKind.TypeAliasDeclaration:\n return this.addSegment(start, end, this.schema.typeColor);\n case ts.SyntaxKind.NewExpression:\n return this.addSegment(start, end, this.schema.variableColor);\n }\n }\n /**\n * Processes a TypeScript template expression and adds highlighting segments for its literal parts.\n *\n * @param templateExpression - The TypeScript template expression to be processed\n *\n * @remarks\n * This method adds color segments for both the template head and each template span's literal part.\n * All template string components are highlighted using the color defined in the schema's stringColor.\n *\n * @example\n * ```ts\n * // Given a template expression like: `Hello ${name}`\n * this.processTemplateExpression(templateNode);\n * // Both \"Hello \" and the closing part after the expression will be highlighted\n * ```\n *\n * @see addSegment\n *\n * @since 1.0.0\n */\n private processTemplateExpression(templateExpression: ts.TemplateExpression): void {\n const start = templateExpression.head.getStart();\n const end = templateExpression.head.getEnd();\n this.addSegment(start, end, this.schema.stringColor);\n templateExpression.templateSpans.forEach(span => {\n const spanStart = span.literal.getStart();\n const spanEnd = span.literal.getEnd();\n this.addSegment(spanStart, spanEnd, this.schema.stringColor);\n });\n }\n /**\n * Processes a TypeScript AST node and adds highlighting segments based on the node's kind.\n *\n * @param node - The TypeScript AST node to be processed\n *\n * @remarks\n * This method identifies the node's kind and applies the appropriate color for highlighting.\n * It handles various syntax kinds including literals (string, numeric, regular expressions),\n * template expressions, identifiers, and type references.\n * For complex node types like template expressions and identifiers, it delegates to specialized processing methods.\n *\n * @throws Error - When casting to TypeParameterDeclaration fails for non-compatible node kinds\n *\n * @example\n * ```ts\n * // Inside the CodeHighlighter class\n * const node = sourceFile.getChildAt(0);\n * this.processNode(node);\n * // Node is now added to the segments map with appropriate colors\n * ```\n *\n * @see processTemplateExpression\n * @see processIdentifier\n *\n * @since 1.0.0\n */\n private processNode(node: ts.Node): void {\n const start = node.getStart();\n const end = node.getEnd();\n switch (node.kind) {\n case ts.SyntaxKind.TypeParameter:\n return this.addSegment(start, start + (node as ts.TypeParameterDeclaration).name.text.length, this.schema.typeColor);\n case ts.SyntaxKind.TypeReference:\n return this.addSegment(start, end, this.schema.typeColor);\n case ts.SyntaxKind.StringLiteral:\n case ts.SyntaxKind.NoSubstitutionTemplateLiteral:\n return this.addSegment(start, end, this.schema.stringColor);\n case ts.SyntaxKind.RegularExpressionLiteral:\n return this.addSegment(start, end, this.schema.regularExpressionColor);\n case ts.SyntaxKind.TemplateExpression:\n return this.processTemplateExpression(node as ts.TemplateExpression);\n case ts.SyntaxKind.Identifier:\n return this.processIdentifier(node);\n case ts.SyntaxKind.BigIntLiteral:\n case ts.SyntaxKind.NumericLiteral:\n return this.addSegment(start, end, this.schema.numericLiteralColor);\n }\n }\n}\n/**\n * Applies semantic highlighting to the provided code string using the specified color scheme.\n *\n * @param code - The source code to be highlighted\n * @param schema - An optional partial schema defining the color styles for various code elements\n *\n * @returns A string with the code elements wrapped in the appropriate color styles\n *\n * @remarks\n * If no schema is provided, the default schema will be used. The function creates a TypeScript\n * source file from the provided code and walks through its AST to apply syntax highlighting.\n *\n * @example\n * ```ts\n * const code = 'const x: number = 42;';\n * const schema = {\n * keywordColor: '\\x1b[34m', // Blue\n * numberColor: '\\x1b[31m', // Red\n * };\n * const highlightedCode = highlightCode(code, schema);\n * console.log(highlightedCode);\n * ```\n *\n * @see CodeHighlighter\n * @see HighlightSchemeInterface\n *\n * @since 1.0.0\n */\nexport function highlightCode(code: string, schema: Partial<HighlightSchemeInterface> = {}) {\n const sourceFile = ts.createSourceFile('temp.ts', code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n const codeHighlighter = new CodeHighlighter(sourceFile, code, Object.assign(defaultScheme, schema));\n function walk(node: ts.Node): void {\n codeHighlighter.parseNode(node);\n for (let i = 0; i < node.getChildCount(); i++) {\n walk(node.getChildAt(i));\n }\n }\n ts.forEachChild(sourceFile, walk);\n return codeHighlighter.highlight();\n}\n"],
|
|
6
|
+
"mappings": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,EAAA,WAAAC,EAAA,kBAAAC,IAAA,eAAAC,EAAAL,GAWA,IAAAM,EAAoB,2BACpBC,EAA2B,sBAeTJ,OACdA,EAAA,MAAQ,UACRA,EAAA,KAAO,iBACPA,EAAA,SAAW,iBACXA,EAAA,WAAa,iBACbA,EA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EACzE,KAAQ,aAAW,mBACf,OAAO,KAAK,0BAA0BX,CAA6B,EACvE,KAAQ,aAAW,WACf,OAAO,KAAK,kBAAkBA,CAAI,EACtC,KAAQ,aAAW,cACnB,KAAQ,aAAW,eACf,OAAO,KAAK,WAAWU,EAAOC,EAAK,KAAK,OAAO,mBAAmB,CAC1E,CACJ,CACJ,EA6BO,SAASnB,EAAcM,EAAcC,EAA4C,CAAC,EAAG,CACxF,IAAMF,EAAgB,mBAAiB,UAAWC,EAAS,eAAa,OAAQ,GAAS,aAAW,EAAE,EAChGsB,EAAkB,IAAI9B,EAAgBO,EAAYC,EAAM,OAAO,OAAOF,EAAeG,CAAM,CAAC,EAClG,SAASsB,EAAKrB,EAAqB,CAC/BoB,EAAgB,UAAUpB,CAAI,EAC9B,QAASsB,EAAI,EAAGA,EAAItB,EAAK,cAAc,EAAGsB,IACtCD,EAAKrB,EAAK,WAAWsB,CAAC,CAAC,CAE/B,CACA,OAAG,eAAazB,EAAYwB,CAAI,EACzBD,EAAgB,UAAU,CACrC",
|
|
7
|
+
"names": ["highlighter_component_exports", "__export", "CodeHighlighter", "Colors", "highlightCode", "__toCommonJS", "ts", "import_typescript", "defaultScheme", "sourceFile", "code", "schema", "node", "previousSegmentEnd", "parent", "result", "a", "b", "segment", "lastSegment", "source", "combinedSource", "start", "end", "color", "reset", "key", "comment", "templateExpression", "span", "spanStart", "spanEnd", "codeHighlighter", "walk", "i"]
|
|
8
|
+
}
|
package/dist/cjs/index.js
CHANGED
|
@@ -1,8 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`)
|
|
3
|
-
`),
|
|
4
|
-
`)}function j(c,e){let{code:t,line:n,column:i,startLine:r}=c;if(n<r||i<1)throw new Error("Invalid line or column number.");return A(t,{startLine:r,action:{triggerLine:n,callback:(o,a,l)=>{let u="^",d=a-1,g=">";e&&(u=`${e.color}${u}${e.reset}`,d+=e.color.length+e.reset.length,g=`${e.color}>${e.reset}`);let h=" | ".padStart(a)+" ".repeat(i-1)+`${u}`;return o=`${g} ${l} |`.padStart(d)+o.split("|")[1],o+`
|
|
5
|
-
${h}`}}})}var s=D(require("typescript"),1),p=require("typescript"),M=(m=>(m.reset="\x1B[0m",m.gray="\x1B[38;5;243m",m.darkGray="\x1B[38;5;238m",m.lightCoral="\x1B[38;5;203m",m.lightOrange="\x1B[38;5;215m",m.oliveGreen="\x1B[38;5;149m",m.burntOrange="\x1B[38;5;208m",m.lightGoldenrodYellow="\x1B[38;5;221m",m.lightYellow="\x1B[38;5;230m",m.canaryYellow="\x1B[38;5;227m",m.deepOrange="\x1B[38;5;166m",m.lightGray="\x1B[38;5;252m",m.brightPink="\x1B[38;5;197m",m))(M||{}),G={enumColor:"\x1B[38;5;208m",typeColor:"\x1B[38;5;221m",classColor:"\x1B[38;5;215m",stringColor:"\x1B[38;5;149m",keywordColor:"\x1B[38;5;203m",commentColor:"\x1B[38;5;238m",functionColor:"\x1B[38;5;215m",variableColor:"\x1B[38;5;208m",interfaceColor:"\x1B[38;5;221m",parameterColor:"\x1B[38;5;166m",getAccessorColor:"\x1B[38;5;230m",numericLiteralColor:"\x1B[38;5;252m",methodSignatureColor:"\x1B[38;5;208m",regularExpressionColor:"\x1B[38;5;149m",propertyAssignmentColor:"\x1B[38;5;227m",propertyAccessExpressionColor:"\x1B[38;5;230m",expressionWithTypeArgumentsColor:"\x1B[38;5;215m"},S=class{constructor(e,t,n){this.sourceFile=e;this.code=t;this.schema=n}segments=new Map;parseNode(e){this.processComments(e),this.processKeywords(e),this.processNode(e)}highlight(){let e=0,t,n=[];return Array.from(this.segments.values()).sort((r,o)=>r.start-o.start||r.end-o.end).forEach(r=>{if(t&&r.start<t.end){let o=n.pop();if(!o)return;let a=this.getSegmentSource(r.start,r.end),l=`${r.color}${a}${t.color}`;n.push(o.replace(a,l));return}n.push(this.getSegmentSource(e,r.start)),n.push(`${r.color}${this.getSegmentSource(r.start,r.end)}${r.reset}`),e=r.end,t=r}),n.join("")+this.getSegmentSource(e)}getSegmentSource(e,t){return this.code.slice(e,t)}addSegment(e,t,n,i="\x1B[0m"){let r=`${e}-${t}`;this.segments.set(r,{start:e,end:t,color:n,reset:i})}processComments(e){[...s.getTrailingCommentRanges(this.sourceFile.getFullText(),e.getFullStart())||[],...s.getLeadingCommentRanges(this.sourceFile.getFullText(),e.getFullStart())||[]].forEach(n=>this.addSegment(n.pos,n.end,this.schema.commentColor))}processKeywords(e){if([p.SyntaxKind.NullKeyword,p.SyntaxKind.VoidKeyword,p.SyntaxKind.StringKeyword,p.SyntaxKind.NumberKeyword,p.SyntaxKind.BooleanKeyword,p.SyntaxKind.UndefinedKeyword].includes(e.kind))return this.addSegment(e.getStart(),e.getEnd(),this.schema.typeColor);e&&e.kind>=s.SyntaxKind.FirstKeyword&&e.kind<=s.SyntaxKind.LastKeyword&&this.addSegment(e.getStart(),e.getEnd(),this.schema.keywordColor)}processIdentifier(e){let t=e.getEnd(),n=e.getStart();switch(e.parent.kind){case s.SyntaxKind.EnumMember:return this.addSegment(n,t,this.schema.enumColor);case s.SyntaxKind.CallExpression:case s.SyntaxKind.EnumDeclaration:case s.SyntaxKind.PropertySignature:case s.SyntaxKind.ModuleDeclaration:return this.addSegment(n,t,this.schema.variableColor);case s.SyntaxKind.InterfaceDeclaration:return this.addSegment(n,t,this.schema.interfaceColor);case s.SyntaxKind.GetAccessor:return this.addSegment(n,t,this.schema.getAccessorColor);case s.SyntaxKind.PropertyAssignment:return this.addSegment(n,t,this.schema.propertyAssignmentColor);case s.SyntaxKind.MethodSignature:return this.addSegment(n,t,this.schema.methodSignatureColor);case s.SyntaxKind.MethodDeclaration:case s.SyntaxKind.FunctionDeclaration:return this.addSegment(n,t,this.schema.functionColor);case s.SyntaxKind.ClassDeclaration:return this.addSegment(n,t,this.schema.classColor);case s.SyntaxKind.Parameter:return this.addSegment(n,t,this.schema.parameterColor);case s.SyntaxKind.VariableDeclaration:return this.addSegment(n,t,this.schema.variableColor);case s.SyntaxKind.PropertyDeclaration:return this.addSegment(n,t,this.schema.variableColor);case s.SyntaxKind.PropertyAccessExpression:return e.parent.getChildAt(0).getText()===e.getText()?this.addSegment(n,t,this.schema.variableColor):this.addSegment(n,t,this.schema.propertyAccessExpressionColor);case s.SyntaxKind.ExpressionWithTypeArguments:return this.addSegment(n,t,this.schema.expressionWithTypeArgumentsColor);case s.SyntaxKind.BreakStatement:case s.SyntaxKind.ShorthandPropertyAssignment:case s.SyntaxKind.BindingElement:return this.addSegment(n,t,this.schema.variableColor);case s.SyntaxKind.BinaryExpression:case s.SyntaxKind.SwitchStatement:case s.SyntaxKind.TemplateSpan:return this.addSegment(n,t,this.schema.variableColor);case s.SyntaxKind.TypeReference:case s.SyntaxKind.TypeAliasDeclaration:return this.addSegment(n,t,this.schema.typeColor);case s.SyntaxKind.NewExpression:return this.addSegment(n,t,this.schema.variableColor)}}processTemplateExpression(e){let t=e.head.getStart(),n=e.head.getEnd();this.addSegment(t,n,this.schema.stringColor),e.templateSpans.forEach(i=>{let r=i.literal.getStart(),o=i.literal.getEnd();this.addSegment(r,o,this.schema.stringColor)})}processNode(e){let t=e.getStart(),n=e.getEnd();switch(e.kind){case s.SyntaxKind.TypeParameter:return this.addSegment(t,t+e.name.text.length,this.schema.typeColor);case s.SyntaxKind.TypeReference:return this.addSegment(t,n,this.schema.typeColor);case s.SyntaxKind.StringLiteral:case s.SyntaxKind.NoSubstitutionTemplateLiteral:return this.addSegment(t,n,this.schema.stringColor);case s.SyntaxKind.RegularExpressionLiteral:return this.addSegment(t,n,this.schema.regularExpressionColor);case s.SyntaxKind.TemplateExpression:return this.processTemplateExpression(e);case s.SyntaxKind.Identifier:return this.processIdentifier(e);case s.SyntaxKind.BigIntLiteral:case s.SyntaxKind.NumericLiteral:return this.addSegment(t,n,this.schema.numericLiteralColor)}}};function V(c,e={}){let t=s.createSourceFile("temp.ts",c,s.ScriptTarget.Latest,!0,s.ScriptKind.TS),n=new S(t,c,Object.assign(G,e));function i(r){n.parseNode(r);for(let o=0;o<r.getChildCount();o++)i(r.getChildAt(o))}return s.forEachChild(t,i),n.highlight()}var y=class c{mapping=[];constructor(e,t=0,n=0){e=e instanceof c?e.mapping:e,Array.isArray(e)?this.decodeMappingArray(e,t,n):this.decodeMappingString(e,t,n)}encode(){return this.encodeMappings(this.mapping)}decode(e,t=0,n=0){e=e instanceof c?e.mapping:e,Array.isArray(e)?this.decodeMappingArray(e,t,n):this.decodeMappingString(e,t,n)}getSegment(e,t,n=0){let i=this.mapping[e-1];if(!i||i.length===0)return null;let r=0,o=i.length-1,a=null;for(;r<=o;){let l=Math.floor((r+o)/2),u=i[l];if(u.generatedColumn<t)r=l+1,a=n===1?u:a;else if(u.generatedColumn>t)o=l-1,a=n===2?u:a;else return u}return a}getOriginalSegment(e,t,n,i=0){let r=null;for(let o of this.mapping){if(!o)continue;let a=0,l=o.length-1;for(;a<=l;){let u=Math.floor((a+l)/2),d=o[u];if(d.sourceIndex<n||d.line<e)a=u+1;else if(d.sourceIndex>n||d.line>e)l=u-1;else if(d.column<t)a=u+1,r=i===1?d:r;else if(d.column>t)l=u-1,r=i===2?d:r;else return d}}return r}initPositionOffsets(e=0,t=0){return{line:0,column:0,nameIndex:e,sourceIndex:t,generatedLine:0,generatedColumn:0}}validateMappingString(e){return/^[a-zA-Z0-9+/,;]+$/.test(e)}validateSegment(e){if(!Number.isFinite(e.line))throw new Error(`Invalid segment: line must be a finite number, received ${e.line}`);if(!Number.isFinite(e.column))throw new Error(`Invalid segment: column must be a finite number, received ${e.column}`);if(e.nameIndex!==null&&!Number.isFinite(e.nameIndex))throw new Error(`Invalid segment: nameIndex must be a number or null, received ${e.nameIndex}`);if(!Number.isFinite(e.sourceIndex))throw new Error(`Invalid segment: sourceIndex must be a finite number, received ${e.sourceIndex}`);if(!Number.isFinite(e.generatedLine))throw new Error(`Invalid segment: generatedLine must be a finite number, received ${e.generatedLine}`);if(!Number.isFinite(e.generatedColumn))throw new Error(`Invalid segment: generatedColumn must be a finite number, received ${e.generatedColumn}`)}encodeSegment(e,t){let{line:n,column:i,generatedColumn:r,nameIndex:o,sourceIndex:a}=t,l=n-1,u=i-1,d=r-1,g=[d-e.generatedColumn,a!==e.sourceIndex?a-e.sourceIndex:0,l-e.line,u-e.column];return o!=null&&(g[4]=o-e.nameIndex,e.nameIndex=o),e.line=l,e.column=u,e.generatedColumn=d,e.sourceIndex=a,x(g)}encodeMappings(e){let t=this.initPositionOffsets();return e.map(n=>n?(t.generatedColumn=0,n.map(r=>this.encodeSegment(t,r)).join(",")):"").join(";")}decodedSegment(e,t){let[n,i,r,o,a]=t;return e.line+=r,e.column+=o,e.nameIndex+=a??0,e.sourceIndex+=i,e.generatedColumn+=n,{line:e.line+1,column:e.column+1,nameIndex:a!==void 0?e.nameIndex:null,sourceIndex:e.sourceIndex,generatedLine:e.generatedLine+1,generatedColumn:e.generatedColumn+1}}decodeMappingString(e,t,n){if(!this.validateMappingString(e))throw new Error("Invalid Mappings string format: the provided string does not conform to expected VLQ format.");let i=e.split(";"),r=this.mapping.length,o=this.initPositionOffsets(t,n);try{i.forEach((a,l)=>{if(!a){this.mapping.push(null);return}o.generatedColumn=0,o.generatedLine=r+l;let u=a.split(",").map(d=>this.decodedSegment(o,I(d)));this.mapping.push(u)})}catch(a){throw new Error(`Error decoding mappings at frame index ${i.length}: ${a.message}`)}}decodeMappingArray(e,t,n){let i=this.mapping.length;if(!Array.isArray(e))throw new Error("Invalid encoded map: expected an array of frames.");try{e.forEach((r,o)=>{if(!r){this.mapping.push(r);return}if(!Array.isArray(r))throw new Error(`Invalid Mappings array format at frame index ${o}: expected an array, received ${typeof r}.`);let a=r.map(l=>(this.validateSegment(l),{...l,nameIndex:typeof l.nameIndex=="number"?l.nameIndex+t:null,sourceIndex:l.sourceIndex+n,generatedLine:l.generatedLine+i}));this.mapping.push(a)})}catch(r){let o=r instanceof Error?r.message:"Unknown error";throw new Error(`Error decoding mappings: ${o}`)}}};var C=class c{file;mappings;sourceRoot;names;sources;sourcesContent;constructor(e,t=null){typeof e=="string"&&(e=JSON.parse(e)),e=e,this.validateSourceMap(e),this.file=e.file??t,this.names=[...e.names??[]],this.sources=[...e.sources??[]],this.sourceRoot=e.sourceRoot??null,this.sourcesContent=e.sourcesContent?[...e.sourcesContent]:[],this.mappings=new y(e.mappings)}getMapObject(){let e={version:3,names:this.names,sources:this.sources,mappings:this.mappings.encode(),sourcesContent:this.sourcesContent};return this.file&&(e.file=this.file),this.sourceRoot&&(e.sourceRoot=this.sourceRoot),e}concat(...e){if(e.length<1)throw new Error("At least one map must be provided for concatenation.");for(let t of e)this.mappings.decode(t.mappings,this.names.length,this.sources.length),this.names.push(...t.names),this.sources.push(...t.sources),this.sourcesContent.push(...t.sourcesContent??[])}concatNewMap(...e){if(e.length<1)throw new Error("At least one map must be provided for concatenation.");let t=new c(this);for(let n of e)t.mappings.decode(n.mappings,t.names.length,t.sources.length),t.names.push(...n.names),t.sources.push(...n.sources),t.sourcesContent.push(...n.sourcesContent??[]);return t}getPositionByOriginal(e,t,n,i=0){let r=n;if(typeof n=="string"&&(r=this.sources.findIndex(a=>a.includes(n))),r<0)return null;let o=this.mappings.getOriginalSegment(e,t,r,i);return o?{name:this.names[o.nameIndex??-1]??null,line:o.line,column:o.column,source:this.sources[o.sourceIndex],sourceRoot:this.sourceRoot,sourceIndex:o.sourceIndex,generatedLine:o.generatedLine,generatedColumn:o.generatedColumn}:null}getPosition(e,t,n=0){let i=this.mappings.getSegment(e,t,n);return i?{name:this.names[i.nameIndex??-1]??null,line:i.line,column:i.column,source:this.sources[i.sourceIndex],sourceRoot:this.sourceRoot,sourceIndex:i.sourceIndex,generatedLine:i.generatedLine,generatedColumn:i.generatedColumn}:null}getPositionWithContent(e,t,n=0){let i=this.getPosition(e,t,n);return i?{...i,sourcesContent:this.sourcesContent[i.sourceIndex]}:null}getPositionWithCode(e,t,n=0,i){let r=this.getPosition(e,t,n);if(!r||!this.sourcesContent[r.sourceIndex])return null;let o=Object.assign({linesAfter:4,linesBefore:3},i),a=this.sourcesContent[r.sourceIndex].split(`
|
|
6
|
-
`),l=Math.min((r.line??1)+o.linesAfter,a.length),u=Math.max((r.line??1)-o.linesBefore,0),d=a.slice(u,Math.min(l+1,a.length)).join(`
|
|
7
|
-
`);return{...r,code:d,endLine:l,startLine:u}}toString(){return JSON.stringify(this.getMapObject())}validateSourceMap(e){if(!["sources","mappings","names"].every(n=>n in e))throw new Error("Missing required keys in SourceMap.")}};0&&(module.exports={CodeHighlighter,Colors,SourceService,decodeVLQ,encodeArrayVLQ,encodeVLQ,formatCode,formatErrorCode,highlightCode,parseErrorStack});
|
|
1
|
+
"use strict";var f=Object.defineProperty;var x=Object.getOwnPropertyDescriptor;var b=Object.getOwnPropertyNames;var v=Object.prototype.hasOwnProperty;var M=(c,e)=>{for(var n in e)f(c,n,{get:e[n],enumerable:!0})},C=(c,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of b(e))!v.call(c,t)&&t!==n&&f(c,t,{get:()=>e[t],enumerable:!(r=x(e,t))||r.enumerable});return c};var N=c=>C(f({},"__esModule",{value:!0}),c);var w={};M(w,{SourceService:()=>g,decodeVLQ:()=>m,encodeArrayVLQ:()=>d,encodeVLQ:()=>h});module.exports=N(w);var S={},y="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");y.forEach((c,e)=>{S[c]=e});function h(c){let e=c<0,n="",r=e?(-c<<1)+1:c<<1;do{let t=r&31;r>>>=5,n+=y[t|(r>0?32:0)]}while(r>0);return n}function d(c){return c.map(h).join("")}function m(c){let e=[],n=0,r=0;for(let t=0;t<c.length;t++){let o=S[c[t]];if(o===void 0)throw new Error(`Invalid Base64 character: ${c[t]}`);let i=o&32;if(r+=(o&31)<<n,i)n+=5;else{let s=(r&1)===1,a=r>>1;e.push(s?-a:a),r=n=0}}return e}var p=class c{mapping=[];constructor(e,n=0,r=0){e=e instanceof c?e.mapping:e,Array.isArray(e)?this.decodeMappingArray(e,n,r):this.decodeMappingString(e,n,r)}encode(){return this.encodeMappings(this.mapping)}decode(e,n=0,r=0){e=e instanceof c?e.mapping:e,Array.isArray(e)?this.decodeMappingArray(e,n,r):this.decodeMappingString(e,n,r)}getSegment(e,n,r=0){let t=this.mapping[e-1];if(!t||t.length===0)return null;let o=0,i=t.length-1,s=null;for(;o<=i;){let a=Math.floor((o+i)/2),u=t[a];if(u.generatedColumn<n)o=a+1,s=r===1?u:s;else if(u.generatedColumn>n)i=a-1,s=r===2?u:s;else return u}return s}getOriginalSegment(e,n,r,t=0){let o=null;for(let i of this.mapping){if(!i)continue;let s=0,a=i.length-1;for(;s<=a;){let u=Math.floor((s+a)/2),l=i[u];if(l.sourceIndex<r||l.line<e)s=u+1;else if(l.sourceIndex>r||l.line>e)a=u-1;else if(l.column<n)s=u+1,o=t===1?l:o;else if(l.column>n)a=u-1,o=t===2?l:o;else return l}}return o}initPositionOffsets(e=0,n=0){return{line:0,column:0,nameIndex:e,sourceIndex:n,generatedLine:0,generatedColumn:0}}validateMappingString(e){return/^[a-zA-Z0-9+/,;]+$/.test(e)}validateSegment(e){if(!Number.isFinite(e.line))throw new Error(`Invalid segment: line must be a finite number, received ${e.line}`);if(!Number.isFinite(e.column))throw new Error(`Invalid segment: column must be a finite number, received ${e.column}`);if(e.nameIndex!==null&&!Number.isFinite(e.nameIndex))throw new Error(`Invalid segment: nameIndex must be a number or null, received ${e.nameIndex}`);if(!Number.isFinite(e.sourceIndex))throw new Error(`Invalid segment: sourceIndex must be a finite number, received ${e.sourceIndex}`);if(!Number.isFinite(e.generatedLine))throw new Error(`Invalid segment: generatedLine must be a finite number, received ${e.generatedLine}`);if(!Number.isFinite(e.generatedColumn))throw new Error(`Invalid segment: generatedColumn must be a finite number, received ${e.generatedColumn}`)}encodeSegment(e,n){let{line:r,column:t,generatedColumn:o,nameIndex:i,sourceIndex:s}=n,a=r-1,u=t-1,l=o-1,I=[l-e.generatedColumn,s!==e.sourceIndex?s-e.sourceIndex:0,a-e.line,u-e.column];return i!=null&&(I[4]=i-e.nameIndex,e.nameIndex=i),e.line=a,e.column=u,e.generatedColumn=l,e.sourceIndex=s,d(I)}encodeMappings(e){let n=this.initPositionOffsets();return e.map(r=>r?(n.generatedColumn=0,r.map(o=>this.encodeSegment(n,o)).join(",")):"").join(";")}decodedSegment(e,n){let[r,t,o,i,s]=n;return e.line+=o,e.column+=i,e.nameIndex+=s??0,e.sourceIndex+=t,e.generatedColumn+=r,{line:e.line+1,column:e.column+1,nameIndex:s!==void 0?e.nameIndex:null,sourceIndex:e.sourceIndex,generatedLine:e.generatedLine+1,generatedColumn:e.generatedColumn+1}}decodeMappingString(e,n,r){if(!this.validateMappingString(e))throw new Error("Invalid Mappings string format: the provided string does not conform to expected VLQ format.");let t=e.split(";"),o=this.mapping.length,i=this.initPositionOffsets(n,r);try{t.forEach((s,a)=>{if(!s){this.mapping.push(null);return}i.generatedColumn=0,i.generatedLine=o+a;let u=s.split(",").map(l=>this.decodedSegment(i,m(l)));this.mapping.push(u)})}catch(s){throw new Error(`Error decoding mappings at frame index ${t.length}: ${s.message}`)}}decodeMappingArray(e,n,r){let t=this.mapping.length;if(!Array.isArray(e))throw new Error("Invalid encoded map: expected an array of frames.");try{e.forEach((o,i)=>{if(!o){this.mapping.push(o);return}if(!Array.isArray(o))throw new Error(`Invalid Mappings array format at frame index ${i}: expected an array, received ${typeof o}.`);let s=o.map(a=>(this.validateSegment(a),{...a,nameIndex:typeof a.nameIndex=="number"?a.nameIndex+n:null,sourceIndex:a.sourceIndex+r,generatedLine:a.generatedLine+t}));this.mapping.push(s)})}catch(o){let i=o instanceof Error?o.message:"Unknown error";throw new Error(`Error decoding mappings: ${i}`)}}};var g=class c{file;mappings;sourceRoot;names;sources;sourcesContent;constructor(e,n=null){typeof e=="string"&&(e=JSON.parse(e)),e=e,this.validateSourceMap(e),this.file=e.file??n,this.names=[...e.names??[]],this.sources=[...e.sources??[]],this.sourceRoot=e.sourceRoot??null,this.sourcesContent=e.sourcesContent?[...e.sourcesContent]:[],this.mappings=new p(e.mappings)}getMapObject(){let e={version:3,names:this.names,sources:this.sources,mappings:this.mappings.encode(),sourcesContent:this.sourcesContent};return this.file&&(e.file=this.file),this.sourceRoot&&(e.sourceRoot=this.sourceRoot),e}concat(...e){if(e.length<1)throw new Error("At least one map must be provided for concatenation.");for(let n of e)this.mappings.decode(n.mappings,this.names.length,this.sources.length),this.names.push(...n.names),this.sources.push(...n.sources),this.sourcesContent.push(...n.sourcesContent??[])}concatNewMap(...e){if(e.length<1)throw new Error("At least one map must be provided for concatenation.");let n=new c(this);for(let r of e)n.mappings.decode(r.mappings,n.names.length,n.sources.length),n.names.push(...r.names),n.sources.push(...r.sources),n.sourcesContent.push(...r.sourcesContent??[]);return n}getPositionByOriginal(e,n,r,t=0){let o=r;if(typeof r=="string"&&(o=this.sources.findIndex(s=>s.includes(r))),o<0)return null;let i=this.mappings.getOriginalSegment(e,n,o,t);return i?{name:this.names[i.nameIndex??-1]??null,line:i.line,column:i.column,source:this.sources[i.sourceIndex],sourceRoot:this.sourceRoot,sourceIndex:i.sourceIndex,generatedLine:i.generatedLine,generatedColumn:i.generatedColumn}:null}getPosition(e,n,r=0){let t=this.mappings.getSegment(e,n,r);return t?{name:this.names[t.nameIndex??-1]??null,line:t.line,column:t.column,source:this.sources[t.sourceIndex],sourceRoot:this.sourceRoot,sourceIndex:t.sourceIndex,generatedLine:t.generatedLine,generatedColumn:t.generatedColumn}:null}getPositionWithContent(e,n,r=0){let t=this.getPosition(e,n,r);return t?{...t,sourcesContent:this.sourcesContent[t.sourceIndex]}:null}getPositionWithCode(e,n,r=0,t){let o=this.getPosition(e,n,r);if(!o||!this.sourcesContent[o.sourceIndex])return null;let i=Object.assign({linesAfter:4,linesBefore:3},t),s=this.sourcesContent[o.sourceIndex].split(`
|
|
2
|
+
`),a=Math.min((o.line??1)+i.linesAfter,s.length),u=Math.max((o.line??1)-i.linesBefore,0),l=s.slice(u,Math.min(a+1,s.length)).join(`
|
|
3
|
+
`);return{...o,code:l,endLine:a,startLine:u}}toString(){return JSON.stringify(this.getMapObject())}validateSourceMap(e){if(!["sources","mappings","names"].every(r=>r in e))throw new Error("Missing required keys in SourceMap.")}};0&&(module.exports={SourceService,decodeVLQ,encodeArrayVLQ,encodeVLQ});
|
|
8
4
|
//# sourceMappingURL=index.js.map
|