/
index.ts
405 lines (353 loc) · 12.8 KB
/
index.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
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
import * as path from 'path'
import { typescript, Project, javascript, JsonFile } from 'projen'
import { JobPermission, JobStep } from 'projen/lib/github/workflows-model'
// eslint-disable-next-line import/no-extraneous-dependencies
import { pathsToModuleNameMapper } from 'ts-jest'
const TURBO_CACHE_DIR = './node_modules/.cache/turbo'
export interface TurborepoPipelineConfig {
/**
* The list of tasks that this task depends on.
*
* Prefixing a task in `dependsOn` with a `^` tells `turbo` that this pipeline task depends on the
* package's topological dependencies completing the task with the `^` prefix first (e.g. "a
* package's `build` tasks should only run once all of its `dependencies` and `devDependencies`
* have completed their own `build` commands").
*
* Items in `dependsOn` without `^` prefix, express the relationships between tasks at the package
* level (e.g. "a package's `test` and `lint` commands depend on `build` being completed first").
*/
readonly dependsOn?: string[];
/**
* Defaults to `["dist/**", "build/**"]`. The set of glob patterns of a task's cacheable
* filesystem outputs.
*
* Note: `turbo` automatically logs `stderr`/`stdout` to `.turbo/run-<task>.log`. This file is
* _always_ treated as a cacheable artifact and never needs to be specified.
*
* Passing an empty array can be used to tell `turbo` that a task is a side-effect and thus
* doesn't emit any filesystem artifacts (e.g. like a linter), but you still want to cache its
* logs (and treat them like an artifact).
*/
readonly outputs?: string[];
/**
* Whether or not to cache the task `outputs`.
*
* Setting `cache` to false is useful for daemon or long-running "watch" or development mode tasks
* that you don't want to cache.
*
* @default true
*/
readonly cache?: boolean;
}
export interface TurborepoConfig {
/**
* A list of globs for implicit global hash dependencies. The contents of these files will be
* included in the global hashing algorithm. This is useful for busting the cache based on `.env`
* files (not in Git) or any root level file that impacts package tasks (but are not represented
* in the traditional dependency graph (e.g. a root `tsconfig.json`, `jest.config.js`, `.eslintrc`
* , etc.)).
*
* @see https://turborepo.org/docs/reference/configuration#globaldependencies
*/
readonly globalDependencies?: string[];
/**
* An object representing the task dependency graph of your project. `turbo` interprets these
* conventions to properly schedule, execute, and cache the outputs of tasks in your project
*
* Each key in the `pipeline` object is the name of a task that can be executed by `turbo run`. If
* `turbo` finds a workspace package with a `package.json` `scripts` object with a matching key,
* it will apply the pipeline task configuration to that NPM script during execution. This allows
* you to use `pipeline` to set conventions across your entire Turborepo.
*
* @see https://turborepo.org/docs/reference/configuration#pipeline
*/
readonly pipeline?: Record<string, TurborepoPipelineConfig>;
}
interface TurborepoConfigInternal extends TurborepoConfig{
/**
* The base branch or your git repository.
* Git is used by turbo in its hashing algorithm and `--since` CLI flag.
*
* @default 'origin/master'
*
* @see https://turborepo.org/docs/reference/configuration#basebranch
*/
readonly baseBranch: string;
/**
* The NPM client in-use in your project.
*
* @default yarn
*
* @see https://turborepo.org/docs/reference/configuration#npmclient
*/
readonly npmClient?: string;
}
export interface TurborepoProjectOptions extends typescript.TypeScriptProjectOptions {
/**
* Turborepo config options.
*
* @default {}
*/
readonly turbo?: TurborepoConfig;
/**
* Add TypeScript path maps in the root project for sub-projects.
*
* @default false
* @experimental
*/
readonly pathMapping?: boolean;
/**
* Add jest config for `moduleNameMapper`.
*
* @see https://jestjs.io/docs/configuration#modulenamemapper-objectstring-string--arraystring
* @see https://kulshekhar.github.io/ts-jest/docs/getting-started/paths-mapping/
*
* @default false
* @experimental
*/
readonly jestModuleNameMapper?: boolean;
/**
* Adds TypeScript project references for each sub-project that depends on other sub-project.
*
* @see https://www.typescriptlang.org/docs/handbook/project-references.html
*
* @default false
* @experimental
*/
readonly projectReferences?: boolean;
/**
* **GitHub Build Workflows**
*
* Adds parallel GitHub Build workflows for each sub-project.
*
* @default false
* @experimental
*/
readonly parallelWorkflows?: boolean;
}
const exp = (val: string) => ['${{', val, '}}'].join(' ')
export class TurborepoProject extends typescript.TypeScriptProject {
private readonly pathMapping: boolean
private readonly projectReferences: boolean
private readonly jestModuleNameMapper: boolean
private readonly parallelWorkflows: boolean
private readonly setupNodeStep: JobStep
constructor(options: TurborepoProjectOptions) {
const setupNodeStep: JobStep = {
name: 'Setup node',
uses: 'actions/setup-node@v2',
with: {},
}
super({
...options,
jest: false,
sampleCode: false,
package: false,
workflowBootstrapSteps: [
setupNodeStep,
],
})
// Because we do not know the value of `this.package.lockFile` before super, we cannot
// add the cache key which uses the lockfile name, we add it later
if (setupNodeStep && setupNodeStep.with) {
Object.assign(setupNodeStep.with, {
// https://github.com/actions/setup-node#caching-packages-dependencies
'cache': this.package.packageManager,
'cache-dependency-path': `**/${this.package.lockFile}`,
})
}
this.setupNodeStep = setupNodeStep
this.pathMapping = options.pathMapping ?? false
this.projectReferences = options.projectReferences ?? false
this.jestModuleNameMapper = options.jestModuleNameMapper ?? false
this.parallelWorkflows = options.parallelWorkflows ?? false
/**
* Adds itself as a depdency, so that we have it in the consuming project, and
* can import it inside the projenrc file.
*/
this.addDevDeps('projen-turborepo')
/**
* Add turborepo as a dependency so we have the CLI.
*/
this.addDevDeps('turbo')
/**
* Turborepo cache directory.
*/
this.gitignore.addPatterns('.turbo')
/**
* Finally, turborepo config.
*
* @see https://turborepo.org/docs/reference/configuration
*/
const outputs = ['build', 'dist', 'lib', 'storybook-static'].sort().map((dir) => `${dir}/**`)
const turbo: TurborepoConfigInternal = {
npmClient: options.packageManager,
// TODO: Cannot get the value set in the projenrc file.
// @see https://github.com/projen/projen/issues/1427
baseBranch: `origin/${options.defaultReleaseBranch || 'master'}`,
...options.turbo,
pipeline: {
build: {
dependsOn: ['^build'],
outputs,
},
compile: {
dependsOn: ['^compile'],
outputs,
},
test: {
dependsOn: ['^build'],
outputs: ['coverage/**', 'test-reports/**'],
},
eslint: {
outputs: [],
},
watch: {
cache: false,
},
...options.turbo?.pipeline,
},
}
this.package.addField('turbo', turbo)
/**
* Monorepo root package is always private!
*/
this.package.addField('private', true)
/**
* @see https://www.typescriptlang.org/tsconfig/composite.html
*/
if (this.projectReferences) {
for (const tsconfig of [this.tsconfig, this.tsconfigDev]) {
tsconfig?.file.addOverride('compilerOptions.composite', true)
}
}
}
private get subProjects(): Project[] {
// https://github.com/projen/projen/issues/1433
// @ts-ignore
const subProjects: Project[] = this.subprojects || []
return subProjects.sort((a, b) => a.name.localeCompare(b.name))
}
preSynthesize() {
const { subProjects } = this
const workspaces: string[] = []
const paths: Record<string, string[]> = {}
const packageNameSubProjectMap: Record<string, Project> = {}
for (const subProject of subProjects) {
const workspace = path.relative(this.outdir, subProject.outdir)
workspaces.push(workspace)
if (subProject instanceof javascript.NodeProject) {
paths[subProject.package.packageName] = [`${workspace}/src`]
packageNameSubProjectMap[subProject.package.packageName] = subProject
}
}
if (workspaces.length > 0) {
this.package.addField('workspaces', workspaces)
// Adds VS Code settings for ESLint to recognize sub-projects
// https://github.com/Microsoft/vscode-eslint#settings-options
new JsonFile(this, '.vscode/settings.json', {
obj: {
eslint: {
workingDirectories: workspaces.map((workspace) => `./${workspace}`),
},
},
})
}
// Adds npm install as the last step to the built-in build job, so that we cache the deps
// for future steps.
if (this.parallelWorkflows) {
const matrixScopeKey = 'scope'
const matrixScope = exp(`matrix.${matrixScopeKey}`)
const nodeModulesCacheStep: JobStep = {
name: 'Cache workspace node_modules',
uses: 'actions/cache@v2',
with: {
path: [
...workspaces.map((workspace) => `./${workspace}/node_modules`),
].join('\n'),
// use the SHA for cache key, as we only need to keep the cache between the jobs
key: exp('github.sha'),
},
}
this.buildWorkflow?.addPostBuildSteps(
nodeModulesCacheStep,
)
this.buildWorkflow?.addPostBuildJob('turbo', {
name: 'build',
runsOn: ['ubuntu-latest'],
permissions: { contents: JobPermission.READ },
steps: [
{
name: 'Checkout',
uses: 'actions/checkout@v2',
},
this.setupNodeStep,
nodeModulesCacheStep,
{
name: 'Build',
run: `npx turbo run build --scope=${matrixScope} --include-dependencies --cache-dir="${TURBO_CACHE_DIR}"`,
},
],
strategy: {
failFast: true,
matrix: {
domain: {
[matrixScopeKey]: Object.keys(packageNameSubProjectMap),
},
},
},
})
}
for (const subProject of subProjects) {
const packageNames = Object.keys(packageNameSubProjectMap)
if (subProject instanceof typescript.TypeScriptProject) {
const depProjects = subProject
.deps
.all
.filter(({ name }) => packageNames.includes(name))
.map(({ name }) => packageNameSubProjectMap[name])
const references = depProjects
.map(({ outdir }) => path.relative(subProject.outdir, outdir))
.map((p) => ({ path: p }))
const pathMappings: Record<string, string[]> = {}
for (const depProject of depProjects) {
if (depProject instanceof javascript.NodeProject) {
pathMappings[depProject.package.packageName] = [
path.relative(subProject.outdir, depProject.outdir),
]
}
}
for (const tsconfig of [subProject.tsconfig, subProject.tsconfigDev]) {
if (this.pathMapping) {
tsconfig?.file.addOverride('compilerOptions.baseUrl', '.')
for (const [packageName, packagePath] of Object.entries(pathMappings)) {
tsconfig?.file.addOverride(`compilerOptions.paths.${packageName}`, [`${packagePath}/src`])
}
}
if (this.projectReferences && references.length > 0) {
tsconfig?.file.addOverride('references', references)
for (const depProject of depProjects) {
if (depProject instanceof typescript.TypeScriptProject) {
for (const depTsconfig of [depProject.tsconfig, depProject.tsconfigDev]) {
depTsconfig?.file.addOverride('compilerOptions.composite', true)
}
}
}
}
}
if (this.jestModuleNameMapper && depProjects.length > 0 && subProject.jest) {
const pathsToModuleNameMappings: Record<string, string[]> = {}
for (const [moduleName, modulePath] of Object.entries(pathMappings)) {
pathsToModuleNameMappings[moduleName] = [[modulePath, 'src'].join('/')]
}
Object.assign(subProject.jest.config, {
moduleNameMapper: {
...subProject.jest.config?.moduleNameMapper,
...pathsToModuleNameMapper(pathsToModuleNameMappings, { prefix: '<rootDir>' }),
},
})
}
}
}
}
}