/
jsii-project.ts
499 lines (421 loc) · 14.4 KB
/
jsii-project.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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
import { JsiiPacmakTarget, JSII_TOOLCHAIN } from "./consts";
import { JsiiDocgen } from "./jsii-docgen";
import { Task } from "..";
import { Job, Step } from "../github/workflows-model";
import { Eslint, NodePackageManager } from "../javascript";
import {
CommonPublishOptions,
GoPublishOptions,
MavenPublishOptions,
NugetPublishOptions,
PyPiPublishOptions,
} from "../release";
import { TypeScriptProject, TypeScriptProjectOptions } from "../typescript";
import { deepMerge } from "../util";
const EMAIL_REGEX =
/(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/;
const URL_REGEX =
/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/;
const REPO_TEMP_DIRECTORY = ".repo";
export interface JsiiProjectOptions extends TypeScriptProjectOptions {
/**
* @default "."
*/
readonly rootdir?: string;
/**
* Git repository URL.
* @default $GIT_REMOTE
*/
readonly repositoryUrl: string;
/**
* The name of the library author.
* @default $GIT_USER_NAME
*/
readonly author: string;
/**
* Email or URL of the library author.
* @default $GIT_USER_EMAIL
*/
readonly authorAddress: string;
/**
* Publish to maven
* @default - no publishing
*/
readonly publishToMaven?: JsiiJavaTarget;
/**
* Publish to pypi
* @default - no publishing
*/
readonly publishToPypi?: JsiiPythonTarget;
/**
* Publish Go bindings to a git repository.
* @default - no publishing
*/
readonly publishToGo?: JsiiGoTarget;
/**
* @deprecated use `publishToPyPi`
*/
readonly python?: JsiiPythonTarget;
/**
* Publish to NuGet
* @default - no publishing
*/
readonly publishToNuget?: JsiiDotNetTarget;
/**
* @deprecated use `publishToNuget`
*/
readonly dotnet?: JsiiDotNetTarget;
/**
* Automatically run API compatibility test against the latest version published to npm after compilation.
*
* - You can manually run compatibility tests using `yarn compat` if this feature is disabled.
* - You can ignore compatibility failures by adding lines to a ".compatignore" file.
*
* @default false
*/
readonly compat?: boolean;
/**
* Name of the ignore file for API compatibility tests.
*
* @default ".compatignore"
*/
readonly compatIgnore?: string;
/**
* Accepts a list of glob patterns. Files matching any of those patterns will be excluded from the TypeScript compiler input.
*
* By default, jsii will include all *.ts files (except .d.ts files) in the TypeScript compiler input.
* This can be problematic for example when the package's build or test procedure generates .ts files
* that cannot be compiled with jsii's compiler settings.
*/
readonly excludeTypescript?: string[];
/**
* File path for generated docs.
* @default "API.md"
*/
readonly docgenFilePath?: string;
/**
* Emit a compressed version of the assembly
* @default false
*/
readonly compressAssembly?: boolean;
}
export enum Stability {
EXPERIMENTAL = "experimental",
STABLE = "stable",
DEPRECATED = "deprecated",
}
export interface JsiiJavaTarget extends MavenPublishOptions {
readonly javaPackage: string;
readonly mavenGroupId: string;
readonly mavenArtifactId: string;
}
export interface JsiiPythonTarget extends PyPiPublishOptions {
readonly distName: string;
readonly module: string;
}
export interface JsiiDotNetTarget extends NugetPublishOptions {
readonly dotNetNamespace: string;
readonly packageId: string;
readonly iconUrl?: string;
}
/**
* Go target configuration
*/
export interface JsiiGoTarget extends GoPublishOptions {
/**
* The name of the target go module.
*
* @example github.com/owner/repo
* @example github.com/owner/repo/subdir
*/
readonly moduleName: string;
/**
* The name of the go package.
*
* @default - derived from the module name
*/
readonly packageName?: string;
}
/**
* Multi-language jsii library project
*
* @pjid jsii
*/
export class JsiiProject extends TypeScriptProject {
public readonly eslint?: Eslint;
private readonly packageAllTask: Task;
constructor(options: JsiiProjectOptions) {
const { authorEmail, authorUrl } = parseAuthorAddress(options);
const defaultOptions = {
repository: options.repositoryUrl,
authorName: options.author,
authorEmail,
authorUrl,
jestOptions: {
jestVersion: "^27",
},
};
const forcedOptions = {
releaseToNpm: false, // we have a jsii release workflow
disableTsconfig: true, // jsii generates its own tsconfig.json
docgen: false, // we use jsii-docgen here so disable typescript docgen
};
const mergedOptions = deepMerge([
defaultOptions,
options,
forcedOptions,
]) as TypeScriptProjectOptions;
super(mergedOptions);
const srcdir = this.srcdir;
const libdir = this.libdir;
this.addFields({ types: `${libdir}/index.d.ts` });
const compressAssembly = options.compressAssembly ?? false;
// this is an unhelpful warning
const jsiiFlags = ["--silence-warnings=reserved-word"];
if (compressAssembly) {
jsiiFlags.push("--compress-assembly");
}
const compatIgnore = options.compatIgnore ?? ".compatignore";
this.addFields({ stability: options.stability ?? Stability.STABLE });
if (options.stability === Stability.DEPRECATED) {
this.addFields({ deprecated: true });
}
const compatTask = this.addTask("compat", {
description: "Perform API compatibility check against latest version",
exec: `jsii-diff npm:$(node -p "require(\'./package.json\').name") -k --ignore-file ${compatIgnore} || (echo "\nUNEXPECTED BREAKING CHANGES: add keys such as \'removed:constructs.Node.of\' to ${compatIgnore} to skip.\n" && exit 1)`,
});
const compat = options.compat ?? false;
if (compat) {
this.compileTask.spawn(compatTask);
}
this.compileTask.reset(["jsii", ...jsiiFlags].join(" "));
this.watchTask.reset(["jsii", "-w", ...jsiiFlags].join(" "));
this.packageAllTask = this.addTask("package-all", {
description: "Packages artifacts for all target languages",
});
// in jsii we consider the entire repo (post build) as the build artifact
// which is then used to create the language bindings in separate jobs.
const prepareRepoForCI = [
`rsync -a . .repo --exclude .git --exclude node_modules`,
`rm -rf ${this.artifactsDirectory}`,
`mv .repo ${this.artifactsDirectory}`,
].join(" && ");
// when running inside CI we just prepare the repo for packaging, which
// takes place in separate tasks.
// outside of CI (i.e locally) we simply package all targets.
this.packageTask.reset(
`if [ ! -z \${CI} ]; then ${prepareRepoForCI}; else ${this.runTaskCommand(
this.packageAllTask
)}; fi`
);
const targets: Record<string, any> = {};
const jsii: any = {
outdir: this.artifactsDirectory,
targets,
tsc: {
outDir: libdir,
rootDir: srcdir,
},
};
if (options.excludeTypescript) {
jsii.excludeTypescript = options.excludeTypescript;
}
this.addFields({ jsii });
this.release?.publisher.addGitHubPrePublishingSteps(
{
name: "Prepare Repository",
run: `mv ${this.artifactsDirectory} ${REPO_TEMP_DIRECTORY}`,
},
{
name: "Collect GitHub Metadata",
run: `mv ${REPO_TEMP_DIRECTORY}/${this.artifactsDirectory} ${this.artifactsDirectory}`,
}
);
const extraJobOptions: Partial<Job> = options.workflowRunsOn
? { runsOn: options.workflowRunsOn }
: {};
if (options.releaseToNpm != false) {
const task = this.addPackagingTask("js");
this.release?.publisher.publishToNpm({
...this.pacmakForLanguage("js", task),
registry: this.package.npmRegistry,
npmTokenSecret: this.package.npmTokenSecret,
codeArtifactOptions: options.codeArtifactOptions,
});
this.addPackagingTarget("js", task, extraJobOptions);
}
// we cannot call an option `java` because the java code generated by jsii
// does not compile due to a conflict between this option name and the `java`
// package (e.g. when `java.util.Objects` is referenced).
if ("java" in options) {
throw new Error('the "java" option is now called "publishToMaven"');
}
if (options.publishToMaven) {
targets.java = {
package: options.publishToMaven.javaPackage,
maven: {
groupId: options.publishToMaven.mavenGroupId,
artifactId: options.publishToMaven.mavenArtifactId,
},
};
const task = this.addPackagingTask("java");
this.release?.publisher.publishToMaven({
...this.pacmakForLanguage("java", task),
...options.publishToMaven,
});
this.addPackagingTarget("java", task, extraJobOptions);
}
const pypi = options.publishToPypi ?? options.python;
if (pypi) {
targets.python = {
distName: pypi.distName,
module: pypi.module,
};
const task = this.addPackagingTask("python");
this.release?.publisher.publishToPyPi({
...this.pacmakForLanguage("python", task),
...pypi,
});
this.addPackagingTarget("python", task, extraJobOptions);
}
const nuget = options.publishToNuget ?? options.dotnet;
if (nuget) {
targets.dotnet = {
namespace: nuget.dotNetNamespace,
packageId: nuget.packageId,
iconUrl: nuget.iconUrl,
};
const task = this.addPackagingTask("dotnet");
this.release?.publisher.publishToNuget({
...this.pacmakForLanguage("dotnet", task),
...nuget,
});
this.addPackagingTarget("dotnet", task, extraJobOptions);
}
const golang = options.publishToGo;
if (golang) {
targets.go = {
moduleName: golang.moduleName,
packageName: golang.packageName,
};
const task = this.addPackagingTask("go");
this.release?.publisher.publishToGo({
...this.pacmakForLanguage("go", task),
...golang,
});
this.addPackagingTarget("go", task, extraJobOptions);
}
this.addDevDeps("jsii", "jsii-diff", "jsii-pacmak");
this.gitignore.exclude(".jsii", "tsconfig.json");
this.npmignore?.include(".jsii");
if (options.docgen ?? true) {
new JsiiDocgen(this, { filePath: options.docgenFilePath });
}
// jsii updates .npmignore, so we make it writable
if (this.npmignore) {
this.npmignore.readonly = false;
}
// https://github.com/projen/projen/issues/2165
this.package.addPackageResolutions("@types/prettier@2.6.0");
// https://github.com/projen/projen/issues/2264
this.package.addPackageResolutions("@types/babel__traverse@7.18.2");
}
/**
* Adds a target language to the build workflow and creates a package task.
* @param language
* @returns
*/
private addPackagingTarget(
language: JsiiPacmakTarget,
packTask: Task,
extraJobOptions: Partial<Job>
) {
if (!this.buildWorkflow) {
return;
}
const pacmak = this.pacmakForLanguage(language, packTask);
this.buildWorkflow.addPostBuildJob(`package-${language}`, {
runsOn: ["ubuntu-latest"],
permissions: {},
tools: {
node: { version: this.nodeVersion ?? "16.x" },
...pacmak.publishTools,
},
steps: pacmak.prePublishSteps ?? [],
...extraJobOptions,
});
}
private addPackagingTask(language: JsiiPacmakTarget): Task {
const packageTask = this.tasks.addTask(`package:${language}`, {
description: `Create ${language} language bindings`,
});
packageTask.exec(`jsii-pacmak -v --target ${language}`);
this.packageAllTask.spawn(packageTask);
return packageTask;
}
private pacmakForLanguage(
target: JsiiPacmakTarget,
packTask: Task
): CommonPublishOptions {
// at this stage, `artifactsDirectory` contains the prebuilt repository.
// for the publishing to work seamlessely, that directory needs to contain the actual artifact.
// so we move the repo, create the artifact, and put it in the expected place.
const prePublishSteps: Array<Step> = [];
prePublishSteps.push(...this.workflowBootstrapSteps);
if (this.package.packageManager === NodePackageManager.PNPM) {
prePublishSteps.push({
name: "Setup pnpm",
uses: "pnpm/action-setup@v2.2.4",
with: { version: this.package.pnpmVersion },
});
}
prePublishSteps.push(
{
name: "Prepare Repository",
run: `mv ${this.artifactsDirectory} ${REPO_TEMP_DIRECTORY}`,
},
{
name: "Install Dependencies",
run: `cd ${REPO_TEMP_DIRECTORY} && ${this.package.installCommand}`,
},
{
name: `Create ${target} artifact`,
run: `cd ${REPO_TEMP_DIRECTORY} && npx projen ${packTask.name}`,
},
{
name: `Collect ${target} Artifact`,
run: `mv ${REPO_TEMP_DIRECTORY}/${this.artifactsDirectory} ${this.artifactsDirectory}`,
}
);
return {
publishTools: JSII_TOOLCHAIN[target],
prePublishSteps,
};
}
}
function parseAuthorAddress(options: JsiiProjectOptions) {
let authorEmail = options.authorEmail;
let authorUrl = options.authorUrl;
if (options.authorAddress) {
if (options.authorEmail && options.authorEmail !== options.authorAddress) {
throw new Error(
"authorEmail is deprecated and cannot be used in conjunction with authorAddress"
);
}
if (options.authorUrl && options.authorUrl !== options.authorAddress) {
throw new Error(
"authorUrl is deprecated and cannot be used in conjunction with authorAddress."
);
}
if (EMAIL_REGEX.test(options.authorAddress)) {
authorEmail = options.authorAddress;
} else if (URL_REGEX.test(options.authorAddress)) {
authorUrl = options.authorAddress;
} else {
throw new Error(
`authorAddress must be either an email address or a URL: ${options.authorAddress}`
);
}
}
return { authorEmail, authorUrl };
}