/
static.ts
107 lines (94 loc) · 2.82 KB
/
static.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import type { BirpcReturn } from 'birpc'
import type { VitestClient } from '@vitest/ws-client'
import type { File, ModuleGraphData, ResolvedConfig, WebSocketEvents, WebSocketHandlers } from 'vitest'
import { parse } from 'flatted'
import { decompressSync, strFromU8 } from 'fflate'
import { StateManager } from '../../../../vitest/src/node/state'
interface HTMLReportMetadata {
paths: string[]
files: File[]
config: ResolvedConfig
moduleGraph: Record<string, ModuleGraphData>
unhandledErrors: unknown[]
}
const noop: any = () => {}
const asyncNoop: any = () => Promise.resolve()
export function createStaticClient(): VitestClient {
const ctx = reactive({
state: new StateManager(),
waitForConnection,
reconnect,
ws: new EventTarget(),
}) as VitestClient
ctx.state.filesMap = reactive(ctx.state.filesMap)
ctx.state.idMap = reactive(ctx.state.idMap)
let metadata!: HTMLReportMetadata
const rpc = {
getFiles: () => {
return metadata.files
},
getPaths: () => {
return metadata.paths
},
getConfig: () => {
return metadata.config
},
getModuleGraph: async (id) => {
return metadata.moduleGraph[id]
},
getUnhandledErrors: () => {
return metadata.unhandledErrors
},
getTransformResult: async (id) => {
return {
code: id,
source: '',
map: null,
}
},
onDone: noop,
onCollected: asyncNoop,
onTaskUpdate: noop,
writeFile: asyncNoop,
rerun: asyncNoop,
updateSnapshot: asyncNoop,
resolveSnapshotPath: asyncNoop,
snapshotSaved: asyncNoop,
onAfterSuiteRun: asyncNoop,
onCancel: asyncNoop,
getCountOfFailedTests: () => 0,
sendLog: asyncNoop,
resolveSnapshotRawPath: asyncNoop,
readSnapshotFile: asyncNoop,
saveSnapshotFile: asyncNoop,
readTestFile: asyncNoop,
removeSnapshotFile: asyncNoop,
onUnhandledError: noop,
saveTestFile: asyncNoop,
getProvidedContext: () => ({}),
} as WebSocketHandlers
ctx.rpc = rpc as any as BirpcReturn<WebSocketHandlers, WebSocketEvents>
let openPromise: Promise<void>
function reconnect() {
registerMetadata()
}
async function registerMetadata() {
const res = await fetch(window.METADATA_PATH!)
const contentType = res.headers.get('content-type')?.toLowerCase() || ''
if (contentType.includes('application/gzip') || contentType.includes('application/x-gzip')) {
const compressed = new Uint8Array(await res.arrayBuffer())
const decompressed = strFromU8(decompressSync(compressed))
metadata = parse(decompressed) as HTMLReportMetadata
}
else {
metadata = parse(await res.text()) as HTMLReportMetadata
}
const event = new Event('open')
ctx.ws.dispatchEvent(event)
}
registerMetadata()
function waitForConnection() {
return openPromise
}
return ctx
}