@webpieces/code-rules 0.4.979 → 0.4.980

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 (55) hide show
  1. package/package.json +8 -7
  2. package/src/code-policy-registry.js +5 -0
  3. package/src/code-policy-registry.js.map +1 -1
  4. package/src/configs/ipc-configs.d.ts +158 -0
  5. package/src/configs/ipc-configs.js +206 -0
  6. package/src/configs/ipc-configs.js.map +1 -0
  7. package/src/index.d.ts +7 -0
  8. package/src/index.js +20 -1
  9. package/src/index.js.map +1 -1
  10. package/src/ipc/ipc-boundary-analyzer.d.ts +92 -0
  11. package/src/ipc/ipc-boundary-analyzer.js +371 -0
  12. package/src/ipc/ipc-boundary-analyzer.js.map +1 -0
  13. package/src/ipc/ipc-contract-inventory.d.ts +83 -0
  14. package/src/ipc/ipc-contract-inventory.js +215 -0
  15. package/src/ipc/ipc-contract-inventory.js.map +1 -0
  16. package/src/ipc/ipc-contract-shape-analyzer.d.ts +54 -0
  17. package/src/ipc/ipc-contract-shape-analyzer.js +186 -0
  18. package/src/ipc/ipc-contract-shape-analyzer.js.map +1 -0
  19. package/src/ipc/ipc-controller-resolver.d.ts +43 -0
  20. package/src/ipc/ipc-controller-resolver.js +187 -0
  21. package/src/ipc/ipc-controller-resolver.js.map +1 -0
  22. package/src/ipc/ipc-pairing-analyzer.d.ts +43 -0
  23. package/src/ipc/ipc-pairing-analyzer.js +247 -0
  24. package/src/ipc/ipc-pairing-analyzer.js.map +1 -0
  25. package/src/ipc/ipc-protocol-fingerprint.d.ts +50 -0
  26. package/src/ipc/ipc-protocol-fingerprint.js +215 -0
  27. package/src/ipc/ipc-protocol-fingerprint.js.map +1 -0
  28. package/src/ipc/ipc-protocol-recorder.d.ts +25 -0
  29. package/src/ipc/ipc-protocol-recorder.js +98 -0
  30. package/src/ipc/ipc-protocol-recorder.js.map +1 -0
  31. package/src/ipc/ipc-rule-support.d.ts +27 -0
  32. package/src/ipc/ipc-rule-support.js +76 -0
  33. package/src/ipc/ipc-rule-support.js.map +1 -0
  34. package/src/ipc/ipc-source.d.ts +96 -0
  35. package/src/ipc/ipc-source.js +239 -0
  36. package/src/ipc/ipc-source.js.map +1 -0
  37. package/src/ipc-record-protocol.d.ts +2 -0
  38. package/src/ipc-record-protocol.js +34 -0
  39. package/src/ipc-record-protocol.js.map +1 -0
  40. package/src/rule-help.js +4 -0
  41. package/src/rule-help.js.map +1 -1
  42. package/src/rule-settings.js +119 -1
  43. package/src/rule-settings.js.map +1 -1
  44. package/src/validate-ipc-boundary.d.ts +20 -0
  45. package/src/validate-ipc-boundary.js +96 -0
  46. package/src/validate-ipc-boundary.js.map +1 -0
  47. package/src/validate-ipc-contract-shape.d.ts +20 -0
  48. package/src/validate-ipc-contract-shape.js +105 -0
  49. package/src/validate-ipc-contract-shape.js.map +1 -0
  50. package/src/validate-ipc-pairing.d.ts +16 -0
  51. package/src/validate-ipc-pairing.js +71 -0
  52. package/src/validate-ipc-pairing.js.map +1 -0
  53. package/src/validate-ipc-protocol-fingerprint.d.ts +23 -0
  54. package/src/validate-ipc-protocol-fingerprint.js +79 -0
  55. package/src/validate-ipc-protocol-fingerprint.js.map +1 -0
