-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathproject.ts
More file actions
406 lines (352 loc) · 12.8 KB
/
project.ts
File metadata and controls
406 lines (352 loc) · 12.8 KB
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
import path from 'node:path'
import * as api from '../rest/api'
import { CheckConfigDefaults } from '../services/checkly-config-loader'
import { Parser } from '../services/check-parser/parser'
import { Construct } from './construct'
import {
Check, AlertChannelSubscription, AlertChannel, CheckGroup, MaintenanceWindow, Dashboard,
PrivateLocation, HeartbeatMonitor, PrivateLocationCheckAssignment, PrivateLocationGroupAssignment,
StatusPage, StatusPageService,
} from './'
import { PrivateLocationApi } from '../rest/private-locations'
import {
FileLoader,
JitiFileLoader,
MixedFileLoader,
NativeFileLoader,
TSNodeFileLoader,
} from '../loader'
import { Diagnostics } from './diagnostics'
import { ConstructDiagnostics, InvalidPropertyValueDiagnostic } from './construct-diagnostics'
import { ProjectBundle, ProjectDataBundle } from './project-bundle'
import { pathToPosix } from '../services/util'
import { Workspace } from '../services/check-parser/package-files/workspace'
import { npmPackageManager, PackageManager } from '../services/check-parser/package-files/package-manager'
import { Err, Result } from '../services/check-parser/package-files/result'
import { Runtime } from '../runtimes'
export interface ProjectProps {
/**
* Friendly name for your project.
*/
name: string
/**
* Git repository URL.
*/
repoUrl?: string
}
export type Resources = {
'check': Check
'check-group': CheckGroup
'alert-channel': AlertChannel
'alert-channel-subscription': AlertChannelSubscription
'maintenance-window': MaintenanceWindow
'private-location': PrivateLocation
'private-location-check-assignment': PrivateLocationCheckAssignment
'private-location-group-assignment': PrivateLocationGroupAssignment
'dashboard': Dashboard
'status-page': StatusPage
'status-page-service': StatusPageService
}
export type ProjectData = {
[x in keyof Resources]: Record<string, Resources[x]>
}
export class Project extends Construct {
name: string
repoUrl?: string
logicalId: string
testOnlyAllowed = false
duplicateResources: Array<{ type: string, logicalId: string }> = []
data: ProjectData = {
'check': {},
'check-group': {},
'alert-channel': {},
'alert-channel-subscription': {},
'maintenance-window': {},
'private-location': {},
'private-location-check-assignment': {},
'private-location-group-assignment': {},
'dashboard': {},
'status-page': {},
'status-page-service': {},
}
static readonly __checklyType = 'project'
/**
* Constructs the Project instance
*
* @param logicalId unique project identifier
* @param props project configuration properties
*/
constructor (logicalId: string, props: ProjectProps) {
super(Project.__checklyType, logicalId)
this.name = props.name
this.repoUrl = props.repoUrl
this.logicalId = logicalId
}
describe (): string {
return `Project:${this.logicalId}`
}
async validate (diagnostics: Diagnostics): Promise<void> {
await super.validate(diagnostics)
for (const { type, logicalId } of this.duplicateResources) {
diagnostics.add(new InvalidPropertyValueDiagnostic(
'logicalId',
new Error(`A ${type} with logicalId "${logicalId}" already exists.`),
))
}
if (!this.name) {
diagnostics.add(new InvalidPropertyValueDiagnostic(
'name',
new Error(`Value must not be empty.`),
))
}
const data: Record<keyof ProjectData, Record<string, Construct>> = this.data
const constructDiagnostics = await Promise.all(
Object.entries(data).flatMap(([, records]) => {
return Object.values(records).map(async construct => {
const diagnostics = new ConstructDiagnostics(construct)
await construct.validate(diagnostics)
return diagnostics
})
}),
)
diagnostics.extend(...constructDiagnostics)
}
allowTestOnly (enabled: boolean) {
this.testOnlyAllowed = enabled
}
addResource (type: string, logicalId: string, resource: Construct) {
const existingResource = this.data[type as keyof ProjectData][logicalId]
if (existingResource) {
// Non-member resources (i.e. references) can be used multiple times.
// Behind the scenes, we'll create a single mapping for them, and the
// referenced resource isn't managed by the project at all.
if (!resource.member && !existingResource.member && existingResource.physicalId === resource.physicalId) {
return
}
this.duplicateResources.push({ type, logicalId })
return
}
this.data[type as keyof ProjectData][logicalId] = resource
}
async bundle (): Promise<ProjectBundle> {
const data: Record<keyof ProjectData, Record<string, Construct>> = {
...this.data,
// Filter out testOnly checks before bundling.
check: Object.fromEntries(
Object.entries(this.data.check)
.filter(([, check]) => !check.testOnly || this.testOnlyAllowed)
.filter(([, check]) => Session.checkFilter?.(check) ?? true),
),
}
const constructBundles = await Promise.all(
Object.entries(data).flatMap(([, records]) => {
return Object.entries(records).map(async ([, construct]) => {
const bundle = await construct.bundle()
return {
construct,
bundle,
}
})
}),
)
const dataBundle = Object.fromEntries(
Object.entries(data).map(([type]) => {
return [type, {}]
}),
) as ProjectDataBundle
for (const constructBundle of constructBundles) {
const { construct: { type, logicalId } } = constructBundle
dataBundle[type as keyof ProjectDataBundle][logicalId] = constructBundle
}
return new ProjectBundle(this, dataBundle)
}
synthesize () {
const project = {
logicalId: this.logicalId,
name: this.name,
repoUrl: this.repoUrl,
}
return {
project,
sharedFiles: Session.sharedFiles,
}
}
getTestOnlyConstructs (): Construct[] {
return Object
.values(this.data)
.flatMap((record: Record<string, Construct>) =>
Object
.values(record)
.filter((construct: Construct) => construct instanceof Check && construct.testOnly))
}
getHeartbeatLogicalIds (): string[] {
return Object
.values(this.data.check)
.filter((construct: Construct) => construct instanceof HeartbeatMonitor)
.map((construct: Check) => construct.logicalId)
}
}
export interface ConstructExport {
type: string
logicalId: string
filePath: string
exportName: string
}
export type CheckFilter = (check: Check) => boolean
export interface SharedFile {
path: string
content: string
}
export type SharedFileRef = number
export class Session {
static loader: FileLoader = new MixedFileLoader(
new NativeFileLoader(),
new JitiFileLoader(),
new TSNodeFileLoader(),
)
static project?: Project
static basePath?: string
static contextPath?: string
static checkDefaults?: CheckConfigDefaults
static checkFilter?: CheckFilter
static browserCheckDefaults?: CheckConfigDefaults
static multiStepCheckDefaults?: CheckConfigDefaults
static checkFilePath?: string
static checkFileAbsolutePath?: string
static availableRuntimes: Record<string, Runtime>
static defaultRuntimeId?: string
static verifyRuntimeDependencies = true
static loadingChecklyConfigFile: boolean
static checklyConfigFileConstructs?: Construct[]
static privateLocations: PrivateLocationApi[]
static parsers = new Map<string, Parser>()
static constructExports: ConstructExport[] = []
static ignoreDirectoriesMatch: string[] = []
static currentCommand?: 'pw-test' | 'test' | 'deploy'
static includeFlagProvided?: boolean
static packageManager: PackageManager = npmPackageManager
static workspace: Result<Workspace, Error> = Err(new Error(`Workspace support not initialized`))
static reset () {
this.project = undefined
this.basePath = undefined
this.contextPath = undefined
this.checkDefaults = undefined
this.checkFilter = undefined
this.browserCheckDefaults = undefined
this.multiStepCheckDefaults = undefined
this.checkFilePath = undefined
this.checkFileAbsolutePath = undefined
this.availableRuntimes = {}
this.defaultRuntimeId = undefined
this.verifyRuntimeDependencies = true
this.loadingChecklyConfigFile = false
this.checklyConfigFileConstructs = undefined
this.privateLocations = []
this.parsers = new Map<string, Parser>()
this.constructExports = []
this.ignoreDirectoriesMatch = []
this.packageManager = npmPackageManager
this.workspace = Err(new Error(`Workspace support not initialized`))
this.resetSharedFiles()
}
static async loadFile<T = unknown> (filePath: string): Promise<T> {
const loader = this.loader
if (loader === undefined) {
throw new Error(`Session has no loader set`)
}
if (!loader.isAuthoritativeFor(filePath)) {
throw new Error(`Unable to find a compatible loader for file '${filePath}'`)
}
try {
const moduleExports = await loader.loadFile<Record<string, any>>(filePath)
// Register all exported constructs we find.
for (const [exportName, value] of Object.entries(moduleExports ?? {})) {
if (value instanceof Construct) {
this.constructExports.push({
type: value.type,
logicalId: value.logicalId,
filePath,
exportName,
})
}
}
const defaultExport = moduleExports?.default ?? moduleExports
if (typeof defaultExport === 'function') {
return await defaultExport()
}
return defaultExport
} catch (err: any) {
throw new Error(`Error loading file '${filePath}'\n${err.stack}`)
}
}
static registerConstruct (construct: Construct) {
if (Session.project) {
Session.project.addResource(construct.type, construct.logicalId, construct)
} else if (Session.loadingChecklyConfigFile && construct.allowInChecklyConfig()) {
Session.checklyConfigFileConstructs!.push(construct)
} else {
throw new Error('Internal Error: Session is not properly configured for using a construct. Please contact Checkly support at support@checklyhq.com.')
}
}
static validateCreateConstruct (construct: Construct) {
if (construct.type === Project.__checklyType) {
// Creating the construct is allowed - We're creating the project.
} else if (Session.project) {
// Creating the construct is allowed - We're in the process of parsing the project.
} else if (Session.loadingChecklyConfigFile && construct.allowInChecklyConfig()) {
// Creating the construct is allowed - We're in the process of parsing the Checkly config.
} else if (Session.loadingChecklyConfigFile) {
throw new Error(`Creating a ${construct.constructor.name} construct in the Checkly config file isn't supported.`)
} else {
throw new Error(`Unable to create a construct '${construct.constructor.name}' outside a Checkly CLI project.`)
}
}
static async getPrivateLocations () {
if (!Session.privateLocations) {
const { data: privateLocations } = await api.privateLocations.getAll()
Session.privateLocations = privateLocations
}
return Session.privateLocations
}
static getRuntime (runtimeId?: string): Runtime | undefined {
const effectiveRuntimeId = runtimeId ?? Session.defaultRuntimeId
if (effectiveRuntimeId === undefined) {
throw new Error('Internal Error: Account default runtime is not set. Please contact Checkly support at support@checklyhq.com.')
}
return Session.availableRuntimes[effectiveRuntimeId]
}
static getParser (runtime: Runtime): Parser {
const cachedParser = Session.parsers.get(runtime.name)
if (cachedParser !== undefined) {
return cachedParser
}
const parser = new Parser({
supportedNpmModules: Object.keys(runtime.dependencies),
checkUnsupportedModules: Session.verifyRuntimeDependencies,
workspace: Session.workspace.ok(),
})
Session.parsers.set(runtime.name, parser)
return parser
}
static relativePosixPath (filePath: string): string {
return pathToPosix(path.relative(Session.basePath!, filePath))
}
static contextRelativePosixPath (filePath: string): string {
return pathToPosix(path.relative(Session.contextPath!, filePath))
}
static sharedFileRefs = new Map<string, SharedFileRef>()
static sharedFiles: SharedFile[] = []
static registerSharedFile (file: SharedFile): SharedFileRef {
const ref = Session.sharedFileRefs.get(file.path)
if (ref !== undefined) {
return ref
}
const newRef = Session.sharedFiles.push(file) - 1
Session.sharedFileRefs.set(file.path, newRef)
return newRef
}
static resetSharedFiles (): void {
Session.sharedFileRefs.clear()
Session.sharedFiles.splice(0)
}
}