├── .gitignore
├── .npmignore
├── .vscode
└── settings.json
├── CONTRIBUTING.md
├── README.md
├── images
└── img.png
├── package.json
├── rollup.config.js
├── scripts
└── getDTS.js
├── src
├── index.ts
└── vendor
│ ├── playground.d.ts
│ ├── pluginUtils.d.ts
│ ├── sandbox.d.ts
│ ├── tsWorker.d.ts
│ ├── typescript-vfs.d.ts
│ └── utils.ts
├── tsconfig.json
└── yarn.lock
/.gitignore:
--------------------------------------------------------------------------------
1 | # Logs
2 | logs
3 | *.log
4 | npm-debug.log*
5 | yarn-debug.log*
6 | yarn-error.log*
7 |
8 | # Runtime data
9 | pids
10 | *.pid
11 | *.seed
12 | *.pid.lock
13 |
14 | # Directory for instrumented libs generated by jscoverage/JSCover
15 | lib-cov
16 |
17 | # Coverage directory used by tools like istanbul
18 | coverage
19 |
20 | # nyc test coverage
21 | .nyc_output
22 |
23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
24 | .grunt
25 |
26 | # Bower dependency directory (https://bower.io/)
27 | bower_components
28 |
29 | # node-waf configuration
30 | .lock-wscript
31 |
32 | # Compiled binary addons (http://nodejs.org/api/addons.html)
33 | build/Release
34 |
35 | # Dependency directories
36 | node_modules/
37 | jspm_packages/
38 |
39 | # Typescript v1 declaration files
40 | typings/
41 |
42 | # Optional npm cache directory
43 | .npm
44 |
45 | # Optional eslint cache
46 | .eslintcache
47 |
48 | # Optional REPL history
49 | .node_repl_history
50 |
51 | # Output of 'npm pack'
52 | *.tgz
53 |
54 | # dotenv environment variables file
55 | .env
56 |
57 | # gatsby files
58 | .cache/
59 | public
60 |
61 | # Mac files
62 | .DS_Store
63 |
64 | # Yarn
65 | yarn-error.log
66 | .pnp/
67 | .pnp.js
68 | # Yarn Integrity file
69 | .yarn-integrity
70 | dist
71 |
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | src
2 | .gitignore
3 | rollup.config.jss
4 | !dist
5 | scripts
6 | .vscode
7 | yarn*
8 | tsconfig.json
9 | rollup*
10 |
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "typescript.tsdk": "node_modules/typescript/lib"
3 | }
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | ## Contributing to a TypeScript Playground Plugin
2 |
3 | ## Contributing
4 |
5 | You can use `yarn start` to set up both a copy of Rollup to generate the JS, and Serve to host it.
6 |
7 | ```sh
8 | yarn start
9 | ```
10 |
11 | Then set up the TypeScript playground to connect to a dev plugin at `http://localhost:5000/index.js`.
12 |
13 | #### Plugin API
14 |
15 | The plugin API is documented in the [interface PlaygroundPlugin in `./src/vendor/playground.d.ts`](src/vendor/playground.d.ts)
16 |
17 | Roughly:
18 |
19 | - There are a set of mounting and un-mounting functions which you can use to handle your UI in the sidebar
20 | - There are `modelChanged` methods, which are shortcuts to knowing when the code in monaco editor has changed
21 |
22 | ### Sandbox
23 |
24 | The plugins are passed copies of the TypeScript sandbox, which is a high level API wrapper to the [`monaco-editor`](https://microsoft.github.io/monaco-editor/). You can learn more about the sandbox on [the TypeScript website](http://www.typescriptlang.org/v2/dev/sandbox/
25 |
26 | #### Rollup
27 |
28 | [Rollup](https://rollupjs.org) is a JavaScript bundler, that will take all of the TypeScript + JavaScript code you reference and then create an AMD bundle for it all. AMD bundles are used in Monaco, TypeScript Sandbox and the Playground - so, this is used for consistency with the rest of the ecosystem.
29 |
30 | #### Serve
31 |
32 | [Serve](https://github.com/zeit/serve) is used to make a web-server for the dist folder.
33 |
34 | ## Deployment
35 |
36 | This module should be deployed to npm when you would like the world to see it, this may mean making your code handle a staging vs production environment (because the URLs will be different.)
37 |
38 | For example, this is how you can handle getting the URL for a CSS file which is included in your `dist` folder:
39 |
40 | ```ts
41 | const isDev = document.location.host.includes('localhost')
42 | const unpkgURL = 'https://unpkg.com/typescript-playground-presentation-mode@latest/dist/slideshow.css'
43 | const cssHref = isDev ? 'http://localhost:5000/slideshow.css' : unpkgURL
44 | ```
45 |
46 | ### Post-Deploy
47 |
48 | Once this is deployed, you can test it on the TypeScript playground by passing in the name of your plugin on npm to the custom plugin box. This is effectively your staging environment.
49 |
50 | Once you're happy and it's polished, you can apply to have it in the default plugin list.
51 |
52 | ## Support
53 |
54 | Ask questions either on the TypeScript Website issues](https://github.com/microsoft/TypeScript-Website/issues), or in the [TypeScript Community Discord](https://discord.gg/typescript) - in the TypeScript Website channel.
55 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## TypeScript Playground Plugin
2 |
3 | Lets you run [TSQuery](https://github.com/phenomnomnominal/tsquery) in realtime
4 |
5 |
6 |
7 | ## Running this plugin
8 |
9 | - Open up the TypeScript Playground
10 | - Go the "Options" in the sidebar
11 | - Look for "External Plugins"
12 | - Add "playground-plugin-tsquery"
13 | - Reload the browser
14 |
15 | Then it will show up as a tab in the sidebar.
16 |
17 | ## Contributing
18 |
19 | See [CONTRIBUTING.md](./CONTRIBUTING.md) for the full details, however, TLDR:
20 |
21 | ```sh
22 | git clone ...
23 | yarn install
24 | yarn start
25 | ```
26 |
27 | Then tick the box for starting plugin development inside the TypeScript Playground.
28 |
--------------------------------------------------------------------------------
/images/img.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/orta/playground-plugin-tsquery/12488c843c7c4e48c1d2b45d6ec0d578d847c2a8/images/img.png
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "playground-plugin-tsquery",
3 | "version": "1.0.0",
4 | "main": "dist/index.js",
5 | "license": "MIT",
6 | "keywords": [
7 | "playground-plugin"
8 | ],
9 | "scripts": {
10 | "build": "rollup -c rollup.config.js;",
11 | "compile": "tsc",
12 | "bootstrap": "node scripts/getDTS.js",
13 | "start": "concurrently -p \"[{name}]\" -n \"ROLLUP,SITE\" -c \"bgBlue.bold,bgMagenta.bold\" \"yarn rollup -c rollup.config.js --watch\" \"yarn serve dist\"",
14 | "prepublish": "yarn build",
15 | "postinstall": "yarn bootstrap; yarn build"
16 | },
17 | "devDependencies": {
18 | "@rollup/plugin-commonjs": "^11.0.2",
19 | "@rollup/plugin-json": "^4.0.2",
20 | "@rollup/plugin-node-resolve": "^7.1.0",
21 | "@rollup/plugin-typescript": "^3.0.0",
22 | "concurrently": "^5.1.0",
23 | "monaco-editor": "^0.19.3",
24 | "node-fetch": "^2.6.0",
25 | "rollup": "^1.31.0",
26 | "rollup-plugin-external-globals": "^0.5.0",
27 | "rollup-plugin-ignore": "^1.0.5",
28 | "serve": "^11.3.0",
29 | "typescript": "latest"
30 | },
31 | "dependencies": {
32 | "@phenomnomnominal/tsquery": "^4.0.0",
33 | "tslib": "^1.10.0"
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/rollup.config.js:
--------------------------------------------------------------------------------
1 | import typescript from "@rollup/plugin-typescript";
2 | import node from "@rollup/plugin-node-resolve";
3 | import commonjs from "@rollup/plugin-commonjs";
4 | import json from "@rollup/plugin-json";
5 | import ignore from "rollup-plugin-ignore";
6 |
7 |
8 | // You can have more root bundles by extending this array
9 | const rootFiles = ["index.ts"];
10 | import externalGlobals from "rollup-plugin-external-globals";
11 |
12 | export default rootFiles.map(name => {
13 | /** @type { import("rollup").RollupOptions } */
14 | const options = {
15 | input: `src/${name}`,
16 | external: ['typescript', 'fs', 'path'],
17 | output: {
18 | paths: {
19 | "typescript":"typescript-sandbox/index",
20 | "fs":"typescript-sandbox/index",
21 | "path":"typescript-sandbox/index",
22 | },
23 | name,
24 | dir: "dist",
25 | format: "amd"
26 | },
27 | plugins: [typescript({ tsconfig: "tsconfig.json" }), externalGlobals({ typescript: "window.ts" }), ignore(["path", "fs"]), commonjs(), node(), json()]
28 | };
29 |
30 | return options;
31 | });
32 |
--------------------------------------------------------------------------------
/scripts/getDTS.js:
--------------------------------------------------------------------------------
1 | // @ts-check
2 |
3 | // Grab the DTS files from the TypeScript website
4 | // then do a bit of string manipulation in order to make it
5 | // compile without _all_ of the dependencies
6 |
7 | const nodeFetch = require("node-fetch").default;
8 | const { writeFileSync, existsSync, mkdirSync } = require("fs");
9 | const { join } = require("path");
10 |
11 | const getFileAndStoreLocally = async (url, path, editFunc) => {
12 | const editingFunc = editFunc ? editFunc : text => text;
13 | const packageJSON = await nodeFetch(url);
14 | const contents = await packageJSON.text();
15 | writeFileSync(join(__dirname, "..", path), editingFunc(contents), "utf8");
16 | };
17 |
18 | const go = async () => {
19 | const vendor = join("src", "vendor");
20 | if (!existsSync(vendor)) {
21 | mkdirSync(vendor);
22 | }
23 |
24 | // const host = 'https://www.typescriptlang.org/v2'
25 | const host = "http://localhost:8000";
26 |
27 | await getFileAndStoreLocally(host + "/js/sandbox/tsWorker.d.ts", join(vendor, "tsWorker.d.ts"));
28 |
29 | await getFileAndStoreLocally(host + "/js/playground/pluginUtils.d.ts", join(vendor, "pluginUtils.d.ts"));
30 |
31 | await getFileAndStoreLocally(
32 | host + "/js/sandbox/vendor/typescript-vfs.d.ts",
33 | join(vendor, "typescript-vfs.d.ts"),
34 | text => {
35 | const removeImports = text.replace('/// ', "");
36 | const removedLZ = removeImports.replace('import("lz-string").LZStringStatic', "any");
37 | return removedLZ;
38 | }
39 | );
40 |
41 | await getFileAndStoreLocally(host + "/js/sandbox/index.d.ts", join(vendor, "sandbox.d.ts"), text => {
42 | const removeImports = text.replace(/^import/g, "// import").replace(/\nimport/g, "]\n// import");
43 | const replaceTSVFS = removeImports.replace(
44 | "// import * as tsvfs from './vendor/typescript-vfs'",
45 | "\nimport * as tsvfs from './typescript-vfs'"
46 | );
47 | const removedLZ = replaceTSVFS.replace("lzstring: typeof lzstring", "// lzstring: typeof lzstring");
48 | const addedTsWorkerImport = 'import { TypeScriptWorker } from "./tsWorker";' + removedLZ;
49 | return addedTsWorkerImport;
50 | });
51 |
52 | await getFileAndStoreLocally(host + "/js/playground/index.d.ts", join(vendor, "/playground.d.ts"), text => {
53 | const replaceSandbox = text.replace(/typescript-sandbox/g, "./sandbox");
54 | const replaceTSVFS = replaceSandbox.replace(
55 | /typescriptlang-org\/static\/js\/sandbox\/vendor\/typescript-vfs/g,
56 | "./typescript-vfs"
57 | );
58 | const removedLZ = replaceTSVFS.replace("lzstring: typeof", "// lzstring: typeof");
59 | const removedWorker = removedLZ.replace("getWorkerProcess", "// getWorkerProcess");
60 | const removedUI = removedWorker.replace("ui:", "// ui:");
61 | return removedUI;
62 | });
63 | };
64 |
65 | go();
66 |
--------------------------------------------------------------------------------
/src/index.ts:
--------------------------------------------------------------------------------
1 | import { tsquery } from "@phenomnomnominal/tsquery";
2 | import type { editor } from "monaco-editor";
3 | import type { Node } from "typescript";
4 | import {PlaygroundPlugin, PluginUtils} from "./vendor/playground"
5 |
6 | const pluginCreator = (utils: PluginUtils) => {
7 |
8 | let astVersion = -1
9 | let ast:Node = undefined
10 |
11 | const plugin: PlaygroundPlugin = {
12 | id: "tsquery",
13 | displayName: "TSQuery",
14 |
15 | didMount: (sandbox, container) => {
16 | // @ts-ignore - so people can use the console to do tsquery also
17 | window.tsquery = tsquery;
18 | console.log('New global:')
19 | // @ts-ignore
20 | console.log('\twindow.tsquery', window.tsquery)
21 |
22 | // Add some info saying how to use it
23 | const p = (str: string) => utils.el(str, "p", container);
24 | p(`Use the textbox below to make a query, queries happen as you type. You can query using any TypeScript AST SyntaxKind type`);
25 |
26 | // Inject a form with an input to the container
27 | const outerQueryForm = createQueryInputForm(sandbox);
28 | container.appendChild(outerQueryForm);
29 |
30 | // Create some elements to put the results in
31 | const resultMeta = document.createElement("p")
32 | resultMeta.id = "query-results-meta"
33 | container.appendChild(resultMeta)
34 |
35 | const results = document.createElement("div");
36 | results.id = "query-results";
37 | container.appendChild(results);
38 |
39 | // Because the query is stored between sessions, then you could
40 | // have something we can run on launch
41 | const model = sandbox.editor.getModel()
42 | runQuery(sandbox, model)
43 | },
44 |
45 | // When we get told about an update to the monaco model then update our query
46 | modelChangedDebounce: async (sandbox, model) => {
47 | runQuery(sandbox, model)
48 | },
49 | };
50 |
51 | /** Runs the input against the current AST */
52 | const runQuery = async (sandbox, model: editor.ITextModel) => {
53 | // Empty the results section
54 | const results = document.getElementById("query-results");
55 | const resultsMeta = document.getElementById("query-results-meta");
56 | resultsMeta.textContent = ""
57 |
58 | // Just being safe
59 | if (!results) return;
60 | while (results.firstChild) {
61 | results.removeChild(results.firstChild);
62 | }
63 |
64 | // NOOP when we don't need to do something
65 | const query = localStorage.getItem("playground-tsquery-current-query");
66 | if (!query) return;
67 |
68 | // If the model hasn't changed (getVersionId increments on text changes)
69 | // then we don't need to get a new copy of the AST to query against
70 | if (model.getVersionId() !== astVersion) {
71 | ast = await sandbox.getAST();
72 | astVersion = model.getVersionId()
73 | }
74 |
75 | // The API throws when the query is invalid, so
76 | // use a try catch to give an error message
77 | let queryResults: Node[]
78 |
79 | try {
80 | queryResults = tsquery(ast, query);
81 | } catch (error) {
82 | console.log(error)
83 | resultsMeta.classList.add("err")
84 | resultsMeta.textContent = error.message
85 | }
86 | // Show resukts
87 | if (queryResults) {
88 | resultsMeta.classList.remove("err")
89 |
90 | const suffix = queryResults.length == 1 ? "result" : "results"
91 | resultsMeta.textContent = `Got ${queryResults.length} ${suffix}`
92 |
93 | queryResults.forEach(node => {
94 | // Use the utils version of `createASTTree` so that this plugin gets
95 | // free upgrades as it becomes good.
96 | const div = utils.createASTTree(node);
97 | results.append(div)
98 | });
99 | }
100 | }
101 |
102 | /** Creates a form with a textbox which runs the query */
103 | const createQueryInputForm = (sandbox) => {
104 | const form = document.createElement("form")
105 |
106 | const textbox = document.createElement("input")
107 | textbox.id = "tsquery-input"
108 | textbox.placeholder = `Identifier[name="Animal"]`
109 | textbox.autocomplete ="off"
110 | textbox.autocapitalize = "off"
111 | textbox.spellcheck = false
112 | // @ts-ignore
113 | textbox.autocorrect = "off"
114 |
115 | const storedQuery = localStorage.getItem("playground-tsquery-current-query")
116 | textbox.value = storedQuery
117 |
118 | const updateState = ({ enable }) => {
119 | if (enable) {
120 | textbox.classList.add("good")
121 | } else {
122 | textbox.classList.remove("good")
123 | }
124 | };
125 |
126 | const textUpdate = e => {
127 | const href = e.target.value.trim()
128 | localStorage.setItem("playground-tsquery-current-query", href)
129 |
130 | console.log("text")
131 | const model = sandbox.editor.getModel()
132 | runQuery(sandbox, model)
133 | };
134 |
135 | textbox.style.width = "90%"
136 | textbox.style.height = "2rem"
137 | textbox.addEventListener("input", textUpdate)
138 |
139 | // Suppress the enter key
140 | textbox.onkeydown = (evt: KeyboardEvent) => {
141 | if (evt.keyCode == 13) return false
142 | }
143 |
144 | form.appendChild(textbox)
145 | updateState({ enable: textbox.textContent && textbox.textContent.length })
146 | return form
147 | };
148 |
149 | return plugin
150 | }
151 |
152 | export default pluginCreator;
153 |
--------------------------------------------------------------------------------
/src/vendor/playground.d.ts:
--------------------------------------------------------------------------------
1 | declare type Sandbox = import('./sandbox').Sandbox;
2 | export { PluginUtils } from './pluginUtils';
3 | export declare type PluginFactory = {
4 | (i: (key: string, components?: any) => string): PlaygroundPlugin;
5 | };
6 | /** The interface of all sidebar plugins */
7 | export interface PlaygroundPlugin {
8 | /** Not public facing, but used by the playground to uniquely identify plugins */
9 | id: string;
10 | /** To show in the tabs */
11 | displayName: string;
12 | /** Should this plugin be selected when the plugin is first loaded? Let's you check for query vars etc to load a particular plugin */
13 | shouldBeSelected?: () => boolean;
14 | /** Before we show the tab, use this to set up your HTML - it will all be removed by the playground when someone navigates off the tab */
15 | willMount?: (sandbox: Sandbox, container: HTMLDivElement) => void;
16 | /** After we show the tab */
17 | didMount?: (sandbox: Sandbox, container: HTMLDivElement) => void;
18 | /** Model changes while this plugin is actively selected */
19 | modelChanged?: (sandbox: Sandbox, model: import('monaco-editor').editor.ITextModel) => void;
20 | /** Delayed model changes while this plugin is actively selected, useful when you are working with the TS API because it won't run on every keypress */
21 | modelChangedDebounce?: (sandbox: Sandbox, model: import('monaco-editor').editor.ITextModel) => void;
22 | /** Before we remove the tab */
23 | willUnmount?: (sandbox: Sandbox, container: HTMLDivElement) => void;
24 | /** After we remove the tab */
25 | didUnmount?: (sandbox: Sandbox, container: HTMLDivElement) => void;
26 | }
27 | interface PlaygroundConfig {
28 | lang: string;
29 | prefix: string;
30 | }
31 | export declare const setupPlayground: (sandbox: {
32 | config: {
33 | text: string;
34 | useJavaScript: boolean;
35 | compilerOptions: import("monaco-editor").languages.typescript.CompilerOptions;
36 | monacoSettings?: import("monaco-editor").editor.IEditorOptions | undefined;
37 | acquireTypes: boolean;
38 | supportTwoslashCompilerOptions: boolean;
39 | suppressAutomaticallyGettingDefaultText?: true | undefined;
40 | suppressAutomaticallyGettingCompilerFlags?: true | undefined;
41 | logger: {
42 | log: (...args: any[]) => void;
43 | error: (...args: any[]) => void;
44 | };
45 | domID: string;
46 | };
47 | supportedVersions: readonly ["3.7.5", "3.6.3", "3.5.1", "3.3.3", "3.1.6", "3.0.1", "2.8.1", "2.7.2", "2.4.1"];
48 | editor: import("monaco-editor").editor.IStandaloneCodeEditor;
49 | language: string;
50 | monaco: typeof import("monaco-editor");
51 | // getWorkerProcess: () => Promise;
52 | tsvfs: typeof import("./typescript-vfs");
53 | getEmitResult: () => Promise;
54 | getRunnableJS: () => Promise;
55 | getDTSForCode: () => Promise;
56 | getDomNode: () => HTMLElement;
57 | getModel: () => import("monaco-editor").editor.ITextModel;
58 | getText: () => string;
59 | setText: (text: string) => void;
60 | getAST: () => Promise;
61 | ts: typeof import("typescript");
62 | createTSProgram: () => Promise;
63 | compilerDefaults: import("monaco-editor").languages.typescript.CompilerOptions;
64 | getCompilerOptions: () => import("monaco-editor").languages.typescript.CompilerOptions;
65 | setCompilerSettings: (opts: import("monaco-editor").languages.typescript.CompilerOptions) => void;
66 | updateCompilerSetting: (key: string | number, value: any) => void;
67 | updateCompilerSettings: (opts: import("monaco-editor").languages.typescript.CompilerOptions) => void;
68 | setDidUpdateCompilerSettings: (func: (opts: import("monaco-editor").languages.typescript.CompilerOptions) => void) => void;
69 | // lzstring: typeof import("typescriptlang-org/static/js/sandbox/vendor/lzstring.min");
70 | getURLQueryWithCompilerOptions: (sandbox: any, paramOverrides?: any) => string;
71 | getTwoSlashComplierOptions: (code: string) => any;
72 | languageServiceDefaults: import("monaco-editor").languages.typescript.LanguageServiceDefaults;
73 | }, monaco: typeof import("monaco-editor"), config: PlaygroundConfig, i: (key: string) => string) => {
74 | exporter: {
75 | openProjectInStackBlitz: () => void;
76 | openProjectInCodeSandbox: () => void;
77 | reportIssue: () => Promise;
78 | copyAsMarkdownIssue: () => Promise;
79 | copyForChat: () => void;
80 | copyForChatWithPreview: () => void;
81 | openInTSAST: () => void;
82 | };
83 | // ui: import("./createUI").UI;
84 | registerPlugin: (plugin: PlaygroundPlugin) => void;
85 | };
86 | export declare type Playground = ReturnType;
87 |
--------------------------------------------------------------------------------
/src/vendor/pluginUtils.d.ts:
--------------------------------------------------------------------------------
1 | import type { Node } from "typescript";
2 | /** Creates a set of util functions which is exposed to Plugins to make it easier to build consistent UIs */
3 | export declare const createUtils: (sandbox: any) => {
4 | /** Use this to make a few dumb element generation funcs */
5 | el: (str: string, el: string, container: Element) => void;
6 | /** Get a relative URL for something in your dist folder depending on if you're in dev mode or not */
7 | requireURL: (path: string) => string;
8 | /** Returns a div which has an interactive AST a TypeScript AST by passing in the root node */
9 | createASTTree: (node: Node) => HTMLDivElement;
10 | };
11 | export declare type PluginUtils = ReturnType;
12 |
--------------------------------------------------------------------------------
/src/vendor/sandbox.d.ts:
--------------------------------------------------------------------------------
1 | import { TypeScriptWorker } from "./tsWorker";// import { TypeScriptWorker } from './tsWorker';]
2 | // import lzstring from './vendor/lzstring.min';]
3 |
4 | import * as tsvfs from './typescript-vfs';
5 | declare type CompilerOptions = import('monaco-editor').languages.typescript.CompilerOptions;
6 | /**
7 | * These are settings for the playground which are the equivalent to props in React
8 | * any changes to it should require a new setup of the playground
9 | */
10 | export declare type PlaygroundConfig = {
11 | /** The default source code for the playground */
12 | text: string;
13 | /** Should it run the ts or js IDE services */
14 | useJavaScript: boolean;
15 | /** Compiler options which are automatically just forwarded on */
16 | compilerOptions: CompilerOptions;
17 | /** Optional monaco settings overrides */
18 | monacoSettings?: import('monaco-editor').editor.IEditorOptions;
19 | /** Acquire types via type acquisition */
20 | acquireTypes: boolean;
21 | /** Support twoslash compiler options */
22 | supportTwoslashCompilerOptions: boolean;
23 | /** Get the text via query params and local storage, useful when the editor is the main experience */
24 | suppressAutomaticallyGettingDefaultText?: true;
25 | /** Suppress setting compiler options from the compiler flags from query params */
26 | suppressAutomaticallyGettingCompilerFlags?: true;
27 | /** Logging system */
28 | logger: {
29 | log: (...args: any[]) => void;
30 | error: (...args: any[]) => void;
31 | };
32 | } & ({
33 | domID: string;
34 | } | {
35 | elementToAppend: HTMLElement;
36 | });
37 | /** The default settings which we apply a partial over */
38 | export declare function defaultPlaygroundSettings(): {
39 | /** The default source code for the playground */
40 | text: string;
41 | /** Should it run the ts or js IDE services */
42 | useJavaScript: boolean;
43 | /** Compiler options which are automatically just forwarded on */
44 | compilerOptions: import("monaco-editor").languages.typescript.CompilerOptions;
45 | /** Optional monaco settings overrides */
46 | monacoSettings?: import("monaco-editor").editor.IEditorOptions | undefined;
47 | /** Acquire types via type acquisition */
48 | acquireTypes: boolean;
49 | /** Support twoslash compiler options */
50 | supportTwoslashCompilerOptions: boolean;
51 | /** Get the text via query params and local storage, useful when the editor is the main experience */
52 | suppressAutomaticallyGettingDefaultText?: true | undefined;
53 | /** Suppress setting compiler options from the compiler flags from query params */
54 | suppressAutomaticallyGettingCompilerFlags?: true | undefined;
55 | /** Logging system */
56 | logger: {
57 | log: (...args: any[]) => void;
58 | error: (...args: any[]) => void;
59 | };
60 | } & {
61 | domID: string;
62 | };
63 | /** Creates a sandbox editor, and returns a set of useful functions and the editor */
64 | export declare const createTypeScriptSandbox: (partialConfig: Partial<{
65 | /** The default source code for the playground */
66 | text: string;
67 | /** Should it run the ts or js IDE services */
68 | useJavaScript: boolean;
69 | /** Compiler options which are automatically just forwarded on */
70 | compilerOptions: import("monaco-editor").languages.typescript.CompilerOptions;
71 | /** Optional monaco settings overrides */
72 | monacoSettings?: import("monaco-editor").editor.IEditorOptions | undefined;
73 | /** Acquire types via type acquisition */
74 | acquireTypes: boolean;
75 | /** Support twoslash compiler options */
76 | supportTwoslashCompilerOptions: boolean;
77 | /** Get the text via query params and local storage, useful when the editor is the main experience */
78 | suppressAutomaticallyGettingDefaultText?: true | undefined;
79 | /** Suppress setting compiler options from the compiler flags from query params */
80 | suppressAutomaticallyGettingCompilerFlags?: true | undefined;
81 | /** Logging system */
82 | logger: {
83 | log: (...args: any[]) => void;
84 | error: (...args: any[]) => void;
85 | };
86 | } & {
87 | domID: string;
88 | }> | Partial<{
89 | /** The default source code for the playground */
90 | text: string;
91 | /** Should it run the ts or js IDE services */
92 | useJavaScript: boolean;
93 | /** Compiler options which are automatically just forwarded on */
94 | compilerOptions: import("monaco-editor").languages.typescript.CompilerOptions;
95 | /** Optional monaco settings overrides */
96 | monacoSettings?: import("monaco-editor").editor.IEditorOptions | undefined;
97 | /** Acquire types via type acquisition */
98 | acquireTypes: boolean;
99 | /** Support twoslash compiler options */
100 | supportTwoslashCompilerOptions: boolean;
101 | /** Get the text via query params and local storage, useful when the editor is the main experience */
102 | suppressAutomaticallyGettingDefaultText?: true | undefined;
103 | /** Suppress setting compiler options from the compiler flags from query params */
104 | suppressAutomaticallyGettingCompilerFlags?: true | undefined;
105 | /** Logging system */
106 | logger: {
107 | log: (...args: any[]) => void;
108 | error: (...args: any[]) => void;
109 | };
110 | } & {
111 | elementToAppend: HTMLElement;
112 | }>, monaco: typeof import("monaco-editor"), ts: typeof import("typescript")) => {
113 | /** The same config you passed in */
114 | config: {
115 | text: string;
116 | useJavaScript: boolean;
117 | compilerOptions: import("monaco-editor").languages.typescript.CompilerOptions;
118 | monacoSettings?: import("monaco-editor").editor.IEditorOptions | undefined;
119 | acquireTypes: boolean;
120 | supportTwoslashCompilerOptions: boolean;
121 | suppressAutomaticallyGettingDefaultText?: true | undefined;
122 | suppressAutomaticallyGettingCompilerFlags?: true | undefined;
123 | logger: {
124 | log: (...args: any[]) => void;
125 | error: (...args: any[]) => void;
126 | };
127 | domID: string;
128 | };
129 | /** A list of TypeScript versions you can use with the TypeScript sandbox */
130 | supportedVersions: readonly ["3.7.5", "3.6.3", "3.5.1", "3.3.3", "3.1.6", "3.0.1", "2.8.1", "2.7.2", "2.4.1"];
131 | /** The monaco editor instance */
132 | editor: import("monaco-editor").editor.IStandaloneCodeEditor;
133 | /** Either "typescript" or "javascript" depending on your config */
134 | language: string;
135 | /** The outer monaco module, the result of require("monaco-editor") */
136 | monaco: typeof import("monaco-editor");
137 | /** Gets a monaco-typescript worker, this will give you access to a language server. Note: prefer this for language server work because it happens on a webworker . */
138 | getWorkerProcess: () => Promise;
139 | /** A copy of require("typescript-vfs") this can be used to quickly set up an in-memory compiler runs for ASTs, or to get complex language server results (anything above has to be serialized when passed)*/
140 | tsvfs: typeof tsvfs;
141 | /** Get all the different emitted files after TypeScript is run */
142 | getEmitResult: () => Promise;
143 | /** Gets just the JavaScript for your sandbox, will transpile if in TS only */
144 | getRunnableJS: () => Promise;
145 | /** Gets the DTS output of the main code in the editor */
146 | getDTSForCode: () => Promise;
147 | /** The monaco-editor dom node, used for showing/hiding the editor */
148 | getDomNode: () => HTMLElement;
149 | /** The model is an object which monaco uses to keep track of text in the editor. Use this to directly modify the text in the editor */
150 | getModel: () => import("monaco-editor").editor.ITextModel;
151 | /** Gets the text of the main model, which is the text in the editor */
152 | getText: () => string;
153 | /** Shortcut for setting the model's text content which would update the editor */
154 | setText: (text: string) => void;
155 | /** WIP: Gets the AST of the current text */
156 | getAST: () => Promise;
157 | /** The module you get from require("typescript") */
158 | ts: typeof import("typescript");
159 | /** Create a new Program, a TypeScript data model which represents the entire project.
160 | *
161 | * The first time this is called it has to download all the DTS files which is needed for an exact compiler run. Which
162 | * at max is about 1.5MB - after that subsequent downloads of dts lib files come from localStorage.
163 | *
164 | * You probably want
165 | */
166 | createTSProgram: () => Promise;
167 | /** The Sandbox's default compiler options */
168 | compilerDefaults: import("monaco-editor").languages.typescript.CompilerOptions;
169 | /** The Sandbox's current compiler options */
170 | getCompilerOptions: () => import("monaco-editor").languages.typescript.CompilerOptions;
171 | /** Replace the Sandbox's compiler options */
172 | setCompilerSettings: (opts: import("monaco-editor").languages.typescript.CompilerOptions) => void;
173 | /** Overwrite the Sandbox's compiler options */
174 | updateCompilerSetting: (key: string | number, value: any) => void;
175 | /** Update a single compiler option in the SAndbox */
176 | updateCompilerSettings: (opts: import("monaco-editor").languages.typescript.CompilerOptions) => void;
177 | /** A way to get callbacks when compiler settings have changed */
178 | setDidUpdateCompilerSettings: (func: (opts: import("monaco-editor").languages.typescript.CompilerOptions) => void) => void;
179 | /** A copy of lzstring, which is used to archive/unarchive code */
180 | // lzstring: typeof lzstring;
181 | /** Returns compiler options found in the params of the current page */
182 | getURLQueryWithCompilerOptions: (sandbox: any, paramOverrides?: any) => string;
183 | /** Returns compiler options in the source code using twoslash notation */
184 | getTwoSlashComplierOptions: (code: string) => any;
185 | /** Gets to the current monaco-language, this is how you talk to the background webworkers */
186 | languageServiceDefaults: import("monaco-editor").languages.typescript.LanguageServiceDefaults;
187 | };
188 | export declare type Sandbox = ReturnType;
189 | export {};
190 |
--------------------------------------------------------------------------------
/src/vendor/tsWorker.d.ts:
--------------------------------------------------------------------------------
1 | import ts from 'typescript';
2 | export declare class TypeScriptWorker implements ts.LanguageServiceHost {
3 | private _ctx;
4 | private _extraLibs;
5 | private _languageService;
6 | private _compilerOptions;
7 | constructor(ctx: any, createData: any);
8 | getCompilationSettings(): ts.CompilerOptions;
9 | getScriptFileNames(): string[];
10 | private _getModel;
11 | getScriptVersion(fileName: string): string;
12 | getScriptSnapshot(fileName: string): ts.IScriptSnapshot | undefined;
13 | getScriptKind?(fileName: string): ts.ScriptKind;
14 | getCurrentDirectory(): string;
15 | getDefaultLibFileName(options: ts.CompilerOptions): string;
16 | isDefaultLibFileName(fileName: string): boolean;
17 | private static clearFiles;
18 | getSyntacticDiagnostics(fileName: string): Promise;
19 | getSemanticDiagnostics(fileName: string): Promise;
20 | getSuggestionDiagnostics(fileName: string): Promise;
21 | getCompilerOptionsDiagnostics(fileName: string): Promise;
22 | getCompletionsAtPosition(fileName: string, position: number): Promise;
23 | getCompletionEntryDetails(fileName: string, position: number, entry: string): Promise;
24 | getSignatureHelpItems(fileName: string, position: number): Promise;
25 | getQuickInfoAtPosition(fileName: string, position: number): Promise;
26 | getOccurrencesAtPosition(fileName: string, position: number): Promise | undefined>;
27 | getDefinitionAtPosition(fileName: string, position: number): Promise | undefined>;
28 | getReferencesAtPosition(fileName: string, position: number): Promise;
29 | getNavigationBarItems(fileName: string): Promise;
30 | getFormattingEditsForDocument(fileName: string, options: ts.FormatCodeOptions): Promise;
31 | getFormattingEditsForRange(fileName: string, start: number, end: number, options: ts.FormatCodeOptions): Promise;
32 | getFormattingEditsAfterKeystroke(fileName: string, postion: number, ch: string, options: ts.FormatCodeOptions): Promise;
33 | findRenameLocations(fileName: string, positon: number, findInStrings: boolean, findInComments: boolean, providePrefixAndSuffixTextForRename: boolean): Promise;
34 | getRenameInfo(fileName: string, positon: number, options: ts.RenameInfoOptions): Promise;
35 | getEmitOutput(fileName: string): Promise;
36 | getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[], formatOptions: ts.FormatCodeOptions): Promise>;
37 | updateExtraLibs(extraLibs: IExtraLibs): void;
38 | }
39 | export interface IExtraLib {
40 | content: string;
41 | version: number;
42 | }
43 | export interface IExtraLibs {
44 | [path: string]: IExtraLib;
45 | }
46 |
--------------------------------------------------------------------------------
/src/vendor/typescript-vfs.d.ts:
--------------------------------------------------------------------------------
1 |
2 | declare type System = import('typescript').System;
3 | declare type CompilerOptions = import('typescript').CompilerOptions;
4 | declare type TS = typeof import('typescript');
5 | export interface VirtualTypeScriptEnvironment {
6 | sys: System;
7 | languageService: import('typescript').LanguageService;
8 | getSourceFile: (fileName: string) => import('typescript').SourceFile | undefined;
9 | createFile: (fileName: string, content: string) => void;
10 | updateFile: (fileName: string, content: string, replaceTextSpan?: import('typescript').TextSpan) => void;
11 | }
12 | /**
13 | * Makes a virtual copy of the TypeScript environment. This is the main API you want to be using with
14 | * typescript-vfs. A lot of the other exposed functions are used by this function to get set up.
15 | *
16 | * @param sys an object which conforms to the TS Sys (a shim over read/write access to the fs)
17 | * @param rootFiles a list of files which are considered inside the project
18 | * @param ts a copy pf the TypeScript module
19 | * @param compilerOptions the options for this compiler run
20 | */
21 | export declare function createVirtualTypeScriptEnvironment(sys: System, rootFiles: string[], ts: TS, compilerOptions?: CompilerOptions): VirtualTypeScriptEnvironment;
22 | /**
23 | * Grab the list of lib files for a particular target, will return a bit more than necessary (by including
24 | * the dom) but that's OK
25 | *
26 | * @param target The compiler settings target baseline
27 | * @param ts A copy of the TypeScript module
28 | */
29 | export declare const knownLibFilesForCompilerOptions: (compilerOptions: import("typescript").CompilerOptions, ts: typeof import("typescript")) => string[];
30 | /**
31 | * Sets up a Map with lib contents by grabbing the necessary files from
32 | * the local copy of typescript via the file system.
33 | */
34 | export declare const createDefaultMapFromNodeModules: (compilerOptions: import("typescript").CompilerOptions) => Map;
35 | /**
36 | * Create a virtual FS Map with the lib files from a particular TypeScript
37 | * version based on the target, Always includes dom ATM.
38 | *
39 | * @param options The compiler target, which dictates the libs to set up
40 | * @param version the versions of TypeScript which are supported
41 | * @param cache should the values be stored in local storage
42 | * @param ts a copy of the typescript import
43 | * @param lzstring an optional copy of the lz-string import
44 | * @param fetcher an optional replacement for the global fetch function (tests mainly)
45 | * @param storer an optional replacement for the localStorage global (tests mainly)
46 | */
47 | export declare const createDefaultMapFromCDN: (options: import("typescript").CompilerOptions, version: string, cache: boolean, ts: typeof import("typescript"), lzstring?: any | undefined, fetcher?: typeof fetch | undefined, storer?: Storage | undefined) => Promise