shiki-twoslash
Advanced tools
Comparing version 0.8.2 to 1.0.0
@@ -1,5 +0,5 @@ | ||
import { Highlighter } from "shiki/dist/highlighter"; | ||
import { Highlighter, HighlighterOptions } from "shiki"; | ||
import { TwoSlashOptions, TwoSlashReturn } from "@typescript/twoslash"; | ||
import { twoslashRenderer } from "./renderers/twoslash"; | ||
import { plainTextRenderer } from "./renderers/plain"; | ||
import { HtmlRendererOptions, plainTextRenderer } from "./renderers/plain"; | ||
import { defaultShikiRenderer } from "./renderers/shiki"; | ||
@@ -11,4 +11,2 @@ import { tsconfigJSONRenderer } from "./renderers/tsconfig"; | ||
}; | ||
/** Checks if a particular lang is available in shiki */ | ||
export declare const canHighlightLang: (lang: string) => boolean; | ||
/** | ||
@@ -21,3 +19,3 @@ * Creates a Shiki highlighter, this is an async call because of the call to WASM to get the regex parser set up. | ||
*/ | ||
export declare const createShikiHighlighter: (options: import("shiki/dist/highlighter").HighlighterOptions) => Promise<Highlighter>; | ||
export declare const createShikiHighlighter: (options: HighlighterOptions) => Promise<Highlighter>; | ||
/** | ||
@@ -35,3 +33,3 @@ * Renders a code sample to HTML, automatically taking into account: | ||
*/ | ||
export declare const renderCodeToHTML: (code: string, lang: string, info: string[], shikiOptions?: import("shiki/dist/renderer").HtmlRendererOptions | undefined, highlighter?: Highlighter | undefined, twoslash?: TwoSlashReturn | undefined) => string; | ||
export declare const renderCodeToHTML: (code: string, lang: string, info: string[], shikiOptions?: HtmlRendererOptions | undefined, highlighter?: Highlighter | undefined, twoslash?: TwoSlashReturn | undefined) => string; | ||
/** | ||
@@ -38,0 +36,0 @@ * Runs Twoslash over the code passed in with a particular language as the default file. |
@@ -1,4 +0,7 @@ | ||
declare type Options = import("shiki/dist/renderer").HtmlRendererOptions; | ||
export interface HtmlRendererOptions { | ||
langId?: string; | ||
fg?: string; | ||
bg?: string; | ||
} | ||
/** You don't have a language which shiki twoslash can handle, make a DOM compatible version */ | ||
export declare function plainTextRenderer(code: string, options: Options): string; | ||
export {}; | ||
export declare function plainTextRenderer(code: string, options: HtmlRendererOptions): string; |
@@ -0,4 +1,4 @@ | ||
import { HtmlRendererOptions } from "./plain"; | ||
declare type Lines = import("shiki").IThemedToken[][]; | ||
declare type Options = import("shiki/dist/renderer").HtmlRendererOptions; | ||
export declare function defaultShikiRenderer(lines: Lines, options: Options): string; | ||
export declare function defaultShikiRenderer(lines: Lines, options: HtmlRendererOptions): string; | ||
export {}; |
declare type Lines = import("shiki").IThemedToken[][]; | ||
declare type Options = import("shiki/dist/renderer").HtmlRendererOptions; | ||
import { HtmlRendererOptions } from "./plain"; | ||
/** | ||
@@ -8,3 +8,3 @@ * Renders a TSConfig JSON object with additional LSP-ish information | ||
*/ | ||
export declare function tsconfigJSONRenderer(lines: Lines, options: Options): string; | ||
export declare function tsconfigJSONRenderer(lines: Lines, options: HtmlRendererOptions): string; | ||
export {}; |
declare type Lines = import("shiki").IThemedToken[][]; | ||
declare type Options = import("shiki/dist/renderer").HtmlRendererOptions; | ||
declare type TwoSlash = import("@typescript/twoslash").TwoSlashReturn; | ||
export declare function twoslashRenderer(lines: Lines, options: Options, twoslash: TwoSlash): string; | ||
import { HtmlRendererOptions } from "./plain"; | ||
export declare function twoslashRenderer(lines: Lines, options: HtmlRendererOptions, twoslash: TwoSlash): string; | ||
export {}; |
@@ -6,3 +6,2 @@ 'use strict'; | ||
var shiki = require('shiki'); | ||
var shikiLanguages = require('shiki-languages'); | ||
var twoslash = require('@typescript/twoslash'); | ||
@@ -491,10 +490,2 @@ var vfs = require('@typescript/vfs'); | ||
var languages = | ||
/*#__PURE__*/ | ||
[].concat(shikiLanguages.commonLangIds, shikiLanguages.commonLangAliases, shikiLanguages.otherLangIds); | ||
/** Checks if a particular lang is available in shiki */ | ||
var canHighlightLang = function canHighlightLang(lang) { | ||
return languages.includes(lang); | ||
}; | ||
/** | ||
@@ -517,20 +508,12 @@ * This gets filled in by the promise below, then should | ||
if (storedHighlighter) return Promise.resolve(storedHighlighter); | ||
var settings = options || {}; | ||
var theme = settings.theme || "nord"; | ||
var shikiTheme; | ||
// shikiTheme = getTheme(theme) | ||
// } catch (error) { | ||
// try { | ||
// shikiTheme = loadTheme(theme) | ||
// } catch (error) { | ||
// throw new Error("Unable to load theme: " + theme + " - " + error.message) | ||
// } | ||
// } | ||
try { | ||
shikiTheme = shiki.getTheme(theme); | ||
} catch (error) { | ||
try { | ||
shikiTheme = shiki.loadTheme(theme); | ||
} catch (error) { | ||
throw new Error("Unable to load theme: " + theme + " - " + error.message); | ||
} | ||
} | ||
return shiki.getHighlighter({ | ||
theme: shikiTheme, | ||
langs: languages | ||
}).then(function (newHighlighter) { | ||
return shiki.getHighlighter(options).then(function (newHighlighter) { | ||
storedHighlighter = newHighlighter; | ||
@@ -556,13 +539,17 @@ return storedHighlighter; | ||
throw new Error("The highlighter object hasn't been initialised via `setupHighLighter` yet in render-shiki-twoslash"); | ||
} // Shiki doesn't know this lang | ||
} // Shiki does know the lang, so tokenize | ||
if (!canHighlightLang(lang)) { | ||
var renderHighlighter = highlighter || storedHighlighter; | ||
var tokens; | ||
try { | ||
// Shiki does know the lang, so tokenize | ||
tokens = renderHighlighter.codeToThemedTokens(code, lang); | ||
} catch (error) { | ||
// Shiki doesn't know this lang | ||
return plainTextRenderer(code, shikiOptions || {}); | ||
} // Shiki does know the lang, so tokenize | ||
} // Twoslash specific renderer | ||
var renderHighlighter = highlighter || storedHighlighter; | ||
var tokens = renderHighlighter.codeToThemedTokens(code, lang); // Twoslash specific renderer | ||
if (info.includes("twoslash") && twoslash) { | ||
@@ -573,3 +560,3 @@ return twoslashRenderer(tokens, shikiOptions || {}, twoslash); | ||
if (lang.startsWith("json") && info.includes("tsconfig")) { | ||
if (lang && lang.startsWith("json") && info.includes("tsconfig")) { | ||
return tsconfigJSONRenderer(tokens, shikiOptions || {}); | ||
@@ -639,3 +626,2 @@ } // Otherwise just the normal shiki renderer | ||
exports.canHighlightLang = canHighlightLang; | ||
exports.createShikiHighlighter = createShikiHighlighter; | ||
@@ -642,0 +628,0 @@ exports.renderCodeToHTML = renderCodeToHTML; |
@@ -1,2 +0,2 @@ | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("shiki"),t=require("shiki-languages"),n=require("@typescript/twoslash"),r=require("@typescript/vfs");function i(){return(i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}).apply(this,arguments)}var o=function(e,t,n,r){return e.slice(0,t)+r+e.slice(t+Math.abs(n))},a=function(e){return e.replace(/</g,"⇍").replace(/>/g,"⇏").replace(/'/g,"⇯")},s=function(e){return e.replace(/⇍/g,"<").replace(/⇏/g,">").replace(/⇯/g,"'")},l=function(e){return e.replace(/⇍/g,"<").replace(/⇏/g,">").replace(/⇯/g,"'")};function c(e){var t={"<":"lt",'"':"quot","'":"apos","&":"amp","\r":"#10","\n":"#13"};return e.toString().replace(/[<"'\r\n&]/g,(function(e){return"&"+t[e]+";"}))}function p(e){return e.replace(/</g,"<").replace(/>/g,">")}function d(e,t,n){var r="";r+='<pre class="shiki twoslash lsp">',t.langId&&(r+='<div class="language-id">'+t.langId+"</div>"),r+="<div class='code-container'><code>";var i=u(n.errors,(function(e){return e.line}))||new Map,d=u(n.staticQuickInfos,(function(e){return e.line}))||new Map,f=u(n.queries,(function(e){return e.line-1}))||new Map,h=0;return e.forEach((function(t,n){var l=i.get(n)||[],u=d.get(n)||[],g=f.get(n)||[];if(0===t.length&&0===n)h+=1;else if(0===t.length)h+=1,r+="\n";else{var m=0;t.forEach((function(e){var t="",n=function(t){return function(n){return t<=n.character&&t+e.content.length>=n.character+n.length}},i=l.filter(n(m)),p=u.filter(n(m)),d=g.filter(n(m)),f=[].concat(i,p,d).sort((function(e,t){return(e.start||0)-(t.start||0)}));t+=f.length?function(e,t){var n=[],r=!1;e.forEach((function(e){"lsp"===e.classes?(n.push({text:"⇍/data-lsp⇏",index:e.end}),n.push({text:"⇍data-lsp lsp=⇯"+(e.lsp||"")+"⇯⇏",index:e.begin})):"err"===e.classes?r=!0:"query"===e.classes&&(n.push({text:"⇍/data-highlight⇏",index:e.end}),n.push({text:"⇍data-highlight'⇏",index:e.begin}))}));var i=(" "+t).slice(1);return n.sort((function(e,t){return t.index-e.index})).forEach((function(e){i=o(i,e.index,0,e.text)})),r&&(i="⇍data-err⇏"+i+"⇍/data-err⇏"),s(c(i))}(f.map((function(e){var t={begin:e.start-h,end:e.start+e.length-h};return"renderedMessage"in e&&(t.classes="err"),"kind"in e&&(t.classes=e.kind),"targetString"in e&&(t.classes="lsp",t.lsp=c(e.text)),t})),e.content):a(e.content),r+='<span style="color: '+e.color+'">'+t+"</span>",m+=e.content.length,h+=e.content.length})),r+="\n",h+=1}if(l.length){var y=l.map((function(e){return p(e.renderedMessage)})).join("</br>"),b=l.map((function(e){return e.code})).join("<br/>");r+='<span class="error"><span>'+y+'</span><span class="code">'+b+"</span></span>",r+='<span class="error-behind">'+y+"</span>"}g.length&&(g.forEach((function(t){switch(t.kind){case"query":var i,o,a,s=(null==(i=(e[n-1]||[])[0])?void 0:i.content)||"",l=s.slice(0,(null==(o=/\S/.exec(s))?void 0:o.index)||0),c=l+"//"+"".padStart(t.offset-2-l.length),p=null==(a=t.text)?void 0:a.split("\n").map((function(e,t){return 0!==t?c+e:e})).join("\n");r+="<span class='query'>"+c+"^ = "+p+"</span>";break;case"completions":if(t.completions){var d=t.completions.filter((function(e){return e.name.startsWith(t.completionsPrefix||"____")})).sort((function(e,t){return e.name.localeCompare(t.name)})).map((function(e){var n,r,i=e.name.substr((null==(n=t.completionsPrefix)?void 0:n.length)||0),o="<span><span class='result-found'>"+(t.completionsPrefix||"")+"</span>"+i+"<span>";return"<li class='"+((null==(r=e.kindModifiers)?void 0:r.split(",").includes("deprecated"))?"deprecated":"")+"'>"+o+"</li>"})).join("");r+="".padStart(t.offset)+"<span class='inline-completions'><ul class='dropdown'>"+d+"</ul></span>"}else r+="<span class='query'>//"+"".padStart(t.offset-2)+"^ - No completions found</span>"}})),r+="\n")})),r=l(r.replace(/\n*$/,"")),r+="</code><a href='"+n.playgroundURL+"'>Try</a></div></pre>"}function u(e,t){var n=new Map;return e.forEach((function(e){var r=t(e),i=n.get(r);i?i.push(e):n.set(r,[e])})),n}function f(e,t){var n="";return n+='<pre class="shiki">',t.langId&&(n+='<div class="language-id">'+t.langId+"</div>"),n+="<div class='code-container'><code>",(n=(n+=p(e)).replace(/\n*$/,""))+"</code></div></pre>"}function h(e,t){var n="";return n+='<pre class="shiki">',t.langId&&(n+='<div class="language-id">'+t.langId+"</div>"),n+="<div class='code-container'><code>",e.forEach((function(e){0===e.length?n+="\n":(e.forEach((function(e){n+='<span style="color: '+e.color+'">'+p(e.content)+"</span>"})),n+="\n")})),n=n.replace(/\n*$/,""),n+="</code></div></pre>"}var g={compilerOptions:"The set of compiler options for your project",allowJs:"Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files.",allowSyntheticDefaultImports:"Allow 'import x from y' when a module doesn't have a default export.",allowUmdGlobalAccess:"Allow accessing UMD globals from modules.",allowUnreachableCode:"Disable error reporting for unreachable code.",allowUnusedLabels:"Disable error reporting for unused labels.",alwaysStrict:"Ensure 'use strict' is always emitted.",assumeChangesOnlyAffectDirectDependencies:"Have recompiles in projects that use `incremental` and `watch` mode assume that changes within a file will only affect files directly depending on it.",baseUrl:"Specify the base directory to resolve non-relative module names.",charset:"No longer supported. In early versions, manually set the text encoding for reading files.",checkJs:"Enable error reporting in type-checked JavaScript files.",composite:"Enable constraints that allow a TypeScript project to be used with project references.",declaration:"Generate .d.ts files from TypeScript and JavaScript files in your project.",declarationDir:"Specify the output directory for generated declaration files.",declarationMap:"Create sourcemaps for d.ts files.",diagnostics:"Output compiler performance information after building.",disableReferencedProjectLoad:"Reduce the number of projects loaded automatically by TypeScript.",disableSizeLimit:"Remove the 20mb cap on total source code size for JavaScript files in the TypeScript language server.",disableSolutionSearching:"Opt a project out of multi-project reference checking when editing.",disableSourceOfProjectReferenceRedirect:"Disable preferring source files instead of declaration files when referencing composite projects",downlevelIteration:"Emit more compliant, but verbose and less performant JavaScript for iteration.",emitBOM:"Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files.",emitDeclarationOnly:"Only output d.ts files and not JavaScript files.",emitDecoratorMetadata:"Emit design-type metadata for decorated declarations in source files.",esModuleInterop:"Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility.",exclude:"Filters results from the `include` option.",experimentalDecorators:"Enable experimental support for TC39 stage 2 draft decorators.",explainFiles:"Print files read during the compilation including why it was included.",extendedDiagnostics:"Output more detailed compiler performance information after building.",extends:"Specify one or more path or node module references to base configuration files from which settings are inherited.",fallbackPolling:"Specify what approach the watcher should use if the system runs out of native file watchers.",files:"Include a list of files. This does not support glob patterns, as opposed to `include`.",forceConsistentCasingInFileNames:"Ensure that casing is correct in imports.",generateCpuProfile:"Emit a v8 CPU profile of the compiler run for debugging.",importHelpers:"Allow importing helper functions from tslib once per project, instead of including them per-file.",importsNotUsedAsValues:"Specify emit/checking behavior for imports that are only used for types.",include:"Specify a list of glob patterns that match files to be included in compilation.",incremental:"Save .tsbuildinfo files to allow for incremental compilation of projects.",inlineSourceMap:"Include sourcemap files inside the emitted JavaScript.",inlineSources:"Include source code in the sourcemaps inside the emitted JavaScript.",isolatedModules:"Ensure that each file can be safely transpiled without relying on other imports.",jsx:"Specify what JSX code is generated.",jsxFactory:"Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'",jsxFragmentFactory:"Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'.",jsxImportSource:"Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.`",keyofStringsOnly:"Make keyof only return strings instead of string, numbers or symbols. Legacy option.",lib:"Specify a set of bundled library declaration files that describe the target runtime environment.",listEmittedFiles:"Print the names of emitted files after a compilation.",listFiles:"Print all of the files read during the compilation.",locale:"Set the language of the messaging from TypeScript. This does not affect emit.",mapRoot:"Specify the location where debugger should locate map files instead of generated locations.",maxNodeModuleJsDepth:"Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`.",module:"Specify what module code is generated.",moduleResolution:"Specify how TypeScript looks up a file from a given module specifier.",newLine:"Set the newline character for emitting files.",noEmit:"Disable emitting file from a compilation.",noEmitHelpers:"Disable generating custom helper functions like `__extends` in compiled output.",noEmitOnError:"Disable emitting files if any type checking errors are reported.",noErrorTruncation:"Disable truncating types in error messages.",noFallthroughCasesInSwitch:"Enable error reporting for fallthrough cases in switch statements.",noImplicitAny:"Enable error reporting for expressions and declarations with an implied `any` type..",noImplicitReturns:"Enable error reporting for codepaths that do not explicitly return in a function.",noImplicitThis:"Enable error reporting when `this` is given the type `any`.",noImplicitUseStrict:"Disable adding 'use strict' directives in emitted JavaScript files.",noLib:"Disable including any library files, including the default lib.d.ts.",noPropertyAccessFromIndexSignature:"Enforces using indexed accessors for keys declared using an indexed type",noResolve:"Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project.",noStrictGenericChecks:"Disable strict checking of generic signatures in function types.",noUncheckedIndexedAccess:"Add `undefined` to a type when accessed using an index.",noUnusedLocals:"Enable error reporting when a local variables aren't read.",noUnusedParameters:"Raise an error when a function parameter isn't read",out:"Deprecated setting. Use `outFile` instead.",outDir:"Specify an output folder for all emitted files.",outFile:"Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output.",paths:"Specify a set of entries that re-map imports to additional lookup locations.",plugins:"Specify a list of language service plugins to include.",preserveConstEnums:"Disable erasing `const enum` declarations in generated code.",preserveSymlinks:"Disable resolving symlinks to their realpath. This correlates to the same flag in node.",preserveWatchOutput:"Disable wiping the console in watch mode",pretty:"Enable color and formatting in output to make compiler errors easier to read",reactNamespace:"Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit.",references:"Specify an array of objects that specify paths for projects. Used in project references.",removeComments:"Disable emitting comments.",resolveJsonModule:"Enable importing .json files",rootDir:"Specify the root folder within your source files.",rootDirs:"Allow multiple folders to be treated as one when resolving modules.",skipDefaultLibCheck:"Skip type checking .d.ts files that are included with TypeScript.",skipLibCheck:"Skip type checking all .d.ts files.",sourceMap:"Create source map files for emitted JavaScript files.",sourceRoot:"Specify the root path for debuggers to find the reference source code.",strict:"Enable all strict type checking options.",strictBindCallApply:"Check that the arguments for `bind`, `call`, and `apply` methods match the original function.",strictFunctionTypes:"When assigning functions, check to ensure parameters and the return values are subtype-compatible.",strictNullChecks:"When type checking, take into account `null` and `undefined`.",strictPropertyInitialization:"Check for class properties that are declared but not set in the constructor.",stripInternal:"Disable emitting declarations that have `@internal` in their JSDoc comments.",suppressExcessPropertyErrors:"Disable reporting of excess property errors during the creation of object literals.",suppressImplicitAnyIndexErrors:"Suppress `noImplicitAny` errors when indexing objects that lack index signatures.",target:"Set the JavaScript language version for emitted JavaScript and include compatible library declarations.",traceResolution:"Log paths used during the `moduleResolution` process.",tsBuildInfoFile:"Specify the folder for .tsbuildinfo incremental compilation files.",typeAcquisition:"Specify options for automatic acquisition of declaration files.",typeRoots:"Specify multiple folders that act like `./node_modules/@types`.",types:"Specify type package names to be included without being referenced in a source file.",useDefineForClassFields:"Emit ECMAScript-standard-compliant class fields.",watchDirectory:"Specify how directories are watched on systems that lack recursive file-watching functionality.",watchFile:"Specify how the TypeScript watch mode works."},m=function(e){return!!e.explanation&&e.explanation.find((function(e){return e.scopes.find((function(e){return e.scopeName.includes("support.type.property-name")}))}))},y=function(e){if('"'!==e.content)return e.content.slice(1,e.content.length-1)in g};function b(e,t){var n="";return n+='<pre class="shiki tsconfig lsp">',t.langId&&(n+='<div class="language-id">'+t.langId+"</div>"),n+="<div class='code-container'><code>",e.forEach((function(e){0===e.length?n+="\n":(e.forEach((function(e){if(m(e)&&y(e)){var t=e.content.slice(1,e.content.length-1);n+='<span style="color: '+e.color+'">"<a aria-hidden=true href=\'https://www.typescriptlang.org/tsconfig#'+t+"'><data-lsp lsp=\""+g[t]+'">'+p(t)+'</data-lsp></a>"</span>'}else n+='<span style="color: '+e.color+'">'+p(e.content)+"</span>"})),n+="\n")})),n=n.replace(/\n*$/,""),n+="</code></div></pre>"}var v=[].concat(t.commonLangIds,t.commonLangAliases,t.otherLangIds),S=function(e){return v.includes(e)},w=null,k=void 0,x={plainTextRenderer:f,defaultShikiRenderer:h,twoslashRenderer:d,tsconfigJSONRenderer:b};exports.canHighlightLang=S,exports.createShikiHighlighter=function(t){if(w)return Promise.resolve(w);var n,r=(t||{}).theme||"nord";try{n=e.getTheme(r)}catch(t){try{n=e.loadTheme(r)}catch(e){throw new Error("Unable to load theme: "+r+" - "+e.message)}}return e.getHighlighter({theme:n,langs:v}).then((function(e){return w=e}))},exports.renderCodeToHTML=function(e,t,n,r,i,o){if(!i&&!w)throw new Error("The highlighter object hasn't been initialised via `setupHighLighter` yet in render-shiki-twoslash");if(!S(t))return f(e,r||{});var a=(i||w).codeToThemedTokens(e,t);return n.includes("twoslash")&&o?d(a,r||{},o):t.startsWith("json")&&n.includes("tsconfig")?b(a,r||{}):h(a,{langId:t})},exports.renderers=x,exports.runTwoSlash=function(e,t,o,a){void 0===o&&(o={}),void 0===a&&(a={});var s=void 0,l={json5:"json"};return l[t]&&(t=l[t]),o.useNodeModules&&(k?s=new Map(k):(s=r.createDefaultMapFromNodeModules({target:6}),k=s),r.addAllFilesFromFolder(s,o.nodeModulesTypesPath||"node_modules/@types")),n.twoslasher(e,t,i({},a,{fsMap:s}))}; | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("shiki"),t=require("@typescript/twoslash"),n=require("@typescript/vfs");function i(){return(i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e}).apply(this,arguments)}var r=function(e,t,n,i){return e.slice(0,t)+i+e.slice(t+Math.abs(n))},o=function(e){return e.replace(/</g,"⇍").replace(/>/g,"⇏").replace(/'/g,"⇯")},a=function(e){return e.replace(/⇍/g,"<").replace(/⇏/g,">").replace(/⇯/g,"'")},s=function(e){return e.replace(/⇍/g,"<").replace(/⇏/g,">").replace(/⇯/g,"'")};function l(e){var t={"<":"lt",'"':"quot","'":"apos","&":"amp","\r":"#10","\n":"#13"};return e.toString().replace(/[<"'\r\n&]/g,(function(e){return"&"+t[e]+";"}))}function c(e){return e.replace(/</g,"<").replace(/>/g,">")}function p(e,t,n){var i="";i+='<pre class="shiki twoslash lsp">',t.langId&&(i+='<div class="language-id">'+t.langId+"</div>"),i+="<div class='code-container'><code>";var p=d(n.errors,(function(e){return e.line}))||new Map,u=d(n.staticQuickInfos,(function(e){return e.line}))||new Map,f=d(n.queries,(function(e){return e.line-1}))||new Map,h=0;return e.forEach((function(t,n){var s=p.get(n)||[],d=u.get(n)||[],g=f.get(n)||[];if(0===t.length&&0===n)h+=1;else if(0===t.length)h+=1,i+="\n";else{var m=0;t.forEach((function(e){var t="",n=function(t){return function(n){return t<=n.character&&t+e.content.length>=n.character+n.length}},c=s.filter(n(m)),p=d.filter(n(m)),u=g.filter(n(m)),f=[].concat(c,p,u).sort((function(e,t){return(e.start||0)-(t.start||0)}));t+=f.length?function(e,t){var n=[],i=!1;e.forEach((function(e){"lsp"===e.classes?(n.push({text:"⇍/data-lsp⇏",index:e.end}),n.push({text:"⇍data-lsp lsp=⇯"+(e.lsp||"")+"⇯⇏",index:e.begin})):"err"===e.classes?i=!0:"query"===e.classes&&(n.push({text:"⇍/data-highlight⇏",index:e.end}),n.push({text:"⇍data-highlight'⇏",index:e.begin}))}));var o=(" "+t).slice(1);return n.sort((function(e,t){return t.index-e.index})).forEach((function(e){o=r(o,e.index,0,e.text)})),i&&(o="⇍data-err⇏"+o+"⇍/data-err⇏"),a(l(o))}(f.map((function(e){var t={begin:e.start-h,end:e.start+e.length-h};return"renderedMessage"in e&&(t.classes="err"),"kind"in e&&(t.classes=e.kind),"targetString"in e&&(t.classes="lsp",t.lsp=l(e.text)),t})),e.content):o(e.content),i+='<span style="color: '+e.color+'">'+t+"</span>",m+=e.content.length,h+=e.content.length})),i+="\n",h+=1}if(s.length){var y=s.map((function(e){return c(e.renderedMessage)})).join("</br>"),b=s.map((function(e){return e.code})).join("<br/>");i+='<span class="error"><span>'+y+'</span><span class="code">'+b+"</span></span>",i+='<span class="error-behind">'+y+"</span>"}g.length&&(g.forEach((function(t){switch(t.kind){case"query":var r,o,a,s=(null==(r=(e[n-1]||[])[0])?void 0:r.content)||"",l=s.slice(0,(null==(o=/\S/.exec(s))?void 0:o.index)||0),c=l+"//"+"".padStart(t.offset-2-l.length),p=null==(a=t.text)?void 0:a.split("\n").map((function(e,t){return 0!==t?c+e:e})).join("\n");i+="<span class='query'>"+c+"^ = "+p+"</span>";break;case"completions":if(t.completions){var d=t.completions.filter((function(e){return e.name.startsWith(t.completionsPrefix||"____")})).sort((function(e,t){return e.name.localeCompare(t.name)})).map((function(e){var n,i,r=e.name.substr((null==(n=t.completionsPrefix)?void 0:n.length)||0),o="<span><span class='result-found'>"+(t.completionsPrefix||"")+"</span>"+r+"<span>";return"<li class='"+((null==(i=e.kindModifiers)?void 0:i.split(",").includes("deprecated"))?"deprecated":"")+"'>"+o+"</li>"})).join("");i+="".padStart(t.offset)+"<span class='inline-completions'><ul class='dropdown'>"+d+"</ul></span>"}else i+="<span class='query'>//"+"".padStart(t.offset-2)+"^ - No completions found</span>"}})),i+="\n")})),i=s(i.replace(/\n*$/,"")),i+="</code><a href='"+n.playgroundURL+"'>Try</a></div></pre>"}function d(e,t){var n=new Map;return e.forEach((function(e){var i=t(e),r=n.get(i);r?r.push(e):n.set(i,[e])})),n}function u(e,t){var n="";return n+='<pre class="shiki">',t.langId&&(n+='<div class="language-id">'+t.langId+"</div>"),n+="<div class='code-container'><code>",(n=(n+=c(e)).replace(/\n*$/,""))+"</code></div></pre>"}function f(e,t){var n="";return n+='<pre class="shiki">',t.langId&&(n+='<div class="language-id">'+t.langId+"</div>"),n+="<div class='code-container'><code>",e.forEach((function(e){0===e.length?n+="\n":(e.forEach((function(e){n+='<span style="color: '+e.color+'">'+c(e.content)+"</span>"})),n+="\n")})),n=n.replace(/\n*$/,""),n+="</code></div></pre>"}var h={compilerOptions:"The set of compiler options for your project",allowJs:"Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files.",allowSyntheticDefaultImports:"Allow 'import x from y' when a module doesn't have a default export.",allowUmdGlobalAccess:"Allow accessing UMD globals from modules.",allowUnreachableCode:"Disable error reporting for unreachable code.",allowUnusedLabels:"Disable error reporting for unused labels.",alwaysStrict:"Ensure 'use strict' is always emitted.",assumeChangesOnlyAffectDirectDependencies:"Have recompiles in projects that use `incremental` and `watch` mode assume that changes within a file will only affect files directly depending on it.",baseUrl:"Specify the base directory to resolve non-relative module names.",charset:"No longer supported. In early versions, manually set the text encoding for reading files.",checkJs:"Enable error reporting in type-checked JavaScript files.",composite:"Enable constraints that allow a TypeScript project to be used with project references.",declaration:"Generate .d.ts files from TypeScript and JavaScript files in your project.",declarationDir:"Specify the output directory for generated declaration files.",declarationMap:"Create sourcemaps for d.ts files.",diagnostics:"Output compiler performance information after building.",disableReferencedProjectLoad:"Reduce the number of projects loaded automatically by TypeScript.",disableSizeLimit:"Remove the 20mb cap on total source code size for JavaScript files in the TypeScript language server.",disableSolutionSearching:"Opt a project out of multi-project reference checking when editing.",disableSourceOfProjectReferenceRedirect:"Disable preferring source files instead of declaration files when referencing composite projects",downlevelIteration:"Emit more compliant, but verbose and less performant JavaScript for iteration.",emitBOM:"Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files.",emitDeclarationOnly:"Only output d.ts files and not JavaScript files.",emitDecoratorMetadata:"Emit design-type metadata for decorated declarations in source files.",esModuleInterop:"Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility.",exclude:"Filters results from the `include` option.",experimentalDecorators:"Enable experimental support for TC39 stage 2 draft decorators.",explainFiles:"Print files read during the compilation including why it was included.",extendedDiagnostics:"Output more detailed compiler performance information after building.",extends:"Specify one or more path or node module references to base configuration files from which settings are inherited.",fallbackPolling:"Specify what approach the watcher should use if the system runs out of native file watchers.",files:"Include a list of files. This does not support glob patterns, as opposed to `include`.",forceConsistentCasingInFileNames:"Ensure that casing is correct in imports.",generateCpuProfile:"Emit a v8 CPU profile of the compiler run for debugging.",importHelpers:"Allow importing helper functions from tslib once per project, instead of including them per-file.",importsNotUsedAsValues:"Specify emit/checking behavior for imports that are only used for types.",include:"Specify a list of glob patterns that match files to be included in compilation.",incremental:"Save .tsbuildinfo files to allow for incremental compilation of projects.",inlineSourceMap:"Include sourcemap files inside the emitted JavaScript.",inlineSources:"Include source code in the sourcemaps inside the emitted JavaScript.",isolatedModules:"Ensure that each file can be safely transpiled without relying on other imports.",jsx:"Specify what JSX code is generated.",jsxFactory:"Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'",jsxFragmentFactory:"Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'.",jsxImportSource:"Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.`",keyofStringsOnly:"Make keyof only return strings instead of string, numbers or symbols. Legacy option.",lib:"Specify a set of bundled library declaration files that describe the target runtime environment.",listEmittedFiles:"Print the names of emitted files after a compilation.",listFiles:"Print all of the files read during the compilation.",locale:"Set the language of the messaging from TypeScript. This does not affect emit.",mapRoot:"Specify the location where debugger should locate map files instead of generated locations.",maxNodeModuleJsDepth:"Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`.",module:"Specify what module code is generated.",moduleResolution:"Specify how TypeScript looks up a file from a given module specifier.",newLine:"Set the newline character for emitting files.",noEmit:"Disable emitting file from a compilation.",noEmitHelpers:"Disable generating custom helper functions like `__extends` in compiled output.",noEmitOnError:"Disable emitting files if any type checking errors are reported.",noErrorTruncation:"Disable truncating types in error messages.",noFallthroughCasesInSwitch:"Enable error reporting for fallthrough cases in switch statements.",noImplicitAny:"Enable error reporting for expressions and declarations with an implied `any` type..",noImplicitReturns:"Enable error reporting for codepaths that do not explicitly return in a function.",noImplicitThis:"Enable error reporting when `this` is given the type `any`.",noImplicitUseStrict:"Disable adding 'use strict' directives in emitted JavaScript files.",noLib:"Disable including any library files, including the default lib.d.ts.",noPropertyAccessFromIndexSignature:"Enforces using indexed accessors for keys declared using an indexed type",noResolve:"Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project.",noStrictGenericChecks:"Disable strict checking of generic signatures in function types.",noUncheckedIndexedAccess:"Add `undefined` to a type when accessed using an index.",noUnusedLocals:"Enable error reporting when a local variables aren't read.",noUnusedParameters:"Raise an error when a function parameter isn't read",out:"Deprecated setting. Use `outFile` instead.",outDir:"Specify an output folder for all emitted files.",outFile:"Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output.",paths:"Specify a set of entries that re-map imports to additional lookup locations.",plugins:"Specify a list of language service plugins to include.",preserveConstEnums:"Disable erasing `const enum` declarations in generated code.",preserveSymlinks:"Disable resolving symlinks to their realpath. This correlates to the same flag in node.",preserveWatchOutput:"Disable wiping the console in watch mode",pretty:"Enable color and formatting in output to make compiler errors easier to read",reactNamespace:"Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit.",references:"Specify an array of objects that specify paths for projects. Used in project references.",removeComments:"Disable emitting comments.",resolveJsonModule:"Enable importing .json files",rootDir:"Specify the root folder within your source files.",rootDirs:"Allow multiple folders to be treated as one when resolving modules.",skipDefaultLibCheck:"Skip type checking .d.ts files that are included with TypeScript.",skipLibCheck:"Skip type checking all .d.ts files.",sourceMap:"Create source map files for emitted JavaScript files.",sourceRoot:"Specify the root path for debuggers to find the reference source code.",strict:"Enable all strict type checking options.",strictBindCallApply:"Check that the arguments for `bind`, `call`, and `apply` methods match the original function.",strictFunctionTypes:"When assigning functions, check to ensure parameters and the return values are subtype-compatible.",strictNullChecks:"When type checking, take into account `null` and `undefined`.",strictPropertyInitialization:"Check for class properties that are declared but not set in the constructor.",stripInternal:"Disable emitting declarations that have `@internal` in their JSDoc comments.",suppressExcessPropertyErrors:"Disable reporting of excess property errors during the creation of object literals.",suppressImplicitAnyIndexErrors:"Suppress `noImplicitAny` errors when indexing objects that lack index signatures.",target:"Set the JavaScript language version for emitted JavaScript and include compatible library declarations.",traceResolution:"Log paths used during the `moduleResolution` process.",tsBuildInfoFile:"Specify the folder for .tsbuildinfo incremental compilation files.",typeAcquisition:"Specify options for automatic acquisition of declaration files.",typeRoots:"Specify multiple folders that act like `./node_modules/@types`.",types:"Specify type package names to be included without being referenced in a source file.",useDefineForClassFields:"Emit ECMAScript-standard-compliant class fields.",watchDirectory:"Specify how directories are watched on systems that lack recursive file-watching functionality.",watchFile:"Specify how the TypeScript watch mode works."},g=function(e){return!!e.explanation&&e.explanation.find((function(e){return e.scopes.find((function(e){return e.scopeName.includes("support.type.property-name")}))}))},m=function(e){if('"'!==e.content)return e.content.slice(1,e.content.length-1)in h};function y(e,t){var n="";return n+='<pre class="shiki tsconfig lsp">',t.langId&&(n+='<div class="language-id">'+t.langId+"</div>"),n+="<div class='code-container'><code>",e.forEach((function(e){0===e.length?n+="\n":(e.forEach((function(e){if(g(e)&&m(e)){var t=e.content.slice(1,e.content.length-1);n+='<span style="color: '+e.color+'">"<a aria-hidden=true href=\'https://www.typescriptlang.org/tsconfig#'+t+"'><data-lsp lsp=\""+h[t]+'">'+c(t)+'</data-lsp></a>"</span>'}else n+='<span style="color: '+e.color+'">'+c(e.content)+"</span>"})),n+="\n")})),n=n.replace(/\n*$/,""),n+="</code></div></pre>"}var b=null,v=void 0,S={plainTextRenderer:u,defaultShikiRenderer:f,twoslashRenderer:p,tsconfigJSONRenderer:y};exports.createShikiHighlighter=function(t){return b?Promise.resolve(b):e.getHighlighter(t).then((function(e){return b=e}))},exports.renderCodeToHTML=function(e,t,n,i,r,o){if(!r&&!b)throw new Error("The highlighter object hasn't been initialised via `setupHighLighter` yet in render-shiki-twoslash");var a,s=r||b;try{a=s.codeToThemedTokens(e,t)}catch(t){return u(e,i||{})}return n.includes("twoslash")&&o?p(a,i||{},o):t&&t.startsWith("json")&&n.includes("tsconfig")?y(a,i||{}):f(a,{langId:t})},exports.renderers=S,exports.runTwoSlash=function(e,r,o,a){void 0===o&&(o={}),void 0===a&&(a={});var s=void 0,l={json5:"json"};return l[r]&&(r=l[r]),o.useNodeModules&&(v?s=new Map(v):(s=n.createDefaultMapFromNodeModules({target:6}),v=s),n.addAllFilesFromFolder(s,o.nodeModulesTypesPath||"node_modules/@types")),t.twoslasher(e,r,i({},a,{fsMap:s}))}; | ||
//# sourceMappingURL=shiki-twoslash.cjs.production.min.js.map |
@@ -1,3 +0,2 @@ | ||
import { getTheme, loadTheme, getHighlighter } from 'shiki'; | ||
import { commonLangIds, commonLangAliases, otherLangIds } from 'shiki-languages'; | ||
import { getHighlighter } from 'shiki'; | ||
import { twoslasher } from '@typescript/twoslash'; | ||
@@ -486,10 +485,2 @@ import { createDefaultMapFromNodeModules, addAllFilesFromFolder } from '@typescript/vfs'; | ||
var languages = | ||
/*#__PURE__*/ | ||
[].concat(commonLangIds, commonLangAliases, otherLangIds); | ||
/** Checks if a particular lang is available in shiki */ | ||
var canHighlightLang = function canHighlightLang(lang) { | ||
return languages.includes(lang); | ||
}; | ||
/** | ||
@@ -512,20 +503,12 @@ * This gets filled in by the promise below, then should | ||
if (storedHighlighter) return Promise.resolve(storedHighlighter); | ||
var settings = options || {}; | ||
var theme = settings.theme || "nord"; | ||
var shikiTheme; | ||
// shikiTheme = getTheme(theme) | ||
// } catch (error) { | ||
// try { | ||
// shikiTheme = loadTheme(theme) | ||
// } catch (error) { | ||
// throw new Error("Unable to load theme: " + theme + " - " + error.message) | ||
// } | ||
// } | ||
try { | ||
shikiTheme = getTheme(theme); | ||
} catch (error) { | ||
try { | ||
shikiTheme = loadTheme(theme); | ||
} catch (error) { | ||
throw new Error("Unable to load theme: " + theme + " - " + error.message); | ||
} | ||
} | ||
return getHighlighter({ | ||
theme: shikiTheme, | ||
langs: languages | ||
}).then(function (newHighlighter) { | ||
return getHighlighter(options).then(function (newHighlighter) { | ||
storedHighlighter = newHighlighter; | ||
@@ -551,13 +534,17 @@ return storedHighlighter; | ||
throw new Error("The highlighter object hasn't been initialised via `setupHighLighter` yet in render-shiki-twoslash"); | ||
} // Shiki doesn't know this lang | ||
} // Shiki does know the lang, so tokenize | ||
if (!canHighlightLang(lang)) { | ||
var renderHighlighter = highlighter || storedHighlighter; | ||
var tokens; | ||
try { | ||
// Shiki does know the lang, so tokenize | ||
tokens = renderHighlighter.codeToThemedTokens(code, lang); | ||
} catch (error) { | ||
// Shiki doesn't know this lang | ||
return plainTextRenderer(code, shikiOptions || {}); | ||
} // Shiki does know the lang, so tokenize | ||
} // Twoslash specific renderer | ||
var renderHighlighter = highlighter || storedHighlighter; | ||
var tokens = renderHighlighter.codeToThemedTokens(code, lang); // Twoslash specific renderer | ||
if (info.includes("twoslash") && twoslash) { | ||
@@ -568,3 +555,3 @@ return twoslashRenderer(tokens, shikiOptions || {}, twoslash); | ||
if (lang.startsWith("json") && info.includes("tsconfig")) { | ||
if (lang && lang.startsWith("json") && info.includes("tsconfig")) { | ||
return tsconfigJSONRenderer(tokens, shikiOptions || {}); | ||
@@ -634,3 +621,3 @@ } // Otherwise just the normal shiki renderer | ||
export { canHighlightLang, createShikiHighlighter, renderCodeToHTML, renderers, runTwoSlash }; | ||
export { createShikiHighlighter, renderCodeToHTML, renderers, runTwoSlash }; | ||
//# sourceMappingURL=shiki-twoslash.esm.js.map |
{ | ||
"name": "shiki-twoslash", | ||
"version": "0.8.2", | ||
"version": "1.0.0", | ||
"license": "MIT", | ||
@@ -33,4 +33,3 @@ "homepage": "https://github.com/microsoft/TypeScript-Website", | ||
"@typescript/vfs": "1.3.2", | ||
"shiki": "^0.1.6", | ||
"shiki-languages": "^0.1.6", | ||
"shiki": "^0.9.1", | ||
"typescript": "*" | ||
@@ -40,3 +39,3 @@ }, | ||
"@types/jest": "^25.1.3", | ||
"gatsby-remark-shiki-twoslash": "0.7.1", | ||
"gatsby-remark-shiki-twoslash": "1.0.0", | ||
"rehype-stringify": "^6.0.1", | ||
@@ -48,3 +47,6 @@ "tsdx": "^0.14.1", | ||
"unist-util-visit": "^2.0.0" | ||
}, | ||
"jest": { | ||
"testEnvironment": "node" | ||
} | ||
} |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
4
1
226840
1451
+ Addedjsonc-parser@3.3.1(transitive)
+ Addedshiki@0.9.15(transitive)
+ Addedvscode-oniguruma@1.7.0(transitive)
+ Addedvscode-textmate@5.2.0(transitive)
- Removedshiki-languages@^0.1.6
- Removedjson5@2.2.3(transitive)
- Removedlru-cache@5.1.1(transitive)
- Removedonigasm@2.2.5(transitive)
- Removedshiki@0.1.7(transitive)
- Removedshiki-languages@0.1.6(transitive)
- Removedshiki-themes@0.1.7(transitive)
- Removedyallist@3.1.1(transitive)
Updatedshiki@^0.9.1