66 lines
2.7 KiB
TypeScript
66 lines
2.7 KiB
TypeScript
/** Shared server-only artifact custody. Resolve paths on demand, never while importing APIs. */
|
|
import { createHash } from 'node:crypto';
|
|
import { realpathSync } from 'node:fs';
|
|
import { readFile } from 'node:fs/promises';
|
|
import { dirname, isAbsolute, relative, resolve } from 'node:path';
|
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
|
|
export function localBuildArtifacts() {
|
|
const engineWrapper = realpathSync(fileURLToPath(import.meta.resolve('@stock-bot/engine')));
|
|
const repositoryRoot = resolve(dirname(engineWrapper), '../../..');
|
|
const ownPath = relative(repositoryRoot, realpathSync(fileURLToPath(import.meta.url)));
|
|
if (isAbsolute(ownPath) || ownPath === '..' || ownPath.startsWith('../')) {
|
|
throw new Error('Canonical engine resolves outside this checkout');
|
|
}
|
|
if (engineWrapper !== resolve(repositoryRoot, 'apps/stock/engine/index.mjs')) {
|
|
throw new Error('Unsupported canonical engine wrapper location');
|
|
}
|
|
return { repositoryRoot, engineWrapper };
|
|
}
|
|
export function bundledHostUrl(name: 'native-worker' | 'paper-host'): URL {
|
|
return pathToFileURL(
|
|
resolve(localBuildArtifacts().repositoryRoot, `apps/stock/orchestrator/dist/${name}.js`)
|
|
);
|
|
}
|
|
export async function hashLocalArtifact(path: string): Promise<string> {
|
|
if (realpathSync(path) !== path) {
|
|
throw new Error('Canonical build artifacts must belong to this checkout');
|
|
}
|
|
return createHash('sha256')
|
|
.update(await readFile(path))
|
|
.digest('hex');
|
|
}
|
|
export async function readBuildArtifacts(name: 'native-worker' | 'paper-host') {
|
|
if (typeof Bun === 'undefined') {
|
|
throw new Error('Canonical execution requires the Bun runtime');
|
|
}
|
|
const { repositoryRoot, engineWrapper } = localBuildArtifacts();
|
|
const [executableSha256, engineWrapperSha256, engineBinarySha256, dependencyLockSha256] =
|
|
await Promise.all([
|
|
hashLocalArtifact(fileURLToPath(bundledHostUrl(name))),
|
|
hashLocalArtifact(engineWrapper),
|
|
hashLocalArtifact(resolve(repositoryRoot, 'apps/stock/engine/dist/engine.node')),
|
|
hashLocalArtifact(resolve(repositoryRoot, 'bun.lock')),
|
|
]);
|
|
return {
|
|
executableSha256,
|
|
engineWrapperSha256,
|
|
engineBinarySha256,
|
|
dependencyLockSha256,
|
|
runtime: 'bun' as const,
|
|
runtimeVersion: Bun.version,
|
|
platform: process.platform,
|
|
arch: process.arch,
|
|
};
|
|
}
|
|
export function verifyBundledHost(name: 'native-worker' | 'paper-host', actualUrl: string): void {
|
|
if (
|
|
realpathSync(fileURLToPath(actualUrl)) !== realpathSync(fileURLToPath(bundledHostUrl(name)))
|
|
) {
|
|
throw new Error(
|
|
name === 'native-worker'
|
|
? 'Canonical research requires the bundled worker from this checkout'
|
|
: 'Paper deployment requires the bundled paper host from this checkout'
|
|
);
|
|
}
|
|
}
|