@webpieces/pr-gate 0.4.809 → 0.4.811

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.
Files changed (28) hide show
  1. package/package.json +3 -3
  2. package/src/index.d.ts +8 -0
  3. package/src/index.js +27 -1
  4. package/src/index.js.map +1 -1
  5. package/src/scripts/commands/finish-upsert-pr-command.d.ts +10 -1
  6. package/src/scripts/commands/finish-upsert-pr-command.js +38 -6
  7. package/src/scripts/commands/finish-upsert-pr-command.js.map +1 -1
  8. package/src/scripts/workflow/contract/consumer-bin-resolver.d.ts +62 -0
  9. package/src/scripts/workflow/contract/consumer-bin-resolver.js +152 -0
  10. package/src/scripts/workflow/contract/consumer-bin-resolver.js.map +1 -0
  11. package/src/scripts/workflow/contract/contract-diff-renderer.d.ts +53 -0
  12. package/src/scripts/workflow/contract/contract-diff-renderer.js +103 -0
  13. package/src/scripts/workflow/contract/contract-diff-renderer.js.map +1 -0
  14. package/src/scripts/workflow/contract/contract-diff-step.d.ts +67 -0
  15. package/src/scripts/workflow/contract/contract-diff-step.js +192 -0
  16. package/src/scripts/workflow/contract/contract-diff-step.js.map +1 -0
  17. package/src/scripts/workflow/contract/generator-package.d.ts +29 -0
  18. package/src/scripts/workflow/contract/generator-package.js +38 -0
  19. package/src/scripts/workflow/contract/generator-package.js.map +1 -0
  20. package/src/scripts/workflow/contract/generator-runner.d.ts +22 -0
  21. package/src/scripts/workflow/contract/generator-runner.js +44 -0
  22. package/src/scripts/workflow/contract/generator-runner.js.map +1 -0
  23. package/src/scripts/workflow/contract/json-value.d.ts +6 -0
  24. package/src/scripts/workflow/contract/json-value.js +3 -0
  25. package/src/scripts/workflow/contract/json-value.js.map +1 -0
  26. package/src/scripts/workflow/contract/openapi-contract-diff.d.ts +45 -0
  27. package/src/scripts/workflow/contract/openapi-contract-diff.js +158 -0
  28. package/src/scripts/workflow/contract/openapi-contract-diff.js.map +1 -0
