Extract shared calculations and preserve legacy research capabilities
This commit is contained in:
parent
ccce401f72
commit
7827220b9b
82 changed files with 3099 additions and 1994 deletions
|
|
@ -7,6 +7,8 @@ export const checks = [
|
|||
'typecheck',
|
||||
'test:contracts',
|
||||
'test:tooling',
|
||||
'test:utils',
|
||||
'test:calculations',
|
||||
'test:integration',
|
||||
'test:native',
|
||||
'lint:check',
|
||||
|
|
|
|||
60
scripts/runtime-imports.ts
Normal file
60
scripts/runtime-imports.ts
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
import { readFileSync } from 'node:fs';
|
||||
import ts from 'typescript';
|
||||
|
||||
/** Runtime edges only: type imports and type re-exports cannot initialize a module. */
|
||||
export function runtimeImports(file: string, sourceText = readFileSync(file, 'utf8')): string[] {
|
||||
const source = ts.createSourceFile(file, sourceText, ts.ScriptTarget.Latest, true);
|
||||
const imports = new Set<string>();
|
||||
function visit(node: ts.Node) {
|
||||
if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) {
|
||||
const clause = node.importClause;
|
||||
const bindings = clause?.namedBindings;
|
||||
const typesOnly =
|
||||
clause?.isTypeOnly ||
|
||||
(clause &&
|
||||
!clause.name &&
|
||||
bindings &&
|
||||
ts.isNamedImports(bindings) &&
|
||||
bindings.elements.length > 0 &&
|
||||
bindings.elements.every(item => item.isTypeOnly));
|
||||
if (!typesOnly) imports.add(node.moduleSpecifier.text);
|
||||
}
|
||||
if (
|
||||
ts.isExportDeclaration(node) &&
|
||||
!node.isTypeOnly &&
|
||||
node.moduleSpecifier &&
|
||||
ts.isStringLiteral(node.moduleSpecifier)
|
||||
) {
|
||||
const clause = node.exportClause;
|
||||
if (
|
||||
!clause ||
|
||||
!ts.isNamedExports(clause) ||
|
||||
!clause.elements.length ||
|
||||
clause.elements.some(item => !item.isTypeOnly)
|
||||
) {
|
||||
imports.add(node.moduleSpecifier.text);
|
||||
}
|
||||
}
|
||||
if (
|
||||
ts.isCallExpression(node) &&
|
||||
(node.expression.kind === ts.SyntaxKind.ImportKeyword ||
|
||||
(ts.isIdentifier(node.expression) && node.expression.text === 'require')) &&
|
||||
node.arguments[0] &&
|
||||
ts.isStringLiteral(node.arguments[0])
|
||||
) {
|
||||
imports.add(node.arguments[0].text);
|
||||
}
|
||||
if (
|
||||
ts.isImportEqualsDeclaration(node) &&
|
||||
!node.isTypeOnly &&
|
||||
ts.isExternalModuleReference(node.moduleReference) &&
|
||||
node.moduleReference.expression &&
|
||||
ts.isStringLiteral(node.moduleReference.expression)
|
||||
) {
|
||||
imports.add(node.moduleReference.expression.text);
|
||||
}
|
||||
ts.forEachChild(node, visit);
|
||||
}
|
||||
visit(source);
|
||||
return [...imports];
|
||||
}
|
||||
|
|
@ -3,63 +3,11 @@ import { dirname, join, relative, resolve } from 'node:path';
|
|||
import { fileURLToPath } from 'node:url';
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
import ts from 'typescript';
|
||||
import { runtimeImports } from '../runtime-imports';
|
||||
|
||||
const root = fileURLToPath(new URL('../../apps/stock/orchestrator/src/', import.meta.url));
|
||||
const files = [...new Bun.Glob('**/*.ts').scanSync({ cwd: root })].map(file => join(root, file));
|
||||
|
||||
/** Include static imports/re-exports and lazy imports; type-only edges do not load code. */
|
||||
function runtimeImports(file: string): string[] {
|
||||
const source = ts.createSourceFile(
|
||||
file,
|
||||
readFileSync(file, 'utf8'),
|
||||
ts.ScriptTarget.Latest,
|
||||
true
|
||||
);
|
||||
const imports = new Set<string>();
|
||||
function visit(node: ts.Node) {
|
||||
if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) {
|
||||
const clause = node.importClause;
|
||||
const bindings = clause?.namedBindings;
|
||||
const typesOnly =
|
||||
clause?.isTypeOnly ||
|
||||
(clause &&
|
||||
!clause.name &&
|
||||
bindings &&
|
||||
ts.isNamedImports(bindings) &&
|
||||
bindings.elements.length > 0 &&
|
||||
bindings.elements.every(item => item.isTypeOnly));
|
||||
if (!typesOnly) imports.add(node.moduleSpecifier.text);
|
||||
}
|
||||
if (
|
||||
ts.isExportDeclaration(node) &&
|
||||
!node.isTypeOnly &&
|
||||
node.moduleSpecifier &&
|
||||
ts.isStringLiteral(node.moduleSpecifier)
|
||||
) {
|
||||
const clause = node.exportClause;
|
||||
if (
|
||||
!clause ||
|
||||
!ts.isNamedExports(clause) ||
|
||||
!clause.elements.length ||
|
||||
clause.elements.some(item => !item.isTypeOnly)
|
||||
) {
|
||||
imports.add(node.moduleSpecifier.text);
|
||||
}
|
||||
}
|
||||
if (
|
||||
ts.isCallExpression(node) &&
|
||||
node.expression.kind === ts.SyntaxKind.ImportKeyword &&
|
||||
node.arguments[0] &&
|
||||
ts.isStringLiteral(node.arguments[0])
|
||||
) {
|
||||
imports.add(node.arguments[0].text);
|
||||
}
|
||||
ts.forEachChild(node, visit);
|
||||
}
|
||||
visit(source);
|
||||
return [...imports];
|
||||
}
|
||||
|
||||
const imports = new Map(files.map(file => [file, runtimeImports(file)]));
|
||||
function localFile(from: string, specifier: string): string | undefined {
|
||||
if (!specifier.startsWith('.')) return undefined;
|
||||
|
|
@ -256,14 +204,14 @@ describe('orchestrator architecture boundaries', () => {
|
|||
expect(dependencies).toEqual(['backtest/BacktestPlayback.ts', 'backtest/execution-engine.ts']);
|
||||
});
|
||||
|
||||
it('shared analytics math is pure and cannot load report facades or application adapters', () => {
|
||||
it('reviewed analytics and window math live in the shared calculations library', () => {
|
||||
for (const entry of ['equity', 'performance', 'return-statistics', 'trade-statistics']) {
|
||||
for (const file of reachable(join(root, 'analytics/' + entry + '.ts'))) {
|
||||
expect(relative(root, file)).toMatch(/^analytics\//);
|
||||
expect(relative(root, file)).not.toBe('analytics/PerformanceAnalyzer.ts');
|
||||
expect((imports.get(file) ?? []).every(specifier => specifier.startsWith('.'))).toBe(true);
|
||||
}
|
||||
expect(existsSync(join(root, 'analytics/' + entry + '.ts'))).toBe(false);
|
||||
}
|
||||
expect(existsSync(join(root, 'indicators/window-statistics.ts'))).toBe(false);
|
||||
expect(imports.get(join(root, 'analytics/PerformanceAnalyzer.ts'))).toEqual([
|
||||
'@stock-bot/calculations/analytics',
|
||||
]);
|
||||
});
|
||||
|
||||
it('backtest reports are independent of run control, native engines, data loading and financial mutation', () => {
|
||||
|
|
@ -276,9 +224,12 @@ describe('orchestrator architecture boundaries', () => {
|
|||
for (const specifier of imports.get(file) ?? []) {
|
||||
expect(
|
||||
specifier.startsWith('.') ||
|
||||
['simple-statistics', 'zod', '@stock-bot/invariants', '@stock-bot/logger'].includes(
|
||||
specifier
|
||||
)
|
||||
[
|
||||
'zod',
|
||||
'@stock-bot/invariants',
|
||||
'@stock-bot/logger',
|
||||
'@stock-bot/calculations/analytics',
|
||||
].includes(specifier)
|
||||
).toBe(true);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
204
scripts/test/library-boundaries.test.ts
Normal file
204
scripts/test/library-boundaries.test.ts
Normal file
|
|
@ -0,0 +1,204 @@
|
|||
import { readFileSync } from 'node:fs';
|
||||
import { dirname, join, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
import * as utils from '@stock-bot/utils';
|
||||
import { fetch } from '@stock-bot/utils/fetch';
|
||||
import { getRandomUserAgent } from '@stock-bot/utils/user-agent';
|
||||
import { checks } from '../check';
|
||||
import { runtimeImports } from '../runtime-imports';
|
||||
|
||||
const root = fileURLToPath(new URL('../../', import.meta.url));
|
||||
const utilsRoot = join(root, 'libs/utils');
|
||||
const manifest = JSON.parse(readFileSync(join(utilsRoot, 'package.json'), 'utf8'));
|
||||
const sourceFiles = [...new Bun.Glob('src/**/*.ts').scanSync({ cwd: utilsRoot })].map(file =>
|
||||
join(utilsRoot, file)
|
||||
);
|
||||
|
||||
describe('shared library boundaries', () => {
|
||||
it('utils exposes general helpers without a financial framework', () => {
|
||||
expect(Object.keys(utils).sort()).toEqual([
|
||||
'createProxyUrl',
|
||||
'dateUtils',
|
||||
'fetch',
|
||||
'getRandomUserAgent',
|
||||
'sleep',
|
||||
'utcDates',
|
||||
]);
|
||||
expect(utils.fetch).toBe(fetch);
|
||||
expect(utils.getRandomUserAgent).toBe(getRandomUserAgent);
|
||||
expect(manifest.private).toBe(true);
|
||||
expect(manifest.exports).toEqual({
|
||||
'.': './src/index.ts',
|
||||
'./fetch': './src/fetch.ts',
|
||||
'./user-agent': './src/user-agent.ts',
|
||||
'./common': './src/common.ts',
|
||||
'./dates': './src/dateUtils.ts',
|
||||
});
|
||||
for (const retired of ['assertions', 'calculations', 'src/fetch', 'dateUtils']) {
|
||||
expect(() => Bun.resolveSync(`@stock-bot/utils/${retired}`, root)).toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
it('utils cannot load infrastructure adapters or grow another domain-math API', () => {
|
||||
expect(Object.keys(manifest.dependencies).sort()).toEqual([
|
||||
'@stock-bot/invariants',
|
||||
'@stock-bot/logger',
|
||||
]);
|
||||
const config = JSON.parse(readFileSync(join(utilsRoot, 'tsconfig.json'), 'utf8'));
|
||||
expect(config.references.map((ref: { path: string }) => ref.path).sort()).toEqual([
|
||||
'../core/invariants',
|
||||
'../core/logger',
|
||||
]);
|
||||
for (const file of sourceFiles) {
|
||||
expect(file).not.toContain('/calculations/');
|
||||
for (const specifier of runtimeImports(file)) {
|
||||
if (specifier.startsWith('.')) {
|
||||
const local = resolve(dirname(file), specifier);
|
||||
expect(
|
||||
sourceFiles.some(
|
||||
target => target === `${local}.ts` || target === join(local, 'index.ts')
|
||||
)
|
||||
).toBe(true);
|
||||
} else {
|
||||
// Logger is a type-only capability; only invariants may be loaded at runtime.
|
||||
expect(specifier).toBe('@stock-bot/invariants');
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('calculations is a portable pure library, with legacy code isolated from supported exports', () => {
|
||||
const directory = join(root, 'libs/calculations');
|
||||
const pkg = JSON.parse(readFileSync(join(directory, 'package.json'), 'utf8'));
|
||||
expect(Object.keys(pkg.dependencies).sort()).toEqual([
|
||||
'@stock-bot/invariants',
|
||||
'@stock-bot/types',
|
||||
]);
|
||||
expect(pkg.private).toBe(true);
|
||||
const sources = [...new Bun.Glob('src/**/*.ts').scanSync({ cwd: directory })].map(file =>
|
||||
join(directory, file)
|
||||
);
|
||||
for (const file of sources) {
|
||||
for (const specifier of runtimeImports(file)) {
|
||||
if (!specifier.startsWith('.')) {
|
||||
expect(specifier).toBe('@stock-bot/invariants');
|
||||
continue;
|
||||
}
|
||||
const target = resolve(dirname(file), specifier);
|
||||
const dependency = sources.find(
|
||||
source => source === `${target}.ts` || source === join(target, 'index.ts')
|
||||
);
|
||||
expect(dependency).toBeDefined();
|
||||
if (!file.includes('/legacy/')) expect(dependency).not.toContain('/legacy/');
|
||||
}
|
||||
}
|
||||
expect(Object.keys(pkg.exports).sort()).toEqual([
|
||||
'.',
|
||||
'./analytics',
|
||||
'./indicators',
|
||||
'./legacy',
|
||||
'./market-data',
|
||||
'./returns',
|
||||
]);
|
||||
for (const path of [
|
||||
'research',
|
||||
'src/legacy/basic-calculations',
|
||||
'legacy/technical-indicators',
|
||||
]) {
|
||||
expect(() => Bun.resolveSync(`@stock-bot/calculations/${path}`, root)).toThrow();
|
||||
}
|
||||
expect(runtimeImports(join(root, 'libs/core/invariants/src/index.ts'))).toEqual([]);
|
||||
});
|
||||
|
||||
it('stock applications use reviewed calculation contracts, not archived prototypes or legacy math', () => {
|
||||
const directory = join(root, 'apps/stock');
|
||||
const files = [...new Bun.Glob('*/src/**/*.ts').scanSync({ cwd: directory })];
|
||||
for (const file of files) {
|
||||
for (const specifier of runtimeImports(join(directory, file))) {
|
||||
expect(specifier).not.toMatch(/^@stock-bot\/calculations\/(legacy|research)/);
|
||||
if (specifier.startsWith('.')) {
|
||||
const target = resolve(dirname(join(directory, file)), specifier);
|
||||
expect(target).not.toContain('/libs/calculations/src/legacy/');
|
||||
expect(target).not.toContain('/libs/calculations/research/');
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('library source and tests contain no disabled or backup copies', () => {
|
||||
const files = [...new Bun.Glob('**/*').scanSync({ cwd: join(root, 'libs') })];
|
||||
const backups = files.filter(
|
||||
file =>
|
||||
!file.split('/').some(part => ['node_modules', 'dist'].includes(part)) &&
|
||||
/\.(old|disabled|bak|orig)$/.test(file)
|
||||
);
|
||||
expect(backups).toEqual([]);
|
||||
});
|
||||
|
||||
it('the root gate runs utility and HTTP-consumer regressions', () => {
|
||||
expect(checks).toContain('test:utils');
|
||||
expect(checks).toContain('test:calculations');
|
||||
const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
|
||||
expect(pkg.scripts['test:utils']).toBe(
|
||||
'bun test libs/utils/test/ libs/core/handlers/test/base-handler-http.test.ts'
|
||||
);
|
||||
for (const path of ['apps/stock/orchestrator', 'tools/coverage-cli']) {
|
||||
const consumer = JSON.parse(readFileSync(join(root, path, 'package.json'), 'utf8'));
|
||||
expect(consumer.dependencies).not.toHaveProperty('@stock-bot/utils');
|
||||
expect(consumer.dependencies).not.toHaveProperty('simple-statistics');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('runtime dependency inspection', () => {
|
||||
it('ignores erased type-only imports and re-exports', () => {
|
||||
expect(
|
||||
runtimeImports(
|
||||
'fixture.ts',
|
||||
`
|
||||
import type { Logger } from 'logger';
|
||||
import { type Cache } from 'cache';
|
||||
import type * as DB from 'database';
|
||||
export type { Portfolio } from 'finance';
|
||||
export { type Model } from 'models';
|
||||
type Lazy = typeof import('type-query');
|
||||
import type Legacy = require('legacy-type');
|
||||
`
|
||||
)
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it('detects static, mixed, side-effect, lazy and CommonJS runtime edges', () => {
|
||||
expect(
|
||||
runtimeImports(
|
||||
'fixture.ts',
|
||||
`
|
||||
import { run, type Options } from 'mixed';
|
||||
import fallback, { type Shape } from 'default';
|
||||
import 'side-effect';
|
||||
export { execute, type Input } from 're-export';
|
||||
export * from 'star';
|
||||
export * as ns from 'namespace';
|
||||
import {} from 'empty-import';
|
||||
export {} from 'empty-export';
|
||||
const module = await import('lazy');
|
||||
const cjs = require('commonjs');
|
||||
import legacy = require('import-equals');
|
||||
`
|
||||
)
|
||||
).toEqual([
|
||||
'mixed',
|
||||
'default',
|
||||
'side-effect',
|
||||
're-export',
|
||||
'star',
|
||||
'namespace',
|
||||
'empty-import',
|
||||
'empty-export',
|
||||
'lazy',
|
||||
'commonjs',
|
||||
'import-equals',
|
||||
]);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue