@yearofthedan/warp 0.3.0 → 0.4.1

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 (45) hide show
  1. package/README.md +20 -22
  2. package/dist/app/check.d.ts +3 -1
  3. package/dist/app/check.js +3 -2
  4. package/dist/app/configLines.d.ts +5 -0
  5. package/dist/app/configLines.js +24 -0
  6. package/dist/app/load.d.ts +2 -2
  7. package/dist/app/load.js +32 -44
  8. package/dist/app/unclassified.js +1 -1
  9. package/dist/builtins/advice.js +9 -9
  10. package/dist/builtins/dependency-direction/dependencyDirection.js +7 -2
  11. package/dist/builtins/module-externals/moduleExternals.js +3 -2
  12. package/dist/builtins/unused-declaration/empty.js +11 -10
  13. package/dist/builtins/unused-declaration/grants.js +39 -11
  14. package/dist/builtins/unused-declaration/surfaces.js +16 -6
  15. package/dist/cli.js +37 -17
  16. package/dist/config/loadConfig.d.ts +8 -2
  17. package/dist/config/loadConfig.js +107 -14
  18. package/dist/git/cache.js +5 -1
  19. package/dist/index.d.ts +0 -1
  20. package/dist/index.js +0 -1
  21. package/dist/model/archetype/data.d.ts +14 -23
  22. package/dist/model/archetype/data.js +1 -1
  23. package/dist/model/archetype/fixes.d.ts +5 -7
  24. package/dist/model/archetype/fixes.js +132 -90
  25. package/dist/model/archetype/language.d.ts +16 -0
  26. package/dist/model/archetype/language.js +432 -0
  27. package/dist/model/archetype/reach.d.ts +8 -3
  28. package/dist/model/archetype/reach.js +122 -56
  29. package/dist/model/archetype/references.d.ts +11 -5
  30. package/dist/model/archetype/references.js +59 -118
  31. package/dist/model/archetype/requirements.d.ts +3 -3
  32. package/dist/model/archetype/requirements.js +75 -58
  33. package/dist/model/archetype/resolve.d.ts +1 -0
  34. package/dist/model/archetype/resolve.js +26 -56
  35. package/dist/model/archetype/rulesets.d.ts +2 -1
  36. package/dist/model/archetype/rulesets.js +74 -43
  37. package/dist/model/archetype/settings.d.ts +1 -0
  38. package/dist/model/archetype/settings.js +5 -0
  39. package/dist/reporters/model.js +4 -3
  40. package/dist/rules/registry.js +2 -2
  41. package/package.json +4 -2
  42. package/dist/model/archetype/builder.d.ts +0 -183
  43. package/dist/model/archetype/builder.js +0 -78
  44. package/dist/model/archetype/draft.d.ts +0 -30
  45. package/dist/model/archetype/draft.js +0 -264
@@ -1,7 +1,13 @@
1
- export declare const configNames: string[];
2
- export declare const findConfig: (dir: string) => string;
1
+ export declare const configName = "warp.yaml";
2
+ export declare const findConfig: (start: string, exists?: (path: string) => boolean) => string;
3
3
  export interface LoadedConfig {
4
4
  raw: unknown;
5
+ plugins: Record<string, unknown>;
6
+ lines: ReadonlyMap<string, number>;
5
7
  digest: string;
6
8
  }
9
+ export declare const parseConfig: (text: string, file: string) => {
10
+ raw: unknown;
11
+ lines: Map<string, number>;
12
+ };
7
13
  export declare const loadConfig: (file: string) => Promise<LoadedConfig>;
@@ -16,22 +16,96 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
16
16
  return path;
17
17
  };
18
18
  import { createHash } from 'node:crypto';
19
- import { existsSync } from 'node:fs';
20
- import { registerHooks } from 'node:module';
21
- import { join } from 'node:path';
19
+ import { existsSync, readFileSync } from 'node:fs';
20
+ import { createRequire, registerHooks } from 'node:module';
21
+ import { basename, dirname, join, resolve } from 'node:path';
22
22
  import { pathToFileURL } from 'node:url';
23
+ import { isAlias, isMap, isNode, isPair, isScalar, parseDocument, visit } from 'yaml';
23
24
  import { ConfigError } from '../model/configError.js';