@@ -0,0 +1,152 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ConsumerBinResolver = exports.ConsumerBin = exports.ConsumerBinRequest = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const fs = tslib_1.__importStar(require("fs"));
6
+ const path = tslib_1.__importStar(require("path"));
7
+ const rules_config_1 = require("@webpieces/rules-config");
8
+ const inversify_1 = require("inversify");
9
+ /** What to resolve, and who is asking. Data-only, per CLAUDE.md. */
10
+ class ConsumerBinRequest {
11
+ ruleName;
12
+ generator;
13
+ searchFrom;
14
+ constructor(
15
+ /** The failing target's name, so a refusal says WHICH step could not find its generator. */
16
+ ruleName, generator,
17
+ /**
18
+ * The CONSUMER's directories, nearest first — the project root, then the workspace root. Lookup
19
+ * walks up from each exactly as node does, and never from the caller's own install location.
20
+ */
21
+ searchFrom) {
22
+ this.ruleName = ruleName;
23
+ this.generator = generator;
24
+ this.searchFrom = searchFrom;
25
+ }
26
+ }
27
+ exports.ConsumerBinRequest = ConsumerBinRequest;
28
+ /** One generator bin, resolved out of the consumer's `node_modules`. Data-only. */
29
+ class ConsumerBin {
30
+ packageName;
31
+ version;
32
+ packageJson;
33
+ binPath;
34
+ constructor(packageName, version,
35
+ /** The installed package.json this was read from. */
36
+ packageJson,
37
+ /** Absolute path to the bin's entry script. */
38
+ binPath) {
39
+ this.packageName = packageName;
40
+ this.version = version;
41
+ this.packageJson = packageJson;
42
+ this.binPath = binPath;
43
+ }
44
+ }
45
+ exports.ConsumerBin = ConsumerBin;
46
+ /** A parsed `X.Y.Z[-pre]`. A prerelease sorts BELOW its release, which is what semver says. */
47
+ class ReleaseVersion {
48
+ major;
49
+ minor;
50
+ patch;
51
+ prerelease;
52
+ constructor(major, minor, patch, prerelease) {
53
+ this.major = major;
54
+ this.minor = minor;
55
+ this.patch = patch;
56
+ this.prerelease = prerelease;
57
+ }
58
+ isAtLeast(other) {
59
+ if (this.major !== other.major)
60
+ return this.major > other.major;
61
+ if (this.minor !== other.minor)
62
+ return this.minor > other.minor;
63
+ if (this.patch !== other.patch)
64
+ return this.patch > other.patch;
65
+ return !this.prerelease || other.prerelease;
66
+ }
67
+ }
68
+ /**
69
+ * Finds a generator bin in the CONSUMER's `node_modules`, never in a copy bundled beside the caller,
70
+ * and refuses one too old to have the capabilities the caller needs.
71
+ *
72
+ * ## Why never a bundled copy
73
+ *
74
+ * The generator reads the decorators the consumer's contracts are written with, so it must be the
75
+ * release the consumer pinned alongside those decorators. A copy shipped inside the nx plugin would be
76
+ * the PLUGIN's release — the rules stream, which a repo deliberately runs one release behind — and would
77
+ * document an app with a reader from a different release. The lookup therefore starts only from the
78
+ * directories the caller names (the consumer's project and workspace), and walks up from each exactly
79
+ * as node's resolution does. It never consults `require.resolve` from this file, which is the one
80
+ * lookup that WOULD find a bundled copy.
81
+ *
82
+ * ## The version handshake
83
+ *
84
+ * A capability always ships in the generator (the server stream) BEFORE a caller relies on it, so an
85
+ * installed generator older than `minimumVersion` is a pin to bump, never a bug to work around. The
86
+ * refusal names the bump: `@webpieces/openapi-generator >= X.Y.Z`.
87
+ */
88
+ let ConsumerBinResolver = class ConsumerBinResolver {
89
+ resolve(request) {
90
+ const packageJson = this.findPackageJson(request);
91
+ const manifest = JSON.parse(fs.readFileSync(packageJson, 'utf8'));
92
+ const version = typeof manifest['version'] === 'string' ? manifest['version'] : '';
93
+ this.assertNewEnough(request, packageJson, version);
94
+ const binPath = this.binPathOf(request, packageJson, manifest);
95
+ return new ConsumerBin(request.generator.packageName, version, packageJson, binPath);
96
+ }
97
+ findPackageJson(request) {
98
+ for (const start of request.searchFrom) {
99
+ let dir = path.resolve(start);
100
+ for (;;) {
101
+ const candidate = path.join(dir, 'node_modules', ...request.generator.packageName.split('/'), 'package.json');
102
+ if (fs.existsSync(candidate))
103
+ return candidate;
104
+ const parent = path.dirname(dir);
105
+ if (parent === dir)
106
+ break;
107
+ dir = parent;
108
+ }
109
+ }
110
+ throw new rules_config_1.RuleFailError(request.ruleName, `${request.generator.packageName} is not installed in this workspace (looked in node_modules at and above: ` +
111
+ `${request.searchFrom.join(', ')}). The generator must be the consumer's OWN install — the ` +
112
+ `release pinned beside the decorators it reads — and is never taken from a bundled copy.`, undefined, undefined, [new rules_config_1.Option(`Add it as a devDependency: ${request.generator.packageName} >= ${request.generator.minimumVersion}`, true)]);
113
+ }
114
+ assertNewEnough(request, packageJson, version) {
115
+ const minimum = this.parseVersion(request.generator.minimumVersion);
116
+ if (minimum === undefined) {
117
+ // Our own constant, not the consumer's input — a malformed one is a webpieces bug.
118
+ throw new Error(`minimumVersion '${request.generator.minimumVersion}' for ${request.generator.packageName} is not X.Y.Z`);
119
+ }
120
+ const installed = this.parseVersion(version);
121
+ if (installed !== undefined && installed.isAtLeast(minimum))
122
+ return;
123
+ throw new rules_config_1.RuleFailError(request.ruleName, `${request.generator.packageName} ${version === '' ? '(no version)' : version} is installed at ${packageJson}, ` +
124
+ `and ${request.ruleName} needs ${request.generator.packageName} >= ${request.generator.minimumVersion}.` +
125
+ (installed !== undefined && installed.prerelease
126
+ ? ' A prerelease such as a workspace link\'s 0.0.0-dev is not a release and has no compiled bin.'
127
+ : ''), undefined, undefined, [new rules_config_1.Option(`Bump the devDependency to ${request.generator.packageName} >= ${request.generator.minimumVersion}`, true)]);
128
+ }
129
+ /** `X.Y.Z[-pre]`, or `undefined` for anything else — which the handshake then refuses. */
130
+ parseVersion(text) {
131
+ const match = /^(\d+)\.(\d+)\.(\d+)(-.+)?$/.exec(text.trim());
132
+ if (match === null)
133
+ return undefined;
134
+ return new ReleaseVersion(Number(match[1]), Number(match[2]), Number(match[3]), match[4] !== undefined);
135
+ }
136
+ binPathOf(request, packageJson, manifest) {
137
+ const bin = manifest['bin'];
138
+ const declared = typeof bin === 'string'
139
+ ? bin
140
+ : (bin !== null && typeof bin === 'object' && !Array.isArray(bin) ? bin[request.generator.binName] : undefined);
141
+ const binPath = typeof declared === 'string' ? path.resolve(path.dirname(packageJson), declared) : '';
142
+ if (binPath !== '' && fs.existsSync(binPath))
143
+ return binPath;
144
+ throw new rules_config_1.RuleFailError(request.ruleName, `${request.generator.packageName} at ${packageJson} declares no runnable '${request.generator.binName}' bin` +
145
+ (binPath === '' ? '.' : ` (${binPath} does not exist).`), undefined, undefined, [new rules_config_1.Option(`Reinstall a published release: ${request.generator.packageName} >= ${request.generator.minimumVersion}`, true)]);
146
+ }
147
+ };
148
+ exports.ConsumerBinResolver = ConsumerBinResolver;
149
+ exports.ConsumerBinResolver = ConsumerBinResolver = tslib_1.__decorate([
150
+ (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton)
151
+ ], ConsumerBinResolver);
152
+ //# sourceMappingURL=consumer-bin-resolver.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"consumer-bin-resolver.js","sourceRoot":"","sources":["../../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/contract/consumer-bin-resolver.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,0DAAgE;AAChE,yCAA2D;AAI3D,oEAAoE;AACpE,MAAa,kBAAkB;IAGd;IACA;IAKA;IARb;IACI,4FAA4F;IACnF,QAAgB,EAChB,SAA2B;IACpC;;;OAGG;IACM,UAA6B;QAN7B,aAAQ,GAAR,QAAQ,CAAQ;QAChB,cAAS,GAAT,SAAS,CAAkB;QAK3B,eAAU,GAAV,UAAU,CAAmB;IACvC,CAAC;CACP;AAXD,gDAWC;AAED,mFAAmF;AACnF,MAAa,WAAW;IAEP;IACA;IAEA;IAEA;IANb,YACa,WAAmB,EACnB,OAAe;IACxB,qDAAqD;IAC5C,WAAmB;IAC5B,+CAA+C;IACtC,OAAe;QALf,gBAAW,GAAX,WAAW,CAAQ;QACnB,YAAO,GAAP,OAAO,CAAQ;QAEf,gBAAW,GAAX,WAAW,CAAQ;QAEnB,YAAO,GAAP,OAAO,CAAQ;IACzB,CAAC;CACP;AATD,kCASC;AAED,+FAA+F;AAC/F,MAAM,cAAc;IAEH;IACA;IACA;IACA;IAJb,YACa,KAAa,EACb,KAA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sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;GAC5B,mBAAmB,CA4E/B","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { Option, RuleFailError } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { GeneratorPackage } from './generator-package';\nimport { JsonObject } from './json-value';\n\n/** What to resolve, and who is asking. Data-only, per CLAUDE.md. */\nexport class ConsumerBinRequest {\n constructor(\n /** The failing target's name, so a refusal says WHICH step could not find its generator. */\n readonly ruleName: string,\n readonly generator: GeneratorPackage,\n /**\n * The CONSUMER's directories, nearest first — the project root, then the workspace root. Lookup\n * walks up from each exactly as node does, and never from the caller's own install location.\n */\n readonly searchFrom: readonly string[],\n ) {}\n}\n\n/** One generator bin, resolved out of the consumer's `node_modules`. Data-only. */\nexport class ConsumerBin {\n constructor(\n readonly packageName: string,\n readonly version: string,\n /** The installed package.json this was read from. */\n readonly packageJson: string,\n /** Absolute path to the bin's entry script. */\n readonly binPath: string,\n ) {}\n}\n\n/** A parsed `X.Y.Z[-pre]`. A prerelease sorts BELOW its release, which is what semver says. */\nclass ReleaseVersion {\n constructor(\n readonly major: number,\n readonly minor: number,\n readonly patch: number,\n readonly prerelease: boolean,\n ) {}\n\n isAtLeast(other: ReleaseVersion): boolean {\n if (this.major !== other.major) return this.major > other.major;\n if (this.minor !== other.minor) return this.minor > other.minor;\n if (this.patch !== other.patch) return this.patch > other.patch;\n return !this.prerelease || other.prerelease;\n }\n}\n\n/**\n * Finds a generator bin in the CONSUMER's `node_modules`, never in a copy bundled beside the caller,\n * and refuses one too old to have the capabilities the caller needs.\n *\n * ## Why never a bundled copy\n *\n * The generator reads the decorators the consumer's contracts are written with, so it must be the\n * release the consumer pinned alongside those decorators. A copy shipped inside the nx plugin would be\n * the PLUGIN's release — the rules stream, which a repo deliberately runs one release behind — and would\n * document an app with a reader from a different release. The lookup therefore starts only from the\n * directories the caller names (the consumer's project and workspace), and walks up from each exactly\n * as node's resolution does. It never consults `require.resolve` from this file, which is the one\n * lookup that WOULD find a bundled copy.\n *\n * ## The version handshake\n *\n * A capability always ships in the generator (the server stream) BEFORE a caller relies on it, so an\n * installed generator older than `minimumVersion` is a pin to bump, never a bug to work around. The\n * refusal names the bump: `@webpieces/openapi-generator >= X.Y.Z`.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ConsumerBinResolver {\n resolve(request: ConsumerBinRequest): ConsumerBin {\n const packageJson = this.findPackageJson(request);\n const manifest = JSON.parse(fs.readFileSync(packageJson, 'utf8')) as JsonObject;\n const version = typeof manifest['version'] === 'string' ? manifest['version'] : '';\n this.assertNewEnough(request, packageJson, version);\n const binPath = this.binPathOf(request, packageJson, manifest);\n return new ConsumerBin(request.generator.packageName, version, packageJson, binPath);\n }\n\n private findPackageJson(request: ConsumerBinRequest): string {\n for (const start of request.searchFrom) {\n let dir = path.resolve(start);\n for (;;) {\n const candidate = path.join(dir, 'node_modules', ...request.generator.packageName.split('/'), 'package.json');\n if (fs.existsSync(candidate)) return candidate;\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n }\n throw new RuleFailError(\n request.ruleName,\n `${request.generator.packageName} is not installed in this workspace (looked in node_modules at and above: ` +\n `${request.searchFrom.join(', ')}). The generator must be the consumer's OWN install — the ` +\n `release pinned beside the decorators it reads — and is never taken from a bundled copy.`,\n undefined,\n undefined,\n [new Option(`Add it as a devDependency: ${request.generator.packageName} >= ${request.generator.minimumVersion}`, true)],\n );\n }\n\n private assertNewEnough(request: ConsumerBinRequest, packageJson: string, version: string): void {\n const minimum = this.parseVersion(request.generator.minimumVersion);\n if (minimum === undefined) {\n // Our own constant, not the consumer's input — a malformed one is a webpieces bug.\n throw new Error(`minimumVersion '${request.generator.minimumVersion}' for ${request.generator.packageName} is not X.Y.Z`);\n }\n const installed = this.parseVersion(version);\n if (installed !== undefined && installed.isAtLeast(minimum)) return;\n throw new RuleFailError(\n request.ruleName,\n `${request.generator.packageName} ${version === '' ? '(no version)' : version} is installed at ${packageJson}, ` +\n `and ${request.ruleName} needs ${request.generator.packageName} >= ${request.generator.minimumVersion}.` +\n (installed !== undefined && installed.prerelease\n ? ' A prerelease such as a workspace link\\'s 0.0.0-dev is not a release and has no compiled bin.'\n : ''),\n undefined,\n undefined,\n [new Option(`Bump the devDependency to ${request.generator.packageName} >= ${request.generator.minimumVersion}`, true)],\n );\n }\n\n /** `X.Y.Z[-pre]`, or `undefined` for anything else — which the handshake then refuses. */\n private parseVersion(text: string): ReleaseVersion | undefined {\n const match = /^(\\d+)\\.(\\d+)\\.(\\d+)(-.+)?$/.exec(text.trim());\n if (match === null) return undefined;\n return new ReleaseVersion(Number(match[1]), Number(match[2]), Number(match[3]), match[4] !== undefined);\n }\n\n private binPathOf(request: ConsumerBinRequest, packageJson: string, manifest: JsonObject): string {\n const bin = manifest['bin'];\n const declared = typeof bin === 'string'\n ? bin\n : (bin !== null && typeof bin === 'object' && !Array.isArray(bin) ? (bin as JsonObject)[request.generator.binName] : undefined);\n const binPath = typeof declared === 'string' ? path.resolve(path.dirname(packageJson), declared) : '';\n if (binPath !== '' && fs.existsSync(binPath)) return binPath;\n throw new RuleFailError(\n request.ruleName,\n `${request.generator.packageName} at ${packageJson} declares no runnable '${request.generator.binName}' bin` +\n (binPath === '' ? '.' : ` (${binPath} does not exist).`),\n undefined,\n undefined,\n [new Option(`Reinstall a published release: ${request.generator.packageName} >= ${request.generator.minimumVersion}`, true)],\n );\n }\n}\n"]}
@@ -0,0 +1,53 @@
1
+ import { ContractChange } from './openapi-contract-diff';
2
+ /** Hidden marker that identifies the contract-diff comment among all comments on a PR. */
3
+ export declare const CONTRACT_DIFF_COMMENT_MARKER = "<!-- webpieces-contract-diff -->";
4
+ /** One declared contract's partner-facing difference, merge-base → HEAD. Data-only. */
5
+ export declare class ContractDiffSection {
6
+ /** The `openapi-generate` target's project. */
7
+ readonly projectName: string;
8
+ /** Workspace-relative manifest path. */
9
+ readonly manifest: string;
10
+ /** The document diffed, e.g. `public-openapi.json`. */
11
+ readonly documentName: string;
12
+ readonly baseSha: string;
13
+ readonly headSha: string;
14
+ /**
15
+ * Why the merge-base side is not a document, or '' when it is. A brand-new contract, or a
16
+ * merge-base today's generator refuses; either way every HEAD item then reads as `added`.
17
+ */
18
+ readonly baseNote: string;
19
+ /** True when HEAD's contracts publish no partner-facing document at all. */
20
+ readonly headHasNoDocument: boolean;
21
+ readonly changes: readonly ContractChange[];
22
+ constructor(
23
+ /** The `openapi-generate` target's project. */
24
+ projectName: string,
25
+ /** Workspace-relative manifest path. */
26
+ manifest: string,
27
+ /** The document diffed, e.g. `public-openapi.json`. */
28
+ documentName: string, baseSha: string, headSha: string,
29
+ /**
30
+ * Why the merge-base side is not a document, or '' when it is. A brand-new contract, or a
31
+ * merge-base today's generator refuses; either way every HEAD item then reads as `added`.
32
+ */
33
+ baseNote: string,
34
+ /** True when HEAD's contracts publish no partner-facing document at all. */
35
+ headHasNoDocument: boolean, changes: readonly ContractChange[]);
36
+ }
37
+ /**
38
+ * Renders the partner-facing contract diff as ONE PR comment.
39
+ *
40
+ * This comment is what replaced committing the generated documents (#986). A committed document made
41
+ * a newly partner-visible endpoint show up as a diff; this shows the same thing where reviewers already
42
+ * look, computed against what actually shipped at the merge-base rather than against a checked-in file
43
+ * somebody may have regenerated wrongly or not at all — and it cannot be skipped by forgetting to run a
44
+ * command.
45
+ *
46
+ * `hidden: true` on a method records what somebody TYPED. The Added section is the backstop that shows
47
+ * what will actually SHIP, so it is listed first.
48
+ */
49
+ export declare class ContractDiffRenderer {
50
+ render(sections: readonly ContractDiffSection[]): string;
51
+ private section;
52
+ private bullet;
53
+ }
@@ -0,0 +1,103 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ContractDiffRenderer = exports.ContractDiffSection = exports.CONTRACT_DIFF_COMMENT_MARKER = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const inversify_1 = require("inversify");
6
+ /** Hidden marker that identifies the contract-diff comment among all comments on a PR. */
7
+ exports.CONTRACT_DIFF_COMMENT_MARKER = '<!-- webpieces-contract-diff -->';
8
+ /** One declared contract's partner-facing difference, merge-base → HEAD. Data-only. */
9
+ class ContractDiffSection {
10
+ projectName;
11
+ manifest;
12
+ documentName;
13
+ baseSha;
14
+ headSha;
15
+ baseNote;
16
+ headHasNoDocument;
17
+ changes;
18
+ constructor(
19
+ /** The `openapi-generate` target's project. */
20
+ projectName,
21
+ /** Workspace-relative manifest path. */
22
+ manifest,
23
+ /** The document diffed, e.g. `public-openapi.json`. */
24
+ documentName, baseSha, headSha,
25
+ /**
26
+ * Why the merge-base side is not a document, or '' when it is. A brand-new contract, or a
27
+ * merge-base today's generator refuses; either way every HEAD item then reads as `added`.
28
+ */
29
+ baseNote,
30
+ /** True when HEAD's contracts publish no partner-facing document at all. */
31
+ headHasNoDocument, changes) {
32
+ this.projectName = projectName;
33
+ this.manifest = manifest;
34
+ this.documentName = documentName;
35
+ this.baseSha = baseSha;
36
+ this.headSha = headSha;
37
+ this.baseNote = baseNote;
38
+ this.headHasNoDocument = headHasNoDocument;
39
+ this.changes = changes;
40
+ }
41
+ }
42
+ exports.ContractDiffSection = ContractDiffSection;
43
+ const HEADINGS = [
44
+ ['added', 'Added — newly visible to partners'],
45
+ ['removed', 'Removed — partners lose this'],
46
+ ['changed', 'Changed'],
47
+ ];
48
+ /**
49
+ * Renders the partner-facing contract diff as ONE PR comment.
50
+ *
51
+ * This comment is what replaced committing the generated documents (#986). A committed document made
52
+ * a newly partner-visible endpoint show up as a diff; this shows the same thing where reviewers already
53
+ * look, computed against what actually shipped at the merge-base rather than against a checked-in file
54
+ * somebody may have regenerated wrongly or not at all — and it cannot be skipped by forgetting to run a
55
+ * command.
56
+ *
57
+ * `hidden: true` on a method records what somebody TYPED. The Added section is the backstop that shows
58
+ * what will actually SHIP, so it is listed first.
59
+ */
60
+ let ContractDiffRenderer = class ContractDiffRenderer {
61
+ render(sections) {
62
+ const lines = [exports.CONTRACT_DIFF_COMMENT_MARKER, '## Partner-facing contract changes', ''];
63
+ for (const section of sections) {
64
+ lines.push(...this.section(section), '');
65
+ }
66
+ return lines.join('\n').trimEnd() + '\n';
67
+ }
68
+ section(section) {
69
+ const lines = [
70
+ `### \`${section.projectName}\` — \`${section.documentName}\``,
71
+ '',
72
+ `\`${section.manifest}\`, merge-base \`${section.baseSha.slice(0, 7)}\` → HEAD \`${section.headSha.slice(0, 7)}\`.`,
73
+ ];
74
+ if (section.baseNote !== '')
75
+ lines.push('', `> ${section.baseNote}`);
76
+ if (section.headHasNoDocument && section.changes.length === 0) {
77
+ lines.push('', 'HEAD publishes no partner-facing document for this contract.');
78
+ return lines;
79
+ }
80
+ if (section.changes.length === 0) {
81
+ lines.push('', '**No partner-facing change.**');
82
+ return lines;
83
+ }
84
+ for (const heading of HEADINGS) {
85
+ const matching = section.changes.filter((change) => change.kind === heading[0]);
86
+ if (matching.length === 0)
87
+ continue;
88
+ lines.push('', `**${heading[1]}**`, '');
89
+ for (const change of matching)
90
+ lines.push(this.bullet(change));
91
+ }
92
+ return lines;
93
+ }
94
+ bullet(change) {
95
+ const detail = change.details.length === 0 ? '' : ` — ${change.details.map((each) => `\`${each}\``).join(', ')}`;
96
+ return `- \`${change.subject}\`${detail}`;
97
+ }
98
+ };
99
+ exports.ContractDiffRenderer = ContractDiffRenderer;
100
+ exports.ContractDiffRenderer = ContractDiffRenderer = tslib_1.__decorate([
101
+ (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton)
102
+ ], ContractDiffRenderer);
103
+ //# sourceMappingURL=contract-diff-renderer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contract-diff-renderer.js","sourceRoot":"","sources":["../../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/contract/contract-diff-renderer.ts"],"names":[],"mappings":";;;;AAAA,yCAA2D;AAG3D,0FAA0F;AAC7E,QAAA,4BAA4B,GAAG,kCAAkC,CAAC;AAE/E,uFAAuF;AACvF,MAAa,mBAAmB;IAGf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M,GAAG,MAAM,CAAC,OAAO,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,IAAY,EAAE,EAAE,CAAC,KAAK,IAAI,IAAI,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QACzH,OAAO,OAAO,MAAM,CAAC,OAAO,KAAK,MAAM,EAAE,CAAC;IAC9C,CAAC;CACJ,CAAA;AArCY,oDAAoB;+BAApB,oBAAoB;IADhC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;GAC5B,oBAAoB,CAqChC","sourcesContent":["import { injectable, bindingScopeValues } from 'inversify';\nimport { ContractChange, ContractChangeKind } from './openapi-contract-diff';\n\n/** Hidden marker that identifies the contract-diff comment among all comments on a PR. */\nexport const CONTRACT_DIFF_COMMENT_MARKER = '<!-- webpieces-contract-diff -->';\n\n/** One declared contract's partner-facing difference, merge-base → HEAD. Data-only. */\nexport class ContractDiffSection {\n constructor(\n /** The `openapi-generate` target's project. */\n readonly projectName: string,\n /** Workspace-relative manifest path. */\n readonly manifest: string,\n /** The document diffed, e.g. `public-openapi.json`. */\n readonly documentName: string,\n readonly baseSha: string,\n readonly headSha: string,\n /**\n * Why the merge-base side is not a document, or '' when it is. A brand-new contract, or a\n * merge-base today's generator refuses; either way every HEAD item then reads as `added`.\n */\n readonly baseNote: string,\n /** True when HEAD's contracts publish no partner-facing document at all. */\n readonly headHasNoDocument: boolean,\n readonly changes: readonly ContractChange[],\n ) {}\n}\n\nconst HEADINGS: ReadonlyArray<[ContractChangeKind, string]> = [\n ['added', 'Added — newly visible to partners'],\n ['removed', 'Removed — partners lose this'],\n ['changed', 'Changed'],\n];\n\n/**\n * Renders the partner-facing contract diff as ONE PR comment.\n *\n * This comment is what replaced committing the generated documents (#986). A committed document made\n * a newly partner-visible endpoint show up as a diff; this shows the same thing where reviewers already\n * look, computed against what actually shipped at the merge-base rather than against a checked-in file\n * somebody may have regenerated wrongly or not at all — and it cannot be skipped by forgetting to run a\n * command.\n *\n * `hidden: true` on a method records what somebody TYPED. The Added section is the backstop that shows\n * what will actually SHIP, so it is listed first.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ContractDiffRenderer {\n render(sections: readonly ContractDiffSection[]): string {\n const lines = [CONTRACT_DIFF_COMMENT_MARKER, '## Partner-facing contract changes', ''];\n for (const section of sections) {\n lines.push(...this.section(section), '');\n }\n return lines.join('\\n').trimEnd() + '\\n';\n }\n\n private section(section: ContractDiffSection): string[] {\n const lines = [\n `### \\`${section.projectName}\\` — \\`${section.documentName}\\``,\n '',\n `\\`${section.manifest}\\`, merge-base \\`${section.baseSha.slice(0, 7)}\\` → HEAD \\`${section.headSha.slice(0, 7)}\\`.`,\n ];\n if (section.baseNote !== '') lines.push('', `> ${section.baseNote}`);\n if (section.headHasNoDocument && section.changes.length === 0) {\n lines.push('', 'HEAD publishes no partner-facing document for this contract.');\n return lines;\n }\n if (section.changes.length === 0) {\n lines.push('', '**No partner-facing change.**');\n return lines;\n }\n for (const heading of HEADINGS) {\n const matching = section.changes.filter((change: ContractChange) => change.kind === heading[0]);\n if (matching.length === 0) continue;\n lines.push('', `**${heading[1]}**`, '');\n for (const change of matching) lines.push(this.bullet(change));\n }\n return lines;\n }\n\n private bullet(change: ContractChange): string {\n const detail = change.details.length === 0 ? '' : ` — ${change.details.map((each: string) => `\\`${each}\\``).join(', ')}`;\n return `- \\`${change.subject}\\`${detail}`;\n }\n}\n"]}
@@ -0,0 +1,67 @@
1
+ import { GitExec } from '../git-exec';
2
+ import { ConsumerBinResolver } from './consumer-bin-resolver';
3
+ import { ContractDiffRenderer } from './contract-diff-renderer';
4
+ import { GeneratorRunner } from './generator-runner';
5
+ import { OpenApiContractDiff } from './openapi-contract-diff';
6
+ /** One project that declared an `openapi-generate` target, and the manifest it names. Data-only. */
7
+ export declare class DeclaredContract {
8
+ readonly projectName: string;
9
+ /** Workspace-relative project root. */
10
+ readonly projectRoot: string;
11
+ /** Workspace-relative manifest path, exactly as the target's `options.manifest` states it. */
12
+ readonly manifest: string;
13
+ constructor(projectName: string,
14
+ /** Workspace-relative project root. */
15
+ projectRoot: string,
16
+ /** Workspace-relative manifest path, exactly as the target's `options.manifest` states it. */
17
+ manifest: string);
18
+ }
19
+ /**
20
+ * The PR-gate step that replaced committing generated documents (#986): for every project that
21
+ * declares an `openapi-generate` target, generate the partner-facing document at the MERGE-BASE and at
22
+ * HEAD, diff the two, and render the result as a PR comment.
23
+ *
24
+ * ## Which contracts
25
+ *
26
+ * Exactly the ones a `project.json` declares with the `openapi-generate` executor — the same
27
+ * declaration that makes the build generate and publish the document. There is no second list to keep
28
+ * in step, and a repo that declares none gets no comment and pays nothing.
29
+ *
30
+ * ## One reader, two sources
31
+ *
32
+ * Both sides run the CONSUMER's installed generator (never a bundled copy — see
33
+ * {@link ConsumerBinResolver}). So the diff isolates what the SOURCE changed; a generator upgrade
34
+ * landing in the same PR is not reported as a contract change on every endpoint.
35
+ *
36
+ * The merge-base is extracted with `git archive` INSIDE the repo (under the branch's scratch dir, which
37
+ * is gitignored with the rest of `.webpieces/`), so its imports resolve through the same
38
+ * `node_modules` by walking up — no second install, no worktree bookkeeping for `wp-cleanup` to reap.
39
+ *
40
+ * ## Failure
41
+ *
42
+ * HEAD failing to generate THROWS, before anything is pushed: the build publishes that document, so a
43
+ * contract that cannot be generated is not a PR to post. The merge-base failing is not this PR's defect
44
+ * (today's generator may refuse a shape an older one accepted) — it is REPORTED in the comment, and the
45
+ * diff then reads every HEAD item as added.
46
+ */
47
+ export declare class ContractDiffStep {
48
+ private readonly gitExec;
49
+ private readonly resolver;
50
+ private readonly runner;
51
+ private readonly differ;
52
+ private readonly renderer;
53
+ constructor(gitExec: GitExec, resolver: ConsumerBinResolver, runner: GeneratorRunner, differ: OpenApiContractDiff, renderer: ContractDiffRenderer);
54
+ /** The comment body, or '' when no project declares a contract. `scratchDir` must be inside the repo. */
55
+ commentBody(repoRoot: string, scratchDir: string): string;
56
+ /** Every tracked `project.json` target running {@link OPENAPI_GENERATE_EXECUTOR}. */
57
+ declaredContracts(repoRoot: string): DeclaredContract[];
58
+ private section;
59
+ private generate;
60
+ private readDocument;
61
+ /**
62
+ * Extract the merge-base tree, unless no declared manifest existed there — a PR that ADDS its first
63
+ * contract needs no 14 MB archive to learn that everything is new.
64
+ */
65
+ private extractIfNeeded;
66
+ private object;
67
+ }
@@ -0,0 +1,192 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ContractDiffStep = exports.DeclaredContract = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const child_process_1 = require("child_process");
6
+ const fs = tslib_1.__importStar(require("fs"));
7
+ const path = tslib_1.__importStar(require("path"));
8
+ const rules_config_1 = require("@webpieces/rules-config");
9
+ const inversify_1 = require("inversify");
10
+ const git_exec_1 = require("../git-exec");
11
+ const consumer_bin_resolver_1 = require("./consumer-bin-resolver");
12
+ const contract_diff_renderer_1 = require("./contract-diff-renderer");
13
+ const generator_runner_1 = require("./generator-runner");
14
+ const generator_package_1 = require("./generator-package");
15
+ const openapi_contract_diff_1 = require("./openapi-contract-diff");
16
+ const RULE_NAME = 'contract-diff';
17
+ /** One project that declared an `openapi-generate` target, and the manifest it names. Data-only. */
18
+ class DeclaredContract {
19
+ projectName;
20
+ projectRoot;
21
+ manifest;
22
+ constructor(projectName,
23
+ /** Workspace-relative project root. */
24
+ projectRoot,
25
+ /** Workspace-relative manifest path, exactly as the target's `options.manifest` states it. */
26
+ manifest) {
27
+ this.projectName = projectName;
28
+ this.projectRoot = projectRoot;
29
+ this.manifest = manifest;
30
+ }
31
+ }
32
+ exports.DeclaredContract = DeclaredContract;
33
+ /** Where one side of the diff is generated from and into. Data-only. */
34
+ class GenerationSide {
35
+ treeRoot;
36
+ outDir;
37
+ constructor(
38
+ /** The tree the manifest's relative paths resolve against: the repo, or an extracted merge-base. */
39
+ treeRoot, outDir) {
40
+ this.treeRoot = treeRoot;
41
+ this.outDir = outDir;
42
+ }
43
+ }
44
+ /**
45
+ * The PR-gate step that replaced committing generated documents (#986): for every project that
46
+ * declares an `openapi-generate` target, generate the partner-facing document at the MERGE-BASE and at
47
+ * HEAD, diff the two, and render the result as a PR comment.
48
+ *
49
+ * ## Which contracts
50
+ *
51
+ * Exactly the ones a `project.json` declares with the `openapi-generate` executor — the same
52
+ * declaration that makes the build generate and publish the document. There is no second list to keep
53
+ * in step, and a repo that declares none gets no comment and pays nothing.
54
+ *
55
+ * ## One reader, two sources
56
+ *
57
+ * Both sides run the CONSUMER's installed generator (never a bundled copy — see
58
+ * {@link ConsumerBinResolver}). So the diff isolates what the SOURCE changed; a generator upgrade
59
+ * landing in the same PR is not reported as a contract change on every endpoint.
60
+ *
61
+ * The merge-base is extracted with `git archive` INSIDE the repo (under the branch's scratch dir, which
62
+ * is gitignored with the rest of `.webpieces/`), so its imports resolve through the same
63
+ * `node_modules` by walking up — no second install, no worktree bookkeeping for `wp-cleanup` to reap.
64
+ *
65
+ * ## Failure
66
+ *
67
+ * HEAD failing to generate THROWS, before anything is pushed: the build publishes that document, so a
68
+ * contract that cannot be generated is not a PR to post. The merge-base failing is not this PR's defect
69
+ * (today's generator may refuse a shape an older one accepted) — it is REPORTED in the comment, and the
70
+ * diff then reads every HEAD item as added.
71
+ */
72
+ let ContractDiffStep = class ContractDiffStep {
73
+ gitExec;
74
+ resolver;
75
+ runner;
76
+ differ;
77
+ renderer;
78
+ constructor(gitExec, resolver, runner, differ, renderer) {
79
+ this.gitExec = gitExec;
80
+ this.resolver = resolver;
81
+ this.runner = runner;
82
+ this.differ = differ;
83
+ this.renderer = renderer;
84
+ }
85
+ /** The comment body, or '' when no project declares a contract. `scratchDir` must be inside the repo. */
86
+ commentBody(repoRoot, scratchDir) {
87
+ const contracts = this.declaredContracts(repoRoot);
88
+ if (contracts.length === 0)
89
+ return '';
90
+ const headSha = this.gitExec.gitQuery(['rev-parse', 'HEAD'], repoRoot, 'git rev-parse HEAD failed');
91
+ const baseSha = this.gitExec.gitQuery(['merge-base', 'origin/main', 'HEAD'], repoRoot, 'git merge-base origin/main HEAD failed');
92
+ fs.rmSync(scratchDir, { recursive: true, force: true });
93
+ const baseTree = path.join(scratchDir, 'merge-base');
94
+ const sections = [];
95
+ // webpieces-disable no-unmanaged-exceptions -- try/FINALLY only, nothing is caught: the extracted
96
+ // merge-base tree is removed however this ends, and any throw still reaches the top-level handler
97
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
98
+ try {
99
+ const extracted = this.extractIfNeeded(repoRoot, baseSha, contracts, baseTree);
100
+ contracts.forEach((contract, index) => {
101
+ const head = new GenerationSide(repoRoot, path.join(scratchDir, 'head', String(index)));
102
+ const base = new GenerationSide(baseTree, path.join(scratchDir, 'base', String(index)));
103
+ sections.push(this.section(repoRoot, contract, extracted, head, base, baseSha, headSha));
104
+ });
105
+ }
106
+ finally {
107
+ fs.rmSync(scratchDir, { recursive: true, force: true });
108
+ }
109
+ return this.renderer.render(sections);
110
+ }
111
+ /** Every tracked `project.json` target running {@link OPENAPI_GENERATE_EXECUTOR}. */
112
+ declaredContracts(repoRoot) {
113
+ const listed = this.gitExec.gitQuery(['ls-files', '--', '*project.json'], repoRoot, 'git ls-files failed');
114
+ const contracts = [];
115
+ for (const file of listed.split('\n').filter((line) => line.trim() !== '').sort()) {
116
+ const project = JSON.parse(fs.readFileSync(path.join(repoRoot, file), 'utf8'));
117
+ const targets = this.object(project['targets']);
118
+ for (const targetName of Object.keys(targets).sort()) {
119
+ const target = this.object(targets[targetName]);
120
+ const manifest = this.object(target['options'])['manifest'];
121
+ if (target['executor'] !== generator_package_1.OPENAPI_GENERATE_EXECUTOR || typeof manifest !== 'string')
122
+ continue;
123
+ const name = typeof project['name'] === 'string' ? project['name'] : path.dirname(file);
124
+ contracts.push(new DeclaredContract(name, path.dirname(file), manifest));
125
+ }
126
+ }
127
+ return contracts;
128
+ }
129
+ // eslint-disable-next-line @typescript-eslint/max-params
130
+ section(repoRoot, contract, extracted, head, base, baseSha, headSha) {
131
+ const bin = this.resolver.resolve(new consumer_bin_resolver_1.ConsumerBinRequest(RULE_NAME, generator_package_1.OPENAPI_GENERATOR, [path.join(repoRoot, contract.projectRoot), repoRoot]));
132
+ const headRun = this.generate(bin, contract, head);
133
+ if (!headRun.ok) {
134
+ throw new rules_config_1.RuleFailError(RULE_NAME, `${contract.manifest} does not generate at HEAD, so there is no partner-facing document to ` +
135
+ `diff or to publish.\n${headRun.output}`, undefined, undefined, [new rules_config_1.Option(`Fix the contract, then re-run: pnpm nx run ${contract.projectName}:openapi-generate`, true)]);
136
+ }
137
+ const after = this.readDocument(head.outDir);
138
+ let baseNote = '';
139
+ let before;
140
+ if (!extracted || !fs.existsSync(path.join(base.treeRoot, contract.manifest))) {
141
+ baseNote = 'The merge-base has no such manifest — a new contract, so everything below is new.';
142
+ }
143
+ else {
144
+ const baseRun = this.generate(bin, contract, base);
145
+ if (baseRun.ok)
146
+ before = this.readDocument(base.outDir);
147
+ else
148
+ baseNote = `The merge-base does not generate with ${bin.packageName} ${bin.version}, so every HEAD item reads as added:\n> ${baseRun.output.split('\n').join('\n> ')}`;
149
+ }
150
+ return new contract_diff_renderer_1.ContractDiffSection(contract.projectName, contract.manifest, generator_package_1.PARTNER_DOCUMENT, baseSha, headSha, baseNote, after === undefined, this.differ.diff(before, after));
151
+ }
152
+ generate(bin, contract, side) {
153
+ fs.mkdirSync(side.outDir, { recursive: true });
154
+ return this.runner.run(bin, [
155
+ '--manifest', path.join(side.treeRoot, contract.manifest), '--out', side.outDir, '--format', 'json',
156
+ ], side.treeRoot);
157
+ }
158
+ readDocument(outDir) {
159
+ const file = path.join(outDir, generator_package_1.PARTNER_DOCUMENT);
160
+ return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : undefined;
161
+ }
162
+ /**
163
+ * Extract the merge-base tree, unless no declared manifest existed there — a PR that ADDS its first
164
+ * contract needs no 14 MB archive to learn that everything is new.
165
+ */
166
+ extractIfNeeded(repoRoot, baseSha, contracts, into) {
167
+ const anyAtBase = contracts.some((contract) => this.gitExec.tryGit(['cat-file', '-e', `${baseSha}:${contract.manifest}`], repoRoot).status === 0);
168
+ if (!anyAtBase)
169
+ return false;
170
+ fs.mkdirSync(into, { recursive: true });
171
+ const tarFile = `${into}.tar`;
172
+ this.gitExec.gitQuery(['archive', '--format=tar', '-o', tarFile, baseSha], repoRoot, `git archive ${baseSha} failed`);
173
+ const untar = (0, child_process_1.spawnSync)('tar', ['-xf', tarFile, '-C', into], { encoding: 'utf8' });
174
+ if (untar.status !== 0) {
175
+ throw new rules_config_1.RuleFailError(RULE_NAME, `Could not extract the merge-base ${baseSha} into ${into}: ${untar.stderr ?? ''}`);
176
+ }
177
+ return true;
178
+ }
179
+ object(value) {
180
+ return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : {};
181
+ }
182
+ };
183
+ exports.ContractDiffStep = ContractDiffStep;
184
+ exports.ContractDiffStep = ContractDiffStep = tslib_1.__decorate([
185
+ (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
186
+ tslib_1.__metadata("design:paramtypes", [git_exec_1.GitExec,
187
+ consumer_bin_resolver_1.ConsumerBinResolver,
188
+ generator_runner_1.GeneratorRunner,
189
+ openapi_contract_diff_1.OpenApiContractDiff,
190
+ contract_diff_renderer_1.ContractDiffRenderer])
191
+ ], ContractDiffStep);
192
+ //# sourceMappingURL=contract-diff-step.js.map