Skip to content

Commit f7e6841

Browse files
authored
chore: refactor server files to TypeScript (#32838)
* convert file_server to TypeScript * chore: convert random to TypeScript * convert a handful of files to TypeScript
1 parent 04a5e9f commit f7e6841

File tree

22 files changed

+193
-184
lines changed

22 files changed

+193
-184
lines changed

packages/https-proxy/lib/index.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,5 @@ import { create as createProxy, reset as resetProxy } from './proxy'
22
import { CA } from './ca'
33

44
export { createProxy, resetProxy, CA }
5+
6+
export type { Server } from './server'

packages/server/lib/cache.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import Promise from 'bluebird'
33
import { globalPubSub } from '@packages/data-context'
44
import { fs } from './util/fs'
55
import appData from './util/app_data'
6-
import FileUtil from './util/file'
6+
import { File as FileUtil } from './util/file'
77
import type { Cache, CachedUser, Preferences, Cohort } from '@packages/types'
88

99
interface Transaction {
@@ -55,6 +55,7 @@ export const cache = {
5555
},
5656

5757
getProjectRoots (): Promise<string[]> {
58+
// @ts-expect-error - transaction is untyped currently
5859
return fileUtil.transaction((tx: Transaction) => {
5960
return this._getProjects(tx).then((projects) => {
6061
const pathsToRemove = Promise.reduce(projects, (memo: string[], path: string) => {
@@ -76,6 +77,7 @@ export const cache = {
7677
},
7778

7879
removeProject (path: string): Promise<void> {
80+
// @ts-expect-error - transaction is untyped currently
7981
return fileUtil.transaction((tx: Transaction) => {
8082
return this._getProjects(tx).then((projects) => {
8183
return this._removeProjects(tx, projects, path)
@@ -84,6 +86,7 @@ export const cache = {
8486
},
8587

8688
insertProject (path: string): Promise<void> {
89+
// @ts-expect-error - transaction is untyped currently
8790
return fileUtil.transaction((tx: Transaction) => {
8891
return this._getProjects(tx).then((projects) => {
8992
// projects are sorted by most recently used, so add a project to
@@ -124,6 +127,7 @@ export const cache = {
124127
},
125128

126129
insertProjectPreferences (projectTitle: string, projectPreferences: Preferences): Promise<void> {
130+
// @ts-expect-error - transaction is untyped currently
127131
return fileUtil.transaction((tx: Transaction) => {
128132
return tx.get('PROJECT_PREFERENCES', {}).then((preferences) => {
129133
return tx.set('PROJECT_PREFERENCES', {
@@ -163,6 +167,7 @@ export const cache = {
163167
},
164168

165169
insertCohort (cohort: Cohort): Promise<void> {
170+
// @ts-expect-error - transaction is untyped currently
166171
return fileUtil.transaction((tx: Transaction) => {
167172
return tx.get('COHORTS', {}).then((cohorts) => {
168173
return tx.set('COHORTS', {

packages/server/lib/cloud/auth.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ const url = require('url')
99
const { shell } = require('electron')
1010

1111
const machineId = require('./machine_id')
12-
const random = require('../util/random')
12+
import { id as randomId } from '../util/random'
1313
const user = require('./user')
1414

1515
let app
@@ -29,7 +29,7 @@ const buildFullLoginUrl = (baseLoginUrl, server, utmSource, utmMedium, utmConten
2929
const { port } = server.address()
3030

3131
if (!authState) {
32-
authState = random.id(32)
32+
authState = randomId(32)
3333
}
3434

3535
const authUrl = url.parse(baseLoginUrl)

packages/server/lib/cloud/protocol.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import os from 'os'
88
import path from 'path'
99
import { strictAgent } from '@packages/network'
1010
import pkg from '@packages/root'
11-
import env from '../util/env'
11+
import * as env from '../util/env'
1212
import { putProtocolArtifact } from './api/put_protocol_artifact'
1313
import { requireScript } from './require_script'
1414
import * as routes from './routes'

packages/server/lib/file_server.js

Lines changed: 0 additions & 81 deletions
This file was deleted.

packages/server/lib/file_server.ts

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
// TODO: move this to packages/core-file-server
2+
import _ from 'lodash'
3+
import debugModule from 'debug'
4+
import url from 'url'
5+
import http from 'http'
6+
import path from 'path'
7+
import send from 'send'
8+
import { httpUtils } from '@packages/network'
9+
import { allowDestroy } from './util/server_destroy'
10+
import { id as randomId } from './util/random'
11+
import networkFailures from './util/network_failures'
12+
import type { AddressInfo } from 'net'
13+
14+
const debug = debugModule('cypress:server:file_server')
15+
16+
export type FileServer = {
17+
token: string
18+
port: () => number
19+
address: () => string
20+
close: () => void
21+
}
22+
23+
const onRequest = function (req: http.IncomingMessage, res: http.ServerResponse, expectedToken: string, fileServerFolder: string) {
24+
const token = req.headers['x-cypress-authorization']
25+
26+
if (token !== expectedToken) {
27+
debug('authorization failed on file_server request %o', { reqUrl: req.url, expectedToken, token })
28+
res.statusCode = 401
29+
res.end()
30+
31+
return
32+
}
33+
34+
const args = _.compact([
35+
fileServerFolder,
36+
req.url,
37+
])
38+
39+
// strip off any query params from our req's url
40+
// since we're pulling this from the file system
41+
// it does not understand query params
42+
// and make sure we decode the uri which swaps out
43+
// %20 with white space
44+
const file = decodeURI(url.parse(path.join(...args)).pathname as string)
45+
46+
res.setHeader('x-cypress-file-path', encodeURI(file))
47+
48+
return send(req, url.parse(req.url as string).pathname as string, {
49+
root: path.resolve(fileServerFolder),
50+
})
51+
.on('error', (err) => {
52+
res.setHeader('x-cypress-file-server-error', 'true')
53+
res.setHeader('content-type', 'text/html')
54+
res.statusCode = err.status
55+
56+
return res.end(networkFailures.get(file, err.status))
57+
}).pipe(res)
58+
}
59+
60+
export const create = (fileServerFolder: string): Promise<FileServer> => {
61+
return new Promise(((resolve) => {
62+
const token = randomId(64)
63+
64+
const srv = http.createServer(httpUtils.lenientOptions, (req: http.IncomingMessage, res: http.ServerResponse) => {
65+
return onRequest(req, res, token, fileServerFolder)
66+
})
67+
68+
allowDestroy(srv)
69+
70+
return srv.listen(0, '127.0.0.1', () => {
71+
const server: FileServer = {
72+
token,
73+
port () {
74+
return (srv.address() as AddressInfo).port
75+
},
76+
address () {
77+
return `http://localhost:${this.port()}`
78+
},
79+
close () {
80+
// @ts-expect-error - destroyAsync is defined when allowDestroy is called
81+
return srv.destroyAsync()
82+
},
83+
}
84+
85+
return resolve(server)
86+
})
87+
}))
88+
}

packages/server/lib/modes/index.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { setCtx } from '@packages/data-context'
22
import _ from 'lodash'
33

44
import { makeDataContext } from '../makeDataContext'
5-
import random from '../util/random'
5+
import { id as randomId } from '../util/random'
66
import { telemetry } from '@packages/telemetry'
77

88
export = (mode, options) => {
@@ -14,7 +14,7 @@ export = (mode, options) => {
1414

1515
if (mode === 'run') {
1616
_.defaults(options, {
17-
socketId: random.id(10),
17+
socketId: randomId(10),
1818
isTextTerminal: true,
1919
browser: 'electron',
2020
quiet: false,

packages/server/lib/modes/record.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ import type { AllCypressErrorNames } from '@packages/errors'
1616
import { get as getErrors, warning as errorsWarning, throwErr } from '../errors'
1717
import * as capture from '../capture'
1818
import { getResolvedRuntimeConfig } from '../config'
19-
import env from '../util/env'
19+
import * as env from '../util/env'
2020
import ciProvider from '../util/ci_provider'
2121
import { flattenSuiteIntoRunnables } from '../util/tests_utils'
2222
import { countStudioUsage } from '../util/spec_writer'

packages/server/lib/modes/run.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,9 @@ import { openProject } from '../open_project'
1515
import * as videoCapture from '../video_capture'
1616
import { fs, getPath } from '../util/fs'
1717
import runEvents from '../plugins/run_events'
18-
import env from '../util/env'
18+
import * as env from '../util/env'
1919
import trash from '../util/trash'
20-
import random from '../util/random'
20+
import { id as randomId } from '../util/random'
2121
import system from '../util/system'
2222
import chromePolicyCheck from '../util/chrome_policy_check'
2323
import type { SpecWithRelativeRoot, SpecFile, TestingType, OpenProjectLaunchOpts, FoundBrowser, BrowserVideoController, VideoRecording, ProcessOptions, ProtocolManagerShape, AutomationCommands } from '@packages/types'
@@ -764,7 +764,7 @@ async function waitForTestsToFinishRunning (options: { project: Project, screens
764764

765765
function screenshotMetadata (data: any, resp: any) {
766766
return {
767-
screenshotId: random.id(),
767+
screenshotId: randomId(),
768768
name: data.name || null,
769769
testId: data.testId,
770770
testAttemptIndex: data.testAttemptIndex,

packages/server/lib/saved_state.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import Debug from 'debug'
44
import Bluebird from 'bluebird'
55
import appData from './util/app_data'
66
import { getCwd } from './cwd'
7-
import FileUtil from './util/file'
7+
import { File as FileUtil } from './util/file'
88
import { fs } from './util/fs'
99
import { AllowedState, allowedKeys } from '@packages/types'
1010
import { globalPubSub } from '@packages/data-context'

0 commit comments

Comments
 (0)