Skip to content

Commit 2e88b3c

Browse files
committed
fix(workflow-code): an unwritable TypeScript cache, cut tsc output and project error chains in the type check
1 parent c3554eb commit 2e88b3c

3 files changed

Lines changed: 114 additions & 14 deletions

File tree

‎packages/sim-cli/src/commands/protocol/source-types.ts‎

Lines changed: 34 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,8 @@ interface Finished {
7474
signal: NodeJS.Signals | null
7575
stdout: string
7676
stderr: string
77+
/** Whether stdout passed {@link MAX_OUTPUT_BYTES} and the rest was left out. */
78+
stdoutCut: boolean
7779
}
7880

7981
/**
@@ -96,10 +98,11 @@ function run(
9698
killSignal: 'SIGKILL',
9799
windowsHide: true,
98100
})
99-
const output = { stdout: '', stderr: '' }
101+
const output = { stdout: '', stderr: '', stdoutCut: false }
100102
for (const stream of ['stdout', 'stderr'] as const) {
101103
child[stream]?.setEncoding('utf8').on('data', (chunk: string) => {
102104
if (output[stream].length < MAX_OUTPUT_BYTES) output[stream] += chunk
105+
else if (stream === 'stdout') output.stdoutCut = true
103106
})
104107
}
105108
child.once('error', (error) =>
@@ -136,6 +139,21 @@ async function installedTsc(): Promise<string> {
136139
const root = typescriptRoot()
137140
const tsc = tscPath(root)
138141
if (existsSync(tsc)) return tsc
142+
try {
143+
await installTypescript(root)
144+
} catch (error) {
145+
if (error instanceof TypesUnavailable) throw error
146+
// The cache folder could not be written (permissions, a full disk).
147+
throw new TypesUnavailable(
148+
`TypeScript could not be installed into ${root} (${getErrorMessage(error)}).`
149+
)
150+
}
151+
return tsc
152+
}
153+
154+
/** Installs the pinned release into `root` (see {@link installedTsc}). */
155+
async function installTypescript(root: string): Promise<void> {
156+
const tsc = tscPath(root)
139157
const parent = dirname(root)
140158
await mkdir(parent, { recursive: true })
141159
const staging = await mkdtemp(join(parent, `.${SOURCE_TYPESCRIPT_VERSION}-`))
@@ -187,7 +205,6 @@ async function installedTsc(): Promise<string> {
187205
} finally {
188206
await rm(staging, { recursive: true, force: true })
189207
}
190-
return tsc
191208
}
192209

193210
/** An error tsc printed at a file position. */
@@ -208,7 +225,7 @@ const PROJECT_ERROR = /^error (TS\d+): (.*)$/
208225
*/
209226
function parseTscOutput(stdout: string): { located: LocatedTscError[]; project: string[] } {
210227
const located: LocatedTscError[] = []
211-
const project: string[] = []
228+
const project: Array<{ message: string }> = []
212229
let last: { message: string } | undefined
213230
for (const line of stdout.split(/\r?\n/)) {
214231
const at = LOCATED_ERROR.exec(line)
@@ -224,12 +241,12 @@ function parseTscOutput(stdout: string): { located: LocatedTscError[]; project:
224241
last = error
225242
} else if (global) {
226243
last = { message: `${global[1]}: ${global[2]}` }
227-
project.push(last.message)
244+
project.push(last)
228245
} else if (last && /^\s/.test(line) && line.trim()) {
229246
last.message += ` ${line.trim()}`
230247
}
231248
}
232-
return { located, project }
249+
return { located, project: project.map(({ message }) => message) }
233250
}
234251

