Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@typescript/twoslash

Package Overview
Dependencies
Maintainers
9
Versions
40
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@typescript/twoslash - npm Package Compare versions

Comparing version 0.6.2 to 1.0.0

5

CHANGELOG.md

@@ -0,1 +1,6 @@

## 1.0.0
- Supports falling back to _your project's_ node modules for resolving types and imports. This drastically simplifies setting up a code sample which relies on types not shipped with TypeScript.
- Support for adding vfs JSON files in a code sample
## 0.5.0

@@ -2,0 +7,0 @@

2

dist/index.d.ts

@@ -8,3 +8,3 @@ declare type LZ = typeof import("lz-string");

name: string;
type: "list" | "boolean" | "number" | "string";
type: "list" | "boolean" | "number" | "string" | import("typescript").Map<any>;
element?: Option;

@@ -11,0 +11,0 @@ };

@@ -403,3 +403,3 @@ 'use strict';

function twoslasher(code, extension, options) {
var _options$tsModule, _options$lzstringModu, _options$defaultCompi, _options$fsMap;
var _options$tsModule, _options$lzstringModu, _options$defaultCompi;

@@ -431,4 +431,14 @@ if (options === void 0) {

var compilerOptions = filterCompilerOptions(codeLines, defaultCompilerOptions, ts);
var vfs$1 = (_options$fsMap = options.fsMap) !== null && _options$fsMap !== void 0 ? _options$fsMap : createLocallyPoweredVFS(compilerOptions, ts);
var system = vfs.createSystem(vfs$1);
var getRoot = function getRoot() {
var path = require("path");
return process.cwd().split(path.sep).join(path.posix.sep);
}; // In a browser we want to DI everything, in node we can use local infra
var useFS = !!options.fsMap;
var vfs$1 = useFS && options.fsMap ? options.fsMap : new Map();
var system = useFS ? vfs.createSystem(vfs$1) : vfs.createFSBackedSystem(vfs$1, getRoot(), ts);
var fsRoot = useFS ? "/" : getRoot() + "/";
var env = vfs.createVirtualTypeScriptEnvironment(system, [], ts, compilerOptions, options.customTransformers);

@@ -440,3 +450,4 @@ var ls = env.languageService;

var highlights = [];
var nameContent = splitTwoslashCodeInfoFiles(code, defaultFileName);
var nameContent = splitTwoslashCodeInfoFiles(code, defaultFileName, fsRoot);
var sourceFiles = ["js", "jsx", "ts", "tsx"];
/** All of the referenced files in the markup */

@@ -448,3 +459,3 @@

var _loop4 = function _loop4() {
var _loop5 = function _loop5() {
var _highlights, _partialQueries;

@@ -463,4 +474,10 @@

var filename = file[0],
codeLines = file[1]; // Create the file in the vfs
codeLines = file[1];
var filetype = filename.split(".").pop() || ""; // Only run the LSP-y things on source files
if (!sourceFiles.includes(filetype)) {
return "continue";
} // Create the file in the vfs
var newFileCode = codeLines.join("\n");

@@ -537,8 +554,14 @@ env.createFile(filename, newFileCode);

for (var _iterator2 = nameContent, _isArray2 = Array.isArray(_iterator2), _i5 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
_loop4: for (var _iterator2 = nameContent, _isArray2 = Array.isArray(_iterator2), _i5 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
var _ret2 = _loop4();
var _ret2 = _loop5();
if (_ret2 === "break") break;
switch (_ret2) {
case "break":
break _loop4;
case "continue":
continue;
}
} // We need to also strip the highlights + queries from the main file which is shown to people

@@ -567,2 +590,8 @@

filenames.forEach(function (file) {
var filetype = file.split(".").pop() || ""; // Only run the LSP-y things on source files
if (!sourceFiles.includes(filetype)) {
return;
}
if (!handbookOptions.noErrors) {

@@ -715,3 +744,3 @@ errs.push.apply(errs, ls.getSemanticDiagnostics(file));

var emitFilename = handbookOptions.showEmittedFile || defaultFileName;
var emitSourceFilename = emitFilename.replace(".js", "").replace(".d.ts", "").replace(".map", "");
var emitSourceFilename = fsRoot + emitFilename.replace(".js", "").replace(".d.ts", "").replace(".map", "");
var emitSource = filenames.find(function (f) {

@@ -722,4 +751,5 @@ return f === emitSourceFilename + ".ts" || f === emitSourceFilename + ".tsx";

if (!emitSource) {
var allFiles = filenames.join(", ");
throw new Error("Cannot find the corresponding source file for " + emitFilename + " " + handbookOptions.showEmittedFile + " - in " + allFiles);
var allFiles = filenames.join(", "); // prettier-ignore
throw new Error("Cannot find the corresponding source file for " + emitFilename + " (looking for: " + emitSourceFilename + " in the vfs) - in " + allFiles);
}

@@ -729,3 +759,3 @@

var file = output.outputFiles.find(function (o) {
return o.name === handbookOptions.showEmittedFile;
return o.name === fsRoot + handbookOptions.showEmittedFile;
});

@@ -736,5 +766,6 @@

return o.name;
}).join(", ");
}).join(", "); // prettier-ignore
throw new Error("Cannot find the file " + handbookOptions.showEmittedFile + " - in " + _allFiles);
throw new Error("Cannot find the file " + handbookOptions.showEmittedFile + " (looking for: " + (fsRoot + handbookOptions.showEmittedFile) + " in the vfs) - in " + _allFiles);
}

@@ -805,7 +836,3 @@

var createLocallyPoweredVFS = function createLocallyPoweredVFS(compilerOptions, ts) {
return vfs.createDefaultMapFromNodeModules(compilerOptions, ts);
};
var splitTwoslashCodeInfoFiles = function splitTwoslashCodeInfoFiles(code, defaultFileName) {
var splitTwoslashCodeInfoFiles = function splitTwoslashCodeInfoFiles(code, defaultFileName, root) {
var lines = code.split(/\r\n?|\n/g);

@@ -831,3 +858,3 @@ var nameForFile = code.includes("@filename: " + defaultFileName) ? "global.ts" : defaultFileName;

if (line.includes("// @filename: ")) {
fileMap.push([nameForFile, currentFileContent]);
fileMap.push([root + nameForFile, currentFileContent]);
nameForFile = line.split("// @filename: ")[1].trim();

@@ -840,3 +867,3 @@ currentFileContent = [];

fileMap.push([nameForFile, currentFileContent]); // Basically, strip these:
fileMap.push([root + nameForFile, currentFileContent]); // Basically, strip these:
// ["index.ts", []]

@@ -843,0 +870,0 @@ // ["index.ts", [""]]

@@ -1,2 +0,2 @@

"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@typescript/vfs");function t(){return(t=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e}).apply(this,arguments)}function r(e,t){switch(t){case"number":return+e;case"string":return e;case"boolean":return"true"===e.toLowerCase()||0===e.length}throw new Error("Unknown primitive type "+t+" with - "+e)}var n=!1;try{n="undefined"!=typeof localStorage}catch(e){}var i="undefined"!=typeof process,o=n&&localStorage.getItem("DEBUG")||i&&process.env.DEBUG?console.log:function(e){return""};function a(e){for(var t=[],r=[],n=0,i=0,a=0,s=function(s){var c=e[s],f=function(){i=n,n+=c.length+1},u=function(t){o("Removing line "+s+" for "+t),a++,e.splice(s,1),s--};if(c.includes("//")){var p=/^\/\/\s*\^+( .+)?$/.exec(c),d=/^\/\/\s*\^\?\s*$/.exec(c),h=/^\s*\/\/ prettier-ignore$/.exec(c),g=/^\/\/\s*\^\|$/.exec(c);if(null!==d){var v=c.indexOf("^");r.push({kind:"query",offset:v,text:void 0,docs:void 0,line:s+a-1}),u("having a query")}else if(null!==p){var m=c.indexOf("^"),y=c.lastIndexOf("^")-m+1,x=i+m,w=p[1]?p[1].trim():"";t.push({kind:"highlight",position:x,length:y,description:w,line:s}),u("having a highlight")}else if(null!==h)u("being a prettier ignore");else if(null!==g){var E=c.indexOf("^");r.push({kind:"completion",offset:E,text:void 0,docs:void 0,line:s+a-1}),u("having a completion query")}else f()}else f();l=s},l=0;l<e.length;l++)s(l);return{highlights:t,queries:r}}function s(e,t,n,i){o("Setting "+e+" to "+t);var a=function(){if(l){if(c>=s.length)return"break";f=s[c++]}else{if((c=s.next()).done)return"break";f=c.value}var i=f;if(i.name.toLowerCase()===e.toLowerCase()){switch(i.type){case"number":case"string":case"boolean":n[i.name]=r(t,i.type);break;case"list":n[i.name]=t.split(",").map((function(e){return r(e,i.element.type)}));break;default:var a=i.type;if(n[i.name]=a.get(t.toLowerCase()),o("Set "+i.name+" to "+n[i.name]),void 0===n[i.name]){var u=Array.from(a.keys());throw new Error("Invalid value "+t+" for "+i.name+". Allowed values: "+u.join(","))}}return{v:void 0}}},s=i.optionDeclarations,l=Array.isArray(s),c=0;e:for(s=l?s:s[Symbol.iterator]();;){var f,u=a();switch(u){case"break":break e;default:if("object"==typeof u)return u.v}}throw new Error("No compiler setting named '"+e+"' exists!")}var l=/^\/\/\s?@(\w+)$/,c=/^\/\/\s?@(\w+):\s?(.+)$/,f={errors:[],noErrors:!1,showEmit:!1,showEmittedFile:"index.js",noStaticSemanticInfo:!1,emit:!1,noErrorValidation:!1};exports.twoslasher=function(r,n,i){var u,p,d,h;void 0===i&&(i={});var g=null!==(u=i.tsModule)&&void 0!==u?u:require("typescript"),v=null!==(p=i.lzstringModule)&&void 0!==p?p:require("lz-string"),m=r,y=function(e){switch(e){case"js":case"javascript":return"js";case"ts":case"typescript":return"ts";case"tsx":return"tsx";case"jsn":return"json"}throw new Error("Cannot handle the file extension:"+e)}(n),x="index."+y;o("\n\nLooking at code: \n```"+y+"\n"+r+"\n```\n");var w=t({strict:!0,target:g.ScriptTarget.ES2016,allowJs:!0},null!==(d=i.defaultCompilerOptions)&&void 0!==d?d:{});!function(e){if(e.includes("// @errors "))throw new Error("You have '@errors ' - you're missing the colon after errors");if(e.includes("// @filename "))throw new Error("You have '@filename ' - you're missing the colon after filename")}(r);var E=(r=function(e){return(e=e.replace(/¨D/g,"$")).replace(/¨T/g,"~")}(r)).split(/\r\n?|\n/g),b=t({},function(e){for(var r=t({},f),n=0;n<e.length;n++){var i=void 0;(i=l.exec(e[n]))?i[1]in r&&(r[i[1]]=!0,o("Setting options."+i[1]+" to true"),e.splice(n,1),n--):(i=c.exec(e[n]))&&i[1]in r&&(r[i[1]]=i[2],o("Setting options."+i[1]+" to "+i[2]),e.splice(n,1),n--)}return"errors"in r&&"string"==typeof r.errors&&(r.errors=r.errors.split(" ").map(Number),o("Setting options.error to ",r.errors)),r}(E),{},i.defaultOptions),S=function(e,r,n){for(var i=t({},r),o=0;o<e.length;){var a=void 0;if(a=l.exec(e[o]))i[a[1]]=!0,s(a[1],"true",i,n);else{if(!(a=c.exec(e[o]))){o++;continue}if("filename"===a[1]){o++;continue}s(a[1],a[2],i,n)}e.splice(o,1)}return i}(E,w,g),k=null!==(h=i.fsMap)&&void 0!==h?h:function(t,r){return e.createDefaultMapFromNodeModules(t,r)}(S,g),j=e.createSystem(k),P=e.createVirtualTypeScriptEnvironment(j,[],g,S,i.customTransformers),A=P.languageService;r=E.join("\n");var O=[],F=[],C=[],T=function(e,t){var r=e.split(/\r\n?|\n/g),n=e.includes("@filename: "+t)?"global.ts":t,i=[],o=[],a=r,s=Array.isArray(a),l=0;for(a=s?a:a[Symbol.iterator]();;){var c;if(s){if(l>=a.length)break;c=a[l++]}else{if((l=a.next()).done)break;c=l.value}var f=c;f.includes("// @filename: ")?(o.push([n,i]),n=f.split("// @filename: ")[1].trim(),i=[]):i.push(f)}return o.push([n,i]),o.filter((function(e){return e[1].length>0&&(e[1].length>1||""!==e[1][0])}))}(r,x),q=T.map((function(e){return e[0]})),L=function(){var e,t;if(D){if(M>=I.length)return"break";$=I[M++]}else{if((M=I.next()).done)return"break";$=M.value}var r=$[0],n=$[1],i=n.join("\n");P.createFile(r,i);var o=a(n);(e=C).push.apply(e,o.highlights);var s=o.queries.map((function(e,t){var n,i,o=P.getSourceFile(r),a=g.getPositionOfLineAndCharacter(o,e.line,e.offset);switch(e.kind){case"query":var s=A.getQuickInfoAtPosition(r,a),l=A.getDefinitionAtPosition(r,a),c="Could not get LSP result: "+[(n=P.getSourceFile(r).text)[(i=a)-3],n[i-2],n[i-1],">",n[i],"<",n[i+1],n[i+2],n[i+3]].filter(Boolean).join(""),f=void 0;return s&&l&&s.displayParts&&(c=s.displayParts.map((function(e){return e.text})).join(""),f=s.documentation?s.documentation.map((function(e){return e.text})).join("<br/>"):void 0),{kind:"query",text:c,docs:f,line:e.line-t,offset:e.offset,file:r};case"completion":var u=A.getCompletionsAtPosition(r,a-1,{});if(!u&&!b.noErrorValidation)throw new Error("Twoslash: The ^| query at line "+e.line+" in "+r+" did not return any completions");var p=function(e,t){e=String(e),t=Number(t)>>>0;var r=e.slice(0,t+1).search(/\S+$/),n=e.slice(t).search(/\s/);return n<0?{word:e.slice(r),startPos:r}:{word:e.slice(r,n+t),startPos:r}}(o.text,a-1),d=o.text.slice(p.startPos,a).split(".").pop()||"";return{kind:"completions",completions:(null==u?void 0:u.entries)||[],completionPrefix:d,line:e.line-t,offset:e.offset,file:r}}}));(t=O).push.apply(t,s);var l=n.join("\n");P.updateFile(r,l)},I=T,D=Array.isArray(I),M=0;for(I=D?I:I[Symbol.iterator]();;){var $;if("break"===L())break}var N=r.split(/\r\n?|\n/g);a(N),r=N.join("\n"),b.emit&&q.forEach((function(e){A.getEmitOutput(e).outputFiles.forEach((function(e){j.writeFile(e.name,e.text)}))}));var U=[],V=[];q.forEach((function(e){b.noErrors||(U.push.apply(U,A.getSemanticDiagnostics(e)),U.push.apply(U,A.getSyntacticDiagnostics(e)));var t=P.sys.readFile(e),n=P.getSourceFile(e);if(!n)throw new Error("No sourcefile found for "+e+" in twoslash");if(!b.showEmit){var i=-1==r.indexOf(t)?0:r.indexOf(t),o=r.slice(0,i).split("\n").length-1,a=b.noStaticSemanticInfo?[]:function(e,t){var r=[];return function n(i){e.forEachChild(i,(function(i){if(e.isIdentifier(i)){var o=i.getStart(t,!1);r.push({span:e.createTextSpan(o,i.end-o),text:i.getText(t)})}n(i)}))}(t),r}(g,n),s=Array.isArray(a),l=0;for(a=s?a:a[Symbol.iterator]();;){var c;if(s){if(l>=a.length)break;c=a[l++]}else{if((l=a.next()).done)break;c=l.value}var f=c,u=f.span,p=A.getQuickInfoAtPosition(e,u.start);if(p&&p.displayParts){var d=p.displayParts.map((function(e){return e.text})).join(""),h=f.text,v=p.documentation?p.documentation.map((function(e){return e.text})).join("\n"):void 0,m=u.start+i,y=g.createSourceFile("_.ts",r,g.ScriptTarget.ES2015),x=g.getLineAndCharacterOfPosition(y,m);V.push({text:d,docs:v,start:m,length:u.length,line:x.line,character:x.character,targetString:h})}}O.filter((function(t){return t.file===e})).forEach((function(e){var t=g.getPositionOfLineAndCharacter(n,e.line,e.offset)+i;switch(e.kind){case"query":F.push({docs:e.docs,kind:"query",start:t+i,length:e.text.length,text:e.text,offset:e.offset,line:e.line+o+1});break;case"completions":F.push({completions:e.completions,kind:"completions",start:t+i,completionsPrefix:e.completionPrefix,length:1,offset:e.offset,line:e.line+o+1})}}))}}));var B=U.filter((function(e){return e.file&&q.includes(e.file.fileName)}));!b.noErrorValidation&&B.length&&function(e,t,r,n){var i=e.filter((function(e){return!t.errors.includes(e.code)})),o=i.map((function(e){return e.code})).join(" ");if(i.length){var a="// @errors: "+e.map((function(e){return e.code})).join(" "),s=t.errors.length?" - the annotation specified "+t.errors:"\n\nExpected:\n"+a,l=i.map((function(e){return"["+e.code+"] - "+("string"==typeof e.messageText?e.messageText:e.messageText.messageText)})).join("\n ");throw new Error("Errors were thrown in the sample, but not included in an errors tag: "+o+s+"\n\n "+l+"\n\n## Code\n\n'''"+r+"\n"+n+"\n'''")}}(B,b,n,m);var Q=[],R=B,_=Array.isArray(R),z=0;for(R=_?R:R[Symbol.iterator]();;){var G;if(_){if(z>=R.length)break;G=R[z++]}else{if((z=R.next()).done)break;G=z.value}var Y=G,J=P.sys.readFile(Y.file.fileName),H=r.indexOf(J),K=g.flattenDiagnosticMessageText(Y.messageText,"\n").replace(/</g,"&lt;"),W="err-"+Y.code+"-"+Y.start+"-"+Y.length,X=g.getLineAndCharacterOfPosition(Y.file,Y.start);Q.push({category:Y.category,code:Y.code,length:Y.length,start:Y.start?Y.start+H:void 0,line:X.line,character:X.character,renderedMessage:K,id:W})}if(b.showEmit){var Z=b.showEmittedFile||x,ee=Z.replace(".js","").replace(".d.ts","").replace(".map",""),te=q.find((function(e){return e===ee+".ts"||e===ee+".tsx"}));if(!te){var re=q.join(", ");throw new Error("Cannot find the corresponding source file for "+Z+" "+b.showEmittedFile+" - in "+re)}var ne=A.getEmitOutput(te),ie=ne.outputFiles.find((function(e){return e.name===b.showEmittedFile}));if(!ie){var oe=ne.outputFiles.map((function(e){return e.name})).join(", ");throw new Error("Cannot find the file "+b.showEmittedFile+" - in "+oe)}r=ie.text,n=ie.name.split(".").pop(),C=[],O=[],V=[]}var ae="https://www.typescriptlang.org/play/#code/"+v.compressToEncodedURIComponent(m),se="// ---cut---\n";if(r.includes(se)){var le=r.indexOf(se)+se.length,ce=r.substr(0,le).split("\n").length-1;r=r.split(se).pop(),V.forEach((function(e){e.start-=le,e.line-=ce})),V=V.filter((function(e){return e.start>-1})),Q.forEach((function(e){e.start&&(e.start-=le),e.line&&(e.line-=ce)})),Q=Q.filter((function(e){return e.start&&e.start>-1})),C.forEach((function(e){e.position-=le,e.line-=ce})),C=C.filter((function(e){return e.position>-1})),F.forEach((function(e){return e.line-=ce})),F=F.filter((function(e){return e.line>-1}))}return{code:r,extension:n,highlights:C,queries:F,staticQuickInfos:V,errors:Q,playgroundURL:ae}};
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@typescript/vfs");function t(){return(t=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e}).apply(this,arguments)}function r(e,t){switch(t){case"number":return+e;case"string":return e;case"boolean":return"true"===e.toLowerCase()||0===e.length}throw new Error("Unknown primitive type "+t+" with - "+e)}var n=!1;try{n="undefined"!=typeof localStorage}catch(e){}var i="undefined"!=typeof process,o=n&&localStorage.getItem("DEBUG")||i&&process.env.DEBUG?console.log:function(e){return""};function a(e){for(var t=[],r=[],n=0,i=0,a=0,s=function(s){var c=e[s],f=function(){i=n,n+=c.length+1},u=function(t){o("Removing line "+s+" for "+t),a++,e.splice(s,1),s--};if(c.includes("//")){var p=/^\/\/\s*\^+( .+)?$/.exec(c),d=/^\/\/\s*\^\?\s*$/.exec(c),h=/^\s*\/\/ prettier-ignore$/.exec(c),g=/^\/\/\s*\^\|$/.exec(c);if(null!==d){var v=c.indexOf("^");r.push({kind:"query",offset:v,text:void 0,docs:void 0,line:s+a-1}),u("having a query")}else if(null!==p){var m=c.indexOf("^"),y=c.lastIndexOf("^")-m+1,x=i+m,w=p[1]?p[1].trim():"";t.push({kind:"highlight",position:x,length:y,description:w,line:s}),u("having a highlight")}else if(null!==h)u("being a prettier ignore");else if(null!==g){var E=c.indexOf("^");r.push({kind:"completion",offset:E,text:void 0,docs:void 0,line:s+a-1}),u("having a completion query")}else f()}else f();l=s},l=0;l<e.length;l++)s(l);return{highlights:t,queries:r}}function s(e,t,n,i){o("Setting "+e+" to "+t);var a=function(){if(l){if(c>=s.length)return"break";f=s[c++]}else{if((c=s.next()).done)return"break";f=c.value}var i=f;if(i.name.toLowerCase()===e.toLowerCase()){switch(i.type){case"number":case"string":case"boolean":n[i.name]=r(t,i.type);break;case"list":n[i.name]=t.split(",").map((function(e){return r(e,i.element.type)}));break;default:var a=i.type;if(n[i.name]=a.get(t.toLowerCase()),o("Set "+i.name+" to "+n[i.name]),void 0===n[i.name]){var u=Array.from(a.keys());throw new Error("Invalid value "+t+" for "+i.name+". Allowed values: "+u.join(","))}}return{v:void 0}}},s=i.optionDeclarations,l=Array.isArray(s),c=0;e:for(s=l?s:s[Symbol.iterator]();;){var f,u=a();switch(u){case"break":break e;default:if("object"==typeof u)return u.v}}throw new Error("No compiler setting named '"+e+"' exists!")}var l=/^\/\/\s?@(\w+)$/,c=/^\/\/\s?@(\w+):\s?(.+)$/,f={errors:[],noErrors:!1,showEmit:!1,showEmittedFile:"index.js",noStaticSemanticInfo:!1,emit:!1,noErrorValidation:!1};exports.twoslasher=function(r,n,i){var u,p,d;void 0===i&&(i={});var h=null!==(u=i.tsModule)&&void 0!==u?u:require("typescript"),g=null!==(p=i.lzstringModule)&&void 0!==p?p:require("lz-string"),v=r,m=function(e){switch(e){case"js":case"javascript":return"js";case"ts":case"typescript":return"ts";case"tsx":return"tsx";case"jsn":return"json"}throw new Error("Cannot handle the file extension:"+e)}(n),y="index."+m;o("\n\nLooking at code: \n```"+m+"\n"+r+"\n```\n");var x=t({strict:!0,target:h.ScriptTarget.ES2016,allowJs:!0},null!==(d=i.defaultCompilerOptions)&&void 0!==d?d:{});!function(e){if(e.includes("// @errors "))throw new Error("You have '@errors ' - you're missing the colon after errors");if(e.includes("// @filename "))throw new Error("You have '@filename ' - you're missing the colon after filename")}(r);var w=(r=function(e){return(e=e.replace(/¨D/g,"$")).replace(/¨T/g,"~")}(r)).split(/\r\n?|\n/g),E=t({},function(e){for(var r=t({},f),n=0;n<e.length;n++){var i=void 0;(i=l.exec(e[n]))?i[1]in r&&(r[i[1]]=!0,o("Setting options."+i[1]+" to true"),e.splice(n,1),n--):(i=c.exec(e[n]))&&i[1]in r&&(r[i[1]]=i[2],o("Setting options."+i[1]+" to "+i[2]),e.splice(n,1),n--)}return"errors"in r&&"string"==typeof r.errors&&(r.errors=r.errors.split(" ").map(Number),o("Setting options.error to ",r.errors)),r}(w),{},i.defaultOptions),b=function(e,r,n){for(var i=t({},r),o=0;o<e.length;){var a=void 0;if(a=l.exec(e[o]))i[a[1]]=!0,s(a[1],"true",i,n);else{if(!(a=c.exec(e[o]))){o++;continue}if("filename"===a[1]){o++;continue}s(a[1],a[2],i,n)}e.splice(o,1)}return i}(w,x,h),S=function(){var e=require("path");return process.cwd().split(e.sep).join(e.posix.sep)},k=!!i.fsMap,j=k&&i.fsMap?i.fsMap:new Map,P=k?e.createSystem(j):e.createFSBackedSystem(j,S(),h),A=k?"/":S()+"/",O=e.createVirtualTypeScriptEnvironment(P,[],h,b,i.customTransformers),F=O.languageService;r=w.join("\n");var C=[],T=[],q=[],L=function(e,t,r){var n=e.split(/\r\n?|\n/g),i=e.includes("@filename: "+t)?"global.ts":t,o=[],a=[],s=n,l=Array.isArray(s),c=0;for(s=l?s:s[Symbol.iterator]();;){var f;if(l){if(c>=s.length)break;f=s[c++]}else{if((c=s.next()).done)break;f=c.value}var u=f;u.includes("// @filename: ")?(a.push([r+i,o]),i=u.split("// @filename: ")[1].trim(),o=[]):o.push(u)}return a.push([r+i,o]),a.filter((function(e){return e[1].length>0&&(e[1].length>1||""!==e[1][0])}))}(r,y,A),I=["js","jsx","ts","tsx"],M=L.map((function(e){return e[0]})),D=function(){var e,t;if(N){if(U>=$.length)return"break";B=$[U++]}else{if((U=$.next()).done)return"break";B=U.value}var r=B[0],n=B[1],i=r.split(".").pop()||"";if(!I.includes(i))return"continue";var o=n.join("\n");O.createFile(r,o);var s=a(n);(e=q).push.apply(e,s.highlights);var l=s.queries.map((function(e,t){var n,i,o=O.getSourceFile(r),a=h.getPositionOfLineAndCharacter(o,e.line,e.offset);switch(e.kind){case"query":var s=F.getQuickInfoAtPosition(r,a),l=F.getDefinitionAtPosition(r,a),c="Could not get LSP result: "+[(n=O.getSourceFile(r).text)[(i=a)-3],n[i-2],n[i-1],">",n[i],"<",n[i+1],n[i+2],n[i+3]].filter(Boolean).join(""),f=void 0;return s&&l&&s.displayParts&&(c=s.displayParts.map((function(e){return e.text})).join(""),f=s.documentation?s.documentation.map((function(e){return e.text})).join("<br/>"):void 0),{kind:"query",text:c,docs:f,line:e.line-t,offset:e.offset,file:r};case"completion":var u=F.getCompletionsAtPosition(r,a-1,{});if(!u&&!E.noErrorValidation)throw new Error("Twoslash: The ^| query at line "+e.line+" in "+r+" did not return any completions");var p=function(e,t){e=String(e),t=Number(t)>>>0;var r=e.slice(0,t+1).search(/\S+$/),n=e.slice(t).search(/\s/);return n<0?{word:e.slice(r),startPos:r}:{word:e.slice(r,n+t),startPos:r}}(o.text,a-1),d=o.text.slice(p.startPos,a).split(".").pop()||"";return{kind:"completions",completions:(null==u?void 0:u.entries)||[],completionPrefix:d,line:e.line-t,offset:e.offset,file:r}}}));(t=C).push.apply(t,l);var c=n.join("\n");O.updateFile(r,c)},$=L,N=Array.isArray($),U=0;e:for($=N?$:$[Symbol.iterator]();;){var B;switch(D()){case"break":break e;case"continue":continue}}var V=r.split(/\r\n?|\n/g);a(V),r=V.join("\n"),E.emit&&M.forEach((function(e){F.getEmitOutput(e).outputFiles.forEach((function(e){P.writeFile(e.name,e.text)}))}));var Q=[],R=[];M.forEach((function(e){var t=e.split(".").pop()||"";if(I.includes(t)){E.noErrors||(Q.push.apply(Q,F.getSemanticDiagnostics(e)),Q.push.apply(Q,F.getSyntacticDiagnostics(e)));var n=O.sys.readFile(e),i=O.getSourceFile(e);if(!i)throw new Error("No sourcefile found for "+e+" in twoslash");if(!E.showEmit){var o=-1==r.indexOf(n)?0:r.indexOf(n),a=r.slice(0,o).split("\n").length-1,s=E.noStaticSemanticInfo?[]:function(e,t){var r=[];return function n(i){e.forEachChild(i,(function(i){if(e.isIdentifier(i)){var o=i.getStart(t,!1);r.push({span:e.createTextSpan(o,i.end-o),text:i.getText(t)})}n(i)}))}(t),r}(h,i),l=Array.isArray(s),c=0;for(s=l?s:s[Symbol.iterator]();;){var f;if(l){if(c>=s.length)break;f=s[c++]}else{if((c=s.next()).done)break;f=c.value}var u=f,p=u.span,d=F.getQuickInfoAtPosition(e,p.start);if(d&&d.displayParts){var g=d.displayParts.map((function(e){return e.text})).join(""),v=u.text,m=d.documentation?d.documentation.map((function(e){return e.text})).join("\n"):void 0,y=p.start+o,x=h.createSourceFile("_.ts",r,h.ScriptTarget.ES2015),w=h.getLineAndCharacterOfPosition(x,y);R.push({text:g,docs:m,start:y,length:p.length,line:w.line,character:w.character,targetString:v})}}C.filter((function(t){return t.file===e})).forEach((function(e){var t=h.getPositionOfLineAndCharacter(i,e.line,e.offset)+o;switch(e.kind){case"query":T.push({docs:e.docs,kind:"query",start:t+o,length:e.text.length,text:e.text,offset:e.offset,line:e.line+a+1});break;case"completions":T.push({completions:e.completions,kind:"completions",start:t+o,completionsPrefix:e.completionPrefix,length:1,offset:e.offset,line:e.line+a+1})}}))}}}));var _=Q.filter((function(e){return e.file&&M.includes(e.file.fileName)}));!E.noErrorValidation&&_.length&&function(e,t,r,n){var i=e.filter((function(e){return!t.errors.includes(e.code)})),o=i.map((function(e){return e.code})).join(" ");if(i.length){var a="// @errors: "+e.map((function(e){return e.code})).join(" "),s=t.errors.length?" - the annotation specified "+t.errors:"\n\nExpected:\n"+a,l=i.map((function(e){return"["+e.code+"] - "+("string"==typeof e.messageText?e.messageText:e.messageText.messageText)})).join("\n ");throw new Error("Errors were thrown in the sample, but not included in an errors tag: "+o+s+"\n\n "+l+"\n\n## Code\n\n'''"+r+"\n"+n+"\n'''")}}(_,E,n,v);var z=[],G=_,Y=Array.isArray(G),J=0;for(G=Y?G:G[Symbol.iterator]();;){var H;if(Y){if(J>=G.length)break;H=G[J++]}else{if((J=G.next()).done)break;H=J.value}var K=H,W=O.sys.readFile(K.file.fileName),X=r.indexOf(W),Z=h.flattenDiagnosticMessageText(K.messageText,"\n").replace(/</g,"&lt;"),ee="err-"+K.code+"-"+K.start+"-"+K.length,te=h.getLineAndCharacterOfPosition(K.file,K.start);z.push({category:K.category,code:K.code,length:K.length,start:K.start?K.start+X:void 0,line:te.line,character:te.character,renderedMessage:Z,id:ee})}if(E.showEmit){var re=E.showEmittedFile||y,ne=A+re.replace(".js","").replace(".d.ts","").replace(".map",""),ie=M.find((function(e){return e===ne+".ts"||e===ne+".tsx"}));if(!ie){var oe=M.join(", ");throw new Error("Cannot find the corresponding source file for "+re+" (looking for: "+ne+" in the vfs) - in "+oe)}var ae=F.getEmitOutput(ie),se=ae.outputFiles.find((function(e){return e.name===A+E.showEmittedFile}));if(!se){var le=ae.outputFiles.map((function(e){return e.name})).join(", ");throw new Error("Cannot find the file "+E.showEmittedFile+" (looking for: "+(A+E.showEmittedFile)+" in the vfs) - in "+le)}r=se.text,n=se.name.split(".").pop(),q=[],C=[],R=[]}var ce="https://www.typescriptlang.org/play/#code/"+g.compressToEncodedURIComponent(v),fe="// ---cut---\n";if(r.includes(fe)){var ue=r.indexOf(fe)+fe.length,pe=r.substr(0,ue).split("\n").length-1;r=r.split(fe).pop(),R.forEach((function(e){e.start-=ue,e.line-=pe})),R=R.filter((function(e){return e.start>-1})),z.forEach((function(e){e.start&&(e.start-=ue),e.line&&(e.line-=pe)})),z=z.filter((function(e){return e.start&&e.start>-1})),q.forEach((function(e){e.position-=ue,e.line-=pe})),q=q.filter((function(e){return e.position>-1})),T.forEach((function(e){return e.line-=pe})),T=T.filter((function(e){return e.line>-1}))}return{code:r,extension:n,highlights:q,queries:T,staticQuickInfos:R,errors:z,playgroundURL:ce}};
//# sourceMappingURL=twoslash.cjs.production.min.js.map

@@ -1,2 +0,2 @@

import { createDefaultMapFromNodeModules, createSystem, createVirtualTypeScriptEnvironment } from '@typescript/vfs';
import { createSystem, createFSBackedSystem, createVirtualTypeScriptEnvironment } from '@typescript/vfs';

@@ -399,3 +399,3 @@ function _extends() {

function twoslasher(code, extension, options) {
var _options$tsModule, _options$lzstringModu, _options$defaultCompi, _options$fsMap;
var _options$tsModule, _options$lzstringModu, _options$defaultCompi;

@@ -427,4 +427,14 @@ if (options === void 0) {

var compilerOptions = filterCompilerOptions(codeLines, defaultCompilerOptions, ts);
var vfs = (_options$fsMap = options.fsMap) !== null && _options$fsMap !== void 0 ? _options$fsMap : createLocallyPoweredVFS(compilerOptions, ts);
var system = createSystem(vfs);
var getRoot = function getRoot() {
var path = require("path");
return process.cwd().split(path.sep).join(path.posix.sep);
}; // In a browser we want to DI everything, in node we can use local infra
var useFS = !!options.fsMap;
var vfs = useFS && options.fsMap ? options.fsMap : new Map();
var system = useFS ? createSystem(vfs) : createFSBackedSystem(vfs, getRoot(), ts);
var fsRoot = useFS ? "/" : getRoot() + "/";
var env = createVirtualTypeScriptEnvironment(system, [], ts, compilerOptions, options.customTransformers);

@@ -436,3 +446,4 @@ var ls = env.languageService;

var highlights = [];
var nameContent = splitTwoslashCodeInfoFiles(code, defaultFileName);
var nameContent = splitTwoslashCodeInfoFiles(code, defaultFileName, fsRoot);
var sourceFiles = ["js", "jsx", "ts", "tsx"];
/** All of the referenced files in the markup */

@@ -444,3 +455,3 @@

var _loop4 = function _loop4() {
var _loop5 = function _loop5() {
var _highlights, _partialQueries;

@@ -459,4 +470,10 @@

var filename = file[0],
codeLines = file[1]; // Create the file in the vfs
codeLines = file[1];
var filetype = filename.split(".").pop() || ""; // Only run the LSP-y things on source files
if (!sourceFiles.includes(filetype)) {
return "continue";
} // Create the file in the vfs
var newFileCode = codeLines.join("\n");

@@ -533,8 +550,14 @@ env.createFile(filename, newFileCode);

for (var _iterator2 = nameContent, _isArray2 = Array.isArray(_iterator2), _i5 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
_loop4: for (var _iterator2 = nameContent, _isArray2 = Array.isArray(_iterator2), _i5 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
var _ret2 = _loop4();
var _ret2 = _loop5();
if (_ret2 === "break") break;
switch (_ret2) {
case "break":
break _loop4;
case "continue":
continue;
}
} // We need to also strip the highlights + queries from the main file which is shown to people

@@ -563,2 +586,8 @@

filenames.forEach(function (file) {
var filetype = file.split(".").pop() || ""; // Only run the LSP-y things on source files
if (!sourceFiles.includes(filetype)) {
return;
}
if (!handbookOptions.noErrors) {

@@ -711,3 +740,3 @@ errs.push.apply(errs, ls.getSemanticDiagnostics(file));

var emitFilename = handbookOptions.showEmittedFile || defaultFileName;
var emitSourceFilename = emitFilename.replace(".js", "").replace(".d.ts", "").replace(".map", "");
var emitSourceFilename = fsRoot + emitFilename.replace(".js", "").replace(".d.ts", "").replace(".map", "");
var emitSource = filenames.find(function (f) {

@@ -718,4 +747,5 @@ return f === emitSourceFilename + ".ts" || f === emitSourceFilename + ".tsx";

if (!emitSource) {
var allFiles = filenames.join(", ");
throw new Error("Cannot find the corresponding source file for " + emitFilename + " " + handbookOptions.showEmittedFile + " - in " + allFiles);
var allFiles = filenames.join(", "); // prettier-ignore
throw new Error("Cannot find the corresponding source file for " + emitFilename + " (looking for: " + emitSourceFilename + " in the vfs) - in " + allFiles);
}

@@ -725,3 +755,3 @@

var file = output.outputFiles.find(function (o) {
return o.name === handbookOptions.showEmittedFile;
return o.name === fsRoot + handbookOptions.showEmittedFile;
});

@@ -732,5 +762,6 @@

return o.name;
}).join(", ");
}).join(", "); // prettier-ignore
throw new Error("Cannot find the file " + handbookOptions.showEmittedFile + " - in " + _allFiles);
throw new Error("Cannot find the file " + handbookOptions.showEmittedFile + " (looking for: " + (fsRoot + handbookOptions.showEmittedFile) + " in the vfs) - in " + _allFiles);
}

@@ -801,7 +832,3 @@

var createLocallyPoweredVFS = function createLocallyPoweredVFS(compilerOptions, ts) {
return createDefaultMapFromNodeModules(compilerOptions, ts);
};
var splitTwoslashCodeInfoFiles = function splitTwoslashCodeInfoFiles(code, defaultFileName) {
var splitTwoslashCodeInfoFiles = function splitTwoslashCodeInfoFiles(code, defaultFileName, root) {
var lines = code.split(/\r\n?|\n/g);

@@ -827,3 +854,3 @@ var nameForFile = code.includes("@filename: " + defaultFileName) ? "global.ts" : defaultFileName;

if (line.includes("// @filename: ")) {
fileMap.push([nameForFile, currentFileContent]);
fileMap.push([root + nameForFile, currentFileContent]);
nameForFile = line.split("// @filename: ")[1].trim();

@@ -836,3 +863,3 @@ currentFileContent = [];

fileMap.push([nameForFile, currentFileContent]); // Basically, strip these:
fileMap.push([root + nameForFile, currentFileContent]); // Basically, strip these:
// ["index.ts", []]

@@ -839,0 +866,0 @@ // ["index.ts", [""]]

{
"name": "@typescript/twoslash",
"version": "0.6.2",
"version": "1.0.0",
"license": "MIT",

@@ -15,3 +15,2 @@ "author": "TypeScript team",

"build": "tsdx build && yarn readme",
"bootstrap": "yarn build",
"readme": "yarn md-magic README.md --config ./scripts/inline-results.js && yarn prettier README.md --write",

@@ -44,3 +43,3 @@ "test": "tsdx test",

"dependencies": {
"@typescript/vfs": "1.1.2",
"@typescript/vfs": "1.2.0",
"debug": "^4.1.1",

@@ -47,0 +46,0 @@ "lz-string": "^1.4.4"

@@ -584,2 +584,54 @@ # TypeScript TwoSlash

#### `importsModules.ts`
```ts
// @filename: Component.tsx
import React from "react"
export function Hello() {
return (
<div>
<h1>Hello World</h1>
</div>
)
}
// @filename: index.ts
import { Hello } from "./Component"
console.log(Hello)
```
Turns to:
> ```ts
> // @filename: Component.tsx
> import React from "react"
>
> export function Hello() {
> return (
> <div>
> <h1>Hello World</h1>
> </div>
> )
> }
>
> // @filename: index.ts
> import { Hello } from "./Component"
> console.log(Hello)
> ```
> With:
> ```json
> {
> "code": "See above",
> "extension": "ts",
> "highlights": [],
> "queries": [],
> "staticQuickInfos": "[ 10 items ]",
> "errors": [],
> "playgroundURL": "https://www.typescriptlang.org/play/#code/PTAEAEDMEsBsFMB2BDAtvAXKAwge1QA66JIAuAdKQM4AeAUNIbgE6mgBK8yAxm5M-lAAiZl15C6deDSKtQkAK6Je0YqAAS8WLFwAKAJSgA3nVChRpBc0Shdps6AA8AE2gA3AHz2HTgBYBGD01tXFAAdRZYZ0dgAK8fGNdPe306AF9JEAgYBBR0LGhEZ2lKKgYmOSMNLR1QNPkBVGFyYDwmEkRSCW5iKlwEch0Ac11gnVSgA"
> }
> ```
#### `query.ts`

@@ -586,0 +638,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

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc