@webpieces/rules-config 0.4.846 → 0.4.848

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 (78) hide show
  1. package/package.json +10 -7
  2. package/src/WebpiecesRulesConfig.d.ts +1 -2
  3. package/src/WebpiecesRulesConfig.js +0 -1
  4. package/src/WebpiecesRulesConfig.js.map +1 -1
  5. package/src/client-module-resolution.d.ts +9 -0
  6. package/src/client-module-resolution.js +102 -0
  7. package/src/client-module-resolution.js.map +1 -0
  8. package/src/config-error-banner.d.ts +0 -2
  9. package/src/config-error-banner.js +1 -3
  10. package/src/config-error-banner.js.map +1 -1
  11. package/src/config-file.d.ts +3 -6
  12. package/src/config-file.js +14 -1
  13. package/src/config-file.js.map +1 -1
  14. package/src/config-key-rules.js +16 -5
  15. package/src/config-key-rules.js.map +1 -1
  16. package/src/config-pruner.d.ts +5 -42
  17. package/src/config-pruner.js +31 -76
  18. package/src/config-pruner.js.map +1 -1
  19. package/src/config-repair-access.d.ts +4 -0
  20. package/src/config-repair-access.js +17 -0
  21. package/src/config-repair-access.js.map +1 -0
  22. package/src/config-repair-bootstrap-source.d.ts +2 -0
  23. package/src/config-repair-bootstrap-source.js +7 -0
  24. package/src/config-repair-bootstrap-source.js.map +1 -0
  25. package/src/config-repair-probe.d.ts +13 -0
  26. package/src/config-repair-probe.js +115 -0
  27. package/src/config-repair-probe.js.map +1 -0
  28. package/src/first-path-match.d.ts +14 -0
  29. package/src/first-path-match.js +35 -0
  30. package/src/first-path-match.js.map +1 -0
  31. package/src/index.d.ts +15 -8
  32. package/src/index.js +40 -10
  33. package/src/index.js.map +1 -1
  34. package/src/legacy-config-upgrade.d.ts +22 -0
  35. package/src/legacy-config-upgrade.js +328 -0
  36. package/src/legacy-config-upgrade.js.map +1 -0
  37. package/src/load-config.d.ts +11 -23
  38. package/src/load-config.js +50 -138
  39. package/src/load-config.js.map +1 -1
  40. package/src/pack-policy-files.d.ts +29 -0
  41. package/src/pack-policy-files.js +194 -0
  42. package/src/pack-policy-files.js.map +1 -0
  43. package/src/policy-field-constraints.d.ts +9 -0
  44. package/src/policy-field-constraints.js +31 -0
  45. package/src/policy-field-constraints.js.map +1 -0
  46. package/src/repository-path.d.ts +7 -0
  47. package/src/repository-path.js +50 -0
  48. package/src/repository-path.js.map +1 -0
  49. package/src/rule-pack-artifacts.d.ts +23 -0
  50. package/src/rule-pack-artifacts.js +180 -0
  51. package/src/rule-pack-artifacts.js.map +1 -0
  52. package/src/rule-pack-registry.d.ts +7 -0
  53. package/src/rule-pack-registry.js +149 -47
  54. package/src/rule-pack-registry.js.map +1 -1
  55. package/src/rule-pack-sync.d.ts +26 -0
  56. package/src/rule-pack-sync.js +236 -0
  57. package/src/rule-pack-sync.js.map +1 -0
  58. package/src/rule-runtime-modules.d.ts +27 -0
  59. package/src/rule-runtime-modules.js +135 -0
  60. package/src/rule-runtime-modules.js.map +1 -0
  61. package/src/rules-sync-cli.d.ts +7 -0
  62. package/src/rules-sync-cli.js +48 -0
  63. package/src/rules-sync-cli.js.map +1 -0
  64. package/src/seed-entry.js +1 -3
  65. package/src/seed-entry.js.map +1 -1
  66. package/src/types.d.ts +4 -6
  67. package/src/types.js +4 -7
  68. package/src/types.js.map +1 -1
  69. package/src/validate-config.d.ts +3 -29
  70. package/src/validate-config.js +99 -244
  71. package/src/validate-config.js.map +1 -1
  72. package/src/validate-pr-gate.d.ts +8 -0
  73. package/src/validate-pr-gate.js +161 -0
  74. package/src/validate-pr-gate.js.map +1 -0
  75. package/templates/webpieces.guard-matrix.md +5 -4
  76. package/src/rule-pack-selection.d.ts +0 -6
  77. package/src/rule-pack-selection.js +0 -50
  78. package/src/rule-pack-selection.js.map +0 -1
@@ -0,0 +1,236 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RulePackSync = exports.RulePackSyncOptions = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const fs = tslib_1.__importStar(require("node:fs"));
6
+ const path = tslib_1.__importStar(require("node:path"));
7
+ const inversify_1 = require("inversify");
8
+ const rules_sdk_1 = require("@webpieces/rules-sdk");
9
+ const tooling_common_1 = require("@webpieces/tooling-common");
10
+ const config_file_1 = require("./config-file");
11
+ const pack_policy_files_1 = require("./pack-policy-files");
12
+ const rule_pack_artifacts_1 = require("./rule-pack-artifacts");
13
+ const rule_pack_registry_1 = require("./rule-pack-registry");
14
+ const config_key_rules_1 = require("./config-key-rules");
15
+ const commands_section_validators_1 = require("./commands-section-validators");
16
+ const validate_config_1 = require("./validate-config");
17
+ const legacy_config_upgrade_1 = require("./legacy-config-upgrade");
18
+ class RulePackSyncOptions {
19
+ mode;
20
+ declarations;
21
+ constructor(mode, declarations) {
22
+ this.mode = mode;
23
+ this.declarations = declarations;
24
+ }
25
+ }
26
+ exports.RulePackSyncOptions = RulePackSyncOptions;
27
+ class OwnerFilePlan {
28
+ filename;
29
+ entries;
30
+ constructor(filename, entries) {
31
+ this.filename = filename;
32
+ this.entries = entries;
33
+ }
34
+ }
35
+ /** Explicit file mutation; normal configuration loading never calls this service. */
36
+ let RulePackSync = class RulePackSync {
37
+ configFile;
38
+ files;
39
+ artifacts;
40
+ atomic;
41
+ constructor(configFile, files, artifacts, atomic) {
42
+ this.configFile = configFile;
43
+ this.files = files;
44
+ this.artifacts = artifacts;
45
+ this.atomic = atomic;
46
+ }
47
+ run(root, options) {
48
+ const filename = path.join(root, config_file_1.CONFIG_FILENAME);
49
+ // webpieces-disable no-any-unknown -- migration reads opaque JSON only at this explicit command boundary
50
+ const document = this.configFile.readRawConfig(filename);
51
+ const declarations = options.declarations ?? this.selectedDeclarations(document, root, options.mode);
52
+ const selected = this.files.select(root, this.files.declarations(declarations, root));
53
+ const registry = new rule_pack_registry_1.RulePackRegistry(selected.map((pack) => pack.manifest));
54
+ for (const pack of selected)
55
+ registry.recordModuleLocation(pack.manifest.packageName, pack.declaration.moduleName());
56
+ const upgraded = options.mode === 'upgrade' ? this.upgradeDocument(document, registry) : document;
57
+ const legacy = options.mode === 'upgrade'
58
+ ? this.legacyEntries(upgraded, registry)
59
+ : new Map();
60
+ const prepared = this.prepare(root, selected, registry, legacy);
61
+ const next = this.rootDocument(upgraded, declarations, options.mode);
62
+ this.validateRoot(next, root);
63
+ // Validate artifact data and canonical destination paths before changing any owner file.
64
+ this.artifacts.render(prepared.resolved);
65
+ this.artifacts.paths(root);
66
+ const changed = [];
67
+ for (const plan of prepared.plans) {
68
+ if (this.atomic.writeIfChanged(plan.filename, JSON.stringify(plan.entries, null, 2) + '\n'))
69
+ changed.push(plan.filename);
70
+ }
71
+ changed.push(...this.artifacts.write(root, prepared.resolved));
72
+ // Commit the root declaration last: all referenced files have already been validated and written.
73
+ if (this.atomic.writeIfChanged(filename, JSON.stringify(next, null, 2) + '\n'))
74
+ changed.push(filename);
75
+ return changed;
76
+ }
77
+ // webpieces-disable no-any-unknown -- only an explicit upgrade may read the previous root shape
78
+ selectedDeclarations(
79
+ // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution
80
+ document, root, mode) {
81
+ if (document['rulePacks'] !== undefined)
82
+ return this.files.declarations(document['rulePacks'], root);
83
+ if (mode !== 'upgrade')
84
+ return this.files.declarations(undefined, root);
85
+ const pkg = this.configFile.readRawConfig(path.join(root, 'package.json'));
86
+ const metadata = this.object(pkg['webpieces'], 'package.json.webpieces');
87
+ const entries = metadata['rulePacks'];
88
+ if (!Array.isArray(entries) || !entries.length) {
89
+ throw new tooling_common_1.InformAiError('Upgrade requires explicit pack selection. Supply --pack=<package>=.webpieces/rules/<owner>.json for every selected pack. Installed dependencies are never inferred as selected packs.');
90
+ }
91
+ // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution
92
+ return entries.map((entry) => {
93
+ const declaration = this.object(entry, 'legacy package.json.webpieces.rulePacks entry');
94
+ const moduleName = declaration['module'];
95
+ if (typeof moduleName !== 'string' || !moduleName.endsWith('/rule-pack')) {
96
+ throw new tooling_common_1.InformAiError('Legacy pack modules must end in /rule-pack. Supply explicit --pack=<package-or-module>=<config.json> declarations for other modules.');
97
+ }
98
+ const packageName = moduleName.slice(0, -'/rule-pack'.length);
99
+ return new pack_policy_files_1.PackPolicyDeclaration(packageName, `.webpieces/rules/${packageName.split('/').at(-1)}.json`);
100
+ });
101
+ }
102
+ // webpieces-disable no-any-unknown -- inherited settings and untyped directory rules cannot be silently converted into declared owners
103
+ upgradeDocument(
104
+ // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution
105
+ document, registry) {
106
+ if (document['extends'] !== undefined)
107
+ throw new tooling_common_1.InformAiError('Remove extends after making inherited values explicit. Upgrade cannot infer inherited policy settings.');
108
+ const directories = document['rulesDir'];
109
+ if (directories !== undefined &&
110
+ (!Array.isArray(directories) || directories.length !== 0)) {
111
+ throw new tooling_common_1.InformAiError('Replace rulesDir with a declared client rule pack, its owned schemas, and implementation modules before upgrade. Directory implementations cannot supply an inferred schema.');
112
+ }
113
+ if (!Object.hasOwn(document, 'rules') && !Object.hasOwn(document, 'hookGuards'))
114
+ return document;
115
+ const prepared = (0, legacy_config_upgrade_1.prepareLegacyUpgrade)(structuredClone(document), registry);
116
+ return { ...document, ...prepared.config };
117
+ }
118
+ // webpieces-disable no-any-unknown -- explicit upgrade gathers settings by canonical owner after applying owner-declared retirements
119
+ legacyEntries(
120
+ // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution
121
+ document, registry) {
122
+ if (document['extends'] !== undefined)
123
+ throw new tooling_common_1.InformAiError('Remove extends after making inherited values explicit. Upgrade cannot infer inherited policy settings.');
124
+ const directories = document['rulesDir'];
125
+ if (directories !== undefined &&
126
+ (!Array.isArray(directories) || directories.length !== 0)) {
127
+ throw new tooling_common_1.InformAiError('Replace rulesDir with a declared client rule pack, its owned schemas, and implementation modules before upgrade. Directory implementations cannot supply an inferred schema.');
128
+ }
129
+ const entries = new Map();
130
+ for (const section of ['rules', 'hookGuards']) {
131
+ if (document[section] === undefined)
132
+ continue;
133
+ const old = this.object(document[section], section);
134
+ for (const id of Object.keys(old)) {
135
+ if (!registry.hasRule(id))
136
+ throw new tooling_common_1.InformAiError(`${section}.${id} has no selected owner. Declare its owner or remove the entry explicitly before upgrading.`);
137
+ if (entries.has(id))
138
+ throw new tooling_common_1.InformAiError(`${id} appears in both legacy sections. Choose one explicit value before upgrading.`);
139
+ entries.set(id, this.object(old[id], `${section}.${id}`));
140
+ }
141
+ }
142
+ return entries;
143
+ }
144
+ prepare(root, selected, registry, legacy) {
145
+ const plans = [], values = {}, targets = new Map();
146
+ const errors = [];
147
+ for (const pack of selected) {
148
+ const filename = this.files.configPath(root, pack.declaration.config);
149
+ const entries = fs.existsSync(filename) ? this.files.read(filename) : {};
150
+ for (const id of Object.keys(entries)) {
151
+ if (!registry.hasRule(id) || registry.ownerOf(id) !== pack.manifest.packageName) {
152
+ errors.push(`${filename}: ${id} has another owner or is unknown. Move or remove it explicitly before sync.`);
153
+ }
154
+ }
155
+ for (const definition of pack.manifest.ownedRules) {
156
+ const previous = Object.hasOwn(entries, definition.id)
157
+ ? entries[definition.id]
158
+ : legacy.get(definition.id);
159
+ if (entries[definition.id] !== undefined &&
160
+ legacy.has(definition.id) &&
161
+ JSON.stringify(entries[definition.id]) !==
162
+ JSON.stringify(legacy.get(definition.id))) {
163
+ errors.push(`${filename}: ${definition.id} conflicts with the legacy value. Choose one explicit value before upgrade.`);
164
+ }
165
+ const value = this.seedMissing(previous, definition);
166
+ errors.push(...registry
167
+ .validateRuleConfig(definition.id, value)
168
+ .map((error) => `${filename}: ${error}`));
169
+ entries[definition.id] = value;
170
+ values[definition.id] = value;
171
+ targets.set(definition.id, filename);
172
+ }
173
+ plans.push(new OwnerFilePlan(filename, entries));
174
+ }
175
+ if (errors.length)
176
+ throw new tooling_common_1.InformAiError(`Sync made no changes:\n${errors.join('\n')}`);
177
+ return new RulePackSyncPlan(plans, new pack_policy_files_1.PackPolicyFilesResult(registry, selected, values, targets));
178
+ }
179
+ seedMissing(previous, definition) {
180
+ const value = previous === undefined
181
+ ? structuredClone(definition.recommendedSeed)
182
+ : Object.assign(new rules_sdk_1.ConfigObject(), this.object(previous, definition.id));
183
+ for (const field of Object.keys(definition.schema)) {
184
+ if (!definition.schema[field].optional && !Object.hasOwn(value, field)) {
185
+ value[field] = structuredClone(definition.recommendedSeed[field]);
186
+ }
187
+ }
188
+ return value;
189
+ }
190
+ // webpieces-disable no-any-unknown -- explicit upgrade removes only the retired sections it actually converted
191
+ rootDocument(
192
+ // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution
193
+ document, declarations, mode) {
194
+ const next = { ...document, rulePacks: declarations };
195
+ if (mode === 'upgrade')
196
+ for (const key of ['rules', 'hookGuards', 'rulesDir', 'extends'])
197
+ // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution
198
+ delete next[key];
199
+ return next;
200
+ }
201
+ // webpieces-disable no-any-unknown -- the same generic-root validators run before any write
202
+ validateRoot(document, root) {
203
+ const errors = [
204
+ ...(0, config_key_rules_1.validateTopLevelKeys)(document),
205
+ ...(0, commands_section_validators_1.validateCommandsSection)(document['commands'], document['pr-gate'], root),
206
+ ...(0, validate_config_1.validateExcludePaths)(document['excludePaths']),
207
+ ...(0, validate_config_1.validateMatchRulesSection)(document['match-rules']),
208
+ ];
209
+ if (errors.length)
210
+ throw new tooling_common_1.InformAiError(`Sync made no changes:\n${errors.join('\n')}`);
211
+ }
212
+ // webpieces-disable no-any-unknown -- JSON object narrowing preserves explicit values for subsequent schema validation
213
+ object(value, label) {
214
+ if (!value || typeof value !== 'object' || Array.isArray(value))
215
+ throw new tooling_common_1.InformAiError(`${label} must be a JSON object. Repair it before sync.`);
216
+ // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution
217
+ return value;
218
+ }
219
+ };
220
+ exports.RulePackSync = RulePackSync;
221
+ exports.RulePackSync = RulePackSync = tslib_1.__decorate([
222
+ (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
223
+ tslib_1.__metadata("design:paramtypes", [config_file_1.ConfigFile,
224
+ pack_policy_files_1.PackPolicyFiles,
225
+ rule_pack_artifacts_1.RulePackArtifacts,
226
+ tooling_common_1.AtomicFile])
227
+ ], RulePackSync);
228
+ class RulePackSyncPlan {
229
+ plans;
230
+ resolved;
231
+ constructor(plans, resolved) {
232
+ this.plans = plans;
233
+ this.resolved = resolved;
234
+ }
235
+ }
236
+ //# sourceMappingURL=rule-pack-sync.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rule-pack-sync.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/rule-pack-sync.ts"],"names":[],"mappings":";;;;AAAA,oDAA8B;AAC9B,wDAAkC;AAClC,yCAA2D;AAC3D,oDAAyE;AACzE,8DAAsE;AACtE,+CAA4D;AAC5D,2DAK6B;AAC7B,+DAA0D;AAC1D,6DAAwD;AACxD,yDAA0D;AAC1D,+EAAwE;AACxE,uDAAoF;AACpF,mEAA+D;AAE/D,MAAa,mBAAmB;IAEf;IACA;IAFb,YACa,IAAwB,EACxB,YAAqD;QADrD,SAAI,GAAJ,IAAI,CAAoB;QACxB,iBAAY,GAAZ,YAAY,CAAyC;IAC/D,CAAC;CACP;AALD,kDAKC;AAED,MAAM,aAAa;IAEF;IACA;IAFb,YACa,QAAgB,EAChB,OAAqC;QADrC,aAAQ,GAAR,QAAQ,CAAQ;QAChB,YAAO,GAAP,OAAO,CAA8B;IAC/C,CAAC;CACP;AAED,qFAAqF;AAE9E,IAAM,YAAY,GAAlB,MAAM,YAAY;IAEA;IACA;IACA;IACA;IAJrB,YACqB,UAAsB,EACtB,KAAsB,EACtB,SAA4B,EAC5B,MAAkB;QAHlB,eAAU,GAAV,UAAU,CAAY;QACtB,UAAK,GAAL,KAAK,CAAiB;QACtB,cAAS,GAAT,SAAS,CAAmB;QAC5B,WAAM,GAAN,MAAM,CAAY;IACpC,CAAC;IAEJ,GAAG,CAAC,IAAY,EAAE,OAA4B;QAC1C,MAAM,QAAQ,GAAG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AS,CAAC;6CAGJ,wBAAU;QACf,mCAAe;QACX,uCAAiB;QACpB,2BAAU;GAL9B,YAAY,CA+PxB;AAED,MAAM,gBAAgB;IAEL;IACA;IAFb,YACa,KAA+B,EAC/B,QAA+B;QAD/B,UAAK,GAAL,KAAK,CAA0B;QAC/B,aAAQ,GAAR,QAAQ,CAAuB;IACzC,CAAC;CACP","sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { ConfigObject, OwnedRuleDefinition } from '@webpieces/rules-sdk';\nimport { AtomicFile, InformAiError } from '@webpieces/tooling-common';\nimport { ConfigFile, CONFIG_FILENAME } from './config-file';\nimport {\n PackPolicyDeclaration,\n PackPolicyFiles,\n PackPolicyFilesResult,\n SelectedPolicyPack,\n} from './pack-policy-files';\nimport { RulePackArtifacts } from './rule-pack-artifacts';\nimport { RulePackRegistry } from './rule-pack-registry';\nimport { validateTopLevelKeys } from './config-key-rules';\nimport { validateCommandsSection } from './commands-section-validators';\nimport { validateExcludePaths, validateMatchRulesSection } from './validate-config';\nimport { prepareLegacyUpgrade } from './legacy-config-upgrade';\n\nexport class RulePackSyncOptions {\n constructor(\n readonly mode: 'sync' | 'upgrade',\n readonly declarations: readonly PackPolicyDeclaration[] | null,\n ) {}\n}\n\nclass OwnerFilePlan {\n constructor(\n readonly filename: string,\n readonly entries: Record<string, ConfigObject>,\n ) {}\n}\n\n/** Explicit file mutation; normal configuration loading never calls this service. */\n@injectable(bindingScopeValues.Singleton)\nexport class RulePackSync {\n constructor(\n private readonly configFile: ConfigFile,\n private readonly files: PackPolicyFiles,\n private readonly artifacts: RulePackArtifacts,\n private readonly atomic: AtomicFile,\n ) {}\n\n run(root: string, options: RulePackSyncOptions): readonly string[] {\n const filename = path.join(root, CONFIG_FILENAME);\n // webpieces-disable no-any-unknown -- migration reads opaque JSON only at this explicit command boundary\n const document = this.configFile.readRawConfig(filename) as Record<string, unknown>;\n const declarations =\n options.declarations ?? this.selectedDeclarations(document, root, options.mode);\n const selected = this.files.select(root, this.files.declarations(declarations, root));\n const registry = new RulePackRegistry(\n selected.map((pack: SelectedPolicyPack) => pack.manifest),\n );\n for (const pack of selected)\n registry.recordModuleLocation(pack.manifest.packageName, pack.declaration.moduleName());\n const upgraded =\n options.mode === 'upgrade' ? this.upgradeDocument(document, registry) : document;\n const legacy =\n options.mode === 'upgrade'\n ? this.legacyEntries(upgraded, registry)\n : new Map<string, ConfigObject>();\n const prepared = this.prepare(root, selected, registry, legacy);\n const next = this.rootDocument(upgraded, declarations, options.mode);\n this.validateRoot(next, root);\n // Validate artifact data and canonical destination paths before changing any owner file.\n this.artifacts.render(prepared.resolved);\n this.artifacts.paths(root);\n const changed: string[] = [];\n for (const plan of prepared.plans) {\n if (\n this.atomic.writeIfChanged(\n plan.filename,\n JSON.stringify(plan.entries, null, 2) + '\\n',\n )\n )\n changed.push(plan.filename);\n }\n changed.push(...this.artifacts.write(root, prepared.resolved));\n // Commit the root declaration last: all referenced files have already been validated and written.\n if (this.atomic.writeIfChanged(filename, JSON.stringify(next, null, 2) + '\\n'))\n changed.push(filename);\n return changed;\n }\n\n // webpieces-disable no-any-unknown -- only an explicit upgrade may read the previous root shape\n private selectedDeclarations(\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n document: Record<string, unknown>,\n root: string,\n mode: 'sync' | 'upgrade',\n ): readonly PackPolicyDeclaration[] {\n if (document['rulePacks'] !== undefined)\n return this.files.declarations(document['rulePacks'], root);\n if (mode !== 'upgrade') return this.files.declarations(undefined, root);\n const pkg = this.configFile.readRawConfig(path.join(root, 'package.json')) as Record<\n string,\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n unknown\n >;\n const metadata = this.object(pkg['webpieces'], 'package.json.webpieces');\n const entries = metadata['rulePacks'];\n if (!Array.isArray(entries) || !entries.length) {\n throw new InformAiError(\n 'Upgrade requires explicit pack selection. Supply --pack=<package>=.webpieces/rules/<owner>.json for every selected pack. Installed dependencies are never inferred as selected packs.',\n );\n }\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n return entries.map((entry: unknown) => {\n const declaration = this.object(entry, 'legacy package.json.webpieces.rulePacks entry');\n const moduleName = declaration['module'];\n if (typeof moduleName !== 'string' || !moduleName.endsWith('/rule-pack')) {\n throw new InformAiError(\n 'Legacy pack modules must end in /rule-pack. Supply explicit --pack=<package-or-module>=<config.json> declarations for other modules.',\n );\n }\n const packageName = moduleName.slice(0, -'/rule-pack'.length);\n return new PackPolicyDeclaration(\n packageName,\n `.webpieces/rules/${packageName.split('/').at(-1)}.json`,\n );\n });\n }\n\n // webpieces-disable no-any-unknown -- inherited settings and untyped directory rules cannot be silently converted into declared owners\n private upgradeDocument(\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n document: Record<string, unknown>,\n registry: RulePackRegistry,\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n ): Record<string, unknown> {\n if (document['extends'] !== undefined)\n throw new InformAiError(\n 'Remove extends after making inherited values explicit. Upgrade cannot infer inherited policy settings.',\n );\n const directories = document['rulesDir'];\n if (\n directories !== undefined &&\n (!Array.isArray(directories) || directories.length !== 0)\n ) {\n throw new InformAiError(\n 'Replace rulesDir with a declared client rule pack, its owned schemas, and implementation modules before upgrade. Directory implementations cannot supply an inferred schema.',\n );\n }\n if (!Object.hasOwn(document, 'rules') && !Object.hasOwn(document, 'hookGuards'))\n return document;\n const prepared = prepareLegacyUpgrade(structuredClone(document), registry);\n return { ...document, ...prepared.config };\n }\n\n // webpieces-disable no-any-unknown -- explicit upgrade gathers settings by canonical owner after applying owner-declared retirements\n private legacyEntries(\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n document: Record<string, unknown>,\n registry: RulePackRegistry,\n ): Map<string, ConfigObject> {\n if (document['extends'] !== undefined)\n throw new InformAiError(\n 'Remove extends after making inherited values explicit. Upgrade cannot infer inherited policy settings.',\n );\n const directories = document['rulesDir'];\n if (\n directories !== undefined &&\n (!Array.isArray(directories) || directories.length !== 0)\n ) {\n throw new InformAiError(\n 'Replace rulesDir with a declared client rule pack, its owned schemas, and implementation modules before upgrade. Directory implementations cannot supply an inferred schema.',\n );\n }\n const entries = new Map<string, ConfigObject>();\n for (const section of ['rules', 'hookGuards']) {\n if (document[section] === undefined) continue;\n const old = this.object(document[section], section);\n for (const id of Object.keys(old)) {\n if (!registry.hasRule(id))\n throw new InformAiError(\n `${section}.${id} has no selected owner. Declare its owner or remove the entry explicitly before upgrading.`,\n );\n if (entries.has(id))\n throw new InformAiError(\n `${id} appears in both legacy sections. Choose one explicit value before upgrading.`,\n );\n entries.set(id, this.object(old[id], `${section}.${id}`) as ConfigObject);\n }\n }\n return entries;\n }\n\n private prepare(\n root: string,\n selected: readonly SelectedPolicyPack[],\n registry: RulePackRegistry,\n legacy: ReadonlyMap<string, ConfigObject>,\n ): RulePackSyncPlan {\n const plans: OwnerFilePlan[] = [],\n values: Record<string, ConfigObject> = {},\n targets = new Map<string, string>();\n const errors: string[] = [];\n for (const pack of selected) {\n const filename = this.files.configPath(root, pack.declaration.config);\n const entries = fs.existsSync(filename) ? this.files.read(filename) : {};\n for (const id of Object.keys(entries)) {\n if (!registry.hasRule(id) || registry.ownerOf(id) !== pack.manifest.packageName) {\n errors.push(\n `${filename}: ${id} has another owner or is unknown. Move or remove it explicitly before sync.`,\n );\n }\n }\n for (const definition of pack.manifest.ownedRules) {\n const previous = Object.hasOwn(entries, definition.id)\n ? entries[definition.id]\n : legacy.get(definition.id);\n if (\n entries[definition.id] !== undefined &&\n legacy.has(definition.id) &&\n JSON.stringify(entries[definition.id]) !==\n JSON.stringify(legacy.get(definition.id))\n ) {\n errors.push(\n `${filename}: ${definition.id} conflicts with the legacy value. Choose one explicit value before upgrade.`,\n );\n }\n const value = this.seedMissing(previous, definition);\n errors.push(\n ...registry\n .validateRuleConfig(definition.id, value)\n .map((error: string) => `${filename}: ${error}`),\n );\n entries[definition.id] = value;\n values[definition.id] = value;\n targets.set(definition.id, filename);\n }\n plans.push(new OwnerFilePlan(filename, entries));\n }\n if (errors.length) throw new InformAiError(`Sync made no changes:\\n${errors.join('\\n')}`);\n return new RulePackSyncPlan(\n plans,\n new PackPolicyFilesResult(registry, selected, values, targets),\n );\n }\n\n private seedMissing(\n previous: ConfigObject | undefined,\n definition: OwnedRuleDefinition,\n ): ConfigObject {\n const value =\n previous === undefined\n ? structuredClone(definition.recommendedSeed)\n : Object.assign(new ConfigObject(), this.object(previous, definition.id));\n for (const field of Object.keys(definition.schema)) {\n if (!definition.schema[field].optional && !Object.hasOwn(value, field)) {\n value[field] = structuredClone(definition.recommendedSeed[field]);\n }\n }\n return value;\n }\n\n // webpieces-disable no-any-unknown -- explicit upgrade removes only the retired sections it actually converted\n private rootDocument(\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n document: Record<string, unknown>,\n declarations: readonly PackPolicyDeclaration[],\n mode: 'sync' | 'upgrade',\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n ): Record<string, unknown> {\n const next = { ...document, rulePacks: declarations };\n if (mode === 'upgrade')\n for (const key of ['rules', 'hookGuards', 'rulesDir', 'extends'])\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n delete (next as Record<string, unknown>)[key];\n return next;\n }\n\n // webpieces-disable no-any-unknown -- the same generic-root validators run before any write\n private validateRoot(document: Record<string, unknown>, root: string): void {\n const errors = [\n ...validateTopLevelKeys(document),\n ...validateCommandsSection(document['commands'], document['pr-gate'], root),\n ...validateExcludePaths(document['excludePaths']),\n ...validateMatchRulesSection(document['match-rules']),\n ];\n if (errors.length) throw new InformAiError(`Sync made no changes:\\n${errors.join('\\n')}`);\n }\n\n // webpieces-disable no-any-unknown -- JSON object narrowing preserves explicit values for subsequent schema validation\n private object(value: unknown, label: string): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value))\n throw new InformAiError(`${label} must be a JSON object. Repair it before sync.`);\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n return value as Record<string, unknown>;\n }\n}\n\nclass RulePackSyncPlan {\n constructor(\n readonly plans: readonly OwnerFilePlan[],\n readonly resolved: PackPolicyFilesResult,\n ) {}\n}\n"]}
@@ -0,0 +1,27 @@
1
+ import { BuildPolicy, BuildDebugRequest, BuildPolicyResult, ConfigObject, ExecutionKind, PolicyRuntimeRequest } from '@webpieces/rules-sdk';
2
+ import { RulePackRegistry } from './rule-pack-registry';
3
+ /** Describes an implementation without evaluating its module during config validation. */
4
+ export declare class RuntimeContributionGroup {
5
+ readonly providerPack: string;
6
+ readonly implementationModule: string;
7
+ readonly executionKind: ExecutionKind;
8
+ readonly ruleIds: readonly string[];
9
+ constructor(providerPack: string, implementationModule: string, executionKind: ExecutionKind, ruleIds: readonly string[]);
10
+ }
11
+ export declare abstract class RuleRuntimeModuleLoader {
12
+ abstract load(moduleName: string, providerModule: string): unknown;
13
+ }
14
+ export declare class NodeRuleRuntimeModuleLoader extends RuleRuntimeModuleLoader {
15
+ private readonly resolution;
16
+ private readonly requireModule;
17
+ constructor(clientRoot: string);
18
+ load(moduleName: string, providerModule: string): unknown;
19
+ }
20
+ /** Grouped module loading has no built-in package list or policy IDs. */
21
+ export declare class RuleRuntimeModules {
22
+ runBuildDebug(exports: unknown, request: BuildDebugRequest): Promise<BuildPolicyResult>;
23
+ groups(registry: RulePackRegistry, kind: ExecutionKind): readonly RuntimeContributionGroup[];
24
+ load(group: RuntimeContributionGroup, providers: ReadonlyMap<string, string>, loader: RuleRuntimeModuleLoader): unknown;
25
+ request(root: string, configs: Readonly<Record<string, ConfigObject>>, group: RuntimeContributionGroup): PolicyRuntimeRequest;
26
+ createBuildPolicies(exports: unknown, request: PolicyRuntimeRequest): Promise<readonly BuildPolicy[]>;
27
+ }
@@ -0,0 +1,135 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RuleRuntimeModules = exports.NodeRuleRuntimeModuleLoader = exports.RuleRuntimeModuleLoader = exports.RuntimeContributionGroup = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const path = tslib_1.__importStar(require("node:path"));
6
+ const node_module_1 = require("node:module");
7
+ const rules_sdk_1 = require("@webpieces/rules-sdk");
8
+ const tooling_common_1 = require("@webpieces/tooling-common");
9
+ const client_module_resolution_1 = require("./client-module-resolution");
10
+ const to_error_1 = require("@webpieces/tooling-common/to-error");
11
+ /** Describes an implementation without evaluating its module during config validation. */
12
+ class RuntimeContributionGroup {
13
+ providerPack;
14
+ implementationModule;
15
+ executionKind;
16
+ ruleIds;
17
+ constructor(providerPack, implementationModule, executionKind, ruleIds) {
18
+ this.providerPack = providerPack;
19
+ this.implementationModule = implementationModule;
20
+ this.executionKind = executionKind;
21
+ this.ruleIds = ruleIds;
22
+ }
23
+ }
24
+ exports.RuntimeContributionGroup = RuntimeContributionGroup;
25
+ class RuleRuntimeModuleLoader {
26
+ }
27
+ exports.RuleRuntimeModuleLoader = RuleRuntimeModuleLoader;
28
+ class NodeRuleRuntimeModuleLoader extends RuleRuntimeModuleLoader {
29
+ resolution;
30
+ requireModule;
31
+ constructor(clientRoot) {
32
+ super();
33
+ this.resolution = new client_module_resolution_1.ClientModuleResolution(clientRoot);
34
+ this.requireModule = (0, node_module_1.createRequire)(path.join(clientRoot, 'package.json'));
35
+ }
36
+ // webpieces-disable no-any-unknown -- narrowed by its execution-family consumer
37
+ load(moduleName, providerModule) {
38
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- a declared module fault names the runtime and declaration needed for repair
39
+ try {
40
+ const resolved = moduleName.startsWith('.') || path.isAbsolute(moduleName)
41
+ ? path.resolve(path.dirname(this.resolution.resolve(providerModule)), moduleName)
42
+ : this.resolution.resolve(moduleName);
43
+ return this.requireModule(resolved);
44
+ // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution
45
+ }
46
+ catch (err) {
47
+ const error = (0, to_error_1.toError)(err);
48
+ throw new tooling_common_1.InformAiError(`Cannot load declared policy runtime ${moduleName} from ${providerModule}: ${error.message}. Repair its public implementation module or root declaration.`, { cause: error });
49
+ }
50
+ }
51
+ }
52
+ exports.NodeRuleRuntimeModuleLoader = NodeRuleRuntimeModuleLoader;
53
+ /** Grouped module loading has no built-in package list or policy IDs. */
54
+ class RuleRuntimeModules {
55
+ // webpieces-disable no-any-unknown -- a selected provider explicitly advertises its debug capability
56
+ async runBuildDebug(exports, request) {
57
+ if (!exports || typeof exports !== 'object' || !('buildDebugRuntime' in exports)) {
58
+ throw new tooling_common_1.InformAiError(`The build provider for ${request.selection.rule} does not support debug runs. Use its declared policy settings and normal validation.`);
59
+ }
60
+ const runtime = exports.buildDebugRuntime;
61
+ if (!runtime || typeof runtime.run !== 'function')
62
+ throw new tooling_common_1.InformAiError('Invalid buildDebugRuntime.run(request). Repair the provider export.');
63
+ const result = await runtime.run(request);
64
+ if (!result || typeof result.success !== 'boolean')
65
+ throw new tooling_common_1.InformAiError('Debug runtime must return an explicit success boolean.');
66
+ return result;
67
+ }
68
+ groups(registry, kind) {
69
+ const groups = [];
70
+ for (const manifest of registry.manifests) {
71
+ const modules = new Map();
72
+ for (const contribution of manifest.contributions) {
73
+ if (contribution.executionKind !== kind)
74
+ continue;
75
+ const ids = modules.get(contribution.implementationModule) ?? [];
76
+ ids.push(contribution.ruleId);
77
+ modules.set(contribution.implementationModule, ids);
78
+ }
79
+ for (const entry of modules) {
80
+ const moduleName = entry[0], ids = entry[1];
81
+ groups.push(new RuntimeContributionGroup(manifest.packageName, moduleName, kind, ids));
82
+ }
83
+ }
84
+ return groups;
85
+ }
86
+ // webpieces-disable no-any-unknown -- transport boundary for execution-family adapters
87
+ load(group, providers, loader) {
88
+ const provider = providers.get(group.providerPack);
89
+ if (!provider)
90
+ throw new tooling_common_1.InformAiError(`Missing declared manifest module for ${group.providerPack}. Repair rulePacks.`);
91
+ return loader.load(group.implementationModule, provider);
92
+ }
93
+ request(root, configs, group) {
94
+ const selected = {};
95
+ for (const id of group.ruleIds) {
96
+ if (!Object.hasOwn(configs, id))
97
+ throw new tooling_common_1.InformAiError(`Missing explicit config for ${id}. Repair its declared owner file.`);
98
+ selected[id] = configs[id];
99
+ }
100
+ return new rules_sdk_1.PolicyRuntimeRequest(root, selected, group.ruleIds);
101
+ }
102
+ // webpieces-disable no-any-unknown -- public exports are validated before use; no concrete execution package is imported
103
+ async createBuildPolicies(
104
+ // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution
105
+ exports, request) {
106
+ if (!exports || typeof exports !== 'object' || !('buildRuleRuntime' in exports)) {
107
+ throw new tooling_common_1.InformAiError('Build contribution must export buildRuleRuntime.create(request). Repair its public runtime export.');
108
+ }
109
+ const runtime = exports.buildRuleRuntime;
110
+ if (!runtime || typeof runtime.create !== 'function')
111
+ throw new tooling_common_1.InformAiError('Invalid buildRuleRuntime.create. Supply a build runtime factory.');
112
+ const checks = await runtime.create(request);
113
+ if (!Array.isArray(checks))
114
+ throw new tooling_common_1.InformAiError('Build runtime must return an array of configured checks.');
115
+ const covered = new Set();
116
+ for (const check of checks) {
117
+ if (!check ||
118
+ typeof check.name !== 'string' ||
119
+ !check.name ||
120
+ !request.ruleIds.includes(check.configKey) ||
121
+ typeof check.shouldRun !== 'function' ||
122
+ typeof check.run !== 'function') {
123
+ throw new tooling_common_1.InformAiError('Invalid build check. Supply name, declared configKey, shouldRun(), and run(root).');
124
+ }
125
+ covered.add(check.configKey);
126
+ }
127
+ for (const id of request.ruleIds) {
128
+ if (!covered.has(id))
129
+ throw new tooling_common_1.InformAiError(`Build runtime omitted declared policy ${id}. Supply its actual implementation.`);
130
+ }
131
+ return checks;
132
+ }
133
+ }
134
+ exports.RuleRuntimeModules = RuleRuntimeModules;
135
+ //# sourceMappingURL=rule-runtime-modules.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rule-runtime-modules.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/rule-runtime-modules.ts"],"names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;YACD,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;QACjC,CAAC;QACD,KAAK,MAAM,EAAE,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;YAC/B,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;gBAChB,MAAM,IAAI,8BAAa,CACnB,yCAAyC,EAAE,qCAAqC,CACnF,CAAC;QACV,CAAC;QACD,OAAO,MAAM,CAAC;IAClB,CAAC;CACJ;AAjHD,gDAiHC","sourcesContent":["import * as path from 'node:path';\nimport { createRequire } from 'node:module';\nimport {\n BuildPolicy,\n BuildRuleRuntime,\n BuildDebugRequest,\n BuildDebugRuntime,\n BuildPolicyResult,\n ConfigObject,\n ExecutionKind,\n PolicyRuntimeRequest,\n} from '@webpieces/rules-sdk';\nimport { InformAiError } from '@webpieces/tooling-common';\nimport { RulePackRegistry } from './rule-pack-registry';\nimport { ClientModuleResolution } from './client-module-resolution';\nimport { toError } from '@webpieces/tooling-common/to-error';\n\n/** Describes an implementation without evaluating its module during config validation. */\nexport class RuntimeContributionGroup {\n constructor(\n readonly providerPack: string,\n readonly implementationModule: string,\n readonly executionKind: ExecutionKind,\n readonly ruleIds: readonly string[],\n ) {}\n}\n\nexport abstract class RuleRuntimeModuleLoader {\n // webpieces-disable no-any-unknown -- execution-family consumers validate external module contracts\n abstract load(moduleName: string, providerModule: string): unknown;\n}\n\nexport class NodeRuleRuntimeModuleLoader extends RuleRuntimeModuleLoader {\n private readonly resolution: ClientModuleResolution;\n private readonly requireModule: NodeRequire;\n\n constructor(clientRoot: string) {\n super();\n this.resolution = new ClientModuleResolution(clientRoot);\n this.requireModule = createRequire(path.join(clientRoot, 'package.json'));\n }\n\n // webpieces-disable no-any-unknown -- narrowed by its execution-family consumer\n override load(moduleName: string, providerModule: string): unknown {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- a declared module fault names the runtime and declaration needed for repair\n try {\n const resolved =\n moduleName.startsWith('.') || path.isAbsolute(moduleName)\n ? path.resolve(\n path.dirname(this.resolution.resolve(providerModule)),\n moduleName,\n )\n : this.resolution.resolve(moduleName);\n return this.requireModule(resolved);\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n } catch (err: unknown) {\n const error = toError(err);\n throw new InformAiError(\n `Cannot load declared policy runtime ${moduleName} from ${providerModule}: ${error.message}. Repair its public implementation module or root declaration.`,\n { cause: error },\n );\n }\n }\n}\n\n/** Grouped module loading has no built-in package list or policy IDs. */\nexport class RuleRuntimeModules {\n // webpieces-disable no-any-unknown -- a selected provider explicitly advertises its debug capability\n async runBuildDebug(exports: unknown, request: BuildDebugRequest): Promise<BuildPolicyResult> {\n if (!exports || typeof exports !== 'object' || !('buildDebugRuntime' in exports)) {\n throw new InformAiError(\n `The build provider for ${request.selection.rule} does not support debug runs. Use its declared policy settings and normal validation.`,\n );\n }\n const runtime = exports.buildDebugRuntime as BuildDebugRuntime;\n if (!runtime || typeof runtime.run !== 'function')\n throw new InformAiError(\n 'Invalid buildDebugRuntime.run(request). Repair the provider export.',\n );\n const result = await runtime.run(request);\n if (!result || typeof result.success !== 'boolean')\n throw new InformAiError('Debug runtime must return an explicit success boolean.');\n return result;\n }\n\n groups(registry: RulePackRegistry, kind: ExecutionKind): readonly RuntimeContributionGroup[] {\n const groups: RuntimeContributionGroup[] = [];\n for (const manifest of registry.manifests) {\n const modules = new Map<string, string[]>();\n for (const contribution of manifest.contributions) {\n if (contribution.executionKind !== kind) continue;\n const ids = modules.get(contribution.implementationModule) ?? [];\n ids.push(contribution.ruleId);\n modules.set(contribution.implementationModule, ids);\n }\n for (const entry of modules) {\n const moduleName = entry[0], ids = entry[1];\n groups.push(\n new RuntimeContributionGroup(manifest.packageName, moduleName, kind, ids),\n );\n }\n }\n return groups;\n }\n\n // webpieces-disable no-any-unknown -- transport boundary for execution-family adapters\n load(\n group: RuntimeContributionGroup,\n providers: ReadonlyMap<string, string>,\n loader: RuleRuntimeModuleLoader,\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n ): unknown {\n const provider = providers.get(group.providerPack);\n if (!provider)\n throw new InformAiError(\n `Missing declared manifest module for ${group.providerPack}. Repair rulePacks.`,\n );\n return loader.load(group.implementationModule, provider);\n }\n\n request(\n root: string,\n configs: Readonly<Record<string, ConfigObject>>,\n group: RuntimeContributionGroup,\n ): PolicyRuntimeRequest {\n const selected: Record<string, ConfigObject> = {};\n for (const id of group.ruleIds) {\n if (!Object.hasOwn(configs, id))\n throw new InformAiError(\n `Missing explicit config for ${id}. Repair its declared owner file.`,\n );\n selected[id] = configs[id];\n }\n return new PolicyRuntimeRequest(root, selected, group.ruleIds);\n }\n\n // webpieces-disable no-any-unknown -- public exports are validated before use; no concrete execution package is imported\n async createBuildPolicies(\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n exports: unknown,\n request: PolicyRuntimeRequest,\n ): Promise<readonly BuildPolicy[]> {\n if (!exports || typeof exports !== 'object' || !('buildRuleRuntime' in exports)) {\n throw new InformAiError(\n 'Build contribution must export buildRuleRuntime.create(request). Repair its public runtime export.',\n );\n }\n const runtime = exports.buildRuleRuntime as BuildRuleRuntime;\n if (!runtime || typeof runtime.create !== 'function')\n throw new InformAiError(\n 'Invalid buildRuleRuntime.create. Supply a build runtime factory.',\n );\n const checks = await runtime.create(request);\n if (!Array.isArray(checks))\n throw new InformAiError('Build runtime must return an array of configured checks.');\n const covered = new Set<string>();\n for (const check of checks) {\n if (\n !check ||\n typeof check.name !== 'string' ||\n !check.name ||\n !request.ruleIds.includes(check.configKey) ||\n typeof check.shouldRun !== 'function' ||\n typeof check.run !== 'function'\n ) {\n throw new InformAiError(\n 'Invalid build check. Supply name, declared configKey, shouldRun(), and run(root).',\n );\n }\n covered.add(check.configKey);\n }\n for (const id of request.ruleIds) {\n if (!covered.has(id))\n throw new InformAiError(\n `Build runtime omitted declared policy ${id}. Supply its actual implementation.`,\n );\n }\n return checks;\n }\n}\n"]}
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ import { RulePackSyncOptions } from './rule-pack-sync';
3
+ /** CLI parsing does not validate the live config: this command repairs missing required settings. */
4
+ export declare class RulesSyncCli {
5
+ parse(args: readonly string[]): RulePackSyncOptions;
6
+ main(): Promise<void>;
7
+ }
@@ -0,0 +1,48 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.RulesSyncCli = void 0;
5
+ const tooling_common_1 = require("@webpieces/tooling-common");
6
+ const config_file_1 = require("./config-file");
7
+ const pack_policy_files_1 = require("./pack-policy-files");
8
+ const rule_pack_artifacts_1 = require("./rule-pack-artifacts");
9
+ const rule_pack_sync_1 = require("./rule-pack-sync");
10
+ const repo_root_1 = require("./repo-root");
11
+ const run_main_1 = require("./run-main");
12
+ /** CLI parsing does not validate the live config: this command repairs missing required settings. */
13
+ class RulesSyncCli {
14
+ parse(args) {
15
+ let mode = 'sync';
16
+ const declarations = [];
17
+ for (let index = 0; index < args.length; index++) {
18
+ const argument = args[index];
19
+ if (argument === '--upgrade') {
20
+ mode = 'upgrade';
21
+ continue;
22
+ }
23
+ const value = argument === '--pack'
24
+ ? args[++index]
25
+ : argument.startsWith('--pack=')
26
+ ? argument.slice(7)
27
+ : undefined;
28
+ if (!value || value.indexOf('=') <= 0 || value.endsWith('=')) {
29
+ throw new tooling_common_1.InformAiError('Usage: pnpm wp-rules-sync [--upgrade] [--pack=<package-or-module>=<repository-relative-config.json>] ...');
30
+ }
31
+ const separator = value.indexOf('=');
32
+ declarations.push(new pack_policy_files_1.PackPolicyDeclaration(value.slice(0, separator), value.slice(separator + 1)));
33
+ }
34
+ return new rule_pack_sync_1.RulePackSyncOptions(mode, declarations.length ? declarations : null);
35
+ }
36
+ async main() {
37
+ const atomic = new tooling_common_1.AtomicFile(), root = new repo_root_1.RepoRootFinder().resolveRepoRoot(process.cwd());
38
+ const sync = new rule_pack_sync_1.RulePackSync(new config_file_1.ConfigFile(), new pack_policy_files_1.PackPolicyFiles(), new rule_pack_artifacts_1.RulePackArtifacts(atomic), atomic);
39
+ const changed = sync.run(root, this.parse(process.argv.slice(2)));
40
+ console.log(changed.length
41
+ ? `Review and commit these explicit config/artifact changes:\n${changed.join('\n')}`
42
+ : 'Rule config and generated artifacts already agree.');
43
+ }
44
+ }
45
+ exports.RulesSyncCli = RulesSyncCli;
46
+ if (require.main === module)
47
+ (0, run_main_1.runMain)(() => new RulesSyncCli().main());
48
+ //# sourceMappingURL=rules-sync-cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rules-sync-cli.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/rules-sync-cli.ts"],"names":[],"mappings":";;;;AACA,8DAAsE;AACtE,+CAA2C;AAC3C,2DAA6E;AAC7E,+DAA0D;AAC1D,qDAAqE;AACrE,2CAA6C;AAC7C,yCAAqC;AAErC,qGAAqG;AACrG,MAAa,YAAY;IACrB,KAAK,CAAC,IAAuB;QACzB,IAAI,IAAI,GAAuB,MAAM,CAAC;QACtC,MAAM,YAAY,GAA4B,EAAE,CAAC;QACjD,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,IAAI,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE,CAAC;YAC/C,MAAM,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC;YAC7B,IAAI,QAAQ,KAAK,WAAW,EAAE,CAAC;gBAC3B,IAAI,GAAG,SAAS,CAAC;gBACjB,SAAS;YACb,CAAC;YACD,MAAM,KAAK,GACP,QAAQ,KAAK,QAAQ;gBACjB,CAAC,CAAC,IAAI,CAAC,EAAE,KAAK,CAAC;gBACf,CAAC,CAAC,QAAQ,CAAC,UAAU,CAAC,SAAS,CAAC;oBAC9B,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC;oBACnB,CAAC,CAAC,SAAS,CAAC;YACtB,IAAI,CAAC,KAAK,IAAI,KAAK,CAAC,OAAO,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AO,EAAC,GAAG,EAAE,CAAC,IAAI,YAAY,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\nimport { AtomicFile, InformAiError } from '@webpieces/tooling-common';\nimport { ConfigFile } from './config-file';\nimport { PackPolicyDeclaration, PackPolicyFiles } from './pack-policy-files';\nimport { RulePackArtifacts } from './rule-pack-artifacts';\nimport { RulePackSync, RulePackSyncOptions } from './rule-pack-sync';\nimport { RepoRootFinder } from './repo-root';\nimport { runMain } from './run-main';\n\n/** CLI parsing does not validate the live config: this command repairs missing required settings. */\nexport class RulesSyncCli {\n parse(args: readonly string[]): RulePackSyncOptions {\n let mode: 'sync' | 'upgrade' = 'sync';\n const declarations: PackPolicyDeclaration[] = [];\n for (let index = 0; index < args.length; index++) {\n const argument = args[index];\n if (argument === '--upgrade') {\n mode = 'upgrade';\n continue;\n }\n const value =\n argument === '--pack'\n ? args[++index]\n : argument.startsWith('--pack=')\n ? argument.slice(7)\n : undefined;\n if (!value || value.indexOf('=') <= 0 || value.endsWith('=')) {\n throw new InformAiError(\n 'Usage: pnpm wp-rules-sync [--upgrade] [--pack=<package-or-module>=<repository-relative-config.json>] ...',\n );\n }\n const separator = value.indexOf('=');\n declarations.push(\n new PackPolicyDeclaration(value.slice(0, separator), value.slice(separator + 1)),\n );\n }\n return new RulePackSyncOptions(mode, declarations.length ? declarations : null);\n }\n\n async main(): Promise<void> {\n const atomic = new AtomicFile(),\n root = new RepoRootFinder().resolveRepoRoot(process.cwd());\n const sync = new RulePackSync(\n new ConfigFile(),\n new PackPolicyFiles(),\n new RulePackArtifacts(atomic),\n atomic,\n );\n const changed = sync.run(root, this.parse(process.argv.slice(2)));\n console.log(\n changed.length\n ? `Review and commit these explicit config/artifact changes:\\n${changed.join('\\n')}`\n : 'Rule config and generated artifacts already agree.',\n );\n }\n}\n\nif (require.main === module) runMain(() => new RulesSyncCli().main());\n"]}
package/src/seed-entry.js CHANGED
@@ -43,9 +43,7 @@ function seedEntryForRule(ruleName, registry) {
43
43
  return registry.seedFor(ruleName);
44
44
  if (registry.isSafeguard(ruleName))
45
45
  throw new tooling_common_1.InformAiError(`${ruleName} is a safeguard with no configurable seed. Remove its config entry.`);
46
- // Existing rulesDir-only custom implementations have no declared schema. This is file-writing advice,
47
- // never a loader default; declared custom policies always use their owner's complete seed.
48
- return { mode: 'OFF', turnOffRuleUntilEpoch: 0, turnOffRuleWhileOnBranch: null };
46
+ throw new tooling_common_1.InformAiError(`No selected owner supplies a seed for ${ruleName}. Declare its client rule pack with a schema and recommended seed; sync never invents settings for unknown policies.`);
49
47
  }
50
48
  /** True when `mode` is one of the gradual (change-scoped) modes — used to decide whether to print the rollout prose. */
51
49
  // webpieces-disable no-function-outside-class -- sibling of the seeding helpers in this file
@@ -1 +1 @@
1
- {"version":3,"file":"seed-entry.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/seed-entry.ts"],"names":[],"mappings":";;AAsBA,wDAMC;AAKD,kDAEC;AAED,4CAMC;AAID,sCAEC;AAjDD,8DAA0D;AAI1D,MAAM,uBAAuB,GAAG;IAC5B,uBAAuB;IACvB,0BAA0B;IAC1B,gBAAgB;IAChB,aAAa;IACb,wBAAwB;IACxB,mBAAmB;IACnB,gGAAgG;IAChG,+FAA+F;IAC/F,kBAAkB;CACrB,CAAC;AAEF,kGAAkG;AAClG,4HAA4H;AAC5H,oGAAoG;AACpG,oGAAoG;AACpG,6CAA6C;AAC7C,yGAAyG;AACzG,SAAgB,sBAAsB,CAAC,KAAwB;IAC3D,MAAM,OAAO,GAAG,uBAAuB,CAAC,IAAI,CAAC,CAAC,CAAS,EAAE,EAAE,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC;IAC/E,IAAI,OAAO;QAAE,OAAO,OAAO,CAAC;IAC5B,IAAI,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC;QAAE,OAAO,IAAI,CAAC;IACtC,IAAI,KAAK,CAAC,QAAQ,CAAC,gBAAgB,CAAC;QAAE,OAAO,gBAAgB,CAAC;IAC9D,OAAO,KAAK,CAAC;AACjB,CAAC;AAGD,oFAAoF;AACpF,0EAA0E;AAC1E,SAAgB,mBAAmB,CAAC,QAAgB,EAAE,QAA0B;IAC5E,OAAO,MAAM,CAAC,gBAAgB,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;AAChE,CAAC;AACD,0EAA0E;AAC1E,SAAgB,gBAAgB,CAAC,QAAgB,EAAE,QAA0B;IACzE,IAAI,QAAQ,CAAC,OAAO,CAAC,QAAQ,CAAC;QAAE,OAAO,QAAQ,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;IAClE,IAAI,QAAQ,CAAC,WAAW,CAAC,QAAQ,CAAC;QAAE,MAAM,IAAI,8BAAa,CAAC,GAAG,QAAQ,qEAAqE,CAAC,CAAC;IAC9I,sGAAsG;IACtG,2FAA2F;IAC3F,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,qBAAqB,EAAE,CAAC,EAAE,wBAAwB,EAAE,IAAI,EAAE,CAAC;AACrF,CAAC;AAED,wHAAwH;AACxH,6FAA6F;AAC7F,SAAgB,aAAa,CAAC,IAAY;IACtC,OAAO,uBAAuB,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;AAClD,CAAC","sourcesContent":["import { InformAiError } from '@webpieces/tooling-common';\nimport { ConfigObject } from '@webpieces/rules-sdk';\nimport { RulePackRegistry } from './rule-pack-registry';\n\nconst GRADUAL_MODE_PREFERENCE = [\n 'NEW_AND_MODIFIED_CODE',\n 'NEW_AND_MODIFIED_METHODS',\n 'MODIFIED_CLASS',\n 'NEW_METHODS',\n 'NEW_AND_MODIFIED_FILES',\n 'MODIFIED_PROJECTS',\n // Same granularity as MODIFIED_PROJECTS, from the other direction: the projects nx's diff makes\n // affected. Listed after it so a rule offering both keeps its existing recommendation (#1017).\n 'AFFECTED_PROJECT',\n];\n\n// The ONE place that decides what mode a rule should arrive as. Every consumer of that decision —\n// the validator's copy-paste snippet (rolloutTip in validate-config.ts), the installer's seeding, and the fault-`Y` deny in\n// ai-hook-rules — calls this, so a seeded config can never contradict the advice printed beside it.\n// Precedence: narrowest gradual mode the rule supports → ON → RUN_EVERY_TIME → OFF (a rule offering\n// none of those has nothing else it can be).\n// webpieces-disable no-function-outside-class -- sibling of the module-scope schema helpers in this file\nexport function recommendedSeedModeFor(modes: readonly string[]): string {\n const gradual = GRADUAL_MODE_PREFERENCE.find((m: string) => modes.includes(m));\n if (gradual) return gradual;\n if (modes.includes('ON')) return 'ON';\n if (modes.includes('RUN_EVERY_TIME')) return 'RUN_EVERY_TIME';\n return 'OFF';\n}\n\n\n/** Recommendations are owner-authored file-writing data, never runtime defaults. */\n// webpieces-disable no-function-outside-class -- pure registry projection\nexport function recommendedSeedMode(ruleName: string, registry: RulePackRegistry): string {\n return String(seedEntryForRule(ruleName, registry)['mode']);\n}\n// webpieces-disable no-function-outside-class -- pure registry projection\nexport function seedEntryForRule(ruleName: string, registry: RulePackRegistry): ConfigObject {\n if (registry.hasRule(ruleName)) return registry.seedFor(ruleName);\n if (registry.isSafeguard(ruleName)) throw new InformAiError(`${ruleName} is a safeguard with no configurable seed. Remove its config entry.`);\n // Existing rulesDir-only custom implementations have no declared schema. This is file-writing advice,\n // never a loader default; declared custom policies always use their owner's complete seed.\n return { mode: 'OFF', turnOffRuleUntilEpoch: 0, turnOffRuleWhileOnBranch: null };\n}\n\n/** True when `mode` is one of the gradual (change-scoped) modes — used to decide whether to print the rollout prose. */\n// webpieces-disable no-function-outside-class -- sibling of the seeding helpers in this file\nexport function isGradualMode(mode: string): boolean {\n return GRADUAL_MODE_PREFERENCE.includes(mode);\n}\n"]}
1
+ {"version":3,"file":"seed-entry.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/seed-entry.ts"],"names":[],"mappings":";;AAsBA,wDAMC;AAID,kDAEC;AAED,4CASC;AAID,sCAEC;AAnDD,8DAA0D;AAI1D,MAAM,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AgB,aAAa,CAAC,IAAY;IACtC,OAAO,uBAAuB,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;AAClD,CAAC","sourcesContent":["import { InformAiError } from '@webpieces/tooling-common';\nimport { ConfigObject } from '@webpieces/rules-sdk';\nimport { RulePackRegistry } from './rule-pack-registry';\n\nconst GRADUAL_MODE_PREFERENCE = [\n 'NEW_AND_MODIFIED_CODE',\n 'NEW_AND_MODIFIED_METHODS',\n 'MODIFIED_CLASS',\n 'NEW_METHODS',\n 'NEW_AND_MODIFIED_FILES',\n 'MODIFIED_PROJECTS',\n // Same granularity as MODIFIED_PROJECTS, from the other direction: the projects nx's diff makes\n // affected. Listed after it so a rule offering both keeps its existing recommendation (#1017).\n 'AFFECTED_PROJECT',\n];\n\n// The ONE place that decides what mode a rule should arrive as. Every consumer of that decision —\n// the validator's copy-paste snippet (rolloutTip in validate-config.ts), the installer's seeding, and the fault-`Y` deny in\n// ai-hook-rules — calls this, so a seeded config can never contradict the advice printed beside it.\n// Precedence: narrowest gradual mode the rule supports → ON → RUN_EVERY_TIME → OFF (a rule offering\n// none of those has nothing else it can be).\n// webpieces-disable no-function-outside-class -- sibling of the module-scope schema helpers in this file\nexport function recommendedSeedModeFor(modes: readonly string[]): string {\n const gradual = GRADUAL_MODE_PREFERENCE.find((m: string) => modes.includes(m));\n if (gradual) return gradual;\n if (modes.includes('ON')) return 'ON';\n if (modes.includes('RUN_EVERY_TIME')) return 'RUN_EVERY_TIME';\n return 'OFF';\n}\n\n/** Recommendations are owner-authored file-writing data, never runtime defaults. */\n// webpieces-disable no-function-outside-class -- pure registry projection\nexport function recommendedSeedMode(ruleName: string, registry: RulePackRegistry): string {\n return String(seedEntryForRule(ruleName, registry)['mode']);\n}\n// webpieces-disable no-function-outside-class -- pure registry projection\nexport function seedEntryForRule(ruleName: string, registry: RulePackRegistry): ConfigObject {\n if (registry.hasRule(ruleName)) return registry.seedFor(ruleName);\n if (registry.isSafeguard(ruleName))\n throw new InformAiError(\n `${ruleName} is a safeguard with no configurable seed. Remove its config entry.`,\n );\n throw new InformAiError(\n `No selected owner supplies a seed for ${ruleName}. Declare its client rule pack with a schema and recommended seed; sync never invents settings for unknown policies.`,\n );\n}\n\n/** True when `mode` is one of the gradual (change-scoped) modes — used to decide whether to print the rollout prose. */\n// webpieces-disable no-function-outside-class -- sibling of the seeding helpers in this file\nexport function isGradualMode(mode: string): boolean {\n return GRADUAL_MODE_PREFERENCE.includes(mode);\n}\n"]}
package/src/types.d.ts CHANGED
@@ -1,14 +1,13 @@
1
1
  export type RuleOptions = Record<string, unknown>;
2
2
  /**
3
- * One rule entry from webpieces.config.json, merged with built-in defaults.
3
+ * One validated owner entry, with only owner-declared optional tuning resolved.
4
4
  *
5
5
  * `options` contains the raw option bag (mode, limit, disableAllowed,
6
6
  * turnOffRuleUntilEpoch, enforcePaths, etc). Consumers extract the
7
7
  * fields they understand and ignore the rest.
8
8
  *
9
9
  * On/off is driven entirely by `mode`: a rule is OFF only when explicitly
10
- * set to `mode: "OFF"`. Any other value (or an absent mode) leaves the rule
11
- * ON. For code-rules, `mode` doubles as the scope selector
10
+ * set to `mode: "OFF"`. Every configured entry has a schema-required mode. For code-rules, `mode` doubles as the scope selector
12
11
  * (e.g. "NEW_AND_MODIFIED_CODE", "NEW_AND_MODIFIED_METHODS"); for simple on/off
13
12
  * rules it is just "ON"/"OFF". (The legacy `enabled` boolean has been
14
13
  * removed in favor of this single, more flexible switch.)
@@ -18,7 +17,7 @@ export declare class ResolvedRuleConfig {
18
17
  constructor(options: RuleOptions);
19
18
  /** Raw mode string from the option bag ("ON" | "OFF" | scope value), if present. */
20
19
  get mode(): string | undefined;
21
- /** A rule is off only when explicitly `mode: "OFF"`. An absent mode means on. */
20
+ /** A rule is off only when explicitly `mode: "OFF"`. The loader rejects an absent mode. */
22
21
  get isOff(): boolean;
23
22
  }
24
23
  /**
@@ -32,7 +31,6 @@ export declare class ResolvedRuleConfig {
32
31
  export declare class ResolvedConfig {
33
32
  readonly rules: Map<string, ResolvedRuleConfig>;
34
33
  readonly userConfiguredRuleNames: ReadonlySet<string>;
35
- readonly rulesDir: readonly string[];
36
34
  readonly configPath: string | null;
37
- constructor(rules: Map<string, ResolvedRuleConfig>, userConfiguredRuleNames: ReadonlySet<string>, rulesDir: readonly string[], configPath: string | null);
35
+ constructor(rules: Map<string, ResolvedRuleConfig>, userConfiguredRuleNames: ReadonlySet<string>, configPath: string | null);
38
36
  }