@bleedingdev/modern-js-code-tools 3.9.0-ultramodern.2 → 3.9.0-ultramodern.20

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 (42) hide show
  1. package/bin/modern-api-check-files.mjs +7 -0
  2. package/bin/modern-api-check.mjs +4 -0
  3. package/bin/modern-i18n-check.mjs +4 -0
  4. package/dist/cjs/cli/microvertical-api-check.cjs +100 -0
  5. package/dist/cjs/cli/oxlint.cjs +9 -5
  6. package/dist/cjs/cli/workspace-source-check.cjs +90 -17
  7. package/dist/cjs/microvertical-api-baseline.cjs +505 -0
  8. package/dist/cjs/microvertical-api-boundary.cjs +586 -0
  9. package/dist/cjs/microvertical-api-owner.cjs +217 -0
  10. package/dist/cjs/module-graph.cjs +321 -0
  11. package/dist/cjs/oxlint-plugin/rules/strict-effect-api-boundaries.cjs +8 -6
  12. package/dist/cjs/source-analysis.cjs +104 -0
  13. package/dist/cjs/strict-effect-runtime.cjs +376 -0
  14. package/dist/esm/cli/microvertical-api-check.js +52 -0
  15. package/dist/esm/cli/oxlint.js +10 -6
  16. package/dist/esm/cli/workspace-source-check.js +86 -13
  17. package/dist/esm/microvertical-api-baseline.js +464 -0
  18. package/dist/esm/microvertical-api-boundary.js +525 -0
  19. package/dist/esm/microvertical-api-owner.js +162 -0
  20. package/dist/esm/module-graph.js +260 -0
  21. package/dist/esm/oxlint-plugin/rules/strict-effect-api-boundaries.js +8 -6
  22. package/dist/esm/source-analysis.js +44 -0
  23. package/dist/esm/strict-effect-runtime.js +324 -0
  24. package/dist/esm-node/cli/microvertical-api-check.js +53 -0
  25. package/dist/esm-node/cli/oxlint.js +10 -6
  26. package/dist/esm-node/cli/workspace-source-check.js +86 -13
  27. package/dist/esm-node/microvertical-api-baseline.js +465 -0
  28. package/dist/esm-node/microvertical-api-boundary.js +526 -0
  29. package/dist/esm-node/microvertical-api-owner.js +163 -0
  30. package/dist/esm-node/module-graph.js +261 -0
  31. package/dist/esm-node/oxlint-plugin/rules/strict-effect-api-boundaries.js +8 -6
  32. package/dist/esm-node/source-analysis.js +45 -0
  33. package/dist/esm-node/strict-effect-runtime.js +325 -0
  34. package/dist/types/cli/microvertical-api-check.d.ts +1 -0
  35. package/dist/types/cli/workspace-source-check.d.ts +1 -1
  36. package/dist/types/microvertical-api-baseline.d.ts +23 -0
  37. package/dist/types/microvertical-api-boundary.d.ts +46 -0
  38. package/dist/types/microvertical-api-owner.d.ts +6 -0
  39. package/dist/types/module-graph.d.ts +52 -0
  40. package/dist/types/source-analysis.d.ts +10 -0
  41. package/dist/types/strict-effect-runtime.d.ts +10 -0
  42. package/package.json +29 -6
@@ -0,0 +1,324 @@
1
+ import node_fs from "node:fs";
2
+ import node_path from "node:path";
3
+ import { SourceSyntaxError, parseSource, traverseSource, unwrapExpression } from "./source-analysis.js";
4
+ import * as __rspack_external__babel_types_6e8337dd from "@babel/types";
5
+ const edge = '@modern-js/bff-effect/effect-edge';
6
+ const nodeRuntime = '@modern-js/bff-effect/effect';
7
+ const assembly = '@modern-js/bff-effect/assembly';
8
+ const failure = 'Generated API entries must export defineEffectBff(...) or the native Effect BFF assembly helper with an explicitly composed handler Layer and an unshadowed executable root; entries must implement handlers through HttpApiBuilder.group.';
9
+ const MAX_API_SOURCE_MODULES = 256;
10
+ function createEffectApiImportResolver(filename) {
11
+ const directory = node_fs.realpathSync(node_path.dirname(filename));
12
+ const owner = node_fs.realpathSync(node_path.resolve(directory, '..'));
13
+ const resolve = (from)=>(specifier)=>{
14
+ if (!specifier.startsWith('.')) return;
15
+ const target = node_path.resolve(node_path.dirname(from), specifier);
16
+ if (!target.startsWith(`${owner}${node_path.sep}`)) return;
17
+ for (const candidate of [
18
+ target,
19
+ `${target}.ts`,
20
+ `${target}.mts`
21
+ ])try {
22
+ const real = node_fs.realpathSync(candidate);
23
+ if (!real.startsWith(`${owner}${node_path.sep}`) || node_fs.statSync(real).size > 1000000) return;
24
+ return {
25
+ id: real,
26
+ source: node_fs.readFileSync(real, 'utf8'),
27
+ resolveImport: resolve(real)
28
+ };
29
+ } catch {}
30
+ };
31
+ return resolve(node_path.join(directory, node_path.basename(filename)));
32
+ }
33
+ function strictEffectRuntimeTopologyViolation(source, resolveImport) {
34
+ const modules = new Map();
35
+ const owners = new Map();
36
+ const paths = new Map();
37
+ const mutated = new Set();
38
+ const load = (input)=>{
39
+ const existing = modules.get(input.id);
40
+ if (existing) return existing;
41
+ if (modules.size >= MAX_API_SOURCE_MODULES || input.source.length > 1000000) throw new SourceSyntaxError('API source budget exceeded');
42
+ const file = parseSource(input.source, input.id, 'Invalid API syntax');
43
+ const module = {
44
+ ...input,
45
+ file
46
+ };
47
+ modules.set(input.id, module);
48
+ traverseSource(file, {
49
+ enter (nodePath) {
50
+ paths.set(nodePath.node, nodePath);
51
+ owners.set(nodePath.node, module);
52
+ if (nodePath.isAssignmentExpression() || nodePath.isUpdateExpression() || nodePath.isUnaryExpression({
53
+ operator: 'delete'
54
+ })) {
55
+ let target = nodePath.isAssignmentExpression() ? nodePath.node.left : nodePath.node.argument;
56
+ while(__rspack_external__babel_types_6e8337dd.isMemberExpression(target))target = target.object;
57
+ if (__rspack_external__babel_types_6e8337dd.isIdentifier(target)) {
58
+ const binding = nodePath.scope.getBinding(target.name);
59
+ if (binding) mutated.add(binding);
60
+ }
61
+ }
62
+ if (nodePath.isTSModuleDeclaration() && __rspack_external__babel_types_6e8337dd.isIdentifier(nodePath.node.id)) {
63
+ const binding = nodePath.scope.getBinding(nodePath.node.id.name);
64
+ if (binding) mutated.add(binding);
65
+ }
66
+ }
67
+ });
68
+ return module;
69
+ };
70
+ try {
71
+ const entry = load({
72
+ id: '/entry.ts',
73
+ source,
74
+ resolveImport
75
+ });
76
+ const unwrap = (node)=>unwrapExpression(node, true);
77
+ const binding = (node)=>{
78
+ node = unwrap(node);
79
+ if (!__rspack_external__babel_types_6e8337dd.isIdentifier(node)) return;
80
+ const nodePath = paths.get(node);
81
+ if (!nodePath) throw new Error('Missing API lexical scope');
82
+ const value = nodePath.scope.getBinding(node.name);
83
+ return value?.constant && !mutated.has(value) ? value : void 0;
84
+ };
85
+ const declaration = (node)=>binding(node)?.path.node;
86
+ const imported = (node)=>{
87
+ const value = binding(node);
88
+ const decl = value?.path.node;
89
+ if (!decl || !__rspack_external__babel_types_6e8337dd.isImportSpecifier(decl) && !__rspack_external__babel_types_6e8337dd.isImportNamespaceSpecifier(decl) || __rspack_external__babel_types_6e8337dd.isImportSpecifier(decl) && 'type' === decl.importKind) return;
90
+ const statement = value.path.parent;
91
+ if (!__rspack_external__babel_types_6e8337dd.isImportDeclaration(statement) || 'type' === statement.importKind) return;
92
+ return {
93
+ namespace: __rspack_external__babel_types_6e8337dd.isImportNamespaceSpecifier(decl),
94
+ name: __rspack_external__babel_types_6e8337dd.isImportNamespaceSpecifier(decl) ? '*' : __rspack_external__babel_types_6e8337dd.isIdentifier(decl.imported) ? decl.imported.name : decl.imported.value,
95
+ specifier: statement.source.value
96
+ };
97
+ };
98
+ const namespaceSources = {
99
+ HttpApi: [
100
+ edge,
101
+ 'effect/unstable/httpapi'
102
+ ],
103
+ HttpApiBuilder: [
104
+ edge,
105
+ 'effect/unstable/httpapi'
106
+ ],
107
+ HttpRouter: [
108
+ edge,
109
+ 'effect/unstable/http'
110
+ ]
111
+ };
112
+ const native = (node, name, sources)=>{
113
+ const value = imported(node);
114
+ if (!value) return false;
115
+ const importedNameMatches = value.namespace ? value.specifier === `effect/${name}` : value.name === name && value.specifier !== `effect/${name}`;
116
+ return importedNameMatches && (sources ?? namespaceSources[name] ?? [
117
+ edge
118
+ ]).includes(value.specifier);
119
+ };
120
+ const method = (node, namespace, member, sources)=>{
121
+ node = unwrap(node);
122
+ return __rspack_external__babel_types_6e8337dd.isMemberExpression(node) && !node.computed && __rspack_external__babel_types_6e8337dd.isIdentifier(node.property, {
123
+ name: member
124
+ }) && native(node.object, namespace, sources);
125
+ };
126
+ const initialized = (node)=>{
127
+ const value = binding(node);
128
+ return value?.kind === 'const' && __rspack_external__babel_types_6e8337dd.isVariableDeclarator(value.path.node) ? value.path.node.init ?? void 0 : void 0;
129
+ };
130
+ const moduleFor = (node)=>{
131
+ const value = imported(node);
132
+ if (!value) return;
133
+ const input = owners.get(node)?.resolveImport?.(value.specifier);
134
+ return input ? {
135
+ module: load(input),
136
+ name: value.name
137
+ } : void 0;
138
+ };
139
+ const exported = (module, name)=>{
140
+ for (const statement of module.file.program.body)if (__rspack_external__babel_types_6e8337dd.isExportNamedDeclaration(statement) && 'type' !== statement.exportKind) {
141
+ if (__rspack_external__babel_types_6e8337dd.isVariableDeclaration(statement.declaration)) {
142
+ for (const decl of statement.declaration.declarations)if (__rspack_external__babel_types_6e8337dd.isIdentifier(decl.id, {
143
+ name
144
+ })) return decl.id;
145
+ }
146
+ if (!statement.source) {
147
+ const specifier = statement.specifiers.find((element)=>__rspack_external__babel_types_6e8337dd.isExportSpecifier(element) && 'type' !== element.exportKind && (__rspack_external__babel_types_6e8337dd.isIdentifier(element.exported) ? element.exported.name : element.exported.value) === name);
148
+ if (__rspack_external__babel_types_6e8337dd.isExportSpecifier(specifier)) return specifier.local;
149
+ }
150
+ }
151
+ };
152
+ const externalValue = (node)=>{
153
+ const value = moduleFor(node);
154
+ return value ? exported(value.module, value.name) : void 0;
155
+ };
156
+ const apiIdentity = (node, seen = new Set())=>{
157
+ node = unwrap(node);
158
+ if (seen.has(node)) return;
159
+ seen.add(node);
160
+ const value = imported(node);
161
+ if (value) {
162
+ if (!value.specifier.startsWith('.')) return;
163
+ const module = moduleFor(node);
164
+ const exportedValue = module && exported(module.module, module.name);
165
+ if (exportedValue) return apiIdentity(exportedValue, seen);
166
+ if (module && /(?:^|\/)shared\/(?:api|rpc)\.ts$/u.test(value.specifier)) return `${module.module.id}:import:${value.name}`;
167
+ if (!owners.get(node)?.resolveImport && /(?:^|\/)shared\/(?:api|rpc)\.ts$/u.test(value.specifier)) return `${value.specifier}:${value.name}`;
168
+ return;
169
+ }
170
+ const init = initialized(node);
171
+ if (init && __rspack_external__babel_types_6e8337dd.isIdentifier(unwrap(init))) return apiIdentity(init, seen);
172
+ const valueBinding = binding(node);
173
+ return valueBinding ? `${owners.get(valueBinding.path.node)?.id}:${valueBinding.identifier.start}` : void 0;
174
+ };
175
+ const properties = (node)=>{
176
+ node = unwrap(node);
177
+ if (!__rspack_external__babel_types_6e8337dd.isObjectExpression(node)) return;
178
+ const result = new Map();
179
+ for (const prop of node.properties){
180
+ if (!__rspack_external__babel_types_6e8337dd.isObjectProperty(prop) || prop.computed || !__rspack_external__babel_types_6e8337dd.isIdentifier(prop.key) || result.has(prop.key.name)) return;
181
+ result.set(prop.key.name, prop.value);
182
+ }
183
+ return result;
184
+ };
185
+ const active = new Set();
186
+ const guarded = (node, check)=>{
187
+ node = unwrap(node);
188
+ if (active.has(node) || active.size > 128) return false;
189
+ active.add(node);
190
+ try {
191
+ return check(node);
192
+ } finally{
193
+ active.delete(node);
194
+ }
195
+ };
196
+ const layerSources = [
197
+ edge,
198
+ 'effect',
199
+ 'effect/Layer'
200
+ ];
201
+ const returned = (body)=>{
202
+ if (!__rspack_external__babel_types_6e8337dd.isBlockStatement(body)) return body;
203
+ const statements = body.body;
204
+ const last = statements.at(-1);
205
+ return statements.slice(0, -1).every((statement)=>__rspack_external__babel_types_6e8337dd.isVariableDeclaration(statement) || __rspack_external__babel_types_6e8337dd.isTSTypeAliasDeclaration(statement) || __rspack_external__babel_types_6e8337dd.isTSInterfaceDeclaration(statement)) && __rspack_external__babel_types_6e8337dd.isReturnStatement(last) ? last.argument : void 0;
206
+ };
207
+ const pipe = (node, check)=>__rspack_external__babel_types_6e8337dd.isMemberExpression(node.callee) && !node.callee.computed && __rspack_external__babel_types_6e8337dd.isIdentifier(node.callee.property, {
208
+ name: 'pipe'
209
+ }) && check(node.callee.object) && node.arguments.every((argument)=>method(argument, 'Layer', 'orDie', layerSources) || __rspack_external__babel_types_6e8337dd.isCallExpression(argument) && method(argument.callee, 'Layer', 'provide', layerSources) && argument.arguments.length > 0);
210
+ const handled = (node)=>{
211
+ node = unwrap(node);
212
+ if (!__rspack_external__babel_types_6e8337dd.isArrowFunctionExpression(node) && !__rspack_external__babel_types_6e8337dd.isFunctionExpression(node)) return false;
213
+ const parameter = node.params[0];
214
+ if (!__rspack_external__babel_types_6e8337dd.isIdentifier(parameter)) return false;
215
+ const body = returned(node.body);
216
+ const chain = (value, count = 0)=>{
217
+ value = unwrap(value);
218
+ if (__rspack_external__babel_types_6e8337dd.isIdentifier(value)) return count > 0 && declaration(value) === parameter;
219
+ return __rspack_external__babel_types_6e8337dd.isCallExpression(value) && __rspack_external__babel_types_6e8337dd.isMemberExpression(value.callee) && !value.callee.computed && __rspack_external__babel_types_6e8337dd.isIdentifier(value.callee.property) && [
220
+ 'handle',
221
+ 'handleRaw'
222
+ ].includes(value.callee.property.name) && 2 === value.arguments.length && chain(value.callee.object, count + 1);
223
+ };
224
+ return !!body && chain(body);
225
+ };
226
+ const handlers = (node, api)=>guarded(node, (node)=>{
227
+ const init = initialized(node) ?? externalValue(node);
228
+ if (init) return handlers(init, api);
229
+ if (!__rspack_external__babel_types_6e8337dd.isCallExpression(node)) return false;
230
+ if (pipe(node, (value)=>handlers(value, api))) return true;
231
+ if (method(node.callee, 'Layer', 'mergeAll', layerSources)) return node.arguments.length > 0 && node.arguments.every((argument)=>handlers(argument, api));
232
+ return method(node.callee, 'HttpApiBuilder', 'group') && 3 === node.arguments.length && apiIdentity(node.arguments[0]) === api && handled(node.arguments[2]);
233
+ });
234
+ const transport = (node)=>guarded(node, (node)=>{
235
+ const init = initialized(node);
236
+ if (init) return transport(init);
237
+ if (!__rspack_external__babel_types_6e8337dd.isCallExpression(node)) return method(node, 'Layer', 'empty', layerSources);
238
+ return pipe(node, transport) || method(node.callee, 'HttpRouter', 'cors') || method(node.callee, 'Layer', 'mergeAll', layerSources) && node.arguments.length > 0 && node.arguments.every(transport);
239
+ });
240
+ const directLayer = (node, api)=>guarded(node, (node)=>{
241
+ const init = initialized(node);
242
+ if (init) return directLayer(init, api);
243
+ if (!__rspack_external__babel_types_6e8337dd.isCallExpression(node) || !__rspack_external__babel_types_6e8337dd.isMemberExpression(node.callee) || node.callee.computed || !__rspack_external__babel_types_6e8337dd.isIdentifier(node.callee.property, {
244
+ name: 'pipe'
245
+ })) return false;
246
+ const base = unwrap(node.callee.object);
247
+ return __rspack_external__babel_types_6e8337dd.isCallExpression(base) && method(base.callee, 'HttpApiBuilder', 'layer') && 1 === base.arguments.length && apiIdentity(base.arguments[0]) === api && node.arguments.length > 0 && node.arguments.every((argument)=>__rspack_external__babel_types_6e8337dd.isCallExpression(argument) && method(argument.callee, 'Layer', 'provide', layerSources) && 1 === argument.arguments.length && handlers(argument.arguments[0], api));
248
+ });
249
+ const rpc = (values)=>{
250
+ const api = values.get('api');
251
+ const apiLayer = values.get('layer');
252
+ const apiInit = api && (initialized(api) ?? unwrap(api));
253
+ if (!apiInit || !__rspack_external__babel_types_6e8337dd.isCallExpression(apiInit) || !method(apiInit.callee, 'HttpApi', 'make') || 1 !== apiInit.arguments.length || !apiLayer || !transport(apiLayer)) return false;
254
+ const config = values.get('rpc');
255
+ const fields = config && properties(config);
256
+ const route = fields?.get('path');
257
+ const serialization = fields?.get('serialization');
258
+ if (!__rspack_external__babel_types_6e8337dd.isStringLiteral(route, {
259
+ value: '/rpc'
260
+ }) || !__rspack_external__babel_types_6e8337dd.isStringLiteral(serialization, {
261
+ value: 'json'
262
+ })) return false;
263
+ const group = fields?.get('group');
264
+ const layer = fields?.get('layer');
265
+ const value = group && imported(group);
266
+ if (!group || !layer || value?.specifier !== '../shared/rpc.ts') return false;
267
+ const groupValue = externalValue(group);
268
+ const groupInit = groupValue && initialized(groupValue);
269
+ if (!groupInit || !__rspack_external__babel_types_6e8337dd.isCallExpression(groupInit) || !method(groupInit.callee, 'RpcGroup', 'make', [
270
+ 'effect/unstable/rpc',
271
+ '@modern-js/bff-effect/effect-client'
272
+ ])) return false;
273
+ const layerInit = initialized(layer) ?? unwrap(layer);
274
+ if (!__rspack_external__babel_types_6e8337dd.isCallExpression(layerInit) || !__rspack_external__babel_types_6e8337dd.isMemberExpression(layerInit.callee) || layerInit.callee.computed || !__rspack_external__babel_types_6e8337dd.isIdentifier(layerInit.callee.property, {
275
+ name: 'toLayer'
276
+ }) || apiIdentity(layerInit.callee.object) !== apiIdentity(group) || 1 !== layerInit.arguments.length) return false;
277
+ const implementation = unwrap(layerInit.arguments[0]);
278
+ if (!__rspack_external__babel_types_6e8337dd.isCallExpression(implementation) || !__rspack_external__babel_types_6e8337dd.isMemberExpression(implementation.callee) || implementation.callee.computed || !__rspack_external__babel_types_6e8337dd.isIdentifier(implementation.callee.property, {
279
+ name: 'of'
280
+ }) || apiIdentity(implementation.callee.object) !== apiIdentity(group) || 1 !== implementation.arguments.length) return false;
281
+ const entries = properties(implementation.arguments[0]);
282
+ return !!entries?.size && [
283
+ ...entries.values()
284
+ ].every((value)=>__rspack_external__babel_types_6e8337dd.isArrowFunctionExpression(value) || __rspack_external__babel_types_6e8337dd.isFunctionExpression(value));
285
+ };
286
+ const runtime = (node)=>guarded(node, (node)=>{
287
+ const init = initialized(node);
288
+ if (init) return runtime(init);
289
+ if (!__rspack_external__babel_types_6e8337dd.isCallExpression(node)) return false;
290
+ const value = imported(node.callee);
291
+ if (value?.name === 'defineEffectBff' && [
292
+ edge,
293
+ nodeRuntime
294
+ ].includes(value.specifier) || value?.name === 'assembleEffectBffRuntime' && value.specifier === assembly) {
295
+ if (1 !== node.arguments.length) return false;
296
+ const values = properties(node.arguments[0]);
297
+ if (!values) return false;
298
+ if ('defineEffectBff' === value.name && values.has('rpc')) return rpc(values);
299
+ const api = values.get('api');
300
+ const apiBinding = api && imported(api);
301
+ if (!api || apiBinding?.specifier !== '../shared/api.ts') return false;
302
+ const identity = apiIdentity(api);
303
+ if (!identity) return false;
304
+ const layer = values.get('defineEffectBff' === value.name ? 'layer' : 'handlers');
305
+ const extra = values.get('transport');
306
+ return void 0 !== layer && ('defineEffectBff' === value.name ? directLayer(layer, identity) : handlers(layer, identity)) && (!extra || transport(extra));
307
+ }
308
+ const decl = declaration(node.callee);
309
+ const factory = decl && __rspack_external__babel_types_6e8337dd.isFunctionDeclaration(decl) ? decl : initialized(node.callee);
310
+ if (!factory || !__rspack_external__babel_types_6e8337dd.isFunctionDeclaration(factory) && !__rspack_external__babel_types_6e8337dd.isArrowFunctionExpression(factory) && !__rspack_external__babel_types_6e8337dd.isFunctionExpression(factory) || !factory.body) return false;
311
+ const result = returned(factory.body);
312
+ return !!result && runtime(result);
313
+ });
314
+ const root = entry.file.program.body.find((statement)=>__rspack_external__babel_types_6e8337dd.isExportDefaultDeclaration(statement));
315
+ return root && runtime(root.declaration) ? void 0 : failure;
316
+ } catch (cause) {
317
+ if (cause instanceof SourceSyntaxError) return failure;
318
+ const message = 'object' == typeof cause && null !== cause && 'message' in cause && 'string' == typeof cause.message ? cause.message : String(cause);
319
+ throw new Error(`Strict Effect API analysis failed: ${message}`, {
320
+ cause
321
+ });
322
+ }
323
+ }
324
+ export { createEffectApiImportResolver, strictEffectRuntimeTopologyViolation };
@@ -0,0 +1,53 @@
1
+ import "node:module";
2
+ import node_path from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ import { checkMicroVerticalApiBoundaries, checkMicroVerticalApiConsumerFiles } from "../microvertical-api-boundary.js";
5
+ const flags = [
6
+ '--workspace-root',
7
+ '--baseline-package-directory',
8
+ '--rules'
9
+ ];
10
+ async function loadContractRules(file) {
11
+ const rules = (await import(pathToFileURL(node_path.resolve(file)).href)).default;
12
+ if (!Array.isArray(rules) || !rules.every((rule)=>'function' == typeof rule)) throw new Error(`${file}: default export must be an array of contract rule functions, e.g. \`export default [myRule]\``);
13
+ return rules;
14
+ }
15
+ async function runMicroVerticalApiCheckCli(args = process.argv.slice(2), filesOnly = false) {
16
+ let workspaceRoot = process.env.ULTRAMODERN_WORKSPACE_ROOT ?? process.cwd();
17
+ let baselinePackageDirectory;
18
+ const ruleFiles = [];
19
+ for(let index = 0; index < args.length; index += 1){
20
+ const argument = args[index];
21
+ if ('--help' === argument || '-h' === argument) {
22
+ console.log(`${filesOnly ? 'modern-api-check-files' : 'modern-api-check'} [--workspace-root <path>] [--baseline-package-directory <path>] [--rules <module>]...\n${filesOnly ? 'Checks consumer files, contracts, package exports and owner identity. Does not analyze runtime topology; run the strict Effect source phase separately.' : 'Checks consumer files, contracts, package exports, owner identity and runtime topology once per API entry.'}\n--rules loads a module whose default export is an array of contract rules; each rule receives the module graph of every API contract.\nWorkspace defaults to ULTRAMODERN_WORKSPACE_ROOT then cwd. Exit codes: 0 valid, 1 consumer violation, 2 tool/configuration failure.`);
23
+ return 0;
24
+ }
25
+ if (!flags.includes(argument ?? '') || !args[index + 1] || args[index + 1]?.startsWith('--')) {
26
+ console.error(`Invalid argument: ${argument ?? ''}. Use --help.`);
27
+ return 2;
28
+ }
29
+ const value = args[++index];
30
+ if ('--workspace-root' === argument) workspaceRoot = value;
31
+ else if ('--rules' === argument) ruleFiles.push(value);
32
+ else baselinePackageDirectory = value;
33
+ }
34
+ const contractRules = [];
35
+ for (const file of ruleFiles)try {
36
+ contractRules.push(...await loadContractRules(file));
37
+ } catch (error) {
38
+ console.error(`API tool error: --rules ${error instanceof Error ? error.message : String(error)}`);
39
+ return 2;
40
+ }
41
+ const result = (filesOnly ? checkMicroVerticalApiConsumerFiles : checkMicroVerticalApiBoundaries)({
42
+ workspaceRoot,
43
+ baselinePackageDirectory,
44
+ contractRules
45
+ });
46
+ for (const diagnostic of result.diagnostics)console.error(`API violation: ${diagnostic}`);
47
+ for (const error of result.toolErrors)console.error(`API tool error: ${error}`);
48
+ if (result.toolErrors.length) return 2;
49
+ if (result.diagnostics.length) return 1;
50
+ console.log(`UltraModern API ${filesOnly ? 'consumer files' : 'boundary'} check passed.`);
51
+ return 0;
52
+ }
53
+ export { runMicroVerticalApiCheckCli };
@@ -4,7 +4,7 @@ import node_fs from "node:fs";
4
4
  import { createRequire } from "node:module";
5
5
  import node_os from "node:os";
6
6
  import node_path from "node:path";
7
- import { fileURLToPath } from "node:url";
7
+ import { fileURLToPath, pathToFileURL } from "node:url";
8
8
  const oxlint_require = createRequire(import.meta.url);
9
9
  const ignoredDirectories = new Set([
10
10
  '.modern',
@@ -74,22 +74,26 @@ const runOxlintRules = ({ cwd, targets, rules })=>{
74
74
  stdout: '',
75
75
  stderr: ''
76
76
  };
77
+ const pluginPath = resolvePluginPath();
77
78
  const tempDir = node_fs.mkdtempSync(node_path.join(node_os.tmpdir(), 'modern-code-tools-oxlint-'));
78
79
  const configPath = node_path.join(tempDir, 'oxlint.config.mjs');
79
- const pluginPath = resolvePluginPath();
80
- node_fs.writeFileSync(configPath, `export default {
81
- jsPlugins: [${JSON.stringify(pluginPath)}],
80
+ const adapterPath = node_path.join(tempDir, 'oxlint-plugin.mjs');
81
+ try {
82
+ node_fs.writeFileSync(adapterPath, `import plugin from ${JSON.stringify(pathToFileURL(pluginPath).href)};
83
+ export default plugin.rules ? plugin : plugin.default;
84
+ `, 'utf-8');
85
+ node_fs.writeFileSync(configPath, `export default {
86
+ jsPlugins: [${JSON.stringify(adapterPath)}],
82
87
  rules: ${JSON.stringify(rules, null, 2)}
83
88
  };
84
89
  `, 'utf-8');
85
- try {
86
90
  const result = spawnSync(process.execPath, [
87
91
  resolveOxlintBin(),
88
92
  ...resolvedTargets,
89
93
  '--config',
90
94
  configPath,
91
95
  '--format',
92
- 'unix',
96
+ 'default',
93
97
  '--quiet'
94
98
  ], {
95
99
  cwd,
@@ -7,6 +7,11 @@ const DEFAULT_LOCALES = [
7
7
  'en',
8
8
  'cs'
9
9
  ];
10
+ const DEFAULT_SOURCE_ROOTS = [
11
+ 'apps',
12
+ 'verticals',
13
+ 'packages'
14
+ ];
10
15
  const ignoredDirectories = new Set([
11
16
  '.modern',
12
17
  '.modernjs',
@@ -40,6 +45,8 @@ const createLocaleJsonMatcher = (locales)=>{
40
45
  const resolvePluralCategories = (locale, overrides)=>overrides?.[locale] ?? new Intl.PluralRules(locale).resolvedOptions().pluralCategories;
41
46
  const readText = (filePath)=>node_fs.readFileSync(filePath, 'utf-8');
42
47
  const localeImportPattern = (locale)=>new RegExp(`import\\s+(?:\\*\\s+as\\s+)?[A-Za-z_$][\\w$]*\\s+from\\s+['"]\\.\\./locales/${escapeRegExp(locale)}/[^'"]+\\.json['"]`, 'u');
48
+ class SourceViolation extends Error {
49
+ }
43
50
  const checkRuntimeResources = (root, filePath, text, locales)=>{
44
51
  const relative = relativePath(root, filePath);
45
52
  if (!relative.endsWith('/src/modern.runtime.ts')) return;
@@ -47,7 +54,7 @@ const checkRuntimeResources = (root, filePath, text, locales)=>{
47
54
  const registersResources = /initOptions\s*:\s*\{[\s\S]*?\bresources\s*[,:}]/u.test(text);
48
55
  if (missingLocales.length > 0 || !registersResources) {
49
56
  const detail = missingLocales.length > 0 ? `missing locale JSON imports for: ${missingLocales.join(', ')}` : 'initOptions does not register a `resources` entry';
50
- throw new Error(`${relative} must register locale JSON resources in modern.runtime.ts so Worker SSR and hydration use the same first-render translations (${detail}).`);
57
+ throw new SourceViolation(`${relative} must register locale JSON resources in modern.runtime.ts so Worker SSR and hydration use the same first-render translations (${detail}).`);
51
58
  }
52
59
  };
53
60
  const visitLocaleKeys = (value, visitor, pathParts = [])=>{
@@ -67,7 +74,7 @@ const checkPluralResources = (root, filePath, json, requiredSuffixes, pluralSuff
67
74
  visitLocaleKeys(json, (key, value, pathParts)=>{
68
75
  if ('string' != typeof value || !value.includes('{{count}}')) return;
69
76
  const suffixMatch = key.match(pluralSuffixPattern);
70
- if (!suffixMatch) throw new Error(`${relative} key ${pathParts.join('.')} contains {{count}} but is not plural-suffixed.`);
77
+ if (!suffixMatch) throw new SourceViolation(`${relative} key ${pathParts.join('.')} contains {{count}} but is not plural-suffixed.`);
71
78
  const [, base = '', suffix = ''] = suffixMatch;
72
79
  const parentPath = pathParts.slice(0, -1).join('.');
73
80
  const groupKey = `${parentPath}.${base}`;
@@ -75,7 +82,7 @@ const checkPluralResources = (root, filePath, json, requiredSuffixes, pluralSuff
75
82
  existing.add(suffix);
76
83
  groups.set(groupKey, existing);
77
84
  });
78
- for (const [group, suffixes] of groups)for (const suffix of requiredSuffixes)if (!suffixes.has(suffix)) throw new Error(`${relative} plural group ${group} is missing _${suffix}.`);
85
+ for (const [group, suffixes] of groups)for (const suffix of requiredSuffixes)if (!suffixes.has(suffix)) throw new SourceViolation(`${relative} plural group ${group} is missing _${suffix}.`);
79
86
  };
80
87
  const runRuntimeAndLocaleResourceChecks = (root, sourceRoots, locales, pluralCategories)=>{
81
88
  if (0 === locales.length) return;
@@ -97,11 +104,7 @@ const runRuntimeAndLocaleResourceChecks = (root, sourceRoots, locales, pluralCat
97
104
  checkPluralResources(root, filePath, JSON.parse(readText(filePath)), localeCategories.get(language) ?? [], pluralSuffixPattern);
98
105
  }
99
106
  };
100
- const runWorkspaceSourceCheck = ({ cwd = process.cwd(), sourceRoots = [
101
- 'apps',
102
- 'verticals',
103
- 'packages'
104
- ], locales = DEFAULT_LOCALES, pluralCategories } = {})=>{
107
+ const runWorkspaceSourceCheck = ({ cwd = process.cwd(), sourceRoots = DEFAULT_SOURCE_ROOTS, locales = DEFAULT_LOCALES, pluralCategories } = {})=>{
105
108
  const oxlintResult = runOxlintRules({
106
109
  cwd,
107
110
  targets: sourceRoots,
@@ -134,13 +137,83 @@ const runWorkspaceSourceCheck = ({ cwd = process.cwd(), sourceRoots = [
134
137
  try {
135
138
  runRuntimeAndLocaleResourceChecks(cwd, sourceRoots, locales, pluralCategories);
136
139
  } catch (error) {
137
- console.error(error instanceof Error ? error.message : 'UltraModern workspace source checks failed.');
138
- return 1;
140
+ console.error(error instanceof Error ? error.message : String(error));
141
+ return error instanceof SourceViolation ? 1 : 2;
139
142
  }
140
143
  console.log(WORKSPACE_SOURCE_SUCCESS);
141
144
  return 0;
142
145
  };
143
- const main = ()=>{
144
- process.exitCode = runWorkspaceSourceCheck();
146
+ const USAGE = `modern-i18n-check [--workspace-root <path>]
147
+ Runs the UltraModern i18n and boundary source checks for a workspace.
148
+ Workspace defaults to ULTRAMODERN_WORKSPACE_ROOT then cwd. Options come from
149
+ package.json "modernjs.i18nCheck": { sourceRoots, locales, pluralCategories }.
150
+ Exit codes: 0 valid, 1 source violation, 2 tool/configuration failure.`;
151
+ const isStringArray = (value)=>Array.isArray(value) && value.every((entry)=>'string' == typeof entry && entry.length > 0);
152
+ const isLocaleArray = (value)=>{
153
+ if (!isStringArray(value)) return false;
154
+ try {
155
+ Intl.getCanonicalLocales(value);
156
+ return true;
157
+ } catch {
158
+ return false;
159
+ }
160
+ };
161
+ const isRecord = (value)=>'object' == typeof value && null !== value && !Array.isArray(value);
162
+ const isWorkspaceDirectory = (root, entry)=>{
163
+ if (node_path.isAbsolute(entry)) return false;
164
+ const target = node_path.resolve(root, entry);
165
+ if (!node_fs.existsSync(target) || !node_fs.statSync(target).isDirectory()) return false;
166
+ const relative = node_path.relative(node_fs.realpathSync(root), node_fs.realpathSync(target));
167
+ return '' !== relative && '..' !== relative && !relative.startsWith(`..${node_path.sep}`) && !node_path.isAbsolute(relative);
168
+ };
169
+ const CLDR_PLURAL_CATEGORIES = new Set([
170
+ 'zero',
171
+ 'one',
172
+ 'two',
173
+ 'few',
174
+ 'many',
175
+ 'other'
176
+ ]);
177
+ const isPluralCategories = (value)=>isRecord(value) && Object.values(value).every((categories)=>isStringArray(categories) && categories.includes('other') && categories.every((category)=>CLDR_PLURAL_CATEGORIES.has(category)));
178
+ const readWorkspaceCheckOptions = (root)=>{
179
+ const manifestPath = node_path.join(root, 'package.json');
180
+ const modernjs = JSON.parse(readText(manifestPath)).modernjs;
181
+ const config = isRecord(modernjs) && Object.hasOwn(modernjs, 'i18nCheck') ? modernjs.i18nCheck : {};
182
+ const invalid = (field, expected)=>new Error(`${manifestPath} "modernjs.i18nCheck${field}" must be ${expected}.`);
183
+ if (!isRecord(config)) throw invalid('', 'an object');
184
+ const { locales, pluralCategories } = config;
185
+ if (void 0 !== locales && !isLocaleArray(locales)) throw invalid('.locales', 'an array of BCP 47 locale codes');
186
+ if (void 0 !== pluralCategories && !isPluralCategories(pluralCategories)) throw invalid('.pluralCategories', 'an object of locale -> CLDR plural categories including "other"');
187
+ const sourceRoots = Object.hasOwn(config, 'sourceRoots') ? config.sourceRoots : DEFAULT_SOURCE_ROOTS.filter((entry)=>isWorkspaceDirectory(root, entry));
188
+ if (!isStringArray(sourceRoots) || 0 === sourceRoots.length || !sourceRoots.every((entry)=>isWorkspaceDirectory(root, entry))) throw invalid('.sourceRoots', `a non-empty array of existing workspace-relative directories (default: whichever of ${DEFAULT_SOURCE_ROOTS.join(', ')} exist)`);
189
+ return {
190
+ cwd: root,
191
+ sourceRoots,
192
+ locales,
193
+ pluralCategories
194
+ };
195
+ };
196
+ const runWorkspaceSourceCheckCli = (args = process.argv.slice(2))=>{
197
+ let workspaceRoot = process.env.ULTRAMODERN_WORKSPACE_ROOT ?? process.cwd();
198
+ for(let index = 0; index < args.length; index += 1){
199
+ const argument = args[index];
200
+ if ('--help' === argument || '-h' === argument) {
201
+ console.log(USAGE);
202
+ return 0;
203
+ }
204
+ const value = args[index + 1];
205
+ if ('--workspace-root' !== argument || !value || value.startsWith('--')) {
206
+ console.error(`Invalid argument: ${argument ?? ''}. Use --help.`);
207
+ return 2;
208
+ }
209
+ workspaceRoot = value;
210
+ index += 1;
211
+ }
212
+ try {
213
+ return runWorkspaceSourceCheck(readWorkspaceCheckOptions(node_path.resolve(workspaceRoot)));
214
+ } catch (error) {
215
+ console.error(error instanceof Error ? error.message : String(error));
216
+ return 2;
217
+ }
145
218
  };
146
- export { main, runWorkspaceSourceCheck };
219
+ export { runWorkspaceSourceCheck, runWorkspaceSourceCheckCli };