forked from microsoft/typescript-go
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHerebyfile.mjs
More file actions
1412 lines (1204 loc) · 46.3 KB
/
Herebyfile.mjs
File metadata and controls
1412 lines (1204 loc) · 46.3 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
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// @ts-check
import AdmZip from "adm-zip";
import chokidar from "chokidar";
import { $ as _$ } from "execa";
import { glob } from "glob";
import { task } from "hereby";
import assert from "node:assert";
import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
import url from "node:url";
import { parseArgs } from "node:util";
import os from "os";
import pLimit from "p-limit";
import pc from "picocolors";
import which from "which";
const __filename = url.fileURLToPath(new URL(import.meta.url));
const __dirname = path.dirname(__filename);
const isCI = !!process.env.CI;
const $pipe = _$({ verbose: "short" });
const $ = _$({ verbose: "short", stdio: "inherit" });
/**
* @param {string} name
* @param {boolean} defaultValue
* @returns {boolean}
*/
function parseEnvBoolean(name, defaultValue = false) {
name = "TSGO_HEREBY_" + name.toUpperCase();
const value = process.env[name];
if (!value) {
return defaultValue;
}
switch (value.toUpperCase()) {
case "1":
case "TRUE":
case "YES":
case "ON":
return true;
case "0":
case "FALSE":
case "NO":
case "OFF":
return false;
}
throw new Error(`Invalid value for ${name}: ${value}`);
}
const { values: rawOptions } = parseArgs({
args: process.argv.slice(2),
options: {
tests: { type: "string", short: "t" },
fix: { type: "boolean" },
debug: { type: "boolean" },
dirty: { type: "boolean" },
insiders: { type: "boolean" },
setPrerelease: { type: "string" },
forRelease: { type: "boolean" },
race: { type: "boolean", default: parseEnvBoolean("RACE") },
noembed: { type: "boolean", default: parseEnvBoolean("NOEMBED") },
concurrentTestPrograms: { type: "boolean", default: parseEnvBoolean("CONCURRENT_TEST_PROGRAMS") },
coverage: { type: "boolean", default: parseEnvBoolean("COVERAGE") },
},
strict: false,
allowPositionals: true,
allowNegative: true,
});
// We can't use parseArgs' strict mode as it errors on hereby's --tasks flag.
/**
* @typedef {{ [K in keyof typeof rawOptions as {} extends Record<K, 1> ? never : K]: typeof rawOptions[K] }} Options
*/
const options = /** @type {Options} */ (rawOptions);
if (options.forRelease && !options.setPrerelease) {
throw new Error("forRelease requires setPrerelease");
}
const defaultGoBuildTags = [
...(options.noembed ? ["noembed"] : []),
];
/**
* @param {...string} extra
* @returns {string[]}
*/
function goBuildTags(...extra) {
const tags = new Set(defaultGoBuildTags.concat(extra));
return tags.size ? [`-tags=${[...tags].join(",")}`] : [];
}
const goBuildFlags = [
...(options.race ? ["-race"] : []),
// https://github.com/go-delve/delve/blob/62cd2d423c6a85991e49d6a70cc5cb3e97d6ceef/Documentation/usage/dlv_exec.md?plain=1#L12
...(options.debug ? ["-gcflags=all=-N -l"] : []),
];
/**
* @template T
* @param {() => T} fn
* @returns {() => T}
*/
function memoize(fn) {
/** @type {T} */
let value;
return () => {
if (fn !== undefined) {
value = fn();
fn = /** @type {any} */ (undefined);
}
return value;
};
}
const typeScriptSubmodulePath = path.join(__dirname, "_submodules", "TypeScript");
const isTypeScriptSubmoduleCloned = memoize(() => {
try {
const stat = fs.statSync(path.join(typeScriptSubmodulePath, "package.json"));
if (stat.isFile()) {
return true;
}
}
catch {}
return false;
});
const warnIfTypeScriptSubmoduleNotCloned = memoize(() => {
if (!isTypeScriptSubmoduleCloned()) {
console.warn(pc.yellow("Warning: TypeScript submodule is not cloned; some tests may be skipped."));
}
});
function assertTypeScriptCloned() {
if (!isTypeScriptSubmoduleCloned()) {
throw new Error("_submodules/TypeScript does not exist; try running `git submodule update --init --recursive`");
}
}
const tools = new Map([
["gotest.tools/gotestsum", "latest"],
]);
/**
* @param {string} tool
*/
function isInstalled(tool) {
return !!which.sync(tool, { nothrow: true });
}
const builtLocal = "./built/local";
const libsDir = "./internal/bundled/libs";
const libsRegexp = /(?:^|[\\/])internal[\\/]bundled[\\/]libs[\\/]/;
/**
* @param {string} out
*/
async function generateLibs(out) {
await fs.promises.mkdir(out, { recursive: true });
const libs = await fs.promises.readdir(libsDir);
await Promise.all(libs.map(async lib => {
fs.promises.copyFile(path.join(libsDir, lib), path.join(out, lib));
}));
}
export const lib = task({
name: "lib",
description: "Copies the libs to built/local.",
run: () => generateLibs(builtLocal),
});
/**
* @param {object} [opts]
* @param {string} [opts.out]
* @param {AbortSignal} [opts.abortSignal]
* @param {Record<string, string | undefined>} [opts.env]
* @param {string[]} [opts.extraFlags]
*/
function buildTsgo(opts) {
opts ||= {};
const out = opts.out ?? "./built/local/";
return $({ cancelSignal: opts.abortSignal, env: opts.env })`go build ${goBuildFlags} ${opts.extraFlags ?? []} ${options.debug ? goBuildTags("noembed") : goBuildTags("noembed", "release")} -o ${out} ./cmd/tsgo`;
}
export const tsgoBuild = task({
name: "tsgo:build",
description: "Builds the tsgo binary.",
run: async () => {
await buildTsgo();
},
});
export const tsgo = task({
name: "tsgo",
dependencies: [lib, tsgoBuild],
});
export const local = task({
name: "local",
dependencies: [tsgo],
});
export const build = task({
name: "build",
dependencies: [local],
});
export const buildWatch = task({
name: "build:watch",
description: "Builds the tsgo binary and watches for changes.",
run: async () => {
await watchDebounced("build:watch", async (paths, abortSignal) => {
let libsChanged = false;
let goChanged = false;
if (paths) {
for (const p of paths) {
if (libsRegexp.test(p)) {
libsChanged = true;
}
else if (p.endsWith(".go")) {
goChanged = true;
}
if (libsChanged && goChanged) {
break;
}
}
}
else {
libsChanged = true;
goChanged = true;
}
if (libsChanged) {
console.log("Generating libs...");
await generateLibs(builtLocal);
}
if (goChanged) {
console.log("Building tsgo...");
await buildTsgo({ abortSignal });
}
}, {
paths: ["cmd", "internal"],
ignored: path => /[\\/]testdata[\\/]/.test(path),
});
},
});
export const cleanBuilt = task({
name: "clean:built",
hiddenFromTaskList: true,
run: () => rimraf("built"),
});
export const generate = task({
name: "generate",
description: "Runs go generate on the project.",
run: async () => {
assertTypeScriptCloned();
await $`go generate -v ./...`;
},
});
const coverageDir = path.join(__dirname, "coverage");
const ensureCoverageDirExists = memoize(() => {
if (options.coverage) {
fs.mkdirSync(coverageDir, { recursive: true });
}
});
/**
* @param {string} taskName
*/
function goTestFlags(taskName) {
ensureCoverageDirExists();
return [
...goBuildFlags,
...goBuildTags(),
...(options.tests ? [`-run=${options.tests}`] : []),
...(options.coverage ? [`-coverprofile=${path.join(coverageDir, "coverage." + taskName + ".out")}`, "-coverpkg=./..."] : []),
];
}
const goTestEnv = {
...(options.concurrentTestPrograms ? { TS_TEST_PROGRAM_SINGLE_THREADED: "false" } : {}),
// Go test caching takes a long time on Windows.
// https://github.com/golang/go/issues/72992
...(process.platform === "win32" ? { GOFLAGS: "-count=1" } : {}),
};
const goTestSumFlags = [
"--format-hide-empty-pkg",
...(!isCI ? ["--hide-summary", "skipped"] : []),
];
const $test = $({ env: goTestEnv });
/**
* @param {string} taskName
*/
function gotestsum(taskName) {
const args = isInstalled("gotestsum") ? ["gotestsum", ...goTestSumFlags, "--"] : ["go", "test"];
return args.concat(goTestFlags(taskName));
}
/**
* @param {string} taskName
*/
function goTest(taskName) {
return ["go", "test"].concat(goTestFlags(taskName));
}
async function runTests() {
warnIfTypeScriptSubmoduleNotCloned();
if (!options.dirty) {
await rimraf(localBaseline);
await fs.promises.mkdir(localBaseline, { recursive: true });
}
await $test`${gotestsum("tests")} ./... ${isCI ? ["--timeout=45m"] : []}`;
}
export const test = task({
name: "test",
description: "Runs all tests. This is the most typical test task to need.",
run: runTests,
});
async function runTestBenchmarks() {
warnIfTypeScriptSubmoduleNotCloned();
// Run the benchmarks once to ensure they compile and run without errors.
await $test`${goTest("benchmarks")} -run=- -bench=. -benchtime=1x ./...`;
}
export const testBenchmarks = task({
name: "test:benchmarks",
description: "Runs all benchmarks.",
run: runTestBenchmarks,
});
async function runTestTools() {
await $test({ cwd: path.join(__dirname, "_tools") })`${gotestsum("tools")} ./...`;
}
async function runTestAPI() {
await $`npm run -w @typescript/api test`;
}
export const testTools = task({
name: "test:tools",
description: "Runs all tests in the _tools module.",
run: runTestTools,
});
export const buildAPITests = task({
name: "build:api:test",
description: "Builds the @typescript/api tests.",
run: async () => {
await $`npm run -w @typescript/api build:test`;
},
});
export const testAPI = task({
name: "test:api",
description: "Runs the @typescript/api tests.",
dependencies: [tsgo, buildAPITests],
run: runTestAPI,
});
export const testAll = task({
name: "test:all",
description: "Runs ALL tests in the repo, including benchmarks, _tools, and the API tests.",
dependencies: [tsgo, buildAPITests],
run: async () => {
// Prevent interleaving by running these directly instead of in parallel.
await runTests();
await runTestBenchmarks();
await runTestTools();
await runTestAPI();
},
});
const customLinterPath = "./_tools/custom-gcl";
const customLinterHashPath = customLinterPath + ".hash";
const golangciLintPackage = memoize(() => {
const golangciLintYml = fs.readFileSync(".custom-gcl.yml", "utf8");
const pattern = /^version:\s*(v\d+\.\d+\.\d+).*$/m;
const match = pattern.exec(golangciLintYml);
if (!match) {
throw new Error("Expected version in .custom-gcl.yml");
}
const version = match[1];
const major = version.split(".")[0];
const versionSuffix = ["v0", "v1"].includes(major) ? "" : "/" + major;
return `github.com/golangci/golangci-lint${versionSuffix}/cmd/golangci-lint@${version}`;
});
const customlintHash = memoize(() => {
const files = glob.sync([
"./_tools/go.mod",
"./_tools/customlint/**/*",
"./.custom-gcl.yml",
], {
ignore: "**/testdata/**",
nodir: true,
absolute: true,
});
files.sort();
const hash = crypto.createHash("sha256");
for (const file of files) {
hash.update(file);
hash.update(fs.readFileSync(file));
}
return hash.digest("hex") + "\n";
});
const buildCustomLinter = memoize(async () => {
const hash = customlintHash();
if (
isInstalled(customLinterPath)
&& fs.existsSync(customLinterHashPath)
&& fs.readFileSync(customLinterHashPath, "utf8") === hash
) {
return;
}
await $`go run ${golangciLintPackage()} custom`;
await $`${customLinterPath} cache clean`;
fs.writeFileSync(customLinterHashPath, hash);
});
export const lint = task({
name: "lint",
description: "Runs golangci-lint.",
run: async () => {
await buildCustomLinter();
const lintArgs = ["run"];
if (defaultGoBuildTags.length) {
lintArgs.push("--build-tags", defaultGoBuildTags.join(","));
}
if (options.fix) {
lintArgs.push("--fix");
}
const resolvedCustomLinterPath = path.resolve(customLinterPath);
await $`${resolvedCustomLinterPath} ${lintArgs}`;
console.log("Linting _tools");
await $({ cwd: "./_tools" })`${resolvedCustomLinterPath} ${lintArgs}`;
},
});
export const installTools = task({
name: "install-tools",
description: "Installs optional tools for developing within the repo.",
run: async () => {
await Promise.all([
...[...tools].map(([tool, version]) => $`go install ${tool}${version ? `@${version}` : ""}`),
buildCustomLinter(),
]);
},
});
export const format = task({
name: "format",
description: "Formats the repo.",
run: async () => {
await $`dprint fmt`;
},
});
export const checkFormat = task({
name: "check:format",
description: "Checks that the repo is formatted.",
run: async () => {
await $`dprint check`;
},
});
/**
* @param {string} localBaseline Path to the local copy of the baselines
* @param {string} refBaseline Path to the reference copy of the baselines
*/
function baselineAcceptTask(localBaseline, refBaseline) {
/**
* @param {string} p
*/
function localPathToRefPath(p) {
const relative = path.relative(localBaseline, p);
return path.join(refBaseline, relative);
}
return async () => {
const toCopy = await glob(`${localBaseline}/**`, { nodir: true, ignore: `${localBaseline}/**/*.delete` });
for (const p of toCopy) {
const out = localPathToRefPath(p);
await fs.promises.mkdir(path.dirname(out), { recursive: true });
await fs.promises.copyFile(p, out);
}
const toDelete = await glob(`${localBaseline}/**/*.delete`, { nodir: true });
for (const p of toDelete) {
const out = localPathToRefPath(p).replace(/\.delete$/, "");
await rimraf(out);
await rimraf(p); // also delete the .delete file so that it no longer shows up in a diff tool.
}
};
}
const localBaseline = "testdata/baselines/local/";
const refBaseline = "testdata/baselines/reference/";
export const baselineAccept = task({
name: "baseline-accept",
description: "Makes the most recent test results the new baseline, overwriting the old baseline.",
run: baselineAcceptTask(localBaseline, refBaseline),
});
/**
* @param {fs.PathLike} p
*/
function rimraf(p) {
// The rimraf package uses maxRetries=10 on Windows, but Node's fs.rm does not have that special case.
return fs.promises.rm(p, { recursive: true, force: true, maxRetries: process.platform === "win32" ? 10 : 0 });
}
/** @typedef {{
* name: string;
* paths: string | string[];
* ignored?: (path: string) => boolean;
* run: (paths: Set<string>, abortSignal: AbortSignal) => void | Promise<unknown>;
* }} WatchTask */
void 0;
/**
* @param {string} name
* @param {(paths: Set<string> | undefined, abortSignal: AbortSignal) => void | Promise<unknown>} run
* @param {object} options
* @param {string | string[]} options.paths
* @param {(path: string) => boolean} [options.ignored]
* @param {string} [options.name]
*/
async function watchDebounced(name, run, options) {
let watching = true;
let running = true;
let lastChangeTimeMs = Date.now();
let changedDeferred = /** @type {Deferred<void>} */ (new Deferred());
let abortController = new AbortController();
const debouncer = new Debouncer(1_000, endRun);
const watcher = chokidar.watch(options.paths, {
ignored: options.ignored,
ignorePermissionErrors: true,
alwaysStat: true,
});
// The paths that have changed since the last run.
/** @type {Set<string> | undefined} */
let paths;
process.on("SIGINT", endWatchMode);
process.on("beforeExit", endWatchMode);
watcher.on("all", onChange);
while (watching) {
const promise = changedDeferred.promise;
const token = abortController.signal;
if (!token.aborted) {
running = true;
try {
const thePaths = paths;
paths = new Set();
await run(thePaths, token);
}
catch {
// ignore
}
running = false;
}
if (watching) {
console.log(pc.yellowBright(`[${name}] run complete, waiting for changes...`));
await promise;
}
}
console.log("end");
/**
* @param {'add' | 'addDir' | 'change' | 'unlink' | 'unlinkDir' | 'all' | 'ready' | 'raw' | 'error'} eventName
* @param {string} path
* @param {fs.Stats | undefined} stats
*/
function onChange(eventName, path, stats) {
switch (eventName) {
case "change":
case "unlink":
case "unlinkDir":
break;
case "add":
case "addDir":
// skip files that are detected as 'add' but haven't actually changed since the last time we ran.
if (stats && stats.mtimeMs <= lastChangeTimeMs) {
return;
}
break;
}
beginRun(path);
}
/**
* @param {string} path
*/
function beginRun(path) {
if (debouncer.empty) {
console.log(pc.yellowBright(`[${name}] changed due to '${path}', restarting...`));
if (running) {
console.log(pc.yellowBright(`[${name}] aborting in-progress run...`));
}
abortController.abort();
abortController = new AbortController();
}
debouncer.enqueue();
paths ??= new Set();
paths.add(path);
}
function endRun() {
lastChangeTimeMs = Date.now();
changedDeferred.resolve();
changedDeferred = /** @type {Deferred<void>} */ (new Deferred());
}
function endWatchMode() {
if (watching) {
watching = false;
console.log(pc.yellowBright(`[${name}] exiting watch mode...`));
abortController.abort();
watcher.close();
}
}
}
/**
* @template T
*/
export class Deferred {
constructor() {
/** @type {Promise<T>} */
this.promise = new Promise((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
});
}
}
export class Debouncer {
/**
* @param {number} timeout
* @param {() => Promise<any> | void} action
*/
constructor(timeout, action) {
this._timeout = timeout;
this._action = action;
}
get empty() {
return !this._deferred;
}
enqueue() {
if (this._timer) {
clearTimeout(this._timer);
this._timer = undefined;
}
if (!this._deferred) {
this._deferred = new Deferred();
}
this._timer = setTimeout(() => this.run(), 100);
return this._deferred.promise;
}
run() {
if (this._timer) {
clearTimeout(this._timer);
this._timer = undefined;
}
const deferred = this._deferred;
assert(deferred);
this._deferred = undefined;
try {
deferred.resolve(this._action());
}
catch (e) {
deferred.reject(e);
}
}
}
const getVersion = memoize(() => {
const f = fs.readFileSync("./internal/core/version.go", "utf8");
const match = f.match(/var version\s*=\s*"(\d+\.\d+\.\d+)(-[^"]+)?"/);
if (!match) {
throw new Error("Failed to extract version from version.go");
}
let version = match[1];
if (options.setPrerelease) {
version += `-${options.setPrerelease}`;
}
else if (match[2]) {
version += match[2];
}
return version;
});
const extensionDir = path.resolve("./_extension");
const builtNpm = path.resolve("./built/npm");
const builtVsix = path.resolve("./built/vsix");
const builtSignTmp = path.resolve("./built/sign-tmp");
const getSignTempDir = memoize(async () => {
const dir = path.resolve(builtSignTmp);
await rimraf(dir);
await fs.promises.mkdir(dir, { recursive: true });
return dir;
});
const cleanSignTempDirectory = task({
name: "clean:sign-tmp",
hiddenFromTaskList: true,
run: () => rimraf(builtSignTmp),
});
let signCount = 0;
/**
* @typedef {{
* SignFileRecordList: {
* SignFileList: { SrcPath: string; DstPath: string | null }[];
* Certs: Cert;
* MacAppName: string | undefined
* }[]
* }} DDSignFileList
*
* @param {DDSignFileList} filelist
*/
async function sign(filelist, unchangedOutputOkay = false) {
let data = JSON.stringify(filelist, undefined, 4);
console.log("filelist:", data);
if (!process.env.MBSIGN_APPFOLDER) {
console.log(pc.yellow("Faking signing because MBSIGN_APPFOLDER is not set."));
// Fake signing for testing.
for (const record of filelist.SignFileRecordList) {
for (const file of record.SignFileList) {
const src = file.SrcPath;
const dst = file.DstPath ?? src;
if (!fs.existsSync(src)) {
throw new Error(`Source file does not exist: ${src}`);
}
const dstDir = path.dirname(dst);
if (!fs.existsSync(dstDir)) {
throw new Error(`Destination directory does not exist: ${dstDir}`);
}
if (dst.endsWith(".sig")) {
console.log(`Faking signature for ${src} -> ${dst}`);
// No great way to fake a signature.
await fs.promises.writeFile(dst, "fake signature");
}
else {
if (src === dst) {
console.log(`Faking signing ${src}`);
}
else {
console.log(`Faking signing ${src} -> ${dst}`);
}
const contents = await fs.promises.readFile(src);
await fs.promises.writeFile(dst, contents);
}
}
}
return;
}
const signingWorkaround = true;
/** @type {{ source: string; target: string }[]} */
const signingWorkaroundFiles = [];
if (signingWorkaround) {
// DstPath is currently broken in the signing tool.
// Copy all of the files to a new tempdir and then leave DstPath unset
// so that it's overwritten, then move the file to the destination.
console.log("Working around DstPath bug");
/** @type {DDSignFileList} */
const newFileList = {
SignFileRecordList: filelist.SignFileRecordList.map(list => {
return {
Certs: list.Certs,
SignFileList: list.SignFileList.map(file => {
const dstPath = file.DstPath;
if (dstPath === null) {
return file;
}
const src = file.SrcPath;
// File extensions must be preserved; use a prefix.
const dstPathTemp = `${path.dirname(src)}/signing-temp-${path.basename(src)}`;
console.log(`Copying: ${src} -> ${dstPathTemp}`);
fs.cpSync(src, dstPathTemp);
signingWorkaroundFiles.push({ source: dstPathTemp, target: dstPath });
return {
SrcPath: dstPathTemp,
DstPath: null,
};
}),
MacAppName: list.MacAppName,
};
}),
};
data = JSON.stringify(newFileList, undefined, 4);
console.log("new filelist:", data);
}
/** @type {Map<string, string>} */
const srcHashes = new Map();
for (const record of filelist.SignFileRecordList) {
for (const file of record.SignFileList) {
const src = file.SrcPath;
const dst = file.DstPath ?? src;
if (!fs.existsSync(src)) {
throw new Error(`Source file does not exist: ${src}`);
}
const hash = crypto.createHash("sha256").update(fs.readFileSync(src)).digest("hex");
srcHashes.set(src, hash);
console.log(`Will sign ${src} -> ${dst}`);
console.log(` sha256: ${hash}`);
}
}
const tmp = await getSignTempDir();
const filelistPath = path.resolve(tmp, `signing-filelist-${signCount++}.json`);
await fs.promises.writeFile(filelistPath, data);
try {
const dll = path.join(process.env.MBSIGN_APPFOLDER, "DDSignFiles.dll");
const filelistFlag = `/filelist:${filelistPath}`;
await $`dotnet ${dll} -- ${filelistFlag}`;
}
finally {
await fs.promises.unlink(filelistPath);
}
if (signingWorkaround) {
// Now, copy the files back.
for (const { source, target } of signingWorkaroundFiles) {
console.log(`Moving signed file: ${source} -> ${target}`);
await fs.promises.rename(source, target);
}
}
/** @type {string[]} */
let failures = [];
for (const record of filelist.SignFileRecordList) {
for (const file of record.SignFileList) {
const src = file.SrcPath;
const dst = file.DstPath ?? src;
if (!fs.existsSync(dst)) {
failures.push(`Signed file does not exist: ${dst}`);
const newSrcHash = crypto.createHash("sha256").update(fs.readFileSync(src)).digest("hex");
const oldSrcHash = srcHashes.get(src);
assert(oldSrcHash);
if (oldSrcHash !== newSrcHash) {
failures.push(` Source file changed during signing: ${src}\n before: ${oldSrcHash}\n after: ${newSrcHash}`);
}
continue;
}
const srcHash = srcHashes.get(src);
assert(srcHash);
const dstHash = crypto.createHash("sha256").update(fs.readFileSync(dst)).digest("hex");
if (srcHash === dstHash) {
const message = `Signed file is identical to source file (not signed?): ${src} -> ${dst}\n sha256: ${dstHash}`;
if (unchangedOutputOkay) {
console.log(message);
}
else {
failures.push(message);
continue;
}
}
if (src === dst) {
console.log(`Signed ${src}`);
}
else {
console.log(`Signed ${src} -> ${dst}`);
}
console.log(` sha256: ${dstHash}`);
}
}
if (failures.length) {
throw new Error("Some files failed to sign:\n" + failures.map(f => " - " + f).join("\n"));
}
}
/**
* @param {string} src
* @param {string} dest
* @param {(p: string) => boolean} [filter]
*/
function cpRecursive(src, dest, filter) {
return fs.promises.cp(src, dest, {
recursive: true,
filter: filter ? src => filter(src.replace(/\\/g, "/")) : undefined,
});
}
/**
* @param {string} src
* @param {string} dest
*/
function cpWithoutNodeModulesOrTsconfig(src, dest) {
return cpRecursive(src, dest, p => !p.endsWith("/node_modules") && !p.endsWith("/tsconfig.json"));
}
const mainNativePreviewPackage = {
npmPackageName: "@typescript/native-preview",
npmDir: path.join(builtNpm, "native-preview"),
npmTarball: path.join(builtNpm, "native-preview.tgz"),
};
/**
* @typedef {"win32" | "linux" | "darwin"} OS
* @typedef {"x64" | "arm" | "arm64"} Arch
* @typedef {"Microsoft400" | "LinuxSign" | "MacDeveloperHarden" | "8020" | "VSCodePublisher"} Cert
* @typedef {`${OS | "alpine"}-${Exclude<Arch, "arm"> | "armhf"}`} VSCodeTarget
*/
void 0;
const nativePreviewPlatforms = memoize(() => {
/** @type {[os: OS, arch: Arch, cert: Cert, alpine?: boolean][]} */
let supportedPlatforms = [
["win32", "x64", "Microsoft400"],
["win32", "arm64", "Microsoft400"],
["linux", "x64", "LinuxSign", true],
["linux", "arm", "LinuxSign"],
["linux", "arm64", "LinuxSign", true],
["darwin", "x64", "MacDeveloperHarden"],
["darwin", "arm64", "MacDeveloperHarden"],
// Wasm?
];
if (!options.forRelease) {
supportedPlatforms = supportedPlatforms.filter(([os, arch]) => os === process.platform && arch === process.arch);
assert.equal(supportedPlatforms.length, 1, "No supported platforms found");
}