GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — TypeScript/Herebyfile.mjs at main · joac/TypeScript Expand file tree/ Copy pathHerebyfile.mjsMore file actions 2891 lines (2546 loc) · 107 KB / Copy pathHerebyfile.mjsFile metadata and controls2891 lines (2546 loc) · 107 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 { task } from "hereby"; import assert from "node:assert"; import crypto from "node:crypto"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import url from "node:url"; import { parseArgs, styleText, } from "node:util"; import * as tar from "tar"; import { xSync } from "tinyexec"; import { enableFileFingerprintCache, run, } from "./tools/scripts/gen/utils.mts"; enableFileFingerprintCache(); if (process.platform === "win32") { process.chdir(fs.realpathSync.native(process.cwd())); } const __filename = url.fileURLToPath(new URL(import.meta.url)); const __dirname = path.dirname(__filename); const isCI = !!process.env.CI || !!process.env.TF_BUILD; const stableThreeComponentVersionPatternSource = String.raw`^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$`; const stableThreeComponentVersionPattern = new RegExp(stableThreeComponentVersionPatternSource); /** @typedef {import("./tools/scripts/gen/utils.mts").RunOptions} RunOptions */ /** * @param {string} command * @param {readonly string[]} [args] * @param {Omit<RunOptions, "captureOutput">} [options] */ function runOutput(command, args, options) { return run(command, args, { ...options, captureOutput: true }); } /** * @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" }, force: { type: "boolean", default: parseEnvBoolean("FORCE") }, api: { type: "boolean" }, all: { type: "boolean" }, debug: { type: "boolean" }, dirty: { type: "boolean" }, release: { type: "boolean" }, setPrerelease: { type: "string" }, forRelease: { type: "boolean" }, respectGoEnv: { type: "boolean" }, vscodeTypescriptRelease: { 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); // Native release branches can edit these constants to publish a fixed stable version. // Main publishes prerelease builds of the TypeScript package. const nativePreviewReleaseProfile = /** @type {"native-preview" | "typescript"} */ ("typescript"); const nativePreviewReleaseVersion = /** @type {string | undefined} */ (undefined); const releaseVscodeTypescript = !!options.vscodeTypescriptRelease; const produceNativePreviewVsix = releaseVscodeTypescript; const produceTypeScriptNightlyVsix = !nativePreviewReleaseVersion && !releaseVscodeTypescript; const usePublishedPlatformPackagesForVsix = releaseVscodeTypescript; const produceAnyVsix = produceNativePreviewVsix || produceTypeScriptNightlyVsix; const publishAsTypescript = nativePreviewReleaseProfile === "typescript"; if (releaseVscodeTypescript && options.setPrerelease) { throw new Error("vscode-typescript releases use the extension's package.json version and do not accept setPrerelease"); } if (!releaseVscodeTypescript && options.forRelease && !options.setPrerelease && (!nativePreviewReleaseVersion || produceAnyVsix)) { throw new Error("forRelease requires setPrerelease unless nativePreviewReleaseVersion is hardcoded and VSIX production is disabled"); } if (options.respectGoEnv && options.forRelease) { throw new Error("respectGoEnv cannot be combined with forRelease"); } if (options.respectGoEnv && options.setPrerelease) { throw new Error("respectGoEnv requires the version declared in the source"); } if (releaseVscodeTypescript && !publishAsTypescript) { throw new Error("vscode-typescript releases require nativePreviewReleaseProfile to be 'typescript'"); } 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"] : []), ]; const goBuildEnv = { ...(options.race ? {} : { CGO_ENABLED: "0" }), }; /** * @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; }; } /** * @param {string} pattern * @param {string[]} [exclude] */ async function globFiles(pattern, exclude) { const files = []; const absolute = path.isAbsolute(pattern); for await (const entry of fs.promises.glob(pattern, { exclude, withFileTypes: true })) { if (entry.isFile()) { const file = path.join(entry.parentPath, entry.name); files.push(absolute ? file : path.relative(process.cwd(), file)); } } return files; } /** * @param {(() => Promise<void>)[]} tasks * @param {number} concurrency */ async function runWithConcurrencyLimit(tasks, concurrency) { const queue = tasks.values(); /** @type {unknown[]} */ const errors = []; const workers = Array.from({ length: Math.min(concurrency, tasks.length) }, async () => { for (const task of queue) { try { await task(); } catch (error) { errors.push(error); } } }); await Promise.all(workers); if (errors.length === 1) { throw errors[0]; } if (errors.length > 1) { throw new AggregateError(errors, `${errors.length} concurrent tasks failed`); } } const builtLocal = "./built/local"; const libsDir = "./tsc/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), }); /** * Gets the release build flags for stripping debug info. * @param {string} [versionOverride] Optional version to embed in the binary. * @returns {string[]} */ function getReleaseBuildFlags(versionOverride) { let ldflags = "-ldflags=-s -w"; if (versionOverride) { ldflags += ` -X github.com/microsoft/TypeScript/tsc/internal/core.version=${versionOverride}`; } return ["-trimpath", ldflags]; } /** * @param {object} [opts] * @param {string} [opts.out] * @param {AbortSignal} [opts.abortSignal] * @param {Record<string, string | undefined>} [opts.env] * @param {string[]} [opts.extraFlags] */ function buildTsc(opts) { opts ||= {}; const out = opts.out ?? path.resolve("./built/local/tsc" + (process.platform === "win32" ? ".exe" : "")); const env = { ...(options.respectGoEnv ? {} : goBuildEnv), ...opts.env }; return run("go", ["build", ...goBuildFlags, ...(opts.extraFlags ?? []), ...goBuildTags("noembed"), "-o", out, "./cmd/tsc"], { signal: opts.abortSignal, env, cwd: "./tsc", }); } export const tscBuild = task({ name: "tsc:build", description: "Builds the tsc binary.", run: async () => { await buildTsc({ extraFlags: options.release ? getReleaseBuildFlags() : [] }); }, }); export const tsgo = task({ name: "tsgo", dependencies: [lib, tscBuild], }); 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 tsc 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 buildTsc({ abortSignal }); } }, { paths: ["tsc/cmd", "tsc/internal"], ignored: path => /[\\/]testdata[\\/]/.test(path), }); }, }); export const cleanBuilt = task({ name: "clean:built", hiddenFromTaskList: true, run: () => rimraf("built"), }); /** @type {(() => Promise<void>)[]} */ const goGenerateActions = []; async function runGenerateGo() { for (const generate of goGenerateActions) { await generate(); } } export const generateGo = task({ name: "generate:go", description: "Runs the project's Go code generators directly. Pass --force to regenerate unchanged files.", run: runGenerateGo, }); const getGoGenerateEnvironment = memoize(async () => { const { stdout } = await runOutput("go", ["env", "-json", "GOOS", "GOARCH", "GOROOT"], { cwd: "./tsc" }); return /** @type {{ GOOS: string; GOARCH: string; GOROOT: string }} */ (JSON.parse(stdout)); }); /** @typedef {import("./tools/scripts/gen/cache.mts").CacheOptions & { file: string }} GoGenerator */ /** * @param {string} name * @param {GoGenerator} generator */ async function runGoGenerator(name, { file, ...spec }) { const { default: cache } = await import("./tools/scripts/gen/cache.mts"); const sourcePath = path.resolve(__dirname, file); const source = fs.readFileSync(sourcePath, "utf8"); const packageName = /^package\s+(\w+)/m.exec(source)?.[1]; const line = source.split(/\r?\n/).findIndex(line => line.trimEnd() === `//go:generate npx hereby ${name}`) + 1; assert(packageName && line, `Missing package or generation directive in ${file}`); const goEnv = await getGoGenerateEnvironment(); const pathKey = process.platform === "win32" ? Object.keys(process.env).find(key => key.toUpperCase() === "PATH") ?? "PATH" : "PATH"; const goBin = path.join(goEnv.GOROOT, "bin"); const searchPath = (process.env[pathKey] ?? "").split(path.delimiter).filter(entry => path.resolve(entry) !== goBin); await cache({ ...spec, cwd: spec.cwd ?? path.dirname(sourcePath), inputs: [__filename, sourcePath, ...spec.inputs], envInputs: [ ...(spec.envInputs ?? ["GOOS", "GOARCH", "GOFLAGS", "GOTOOLCHAIN", "GOEXPERIMENT", "CGO_ENABLED", "GOWORK"]), "GOROOT", "GOFILE", "GOLINE", "GOPACKAGE", "DOLLAR", ], env: { ...goEnv, GOFILE: path.basename(sourcePath), GOLINE: String(line), GOPACKAGE: packageName, DOLLAR: "$", [pathKey]: [goBin, ...searchPath].join(path.delimiter), }, force: !!options.force, }); } /** * @param {string} name * @param {GoGenerator[] | (() => Promise<void>)} generators */ function goGenerateTask(name, generators) { const run = typeof generators === "function" ? generators : async () => { for (const generator of generators) await runGoGenerator(name, generator); }; goGenerateActions.push(run); return task({ name, description: `Generates ${name.slice("generate:".length)} files. Pass --force to regenerate unchanged files.`, run, }); } /** * @param {string} file * @param {string} type * @param {string} output * @param {string} [trimPrefix] * @returns {GoGenerator} */ function stringerGenerator(file, type, output, trimPrefix) { return { file, inputs: [], outputs: [output], commands: [ ["go", "tool", "golang.org/x/tools/cmd/stringer", `-type=${type}`, ...(trimPrefix ? [`-trimprefix=${trimPrefix}`] : []), `-output=${output}`], ["dprint", "fmt", output], ], }; } /** * @param {string} file * @param {string} type * @param {string} output * @param {{ source?: string; packageName: string; inputs?: string[]; stub?: boolean }} options * @returns {GoGenerator} */ function moqGenerator(file, type, output, { source = ".", packageName, inputs = [], stub = false }) { return { file, inputs, outputs: [output], commands: [ ["go", "tool", "github.com/matryer/moq", ...(stub ? ["-stub"] : []), "-fmt", "goimports", "-pkg", packageName, "-out", output, source, type], ["dprint", "fmt", output], ], }; } async function runGenerateASTStringer() { await runGoGenerator("generate:ast-stringer", stringerGenerator("tsc/internal/ast/kind_generated.go", "Kind", "kind_stringer_generated.go")); } export const generateASTStringer = goGenerateTask("generate:ast-stringer", runGenerateASTStringer); export const generateBundled = goGenerateTask("generate:bundled", [{ file: "tsc/internal/bundled/bundled.go", inputs: ["generate.go", "CopyrightNotice.txt", "libs/*"], outputs: ["libs_generated.go", "embed_generated.go"], commands: [["go", "run", "generate.go"]], }]); export const generateChecker = goGenerateTask("generate:checker", [ stringerGenerator("tsc/internal/checker/types.go", "SignatureKind", "stringer_generated.go"), ]); export const generateCompilerOptions = goGenerateTask("generate:compileroptions", [ stringerGenerator("tsc/internal/core/compileroptions.go", "ModuleKind", "modulekind_stringer_generated.go", "ModuleKind"), stringerGenerator("tsc/internal/core/compileroptions.go", "ScriptTarget", "scripttarget_stringer_generated.go", "ScriptTarget"), ]); export const generateLanguageVariant = goGenerateTask("generate:languagevariant", [ stringerGenerator("tsc/internal/core/languagevariant.go", "LanguageVariant", "languagevariant_stringer_generated.go"), ]); export const generateScriptKind = goGenerateTask("generate:scriptkind", [ stringerGenerator("tsc/internal/core/scriptkind.go", "ScriptKind", "scriptkind_stringer_generated.go"), ]); export const generateTristate = goGenerateTask("generate:tristate", [ stringerGenerator("tsc/internal/core/tristate.go", "Tristate", "tristate_stringer_generated.go"), ]); export const generateDiagnostics = goGenerateTask("generate:diagnostics", [ { file: "tsc/internal/diagnostics/diagnostics.go", inputs: ["generate.go", "diagnosticMessages.json", "../../../tools/LocProject.json", "../{collections,json}/*.go", "loc/*.generated.json"], exclude: ["**/*_test.go"], outputs: ["diagnostics_generated.go", "diagnosticMessages.generated.json", "loc_generated.go", "loc/*.json.gz"], commands: [ [ "go", "run", "generate.go", "-diagnostics", "diagnostics_generated.go", "-loc", "loc_generated.go", "-locdir", "loc", "-locproject", "../../../tools/LocProject.json", "-locsource", "diagnosticMessages.generated.json", ], ["dprint", "fmt", "diagnostics_generated.go", "loc_generated.go"], ], }, stringerGenerator("tsc/internal/diagnostics/diagnostics.go", "Category", "stringer_generated.go"), ]); export const generateAutoImport = goGenerateTask("generate:autoimport", [ stringerGenerator("tsc/internal/ls/autoimport/export.go", "ExportSyntax", "export_stringer_generated.go"), ]); export const generateProject = goGenerateTask("generate:project", [ stringerGenerator("tsc/internal/project/project.go", "Kind", "project_stringer_generated.go", "Kind"), ]); export const generateProjectTestUtil = goGenerateTask("generate:projecttestutil", [ moqGenerator("tsc/internal/testutil/projecttestutil/projecttestutil.go", "Client", "clientmock_generated.go", { source: "../../project", packageName: "projecttestutil", inputs: ["../../project/client.go"], stub: true, }), moqGenerator("tsc/internal/testutil/projecttestutil/projecttestutil.go", "NpmExecutor", "npmexecutormock_generated.go", { source: "../../project/ata", packageName: "projecttestutil", inputs: ["../../project/ata/ata.go"], stub: true, }), ]); export const generateVFS = goGenerateTask("generate:vfs", [ moqGenerator("tsc/internal/vfs/vfs.go", "FS", "vfsmock/mock_generated.go", { packageName: "vfsmock" }), ]); export const generateVFSMatch = goGenerateTask("generate:vfsmatch", [ stringerGenerator("tsc/internal/vfs/vfsmatch/vfsmatch.go", "Usage", "stringer_generated.go", "Usage"), ]); export const generateUnicode = goGenerateTask("generate:unicode", async () => { const { default: generate } = await import("./tsc/internal/stringutil/_scripts/generate-unicode-data.mts"); await generate(!!options.force); }); async function runGenerateExtension() { const { default: cache } = await import("./tools/scripts/gen/cache.mts"); await cache({ cwd: __dirname, inputs: [__filename, "packages/vscode-typescript/package.json", "packages/vscode-typescript/src/**/*"], outputs: ["packages/vscode-typescript/l10n/bundle.l10n.json"], commands: [["npm", "run", "-w", "native-preview", "generateLocBundle"]], envInputs: [], force: !!options.force, }); } export const generateExtension = task({ name: "generate:extension", description: "Generates files in the extension. Pass --force to regenerate unchanged files.", run: runGenerateExtension, }); async function runGenerateExtensionTest() { const { default: cache } = await import("./tools/scripts/gen/cache.mts"); await cache({ cwd: __dirname, inputs: [__filename, "packages/vscode-typescript/package.json", "packages/vscode-typescript/l10n/bundle.l10n.json", "packages/vscode-typescript/package.nls.json"], outputs: ["packages/vscode-typescript/l10n/bundle.l10n.qps-ploc.json", "packages/vscode-typescript/package.nls.qps-ploc.json"], commands: [["npm", "run", "-w", "native-preview", "generateLocTest"]], envInputs: [], force: !!options.force, }); } export const generateExtensionTest = task({ name: "generate:extension-test", description: "Generates pseudo-localized extension resources. Pass --force to regenerate unchanged files.", dependencies: [generateExtension], run: runGenerateExtensionTest, }); async function runGenerateLSP() { const { GeneratedFile } = await import("./tools/scripts/gen/generatedFile.mts"); const directory = path.join(__dirname, "tsc/internal/lsp/lsproto/_generate"); const modelFiles = ["metaModel.json", "metaModelSchema.mts"].map(file => new GeneratedFile(path.join(directory, file), [path.join(directory, "fetchModel.mts"), path.join(__dirname, "package-lock.json")])); if (!modelFiles.every(file => file.isCurrent(!!options.force))) { for (const file of modelFiles) file.invalidate(); const { default: fetchModel } = await import("./tsc/internal/lsp/lsproto/_generate/fetchModel.mts"); await fetchModel(); for (const file of modelFiles) file.markCurrent(); } const output = new GeneratedFile(path.join(directory, "../lsp_generated.go"), [ __filename, path.join(directory, "generate.mts"), ...modelFiles.map(file => file.fileName), ]); if (output.isCurrent(!!options.force)) { console.log("LSP bindings are up to date."); return; } output.invalidate(); const { default: generate } = await import("./tsc/internal/lsp/lsproto/_generate/generate.mts"); await generate(); output.markCurrent(); } export const generateLSP = task({ name: "generate:lsp", description: "Generates LSP bindings from the pinned protocol model. Pass --force to regenerate unchanged files.", run: runGenerateLSP, }); async function runGenerateEnums() { const { default: generate } = await import("./tools/scripts/tsc/generate-enums.ts"); await generate(!!options.force); } export const generateEnums = task({ name: "generate:enums", description: "Generates TypeScript enum files from Go source. Pass --force to regenerate unchanged files.", run: runGenerateEnums, }); async function runGenerateAST() { const { default: generate } = await import("./tools/scripts/tsc/generate.ts"); generate(!!options.force); await runGenerateASTStringer(); } export const generateAST = task({ name: "generate:ast", description: "Generates AST, kind stringer, and encoder files from ast.json. Pass --force to regenerate unchanged files.", run: runGenerateAST, }); async function runGenerateSync() { const { generateSync } = await import("./packages/typescript/scripts/generateSync.ts"); generateSync(!!options.force); } export const generateSync = task({ name: "generate:sync", description: "Generates synchronous and generator APIs and tests. Pass --force to regenerate unchanged files.", run: runGenerateSync, }); async function runGenerateAPI() { await runGoGenerator("generate:api", { file: "tsc/internal/api/proto.go", cwd: __dirname, inputs: [ "tsc/internal/api/*.go", "tsc/internal/api/requestfilesystem/*.go", "tsc/internal/core/*.go", "tsc/internal/checker/types.go", "tsc/internal/diagnostics/diagnostics.go", "tsc/internal/tspath/path.go", "tools/gen-proto/*.go", ], exclude: ["**/*_test.go", "**/*_generated.go"], envInputs: [], outputs: ["packages/typescript/src/api/proto.generated.ts"], commands: [ ["go", "-C", "./tools", "run", "./gen-proto", "../tsc/internal/api/proto.go", "../packages/typescript/src/api/proto.generated.ts"], ["dprint", "fmt", "packages/typescript/src/api/proto.generated.ts"], ], }); } export const generateAPI = goGenerateTask("generate:api", runGenerateAPI); const vendorJsonrpcDir = "packages/typescript/vendor/vscode-jsonrpc"; const vendorJsonrpcSrc = "node_modules/vscode-jsonrpc"; // Files copied verbatim from the installed vscode-jsonrpc package into the // vendored copy. Only the runtime files needed by the `#vscode-jsonrpc/node` // import (lib + typings + package.json) plus license/readme are vendored. const vendorJsonrpcFiles = ["package.json", "README.md", "License.txt", "lib", "typings"]; async function runGenerateVendor() { const { GeneratedFile } = await import("./tools/scripts/gen/generatedFile.mts"); const src = path.join(__dirname, vendorJsonrpcSrc); const dest = path.join(__dirname, vendorJsonrpcDir); if (!fs.existsSync(src)) { throw new Error(`${vendorJsonrpcSrc} is not installed; run \`npm ci\` first.`); } const manifest = new GeneratedFile(path.join(dest, "package.json"), [__filename, path.join(src, "package.json")]); if (manifest.isCurrent(!!options.force)) { console.log("Vendored vscode-jsonrpc files are up to date."); return; } manifest.invalidate(); await rimraf(dest); await fs.promises.mkdir(dest, { recursive: true }); for (const file of vendorJsonrpcFiles) { await cpRecursive(path.join(src, file), path.join(dest, file)); } manifest.markCurrent(); } export const generateVendor = task({ name: "generate:vendor", description: "Updates the vendored copy of vscode-jsonrpc from node_modules. Pass --force to regenerate unchanged files.", run: runGenerateVendor, }); const generateCompiler = task({ name: "generate:compiler", hiddenFromTaskList: true, dependencies: [generateAST, generateLSP], run: async () => { await runGenerateGo(); await runGenerateEnums(); }, }); export const generate = task({ name: "generate", description: "Runs all code generation, including AST, LSP, APIs, extension localization, and vendored dependencies.", dependencies: [generateCompiler, generateSync, generateExtensionTest, generateVendor], }); 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=./..."] : []), ]; } function getGODEBUG() { const key = "tracebackancestors"; const setting = `${key}=10`; const existing = process.env.GODEBUG ?? ""; if (!existing) return setting; if (existing.includes(`${key}=`)) return existing; return `${existing},${setting}`; } const goTestEnv = { GODEBUG: getGODEBUG(), ...(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 baselineTrackingEnabled = false && ![ options.tests, options.noembed, options.concurrentTestPrograms, options.race, options.dirty, ].some(Boolean); const goTestSumFlags = [ "--format-hide-empty-pkg", "--hide-summary", "skipped", ]; /** * Collects all baseline files that were used during the test run. * @param {string} trackingDir * @returns {Promise<Set<string>>} */ async function collectUsedBaselines(trackingDir) { /** @type {Set<string>} */ const usedBaselines = new Set(); if (!fs.existsSync(trackingDir)) { return usedBaselines; } const trackingFiles = await fs.promises.readdir(trackingDir); for (const file of trackingFiles) { const content = await fs.promises.readFile(path.join(trackingDir, file), "utf-8"); for (const line of content.split("\n")) { const trimmed = line.trim(); if (trimmed) { usedBaselines.add(trimmed); } } } return usedBaselines; } /** * Checks for unused baseline files and reports them. * @param {string} trackingDir * @returns {Promise<string[]>} List of unused baseline file paths. */ async function checkUnusedBaselines(trackingDir) { const usedBaselines = await collectUsedBaselines(trackingDir); if (usedBaselines.size === 0) { // No baselines recorded - either no tests ran or tracking wasn't set up properly return []; } const allBaselines = await globFiles(`${refBaseline}/**`); const unusedBaselines = allBaselines .map(p => path.relative(refBaseline, p)) .filter(p => !usedBaselines.has(p)); return unusedBaselines; } /** * @param {string} taskName */ function gotestsumArgs(taskName) { return [ ...goTestSumFlags, "--", ...goTestFlags(taskName), ]; } /** * @param {string} taskName */ function goTest(taskName) { return ["go", "test"].concat(goTestFlags(taskName)); } async function runTests() { if (!options.dirty) { await rimraf(localBaseline); await fs.promises.mkdir(localBaseline, { recursive: true }); } // Create a tmp directory for baseline tracking if enabled /** @type {string | undefined} */ let trackingDir; /** @type {(() => Promise<void>) | undefined} */ let cleanupTracking; if (baselineTrackingEnabled) { const tempTrackingDir = fs.mkdtempSync(path.join(os.tmpdir(), "tsgo-baseline-tracking-")); trackingDir = tempTrackingDir; cleanupTracking = () => rimraf(tempTrackingDir); } try { const testEnv = { ...goTestEnv, ...(trackingDir ? { TSGO_BASELINE_TRACKING_DIR: trackingDir } : {}), }; await gotestsumTool.run([...gotestsumArgs("tests"), "./...", ...(isCI ? ["--timeout=45m"] : [])], { env: testEnv, cwd: "./tsc", }); // Check for unused baselines after tests complete if (trackingDir) { const unusedBaselines = await checkUnusedBaselines(trackingDir); if (unusedBaselines.length > 0) { console.error(styleText("red", `\nFound ${unusedBaselines.length} unused baseline file(s):`)); for (const baseline of unusedBaselines.slice(0, 20)) { console.error(styleText("red", ` ${baseline}`)); } if (unusedBaselines.length > 20) { console.error(styleText("red", ` ... and ${unusedBaselines.length - 20} more`)); } // Create .delete files for each unused baseline so baseline-accept can remove them for (const baseline of unusedBaselines) { const deleteFilePath = path.join(localBaseline, baseline + ".delete"); await fs.promises.mkdir(path.dirname(deleteFilePath), { recursive: true }); await fs.promises.writeFile(deleteFilePath, ""); } console.error(styleText("red", `\nRun 'hereby baseline-accept' to delete them.`)); throw new Error(`Found ${unusedBaselines.length} unused baseline file(s). Run 'hereby baseline-accept' to delete them.`); } } } finally { if (cleanupTracking) { await cleanupTracking(); } } } async function runTestExtension() { await run("npm", ["test", "-w", "native-preview"]); } export const testTsc = task({ name: "test:tsc", description: "Runs all tests in the tsc module.", run: runTests, }); export const testExtension = task({ name: "test:extension", description: "Runs the VS Code extension tests.", run: runTestExtension, }); export const test = task({ name: "test", description: "Alias for test:tsc.", dependencies: [testTsc], }); async function runTestBenchmarks() { // Run the benchmarks once to ensure they compile and run without errors. const command = goTest("benchmarks"); await run(command[0], [...command.slice(1), "-run=-", "-bench=.", "-benchtime=1x", "./..."], { env: goTestEnv, cwd: "./tsc" }); } export const testBenchmarks = task({ name: "test:benchmarks", description: "Runs Go benchmarks once; excluded from validate.", run: runTestBenchmarks, }); async function runTestTools() { await gotestsumTool.run([...gotestsumArgs("tools"), "./..."], { env: goTestEnv, cwd: path.join(__dirname, "tools") }); } async function runTestAPI() { // Running the package script doesn't work on Windows; some path escaping isn't done correctly and the test runner runs no tests. await run("node", ["--conditions", "@typescript/source", "--test", "./test/**/*.test.ts"], { cwd: "./packages/typescript" }); } async function runTestAPIBenchmarks() { for (const variant of ["async", "sync", "generators"]) { await run("node", ["--conditions", "@typescript/source", `./test/${variant}/api.bench.ts`, "--singleIteration"], { cwd: "./packages/typescript" }); } } export const testTools = task({ name: "test:tools", description: "Runs all tests in the tools module.", run: runTestTools, }); export const testCodegen = task({ name: "test:codegen", description: "Runs incremental codegen tests.", run: async () => { await run("go", ["-C", "tsc", "mod", "download"]); await run("node", ["--test", "--test-concurrency=1", "./tools/scripts/gen/*.test.mts"]); }, }); export const buildAPI = task({ name: "build:api", description: "Builds @typescript/typescript JS API.", run: async () => { await run("npm", ["run", "-w", "@typescript/typescript", "build"]); }, }); async function runBuildAPITests(generateSources = true) { if (generateSources) await runGenerateSync(); await run("npm", ["run", "-w", "@typescript/typescript", "build:test"]); } export const buildAPITests = task({ name: "build:api:test", description: "Builds the @typescript/typescript JS API tests.", dependencies: [generateEnums, generateAPI], run: runBuildAPITests, }); export const testAPI = task({ name: "test:api", description: "Runs the @typescript/typescript JS API tests.", dependencies: [tsgo, buildAPITests], run: runTestAPI, }); export const testAPIBenchmarks = task({ name: "test:benchmarks:api", description: "Runs async, sync, and generator API benchmarks once; excluded from validate.", |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |