workspace-conformance 2.0.1 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -947,6 +947,41 @@ async function readWorkspacePackages(cwd, layout) {
947
947
  if (discovered.length === 0) throw new ConformanceError(`no workspace package found: ${patterns.length === 0 ? "the package patterns are empty, so no directory is selected" : `no directory the patterns ${patterns.join(", ")} select holds a package.json`}; for a single-package repository, set the layout's packages to ['.']`);
948
948
  return classifyPackages(discovered, layout);
949
949
  }
950
+ /**
951
+ * The `package.json` fields a package's declared dependencies are read from when the layout's `dependencyFields` is omitted, the default of the ESLint workspace rules that read the same layout.
952
+ */
953
+ const DEFAULT_DEPENDENCY_FIELDS = ["dependencies"];
954
+ /**
955
+ * The fields npm and pnpm install dependencies from, read alongside the layout's own so that a dependency declared outside them can be told apart from one not declared at all.
956
+ */
957
+ const MANIFEST_DEPENDENCY_FIELDS = [
958
+ "dependencies",
959
+ "devDependencies",
960
+ "peerDependencies",
961
+ "optionalDependencies"
962
+ ];
963
+ /**
964
+ * For each package directory, the fields its `package.json` declares each dependency in: the manifest dependency fields and any other the layout's `dependencyFields` names.
965
+ */
966
+ async function readDeclaredDependencies(root, packages, layout) {
967
+ const fields = [.../* @__PURE__ */ new Set([...MANIFEST_DEPENDENCY_FIELDS, ...layout.dependencyFields ?? DEFAULT_DEPENDENCY_FIELDS])];
968
+ return new Map(await Promise.all(packages.map(async (member) => {
969
+ const manifest = (0, node_path.join)(root, member.dir, "package.json");
970
+ let content;
971
+ try {
972
+ content = JSON.parse(await (0, node_fs_promises.readFile)(manifest, "utf8"));
973
+ } catch (error) {
974
+ throw new ConformanceError(`${manifest} cannot be read as JSON`, { cause: error });
975
+ }
976
+ if (!isRecord(content)) throw new ConformanceError(`${manifest} is not a JSON object`);
977
+ const declared = /* @__PURE__ */ new Map();
978
+ for (const field of fields) {
979
+ const entries = content[field];
980
+ for (const name of isRecord(entries) ? Object.keys(entries) : []) declared.set(name, [...declared.get(name) ?? [], field]);
981
+ }
982
+ return [member.dir, declared];
983
+ })));
984
+ }
950
985
  //#endregion
951
986
  //#region src/checks/engines-floor.ts
952
987
  /**
@@ -1530,10 +1565,17 @@ async function runImportChecks(input) {
1530
1565
  const { cwd, layout, entries } = input;
1531
1566
  const root = workspaceRoot(cwd, layout);
1532
1567
  const packages = await readWorkspacePackages(cwd, layout);
1568
+ const declared = await readDeclaredDependencies(root, packages, layout);
1569
+ const read = new Set(layout.dependencyFields ?? DEFAULT_DEPENDENCY_FIELDS);
1570
+ const judged = (from, to) => {
1571
+ const fields = to.name === void 0 ? void 0 : declared.get(from.dir)?.get(to.name);
1572
+ return fields === void 0 || fields.some((field) => read.has(field));
1573
+ };
1533
1574
  const scope = {
1534
1575
  cwd,
1535
1576
  root,
1536
- packages
1577
+ packages,
1578
+ judged
1537
1579
  };
1538
1580
  const contributions = entries.map((entry) => ({
1539
1581
  ...entry,
@@ -1589,13 +1631,13 @@ async function runImportCheck(context, spec) {
1589
1631
  })).get(spec.name) ?? [];
1590
1632
  }
1591
1633
  /**
1592
- * The report of a check whose every rule forbids one package importing another: one violation per finding, at the importing file, ordered by file and message.
1634
+ * The report of a check whose every rule forbids one package importing another: one violation per finding the scope judges, at the importing file, ordered by file and message.
1593
1635
  */
