shiki-twoslash
Advanced tools
Comparing version 2.0.3 to 2.1.0
@@ -19,2 +19,4 @@ import { Highlighter, HighlighterOptions } from "shiki"; | ||
alwayRaiseForTwoslashExceptions?: true; | ||
/** Ignore transforming certain code blocks */ | ||
ignoreCodeblocksWithCodefenceMeta?: string[]; | ||
} | ||
@@ -21,0 +23,0 @@ /** The possible user config, a combination of all shiki, twoslash and twoslash-shiki options */ |
@@ -26,2 +26,29 @@ 'use strict'; | ||
var htmlForTags = function htmlForTags(tags) { | ||
var html = ""; | ||
tags.forEach(function (t) { | ||
if (t.name === "annotate" && t.annotation) { | ||
var meta = t.annotation.split(" - "); | ||
var text = meta.pop(); | ||
var info = (meta[0] || "").trim(); | ||
var flipped = info.includes("right"); | ||
var arrowRotation = info.split(" ")[1] || flipped ? "310" : "56"; | ||
var textRotation = info.split(" ")[2] || "0"; | ||
var arrowSVG = arrow({ | ||
flipped: flipped, | ||
rotation: arrowRotation | ||
}); | ||
html += "\n<div class='twoslash-annotation' style=\"top: " + t.line + "em;\">\n " + arrowSVG + "\n <p class='twoslash-annotation-text " + (flipped ? "right" : "left") + "' style=\"transform: rotate(" + textRotation + "deg)\">" + text + "</p>\n</div>"; | ||
} | ||
}); | ||
return html; | ||
}; | ||
var arrow = function arrow(style) { | ||
var leftInner = "M27 39C26.5 32.7511 21.9 17.5173 7.5 6.57333M16.5 4.04L0.999999 0.999998C3.16667 4.88444 7.5 13.16 7.5 15.1867"; | ||
var rightInner = "M1 39C1.5 32.7511 6.1 17.5173 20.5 6.57333M11.5 4.04L27 0.999998C24.8333 4.88444 20.5 13.16 20.5 15.1867"; | ||
var inner = style.flipped ? leftInner : rightInner; | ||
return "<svg width=\"40\" height=\"40\" viewBox=\"0 0 40 40\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n <path d=\"" + inner + "\" stroke=\"black\" transform=\"rotate(" + style.rotation + " 20 20)\"/>\n</svg>"; | ||
}; | ||
/** | ||
@@ -425,2 +452,7 @@ * We're given the text which lives inside the token, and this function will | ||
html += "</code>"; | ||
} // Attach annotations which live above of the code | ||
if (twoslash.tags && twoslash.tags.length) { | ||
html += htmlForTags(twoslash.tags); | ||
} | ||
@@ -764,3 +796,3 @@ | ||
if (replacer[lang]) lang = replacer[lang]; // Add react import | ||
if (replacer[lang]) lang = replacer[lang]; // Add react import to code samples indicating they're needing react. | ||
@@ -781,2 +813,3 @@ if (["tsx", "jsx"].includes(lang) && !settings.disableImplicitReactImport) { | ||
settings.customTags = ["annotate"]; | ||
var results = twoslash.twoslasher(code, lang, settings); | ||
@@ -783,0 +816,0 @@ return results; |
@@ -1,2 +0,2 @@ | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("shiki"),t=require("@typescript/twoslash");function i(){return(i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&(e[n]=i[n])}return e}).apply(this,arguments)}function n(e){return e.replace(/</g,"<").replace(/>/g,">")}var r=function(e){return!!Object.keys(e||{}).find((function(e){return!!e.includes("-")||!isNaN(parseInt(e))}))},o=function(e){var t=[];return Object.keys(e||{}).find((function(e){if(isNaN(parseInt(e))||t.push(parseInt(e)),e.includes("-"))for(var i=e.split("-"),n=i[0],r=parseInt(i[1])+1,o=parseInt(n);o<r;o++)t.push(o)})),function(e){return t.includes(e)}},a=function(e,t,i){var n=e.bg||"#fff",r=e.fg||"black",o=["shiki",e.themeName||"",t.class,t.title?"with-title":""].concat(i||[]).filter(Boolean).join(" ").trim(),a=Object.entries(t).filter((function(e){return["string","number","boolean"].includes(typeof e[1])&&!["class","twoslash"].includes(e[0])&&!1!==e[1]})).map((function(e){return e[0]+'="'+e[1]+'"'})).join(" ").trim();return'<pre class="'+o+'" style="background-color: '+n+"; color: "+r+'"'+(a?" "+a:"")+">"};function s(e,t,i){var r="";return r+=a(t,i,[]),i.title&&(r+="<div class='code-title'>"+i.title+"</div>"),t.langId&&(r+='<div class="language-id">'+t.langId+"</div>"),r+="<div class='code-container'><code>",(r=(r+=n(e)).replace(/\n*$/,""))+"</code></div></pre>"}function l(e,t,i,s){var l="",p=s.highlight&&r(s.highlight),d=o(s.highlight);l+=a(t,s,["twoslash","lsp"]),s.title&&(l+="<div class='code-title'>"+s.title+"</div>"),t.langId&&(l+='<div class="language-id">'+t.langId+"</div>"),l+="<div class='code-container'><code>";var u,f=c(i.errors,(function(e){return e.line}))||new Map,h=c(i.staticQuickInfos,(function(e){return e.line}))||new Map,g=c(i.queries,(function(e){return e.line-1}))||new Map,m=0;return e.forEach((function(e,i){var r=f.get(i)||[],o=h.get(i)||[],a=g.get(i)||[],s="<div class='line"+(p?d(i)?" highlight":" dim":"")+"'>";if(0===e.length&&0===i)m+=1;else if(0===e.length)l+=s+" </div>",m+=1;else{l+=s;var c=0;e.forEach((function(e){var i,n="",s=function(t){return function(i){return t<=i.character&&t+e.content.length>=i.character+i.length}},p=r.filter(s(c)),d=o.filter(s(c)),u=a.filter(s(c));i=i||d.find((function(e){return e.text===(a.length&&a[0].text)}));var f,h=[].concat(p,d,u).sort((function(e,t){return(e.start||0)-(t.start||0)}));n+=h.length?function(e,t,i){void 0===i&&(i="");var n=function(e){return"⇍"+e+"⇏"},r=function(e,t){switch(e.classes){case"lsp":var r=function(e){return e.replace(/"/g,"⃟")}(e.lsp||"");return n(t?"/data-lsp":"data-lsp lsp=¿"+r+"¿ "+(e.lsp===i?"style=⇯border-bottom: solid 2px lightgrey;⇯":""));case"query":return n((t?"/":"")+"data-highlight");case"err":default:return n((t?"/":"")+"data-err")}};e.sort((function(e,t){var i=function(e){return["err","query","lsp"].indexOf(null!=e?e:"")},n=0;return!(n=e.begin-t.begin)&&!(n=t.end-e.end)&&(n=i(e.classes)-i(t.classes)),n}));var o=0;return function(e){return e.replace(/⃟/g,'"')}(function(e){return e.replace(/⇍/g,"<").replace(/⇏/g,">").replace(/⇯/g,"'").replace(/¿/g,"'")}(function(e){var t={"<":"lt",'"':"quot","'":"apos","&":"amp","\r":"#13","\n":"#10"};return e.toString().replace(/[<"'\r\n&]/g,(function(e){return"&"+t[e]+";"}))}(function e(i){var n="",a=i.shift();return n+=t.substring(o,a.begin),o=a.begin,n+=r(a),i.some((function(e){return e.begin<a.end}))?n+=e(i):(n+=t.substring(a.begin,a.end),o=a.end),n+=r(a,!0),0!==i.length&&(n+=e(i)),n}(JSON.parse(JSON.stringify(e)))+t.substring(o))))}(h.map((function(e){var i={begin:e.start-m,end:e.start+e.length-m};return"renderedMessage"in e&&(i.classes="err"),"kind"in e&&(i.classes=e.kind),"targetString"in e&&(i.classes="lsp",i.lsp=t.includeJSDocInHover&&e.docs?e.docs+"\n\n"+e.text:e.text),i})),e.content,null==(f=i)?void 0:f.text):e.content.replace(/</g,"⇍").replace(/>/g,"⇏").replace(/'/g,"⇯"),l+='<span style="color: '+e.color+'">'+n+"</span>",c+=e.content.length,m+=e.content.length})),l+="</div>",m+=1}if(r.length){var u=r.map((function(e){return n(e.renderedMessage)})).join("</br>"),y=r.map((function(e){return e.code})).join("<br/>");l+='<span class="error"><span>'+u+'</span><span class="code">'+y+"</span></span>",l+='<span class="error-behind">'+u+"</span>"}a.length&&a.forEach((function(e){switch(l+="<div class='meta-line'>",e.kind){case"query":var t=n(e.text),r=(h.get(i)||[]).find((function(e){return e.text===(a.length&&a[0].text)}));l+="<span class='popover-prefix'>"+" ".repeat((r&&r.character+(null==r?void 0:r.length)/2)-1||0)+"</span><span class='popover'><div class='arrow'></div>"+t+"</span>";break;case"completions":if(e.completions){var o=e.completions.filter((function(t){return t.name.startsWith(e.completionsPrefix||"____")})).sort((function(e,t){return e.name.localeCompare(t.name)})).map((function(t){var i,n,r=t.name.substr((null==(i=e.completionsPrefix)?void 0:i.length)||0),o="<span><span class='result-found'>"+(e.completionsPrefix||"")+"</span>"+r+"<span>";return"<li class='"+((null==(n=t.kindModifiers)?void 0:n.split(",").includes("deprecated"))?"deprecated":"")+"'>"+o+"</li>"})).join("");l+=" ".repeat(e.offset)+"<span class='inline-completions'><ul class='dropdown'>"+o+"</ul></span>"}else l+="<span class='query'>//"+"".padStart(e.offset-2)+"^ - No completions found</span>"}l+="</div>"}))})),u=l.replace(/\n*$/,""),l=u.replace(/⇍/g,"<").replace(/⇏/g,">").replace(/⇯/g,"'"),l+=t.addTryButton?"</code><a class='playground-link' href='"+i.playgroundURL+"'>Try</a>":"</code>",l+="</div></pre>"}function c(e,t){var i=new Map;return e.forEach((function(e){var n=t(e),r=i.get(n);r?r.push(e):i.set(n,[e])})),i}function p(e,t,i){var s="",l=i.highlight&&r(i.highlight),c=o(i.highlight);return s+=a(t,i,[]),i.title&&(s+="<div class='code-title'>"+i.title+"</div>"),t.langId&&(s+='<div class="language-id">'+t.langId+"</div>"),s+="<div class='code-container'><code>",e.forEach((function(e,t){if(0===e.length)s+="<div class='line'></div>";else{var i=l?c(t)?" highlight":" dim":"";s+="<div class='line"+i+"'>",e.forEach((function(e){s+='<span style="color: '+e.color+'">'+n(e.content)+"</span>"})),s+="</div>"}})),s=s.replace(/\n*$/,""),s+="</code></div></pre>"}var d={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.",clean:"Delete the outputs of all projects.",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.",disableFilenameBasedTypeAcquisition:"Disables inference for type acquisition by looking at filenames in a project.",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.",enable:"Disable the type acquisition for JavaScript projects",esModuleInterop:"Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility.",exactOptionalPropertyTypes:"Differentiate between undefined and not present when type checking",exclude:"Filters results from the `include` option.",excludeDirectories:"Remove a list of directories from the watch process.",excludeFiles:"Remove a list of files from the watch mode's processing.",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`.",force:"Build all projects, including those that appear to be up to date",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..",noImplicitOverride:"Ensure overriding members in derived classes are marked with an override modifier.",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.",synchronousWatchDirectory:"Synchronously call callbacks and update the state of directory watchers on platforms that don`t support recursive watching natively.",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.",useUnknownInCatchVariables:"Default catch clause variables as `unknown` instead of `any`.",verbose:"Enable verbose logging",watchDirectory:"Specify how directories are watched on systems that lack recursive file-watching functionality.",watchFile:"Specify how the TypeScript watch mode works."};function u(e,t,i){var r="";return r+=a(t,i,["tsconfig","lsp"]),i.title&&(r+='<div class="code-title">'+i.title+"</div>"),t.langId&&(r+='<div class="language-id">'+t.langId+"</div>"),r+="<div class='code-container'><code>",e.forEach((function(e){0===e.length?r+="<div class='line'></div>":(r+="<div class='line'>",e.forEach((function(e){if(function(e){return!!e.explanation&&e.explanation.find((function(e){return e.scopes.find((function(e){return e.scopeName.includes("support.type.property-name")}))}))}(e)&&function(e){if('"'!==e.content)return e.content.slice(1,e.content.length-1)in d}(e)){var t=e.content.slice(1,e.content.length-1);r+='<span style="color: '+e.color+'">"<a aria-hidden=true tabindex="-1" href=\'https://www.typescriptlang.org/tsconfig#'+t+"'><data-lsp lsp=\""+d[t]+'">'+n(t)+'</data-lsp></a>"</span>'}else r+='<span style="color: '+e.color+'">'+n(e.content)+"</span>"})),r+="</div>")})),r=r.replace(/\n*$/,""),r+="</code></div></pre>"}var f=null,h={plainTextRenderer:s,defaultShikiRenderer:p,twoslashRenderer:l,tsconfigJSONRenderer:u};exports.createShikiHighlighter=function(t){return f?Promise.resolve(f):e.getHighlighter(t).then((function(e){return f=e}))},exports.renderCodeToHTML=function(e,t,n,r,o,a){if(!o&&!f)throw new Error("The highlighter object hasn't been initialised via `setupHighLighter` yet in shiki-twoslash");var c,d=o||f,h=i({fg:d.getForegroundColor(),bg:d.getBackgroundColor()},r);try{c=d.codeToThemedTokens(e,"jsx"===t?"tsx":t)}catch(i){var g="\x3c!-- Note from shiki-twoslash: the language "+t+" was not set up for Shiki to use, and so there is no code highlighting --!>";return s(e,h,n)+g}return t&&n.twoslash&&a?l(c,i({},h,{langId:t}),a,n):t&&t.startsWith("json")&&n.tsconfig?u(c,h,n):p(c,i({},h,{langId:t}),n)},exports.renderers=h,exports.runTwoSlash=function(e,i,n){void 0===n&&(n={});var r=e,o={json5:"json",yml:"yaml"};if(o[i]&&(i=o[i]),["tsx","jsx"].includes(i)&&!n.disableImplicitReactImport){var a="import React from 'react'\n",s="// ---cut---\n";r=r.includes(s)?r.split(s).map((function(e,t){return 0==t?a.concat(e):e})).join(s):[a,s,r].join("")}return t.twoslasher(r,i,n)}; | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("shiki"),t=require("@typescript/twoslash");function i(){return(i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&(e[n]=i[n])}return e}).apply(this,arguments)}function n(e){return e.replace(/</g,"<").replace(/>/g,">")}var r=function(e){return!!Object.keys(e||{}).find((function(e){return!!e.includes("-")||!isNaN(parseInt(e))}))},o=function(e){var t=[];return Object.keys(e||{}).find((function(e){if(isNaN(parseInt(e))||t.push(parseInt(e)),e.includes("-"))for(var i=e.split("-"),n=i[0],r=parseInt(i[1])+1,o=parseInt(n);o<r;o++)t.push(o)})),function(e){return t.includes(e)}},a=function(e,t,i){var n=e.bg||"#fff",r=e.fg||"black",o=["shiki",e.themeName||"",t.class,t.title?"with-title":""].concat(i||[]).filter(Boolean).join(" ").trim(),a=Object.entries(t).filter((function(e){return["string","number","boolean"].includes(typeof e[1])&&!["class","twoslash"].includes(e[0])&&!1!==e[1]})).map((function(e){return e[0]+'="'+e[1]+'"'})).join(" ").trim();return'<pre class="'+o+'" style="background-color: '+n+"; color: "+r+'"'+(a?" "+a:"")+">"};function s(e,t,i){var r="";return r+=a(t,i,[]),i.title&&(r+="<div class='code-title'>"+i.title+"</div>"),t.langId&&(r+='<div class="language-id">'+t.langId+"</div>"),r+="<div class='code-container'><code>",(r=(r+=n(e)).replace(/\n*$/,""))+"</code></div></pre>"}function l(e,t,i,s){var l="",p=s.highlight&&r(s.highlight),d=o(s.highlight);l+=a(t,s,["twoslash","lsp"]),s.title&&(l+="<div class='code-title'>"+s.title+"</div>"),t.langId&&(l+='<div class="language-id">'+t.langId+"</div>"),l+="<div class='code-container'><code>";var u,f=c(i.errors,(function(e){return e.line}))||new Map,h=c(i.staticQuickInfos,(function(e){return e.line}))||new Map,g=c(i.queries,(function(e){return e.line-1}))||new Map,m=0;return e.forEach((function(e,i){var r=f.get(i)||[],o=h.get(i)||[],a=g.get(i)||[],s="<div class='line"+(p?d(i)?" highlight":" dim":"")+"'>";if(0===e.length&&0===i)m+=1;else if(0===e.length)l+=s+" </div>",m+=1;else{l+=s;var c=0;e.forEach((function(e){var i,n="",s=function(t){return function(i){return t<=i.character&&t+e.content.length>=i.character+i.length}},p=r.filter(s(c)),d=o.filter(s(c)),u=a.filter(s(c));i=i||d.find((function(e){return e.text===(a.length&&a[0].text)}));var f,h=[].concat(p,d,u).sort((function(e,t){return(e.start||0)-(t.start||0)}));n+=h.length?function(e,t,i){void 0===i&&(i="");var n=function(e){return"⇍"+e+"⇏"},r=function(e,t){switch(e.classes){case"lsp":var r=function(e){return e.replace(/"/g,"⃟")}(e.lsp||"");return n(t?"/data-lsp":"data-lsp lsp=¿"+r+"¿ "+(e.lsp===i?"style=⇯border-bottom: solid 2px lightgrey;⇯":""));case"query":return n((t?"/":"")+"data-highlight");case"err":default:return n((t?"/":"")+"data-err")}};e.sort((function(e,t){var i=function(e){return["err","query","lsp"].indexOf(null!=e?e:"")},n=0;return!(n=e.begin-t.begin)&&!(n=t.end-e.end)&&(n=i(e.classes)-i(t.classes)),n}));var o=0;return function(e){return e.replace(/⃟/g,'"')}(function(e){return e.replace(/⇍/g,"<").replace(/⇏/g,">").replace(/⇯/g,"'").replace(/¿/g,"'")}(function(e){var t={"<":"lt",'"':"quot","'":"apos","&":"amp","\r":"#13","\n":"#10"};return e.toString().replace(/[<"'\r\n&]/g,(function(e){return"&"+t[e]+";"}))}(function e(i){var n="",a=i.shift();return n+=t.substring(o,a.begin),o=a.begin,n+=r(a),i.some((function(e){return e.begin<a.end}))?n+=e(i):(n+=t.substring(a.begin,a.end),o=a.end),n+=r(a,!0),0!==i.length&&(n+=e(i)),n}(JSON.parse(JSON.stringify(e)))+t.substring(o))))}(h.map((function(e){var i={begin:e.start-m,end:e.start+e.length-m};return"renderedMessage"in e&&(i.classes="err"),"kind"in e&&(i.classes=e.kind),"targetString"in e&&(i.classes="lsp",i.lsp=t.includeJSDocInHover&&e.docs?e.docs+"\n\n"+e.text:e.text),i})),e.content,null==(f=i)?void 0:f.text):e.content.replace(/</g,"⇍").replace(/>/g,"⇏").replace(/'/g,"⇯"),l+='<span style="color: '+e.color+'">'+n+"</span>",c+=e.content.length,m+=e.content.length})),l+="</div>",m+=1}if(r.length){var u=r.map((function(e){return n(e.renderedMessage)})).join("</br>"),y=r.map((function(e){return e.code})).join("<br/>");l+='<span class="error"><span>'+u+'</span><span class="code">'+y+"</span></span>",l+='<span class="error-behind">'+u+"</span>"}a.length&&a.forEach((function(e){switch(l+="<div class='meta-line'>",e.kind){case"query":var t=n(e.text),r=(h.get(i)||[]).find((function(e){return e.text===(a.length&&a[0].text)}));l+="<span class='popover-prefix'>"+" ".repeat((r&&r.character+(null==r?void 0:r.length)/2)-1||0)+"</span><span class='popover'><div class='arrow'></div>"+t+"</span>";break;case"completions":if(e.completions){var o=e.completions.filter((function(t){return t.name.startsWith(e.completionsPrefix||"____")})).sort((function(e,t){return e.name.localeCompare(t.name)})).map((function(t){var i,n,r=t.name.substr((null==(i=e.completionsPrefix)?void 0:i.length)||0),o="<span><span class='result-found'>"+(e.completionsPrefix||"")+"</span>"+r+"<span>";return"<li class='"+((null==(n=t.kindModifiers)?void 0:n.split(",").includes("deprecated"))?"deprecated":"")+"'>"+o+"</li>"})).join("");l+=" ".repeat(e.offset)+"<span class='inline-completions'><ul class='dropdown'>"+o+"</ul></span>"}else l+="<span class='query'>//"+"".padStart(e.offset-2)+"^ - No completions found</span>"}l+="</div>"}))})),u=l.replace(/\n*$/,""),l=u.replace(/⇍/g,"<").replace(/⇏/g,">").replace(/⇯/g,"'"),l+=t.addTryButton?"</code><a class='playground-link' href='"+i.playgroundURL+"'>Try</a>":"</code>",i.tags&&i.tags.length&&(l+=function(e){var t="";return e.forEach((function(e){if("annotate"===e.name&&e.annotation){var i=e.annotation.split(" - "),n=i.pop(),r=(i[0]||"").trim(),o=r.includes("right"),a=r.split(" ")[1]||o?"310":"56",s=r.split(" ")[2]||"0",l='<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="'+((c={flipped:o,rotation:a}).flipped?"M27 39C26.5 32.7511 21.9 17.5173 7.5 6.57333M16.5 4.04L0.999999 0.999998C3.16667 4.88444 7.5 13.16 7.5 15.1867":"M1 39C1.5 32.7511 6.1 17.5173 20.5 6.57333M11.5 4.04L27 0.999998C24.8333 4.88444 20.5 13.16 20.5 15.1867")+'" stroke="black" transform="rotate('+c.rotation+' 20 20)"/>\n</svg>';t+="\n<div class='twoslash-annotation' style=\"top: "+e.line+'em;">\n '+l+"\n <p class='twoslash-annotation-text "+(o?"right":"left")+"' style=\"transform: rotate("+s+'deg)">'+n+"</p>\n</div>"}var c})),t}(i.tags)),l+="</div></pre>"}function c(e,t){var i=new Map;return e.forEach((function(e){var n=t(e),r=i.get(n);r?r.push(e):i.set(n,[e])})),i}function p(e,t,i){var s="",l=i.highlight&&r(i.highlight),c=o(i.highlight);return s+=a(t,i,[]),i.title&&(s+="<div class='code-title'>"+i.title+"</div>"),t.langId&&(s+='<div class="language-id">'+t.langId+"</div>"),s+="<div class='code-container'><code>",e.forEach((function(e,t){if(0===e.length)s+="<div class='line'></div>";else{var i=l?c(t)?" highlight":" dim":"";s+="<div class='line"+i+"'>",e.forEach((function(e){s+='<span style="color: '+e.color+'">'+n(e.content)+"</span>"})),s+="</div>"}})),s=s.replace(/\n*$/,""),s+="</code></div></pre>"}var d={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.",clean:"Delete the outputs of all projects.",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.",disableFilenameBasedTypeAcquisition:"Disables inference for type acquisition by looking at filenames in a project.",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.",enable:"Disable the type acquisition for JavaScript projects",esModuleInterop:"Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility.",exactOptionalPropertyTypes:"Differentiate between undefined and not present when type checking",exclude:"Filters results from the `include` option.",excludeDirectories:"Remove a list of directories from the watch process.",excludeFiles:"Remove a list of files from the watch mode's processing.",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`.",force:"Build all projects, including those that appear to be up to date",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..",noImplicitOverride:"Ensure overriding members in derived classes are marked with an override modifier.",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.",synchronousWatchDirectory:"Synchronously call callbacks and update the state of directory watchers on platforms that don`t support recursive watching natively.",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.",useUnknownInCatchVariables:"Default catch clause variables as `unknown` instead of `any`.",verbose:"Enable verbose logging",watchDirectory:"Specify how directories are watched on systems that lack recursive file-watching functionality.",watchFile:"Specify how the TypeScript watch mode works."};function u(e,t,i){var r="";return r+=a(t,i,["tsconfig","lsp"]),i.title&&(r+='<div class="code-title">'+i.title+"</div>"),t.langId&&(r+='<div class="language-id">'+t.langId+"</div>"),r+="<div class='code-container'><code>",e.forEach((function(e){0===e.length?r+="<div class='line'></div>":(r+="<div class='line'>",e.forEach((function(e){if(function(e){return!!e.explanation&&e.explanation.find((function(e){return e.scopes.find((function(e){return e.scopeName.includes("support.type.property-name")}))}))}(e)&&function(e){if('"'!==e.content)return e.content.slice(1,e.content.length-1)in d}(e)){var t=e.content.slice(1,e.content.length-1);r+='<span style="color: '+e.color+'">"<a aria-hidden=true tabindex="-1" href=\'https://www.typescriptlang.org/tsconfig#'+t+"'><data-lsp lsp=\""+d[t]+'">'+n(t)+'</data-lsp></a>"</span>'}else r+='<span style="color: '+e.color+'">'+n(e.content)+"</span>"})),r+="</div>")})),r=r.replace(/\n*$/,""),r+="</code></div></pre>"}var f=null,h={plainTextRenderer:s,defaultShikiRenderer:p,twoslashRenderer:l,tsconfigJSONRenderer:u};exports.createShikiHighlighter=function(t){return f?Promise.resolve(f):e.getHighlighter(t).then((function(e){return f=e}))},exports.renderCodeToHTML=function(e,t,n,r,o,a){if(!o&&!f)throw new Error("The highlighter object hasn't been initialised via `setupHighLighter` yet in shiki-twoslash");var c,d=o||f,h=i({fg:d.getForegroundColor(),bg:d.getBackgroundColor()},r);try{c=d.codeToThemedTokens(e,"jsx"===t?"tsx":t)}catch(i){var g="\x3c!-- Note from shiki-twoslash: the language "+t+" was not set up for Shiki to use, and so there is no code highlighting --!>";return s(e,h,n)+g}return t&&n.twoslash&&a?l(c,i({},h,{langId:t}),a,n):t&&t.startsWith("json")&&n.tsconfig?u(c,h,n):p(c,i({},h,{langId:t}),n)},exports.renderers=h,exports.runTwoSlash=function(e,i,n){void 0===n&&(n={});var r=e,o={json5:"json",yml:"yaml"};if(o[i]&&(i=o[i]),["tsx","jsx"].includes(i)&&!n.disableImplicitReactImport){var a="import React from 'react'\n",s="// ---cut---\n";r=r.includes(s)?r.split(s).map((function(e,t){return 0==t?a.concat(e):e})).join(s):[a,s,r].join("")}return n.customTags=["annotate"],t.twoslasher(r,i,n)}; | ||
//# sourceMappingURL=shiki-twoslash.cjs.production.min.js.map |
@@ -22,2 +22,29 @@ import { getHighlighter } from 'shiki'; | ||
var htmlForTags = function htmlForTags(tags) { | ||
var html = ""; | ||
tags.forEach(function (t) { | ||
if (t.name === "annotate" && t.annotation) { | ||
var meta = t.annotation.split(" - "); | ||
var text = meta.pop(); | ||
var info = (meta[0] || "").trim(); | ||
var flipped = info.includes("right"); | ||
var arrowRotation = info.split(" ")[1] || flipped ? "310" : "56"; | ||
var textRotation = info.split(" ")[2] || "0"; | ||
var arrowSVG = arrow({ | ||
flipped: flipped, | ||
rotation: arrowRotation | ||
}); | ||
html += "\n<div class='twoslash-annotation' style=\"top: " + t.line + "em;\">\n " + arrowSVG + "\n <p class='twoslash-annotation-text " + (flipped ? "right" : "left") + "' style=\"transform: rotate(" + textRotation + "deg)\">" + text + "</p>\n</div>"; | ||
} | ||
}); | ||
return html; | ||
}; | ||
var arrow = function arrow(style) { | ||
var leftInner = "M27 39C26.5 32.7511 21.9 17.5173 7.5 6.57333M16.5 4.04L0.999999 0.999998C3.16667 4.88444 7.5 13.16 7.5 15.1867"; | ||
var rightInner = "M1 39C1.5 32.7511 6.1 17.5173 20.5 6.57333M11.5 4.04L27 0.999998C24.8333 4.88444 20.5 13.16 20.5 15.1867"; | ||
var inner = style.flipped ? leftInner : rightInner; | ||
return "<svg width=\"40\" height=\"40\" viewBox=\"0 0 40 40\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n <path d=\"" + inner + "\" stroke=\"black\" transform=\"rotate(" + style.rotation + " 20 20)\"/>\n</svg>"; | ||
}; | ||
/** | ||
@@ -421,2 +448,7 @@ * We're given the text which lives inside the token, and this function will | ||
html += "</code>"; | ||
} // Attach annotations which live above of the code | ||
if (twoslash.tags && twoslash.tags.length) { | ||
html += htmlForTags(twoslash.tags); | ||
} | ||
@@ -760,3 +792,3 @@ | ||
if (replacer[lang]) lang = replacer[lang]; // Add react import | ||
if (replacer[lang]) lang = replacer[lang]; // Add react import to code samples indicating they're needing react. | ||
@@ -777,2 +809,3 @@ if (["tsx", "jsx"].includes(lang) && !settings.disableImplicitReactImport) { | ||
settings.customTags = ["annotate"]; | ||
var results = twoslasher(code, lang, settings); | ||
@@ -779,0 +812,0 @@ return results; |
{ | ||
"name": "shiki-twoslash", | ||
"version": "2.0.3", | ||
"version": "2.1.0", | ||
"license": "MIT", | ||
@@ -30,3 +30,3 @@ "homepage": "https://github.com/shikijs/twoslash", | ||
"dependencies": { | ||
"@typescript/twoslash": "2.1.0", | ||
"@typescript/twoslash": "2.2.0", | ||
"@typescript/vfs": "1.3.4", | ||
@@ -33,0 +33,0 @@ "shiki": "0.9.3", |
@@ -87,2 +87,4 @@ ### shiki-twoslash | ||
vfsRoot?: string; | ||
/** A set of known `// @[tags]` tags to extract and not treat as a comment */ | ||
customTags?: string[]; | ||
} | ||
@@ -135,2 +137,4 @@ ``` | ||
alwayRaiseForTwoslashExceptions?: true; | ||
/** Ignore transforming certain code blocks */ | ||
ignoreCodeblocksWithCodefenceMeta?: string[]; | ||
} | ||
@@ -137,0 +141,0 @@ ``` |
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
304347
19
1721
282
+ Added@typescript/twoslash@2.2.0(transitive)
- Removed@typescript/twoslash@2.1.0(transitive)
Updated@typescript/twoslash@2.2.0