Tsserver protocol and projects
Concept and boundary
tsserver wraps project management and language services behind a JSON protocol. Configured projects derive from tsconfig, inferred projects cover open files lacking a configuration, and external projects are supplied by a client. Direct LanguageService calls are not protocol messages. The first two workshops query the direct service; the third starts a real local tsserver and verifies its configured-project response. Inferred and external project sessions are not executed.
Local tooling setup
For each workshop use a fresh folder. Install the pinned compiler with npm install --save-dev typescript@5.8.3, then create the listed files and run node example.cjs with Node.js 22.16.0. Assertions fail if the expected behavior changes. These are local JavaScript tooling scripts, not browser CodeRunner tasks; they do not independently type-check the tooling source.
Workshop 1: language-service-get-program
Revisit reference fixture ts-api-language-service-get-program (historical V29, rerun in V74).
const ts = require("typescript");const assert = require("node:assert/strict");const path = require("node:path");// Project documents live in memory; compiler libraries use the local filesystem.function workspace(initial, extraOptions = {}) { const files = new Map(Object.entries(initial).map(([name, text]) => [path.resolve(name), { text, version: 0 }])); const options = { strict: true, target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS, types: [], noEmit: true, ...extraOptions }; const key = name => path.resolve(name); const read = name => files.get(key(name))?.text ?? ts.sys.readFile(name); const host = { getCompilationSettings: () => options, getScriptFileNames: () => [...files.keys()], getScriptVersion: name => String(files.get(key(name))?.version ?? 0), getScriptSnapshot: name => { const text = read(name); return text === undefined ? undefined : ts.ScriptSnapshot.fromString(text); }, getCurrentDirectory: () => process.cwd(), getDefaultLibFileName: opts => ts.getDefaultLibFilePath(opts), fileExists: name => files.has(key(name)) || ts.sys.fileExists(name), readFile: read, readDirectory: ts.sys.readDirectory, directoryExists: ts.sys.directoryExists, getDirectories: ts.sys.getDirectories, useCaseSensitiveFileNames: () => ts.sys.useCaseSensitiveFileNames, getNewLine: () => "\n" }; function edit(name, text) { const file = files.get(key(name)); assert(file, "edit requires an existing file"); files.set(key(name), { text, version: file.version + 1 }); } return { host, edit, read, key };}const format = { indentSize: 2, tabSize: 2, convertTabsToSpaces: true, newLineCharacter: "\n", insertSpaceAfterCommaDelimiter: true, insertSpaceBeforeAndAfterBinaryOperators: true, insertSpaceAfterKeywordsInControlFlowStatements: true, semicolons: ts.SemicolonPreference.Insert };function apply(text, changes) { // All spans refer to the same original snapshot; edit from right to left. for (const change of [...changes].sort((a,b)=>b.span.start-a.span.start)) { const {start,length}=change.span; text=text.slice(0,start)+change.newText+text.slice(start+length); } return text;}function applyFiles(w, edits) { for (const edit of edits) w.edit(edit.fileName, apply(w.read(edit.fileName), edit.textChanges));}function run(initial, fn, options = {}) { const w=workspace(initial,options), service=ts.createLanguageService(w.host); try { fn(w,service,w.key("main.ts")); } finally { service.dispose(); }}run({"main.ts":"let count = 7;"},(w,s,f)=>{ const p=s.getProgram(); assert(p); const original=p.getSourceFile(f); assert(original); w.edit(f,'let count = "x";'); const next=s.getProgram(); assert(next); assert.notEqual(next,p); assert.equal(original.text,"let count = 7;"); assert.equal(next.getSourceFile(f).text,'let count = "x";'); console.log("new program; old snapshot preserved");});Expected stdout (exit 0):
new program; old snapshot preservedWorkshop 2: language-service-host
Revisit reference fixture ts-api-language-service-host (historical V25, rerun in V74).
const ts = require("typescript");const assert = require("node:assert/strict");const path = require("node:path");// Project documents live in memory; compiler libraries use the local filesystem.function workspace(initial) { const files = new Map(Object.entries(initial).map(([name, text]) => [path.resolve(name), { text, version: 0 }])); const options = { strict: true, target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS, types: [], noEmit: true }; const key = name => path.resolve(name); const read = name => files.get(key(name))?.text ?? ts.sys.readFile(name); const host = { getCompilationSettings: () => options, getScriptFileNames: () => [...files.keys()], getScriptVersion: name => String(files.get(key(name))?.version ?? 0), getScriptSnapshot: name => { const text = read(name); return text === undefined ? undefined : ts.ScriptSnapshot.fromString(text); }, getCurrentDirectory: () => process.cwd(), getDefaultLibFileName: opts => ts.getDefaultLibFilePath(opts), fileExists: name => files.has(key(name)) || ts.sys.fileExists(name), readFile: read, readDirectory: ts.sys.readDirectory, directoryExists: ts.sys.directoryExists, getDirectories: ts.sys.getDirectories, useCaseSensitiveFileNames: () => ts.sys.useCaseSensitiveFileNames, getNewLine: () => "\n" }; function edit(name, text) { const file = files.get(key(name)); assert(file, "edit requires an existing file"); files.set(key(name), { text, version: file.version + 1 }); } return { host, edit, read, key };}const w = workspace({"main.ts": "export const n = 1;"});const file = w.key("main.ts");const service = ts.createLanguageService(w.host);try { const first = w.host.getScriptSnapshot(file); assert.equal(w.host.getScriptVersion(file), "0"); assert.equal(first.getText(0, first.getLength()), "export const n = 1;"); w.edit("main.ts", "export const n = 2;"); assert.equal(w.host.getScriptVersion(file), "1"); assert.equal(w.host.getScriptSnapshot(file).getText(0, 19), "export const n = 2;"); assert.equal(first.getText(0, first.getLength()), "export const n = 1;"); console.log("0 -> 1");} finally { service.dispose(); }Expected stdout (exit 0):
0 -> 1Workshop 3: tsserver-configured-project
const cp = require("node:child_process");const path = require("node:path");const assert = require("node:assert/strict");const server = path.join(path.dirname(require.resolve("typescript")), "tsserver.js");const child = cp.spawn(process.execPath,[server,"--disableAutomaticTypingAcquisition"],{stdio:["pipe","pipe","pipe"]});const file = path.resolve("input.ts");let buffer = Buffer.alloc(0), done=false;const timer = setTimeout(()=>{child.kill();process.exitCode=1;console.error("timeout")},15000);function send(seq,command,args){child.stdin.write(JSON.stringify({seq,type:"request",command,arguments:args})+"\n")}child.stdout.on("data",chunk=>{ buffer=Buffer.concat([buffer,chunk]); while(true){ const split=buffer.indexOf("\r\n\r\n"); if(split<0)return; const h=buffer.subarray(0,split).toString(); const match=/Content-Length: (\d+)/i.exec(h); if(!match)throw Error("missing length"); const n=Number(match[1]); if(buffer.length<split+4+n)return; const payload=buffer.subarray(split+4,split+4+n).toString(); buffer=buffer.subarray(split+4+n); const msg=JSON.parse(payload); if(msg.type==="response" && msg.request_seq===2){ assert.equal(msg.success,true); assert.equal(path.basename(msg.body.configFileName),"tsconfig.json"); done=true; clearTimeout(timer); console.log("configured project confirmed"); child.stdin.end(); child.kill(); } }});child.on("exit",()=>{clearTimeout(timer);if(!done)process.exitCode=1});send(1,"open",{file}); send(2,"projectInfo",{file,needFileNameList:true});tsconfig.json
{ "compilerOptions": { "types": [] }, "files": [ "input.ts" ]}Expected stdout (exit 0):
configured project confirmedPractice and recap
Design an open request with sequence number, command and file path; identify which project kind owns the file.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Tsserver protocol and projects — knowledge check
Check the concept and interpret the locally verified compiler tooling probes.
Which statement correctly describes Tsserver protocol and projects?
What does workshop 1 (language-service-get-program) print when run unchanged with the specified compiler?
const ts = require("typescript");const assert = require("node:assert/strict");const path = require("node:path");// Project documents live in memory; compiler libraries use the local filesystem.function workspace(initial, extraOptions = {}) { const files = new Map(Object.entries(initial).map(([name, text]) => [path.resolve(name), { text, version: 0 }])); const options = { strict: true, target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS, types: [], noEmit: true, ...extraOptions }; const key = name => path.resolve(name); const read = name => files.get(key(name))?.text ?? ts.sys.readFile(name); const host = { getCompilationSettings: () => options, getScriptFileNames: () => [...files.keys()], getScriptVersion: name => String(files.get(key(name))?.version ?? 0), getScriptSnapshot: name => { const text = read(name); return text === undefined ? undefined : ts.ScriptSnapshot.fromString(text); }, getCurrentDirectory: () => process.cwd(), getDefaultLibFileName: opts => ts.getDefaultLibFilePath(opts), fileExists: name => files.has(key(name)) || ts.sys.fileExists(name), readFile: read, readDirectory: ts.sys.readDirectory, directoryExists: ts.sys.directoryExists, getDirectories: ts.sys.getDirectories, useCaseSensitiveFileNames: () => ts.sys.useCaseSensitiveFileNames, getNewLine: () => "\n" }; function edit(name, text) { const file = files.get(key(name)); assert(file, "edit requires an existing file"); files.set(key(name), { text, version: file.version + 1 }); } return { host, edit, read, key };}const format = { indentSize: 2, tabSize: 2, convertTabsToSpaces: true, newLineCharacter: "\n", insertSpaceAfterCommaDelimiter: true, insertSpaceBeforeAndAfterBinaryOperators: true, insertSpaceAfterKeywordsInControlFlowStatements: true, semicolons: ts.SemicolonPreference.Insert };function apply(text, changes) { // All spans refer to the same original snapshot; edit from right to left. for (const change of [...changes].sort((a,b)=>b.span.start-a.span.start)) { const {start,length}=change.span; text=text.slice(0,start)+change.newText+text.slice(start+length); } return text;}function applyFiles(w, edits) { for (const edit of edits) w.edit(edit.fileName, apply(w.read(edit.fileName), edit.textChanges));}function run(initial, fn, options = {}) { const w=workspace(initial,options), service=ts.createLanguageService(w.host); try { fn(w,service,w.key("main.ts")); } finally { service.dispose(); }}run({"main.ts":"let count = 7;"},(w,s,f)=>{ const p=s.getProgram(); assert(p); const original=p.getSourceFile(f); assert(original); w.edit(f,'let count = "x";'); const next=s.getProgram(); assert(next); assert.notEqual(next,p); assert.equal(original.text,"let count = 7;"); assert.equal(next.getSourceFile(f).text,'let count = "x";'); console.log("new program; old snapshot preserved");});What does workshop 2 (language-service-host) print when run unchanged with the specified compiler?
const ts = require("typescript");const assert = require("node:assert/strict");const path = require("node:path");// Project documents live in memory; compiler libraries use the local filesystem.function workspace(initial) { const files = new Map(Object.entries(initial).map(([name, text]) => [path.resolve(name), { text, version: 0 }])); const options = { strict: true, target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS, types: [], noEmit: true }; const key = name => path.resolve(name); const read = name => files.get(key(name))?.text ?? ts.sys.readFile(name); const host = { getCompilationSettings: () => options, getScriptFileNames: () => [...files.keys()], getScriptVersion: name => String(files.get(key(name))?.version ?? 0), getScriptSnapshot: name => { const text = read(name); return text === undefined ? undefined : ts.ScriptSnapshot.fromString(text); }, getCurrentDirectory: () => process.cwd(), getDefaultLibFileName: opts => ts.getDefaultLibFilePath(opts), fileExists: name => files.has(key(name)) || ts.sys.fileExists(name), readFile: read, readDirectory: ts.sys.readDirectory, directoryExists: ts.sys.directoryExists, getDirectories: ts.sys.getDirectories, useCaseSensitiveFileNames: () => ts.sys.useCaseSensitiveFileNames, getNewLine: () => "\n" }; function edit(name, text) { const file = files.get(key(name)); assert(file, "edit requires an existing file"); files.set(key(name), { text, version: file.version + 1 }); } return { host, edit, read, key };}const w = workspace({"main.ts": "export const n = 1;"});const file = w.key("main.ts");const service = ts.createLanguageService(w.host);try { const first = w.host.getScriptSnapshot(file); assert.equal(w.host.getScriptVersion(file), "0"); assert.equal(first.getText(0, first.getLength()), "export const n = 1;"); w.edit("main.ts", "export const n = 2;"); assert.equal(w.host.getScriptVersion(file), "1"); assert.equal(w.host.getScriptSnapshot(file).getText(0, 19), "export const n = 2;"); assert.equal(first.getText(0, first.getLength()), "export const n = 1;"); console.log("0 -> 1");} finally { service.dispose(); }What does workshop 3 (tsserver-configured-project) print when run unchanged with the specified compiler?
const cp = require("node:child_process");const path = require("node:path");const assert = require("node:assert/strict");const server = path.join(path.dirname(require.resolve("typescript")), "tsserver.js");const child = cp.spawn(process.execPath,[server,"--disableAutomaticTypingAcquisition"],{stdio:["pipe","pipe","pipe"]});const file = path.resolve("input.ts");let buffer = Buffer.alloc(0), done=false;const timer = setTimeout(()=>{child.kill();process.exitCode=1;console.error("timeout")},15000);function send(seq,command,args){child.stdin.write(JSON.stringify({seq,type:"request",command,arguments:args})+"\n")}child.stdout.on("data",chunk=>{ buffer=Buffer.concat([buffer,chunk]); while(true){ const split=buffer.indexOf("\r\n\r\n"); if(split<0)return; const h=buffer.subarray(0,split).toString(); const match=/Content-Length: (\d+)/i.exec(h); if(!match)throw Error("missing length"); const n=Number(match[1]); if(buffer.length<split+4+n)return; const payload=buffer.subarray(split+4,split+4+n).toString(); buffer=buffer.subarray(split+4+n); const msg=JSON.parse(payload); if(msg.type==="response" && msg.request_seq===2){ assert.equal(msg.success,true); assert.equal(path.basename(msg.body.configFileName),"tsconfig.json"); done=true; clearTimeout(timer); console.log("configured project confirmed"); child.stdin.end(); child.kill(); } }});child.on("exit",()=>{clearTimeout(timer);if(!done)process.exitCode=1});send(1,"open",{file}); send(2,"projectInfo",{file,needFileNameList:true});