24
- export const configNames = ['warp.config.ts', 'warp.config.mts', 'warp.config.js', 'warp.config.mjs'];
25
- export const findConfig = (dir) => {
26
- const found = configNames.map((name) => join(dir, name)).find((file) => existsSync(file));
27
- if (!found)
28
- throw new ConfigError(`no config in ${dir}: add one of ${configNames.join(', ')}`);
29
- return found;
25
+ export const configName = 'warp.yaml';
26
+ export const findConfig = (start, exists = existsSync) => {
27
+ for (let dir = start;; dir = dirname(dir)) {
28
+ const found = join(dir, configName);
29
+ if (exists(found))
30
+ return found;
31
+ if (dirname(dir) === dir)
32
+ throw new ConfigError(`no ${configName} in ${start} or any folder above it`);
33
+ }
34
+ };
35
+ export const parseConfig = (text, file) => {
36
+ const doc = parseDocument(text, { version: '1.2', merge: false, uniqueKeys: true });
37
+ const lineOf = (offset) => text.slice(0, offset).split('\n').length;
38
+ const unquoted = doc.errors.filter((error) => error.code === 'BAD_ALIAS' && text[error.pos[0]] === '*');
39
+ const problems = [
40
+ ...doc.errors.map((error) => `${file}:${lineOf(error.pos[0])}: ${yamlProblem(error, text, unquoted)}`),
41
+ ...anchors(doc)
42
+ .filter((offset) => !unquoted.some((error) => error.pos[0] === offset))
43
+ .map((offset) => `${file}:${lineOf(offset)}: anchors and aliases are not part of warp.yaml; write it out`),
44
+ ];
45
+ if (problems.length > 0)
46
+ throw new ConfigError(problems.join('\n'));
47
+ const lines = new Map();
48
+ const walk = (node, at) => {
49
+ if (!isMap(node))
50
+ return;
51
+ for (const pair of node.items.filter(isPair)) {
52
+ if (!isScalar(pair.key))
53
+ continue;
54
+ const place = at(String(pair.key.value));
55
+ if (place.path !== undefined)
56
+ lines.set(place.path, lineOf(pair.key.range?.[0] ?? 0));
57
+ walk(pair.value, place.inside);
58
+ }
59
+ };
60
+ walk(doc.contents, top);
61
+ return { raw: doc.toJS() ?? {}, lines };
62
+ };
63
+ const yamlProblem = (error, text, unquoted) => {
64
+ if (unquoted.includes(error))
65
+ return "a value that starts with * is quoted, '*'";
66
+ if (error.code !== 'DUPLICATE_KEY')
67
+ return firstLine(error.message);
68
+ return `${firstLine(error.message)} (${/^['"]?([^'":\n]*)/.exec(text.slice(error.pos[0]))[1]})`;
69
+ };
70
+ const firstLine = (message) => message.split('\n')[0].replace(/ at line \d+, column \d+:?$/, '');
71
+ const anchors = (doc) => {
72
+ const offsets = [];
73
+ visit(doc, {
74
+ Node: (_, node) => {
75
+ if (isAlias(node) || (isNode(node) && node.anchor))
76
+ offsets.push(node.range?.[0] ?? 0);
77
+ },
78
+ });
79
+ return offsets;
80
+ };
81
+ const plain = (path) => (key) => ({ path: `${path}.${key}`, inside: plain(`${path}.${key}`) });
82
+ const moduleAt = (path) => ({ path, inside: moduleKey(path) });
83
+ const moduleKey = (path) => (key) => {
84
+ if (key === 'modules')
85
+ return { path: `${path}.modules`, inside: (child) => moduleAt(`${path}.${child}`) };
86
+ if (key === 'test')
87
+ return { path: `${path}.test`, inside: testKey(path) };
88
+ return plain(path)(key);
89
+ };
90
+ const testKey = (path) => (key) => key === 'modules'
91
+ ? { path: `${path}.test.modules`, inside: (child) => moduleAt(`${path}.${child}`) }
92
+ : plain(`${path}.test`)(key);
93
+ const top = (key) => {
94
+ if (key === 'root')
95
+ return moduleAt('root');
96
+ if (key === 'archetypes')
97
+ return { inside: moduleAt };
98
+ return { path: key, inside: plain(key) };
30
99
  };
31
100
  const entry = new URL(import.meta.url.endsWith('.ts') ? '../index.ts' : '../index.js', import.meta.url).href;
32
101
  const ownFiles = new URL('../../', import.meta.url).href;
33
102
  export const loadConfig = async (file) => {
34
- const digest = createHash('sha256');
103
+ const text = readFileSync(file, 'utf8');
104
+ const digest = createHash('sha256').update(text);
105
+ const name = basename(file);
106
+ const { raw, lines } = parseConfig(text, name);
107
+ const declared = raw.plugins;
108
+ const specs = declared && typeof declared === 'object' && !Array.isArray(declared) ? Object.entries(declared) : [];
35
109
  const hooks = registerHooks({
36
110
  resolve: (specifier, context, nextResolve) => specifier === '@yearofthedan/warp' ? { url: entry, shortCircuit: true } : nextResolve(specifier, context),
37
111
  load: (url, context, nextLoad) => {
@@ -42,12 +116,31 @@ export const loadConfig = async (file) => {
42
116
  },
43
117
  });
44
118
  try {
45
- const module = await import(__rewriteRelativeImportExtension(pathToFileURL(file).href));
46
- if (module.default === undefined)
47
- throw new ConfigError(`${file}: expected the config as its default export`);
48
- return { raw: module.default, digest: digest.digest('hex') };
119
+ const plugins = {};
120
+ for (const [namespace, spec] of specs) {
121
+ if (typeof spec !== 'string')
122
+ continue;
123
+ plugins[namespace] = await importPlugin(file, spec, `${name}:${lines.get(`plugins.${namespace}`) ?? 1}: plugins.${namespace}`);
124
+ }
125
+ return { raw, plugins, lines, digest: digest.digest('hex') };
49
126
  }
50
127
  finally {
51
128
  hooks.deregister();
52
129
  }
53
130
  };
131
+ const importPlugin = async (file, spec, at) => {
132
+ const path = pluginPath(file, spec, at);
133
+ if (!spec.startsWith('npm:') && !existsSync(path))
134
+ throw new ConfigError(`${at}: no file at ${spec}`);
135
+ const module = await import(__rewriteRelativeImportExtension(pathToFileURL(path).href));
136
+ if (module.default === undefined)
137
+ throw new ConfigError(`${at}: ${spec} has no default export; export the plugin as default`);
138
+ return module.default;
139
+ };
140
+ const pluginPath = (file, spec, at) => {
141
+ if (spec.startsWith('npm:'))
142
+ return createRequire(file).resolve(spec.slice(4));
143
+ if (spec.startsWith('./') || spec.startsWith('../'))
144
+ return resolve(dirname(file), spec);
145
+ throw new ConfigError(`${at}: '${spec}' is a path, ./${spec}, or a package, npm:${spec}`);
146
+ };
package/dist/git/cache.js CHANGED
@@ -3,7 +3,11 @@ import { mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, uti
3
3
  import { join, resolve } from 'node:path';
4
4
  export const maxAgeMs = 30 * 24 * 60 * 60 * 1000;
5
5
  export const gitDirCache = (projectRoot, now = Date.now) => {
6
- const gitDir = execFileSync('git', ['rev-parse', '--git-common-dir'], { cwd: projectRoot, encoding: 'utf8' }).trim();
6
+ const gitDir = execFileSync('git', ['rev-parse', '--git-common-dir'], {
7
+ cwd: projectRoot,
8
+ encoding: 'utf8',
9
+ stdio: ['ignore', 'pipe', 'pipe'],
10
+ }).trim();
7
11
  const dir = join(resolve(projectRoot, gitDir), 'warp-cache');
8
12
  const file = (key) => join(dir, `${key}.json`);
9
13
  const touch = (key) => {
package/dist/index.d.ts CHANGED
@@ -1,4 +1,3 @@
1
- export { all, archetype, contains, defineConfig, dir, exposes, files, mirror, pkg, ruleset, using, type ModuleHandle, type Selector, type Ruleset, type RuleSettings, type WarpConfig, type All, type Archetype, type Exposed, type Using, type TestUsing, type UsingContext, type Package, type Reference, type Shape, } from './model/archetype/builder.ts';
2
1
  export { loadConfigData, type LoadedConfigData } from './app/load.ts';
3
2
  export type * from './model/archetype/data.ts';
4
3
  export type { Complexity, FunctionFacts, ImportEdge, FileFacts, Member, MemberGraph, MemberKind, } from './model/facts.ts';
package/dist/index.js CHANGED
@@ -1,4 +1,3 @@
1
- export { all, archetype, contains, defineConfig, dir, exposes, files, mirror, pkg, ruleset, using, } from './model/archetype/builder.js';
2
1
  export { loadConfigData } from './app/load.js';
3
2
  export { ConfigError } from './model/configError.js';
4
3
  export { wholeNumberOptions, } from './rules/rule.js';
@@ -2,6 +2,8 @@ export interface ModuleRefData {
2
2
  kind: 'module';
3
3
  module: string;
4
4
  surface?: string;
5
+ up?: number;
6
+ top?: true;
5
7
  }
6
8
  export interface RequiredRefData {
7
9
  kind: 'required';
@@ -24,14 +26,6 @@ export type ExposesData = {
24
26
  kind: 'surfaces';
25
27
  surfaces: Record<string, RefData[]>;
26
28
  };
27
- export type LocatorData = {
28
- kind: 'dir' | 'files';
29
- patterns: string[];
30
- } | {
31
- kind: 'mirror';
32
- from: string;
33
- to: string;
34
- };
35
29
  export interface FilesModuleData {
36
30
  kind: 'files';
37
31
  name: string;
@@ -48,14 +42,18 @@ export interface DirModuleData {
48
42
  name: string;
49
43
  paths: string[];
50
44
  archetype: string;
45
+ test?: true;
51
46
  using: RefData[];
47
+ inputs?: Record<string, RefData>;
48
+ testInputs?: Record<string, RefData>;
52
49
  rules?: RuleSettingsData;
53
50
  description?: string;
54
51
  }
55
52
  export interface TestModuleData {
56
53
  kind: 'test';
57
54
  name: string;
58
- locator: LocatorData;
55
+ patterns: string[];
56
+ of?: string;
59
57
  using: RefData[];
60
58
  exposes?: Exclude<ExposesData, {
61
59
  kind: 'surfaces';
@@ -64,28 +62,21 @@ export interface TestModuleData {
64
62
  description?: string;
65
63
  }
66
64
  export type ModuleData = FilesModuleData | DirModuleData | TestModuleData;
67
- export type RequirementData = {
68
- kind: 'archetype';
69
- archetype: string;
70
- } | {
71
- kind: 'dir';
72
- } | {
73
- kind: 'files';
74
- };
75
- export type IdentifyData = {
65
+ export declare const isTestData: (module: ModuleData) => boolean;
66
+ export interface IdentifyData {
76
67
  marker: string;
77
- } | {
78
- match: (dir: string, chain: readonly unknown[]) => false | Record<string, string>;
79
- };
68
+ }
80
69
  export interface ArchetypeData {
81
70
  name: string;
82
71
  inline?: true;
72
+ test?: true;
83
73
  description?: string;
84
74
  identify?: IdentifyData;
85
- requires: Record<string, RequirementData>;
75
+ requires: string[];
76
+ testRequires?: string[];
86
77
  modules: ModuleData[];
87
78
  exposes?: ExposesData;
88
- provides: Record<string, ModuleRefData>;
79
+ testExposes?: Record<string, RefData[]>;
89
80
  testUsing?: RefData[];
90
81
  rules?: RuleSettingsData;
91
82
  }
@@ -1 +1 @@
1
- export {};
1
+ export const isTestData = (module) => module.kind === 'test' || (module.kind === 'dir' && module.test === true);
@@ -4,7 +4,6 @@ export interface Site {
4
4
  label: string;
5
5
  holder: ModuleView;
6
6
  add(config: ConfigData, ref: RefData): ConfigData;
7
- visible: ReadonlySet<string>;
8
7
  self?: string;
9
8
  tests: boolean;
10
9
  }
@@ -12,21 +11,20 @@ export type Fix = {
12
11
  kind: 'using';
13
12
  site: string;
14
13
  ref: RefData;
15
- } | {
16
- kind: 'declare';
17
- archetype: string;
18
- module: string;
19
- above: string;
20
14
  } | {
21
15
  kind: 'require';
22
16
  archetype: string;
23
17
  name: string;
24
- provider: string;
18
+ sites: string[];
25
19
  module: string;
26
20
  } | {
27
21
  kind: 'expose';
28
22
  archetype: string;
29
23
  ref: RefData;
24
+ } | {
25
+ kind: 'test-expose';
26
+ archetype: string;
27
+ ref: RefData;
30
28
  } | {
31
29
  kind: 'expose-file';
32
30
  archetype: string;
@@ -1,4 +1,4 @@
1
- import { verdicts } from './reach.js';
1
+ import { instanceOf, verdicts } from './reach.js';
2
2
  const ancestors = function* (module) {
3
3
  for (let at = module.parent; at; at = at.parent)
4
4
  yield at;
@@ -16,24 +16,20 @@ const withModule = (config, archetype, name, change) => withArchetype(config, ar
16
16
  const declarationSite = (config, module) => {
17
17
  const holder = module.parent;
18
18
  const archetype = holder.archetype;
19
- const declared = config.archetypes[archetype].modules;
20
- const index = declared.findIndex((data) => data.name === module.name);
21
19
  return {
22
- label: `the using of ${archetype}.${module.name}`,
20
+ label: `${archetype}.${module.name}.dependencies`,
23
21
  holder,
24
22
  add: (from, ref) => withModule(from, archetype, module.name, (data) => ({ ...data, using: [...data.using, ref] })),
25
- visible: new Set(declared.slice(0, index).map((data) => data.name)),
26
23
  self: module.name,
27
- tests: module.kind === 'test',
24
+ tests: module.test === true,
28
25
  };
29
26
  };
30
- const kitSite = (config, at) => {
27
+ const kitSite = (at) => {
31
28
  const archetype = at.archetype;
32
29
  return {
33
- label: `the testUsing of ${archetype}`,
30
+ label: `${archetype}.test.provides`,
34
31
  holder: at,
35
32
  add: (from, ref) => withArchetype(from, archetype, (data) => ({ ...data, testUsing: [...(data.testUsing ?? []), ref] })),
36
- visible: new Set(config.archetypes[archetype].modules.map((data) => data.name)),
37
33
  tests: true,
38
34
  };
39
35
  };
@@ -41,23 +37,36 @@ export const sitesOf = (config, model, file) => {
41
37
  const module = model.moduleOf(file);
42
38
  if (!module || module.looseFiles.includes(file))
43
39
  return [];
44
- if (module.kind === 'test')
45
- return [declarationSite(config, module), ...lineage(module.parent).map((at) => kitSite(config, at))];
46
- const owners = module.kind === 'files' ? [module, module.parent] : [module];
47
- return owners.filter((owner) => owner.parent).map((owner) => declarationSite(config, owner));
48
- };
49
- const surfacesOf = (exposes) => exposes?.kind === 'surfaces' ? Object.keys(exposes.surfaces) : [];
50
- const moduleRefs = (config, module) => {
51
- const surfaces = module.kind === 'dir' ? surfacesOf(config.archetypes[module.archetype].exposes) : [];
40
+ if (module.test)
41
+ return lineage(module).map((at) => (at.test ? declarationSite(config, at) : kitSite(at)));
42
+ return module.parent ? [declarationSite(config, module)] : [];
43
+ };
44
+ const surfacesOf = ({ exposes, testExposes }, tests) => [
45
+ ...new Set([
46
+ ...(exposes?.kind === 'surfaces' ? Object.keys(exposes.surfaces) : []),
47
+ ...(tests ? Object.keys(testExposes ?? {}) : []),
48
+ ]),
49
+ ];
50
+ const moduleRefs = (config, module, tests, up = 0, top = false) => {
51
+ const surfaces = module.kind === 'dir' ? surfacesOf(config.archetypes[module.archetype], tests) : [];
52
52
  const name = module.name;
53
+ const out = { ...(up > 0 ? { up } : {}), ...(top ? { top: true } : {}) };
53
54
  return [
54
- ...surfaces.map((surface) => ({ kind: 'module', module: name, surface })),
55
- { kind: 'module', module: name },
55
+ ...surfaces.map((surface) => ({ kind: 'module', module: name, surface, ...out })),
56
+ { kind: 'module', module: name, ...out },
56
57
  ];
57
58
  };
58
- const requiredRefs = (config, name, requirement) => {
59
- const surfaces = requirement.kind === 'archetype' ? surfacesOf(config.archetypes[requirement.archetype].exposes) : [];
60
- return [...surfaces.map((surface) => ({ kind: 'required', name, surface })), { kind: 'required', name }];
59
+ const levels = (config, holder) => {
60
+ const found = [holder];
61
+ for (let at = holder; config.archetypes[at.archetype].inline && at.parent; at = at.parent)
62
+ found.push(at.parent);
63
+ return found;
64
+ };
65
+ const declares = (config, level, name) => config.archetypes[level.archetype].modules.some((module) => module.name === name);
66
+ const inputsOf = (config, site) => {
67
+ const named = config.archetypes[namedArchetype(config, site.holder.archetype)];
68
+ const names = [...named.requires, ...(site.tests ? (named.testRequires ?? []) : [])];
69
+ return names.map((name) => ({ kind: 'required', name }));
61
70
  };
62
71
  const allowed = ({ model, from, to }, config) => verdicts(config, model).verdict(from, to).allowed;
63
72
  const targetLineage = ({ model, to }) => lineage(model.moduleOf(to));
@@ -66,82 +75,87 @@ const reachable = (search) => {
66
75
  const importer = lineage(search.model.moduleOf(search.from));
67
76
  return targetLineage(search).filter((module) => !importer.some((own) => sameDeclaration(own, module)));
68
77
  };
69
- const nameable = (site, module) => module.parent === site.holder && module.name !== site.self && (site.tests || module.kind !== 'test');
78
+ const nameable = (site, module) => !(module.parent === site.holder && module.name === site.self) && (site.tests || !module.test);
70
79
  const usingChanges = function* (search, config) {
71
80
  const targets = reachable(search);
72
81
  for (const site of sitesOf(config, search.model, search.from)) {
73
- const own = targets.filter((module) => nameable(site, module) && site.visible.has(module.name));
74
- const named = namedArchetype(config, site.holder.archetype);
75
- const required = Object.entries(config.archetypes[named].requires).flatMap(([name, requirement]) => requiredRefs(config, name, requirement));
76
- for (const ref of [...own.flatMap((module) => moduleRefs(config, module)), ...required])
82
+ const scopes = levels(config, site.holder);
83
+ const own = scopes.flatMap((level, up) => targets
84
+ .filter((module) => module.parent === level && nameable(site, module))
85
+ .flatMap((module) => {
86
+ const shadowed = scopes.slice(0, up).some((nearer) => declares(config, nearer, module.name));
87
+ if (!shadowed)
88
+ return moduleRefs(config, module, site.tests, up);
89
+ return up === scopes.length - 1 ? moduleRefs(config, module, site.tests, up, true) : [];
90
+ }));
91
+ for (const ref of [...own, ...inputsOf(config, site)])
77
92
  yield [{ fix: { kind: 'using', site: site.label, ref }, config: site.add(config, ref) }];
78
93
  }
79
94
  };
80
- const declareChanges = function* (search, config) {
81
- const targets = reachable(search);
82
- for (const site of sitesOf(config, search.model, search.from))
83
- for (const module of targets.filter((candidate) => nameable(site, candidate) && !site.visible.has(candidate.name))) {
84
- const declared = declare(config, site, module);
85
- if (!declared)
86
- continue;
87
- for (const ref of moduleRefs(declared.config, module))
88
- yield [declared, { fix: { kind: 'using', site: site.label, ref }, config: site.add(declared.config, ref) }];
89
- }
95
+ const bindingAt = (config, chain, { holder }, name) => {
96
+ for (let key = holder, up = 0;; up += 1) {
97
+ if (config.archetypes[key].modules.some((module) => module.name === name))
98
+ return { kind: 'module', module: name, ...(up > 0 ? { up } : {}) };
99
+ if (!config.archetypes[key].inline)
100
+ break;
101
+ key = key.slice(0, key.lastIndexOf('.'));
102
+ }
103
+ return chain.has(namedArchetype(config, holder)) ? { kind: 'required', name } : undefined;
90
104
  };
91
- const declare = (config, site, module) => {
92
- if (site.self === undefined)
93
- return undefined;
94
- const archetype = site.holder.archetype;
95
- const modules = config.archetypes[archetype].modules;
96
- const moved = modules.find((data) => data.name === module.name);
97
- const sees = moved.using.every((ref) => ref.kind !== 'module' || site.visible.has(ref.module));
98
- if (!sees)
99
- return undefined;
100
- const rest = modules.filter((data) => data !== moved);
101
- const at = rest.findIndex((data) => data.name === site.self);
102
- return {
103
- fix: { kind: 'declare', archetype, module: module.name, above: site.self },
104
- config: withArchetype(config, archetype, (data) => ({
105
- ...data,
106
- modules: [...rest.slice(0, at), moved, ...rest.slice(at)],
107
- })),
108
- };
105
+ const usesOf = (config, archetype) => Object.entries(config.archetypes).flatMap(([holder, data]) => data.modules
106
+ .filter((module) => module.kind === 'dir' && module.archetype === archetype)
107
+ .map((module) => ({ holder, name: module.name })));
108
+ const chainTo = (config, holder, target) => {
109
+ const scope = instanceOf({ config }, target.parent);
110
+ const chain = [];
111
+ for (let instance = instanceOf({ config }, holder); instance.parent; instance = instanceOf({ config }, instance.parent)) {
112
+ if (!chain.includes(instance.archetype))
113
+ chain.push(instance.archetype);
114
+ if (instanceOf({ config }, instance.parent) === scope)
115
+ return chain;
116
+ }
117
+ return undefined;
109
118
  };
110
- const providedEverywhere = (config, model, archetype, name) => model.modules
111
- .filter((module) => module.archetype !== undefined && namedArchetype(config, module.archetype) === archetype)
112
- .every((module) => [...ancestors(module)].some((at) => config.archetypes[at.archetype].provides[name]));
113
119
  const requireChanges = function* (search, config) {
114
- const targets = reachable(search);
120
+ const targets = reachable(search).filter((target) => !target.test);
115
121
  for (const site of sitesOf(config, search.model, search.from))
116
- for (const provider of ancestors(site.holder))
117
- for (const module of targets.filter((target) => target.parent === provider && target.kind !== 'test')) {
118
- const changes = requirement(search, config, site, provider, module);
119
- if (changes)
120
- yield changes;
121
- }
122
- };
123
- const requirement = (search, config, site, provider, module) => {
124
- const archetype = namedArchetype(config, site.holder.archetype);
122
+ for (const module of targets) {
123
+ const chain = chainTo(config, site.holder, module);
124
+ const changes = chain && requirement(config, site, chain, module);
125
+ if (changes)
126
+ yield changes;
127
+ }
128
+ };
129
+ const requirement = (config, site, chain, module) => {
125
130
  const name = module.name;
126
- const providing = config.archetypes[provider.archetype].provides[name];
127
- if (config.archetypes[archetype].requires[name] || (providing && providing.module !== name))
128
- return undefined;
129
- const required = withArchetype(withArchetype(config, archetype, (data) => ({
130
- ...data,
131
- requires: { ...data.requires, [name]: { kind: module.kind === 'dir' ? 'dir' : 'files' } },
132
- })), provider.archetype, (data) => ({ ...data, provides: { ...data.provides, [name]: { kind: 'module', module: name } } }));
133
- if (!providedEverywhere(required, search.model, archetype, name))
131
+ if (config.archetypes[chain[0]].requires.includes(name))
134
132
  return undefined;
133
+ const passing = new Set(chain);
134
+ let required = config;
135
+ const fixes = [];
136
+ for (const archetype of chain.filter((at) => !config.archetypes[at].requires.includes(name))) {
137
+ const uses = usesOf(config, archetype);
138
+ const bindings = uses.map((use) => bindingAt(config, passing, use, name));
139
+ if (bindings.includes(undefined))
140
+ return undefined;
141
+ required = withArchetype(required, archetype, (data) => ({ ...data, requires: [...data.requires, name] }));
142
+ for (const [index, use] of uses.entries())
143
+ required = withModule(required, use.holder, use.name, (declared) => {
144
+ const dir = declared;
145
+ return { ...dir, inputs: { ...dir.inputs, [name]: bindings[index] } };
146
+ });
147
+ const sites = uses.map((use) => `${use.holder}.${use.name}`);
148
+ fixes.push({ fix: { kind: 'require', archetype, name, sites, module: name }, config: required });
149
+ }
135
150
  const ref = { kind: 'required', name };
136
- return [
137
- { fix: { kind: 'require', archetype, name, provider: provider.archetype, module: name }, config: required },
138
- { fix: { kind: 'using', site: site.label, ref }, config: site.add(required, ref) },
139
- ];
151
+ return [...fixes, { fix: { kind: 'using', site: site.label, ref }, config: site.add(required, ref) }];
140
152
  };
141
153
  const relative = (module, file) => module.dir === '' ? file : file.slice(module.dir.length + 1);
142
154
  const exposeChange = (search, config, hiddenBy) => {
143
155
  if (hiddenBy.kind !== 'dir')
144
156
  return exposeFilesModule(search, config, hiddenBy);
157
+ if (search.model.isTest(search.to) && !hiddenBy.test)
158
+ return testExposeChange(search, config, hiddenBy);
145
159
  const archetype = hiddenBy.archetype;
146
160
  const exposes = config.archetypes[archetype].exposes;
147
161
  const child = targetLineage(search).find((module) => module.parent === hiddenBy);
@@ -155,7 +169,7 @@ const exposeChange = (search, config, hiddenBy) => {
155
169
  config: withArchetype(config, archetype, (data) => ({ ...data, exposes: { kind: 'surfaces', surfaces } })),
156
170
  };
157
171
  }
158
- if (exposes?.kind === 'all' || exposes?.entry || child?.kind === 'test')
172
+ if (exposes?.kind === 'all' || exposes?.entry)
159
173
  return undefined;
160
174
  const pattern = relative(hiddenBy, search.to);
161
175
  const opened = { kind: 'files', patterns: [...(exposes?.patterns ?? []), pattern] };
@@ -164,6 +178,19 @@ const exposeChange = (search, config, hiddenBy) => {
164
178
  config: withArchetype(config, archetype, (data) => ({ ...data, exposes: opened })),
165
179
  };
166
180
  };
181
+ const testExposeChange = (search, config, hiddenBy) => {
182
+ const child = targetLineage(search).find((module) => module.parent === hiddenBy);
183
+ if (!child)
184
+ return undefined;
185
+ const archetype = hiddenBy.archetype;
186
+ const ref = { kind: 'module', module: child.name };
187
+ const surfaces = config.archetypes[archetype].testExposes ?? {};
188
+ const testExposes = { ...surfaces, [child.name]: [...(surfaces[child.name] ?? []), ref] };
189
+ return {
190
+ fix: { kind: 'test-expose', archetype, ref },
191
+ config: withArchetype(config, archetype, (data) => ({ ...data, testExposes })),
192
+ };
193
+ };
167
194
  const exposeFilesModule = (search, config, hiddenBy) => {
168
195
  const archetype = hiddenBy.parent.archetype;
169
196
  const declared = config.archetypes[archetype].modules.find((data) => data.name === hiddenBy.name);
@@ -182,13 +209,27 @@ const exposeFilesModule = (search, config, hiddenBy) => {
182
209
  };
183
210
  };
184
211
  const subtree = (module) => [module, ...module.children.flatMap(subtree)];
185
- const reaches = (config, model, from, to) => {
212
+ const uses = (config, model, from, under) => {
186
213
  const judge = verdicts(config, model);
187
- const files = new Set(subtree(to).flatMap((module) => module.files));
188
- return subtree(from).some((module) => {
189
- const file = module.files[0];
190
- return file !== undefined && judge.reach(file).some((grant) => [...grant.files].some((to) => files.has(to)));
191
- });
214
+ const reached = subtree(from).flatMap((module) => module.files.slice(0, 1).flatMap((file) => (judge.reach(file) ?? []).flatMap((grant) => [...grant.files])));
215
+ const found = new Set();
216
+ for (const to of reached) {
217
+ const target = model.moduleOf(to);
218
+ if (target && lineage(target).includes(under))
219
+ found.add(topOf(target, under));
220
+ }
221
+ found.delete(from);
222
+ return found;
223
+ };
224
+ const reaches = (config, model, from, to, under) => {
225
+ const seen = new Set([from]);
226
+ for (const at of seen) {
227
+ if (at === to)
228
+ return true;
229
+ for (const next of uses(config, model, at, under))
230
+ seen.add(next);
231
+ }
232
+ return false;
192
233
  };
193
234
  const topOf = (module, under) => {
194
235
  let at = module;
@@ -204,7 +245,7 @@ const loops = ({ model, from, to }, config) => {
204
245
  const common = [...lineage(source)].find((module) => lineage(target).includes(module));
205
246
  if (!common || common === source || common === target)
206
247
  return false;
207
- return reaches(config, model, topOf(target, common), topOf(source, common));
248
+ return reaches(config, model, topOf(target, common), topOf(source, common), common);
208
249
  };
209
250
  const search = (state, config, fixes) => {
210
251
  const verdict = verdicts(config, state.model).verdict(state.from, state.to);
@@ -214,7 +255,7 @@ const search = (state, config, fixes) => {
214
255
  const change = exposeChange(state, config, verdict.hiddenBy);
215
256
  return change && search(state, change.config, [...fixes, change.fix]);
216
257
  }
217
- for (const candidates of [usingChanges, declareChanges, requireChanges])
258
+ for (const candidates of [usingChanges, requireChanges])
218
259
  for (const changes of candidates(state, config)) {
219
260
  const changed = changes.at(-1).config;
220
261
  if (allowed(state, changed) && !loops(state, changed))
@@ -227,8 +268,9 @@ const search = (state, config, fixes) => {
227
268
  const hiddenOnTheWay = ({ model, from, to }, config) => {
228
269
  const judge = verdicts(config, model);
229
270
  const above = lineage(model.moduleOf(from));
271
+ const view = model.isTest(from) ? 'test' : 'production';
230
272
  return lineage(model.moduleOf(to))
231
273
  .filter((module) => !above.includes(module))
232
- .find((module) => !judge.surface(module).has(to));
274
+ .find((module) => !judge.surface(module, undefined, view).has(to));
233
275
  };
234
276
  export const fixesFor = (config, model, from, to) => search({ model, from, to }, config, []);
@@ -0,0 +1,16 @@
1
+ import type { ArchetypeData, RefData } from './data.ts';
2
+ import { type Fail } from './shared.ts';
3
+ export interface PendingRef {
4
+ ref: RefData;
5
+ where: string;
6
+ archetype: string;
7
+ tests: boolean;
8
+ surface?: true;
9
+ }
10
+ export interface Structure {
11
+ root: string;
12
+ archetypes: Record<string, ArchetypeData>;
13
+ pending: PendingRef[];
14
+ }
15
+ export declare const rootName = "root";
16
+ export declare const parseStructure: (root: unknown, archetypes: unknown, fail: Fail) => Structure;