@typesol/cli 0.29.0 → 0.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,19 @@ codes, and says so here.
6
6
 
7
7
  ## Unreleased
8
8
 
9
+ ## 0.30.0 — 2026-10-30
10
+
11
+ Editor errors that follow you through a program, faster. The compiler's output is the same as 0.29.0 for every
12
+ program.
13
+
14
+ - Changed: `typesol/ts-plugin` shows the compiler's refusals in every file of a program (a helper or state file the
15
+ entry imports, not only the entry), for the unsaved text of every open file, underlining the whole construct.
16
+ - Changed: the plugin runs the compiler inside the editor's TypeScript server once it has loaded (a check takes
17
+ milliseconds instead of starting a process), and `typesol init` writes `.vscode/settings.json` so VS Code offers the
18
+ workspace's TypeScript, which loads the plugin.
19
+ - New: `typesol check --files` reads `{ "files": { "<path>": "<text>" } }` from stdin (unsaved buffers of any file);
20
+ `--json` diagnostics carry a `length`. The compiler's `generate(entry, { files })` takes the same overrides.
21
+
9
22
  ## 0.29.0 — 2026-10-30
10
23
 
11
24
  The remaining Anchor gaps: declarative constraints in Anchor's order, Anchor's unbounded `Vec` in Borsh accounts, and