235252
/** The type check's outcome: whether it ran, and its findings. */
@@ -252,7 +269,18 @@ async function tscErrors(root: string): Promise<ReturnType<typeof parseTscOutput
252269
cwd: root,
253270
}
254271
)
255-
const errors = parseTscOutput(finished.stdout)
272+
// Output past the cap ends mid-line: parse whole lines only, and say what was left out, as an
273+
// error no filter drops, so a cut list never reads as a clean check.
274+
const errors = parseTscOutput(
275+
finished.stdoutCut
276+
? finished.stdout.slice(0, finished.stdout.lastIndexOf('\n'))
277+
: finished.stdout
278+
)
279+
if (finished.stdoutCut) {
280+
errors.project.push(
281+
'TypeScript reported more errors than a check lists; fix these and check again to see the rest.'
282+
)
283+
}
256284
if (finished.code !== 0 && errors.located.length === 0 && errors.project.length === 0) {
257285
const said = (finished.stderr || finished.stdout).trim().split('\n')[0] ?? ''
258286
throw new TypesUnavailable(

‎packages/sim-cli/src/commands/protocol/workspace-source-get.test.ts‎

Lines changed: 60 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ import { knowledgeCodec } from '@sim/workspace-code/kinds/knowledge'
1919
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2020
import { SimApiError } from '../../http/client'
2121
import { contextMockFns, contextMockState, mockedProfile } from '../../test/context-mock'
22-
import { provideTypescript } from '../../test/typescript'
22+
import { provideTscPrinting, provideTypescript } from '../../test/typescript'
2323
import { runWorkflowSourceCheck, runWorkspaceSource } from '../../test/workspace-source-command'
2424
import { blobBytes, blobDigests } from './workspace-source-blobs'
2525
import { kindFolders } from './workspace-source-dir'
@@ -1343,6 +1343,65 @@ describe('the type check of workspaces source check', () => {
13431343
expect(env).not.toContain('sk-sim-secret')
13441344
})
13451345

1346+
it('warns and passes on the compile alone when the TypeScript cache cannot be written', async () => {
1347+
serve({ 'tables/leads.ts': LEADS })
1348+
await get()
1349+
rmSync(join(rootDir, 'config/cache/typescript'), { recursive: true })
1350+
writeFileSync(join(rootDir, 'config/cache/typescript'), 'not a folder')
1351+
1352+
await runWorkspaceSource('check', dir)
1353+
1354+
expect(result()).toMatchObject({ checked: ['compile'], errors: 0 })
1355+
expect(result().diagnostics).toContainEqual(
1356+
expect.objectContaining({
1357+
code: 'W_TYPES_UNCHECKED',
1358+
message: expect.stringContaining('TypeScript could not be installed into'),
1359+
})
1360+
)
1361+
})
1362+
1363+
it('fails rather than passing when TypeScript prints more than a check keeps', async () => {
1364+
serve({ 'tables/leads.ts': LEADS })
1365+
await get()
1366+
rmSync(join(rootDir, 'config/cache/typescript'), { recursive: true })
1367+
const flood =
1368+
"tables/leads.ts(2,1): error TS2322: Type 'string' is not assignable to type 'number'.\n"
1369+
provideTscPrinting(
1370+
join(rootDir, 'config'),
1371+
flood.repeat(Math.ceil((1.2 * 1024 * 1024) / flood.length))
1372+
)
1373+
1374+
await runWorkspaceSource('check', dir)
1375+
1376+
expect(result()).toMatchObject({ checked: ['compile', 'types'], errors: 1 })
1377+
expect(result().diagnostics).toEqual([
1378+
expect.objectContaining({
1379+
code: 'E_TYPE',
1380+
message: expect.stringContaining('more errors than a check lists'),
1381+
}),
1382+
])
1383+
expect(process.exitCode).toBe(1)
1384+
})
1385+
1386+
it('keeps the whole message chain of a project error', async () => {
1387+
serve({ 'tables/leads.ts': LEADS })
1388+
await get()
1389+
rmSync(join(rootDir, 'config/cache/typescript'), { recursive: true })
1390+
provideTscPrinting(
1391+
join(rootDir, 'config'),
1392+
"error TS5110: Option 'module' must be set.\n Set it in tsconfig.json.\n"
1393+
)
1394+
1395+
await runWorkspaceSource('check', dir)
1396+
1397+
expect(result().diagnostics).toEqual([
1398+
expect.objectContaining({
1399+
code: 'E_TYPE',
1400+
message: "TS5110: Option 'module' must be set. Set it in tsconfig.json.",
1401+
}),
1402+
])
1403+
})
1404+
13461405
it('skips the type check with --no-types', async () => {
13471406
serve({ 'tables/leads.ts': LEADS })
13481407
await get()
Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { mkdirSync, symlinkSync } from 'node:fs'
1+
import { mkdirSync, symlinkSync, writeFileSync } from 'node:fs'
22
import { dirname, join } from 'node:path'
33
import { SOURCE_TYPESCRIPT_VERSION } from '@sim/workflow-sdk/codegen'
44

@@ -10,12 +10,25 @@ const REPO_TYPESCRIPT = join(__dirname, '../../../../node_modules/typescript')
1010
* by linking the repository's copy, so a check type-checks without reaching npm.
1111
*/
1212
export function provideTypescript(configDir: string): void {
13-
const installed = join(
14-
configDir,
15-
'cache/typescript',
16-
SOURCE_TYPESCRIPT_VERSION,
17-
'node_modules/typescript'
18-
)
13+
const installed = installedPath(configDir)
1914
mkdirSync(dirname(installed), { recursive: true })
2015
symlinkSync(REPO_TYPESCRIPT, installed, 'dir')
2116
}
17+
18+
function installedPath(configDir: string): string {
19+
return join(configDir, 'cache/typescript', SOURCE_TYPESCRIPT_VERSION, 'node_modules/typescript')
20+
}
21+
22+
/**
23+
* Installs, in place of the pinned TypeScript, a `tsc` that prints `stdout` and exits 2, as tsc
24+
* does on errors: for output real sources rarely produce (a cut-off flood, a project error chain).
25+
*/
26+
export function provideTscPrinting(configDir: string, stdout: string): void {
27+
const installed = installedPath(configDir)
28+
mkdirSync(join(installed, 'bin'), { recursive: true })
29+
writeFileSync(join(installed, 'output.txt'), stdout)
30+
writeFileSync(
31+
join(installed, 'bin/tsc'),
32+
"const { readFileSync } = require('node:fs')\nprocess.stdout.write(readFileSync(require('node:path').join(__dirname, '../output.txt'), 'utf8'), () => process.exit(2))\n"
33+
)
34+
}

0 commit comments

Comments
 (0)