@@ -0,0 +1,50 @@
1
+ /**
2
+ * The IPC protocol fingerprint (#1389) — a port of the replaced script's `version.mjs` +
3
+ * `metadata.mjs#wireSurface`, kept byte-compatible with it: the same declaration objects in the same key
4
+ * order, the same resolved-shape walk, the same comment-free printer, the same sha256 input order. A
5
+ * manifest recorded by the script therefore verifies here when the configured files are the ones it hashed.
6
+ *
7
+ * The checker it needs comes from the contract-rooted program in {@link IpcContractInventory}; no endpoint
8
+ * file is ever part of it.
9
+ */
10
+ import { IpcContractInventory } from './ipc-contract-inventory';
11
+ /** The recorded manifest: the protocol integer and the fingerprint of the wire it speaks. Data-only. */
12
+ export declare class IpcProtocolSnapshot {
13
+ readonly protocol: number;
14
+ readonly fingerprint: string;
15
+ constructor(protocol: number, fingerprint: string);
16
+ /** The manifest file's text, exactly as the replaced script wrote it. */
17
+ toManifestText(): string;
18
+ }
19
+ /** Inputs of one snapshot, already resolved to workspace files. Data-only. */
20
+ export declare class IpcFingerprintInputs {
21
+ readonly workspaceRoot: string;
22
+ readonly inventory: IpcContractInventory;
23
+ /** Workspace-relative, in hash order. */
24
+ readonly normalizedSourceFiles: readonly string[];
25
+ readonly versionFile: string;
26
+ readonly versionConstant: string;
27
+ constructor(workspaceRoot: string, inventory: IpcContractInventory,
28
+ /** Workspace-relative, in hash order. */
29
+ normalizedSourceFiles: readonly string[], versionFile: string, versionConstant: string);
30
+ }
31
+ export declare class IpcProtocolFingerprinter {
32
+ snapshot(inputs: IpcFingerprintInputs): IpcProtocolSnapshot;
33
+ /** The integer `export const <versionConstant> = <n>` declares; `\b` keeps `MIN_<constant>` out. */
34
+ private protocolOf;
35
+ /** Wire identity and resolved payload shapes, independent of file, class and method renames. */
36
+ private wireSurface;
37
+ /** Without a wire table, every contract method is one operation, named `<apiId>.<methodId>`. */
38
+ private rowsFromContracts;
39
+ private rowOf;
40
+ private shape;
41
+ /** Decorators, masks and validators, printed without comments so formatting never moves the hash. */
42
+ private normalizedSource;
43
+ }
44
+ /** The three ways a fingerprint check fails, worded for the configured version constant. */
45
+ export declare class IpcProtocolComparison {
46
+ private readonly versionConstant;
47
+ private readonly recordCommand;
48
+ constructor(versionConstant: string, recordCommand: string);
49
+ compare(current: IpcProtocolSnapshot, committed: IpcProtocolSnapshot, base: IpcProtocolSnapshot | undefined): string[];
50
+ }
@@ -0,0 +1,215 @@
1
+ "use strict";
2
+ /**
3
+ * The IPC protocol fingerprint (#1389) — a port of the replaced script's `version.mjs` +
4
+ * `metadata.mjs#wireSurface`, kept byte-compatible with it: the same declaration objects in the same key
5
+ * order, the same resolved-shape walk, the same comment-free printer, the same sha256 input order. A
6
+ * manifest recorded by the script therefore verifies here when the configured files are the ones it hashed.
7
+ *
8
+ * The checker it needs comes from the contract-rooted program in {@link IpcContractInventory}; no endpoint
9
+ * file is ever part of it.
10
+ */
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.IpcProtocolComparison = exports.IpcProtocolFingerprinter = exports.IpcFingerprintInputs = exports.IpcProtocolSnapshot = void 0;
13
+ const tslib_1 = require("tslib");
14
+ const crypto_1 = require("crypto");
15
+ const fs = tslib_1.__importStar(require("fs"));
16
+ const path = tslib_1.__importStar(require("path"));
17
+ const ts = tslib_1.__importStar(require("typescript"));
18
+ const tooling_common_1 = require("@webpieces/tooling-common");
19
+ const ipc_contract_inventory_1 = require("./ipc-contract-inventory");
20
+ /** The recorded manifest: the protocol integer and the fingerprint of the wire it speaks. Data-only. */
21
+ class IpcProtocolSnapshot {
22
+ protocol;
23
+ fingerprint;
24
+ constructor(protocol, fingerprint) {
25
+ this.protocol = protocol;
26
+ this.fingerprint = fingerprint;
27
+ }
28
+ /** The manifest file's text, exactly as the replaced script wrote it. */
29
+ toManifestText() {
30
+ return `${JSON.stringify({ protocol: this.protocol, fingerprint: this.fingerprint }, null, 2)}\n`;
31
+ }
32
+ }
33
+ exports.IpcProtocolSnapshot = IpcProtocolSnapshot;
34
+ /** The structural half of a {@link WireShape}; keys mirror the replaced script's JSON exactly. */
35
+ class WireShapeObject {
36
+ promise;
37
+ array;
38
+ tuple;
39
+ properties;
40
+ index;
41
+ }
42
+ class WirePropertyShape {
43
+ optional;
44
+ type;
45
+ constructor(optional, type) {
46
+ this.optional = optional;
47
+ this.type = type;
48
+ }
49
+ }
50
+ /** One fingerprinted operation; field order is the hash input's key order. Data-only. */
51
+ class WireDeclaration {
52
+ wire;
53
+ apiId;
54
+ methodId;
55
+ kind;
56
+ direction;
57
+ since;
58
+ parameters;
59
+ reply;
60
+ constructor(wire, apiId, methodId, kind, direction, since, parameters, reply) {
61
+ this.wire = wire;
62
+ this.apiId = apiId;
63
+ this.methodId = methodId;
64
+ this.kind = kind;
65
+ this.direction = direction;
66
+ this.since = since;
67
+ this.parameters = parameters;
68
+ this.reply = reply;
69
+ }
70
+ }
71
+ /** Inputs of one snapshot, already resolved to workspace files. Data-only. */
72
+ class IpcFingerprintInputs {
73
+ workspaceRoot;
74
+ inventory;
75
+ normalizedSourceFiles;
76
+ versionFile;
77
+ versionConstant;
78
+ constructor(workspaceRoot, inventory,
79
+ /** Workspace-relative, in hash order. */
80
+ normalizedSourceFiles, versionFile, versionConstant) {
81
+ this.workspaceRoot = workspaceRoot;
82
+ this.inventory = inventory;
83
+ this.normalizedSourceFiles = normalizedSourceFiles;
84
+ this.versionFile = versionFile;
85
+ this.versionConstant = versionConstant;
86
+ }
87
+ }
88
+ exports.IpcFingerprintInputs = IpcFingerprintInputs;
89
+ class IpcProtocolFingerprinter {
90
+ snapshot(inputs) {
91
+ const declarations = this.wireSurface(inputs.inventory);
92
+ const fingerprint = (0, crypto_1.createHash)('sha256')
93
+ .update(JSON.stringify(declarations))
94
+ .update(this.normalizedSource(inputs.workspaceRoot, inputs.normalizedSourceFiles))
95
+ .digest('hex');
96
+ return new IpcProtocolSnapshot(this.protocolOf(inputs), fingerprint);
97
+ }
98
+ /** The integer `export const <versionConstant> = <n>` declares; `\b` keeps `MIN_<constant>` out. */
99
+ protocolOf(inputs) {
100
+ const absFile = path.join(inputs.workspaceRoot, inputs.versionFile);
101
+ if (!fs.existsSync(absFile)) {
102
+ throw new tooling_common_1.InformAiError(`ipc-protocol-fingerprint: versionFile "${inputs.versionFile}" does not exist.`);
103
+ }
104
+ const escaped = inputs.versionConstant.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
105
+ const match = fs.readFileSync(absFile, 'utf8').match(new RegExp(`\\b${escaped}\\s*=\\s*(\\d+)`));
106
+ if (match === null) {
107
+ throw new tooling_common_1.InformAiError(`ipc-protocol-fingerprint: ${inputs.versionConstant} in ${inputs.versionFile} must be a literal integer ` +
108
+ `(\`export const ${inputs.versionConstant} = <n>;\`).`);
109
+ }
110
+ return Number(match[1]);
111
+ }
112
+ /** Wire identity and resolved payload shapes, independent of file, class and method renames. */
113
+ wireSurface(inventory) {
114
+ const checker = inventory.checker;
115
+ const rows = inventory.rows ?? this.rowsFromContracts(inventory);
116
+ return rows
117
+ .map((row) => {
118
+ const contract = typeof row.api === 'string' ? inventory.contracts.get(row.api) : undefined;
119
+ const method = contract?.methods.find((each) => each.name === row.method);
120
+ if (contract === undefined || method === undefined) {
121
+ throw new tooling_common_1.InformAiError(`ipc-protocol-fingerprint: cannot fingerprint unbound IPC method ${String(row.api)}.${String(row.method)} — ` +
122
+ 'every wire table row must name an existing contract class and one of its methods; fix that row and retry.');
123
+ }
124
+ const signature = checker.getSignatureFromDeclaration(method.declaration);
125
+ const reply = signature === undefined ? 'unknown' : this.shape(checker, checker.getReturnTypeOfSignature(signature), method.declaration);
126
+ return new WireDeclaration(row.wire, contract.id, method.id, row.kind, row.direction, row.since, method.declaration.parameters.map((p) => this.shape(checker, checker.getTypeAtLocation(p), p)), reply);
127
+ })
128
+ .sort((a, b) => String(a.wire).localeCompare(String(b.wire)));
129
+ }
130
+ /** Without a wire table, every contract method is one operation, named `<apiId>.<methodId>`. */
131
+ rowsFromContracts(inventory) {
132
+ const rows = [];
133
+ for (const contract of inventory.contracts.values()) {
134
+ rows.push(...contract.methods.map((method) => this.rowOf(contract, method)));
135
+ }
136
+ return rows;
137
+ }
138
+ rowOf(contract, method) {
139
+ const wire = `${String(contract.id)}.${String(method.id)}`;
140
+ return new ipc_contract_inventory_1.IpcWireRow(contract.name, method.name, wire, undefined, method.kind, undefined);
141
+ }
142
+ shape(checker, type, node, visiting = new Set()) {
143
+ if (visiting.has(type))
144
+ return 'recursive';
145
+ if (type.isUnion()) {
146
+ return type.types
147
+ .map((part) => this.shape(checker, part, node, visiting))
148
+ .sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)));
149
+ }
150
+ if (!(type.flags & ts.TypeFlags.Object))
151
+ return checker.typeToString(type);
152
+ const next = new Set(visiting).add(type);
153
+ const out = new WireShapeObject();
154
+ if (type.getSymbol()?.name === 'Promise') {
155
+ out.promise = this.shape(checker, checker.getTypeArguments(type)[0], node, next);
156
+ return out;
157
+ }
158
+ if (checker.isArrayType(type)) {
159
+ out.array = this.shape(checker, checker.getTypeArguments(type)[0], node, next);
160
+ return out;
161
+ }
162
+ if (checker.isTupleType(type)) {
163
+ out.tuple = checker.getTypeArguments(type).map((part) => this.shape(checker, part, node, next));
164
+ return out;
165
+ }
166
+ out.properties = type
167
+ .getProperties()
168
+ .map((property) => [
169
+ property.name,
170
+ new WirePropertyShape((property.flags & ts.SymbolFlags.Optional) !== 0, this.shape(checker, checker.getTypeOfSymbolAtLocation(property, property.valueDeclaration ?? property.declarations?.[0] ?? node), node, next)),
171
+ ])
172
+ .sort((a, b) => a[0].localeCompare(b[0]));
173
+ const index = checker.getIndexTypeOfType(type, ts.IndexKind.String);
174
+ if (index !== undefined)
175
+ out.index = this.shape(checker, index, node, next);
176
+ return out;
177
+ }
178
+ /** Decorators, masks and validators, printed without comments so formatting never moves the hash. */
179
+ normalizedSource(workspaceRoot, files) {
180
+ const printer = ts.createPrinter({ removeComments: true });
181
+ return files
182
+ .map((rel) => {
183
+ const absFile = path.join(workspaceRoot, rel);
184
+ return printer.printFile(ts.createSourceFile(absFile, fs.readFileSync(absFile, 'utf8'), ts.ScriptTarget.Latest, true));
185
+ })
186
+ .join('\n');
187
+ }
188
+ }
189
+ exports.IpcProtocolFingerprinter = IpcProtocolFingerprinter;
190
+ /** The three ways a fingerprint check fails, worded for the configured version constant. */
191
+ class IpcProtocolComparison {
192
+ versionConstant;
193
+ recordCommand;
194
+ constructor(versionConstant, recordCommand) {
195
+ this.versionConstant = versionConstant;
196
+ this.recordCommand = recordCommand;
197
+ }
198
+ compare(current, committed, base) {
199
+ const errors = [];
200
+ if (current.fingerprint !== committed.fingerprint || current.protocol !== committed.protocol) {
201
+ errors.push(`IPC contract fingerprint changed. Review request/reply/event shape, increment ${this.versionConstant} ` +
202
+ `for a wire change, then run ${this.recordCommand}.`);
203
+ }
204
+ if (base !== undefined && current.protocol < base.protocol) {
205
+ errors.push(`${this.versionConstant} cannot decrease, including on a revert.`);
206
+ }
207
+ if (base !== undefined && current.fingerprint !== base.fingerprint && current.protocol <= base.protocol) {
208
+ errors.push(`IPC contract changed without a ${this.versionConstant} increment relative to the branch base. ` +
209
+ 'Updating the manifest alone cannot waive a protocol change.');
210
+ }
211
+ return errors;
212
+ }
213
+ }
214
+ exports.IpcProtocolComparison = IpcProtocolComparison;
215
+ //# sourceMappingURL=ipc-protocol-fingerprint.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ipc-protocol-fingerprint.js","sourceRoot":"","sources":["../../../../../../packages/tooling/code-rules/src/ipc/ipc-protocol-fingerprint.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG;;;;AAEH,mCAAoC;AACpC,+CAAyB;AACzB,mDAA6B;AAC7B,uDAAiC;AACjC,8DAA0D;AAC1D,qEAAmI;AAEnI,wGAAwG;AACxG,MAAa,mBAAmB;IAEf;IACA;IAFb,YACa,QAAgB,EAChB,WAAmB;QADnB,aAAQ,GAAR,QAAQ,CAAQ;QAChB,gBAAW,GAAX,WAAW,CAAQ;IAC7B,CAAC;IAEJ,yEAAyE;IACzE,cAAc;QACV,OAAO,GAAG,IAAI,CAAC,SAAS,CAAC,EAAE,QAAQ,EAAE,IAAI,CAAC,QAAQ,EAAE,WAAW,EAAE,IAAI,CAAC,WAAW,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC;IACtG,CAAC;CACJ;AAVD,kDAUC;AAKD,kGAAkG;AAClG,MAAM,eAAe;IACjB,OAAO,CAAa;IACpB,KAAK,CAAa;IAClB,KAAK,CAAe;IACpB,UAAU,CAAkB;IAC5B,KAAK,CAAa;CACrB;AAKD,MAAM,iBAAiB;IAEN;IACA;IAFb,YACa,QAAiB,EACjB,IAAe;QADf,aAAQ,GAAR,QAAQ,CAAS;QACjB,SAAI,GAAJ,IAAI,CAAW;IACzB,CAAC;CACP;AAED,yFAAyF;AACzF,MAAM,eAAe;IAEJ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AI,CAAC,IAAI,CAAC,CAAC;IACpB,CAAC;CACJ;AA3HD,4DA2HC;AAED,4FAA4F;AAC5F,MAAa,qBAAqB;IAET;IACA;IAFrB,YACqB,eAAuB,EACvB,aAAqB;QADrB,oBAAe,GAAf,eAAe,CAAQ;QACvB,kBAAa,GAAb,aAAa,CAAQ;IACvC,CAAC;IAEJ,OAAO,CAAC,OAA4B,EAAE,SAA8B,EAAE,IAAqC;QACvG,MAAM,MAAM,GAAa,EAAE,CAAC;QAC5B,IAAI,OAAO,CAAC,WAAW,KAAK,SAAS,CAAC,WAAW,IAAI,OAAO,CAAC,QAAQ,KAAK,SAAS,CAAC,QAAQ,EAAE,CAAC;YAC3F,MAAM,CAAC,IAAI,CACP,iFAAiF,IAAI,CAAC,eAAe,GAAG;gBACpG,+BAA+B,IAAI,CAAC,aAAa,GAAG,CAC3D,CAAC;QACN,CAAC;QACD,IAAI,IAAI,KAAK,SAAS,IAAI,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,QAAQ,EAAE,CAAC;YACzD,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,eAAe,0CAA0C,CAAC,CAAC;QACnF,CAAC;QACD,IAAI,IAAI,KAAK,SAAS,IAAI,OAAO,CAAC,WAAW,KAAK,IAAI,CAAC,WAAW,IAAI,OAAO,CAAC,QAAQ,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;YACtG,MAAM,CAAC,IAAI,CACP,kCAAkC,IAAI,CAAC,eAAe,0CAA0C;gBAC5F,6DAA6D,CACpE,CAAC;QACN,CAAC;QACD,OAAO,MAAM,CAAC;IAClB,CAAC;CACJ;AAzBD,sDAyBC","sourcesContent":["/**\n * The IPC protocol fingerprint (#1389) — a port of the replaced script's `version.mjs` +\n * `metadata.mjs#wireSurface`, kept byte-compatible with it: the same declaration objects in the same key\n * order, the same resolved-shape walk, the same comment-free printer, the same sha256 input order. A\n * manifest recorded by the script therefore verifies here when the configured files are the ones it hashed.\n *\n * The checker it needs comes from the contract-rooted program in {@link IpcContractInventory}; no endpoint\n * file is ever part of it.\n */\n\nimport { createHash } from 'crypto';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as ts from 'typescript';\nimport { InformAiError } from '@webpieces/tooling-common';\nimport { IpcContractInventory, IpcContractMethod, IpcDirectionalContract, IpcLiteral, IpcWireRow } from './ipc-contract-inventory';\n\n/** The recorded manifest: the protocol integer and the fingerprint of the wire it speaks. Data-only. */\nexport class IpcProtocolSnapshot {\n constructor(\n readonly protocol: number,\n readonly fingerprint: string,\n ) {}\n\n /** The manifest file's text, exactly as the replaced script wrote it. */\n toManifestText(): string {\n return `${JSON.stringify({ protocol: this.protocol, fingerprint: this.fingerprint }, null, 2)}\\n`;\n }\n}\n\n/** A resolved wire shape: a type name, a sorted union, or a structural description. */\ntype WireShape = string | WireShape[] | WireShapeObject;\n\n/** The structural half of a {@link WireShape}; keys mirror the replaced script's JSON exactly. */\nclass WireShapeObject {\n promise?: WireShape;\n array?: WireShape;\n tuple?: WireShape[];\n properties?: WireProperty[];\n index?: WireShape;\n}\n\n/** `[name, { optional, type }]`, the script's property tuple. */\ntype WireProperty = [string, WirePropertyShape];\n\nclass WirePropertyShape {\n constructor(\n readonly optional: boolean,\n readonly type: WireShape,\n ) {}\n}\n\n/** One fingerprinted operation; field order is the hash input's key order. Data-only. */\nclass WireDeclaration {\n constructor(\n readonly wire: IpcLiteral,\n readonly apiId: IpcLiteral,\n readonly methodId: IpcLiteral,\n readonly kind: IpcLiteral,\n readonly direction: IpcLiteral,\n readonly since: IpcLiteral,\n readonly parameters: WireShape[],\n readonly reply: WireShape,\n ) {}\n}\n\n/** Inputs of one snapshot, already resolved to workspace files. Data-only. */\nexport class IpcFingerprintInputs {\n constructor(\n readonly workspaceRoot: string,\n readonly inventory: IpcContractInventory,\n /** Workspace-relative, in hash order. */\n readonly normalizedSourceFiles: readonly string[],\n readonly versionFile: string,\n readonly versionConstant: string,\n ) {}\n}\n\nexport class IpcProtocolFingerprinter {\n snapshot(inputs: IpcFingerprintInputs): IpcProtocolSnapshot {\n const declarations = this.wireSurface(inputs.inventory);\n const fingerprint = createHash('sha256')\n .update(JSON.stringify(declarations))\n .update(this.normalizedSource(inputs.workspaceRoot, inputs.normalizedSourceFiles))\n .digest('hex');\n return new IpcProtocolSnapshot(this.protocolOf(inputs), fingerprint);\n }\n\n /** The integer `export const <versionConstant> = <n>` declares; `\\b` keeps `MIN_<constant>` out. */\n private protocolOf(inputs: IpcFingerprintInputs): number {\n const absFile = path.join(inputs.workspaceRoot, inputs.versionFile);\n if (!fs.existsSync(absFile)) {\n throw new InformAiError(`ipc-protocol-fingerprint: versionFile \"${inputs.versionFile}\" does not exist.`);\n }\n const escaped = inputs.versionConstant.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const match = fs.readFileSync(absFile, 'utf8').match(new RegExp(`\\\\b${escaped}\\\\s*=\\\\s*(\\\\d+)`));\n if (match === null) {\n throw new InformAiError(\n `ipc-protocol-fingerprint: ${inputs.versionConstant} in ${inputs.versionFile} must be a literal integer ` +\n `(\\`export const ${inputs.versionConstant} = <n>;\\`).`,\n );\n }\n return Number(match[1]);\n }\n\n /** Wire identity and resolved payload shapes, independent of file, class and method renames. */\n private wireSurface(inventory: IpcContractInventory): WireDeclaration[] {\n const checker = inventory.checker;\n const rows = inventory.rows ?? this.rowsFromContracts(inventory);\n return rows\n .map((row: IpcWireRow) => {\n const contract = typeof row.api === 'string' ? inventory.contracts.get(row.api) : undefined;\n const method = contract?.methods.find((each: IpcContractMethod) => each.name === row.method);\n if (contract === undefined || method === undefined) {\n throw new InformAiError(\n `ipc-protocol-fingerprint: cannot fingerprint unbound IPC method ${String(row.api)}.${String(row.method)} — ` +\n 'every wire table row must name an existing contract class and one of its methods; fix that row and retry.',\n );\n }\n const signature = checker.getSignatureFromDeclaration(method.declaration);\n const reply = signature === undefined ? 'unknown' : this.shape(checker, checker.getReturnTypeOfSignature(signature), method.declaration);\n return new WireDeclaration(\n row.wire,\n contract.id,\n method.id,\n row.kind,\n row.direction,\n row.since,\n method.declaration.parameters.map((p: ts.ParameterDeclaration) => this.shape(checker, checker.getTypeAtLocation(p), p)),\n reply,\n );\n })\n .sort((a: WireDeclaration, b: WireDeclaration) => String(a.wire).localeCompare(String(b.wire)));\n }\n\n /** Without a wire table, every contract method is one operation, named `<apiId>.<methodId>`. */\n private rowsFromContracts(inventory: IpcContractInventory): IpcWireRow[] {\n const rows: IpcWireRow[] = [];\n for (const contract of inventory.contracts.values()) {\n rows.push(...contract.methods.map((method: IpcContractMethod) => this.rowOf(contract, method)));\n }\n return rows;\n }\n\n private rowOf(contract: IpcDirectionalContract, method: IpcContractMethod): IpcWireRow {\n const wire = `${String(contract.id)}.${String(method.id)}`;\n return new IpcWireRow(contract.name, method.name, wire, undefined, method.kind, undefined);\n }\n\n private shape(checker: ts.TypeChecker, type: ts.Type, node: ts.Node, visiting: ReadonlySet<ts.Type> = new Set<ts.Type>()): WireShape {\n if (visiting.has(type)) return 'recursive';\n if (type.isUnion()) {\n return type.types\n .map((part: ts.Type) => this.shape(checker, part, node, visiting))\n .sort((a: WireShape, b: WireShape) => JSON.stringify(a).localeCompare(JSON.stringify(b)));\n }\n if (!(type.flags & ts.TypeFlags.Object)) return checker.typeToString(type);\n const next = new Set<ts.Type>(visiting).add(type);\n const out = new WireShapeObject();\n if (type.getSymbol()?.name === 'Promise') {\n out.promise = this.shape(checker, checker.getTypeArguments(type as ts.TypeReference)[0], node, next);\n return out;\n }\n if (checker.isArrayType(type)) {\n out.array = this.shape(checker, checker.getTypeArguments(type as ts.TypeReference)[0], node, next);\n return out;\n }\n if (checker.isTupleType(type)) {\n out.tuple = checker.getTypeArguments(type as ts.TypeReference).map((part: ts.Type) => this.shape(checker, part, node, next));\n return out;\n }\n out.properties = type\n .getProperties()\n .map((property: ts.Symbol): WireProperty => [\n property.name,\n new WirePropertyShape(\n (property.flags & ts.SymbolFlags.Optional) !== 0,\n this.shape(\n checker,\n checker.getTypeOfSymbolAtLocation(property, property.valueDeclaration ?? property.declarations?.[0] ?? node),\n node,\n next,\n ),\n ),\n ])\n .sort((a: WireProperty, b: WireProperty) => a[0].localeCompare(b[0]));\n const index = checker.getIndexTypeOfType(type, ts.IndexKind.String);\n if (index !== undefined) out.index = this.shape(checker, index, node, next);\n return out;\n }\n\n /** Decorators, masks and validators, printed without comments so formatting never moves the hash. */\n private normalizedSource(workspaceRoot: string, files: readonly string[]): string {\n const printer = ts.createPrinter({ removeComments: true });\n return files\n .map((rel: string) => {\n const absFile = path.join(workspaceRoot, rel);\n return printer.printFile(ts.createSourceFile(absFile, fs.readFileSync(absFile, 'utf8'), ts.ScriptTarget.Latest, true));\n })\n .join('\\n');\n }\n}\n\n/** The three ways a fingerprint check fails, worded for the configured version constant. */\nexport class IpcProtocolComparison {\n constructor(\n private readonly versionConstant: string,\n private readonly recordCommand: string,\n ) {}\n\n compare(current: IpcProtocolSnapshot, committed: IpcProtocolSnapshot, base: IpcProtocolSnapshot | undefined): string[] {\n const errors: string[] = [];\n if (current.fingerprint !== committed.fingerprint || current.protocol !== committed.protocol) {\n errors.push(\n `IPC contract fingerprint changed. Review request/reply/event shape, increment ${this.versionConstant} ` +\n `for a wire change, then run ${this.recordCommand}.`,\n );\n }\n if (base !== undefined && current.protocol < base.protocol) {\n errors.push(`${this.versionConstant} cannot decrease, including on a revert.`);\n }\n if (base !== undefined && current.fingerprint !== base.fingerprint && current.protocol <= base.protocol) {\n errors.push(\n `IPC contract changed without a ${this.versionConstant} increment relative to the branch base. ` +\n 'Updating the manifest alone cannot waive a protocol change.',\n );\n }\n return errors;\n }\n}\n"]}
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Builds the current {@link IpcProtocolSnapshot} from an `ipc-protocol-fingerprint` config, and reads the
3
+ * committed and branch-base manifests (#1389). Shared by the validator and the `wp-ipc-record-protocol`
4
+ * bin, so what the bin records is exactly what the rule later verifies.
5
+ */
6
+ import { GitProcessApi } from '@webpieces/tooling-common';
7
+ import { IpcProtocolFingerprintConfig } from '../configs/ipc-configs';
8
+ import { IpcProtocolSnapshot } from './ipc-protocol-fingerprint';
9
+ import { IpcRuleSupport } from './ipc-rule-support';
10
+ export declare const IPC_FINGERPRINT_RULE = "ipc-protocol-fingerprint";
11
+ /** The command that re-records the manifest; every refusal names it. */
12
+ export declare const IPC_RECORD_COMMAND = "pnpm wp-ipc-record-protocol";
13
+ export declare class IpcProtocolRecorder {
14
+ private readonly support;
15
+ constructor(support: IpcRuleSupport);
16
+ /** The snapshot of the working tree's contract, as the rule computes it. */
17
+ current(workspaceRoot: string, config: IpcProtocolFingerprintConfig): Promise<IpcProtocolSnapshot>;
18
+ /** Write `snapshot` to the configured manifest path, creating its directory. */
19
+ record(workspaceRoot: string, config: IpcProtocolFingerprintConfig, snapshot: IpcProtocolSnapshot): string;
20
+ /** The committed manifest in the working tree; a missing one names the record command. */
21
+ committed(workspaceRoot: string, config: IpcProtocolFingerprintConfig): IpcProtocolSnapshot;
22
+ /** The manifest at `base`, or undefined when that commit has none at this path. */
23
+ atBase(workspaceRoot: string, config: IpcProtocolFingerprintConfig, base: string, git: GitProcessApi): Promise<IpcProtocolSnapshot | undefined>;
24
+ private parse;
25
+ }
@@ -0,0 +1,98 @@
1
+ "use strict";
2
+ /**
3
+ * Builds the current {@link IpcProtocolSnapshot} from an `ipc-protocol-fingerprint` config, and reads the
4
+ * committed and branch-base manifests (#1389). Shared by the validator and the `wp-ipc-record-protocol`
5
+ * bin, so what the bin records is exactly what the rule later verifies.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.IpcProtocolRecorder = exports.IPC_RECORD_COMMAND = exports.IPC_FINGERPRINT_RULE = void 0;
9
+ const tslib_1 = require("tslib");
10
+ const fs = tslib_1.__importStar(require("fs"));
11
+ const path = tslib_1.__importStar(require("path"));
12
+ const tooling_common_1 = require("@webpieces/tooling-common");
13
+ const to_error_1 = require("@webpieces/tooling-common/to-error");
14
+ const ipc_contract_inventory_1 = require("./ipc-contract-inventory");
15
+ const ipc_protocol_fingerprint_1 = require("./ipc-protocol-fingerprint");
16
+ const ipc_source_1 = require("./ipc-source");
17
+ exports.IPC_FINGERPRINT_RULE = 'ipc-protocol-fingerprint';
18
+ /** The command that re-records the manifest; every refusal names it. */
19
+ exports.IPC_RECORD_COMMAND = 'pnpm wp-ipc-record-protocol';
20
+ class IpcProtocolRecorder {
21
+ support;
22
+ constructor(support) {
23
+ this.support = support;
24
+ }
25
+ /** The snapshot of the working tree's contract, as the rule computes it. */
26
+ async current(workspaceRoot, config) {
27
+ const wireTable = new ipc_contract_inventory_1.IpcWireTableConfig().of(exports.IPC_FINGERPRINT_RULE, config.wireTableFile, config.wireTableExport);
28
+ const contractFiles = await this.support.sourceFilesMatching(workspaceRoot, config.contractPaths);
29
+ if (contractFiles.length === 0) {
30
+ throw new tooling_common_1.InformAiError(`${exports.IPC_FINGERPRINT_RULE}: no source file matches "contractPaths" ${JSON.stringify(config.contractPaths)}.`);
31
+ }
32
+ const normalized = [];
33
+ for (const glob of config.normalizedSourceFiles) {
34
+ for (const rel of await this.support.sourceFilesMatching(workspaceRoot, [glob])) {
35
+ if (!normalized.includes(rel))
36
+ normalized.push(rel);
37
+ }
38
+ }
39
+ if (normalized.length === 0) {
40
+ throw new tooling_common_1.InformAiError(`${exports.IPC_FINGERPRINT_RULE}: no source file matches "normalizedSourceFiles" ${JSON.stringify(config.normalizedSourceFiles)}.`);
41
+ }
42
+ const options = new ipc_source_1.IpcCompilerOptionsReader().read(workspaceRoot, config.tsconfigPath);
43
+ const inventory = new ipc_contract_inventory_1.IpcContractInventoryReader().read(workspaceRoot, options, contractFiles, config.apiClassSuffixes, wireTable);
44
+ if (inventory.errors.length > 0) {
45
+ throw new tooling_common_1.InformAiError(`${exports.IPC_FINGERPRINT_RULE}: cannot fingerprint the contract until its wire table is readable — ` +
46
+ `${inventory.errors.join(' ')} Fix ${config.wireTableFile ?? 'the wire table'} and retry.`);
47
+ }
48
+ return new ipc_protocol_fingerprint_1.IpcProtocolFingerprinter().snapshot(new ipc_protocol_fingerprint_1.IpcFingerprintInputs(workspaceRoot, inventory, normalized, config.versionFile, config.versionConstant));
49
+ }
50
+ /** Write `snapshot` to the configured manifest path, creating its directory. */
51
+ record(workspaceRoot, config, snapshot) {
52
+ const absFile = path.join(workspaceRoot, config.manifestPath);
53
+ fs.mkdirSync(path.dirname(absFile), { recursive: true });
54
+ fs.writeFileSync(absFile, snapshot.toManifestText());
55
+ return absFile;
56
+ }
57
+ /** The committed manifest in the working tree; a missing one names the record command. */
58
+ committed(workspaceRoot, config) {
59
+ const absFile = path.join(workspaceRoot, config.manifestPath);
60
+ if (!fs.existsSync(absFile)) {
61
+ throw new tooling_common_1.InformAiError(`${exports.IPC_FINGERPRINT_RULE}: manifest ${config.manifestPath} does not exist. Run ${exports.IPC_RECORD_COMMAND} and commit it.`);
62
+ }
63
+ return this.parse(fs.readFileSync(absFile, 'utf8'), config.manifestPath);
64
+ }
65
+ /** The manifest at `base`, or undefined when that commit has none at this path. */
66
+ async atBase(workspaceRoot, config, base, git) {
67
+ const listed = await git.run(['ls-tree', '--name-only', base, '--', config.manifestPath], workspaceRoot);
68
+ if (!listed.ok) {
69
+ throw new tooling_common_1.InformAiError(`IPC protocol baseline lookup of ${config.manifestPath} at ${base} failed: ${listed.stderr.trim()}. ` +
70
+ 'Fetch origin main (or set NX_BASE to a reachable commit) and retry.');
71
+ }
72
+ if (listed.stdout.trim() === '')
73
+ return undefined;
74
+ const shown = await git.run(['show', `${base}:${config.manifestPath}`], workspaceRoot);
75
+ if (!shown.ok) {
76
+ throw new tooling_common_1.InformAiError(`IPC protocol baseline read of ${config.manifestPath} at ${base} failed: ${shown.stderr.trim()}.`);
77
+ }
78
+ return this.parse(shown.stdout, `${base}:${config.manifestPath}`);
79
+ }
80
+ parse(text, where) {
81
+ let raw;
82
+ // webpieces-disable no-unmanaged-exceptions -- name the manifest that failed to parse while preserving the parse failure as cause
83
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
84
+ try {
85
+ raw = JSON.parse(text);
86
+ }
87
+ catch (err) {
88
+ const error = (0, to_error_1.toError)(err);
89
+ throw new tooling_common_1.InformAiError(`${exports.IPC_FINGERPRINT_RULE}: ${where} is not valid JSON. Re-run ${exports.IPC_RECORD_COMMAND}.`, { cause: error });
90
+ }
91
+ if (typeof raw.protocol !== 'number' || typeof raw.fingerprint !== 'string') {
92
+ throw new tooling_common_1.InformAiError(`${exports.IPC_FINGERPRINT_RULE}: ${where} must hold { "protocol": <integer>, "fingerprint": "<sha256>" }. Re-run ${exports.IPC_RECORD_COMMAND}.`);
93
+ }
94
+ return new ipc_protocol_fingerprint_1.IpcProtocolSnapshot(raw.protocol, raw.fingerprint);
95
+ }
96
+ }
97
+ exports.IpcProtocolRecorder = IpcProtocolRecorder;
98
+ //# sourceMappingURL=ipc-protocol-recorder.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ipc-protocol-recorder.js","sourceRoot":"","sources":["../../../../../../packages/tooling/code-rules/src/ipc/ipc-protocol-recorder.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;;;AAEH,+CAAyB;AACzB,mDAA6B;AAC7B,8DAAyE;AACzE,iEAA6D;AAE7D,qEAA0F;AAC1F,yEAAiH;AAEjH,6CAAwD;AAE3C,QAAA,oBAAoB,GAAG,0BAA0B,CAAC;AAE/D,wEAAwE;AAC3D,QAAA,kBAAkB,GAAG,6BAA6B,CAAC;AAKhE,MAAa,mBAAmB;IACC;IAA7B,YAA6B,OAAuB;QAAvB,YAAO,GAAP,OAAO,CAAgB;IAAG,CAAC;IAExD,4EAA4E;IAC5E,KAAK,CAAC,OAAO,CAAC,aAAqB,EAAE,MAAoC;QACrE,MAAM,SAAS,GAAG,IAAI,2CAAkB,EAAE,CAAC,EAAE,CAAC,4BAAoB,EAAE,MAAM,CAAC,aAAa,EAAE,MAAM,CAAC,eAAe,CAAC,CAAC;QAClH,MAAM,aAAa,GAAG,MAAM,IAAI,CAAC,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AE,KAAK,EAAE,CAAC,CAAC;QACpI,CAAC;QACD,IAAI,OAAO,GAAG,CAAC,QAAQ,KAAK,QAAQ,IAAI,OAAO,GAAG,CAAC,WAAW,KAAK,QAAQ,EAAE,CAAC;YAC1E,MAAM,IAAI,8BAAa,CACnB,GAAG,4BAAoB,KAAK,KAAK,2EAA2E,0BAAkB,GAAG,CACpI,CAAC;QACN,CAAC;QACD,OAAO,IAAI,8CAAmB,CAAC,GAAG,CAAC,QAAQ,EAAE,GAAG,CAAC,WAAW,CAAC,CAAC;IAClE,CAAC;CACJ;AAvFD,kDAuFC","sourcesContent":["/**\n * Builds the current {@link IpcProtocolSnapshot} from an `ipc-protocol-fingerprint` config, and reads the\n * committed and branch-base manifests (#1389). Shared by the validator and the `wp-ipc-record-protocol`\n * bin, so what the bin records is exactly what the rule later verifies.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { GitProcessApi, InformAiError } from '@webpieces/tooling-common';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { IpcProtocolFingerprintConfig } from '../configs/ipc-configs';\nimport { IpcContractInventoryReader, IpcWireTableConfig } from './ipc-contract-inventory';\nimport { IpcFingerprintInputs, IpcProtocolFingerprinter, IpcProtocolSnapshot } from './ipc-protocol-fingerprint';\nimport { IpcRuleSupport } from './ipc-rule-support';\nimport { IpcCompilerOptionsReader } from './ipc-source';\n\nexport const IPC_FINGERPRINT_RULE = 'ipc-protocol-fingerprint';\n\n/** The command that re-records the manifest; every refusal names it. */\nexport const IPC_RECORD_COMMAND = 'pnpm wp-ipc-record-protocol';\n\n/** The two fields of a manifest file. */\ntype RawManifest = { protocol?: number; fingerprint?: string };\n\nexport class IpcProtocolRecorder {\n constructor(private readonly support: IpcRuleSupport) {}\n\n /** The snapshot of the working tree's contract, as the rule computes it. */\n async current(workspaceRoot: string, config: IpcProtocolFingerprintConfig): Promise<IpcProtocolSnapshot> {\n const wireTable = new IpcWireTableConfig().of(IPC_FINGERPRINT_RULE, config.wireTableFile, config.wireTableExport);\n const contractFiles = await this.support.sourceFilesMatching(workspaceRoot, config.contractPaths);\n if (contractFiles.length === 0) {\n throw new InformAiError(`${IPC_FINGERPRINT_RULE}: no source file matches \"contractPaths\" ${JSON.stringify(config.contractPaths)}.`);\n }\n const normalized: string[] = [];\n for (const glob of config.normalizedSourceFiles) {\n for (const rel of await this.support.sourceFilesMatching(workspaceRoot, [glob])) {\n if (!normalized.includes(rel)) normalized.push(rel);\n }\n }\n if (normalized.length === 0) {\n throw new InformAiError(\n `${IPC_FINGERPRINT_RULE}: no source file matches \"normalizedSourceFiles\" ${JSON.stringify(config.normalizedSourceFiles)}.`,\n );\n }\n const options = new IpcCompilerOptionsReader().read(workspaceRoot, config.tsconfigPath);\n const inventory = new IpcContractInventoryReader().read(workspaceRoot, options, contractFiles, config.apiClassSuffixes, wireTable);\n if (inventory.errors.length > 0) {\n throw new InformAiError(\n `${IPC_FINGERPRINT_RULE}: cannot fingerprint the contract until its wire table is readable — ` +\n `${inventory.errors.join(' ')} Fix ${config.wireTableFile ?? 'the wire table'} and retry.`,\n );\n }\n return new IpcProtocolFingerprinter().snapshot(\n new IpcFingerprintInputs(workspaceRoot, inventory, normalized, config.versionFile, config.versionConstant),\n );\n }\n\n /** Write `snapshot` to the configured manifest path, creating its directory. */\n record(workspaceRoot: string, config: IpcProtocolFingerprintConfig, snapshot: IpcProtocolSnapshot): string {\n const absFile = path.join(workspaceRoot, config.manifestPath);\n fs.mkdirSync(path.dirname(absFile), { recursive: true });\n fs.writeFileSync(absFile, snapshot.toManifestText());\n return absFile;\n }\n\n /** The committed manifest in the working tree; a missing one names the record command. */\n committed(workspaceRoot: string, config: IpcProtocolFingerprintConfig): IpcProtocolSnapshot {\n const absFile = path.join(workspaceRoot, config.manifestPath);\n if (!fs.existsSync(absFile)) {\n throw new InformAiError(\n `${IPC_FINGERPRINT_RULE}: manifest ${config.manifestPath} does not exist. Run ${IPC_RECORD_COMMAND} and commit it.`,\n );\n }\n return this.parse(fs.readFileSync(absFile, 'utf8'), config.manifestPath);\n }\n\n /** The manifest at `base`, or undefined when that commit has none at this path. */\n async atBase(workspaceRoot: string, config: IpcProtocolFingerprintConfig, base: string, git: GitProcessApi): Promise<IpcProtocolSnapshot | undefined> {\n const listed = await git.run(['ls-tree', '--name-only', base, '--', config.manifestPath], workspaceRoot);\n if (!listed.ok) {\n throw new InformAiError(\n `IPC protocol baseline lookup of ${config.manifestPath} at ${base} failed: ${listed.stderr.trim()}. ` +\n 'Fetch origin main (or set NX_BASE to a reachable commit) and retry.',\n );\n }\n if (listed.stdout.trim() === '') return undefined;\n const shown = await git.run(['show', `${base}:${config.manifestPath}`], workspaceRoot);\n if (!shown.ok) {\n throw new InformAiError(`IPC protocol baseline read of ${config.manifestPath} at ${base} failed: ${shown.stderr.trim()}.`);\n }\n return this.parse(shown.stdout, `${base}:${config.manifestPath}`);\n }\n\n private parse(text: string, where: string): IpcProtocolSnapshot {\n let raw: RawManifest;\n // webpieces-disable no-unmanaged-exceptions -- name the manifest that failed to parse while preserving the parse failure as cause\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n raw = JSON.parse(text) as RawManifest;\n } catch (err: unknown) {\n const error = toError(err);\n throw new InformAiError(`${IPC_FINGERPRINT_RULE}: ${where} is not valid JSON. Re-run ${IPC_RECORD_COMMAND}.`, { cause: error });\n }\n if (typeof raw.protocol !== 'number' || typeof raw.fingerprint !== 'string') {\n throw new InformAiError(\n `${IPC_FINGERPRINT_RULE}: ${where} must hold { \"protocol\": <integer>, \"fingerprint\": \"<sha256>\" }. Re-run ${IPC_RECORD_COMMAND}.`,\n );\n }\n return new IpcProtocolSnapshot(raw.protocol, raw.fingerprint);\n }\n}\n"]}
@@ -0,0 +1,27 @@
1
+ /**
2
+ * What the four IPC validators share (#1389): the file listing, the MODIFIED_PROJECTS trigger of the two
3
+ * project-scoped rules, and the ONE failure spelling (a thrown `RuleFailError`, one `Option` per site,
4
+ * which `RuleReporter` renders).
5
+ */
6
+ import { DiffScope, RuleFailError } from '@webpieces/rules-config';
7
+ import { IpcProjectMode } from '../configs/ipc-configs';
8
+ import { ProjectCatalog } from '../scan-scope';
9
+ import { IpcFinding } from './ipc-source';
10
+ export declare class IpcRuleSupport {
11
+ private readonly diffScope;
12
+ private readonly catalog;
13
+ constructor(diffScope: DiffScope, catalog: ProjectCatalog);
14
+ /** True for a production TypeScript source file an IPC rule may judge. */
15
+ isProductionSource(relFile: string): boolean;
16
+ /** Every production TypeScript file in the workspace (names only — git's listing, nothing parsed). */
17
+ sourceFiles(workspaceRoot: string): Promise<string[]>;
18
+ /** The production TypeScript files matching `globs`, sorted by path. */
19
+ sourceFilesMatching(workspaceRoot: string, globs: readonly string[]): Promise<string[]>;
20
+ /**
21
+ * Whether a project-scoped IPC rule runs: always under RUN_EVERY_TIME; under MODIFIED_PROJECTS when the
22
+ * diff touches a file matching `globs` or any project that owns one.
23
+ */
24
+ triggered(workspaceRoot: string, mode: IpcProjectMode, ruleName: string, globs: readonly string[]): Promise<boolean>;
25
+ /** The one failure: every finding as `file:line — message`, plus one fix option per site. */
26
+ failure(ruleName: string, why: string, findings: readonly IpcFinding[]): RuleFailError;
27
+ }
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ /**
3
+ * What the four IPC validators share (#1389): the file listing, the MODIFIED_PROJECTS trigger of the two
4
+ * project-scoped rules, and the ONE failure spelling (a thrown `RuleFailError`, one `Option` per site,
5
+ * which `RuleReporter` renders).
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.IpcRuleSupport = void 0;
9
+ const rules_config_1 = require("@webpieces/rules-config");
10
+ const tooling_common_1 = require("@webpieces/tooling-common");
11
+ /** A test or test-support file is never production IPC code, whatever the listing says. */
12
+ const TEST_FILE = /\.(spec|test)(?:-support)?\.[cm]?[jt]sx?$|(^|\/)__tests__\//;
13
+ class IpcRuleSupport {
14
+ diffScope;
15
+ catalog;
16
+ constructor(diffScope, catalog) {
17
+ this.diffScope = diffScope;
18
+ this.catalog = catalog;
19
+ }
20
+ /** True for a production TypeScript source file an IPC rule may judge. */
21
+ isProductionSource(relFile) {
22
+ if (!/\.tsx?$/.test(relFile) || relFile.endsWith('.d.ts'))
23
+ return false;
24
+ return !TEST_FILE.test(relFile);
25
+ }
26
+ /** Every production TypeScript file in the workspace (names only — git's listing, nothing parsed). */
27
+ async sourceFiles(workspaceRoot) {
28
+ const all = await this.diffScope.getAllFiles(workspaceRoot);
29
+ return all.filter((rel) => this.isProductionSource(rel));
30
+ }
31
+ /** The production TypeScript files matching `globs`, sorted by path. */
32
+ async sourceFilesMatching(workspaceRoot, globs) {
33
+ return (await this.sourceFiles(workspaceRoot)).filter((rel) => (0, rules_config_1.matchesAnyGlob)(rel, globs)).sort();
34
+ }
35
+ /**
36
+ * Whether a project-scoped IPC rule runs: always under RUN_EVERY_TIME; under MODIFIED_PROJECTS when the
37
+ * diff touches a file matching `globs` or any project that owns one.
38
+ */
39
+ async triggered(workspaceRoot, mode, ruleName, globs) {
40
+ if (mode === 'RUN_EVERY_TIME')
41
+ return true;
42
+ const range = await this.diffScope.resolveBase(workspaceRoot);
43
+ if (range.base === undefined) {
44
+ throw new tooling_common_1.InformAiError(`${ruleName} could not determine the comparison base for MODIFIED_PROJECTS. Set NX_BASE to the ` +
45
+ 'base branch or commit and retry.');
46
+ }
47
+ const changed = await this.diffScope.getChangedFiles(workspaceRoot, range.base, range.head, { tsOnly: false });
48
+ if (changed.some((rel) => (0, rules_config_1.matchesAnyGlob)(rel, globs)))
49
+ return true;
50
+ const touched = new Set();
51
+ for (const rel of changed) {
52
+ const owner = await this.catalog.ownerOf(workspaceRoot, rel);
53
+ if (owner !== undefined && owner.dir !== '')
54
+ touched.add(owner.dir);
55
+ }
56
+ if (touched.size === 0)
57
+ return false;
58
+ const listed = await this.diffScope.getAllFiles(workspaceRoot, { tsOnly: false });
59
+ for (const rel of listed) {
60
+ if (!(0, rules_config_1.matchesAnyGlob)(rel, globs))
61
+ continue;
62
+ const owner = await this.catalog.ownerOf(workspaceRoot, rel);
63
+ if (owner !== undefined && touched.has(owner.dir))
64
+ return true;
65
+ }
66
+ return false;
67
+ }
68
+ /** The one failure: every finding as `file:line — message`, plus one fix option per site. */
69
+ failure(ruleName, why, findings) {
70
+ const lines = findings.map((each) => ` ${each.relFile}:${each.line} — ${each.message}${each.snippet ? `\n ${each.snippet}` : ''}`);
71
+ const message = `${findings.length} IPC site(s) refused by ${ruleName}: ${why}\n${lines.join('\n')}`;
72
+ return new rules_config_1.RuleFailError(ruleName, message, undefined, undefined, findings.map((each) => new rules_config_1.Option(`${each.relFile}:${each.line}: ${each.message}`, true)));
73
+ }
74
+ }
75
+ exports.IpcRuleSupport = IpcRuleSupport;
76
+ //# sourceMappingURL=ipc-rule-support.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ipc-rule-support.js","sourceRoot":"","sources":["../../../../../../packages/tooling/code-rules/src/ipc/ipc-rule-support.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;;AAEH,0DAA2F;AAC3F,8DAA0D;AAK1D,2FAA2F;AAC3F,MAAM,SAAS,GAAG,6DAA6D,CAAC;AAEhF,MAAa,cAAc;IAEF;IACA;IAFrB,YACqB,SAAoB,EACpB,OAAuB;QADvB,cAAS,GAAT,SAAS,CAAW;QACpB,YAAO,GAAP,OAAO,CAAgB;IACzC,CAAC;IAEJ,0EAA0E;IAC1E,kBAAkB,CAAC,OAAe;QAC9B,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC;YAAE,OAAO,KAAK,CAAC;QACxE,OAAO,CAAC,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACpC,CAAC;IAED,sGAAsG;IACtG,KAAK,CAAC,WAAW,CAAC,aAAqB;QACnC,MAAM,GAAG,GAAG,MAAM,IAAI,CAAC,SAAS,CAAC,WAAW,CAAC,aAAa,CAAC,CAAC;QAC5D,OAAO,GAA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AQ,EACR,OAAO,EACP,SAAS,EACT,SAAS,EACT,QAAQ,CAAC,GAAG,CAAC,CAAC,IAAgB,EAAE,EAAE,CAAC,IAAI,qBAAM,CAAC,GAAG,IAAI,CAAC,OAAO,IAAI,IAAI,CAAC,IAAI,KAAK,IAAI,CAAC,OAAO,EAAE,EAAE,IAAI,CAAC,CAAC,CACxG,CAAC;IACN,CAAC;CACJ;AAlED,wCAkEC","sourcesContent":["/**\n * What the four IPC validators share (#1389): the file listing, the MODIFIED_PROJECTS trigger of the two\n * project-scoped rules, and the ONE failure spelling (a thrown `RuleFailError`, one `Option` per site,\n * which `RuleReporter` renders).\n */\n\nimport { DiffScope, Option, RuleFailError, matchesAnyGlob } from '@webpieces/rules-config';\nimport { InformAiError } from '@webpieces/tooling-common';\nimport { IpcProjectMode } from '../configs/ipc-configs';\nimport { ProjectCatalog, ProjectEntry } from '../scan-scope';\nimport { IpcFinding } from './ipc-source';\n\n/** A test or test-support file is never production IPC code, whatever the listing says. */\nconst TEST_FILE = /\\.(spec|test)(?:-support)?\\.[cm]?[jt]sx?$|(^|\\/)__tests__\\//;\n\nexport class IpcRuleSupport {\n constructor(\n private readonly diffScope: DiffScope,\n private readonly catalog: ProjectCatalog,\n ) {}\n\n /** True for a production TypeScript source file an IPC rule may judge. */\n isProductionSource(relFile: string): boolean {\n if (!/\\.tsx?$/.test(relFile) || relFile.endsWith('.d.ts')) return false;\n return !TEST_FILE.test(relFile);\n }\n\n /** Every production TypeScript file in the workspace (names only — git's listing, nothing parsed). */\n async sourceFiles(workspaceRoot: string): Promise<string[]> {\n const all = await this.diffScope.getAllFiles(workspaceRoot);\n return all.filter((rel: string) => this.isProductionSource(rel));\n }\n\n /** The production TypeScript files matching `globs`, sorted by path. */\n async sourceFilesMatching(workspaceRoot: string, globs: readonly string[]): Promise<string[]> {\n return (await this.sourceFiles(workspaceRoot)).filter((rel: string) => matchesAnyGlob(rel, globs)).sort();\n }\n\n /**\n * Whether a project-scoped IPC rule runs: always under RUN_EVERY_TIME; under MODIFIED_PROJECTS when the\n * diff touches a file matching `globs` or any project that owns one.\n */\n async triggered(workspaceRoot: string, mode: IpcProjectMode, ruleName: string, globs: readonly string[]): Promise<boolean> {\n if (mode === 'RUN_EVERY_TIME') return true;\n const range = await this.diffScope.resolveBase(workspaceRoot);\n if (range.base === undefined) {\n throw new InformAiError(\n `${ruleName} could not determine the comparison base for MODIFIED_PROJECTS. Set NX_BASE to the ` +\n 'base branch or commit and retry.',\n );\n }\n const changed = await this.diffScope.getChangedFiles(workspaceRoot, range.base, range.head, { tsOnly: false });\n if (changed.some((rel: string) => matchesAnyGlob(rel, globs))) return true;\n const touched = new Set<string>();\n for (const rel of changed) {\n const owner = await this.catalog.ownerOf(workspaceRoot, rel);\n if (owner !== undefined && owner.dir !== '') touched.add(owner.dir);\n }\n if (touched.size === 0) return false;\n const listed = await this.diffScope.getAllFiles(workspaceRoot, { tsOnly: false });\n for (const rel of listed) {\n if (!matchesAnyGlob(rel, globs)) continue;\n const owner: ProjectEntry | undefined = await this.catalog.ownerOf(workspaceRoot, rel);\n if (owner !== undefined && touched.has(owner.dir)) return true;\n }\n return false;\n }\n\n /** The one failure: every finding as `file:line — message`, plus one fix option per site. */\n failure(ruleName: string, why: string, findings: readonly IpcFinding[]): RuleFailError {\n const lines = findings.map((each: IpcFinding) =>\n ` ${each.relFile}:${each.line} — ${each.message}${each.snippet ? `\\n ${each.snippet}` : ''}`);\n const message = `${findings.length} IPC site(s) refused by ${ruleName}: ${why}\\n${lines.join('\\n')}`;\n return new RuleFailError(\n ruleName,\n message,\n undefined,\n undefined,\n findings.map((each: IpcFinding) => new Option(`${each.relFile}:${each.line}: ${each.message}`, true)),\n );\n }\n}\n"]}