1594
1636
  function edgeReport(spec) {
1595
- return (findings, { cwd, root, packages }) => findings.map((finding) => {
1637
+ return (findings, { cwd, root, packages, judged }) => findings.flatMap((finding) => {
1596
1638
  const from = packageOfPath(packages, finding.from);
1597
1639
  const to = packageOfPath(packages, finding.to);
1598
- return {
1640
+ return judged(from, to) ? [{
1599
1641
  code: `${spec.name}/${spec.reason}`,
1600
1642
  message: spec.message({
1601
1643
  from,
@@ -1604,7 +1646,7 @@ function edgeReport(spec) {
1604
1646
  toFile: finding.to
1605
1647
  }),
1606
1648
  file: relativePosix(cwd, (0, node_path.join)(root, finding.from))
1607
- };
1649
+ }] : [];
1608
1650
  }).sort((a, b) => a.file.localeCompare(b.file) || a.message.localeCompare(b.message));
1609
1651
  }
1610
1652
  /**
@@ -2239,7 +2281,9 @@ function createGitHubClient(options) {
2239
2281
  pullRequests: rules.filter((rule) => rule.type === "pull_request").map((rule) => ({
2240
2282
  requiredReviewThreadResolution: rule.parameters?.required_review_thread_resolution === true,
2241
2283
  allowedMergeMethods: rule.parameters?.allowed_merge_methods
2242
- }))
2284
+ })),
2285
+ requiredLinearHistory: rules.some((rule) => rule.type === "required_linear_history"),
2286
+ mergeQueue: rules.some((rule) => rule.type === "merge_queue")
2243
2287
  };
2244
2288
  }
2245
2289
  };
@@ -2307,7 +2351,15 @@ const METHODS = [
2307
2351
  "merge"
2308
2352
  ];
2309
2353
  /**
2310
- * Only one merge method is available for a pull request into the branch, `rebase` unless the options say otherwise. A method is available when the repository allows it and no `pull_request` rule that applies to the branch leaves it out of its allowed methods.
2354
+ * How a message names each method, in the words GitHub's settings page uses.
2355
+ */
2356
+ const METHOD_NAMES = {
2357
+ rebase: "rebase merging",
2358
+ squash: "squash merging",
2359
+ merge: "merge commits"
2360
+ };
2361
+ /**
2362
+ * Only one merge method is available for a pull request into the branch, `rebase` unless the options say otherwise. A method is available when the repository allows it, no `pull_request` rule that applies to the branch leaves it out of its allowed methods, and, for a merge commit, no `required_linear_history` rule applies, since that rule keeps merge commits off the branch.
2311
2363
  *
2312
2364
  * When the repository's plan has no rulesets, no rule applies to the branch and the repository settings alone decide.
2313
2365
  *
@@ -2325,15 +2377,17 @@ const settingsMergeMethods = async ({ cwd, options, github }) => {
2325
2377
  squash: settings.allowSquashMerge,
2326
2378
  merge: settings.allowMergeCommit
2327
2379
  };
2328
- const available = METHODS.filter((method) => repositoryAllows[method] && pullRequests.every((rule) => rule.allowedMergeMethods === void 0 || rule.allowedMergeMethods.includes(method)));
2380
+ const requiredLinearHistory = "unavailable" in read ? false : read.rules.requiredLinearHistory;
2381
+ const rulesAllow = (method) => !(method === "merge" && requiredLinearHistory) && pullRequests.every((rule) => rule.allowedMergeMethods === void 0 || rule.allowedMergeMethods.includes(method));
2382
+ const available = METHODS.filter((method) => repositoryAllows[method] && rulesAllow(method));
2329
2383
  const violations = available.filter((method) => method !== wanted).map((method) => ({
2330
2384
  code: "settings-merge-methods/method-enabled",
2331
- message: `${file} allows ${method} merges; only ${wanted} should be allowed`,
2385
+ message: `${file} allows ${METHOD_NAMES[method]}; only ${METHOD_NAMES[wanted]} should be allowed`,
2332
2386
  file
2333
2387
  }));
2334
2388
  if (!available.includes(wanted)) violations.push({
2335
2389
  code: "settings-merge-methods/method-unavailable",
2336
- message: `${file} does not allow ${wanted} merges`,
2390
+ message: `${file} does not allow ${METHOD_NAMES[wanted]}`,
2337
2391
  file
2338
2392
  });
2339
2393
  return violations;
@@ -2526,6 +2580,7 @@ function parseWorkflow(file, source) {
2526
2580
  const triggers = triggersOf(reader, root["on"]);
2527
2581
  const call = triggers.get("workflow_call");
2528
2582
  const outputs = reader.record(reader.record(call, "on.workflow_call")["outputs"], "on.workflow_call.outputs");
2583
+ const inputs = reader.record(reader.record(call, "on.workflow_call")["inputs"], "on.workflow_call.inputs");
2529
2584
  return {
2530
2585
  file,
2531
2586
  name: reader.text(root["name"], "name"),
@@ -2535,7 +2590,8 @@ function parseWorkflow(file, source) {
2535
2590
  permissionsLocation: root["permissions"] === void 0 ? void 0 : reader.location(["permissions"]),
2536
2591
  env: reader.texts(root["env"], "env"),
2537
2592
  jobs: Object.entries(reader.record(root["jobs"], "jobs")).map(([id, job]) => jobOf(reader, id, job)),
2538
- callOutputs: Object.fromEntries(Object.entries(outputs).map(([name, output]) => [name, reader.text(reader.record(output, `on.workflow_call.outputs.${name}`)["value"], `on.workflow_call.outputs.${name}.value`) ?? ""]))
2593
+ callOutputs: Object.fromEntries(Object.entries(outputs).map(([name, output]) => [name, reader.text(reader.record(output, `on.workflow_call.outputs.${name}`)["value"], `on.workflow_call.outputs.${name}.value`) ?? ""])),
2594
+ callInputs: Object.fromEntries(Object.entries(inputs).map(([name, input]) => [name, reader.text(reader.record(input, `on.workflow_call.inputs.${name}`)["default"], `on.workflow_call.inputs.${name}.default`)]))
2539
2595
  };
2540
2596
  }
2541
2597
  /**
@@ -2882,6 +2938,15 @@ const PACKAGE_MANAGER_OPTIONS = String.raw`(?:\s+(?:(?:--filter|-F|--workspace|-
2882
2938
  * Commands that publish a package to a registry.
2883
2939
  */
2884
2940
  const PUBLISH_COMMAND = new RegExp(String.raw`^(?:(?:npm|pnpm|yarn)${PACKAGE_MANAGER_OPTIONS}(?:\s+npm)?\s+publish|(?:(?:pnpm|yarn)(?:\s+exec)?\s+|npx\s+)?(?:semantic-release|changeset\s+publish|lerna\s+publish))(?:\s|$)`, "u");
2941
+ /**
2942
+ * npm reads no token variable by name: a variable reaches it only through `${NAME}` (or `${NAME?}`) in the value of an `.npmrc` setting. These are the settings that carry credentials.
2943
+ */
2944
+ const NPMRC_AUTH_SETTING = /^\s*[^#;=\s]*(?:_authToken|_auth|_password)\s*=(.*)$/u;
2945
+ const NPMRC_VARIABLE = /\$\{([^${}?]+)\??\}/gu;
2946
+ /**
2947
+ * `semantic-release` as the command a publish line runs, whose npm plugin reads `NPM_TOKEN` itself.
2948
+ */
2949
+ const SEMANTIC_RELEASE = /(?:^|\s)semantic-release(?:\s|$)/u;
2885
2950
  const PROVENANCE_FLAG = /--provenance(?:=true)?(?:\s|$)/u;
2886
2951
  /**
2887
2952
  * Whether the `package.json` in the working directory asks for provenance with `publishConfig.provenance: true`, which applies to every publish of that package.
@@ -2893,6 +2958,34 @@ async function requestsProvenance(cwd) {
2893
2958
  const config = isRecord(manifest) ? manifest["publishConfig"] : void 0;
2894
2959
  return isRecord(config) && config["provenance"] === true;
2895
2960
  }
2961
+ /**
2962
+ * The variables the auth settings of the `.npmrc` in the working directory read, which npm and pnpm load for a publish run there.
2963
+ */
2964
+ async function npmrcTokenVariables(cwd) {
2965
+ const file = (0, node_path.resolve)(cwd, ".npmrc");
2966
+ if (!(0, node_fs.existsSync)(file)) return [];
2967
+ const values = (await (0, node_fs_promises.readFile)(file, "utf8")).split("\n").flatMap((line) => NPMRC_AUTH_SETTING.exec(line)?.[1] ?? []);
2968
+ return [...new Set(values.flatMap((value) => [...value.matchAll(NPMRC_VARIABLE)].flatMap((match) => match[1] ?? [])))];
2969
+ }
2970
+ /**
2971
+ * The token variables that what a publish step runs reads, with what reads each: the `.npmrc` that an earlier `actions/setup-node` step with `registry-url` writes reads `NODE_AUTH_TOKEN`, semantic-release's npm plugin reads `NPM_TOKEN`, and the `.npmrc` of the working directory reads the variables of its auth settings.
2972
+ */
2973
+ function tokenReads(job, step, publishes, npmrcVariables) {
2974
+ const reads = [];
2975
+ if (job.steps.some((earlier) => earlier.index < step.index && stepUses(earlier, "actions/setup-node") && (earlier.with["registry-url"] ?? "") !== "")) reads.push({
2976
+ variable: "NODE_AUTH_TOKEN",
2977
+ reader: "the .npmrc actions/setup-node writes for registry-url"
2978
+ });
2979
+ if (publishes.some((line) => SEMANTIC_RELEASE.test(line))) reads.push({
2980
+ variable: "NPM_TOKEN",
2981
+ reader: "semantic-release's npm plugin"
2982
+ });
2983
+ reads.push(...npmrcVariables.map((variable) => ({
2984
+ variable,
2985
+ reader: "the .npmrc of the working directory"
2986
+ })));
2987
+ return reads.filter((read, index) => reads.findIndex((other) => other.variable === read.variable) === index);
2988
+ }
2896
2989
  function attestationViolations(workflow, job) {
2897
2990
  const permissions = effectivePermissions(workflow, job);
2898
2991
  return job.steps.filter((step) => ATTESTATION_ACTIONS.some((action) => stepUses(step, action))).flatMap((step) => {
@@ -2904,18 +2997,18 @@ function attestationViolations(workflow, job) {
2904
2997
  /**
2905
2998
  * Whether the job passes a registry token to a step, which makes its publish not tokenless: a token variable with a value other than the empty string, anywhere in the environment.
2906
2999
  */
2907
- function passesToken(workflow, job) {
2908
- return [void 0, ...job.steps].some((step) => REGISTRY_TOKEN_VARIABLES.some((variable) => (effectiveEnv(workflow, job, step)[variable] ?? "") !== ""));
3000
+ function passesToken(workflow, job, variables) {
3001
+ return [void 0, ...job.steps].some((step) => variables.some((variable) => (effectiveEnv(workflow, job, step)[variable] ?? "") !== ""));
2909
3002
  }
2910
- function tokenlessPublishViolations(workflow, job, provenanceInManifest) {
2911
- if (accessOf(effectivePermissions(workflow, job), "id-token") !== "write" || passesToken(workflow, job)) return [];
3003
+ function tokenlessPublishViolations(workflow, job, provenanceInManifest, npmrcVariables) {
3004
+ if (accessOf(effectivePermissions(workflow, job), "id-token") !== "write" || passesToken(workflow, job, [...REGISTRY_TOKEN_VARIABLES, ...npmrcVariables])) return [];
2912
3005
  return job.steps.flatMap((step) => {
2913
3006
  const publishes = scriptCommands(step.run).filter((line) => PUBLISH_COMMAND.test(line));
2914
3007
  if (publishes.length === 0) return [];
2915
3008
  const env = effectiveEnv(workflow, job, step);
2916
- const blanked = REGISTRY_TOKEN_VARIABLES.every((variable) => env[variable] === "");
3009
+ const unprotected = tokenReads(job, step, publishes, npmrcVariables).filter((read) => env[read.variable] !== "");
2917
3010
  const provenance = provenanceInManifest || publishes.some((line) => PROVENANCE_FLAG.test(line)) || env["NPM_CONFIG_PROVENANCE"] === "true";
2918
- return blanked || provenance ? [] : [workflowViolation(workflow, "workflow-credentials/tokenless-publish-unprotected", `job '${job.id}' publishes with an OIDC identity and no token, but does not set ${REGISTRY_TOKEN_VARIABLES.join(" and ")} to the empty string, so a token inherited from the environment is used when the OIDC exchange fails; set them to the empty string to prevent that, or request provenance so that such a publish at least carries a traceable attestation`, step.location)];
3011
+ return unprotected.length === 0 || provenance ? [] : [workflowViolation(workflow, "workflow-credentials/tokenless-publish-unprotected", `job '${job.id}' publishes with an OIDC identity and no token, but does not set ${unprotected.map((read) => `${read.variable} (read by ${read.reader})`).join(" and ")} to the empty string, so a token inherited from the environment is used when the OIDC exchange fails; set ${unprotected.length === 1 ? "it" : "them"} to the empty string to prevent that, or request provenance so that such a publish at least carries a traceable attestation`, step.location)];
2919
3012
  });
2920
3013
  }
2921
3014
  /**
@@ -2923,45 +3016,19 @@ function tokenlessPublishViolations(workflow, job, provenanceInManifest) {
2923
3016
  *
2924
3017
  * `workflow-credentials/attestation-permissions`: a step of `actions/attest`, `actions/attest-build-provenance` or `actions/attest-sbom` needs `id-token: write` and `attestations: write` in the job's effective permissions. Permissions a job declares replace the workflow's; permissions declared nowhere are the repository's default, which the file cannot show and which never includes `id-token`, so they are reported.
2925
3018
  *
2926
- * `workflow-credentials/tokenless-publish-unprotected`: a job with `id-token: write` that publishes (`npm`, `pnpm` or `yarn npm publish`, with options such as `-r` or `--filter <package>` before `publish`, `semantic-release`, `changeset publish`, `lerna publish`, bare or run through `pnpm`, `pnpm exec`, `yarn` or `npx`) and passes no token must blank `NODE_AUTH_TOKEN` and `NPM_TOKEN` (set them to `''` at step, job or workflow level) or request provenance (`--provenance`, `NPM_CONFIG_PROVENANCE: true`, or `publishConfig.provenance: true` in the `package.json` of the working directory). The npm CLI replaces any configured token with the one from the OIDC exchange, but when the exchange fails it falls back to whatever token the environment holds, silently. Only blanking the variables prevents that fallback. Provenance does not: npm signs it with the CI's own OIDC identity (through Sigstore), separately from the registry token, so a fallback publish still goes ahead with the inherited token and carries an attestation of where it was built. Requesting provenance is accepted because it makes such a publish traceable, not because it makes it safe.
3019
+ * `workflow-credentials/tokenless-publish-unprotected`: a job with `id-token: write` that publishes (`npm`, `pnpm` or `yarn npm publish`, with options such as `-r` or `--filter <package>` before `publish`, `semantic-release`, `changeset publish`, `lerna publish`, bare or run through `pnpm`, `pnpm exec`, `yarn` or `npx`) and passes no token must blank (set to `''` at step, job or workflow level) every token variable the publish reads, or request provenance (`--provenance`, `NPM_CONFIG_PROVENANCE: true`, or `publishConfig.provenance: true` in the `package.json` of the working directory). The npm CLI replaces any configured token with the one from the OIDC exchange, but when the exchange fails it falls back to whatever token the environment holds, silently. Only blanking the variables prevents that fallback. Provenance does not: npm signs it with the CI's own OIDC identity (through Sigstore), separately from the registry token, so a fallback publish still goes ahead with the inherited token and carries an attestation of where it was built. Requesting provenance is accepted because it makes such a publish traceable, not because it makes it safe.
3020
+ *
3021
+ * A variable is judged only where something reads it, since npm reads none by name, only through `${NAME}` in an `.npmrc`: `NODE_AUTH_TOKEN` after an `actions/setup-node` step with `registry-url`, whose `.npmrc` refers to it; `NPM_TOKEN` for `semantic-release`, whose npm plugin reads it; and the variables the auth settings (`_authToken`, `_auth`, `_password`) of the `.npmrc` in the working directory refer to.
2927
3022
  *
2928
- * Limits: `registry-url` is not reported, because it does not stop the exchange (see the README); a job that calls a reusable workflow is not read; a publish inside a script file or composite action is not seen; provenance set in a `package.json` other than the one in the working directory is not read; a job is tokenless only when no token variable is non-empty anywhere in the job, so a publish that uses a secret is left alone.
3023
+ * Limits: `registry-url` is not reported, because it does not stop the exchange (see the README); an `.npmrc` the file does not show, such as one in the runner's home directory, a Yarn `.yarnrc.yml` and a token set through an `npm_config_` variable are not read; a job that calls a reusable workflow is not read; a publish inside a script file or composite action is not seen; provenance set in a `package.json` other than the one in the working directory is not read; a job is tokenless only when no token variable is non-empty anywhere in the job, so a publish that uses a secret is left alone.
2929
3024
  */
2930
3025
  const workflowCredentials = async ({ cwd, options }) => {
2931
3026
  const provenanceInManifest = await requestsProvenance(cwd);
2932
- return (await loadWorkflows(cwd, options)).flatMap((workflow) => workflow.jobs.flatMap((job) => [...attestationViolations(workflow, job), ...tokenlessPublishViolations(workflow, job, provenanceInManifest)]));
3027
+ const npmrcVariables = await npmrcTokenVariables(cwd);
3028
+ return (await loadWorkflows(cwd, options)).flatMap((workflow) => workflow.jobs.flatMap((job) => [...attestationViolations(workflow, job), ...tokenlessPublishViolations(workflow, job, provenanceInManifest, npmrcVariables)]));
2933
3029
  };
2934
3030
  //#endregion
2935
- //#region src/checks/workflow-job-ordering.ts
2936
- const DEFAULT_DEPLOY_JOBS = ["deploy"];
2937
- const DEFAULT_DOCS_DEPLOY_JOBS = ["docs-deploy"];
2938
- const DEFAULT_BRANCH = "main";
2939
- /**
2940
- * The expression that always names the repository's default branch.
2941
- */
2942
- const DEFAULT_BRANCH_EXPRESSION$1 = /^\$\{\{\s*github\.event\.repository\.default_branch\s*\}\}$/u;
2943
- /**
2944
- * The text a junction job decides on: its `if`, and the conditions and scripts of its steps.
2945
- */
2946
- function decisionText(job) {
2947
- return [job.condition, ...job.steps.flatMap((step) => [
2948
- step.condition,
2949
- step.run,
2950
- ...Object.values(step.env),
2951
- ...Object.values(step.with)
2952
- ])].filter((text) => text !== void 0).join("\n");
2953
- }
2954
- /**
2955
- * Where a script gets the results of the jobs it needs from: `needs.*.result`, one job's `needs.<job>.result` or the whole of `needs`.
2956
- */
2957
- const RESULT_SOURCE = /needs\.(?:\*|[\w-]+)\.result|toJSON\(\s*needs\s*\)/u;
2958
- const FAILURE_WORD = /['"]failure['"]/u;
2959
- const CANCELLED_WORD = /['"]cancelled['"]/u;
2960
- const SKIPPED_OR_NOT_SUCCESS = /needs\.(?:\*|[\w-]+)\.result[^\n]*(?:['"]skipped['"]|!==?\s*['"]success['"])|!\s*contains\(\s*needs\.\*\.result\s*,\s*['"]success['"]/u;
2961
- /**
2962
- * An `if` that compares the ref or the event name.
2963
- */
2964
- const COMPARES_REF_OR_EVENT = /github\.(?:ref|ref_name|event_name)\s*==/u;
3031
+ //#region src/workflows/expressions.ts
2965
3032
  /**
2966
3033
  * An expression written inside the `${{ }}` that marks it as one.
2967
3034
  */
@@ -3009,6 +3076,153 @@ function unwrapped(expression) {
3009
3076
  return enclosedByOneGroup(inner) ? unwrapped(inner.slice(1, -1)) : inner;
3010
3077
  }
3011
3078
  /**
3079
+ * A string literal of an expression, whose body writes a quote as `''`.
3080
+ */
3081
+ const STRING_LITERAL = /^'((?:[^']|'')*)'$/u;
3082
+ /**
3083
+ * A call of `format`, whose name, like every function name in an expression, is case-insensitive.
3084
+ */
3085
+ const FORMAT_CALL = /^format\s*\(([\s\S]*)\)$/iu;
3086
+ /**
3087
+ * A reference to an input of the workflow.
3088
+ */
3089
+ const INPUT_REFERENCE = /^inputs\.([\w-]+)$/u;
3090
+ /**
3091
+ * A placeholder of a `format` pattern, or the doubled brace that writes a literal one.
3092
+ */
3093
+ const FORMAT_PLACEHOLDER = /\{\{|\}\}|\{(\d+)\}/gu;
3094
+ /**
3095
+ * The arguments of a call, split at the commas outside quotes and parentheses.
3096
+ */
3097
+ function callArguments(text) {
3098
+ const parts = [];
3099
+ let depth = 0;
3100
+ let quoted = false;
3101
+ let start = 0;
3102
+ for (let index = 0; index < text.length; index += 1) {
3103
+ const character = text.charAt(index);
3104
+ if (character === "'") quoted = !quoted;
3105
+ else if (!quoted && character === "(") depth += 1;
3106
+ else if (!quoted && character === ")") depth -= 1;
3107
+ else if (!quoted && depth === 0 && character === ",") {
3108
+ parts.push(text.slice(start, index));
3109
+ start = index + 1;
3110
+ }
3111
+ }
3112
+ parts.push(text.slice(start));
3113
+ return parts.map((part) => part.trim());
3114
+ }
3115
+ /**
3116
+ * `format(pattern, ...values)` as GitHub evaluates it: `{N}` is the value at index N and `{{` and `}}` are literal braces. `undefined` when a placeholder names a value that is not given, which GitHub rejects.
3117
+ */
3118
+ function formatted(pattern, values) {
3119
+ let text = "";
3120
+ let end = 0;
3121
+ for (const match of pattern.matchAll(FORMAT_PLACEHOLDER)) {
3122
+ const index = match[1];
3123
+ const value = index === void 0 ? match[0].charAt(0) : values[Number(index)];
3124
+ if (value === void 0) return;
3125
+ text += `${pattern.slice(end, match.index)}${value}`;
3126
+ end = match.index + match[0].length;
3127
+ }
3128
+ return `${text}${pattern.slice(end)}`;
3129
+ }
3130
+ /**
3131
+ * The value an operand of an expression has on every run, or `undefined` when that depends on the run: a string literal, an input whose value `inputs` gives, or `format()` of such values. An input `inputs` holds as `undefined`, or does not hold, is not known.
3132
+ */
3133
+ function constantString(operand, inputs) {
3134
+ const text = unwrapped(operand);
3135
+ const literal = STRING_LITERAL.exec(text)?.[1];
3136
+ if (literal !== void 0) return literal.replaceAll("''", "'");
3137
+ const input = INPUT_REFERENCE.exec(text)?.[1];
3138
+ if (input !== void 0) return Object.hasOwn(inputs, input) ? inputs[input] : void 0;
3139
+ const call = FORMAT_CALL.exec(text)?.[1];
3140
+ if (call === void 0) return;
3141
+ const [pattern, ...rest] = callArguments(call).map((argument) => constantString(argument, inputs));
3142
+ const values = rest.filter((value) => value !== void 0);
3143
+ return pattern === void 0 || values.length !== rest.length ? void 0 : formatted(pattern, values);
3144
+ }
3145
+ //#endregion
3146
+ //#region src/checks/workflow-job-ordering.ts
3147
+ const DEFAULT_DEPLOY_JOBS = ["deploy"];
3148
+ const DEFAULT_DOCS_DEPLOY_JOBS = ["docs-deploy"];
3149
+ const DEFAULT_BRANCH = "main";
3150
+ /**
3151
+ * The expression that always names the repository's default branch.
3152
+ */
3153
+ const DEFAULT_BRANCH_EXPRESSION$1 = /^\$\{\{\s*github\.event\.repository\.default_branch\s*\}\}$/u;
3154
+ /**
3155
+ * The whole of an environment value that is one expression, `${{ <expression> }}`.
3156
+ */
3157
+ const WHOLE_EXPRESSION = /^\$\{\{\s*([\s\S]*?)\s*\}\}$/u;
3158
+ /**
3159
+ * A reference to an environment variable in a script, `$NAME` or `${NAME}`, and in an expression, `env.NAME`.
3160
+ */
3161
+ const SCRIPT_VARIABLE = /\$(?:\{([A-Za-z_]\w*)\}|([A-Za-z_]\w*))/gu;
3162
+ const EXPRESSION_VARIABLE = /\benv\.([A-Za-z_]\w*)/gu;
3163
+ /**
3164
+ * A script or condition with each environment variable whose value is a whole expression replaced by that expression, so `"$RESULT" != "success"` with `RESULT: ${{ needs.test.result }}` reads as the test of `needs.test.result` it is.
3165
+ */
3166
+ function withVariablesResolved(text, env, reference) {
3167
+ return text.replaceAll(reference, (match, ...names) => {
3168
+ const name = names.find((candidate) => typeof candidate === "string");
3169
+ const value = name === void 0 ? void 0 : env[name];
3170
+ return (value === void 0 ? void 0 : WHOLE_EXPRESSION.exec(value.trim())?.[1]) ?? match;
3171
+ });
3172
+ }
3173
+ /**
3174
+ * The text a junction job decides on: its `if`, and the conditions, scripts and inputs of its steps, with the environment variables they read replaced by the expressions that set them, and the values of their environments.
3175
+ */
3176
+ function decisionText(workflow, job) {
3177
+ return [job.condition === void 0 ? void 0 : withVariablesResolved(job.condition, effectiveEnv(workflow, job, void 0), EXPRESSION_VARIABLE), ...job.steps.flatMap((step) => {
3178
+ const env = effectiveEnv(workflow, job, step);
3179
+ return [
3180
+ step.condition === void 0 ? void 0 : withVariablesResolved(step.condition, env, EXPRESSION_VARIABLE),
3181
+ step.run === void 0 ? void 0 : withVariablesResolved(step.run, env, SCRIPT_VARIABLE),
3182
+ ...Object.values(env),
3183
+ ...Object.values(step.with)
3184
+ ];
3185
+ })].filter((text) => text !== void 0).join("\n");
3186
+ }
3187
+ /**
3188
+ * Where a script gets the results of the jobs it needs from: `needs.*.result`, one job's `needs.<job>.result` or the whole of `needs`.
3189
+ */
3190
+ const RESULT_SOURCE = /needs\.(?:\*|[\w-]+)\.result|toJSON\(\s*needs\s*\)/u;
3191
+ const FAILURE_WORD = /['"]failure['"]/u;
3192
+ const CANCELLED_WORD = /['"]cancelled['"]/u;
3193
+ /**
3194
+ * A test that a result is not `success`, which fails on `failure` and `cancelled`, and on `skipped` too. The group is the job, or `*`.
3195
+ */
3196
+ const NOT_SUCCESS = /needs\.(\*|[\w-]+)\.result[^\n]*?!==?\s*['"]success['"]/gu;
3197
+ /**
3198
+ * A test that names `skipped`, or that fails unless some result is `success`.
3199
+ */
3200
+ const SKIPPED_TEST = /needs\.(?:\*|[\w-]+)\.result[^\n]*['"]skipped['"]|!\s*contains\(\s*needs\.\*\.result\s*,\s*['"]success['"]/u;
3201
+ /**
3202
+ * A read of a job's output, which is what an `if` that skips a job on the result of an earlier one reads.
3203
+ */
3204
+ const OUTPUT_READ = /needs\.[\w-]+\.outputs\.[\w-]+/gu;
3205
+ /**
3206
+ * Whether an `if` can skip the job, its own or that of a job it needs, without the junction job seeing why: a job runs unless an `if` other than `always()` stops it, and a skip that comes only from a need that failed is a failure the junction rightly fails on. A skip is seen when the junction reads every job output those conditions read, as a junction that tests `has-packages` before the result of a job skipped on it does.
3207
+ */
3208
+ function skippableUnseen(workflow, jobId, text) {
3209
+ return workflow.jobs.filter((job) => job.id === jobId || transitiveNeeds(workflow, jobId).has(job.id)).flatMap((job) => job.condition === void 0 || callsAlways(job.condition) ? [] : [job.condition]).some((condition) => {
3210
+ const reads = [...condition.matchAll(OUTPUT_READ)].map((read) => read[0]);
3211
+ return reads.length === 0 || !reads.every((read) => text.includes(read));
3212
+ });
3213
+ }
3214
+ /**
3215
+ * Whether the junction fails when a job it needs is skipped: it names `skipped`, or tests a result for not being `success` where an `if` can skip that job (any of its needs, for `needs.*.result`) unseen.
3216
+ */
3217
+ function failsOnSkipped(workflow, junction, text) {
3218
+ const tested = [...text.matchAll(NOT_SUCCESS)].flatMap((match) => match[1] === "*" ? junction.needs : match[1] ?? []);
3219
+ return SKIPPED_TEST.test(text) || tested.some((id) => skippableUnseen(workflow, id, text));
3220
+ }
3221
+ /**
3222
+ * An `if` that compares the ref or the event name.
3223
+ */
3224
+ const COMPARES_REF_OR_EVENT = /github\.(?:ref|ref_name|event_name)\s*==/u;
3225
+ /**
3012
3226
  * Whether an expression can only hold in runs other than those of a pull request and of a merge group, which are the runs the required check decides on: an operand of an `&&` that does so is enough, every operand of an `||` must, and a comparison of the ref or the event name does so when it names neither `pull_request` nor `merge_group`.
3013
3227
  */
3014
3228
  function keepsOutOfPullRequests(expression) {
@@ -3055,17 +3269,17 @@ function junctionOrdering(workflow, options) {
3055
3269
  if (!callsAlways(junction.condition)) violations.push(workflowViolation(workflow, "workflow-job-ordering/junction-not-always", `junction job '${junction.id}' has no if: always(), so it is skipped, and its required check never reports, when a job it needs fails`, junction.location));
3056
3270
  const missing = workflow.jobs.filter((job) => job.id !== junction.id && !exempt.has(job.id) && !junction.needs.includes(job.id) && !transitiveNeeds(workflow, job.id).has(junction.id));
3057
3271
  for (const job of missing) violations.push(workflowViolation(workflow, "workflow-job-ordering/junction-missing-need", `junction job '${junction.id}' does not list job '${job.id}' in needs, so its result is not part of the required check`, junction.location));
3058
- const text = decisionText(junction);
3272
+ const text = decisionText(workflow, junction);
3059
3273
  const reportsOutcome = junction.steps.some((step) => stepUses(step, OUTCOME_ACTION));
3060
- if (SKIPPED_OR_NOT_SUCCESS.test(text)) violations.push(workflowViolation(workflow, "workflow-job-ordering/junction-fails-on-skipped", `junction job '${junction.id}' fails when a needed job is skipped, but a skipped job is how a path filter or an if keeps a job out; fail only on 'failure' and 'cancelled'`, junction.location));
3061
- if (!reportsOutcome && !(RESULT_SOURCE.test(text) && FAILURE_WORD.test(text) && CANCELLED_WORD.test(text))) violations.push(workflowViolation(workflow, "workflow-job-ordering/junction-no-failure-condition", `junction job '${junction.id}' does not test the results of its needs for both 'failure' and 'cancelled', so it can pass when a job it needs did not succeed`, junction.location));
3274
+ if (failsOnSkipped(workflow, junction, text)) violations.push(workflowViolation(workflow, "workflow-job-ordering/junction-fails-on-skipped", `junction job '${junction.id}' fails when a needed job is skipped, but a skipped job is how a path filter or an if keeps a job out; fail only on 'failure' and 'cancelled'`, junction.location));
3275
+ if (!reportsOutcome && !(RESULT_SOURCE.test(text) && (FAILURE_WORD.test(text) && CANCELLED_WORD.test(text) || [...text.matchAll(NOT_SUCCESS)].length > 0))) violations.push(workflowViolation(workflow, "workflow-job-ordering/junction-no-failure-condition", `junction job '${junction.id}' does not test the results of its needs for both 'failure' and 'cancelled', so it can pass when a job it needs did not succeed`, junction.location));
3062
3276
  }
3063
3277
  return violations;
3064
3278
  }
3065
3279
  /**
3066
3280
  * The jobs that release, deploy and report a required check are ordered so that a failure stops what follows: a release job needs the deploy job, a documentation deploy job needs the release job and checks out the default branch afresh, and one junction job with `if: always()` needs every other job and fails only on `failure` or `cancelled`.
3067
3281
  *
3068
- * Jobs are recognised by id (see the options), and a role with no job in a workflow is not judged there. Ordering is judged through the transitive `needs` graph; the junction job must list every job directly, because `needs.*.result` only covers direct needs, except jobs that never run for a pull request or a merge group (an `if` on `github.ref` or `github.event_name` that mentions neither `pull_request` nor `merge_group`, where an `&&` needs one such operand and an `||` needs every operand to be), jobs that need such a job or the junction job itself, and the ids in `junctionExempt`. What the junction job decides on is read as text: it must read the results of its needs (`needs.*.result`, `needs.<job>.result` or `toJSON(needs)`) and name both `'failure'` and `'cancelled'`, or use the `re-actors/alls-green` action; a result read in a way the text does not show is reported as incomplete.
3282
+ * Jobs are recognised by id (see the options), and a role with no job in a workflow is not judged there. Ordering is judged through the transitive `needs` graph; the junction job must list every job directly, because `needs.*.result` only covers direct needs, except jobs that never run for a pull request or a merge group (an `if` on `github.ref` or `github.event_name` that mentions neither `pull_request` nor `merge_group`, where an `&&` needs one such operand and an `||` needs every operand to be), jobs that need such a job or the junction job itself, and the ids in `junctionExempt`. What the junction job decides on is read as text, with the environment variables its scripts and conditions read replaced by the expressions that set them: it must read the results of its needs (`needs.*.result`, `needs.<job>.result` or `toJSON(needs)`) and name both `'failure'` and `'cancelled'` or test a result for `!= 'success'`, or use the `re-actors/alls-green` action; a result read in a way the text does not show is reported as incomplete. A `!= 'success'` test fails on a skip too, which is reported only for a job an `if` can skip without the junction reading what that `if` reads.
3069
3283
  */
3070
3284
  const workflowJobOrdering = async ({ cwd, options }) => (await loadWorkflows(cwd, options)).flatMap((workflow) => [...releaseAndDocsOrdering(workflow, options), ...junctionOrdering(workflow, options)]);
3071
3285
  //#endregion
@@ -3073,12 +3287,21 @@ const workflowJobOrdering = async ({ cwd, options }) => (await loadWorkflows(cwd
3073
3287
  /**
3074
3288
  * A workflow that checks pull requests also runs for the merge queue: GitHub starts no run of it for a queued pull request unless the workflow has a `merge_group` trigger, and a required check that never reports blocks the queue.
3075
3289
  *
3076
- * A workflow is taken to produce required checks when it is triggered by `pull_request`; `pull_request_target` is left out, since it runs trusted code against untrusted input and is not a place for required checks. The file cannot show which checks are required, so a `pull_request` workflow whose checks are not required is reported too: narrow the check with `workflows` and `exclude`. A `merge_group` trigger on a workflow with no `pull_request` trigger is not judged. Limits: a `merge_group` trigger takes only `branches` filters (`paths` is a filter of `push`, `pull_request` and `pull_request_target`), so a workflow path-filtered for pull requests still runs in the queue once it has the trigger; the `branches` filter of a `merge_group` trigger is not read.
3290
+ * A workflow is taken to produce required checks when it is triggered by `pull_request`; `pull_request_target` is left out, since it runs trusted code against untrusted input and is not a place for required checks. The file cannot show which checks are required, so a `pull_request` workflow whose checks are not required is reported too: narrow the check with `workflows` and `exclude`. A `merge_group` trigger on a workflow with no `pull_request` trigger is not judged.
3291
+ *
3292
+ * Whether the branch has a merge queue is a setting, not something a file shows. Given a GitHub client, the check reads the rules of the branch (`branch`, else the default branch, of `repository`, else the `origin` remote) once it has found a workflow without the trigger, and reports only when a `merge_queue` rule applies, since without a queue no `merge_group` event is ever sent. Offline it cannot tell, so it reports every such workflow.
3293
+ *
3294
+ * Limits: a `merge_group` trigger takes only `branches` filters (`paths` is a filter of `push`, `pull_request` and `pull_request_target`), so a workflow path-filtered for pull requests still runs in the queue once it has the trigger; the `branches` filter of a `merge_group` trigger is not read; only rulesets are read, so a queue configured through classic branch protection is not seen and, with a client, nothing is reported for it.
3077
3295
  */
3078
- const workflowMergeGroup = async ({ cwd, options }) => (await loadWorkflows(cwd, options)).flatMap((workflow) => {
3079
- const location = workflow.triggerLocations.get("pull_request");
3080
- return location === void 0 || workflow.triggers.has("merge_group") ? [] : [workflowViolation(workflow, "workflow-merge-group/missing-trigger", "the workflow runs for pull requests but has no merge_group trigger, so its checks do not report for a pull request in the merge queue", location)];
3081
- });
3296
+ const workflowMergeGroup = async ({ cwd, options, github }) => {
3297
+ const violations = (await loadWorkflows(cwd, options)).flatMap((workflow) => {
3298
+ const location = workflow.triggerLocations.get("pull_request");
3299
+ return location === void 0 || workflow.triggers.has("merge_group") ? [] : [workflowViolation(workflow, "workflow-merge-group/missing-trigger", "the workflow runs for pull requests but has no merge_group trigger, so its checks do not report for a pull request in the merge queue", location)];
3300
+ });
3301
+ if (violations.length === 0 || github === void 0) return violations;
3302
+ const slug = await repositoryOf(cwd, options);
3303
+ return (await github.branchRules(slug, await branchOf(github, slug, options))).mergeQueue ? violations : [];
3304
+ };
3082
3305
  //#endregion
3083
3306
  //#region src/checks/workflow-release-job.ts
3084
3307
  const CHECKOUT_ACTION$1 = "actions/checkout";
@@ -3273,7 +3496,7 @@ const workflowRepositoryDispatch = async ({ cwd, options }) => (await loadWorkfl
3273
3496
  //#endregion
3274
3497
  //#region src/checks/workflow-runner-resolution.ts
3275
3498
  /**
3276
- * GitHub's own images: `ubuntu`, `windows` and `macos`, as `-latest`, a version, or a version with an architecture or size suffix, and `ubuntu-slim`.
3499
+ * The `hostedLabels` used when the options set none: GitHub's own images, `ubuntu`, `windows` and `macos`, as `-latest`, a version, or a version with an architecture or size suffix, and `ubuntu-slim`. Setting `hostedLabels` replaces it, so a workflow that also falls back to a third-party hosted runner extends it: `[...DEFAULT_HOSTED_LABELS, '^blacksmith-']`.
3277
3500
  */
3278
3501
  const DEFAULT_HOSTED_LABELS = ["^(?:ubuntu|windows|macos)-(?:latest|slim|[0-9][0-9.]*)(?:-(?:arm|intel|xlarge|large))*$"];
3279
3502
  /**
@@ -3285,10 +3508,6 @@ const RESOLVED_RUNNER = /fromJSON\(\s*needs\.([\w-]+)\.outputs\.([\w-]+)\s*\)/gi
3285
3508
  */
3286
3509
  const JOB_OUTPUT_REFERENCE = /^\$\{\{\s*jobs\.([\w-]+)\.outputs\.([\w-]+)\s*\}\}$/u;
3287
3510
  /**
3288
- * A fallback in an output expression: `||` followed by a string literal, whose body may hold `''` for a quote.
3289
- */
3290
- const LITERAL_FALLBACK = /\|\|\s*'((?:[^']|'')*)'/gu;
3291
- /**
3292
3511
  * The resolver behind each `fromJson(needs.<job>.outputs.<name>)` in a `runs-on` of the workflow; none for one this check cannot read.
3293
3512
  */
3294
3513
  function resolversOf(workflow, workflows) {
@@ -3306,7 +3525,8 @@ function implementation(workflow, workflows, caller, output) {
3306
3525
  if (caller.uses === void 0) return {
3307
3526
  workflow,
3308
3527
  job: caller,
3309
- output
3528
+ output,
3529
+ inputs: {}
3310
3530
  };
3311
3531
  const reference = parseUses(caller.uses);
3312
3532
  if (reference.kind !== "local") return;
@@ -3315,17 +3535,22 @@ function implementation(workflow, workflows, caller, output) {
3315
3535
  const forwarded = JOB_OUTPUT_REFERENCE.exec(called.callOutputs[output] ?? "");
3316
3536
  const job = called.jobs.find((candidate) => candidate.id === forwarded?.[1]);
3317
3537
  const jobOutput = forwarded?.[2];
3538
+ const inputs = Object.fromEntries(Object.entries(called.callInputs).map(([name, fallback]) => {
3539
+ const passed = caller.with[name];
3540
+ return [name, passed === void 0 ? fallback : hasExpression(passed) ? void 0 : passed];
3541
+ }));
3318
3542
  return job === void 0 || jobOutput === void 0 ? void 0 : {
3319
3543
  workflow: called,
3320
3544
  job,
3321
- output: jobOutput
3545
+ output: jobOutput,
3546
+ inputs
3322
3547
  };
3323
3548
  }
3324
3549
  /**
3325
- * The runner labels the last literal fallback of an output expression names, read as the JSON the `fromJson` that consumes it expects: a label or a list of labels. `undefined` when there is no literal fallback, and an empty list when the literal is not labels.
3550
+ * The runner labels the fallback of an output expression names, read as the JSON the `fromJson` that consumes it expects: a label or a list of labels. The fallback is the first operand after the first of the expression's top-level `||` chain whose value is the same on every run and not empty (see `constantString`), which is what the chain yields when the operands before it are empty. `undefined` when there is no such operand, and an empty list when its value is not labels.
3326
3551
  */
3327
- function fallbackLabels(expression) {
3328
- const literal = [...expression.matchAll(LITERAL_FALLBACK)].at(-1)?.[1]?.replaceAll("''", "'");
3552
+ function fallbackLabels(expression, inputs) {
3553
+ const literal = operands(unwrapped(expression), "||").slice(1).map((operand) => constantString(operand, inputs)).find((value) => value !== void 0 && value !== "");
3329
3554
  if (literal === void 0) return;
3330
3555
  let parsed;
3331
3556
  try {
@@ -3340,9 +3565,13 @@ function fallbackLabels(expression) {
3340
3565
  function resolverViolations(resolver, hosted) {
3341
3566
  const violations = [];
3342
3567
  if (resolver.job.timeoutMinutes === void 0) violations.push(workflowViolation(resolver.workflow, "workflow-runner-resolution/resolver-no-timeout", `resolver job '${resolver.job.id}' has no timeout-minutes, so a runner that never starts holds every job waiting for it until the default six hours`, resolver.job.location));
3343
- const fallback = fallbackLabels(resolver.job.outputs[resolver.output] ?? "");
3344
- if (fallback === void 0) violations.push(workflowViolation(resolver.workflow, "workflow-runner-resolution/resolver-no-fallback", `output '${resolver.output}' of resolver job '${resolver.job.id}' has no literal fallback (\`|| '["<hosted label>"]'\`), so the jobs that read it have no runner when resolution produces nothing`, resolver.job.location));
3345
- else if (fallback.length === 0 || !fallback.every((label) => hosted.some((pattern) => pattern.test(label)))) violations.push(workflowViolation(resolver.workflow, "workflow-runner-resolution/resolver-fallback-not-hosted", `the literal fallback of output '${resolver.output}' of resolver job '${resolver.job.id}' does not name only hosted runner labels, so it offers no runner when the self-hosted fleet is down`, resolver.job.location));
3568
+ const fallback = fallbackLabels(resolver.job.outputs[resolver.output] ?? "", resolver.inputs);
3569
+ if (fallback === void 0) violations.push(workflowViolation(resolver.workflow, "workflow-runner-resolution/resolver-no-fallback", `output '${resolver.output}' of resolver job '${resolver.job.id}' has no fallback whose value is known before the run (\`|| '["<hosted label>"]'\`, or format() of literals and of inputs with a literal value), so the jobs that read it have no runner when resolution produces nothing`, resolver.job.location));
3570
+ else if (fallback.length === 0) violations.push(workflowViolation(resolver.workflow, "workflow-runner-resolution/resolver-fallback-not-hosted", `the literal fallback of output '${resolver.output}' of resolver job '${resolver.job.id}' is not a runner label or a non-empty list of them, so the jobs that read it have no runner when resolution produces nothing`, resolver.job.location));
3571
+ else {
3572
+ const unhosted = fallback.filter((label) => !hosted.some((pattern) => pattern.test(label)));
3573
+ if (unhosted.length > 0) violations.push(workflowViolation(resolver.workflow, "workflow-runner-resolution/resolver-fallback-not-hosted", `the literal fallback of output '${resolver.output}' of resolver job '${resolver.job.id}' names ${unhosted.map((label) => `'${label}'`).join(", ")}, which ${unhosted.length === 1 ? "matches" : "match"} no pattern of hostedLabels, so it is not known to offer a runner when resolution produces nothing; name a hosted label, or add the label's pattern to hostedLabels (extending DEFAULT_HOSTED_LABELS) if it is hosted, by GitHub or by a third party`, resolver.job.location));
3574
+ }
3346
3575
  return violations;
3347
3576
  }
3348
3577
  function customLabels(job, hosted) {
@@ -3362,14 +3591,14 @@ function repeatedLabels(workflow, hosted) {
3362
3591
  /**
3363
3592
  * A self-hosted or custom runner label named literally in more than one job of a workflow is resolved once instead: a resolver job decides the runner and the others read it with `fromJson(needs.<resolver>.outputs.<name>)`. The resolver must have a `timeout-minutes` and its output a literal fallback that names only hosted runner labels, so jobs still get a runner when resolution fails or the self-hosted fleet is down.
3364
3593
  *
3365
- * A label is custom when it matches none of `hostedLabels`; the default patterns recognise GitHub's standard images, so a larger runner is named by a custom label and counts. Labels are compared within a workflow file, not across files. A resolver that is a reusable workflow is followed when it is a file of this repository (the output is traced through `on.workflow_call.outputs` to the job that sets it); a resolver in another repository cannot be read and is not judged. An output is taken to have a fallback when its expression has `||` followed by a string literal, and the last such literal is read as JSON (a label or a list of labels) and matched against `hostedLabels`; a fallback that is not valid JSON, or names any other label, is reported.
3594
+ * A label is custom when it matches none of `hostedLabels`; the default patterns recognise GitHub's standard images, so a larger runner is named by a custom label and counts. Labels are compared within a workflow file, not across files. A resolver that is a reusable workflow is followed when it is a file of this repository (the output is traced through `on.workflow_call.outputs` to the job that sets it); a resolver in another repository cannot be read and is not judged. An output's fallback is the first operand after the first of its expression's top-level `||` chain whose value is the same on every run: a string literal, or `format()` of literals and of inputs of the reusable workflow, read from the literal the caller passes or else the input's default. It is read as JSON (a label or a list of labels) and matched against `hostedLabels`; a fallback that is not valid JSON, or names any other label, is reported, and an output with no such operand has no fallback.
3366
3595
  */
3367
3596
  const workflowRunnerResolution = async ({ cwd, options }) => {
3368
3597
  const hosted = (options.hostedLabels ?? DEFAULT_HOSTED_LABELS).map((source) => new RegExp(source, "u"));
3369
3598
  const selected = await loadWorkflows(cwd, options);
3370
3599
  const available = await loadWorkflows(cwd, { workflows: DEFAULT_WORKFLOWS });
3371
3600
  const resolvers = /* @__PURE__ */ new Map();
3372
- for (const workflow of selected) for (const resolver of resolversOf(workflow, available)) resolvers.set(`${resolver.workflow.file}#${resolver.job.id}#${resolver.output}`, resolver);
3601
+ for (const workflow of selected) for (const resolver of resolversOf(workflow, available)) resolvers.set(`${resolver.workflow.file}#${resolver.job.id}#${resolver.output}#${JSON.stringify(resolver.inputs)}`, resolver);
3373
3602
  return [...selected.flatMap((workflow) => repeatedLabels(workflow, hosted)), ...[...resolvers.values()].flatMap((resolver) => resolverViolations(resolver, hosted))];
3374
3603
  };
3375
3604
  //#endregion
@@ -3735,7 +3964,10 @@ const checks = zod.z.strictObject({
3735
3964
  dependabot: zod.z.exactOptional(path),
3736
3965
  renovate: zod.z.exactOptional(path)
3737
3966
  }))),
3738
- "workflow-merge-group": zod.z.exactOptional(enabled(zod.z.strictObject(selection))),
3967
+ "workflow-merge-group": zod.z.exactOptional(enabled(zod.z.strictObject({
3968
+ ...selection,
3969
+ ...settings
3970
+ }))),
3739
3971
  "workflow-action-pinning": zod.z.exactOptional(enabled(zod.z.strictObject({
3740
3972
  ...selection,
3741
3973
  thirdParty: zod.z.exactOptional(pinningLevel),
@@ -3814,6 +4046,25 @@ function online(spec) {
3814
4046
  }
3815
4047
  };
3816
4048
  }
4049
+ function settingsAware(spec) {
4050
+ return {
4051
+ name: spec.name,
4052
+ description: spec.description,
4053
+ requiresLayout: false,
4054
+ requiresGitHub: false,
4055
+ isEnabled: (checks) => spec.select(checks) !== void 0,
4056
+ run: async ({ cwd, checks, configFiles, github }) => {
4057
+ const options = spec.select(checks);
4058
+ if (options === void 0) throw new ConformanceError(`the check '${spec.name}' is not enabled`);
4059
+ return spec.check({
4060
+ cwd,
4061
+ options,
4062
+ ...github === void 0 ? {} : { github },
4063
+ ...configFiles === void 0 ? {} : { configFiles }
4064
+ });
4065
+ }
4066
+ };
4067
+ }
3817
4068
  function importCheck(spec) {
3818
4069
  return {
3819
4070
  name: spec.name,
@@ -3975,7 +4226,7 @@ const registry = {
3975
4226
  select: (checks) => enabledOptions(checks["workflow-update-bot-cooldown"]),
3976
4227
  check: workflowUpdateBotCooldown
3977
4228
  }),
3978
- "workflow-merge-group": plain({
4229
+ "workflow-merge-group": settingsAware({
3979
4230
  name: "workflow-merge-group",
3980
4231
  description: "A workflow that runs for pull requests also runs for the merge queue",
3981
4232
  select: (checks) => enabledOptions(checks["workflow-merge-group"]),
@@ -4142,7 +4393,9 @@ var ExhaustivenessError = class extends Error {
4142
4393
  }
4143
4394
  };
4144
4395
  /**
4145
- * Compiler options for the in-memory programs: strict, ESM, no libraries beyond the language's own, and no ambient types. Only what a self-contained snippet needs.
4396
+ * Compiler options for the in-memory programs: strict, ESM, the target's default library (for ES2022 that is `lib.es2022.full.d.ts`, which includes the DOM), and no ambient types. Only what a self-contained snippet needs.
4397
+ *
4398
+ * `skipDefaultLibCheck` leaves TypeScript's own library files unchecked, so diagnostics cover the snippet and not the library's declarations, which otherwise dominate the cost of every program. Errors in the snippet's own files, declaration files included, are still reported.
4146
4399
  */
4147
4400
  const SNIPPET_COMPILER_OPTIONS = {
4148
4401
  strict: true,
@@ -4150,7 +4403,8 @@ const SNIPPET_COMPILER_OPTIONS = {
4150
4403
  target: ts_morph.ScriptTarget.ES2022,
4151
4404
  module: ts_morph.ModuleKind.ESNext,
4152
4405
  moduleResolution: ts_morph.ModuleResolutionKind.Bundler,
4153
- types: []
4406
+ types: [],
4407
+ skipDefaultLibCheck: true
4154
4408
  };
4155
4409
  function inMemoryProject(files, options) {
4156
4410
  const project = new ts_morph.Project({
@@ -4164,15 +4418,41 @@ function inMemoryProject(files, options) {
4164
4418
  return project;
4165
4419
  }
4166
4420
  /**
4421
+ * One project per distinct set of compiler options, kept for the life of the module so that the default library is parsed and bound once instead of once per program. {@link typeErrors} adds its files to the project and removes them before it returns, so a call never sees another call's files.
4422
+ */
4423
+ const projectsByOptions = /* @__PURE__ */ new Map();
4424
+ function sharedProject(options) {
4425
+ const compilerOptions = {
4426
+ ...SNIPPET_COMPILER_OPTIONS,
4427
+ ...options
4428
+ };
4429
+ const key = JSON.stringify(compilerOptions);
4430
+ const existing = projectsByOptions.get(key);
4431
+ if (existing !== void 0) return existing;
4432
+ const project = new ts_morph.Project({
4433
+ useInMemoryFileSystem: true,
4434
+ compilerOptions
4435
+ });
4436
+ projectsByOptions.set(key, project);
4437
+ return project;
4438
+ }
4439
+ /**
4167
4440
  * Compile the files in memory and return every error the type checker reports. Names are paths in the in-memory file system, so one file can import another with a relative path.
4168
4441
  */
4169
4442
  function typeErrors(files, options = {}) {
4170
- return inMemoryProject(files, options).getPreEmitDiagnostics().map((diagnostic) => ({
4171
- file: diagnostic.getSourceFile()?.getBaseName() ?? "",
4172
- line: diagnostic.getLineNumber() ?? 0,
4173
- code: diagnostic.getCode(),
4174
- message: ts_morph.ts.flattenDiagnosticMessageText(diagnostic.compilerObject.messageText, "\n")
4175
- }));
4443
+ const project = sharedProject(options);
4444
+ const added = [];
4445
+ try {
4446
+ for (const [name, source] of Object.entries(files)) added.push(project.createSourceFile(name, source));
4447
+ return project.getPreEmitDiagnostics().map((diagnostic) => ({
4448
+ file: diagnostic.getSourceFile()?.getBaseName() ?? "",
4449
+ line: diagnostic.getLineNumber() ?? 0,
4450
+ code: diagnostic.getCode(),
4451
+ message: ts_morph.ts.flattenDiagnosticMessageText(diagnostic.compilerObject.messageText, "\n")
4452
+ }));
4453
+ } finally {
4454
+ for (const sourceFile of added) project.removeSourceFile(sourceFile);
4455
+ }
4176
4456
  }
4177
4457
  function handlerMap(source, map) {
4178
4458
  let initializer = source.getVariableDeclaration(map)?.getInitializer();
@@ -4226,6 +4506,7 @@ function proveExhaustive(input) {
4226
4506
  //#endregion
4227
4507
  exports.ConformanceError = ConformanceError;
4228
4508
  exports.DEFAULT_DERIVED_TYPE_INFERENCES = DEFAULT_DERIVED_TYPE_INFERENCES;
4509
+ exports.DEFAULT_HOSTED_LABELS = DEFAULT_HOSTED_LABELS;
4229
4510
  exports.DEFAULT_INFERENCES = DEFAULT_INFERENCES;
4230
4511
  exports.DEFAULT_WORKFLOWS = DEFAULT_WORKFLOWS;
4231
4512
  exports.EXIT_CODES = EXIT_CODES;