package/README.md CHANGED
@@ -225,7 +225,7 @@ The full reference, with every type, check and built-in, is in [docs/language.md
225
225
  | `typesol cpi <idl.json>` | generate typed CPI helpers for another program |
226
226
  | `typesol client <idl.json>` | generate a typed TypeScript client from an Anchor IDL (`typesol build` writes one per program) |
227
227
  | `typesol port` | a TypeSOL skeleton of an Anchor program from its IDL, keeping discriminators and error codes |
228
- | `typesol/ts-plugin` | the compiler's errors in the editor as you type ([docs/cli.md](docs/cli.md#editor)) |
228
+ | `typesol/ts-plugin` | the compiler's errors in the editor as you type, in every file of a program ([docs/cli.md](docs/cli.md#editor)) |
229
229
  | `typesol verify` | rebuild from source and compare with the program and IDL on chain (or a dumped `.so`) |
230
230
  | `typesol profile` | compute units per TypeScript line, from a `--profile` build's logs |
231
231
  | `typesol emit-c` | print the generated C |
package/dist/cli.js CHANGED
@@ -5,7 +5,6 @@ import os from "node:os";
5
5
  import path from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { parseArgs } from "node:util";
8
- import ts from "typescript";
9
8
  import { build, CompileError, COMPILER_VERSION, generate, SBPF_VERSIONS, verifyBinary } from "./compiler/index.js";
10
9
  import { generateCpi } from "./tools/cpigen.js";
11
10
  import { generatePort } from "./tools/portgen.js";
@@ -44,7 +43,7 @@ const COMMANDS = {
44
43
  init: {
45
44
  usage: "typesol init [<dir>] [--name <program>] [--template counter|vault|escrow]",
46
45
  help: [
47
- "Create a project: typesol.json, programs/<name>.ts, tests/<name>.test.ts (LiteSVM), package.json, tsconfig.json, .gitignore.",
46
+ "Create a project: typesol.json, programs/<name>.ts, tests/<name>.test.ts (LiteSVM), package.json, tsconfig.json, .gitignore, .vscode/settings.json (editor errors).",
48
47
  "Refuses to overwrite files. <name> must be snake_case (default: derived from <dir>).",
49
48
  "--template counter a PDA counter per user (default)",
50
49
  "--template vault a SOL vault at a PDA: deposit, withdraw above rent, close",
@@ -132,20 +131,27 @@ const COMMANDS = {
132
131
  },
133
132
  },
134
133
  check: {
135
- usage: "typesol check <program.ts> [--json] [--stdin]",
134
+ usage: "typesol check <program.ts> [--json] [--stdin | --files]",
136
135
  help: [
137
136
  "Typecheck and validate the TypeSOL subset without building.",
138
137
  "--json print { ok, diagnostics: [{ file, line, column, message }] } (exit 1 when there are diagnostics)",
139
138
  "--stdin read <program.ts>'s text from stdin instead of the file (an editor's unsaved buffer); its imports are read from disk",
139
+ '--files read { "files": { "<absolute path>": "<text>", … } } from stdin: those files\' texts instead of the disk (unsaved buffers)',
140
140
  ].join("\n "),
141
- options: { json: { type: "boolean" }, stdin: { type: "boolean" } },
141
+ options: { json: { type: "boolean" }, stdin: { type: "boolean" }, files: { type: "boolean" } },
142
142
  run(v, args) {
143
143
  const file = path.resolve(one(args, "<program.ts>"));
144
- const restore = v.stdin ? overrideFile(file, readFileSync(0, "utf8")) : undefined;
144
+ let files;
145
+ if (v.stdin)
146
+ files = new Map([[file, readFileSync(0, "utf8")]]);
147
+ else if (v.files) {
148
+ const given = JSON.parse(readFileSync(0, "utf8")).files ?? {};
149
+ files = new Map(Object.entries(given).map(([p, t]) => [path.resolve(p), t]));
150
+ }
145
151
  try {
146
- if (!v.stdin)
152
+ if (!files?.has(file))
147
153
  mustExist(file);
148
- const { model } = generate(file);
154
+ const { model } = generate(file, { files });
149
155
  if (v.json)
150
156
  log(JSON.stringify({ ok: true, diagnostics: [] }));
151
157
  else
@@ -158,9 +164,6 @@ const COMMANDS = {
158
164
  log(JSON.stringify({ ok: false, diagnostics: e.diagnostics }));
159
165
  return 1;
160
166
  }
161
- finally {
162
- restore?.();
163
- }
164
167
  },
165
168
  },
166
169
  "emit-c": {
@@ -517,16 +520,6 @@ function readJson(file) {
517
520
  }
518
521
  }
519
522
  /** Make the compiler read `text` for `file` (instead of the disk) until the returned function is called. */
520
- function overrideFile(file, text) {
521
- const sys = ts.sys;
522
- const { readFile, fileExists } = sys;
523
- sys.readFile = (p, enc) => (path.resolve(p) === file ? text : readFile.call(sys, p, enc));
524
- sys.fileExists = (p) => path.resolve(p) === file || fileExists.call(sys, p);
525
- return () => {
526
- sys.readFile = readFile;
527
- sys.fileExists = fileExists;
528
- };
529
- }
530
523
  /** json_rpc_url / keypair_path from a Solana CLI config (the given file, or the CLI's default one). */
531
524
  function solanaConfig(file) {
532
525
  const cfg = readSolanaConfig(file);
@@ -47,9 +47,11 @@ export interface TypeScope {
47
47
  }
48
48
  export declare function snakeCase(name: string): string;
49
49
  export declare function discriminator(preimage: string): number[];
50
+ /** Source text by absolute path: an editor's unsaved buffers, read instead of the files on disk. */
51
+ export type SourceOverrides = ReadonlyMap<string, string>;
50
52
  /** Resolve a relative import to a `.ts` file next to `from`, or undefined. */
51
53
  export declare function resolveRelative(from: string, spec: string): string | undefined;
52
- export declare function analyze(entry: string): Analysis;
54
+ export declare function analyze(entry: string, files?: SourceOverrides): Analysis;
53
55
  /**
54
56
  * Instruction-argument types beyond scalars: a fixed-size struct (`p: Point`), `FixedArray<T, N>`, or
55
57
  * `Vec<Struct>`. They are Borsh-identical to TypeSOL's fixed layouts, so they are copied as is and validated.
@@ -145,7 +145,12 @@ export function discriminator(preimage) {
145
145
  return [...createHash("sha256").update(preimage).digest().subarray(0, 8)];
146
146
  }
147
147
  /** Run the TypeScript checker over the entry file with `typesol` mapped to our declarations. */
148
- function typecheck(entry) {
148
+ /**
149
+ * Library declarations (TypeScript's lib files, typesol.d.ts) parsed once per process: an editor checks the same
150
+ * program on every keystroke, and these never change.
151
+ */
152
+ const libSourceFiles = new Map();
153
+ function typecheck(entry, files) {
149
154
  const options = {
150
155
  strict: true,
151
156
  noEmit: true,
@@ -157,7 +162,30 @@ function typecheck(entry) {
157
162
  paths: { typesol: [LIB_PATH] },
158
163
  skipLibCheck: true,
159
164
  };
160
- const program = ts.createProgram([entry], options);
165
+ const host = ts.createCompilerHost(options);
166
+ const getSourceFile = host.getSourceFile.bind(host);
167
+ host.getSourceFile = (fileName, language, onError, shouldCreate) => {
168
+ const text = files?.get(path.resolve(fileName));
169
+ if (text !== undefined)
170
+ return ts.createSourceFile(fileName, text, language, true);
171
+ const lib = fileName.endsWith(".d.ts") && (path.resolve(fileName) === LIB_PATH || fileName.includes(`${path.sep}typescript${path.sep}lib${path.sep}`));
172
+ if (!lib)
173
+ return getSourceFile(fileName, language, onError, shouldCreate);
174
+ let sf = libSourceFiles.get(fileName);
175
+ if (!sf) {
176
+ sf = getSourceFile(fileName, language, onError, shouldCreate);
177
+ if (sf)
178
+ libSourceFiles.set(fileName, sf);
179
+ }
180
+ return sf;
181
+ };
182
+ if (files) {
183
+ const readFile = host.readFile.bind(host);
184
+ const fileExists = host.fileExists.bind(host);
185
+ host.readFile = (f) => files.get(path.resolve(f)) ?? readFile(f);
186
+ host.fileExists = (f) => files.has(path.resolve(f)) || fileExists(f);
187
+ }
188
+ const program = ts.createProgram([entry], options, host);
161
189
  const sourceFile = program.getSourceFile(entry);
162
190
  if (!sourceFile)
163
191
  throw new CompileError([{ file: entry, line: 1, column: 1, message: "cannot read source file" }]);
@@ -170,7 +198,7 @@ function typecheck(entry) {
170
198
  if (!d.file || d.start === undefined)
171
199
  return { file: entry, line: 1, column: 1, message };
172
200
  const { line, character } = d.file.getLineAndCharacterOfPosition(d.start);
173
- return { file: d.file.fileName, line: line + 1, column: character + 1, message };
201
+ return { file: d.file.fileName, line: line + 1, column: character + 1, message, length: d.length };
174
202
  });
175
203
  throw new CompileError(diagnostics);
176
204
  }
@@ -190,14 +218,14 @@ export function resolveRelative(from, spec) {
190
218
  * Reject foreign imports before typechecking so the user sees why, not "cannot find module".
191
219
  * Follows relative imports so every file of the program is checked.
192
220
  */
193
- function checkImports(entry) {
221
+ function checkImports(entry, files) {
194
222
  const reporter = new Reporter();
195
223
  const seen = new Set();
196
224
  const visit = (file) => {
197
225
  if (seen.has(file))
198
226
  return;
199
227
  seen.add(file);
200
- const text = ts.sys.readFile(file);
228
+ const text = files?.get(file) ?? ts.sys.readFile(file);
201
229
  if (text === undefined)
202
230
  throw new CompileError([{ file, line: 1, column: 1, message: "cannot read source file" }]);
203
231
  const sf = ts.createSourceFile(file, text, ts.ScriptTarget.ES2022, true);
@@ -241,10 +269,10 @@ function programFiles(program, entry) {
241
269
  visit(entry);
242
270
  return order;
243
271
  }
244
- export function analyze(entry) {
272
+ export function analyze(entry, files) {
245
273
  const entryPath = path.resolve(entry);
246
- checkImports(entryPath);
247
- const { program, sourceFile } = typecheck(entryPath);
274
+ checkImports(entryPath, files);
275
+ const { program, sourceFile } = typecheck(entryPath, files);
248
276
  const reporter = new Reporter();
249
277
  const errorEnums = new Map();
250
278
  const enums = new Map();
@@ -4,6 +4,8 @@ export interface Diagnostic {
4
4
  line: number;
5
5
  column: number;
6
6
  message: string;
7
+ /** Characters the problem spans from line:column (the construct refused), when known. */
8
+ length?: number;
7
9
  }
8
10
  export declare class CompileError extends Error {
9
11
  readonly diagnostics: Diagnostic[];
@@ -11,8 +11,9 @@ export function formatDiagnostic(d) {
11
11
  }
12
12
  export function diagnosticAt(node, message) {
13
13
  const sf = node.getSourceFile();
14
- const { line, character } = sf.getLineAndCharacterOfPosition(node.getStart(sf));
15
- return { file: sf.fileName, line: line + 1, column: character + 1, message };
14
+ const start = node.getStart(sf);
15
+ const { line, character } = sf.getLineAndCharacterOfPosition(start);
16
+ return { file: sf.fileName, line: line + 1, column: character + 1, message, length: Math.max(1, node.getEnd() - start) };
16
17
  }
17
18
  /** Collects diagnostics; `fail` records one and throws to unwind the current construct. */
18
19
  export class Reporter {
@@ -128,6 +128,8 @@ export declare function helperSignature(h: Helper): string;
128
128
  export interface EmitOptions {
129
129
  /** Log a marker and the remaining compute units before every statement (`typesol build --profile`). */
130
130
  profile?: boolean;
131
+ /** Source text by absolute path (an editor's unsaved buffers), read instead of the files on disk. */
132
+ files?: ReadonlyMap<string, string>;
131
133
  }
132
134
  /** C type of a growable Vec stored after the first one of struct `s`: `{ uint32_t len; T items[]; }`. */
133
135
  export declare function laterVecC(s: string, field: string): string;
@@ -12,7 +12,7 @@ export { CompileError, formatDiagnostic } from "./diagnostics.js";
12
12
  export { SBPF_VERSIONS } from "./toolchain.js";
13
13
  /** Typecheck, enforce the TypeSOL subset, and generate C. Throws CompileError with every diagnostic. */
14
14
  export function generate(entry, opts = {}) {
15
- const analysis = analyze(entry);
15
+ const analysis = analyze(entry, opts.files);
16
16
  analysis.reporter.throwIfAny();
17
17
  const c = emitProgram(analysis, opts);
18
18
  analysis.reporter.throwIfAny();
@@ -48,5 +48,5 @@ export declare function deployArgs(soPath: string, keypair: string, opts: {
48
48
  payer?: string;
49
49
  config?: string;
50
50
  }): string[];
51
- /** Create a project: typesol.json, one program from a template, its LiteSVM test, configs. Refuses to overwrite files. */
51
+ /** Create a project: typesol.json, one program from a template, its LiteSVM test, configs (editor settings included). Refuses to overwrite files. */
52
52
  export declare function scaffold(dir: string, name: string, template?: TemplateName): string[];
package/dist/workspace.js CHANGED
@@ -105,7 +105,7 @@ export function deployArgs(soPath, keypair, opts) {
105
105
  args.push("--keypair", opts.payer);
106
106
  return args;
107
107
  }
108
- /** Create a project: typesol.json, one program from a template, its LiteSVM test, configs. Refuses to overwrite files. */
108
+ /** Create a project: typesol.json, one program from a template, its LiteSVM test, configs (editor settings included). Refuses to overwrite files. */
109
109
  export function scaffold(dir, name, template = "counter") {
110
110
  const t = TEMPLATES[template];
111
111
  if (!/^[a-z][a-z0-9_]*$/.test(name))
@@ -146,6 +146,8 @@ export function scaffold(dir, name, template = "counter") {
146
146
  ...t.devDependencies,
147
147
  },
148
148
  }, null, 2) + "\n",
149
+ // VS Code loads tsconfig plugins (typesol/ts-plugin) only with the workspace's TypeScript: offer to switch to it.
150
+ ".vscode/settings.json": JSON.stringify({ "typescript.tsdk": "node_modules/typescript/lib", "typescript.enablePromptUseWorkspaceTsdk": true }, null, 2) + "\n",
149
151
  // target/deploy/*-keypair.json are the programs' addresses: never commit them, but keep a backup.
150
152
  ".gitignore": "node_modules/\n# target/deploy/*-keypair.json are the programs' addresses (and upgrade keys): never commit them, but BACK THEM UP.\n# A fresh clone cannot build or deploy a program whose address is recorded in typesol.json without its keypair.\ntarget/\n",
151
153
  "tsconfig.json": JSON.stringify({
@@ -60,7 +60,7 @@ program.so + program.build.json (manifest: versions, sha256 of sources and binar
60
60
  | `src/templates.ts` | The programs and tests `typesol init --template` writes (copies of `examples/`; a test checks they match). |
61
61
  | `src/tools/svmrpc.ts` | `svmConnection`: a kit RPC and subscriptions pair answered by LiteSVM, so generated clients run in tests (exported by `typesol/testing`). |
62
62
  | `src/keys.ts` | Base58 and program keypair helpers. |
63
- | `ts-plugin/index.js` | `typesol/ts-plugin` (CommonJS, loaded by tsserver): runs `typesol check --json --stdin` on program entries and adds the diagnostics. |
63
+ | `ts-plugin/index.js` | `typesol/ts-plugin` (CommonJS, loaded by tsserver): checks the program entries with the editor's texts (`generate(entry, { files })`, in-process once `dist/compiler` has loaded, `typesol check --json --files` before) and adds each diagnostic to the file it is in. |
64
64
  | `src/testing.ts` | `typesol/testing`: LiteSVM test helpers for projects (accounts by name from the IDL, plain values). |
65
65
  | `src/tools/onchain.ts` | `typesol verify --address`: a deployed program's ELF, authority and deploy slot under loader v2, v3 or v4. |
66
66
  | `src/tools/profile.ts` | Turns `--profile` logs into compute units per source line. |
package/docs/cli.md CHANGED
@@ -38,10 +38,13 @@ safe and out of git: it is each program's address and its first upgrade authorit
38
38
  ## Editor
39
39
 
40
40
  `typesol init` projects load `typesol/ts-plugin` from `programs/tsconfig.json`: besides TypeScript's errors, the editor
41
- shows what the TypeSOL compiler refuses (an unsupported construct, a constraint that cannot hold…) at its line, for the
42
- text being edited, once TypeScript itself has nothing to report. It checks the program entries listed in
43
- `typesol.json`. Editors load tsconfig plugins from the project's own TypeScript: in VS Code, run "TypeScript: Select
44
- TypeScript Version" → "Use Workspace Version". To add it to an existing project:
41
+ underlines what the TypeSOL compiler refuses (an unsupported construct, a constraint that cannot hold…), for the text
42
+ being edited (unsaved changes in every open file), once TypeScript itself has nothing to report. It checks the program
43
+ entries listed in `typesol.json` and shows each problem in the file it is in, the entry or any file it imports. The
44
+ compiler runs inside the editor's TypeScript server once it has loaded (a check takes milliseconds; the first ones run
45
+ `typesol check --json --files` as a child process). Editors load tsconfig plugins from the project's own TypeScript:
46
+ `typesol init` writes `.vscode/settings.json` so VS Code offers to switch to it ("Use Workspace Version"). To add the
47
+ plugin to an existing project:
45
48
 
46
49
  ```json
47
50
  { "compilerOptions": { "plugins": [{ "name": "typesol/ts-plugin" }] } }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@typesol/cli",
3
- "version": "0.29.0",
3
+ "version": "0.30.0",
4
4
  "description": "Compile a TypeScript-syntax language directly to Solana SBF programs.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -2,17 +2,22 @@
2
2
  //
3
3
  // programs/tsconfig.json: { "compilerOptions": { …, "plugins": [{ "name": "typesol/ts-plugin" }] } }
4
4
  //
5
- // For each program entry of the project (typesol.json), once TypeScript itself reports no errors, it runs
6
- // `typesol check --json --stdin` on the editor's text (unsaved changes included) and shows what the compiler refuses
7
- // (an unsupported construct, a missing account constraint…) at its line and column. Editors load tsconfig plugins
8
- // from the workspace's TypeScript (VS Code: "TypeScript: Select TypeScript Version" → "Use Workspace Version").
5
+ // Once TypeScript itself reports no errors in a file, the program entries of the project (typesol.json) are checked
6
+ // with the TypeSOL compiler on the editor's text (unsaved changes in every open file included), and what the compiler
7
+ // refuses (an unsupported construct, a constraint that cannot hold…) is shown where it is: in the entry or in any file
8
+ // it imports. The compiler runs in the editor's process once it has loaded (an ESM import, started when the plugin
9
+ // is created) and as `typesol check --json --files` until then. Editors load tsconfig plugins from the workspace's
10
+ // TypeScript (VS Code: "TypeScript: Select TypeScript Version" → "Use Workspace Version"; `typesol init` sets that up).
9
11
  // CommonJS on purpose: tsserver loads plugins with require().
10
12
  "use strict";
11
13
  const { execFileSync } = require("node:child_process");
14
+ const { createHash } = require("node:crypto");
12
15
  const fs = require("node:fs");
13
16
  const path = require("node:path");
17
+ const { pathToFileURL } = require("node:url");
14
18
 
15
- const CLI = path.join(__dirname, "..", "dist", "cli.js");
19
+ const DIST = path.join(__dirname, "..", "dist");
20
+ const CLI = path.join(DIST, "cli.js");
16
21
  const CODE = 9900;
17
22
 
18
23
  /** The program entry files of the typesol.json at or above `dir` (absolute), or an empty set. */
@@ -35,46 +40,62 @@ function init({ typescript: ts }) {
35
40
  function create(info) {
36
41
  const ls = info.languageService;
37
42
  const log = (m) => info.project.projectService.logger.info(`[typesol] ${m}`);
38
- const cache = new Map(); // fileName -> { text, found }
43
+ /** The compiler, loaded in the background; until then each check runs as a child process. */
44
+ let compiler;
45
+ const ready = import(pathToFileURL(path.join(DIST, "compiler", "index.js")).href).then(
46
+ (m) => (compiler = m),
47
+ (e) => log(`in-process compiler unavailable (${e.message}); checking with the CLI`),
48
+ );
49
+ const cache = new Map(); // entry -> { key, found }
39
50
 
40
- /** The entry's text plus the modification times of the .ts files beside it (its imports usually live there). */
41
- function key(fileName, sf) {
42
- const dir = path.dirname(path.resolve(fileName));
43
- let stamps = "";
44
- try {
45
- for (const f of fs.readdirSync(dir).sort())
46
- if (f.endsWith(".ts") && path.join(dir, f) !== path.resolve(fileName)) stamps += `${f}:${fs.statSync(path.join(dir, f)).mtimeMs};`;
47
- } catch {
48
- stamps = "";
51
+ /** The diagnostics of one program entry for these texts: in-process when possible, else through the CLI. */
52
+ function check(entry, files) {
53
+ if (compiler) {
54
+ try {
55
+ compiler.generate(entry, { files: new Map(Object.entries(files)) });
56
+ return [];
57
+ } catch (e) {
58
+ if (e instanceof compiler.CompileError) return e.diagnostics;
59
+ log(`check failed for ${entry}: ${e.message}`);
60
+ return [];
61
+ }
49
62
  }
50
- return `${stamps}\n${sf.text}`;
51
- }
52
-
53
- function typesolDiagnostics(fileName, sf) {
54
- const k = key(fileName, sf);
55
- const hit = cache.get(fileName);
56
- if (hit && hit.key === k) return hit.found;
57
- let found = [];
58
63
  try {
59
- const out = execFileSync(process.execPath, [CLI, "check", fileName, "--json", "--stdin"], {
60
- input: sf.text,
64
+ const out = execFileSync(process.execPath, [CLI, "check", entry, "--json", "--files"], {
65
+ input: JSON.stringify({ files }),
61
66
  encoding: "utf8",
62
67
  timeout: 15000,
63
68
  // tsserver may run inside an editor's Electron: make it behave as plain Node for the child.
64
69
  env: { ...process.env, ELECTRON_RUN_AS_NODE: "1" },
65
70
  stdio: ["pipe", "pipe", "pipe"],
66
71
  });
67
- found = JSON.parse(out).diagnostics;
72
+ return JSON.parse(out).diagnostics;
68
73
  } catch (e) {
69
74
  // Exit 1 with JSON on stdout means diagnostics; anything else is a crash worth logging, not showing.
70
75
  try {
71
- found = JSON.parse(String(e.stdout)).diagnostics;
76
+ return JSON.parse(String(e.stdout)).diagnostics;
72
77
  } catch {
73
- log(`check failed for ${fileName}: ${e.message}`);
74
- found = [];
78
+ log(`check failed for ${entry}: ${e.message}`);
79
+ return [];
75
80
  }
76
81
  }
77
- cache.set(fileName, { key: k, found });
82
+ }
83
+
84
+ /** `check`, cached on the texts it reads and the modification times of the .ts files beside the entry. */
85
+ function cachedCheck(entry, files) {
86
+ const hash = createHash("sha1");
87
+ for (const f of Object.keys(files).sort()) hash.update(`${f}\0${files[f]}\0`);
88
+ const dir = path.dirname(entry);
89
+ try {
90
+ for (const f of fs.readdirSync(dir).sort()) if (f.endsWith(".ts")) hash.update(`${f}:${fs.statSync(path.join(dir, f)).mtimeMs};`);
91
+ } catch {
92
+ /* the texts alone */
93
+ }
94
+ const key = hash.digest("hex");
95
+ const hit = cache.get(entry);
96
+ if (hit && hit.key === key) return hit.found;
97
+ const found = check(entry, files);
98
+ cache.set(entry, { key, found });
78
99
  return found;
79
100
  }
80
101
 
@@ -83,27 +104,42 @@ function init({ typescript: ts }) {
83
104
  proxy.getSemanticDiagnostics = (fileName) => {
84
105
  const prior = ls.getSemanticDiagnostics(fileName);
85
106
  if (prior.some((d) => d.category === ts.DiagnosticCategory.Error)) return prior; // TypeScript's errors first
86
- if (!entriesNear(path.dirname(path.resolve(fileName))).has(path.resolve(fileName))) return prior;
87
- const sf = ls.getProgram() && ls.getProgram().getSourceFile(fileName);
107
+ const target = path.resolve(fileName);
108
+ const entries = entriesNear(path.dirname(target));
109
+ if (!entries.size) return prior;
110
+ const program = ls.getProgram();
111
+ const sf = program && program.getSourceFile(fileName);
88
112
  if (!sf) return prior;
89
- const own = typesolDiagnostics(fileName, sf)
90
- .filter((d) => path.resolve(d.file) === path.resolve(fileName))
91
- .map((d) => {
113
+ // The editor's text of the project's own files (open buffers included).
114
+ const files = {};
115
+ for (const f of program.getSourceFiles()) if (!f.isDeclarationFile && !f.fileName.includes("/node_modules/")) files[path.resolve(f.fileName)] = f.text;
116
+ // An entry is checked on its own; another file through every entry (whichever imports it reports it).
117
+ const run = entries.has(target) ? [target] : [...entries].filter((e) => fs.existsSync(e) || files[e] !== undefined);
118
+ const seen = new Set();
119
+ const own = [];
120
+ for (const entry of run)
121
+ for (const d of cachedCheck(entry, files)) {
122
+ if (path.resolve(d.file) !== target) continue;
123
+ const id = `${d.line}:${d.column}:${d.message}`;
124
+ if (seen.has(id)) continue;
125
+ seen.add(id);
92
126
  const line = Math.max(0, Math.min(d.line - 1, sf.getLineStarts().length - 1));
93
127
  const start = Math.min(sf.getPositionOfLineAndCharacter(line, 0) + Math.max(0, d.column - 1), sf.end);
94
128
  const word = /^[\w$]+/.exec(sf.text.slice(start));
95
- return {
129
+ own.push({
96
130
  file: sf,
97
131
  start,
98
- length: word ? word[0].length : 1,
132
+ length: Math.max(1, Math.min(d.length || (word ? word[0].length : 1), sf.end - start)),
99
133
  messageText: d.message,
100
134
  category: ts.DiagnosticCategory.Error,
101
135
  code: CODE,
102
136
  source: "typesol",
103
- };
104
- });
137
+ });
138
+ }
105
139
  return [...prior, ...own];
106
140
  };
141
+ // Tests (and curious hosts) can wait for the in-process compiler.
142
+ proxy.typesolReady = () => ready;
107
143
  return proxy;
108
144
  }
109
145
  return { create };