Initial Commit
This commit is contained in:
50
packages/media/audio/audio-core/tests/exports.test.ts
Normal file
50
packages/media/audio/audio-core/tests/exports.test.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { describe, expect, it } from "@suaveplan/testing/runner";
|
||||
|
||||
const PKG_ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
|
||||
// Every feature module the spec's "Subpath exports per feature module"
|
||||
// requirement mandates an `exports` entry for.
|
||||
const FEATURE_MODULES = [
|
||||
"./document/document",
|
||||
"./page/page",
|
||||
"./plan/plan-engine",
|
||||
"./plan/segment",
|
||||
"./process/process-pipeline",
|
||||
"./process/block-processor",
|
||||
"./registry/op-registry",
|
||||
"./stream/stream",
|
||||
"./render/render",
|
||||
"./stats/stats",
|
||||
];
|
||||
|
||||
describe("subpath exports", () => {
|
||||
it("every feature module has a subpath export entry", {
|
||||
timeout: 5000,
|
||||
}, () => {
|
||||
const pkg = JSON.parse(
|
||||
readFileSync(join(PKG_ROOT, "package.json"), "utf8")
|
||||
) as {
|
||||
exports: Record<string, unknown>;
|
||||
sideEffects?: boolean;
|
||||
};
|
||||
for (const mod of FEATURE_MODULES) {
|
||||
// The export entry exists...
|
||||
expect({ mod, defined: pkg.exports[mod] !== undefined }).toEqual({
|
||||
mod,
|
||||
defined: true,
|
||||
});
|
||||
// ...and resolves to a feature module that exists in src/.
|
||||
const source = join(PKG_ROOT, "src", `${mod.slice(2)}.ts`);
|
||||
expect({ mod, exists: existsSync(source) }).toEqual({
|
||||
mod,
|
||||
exists: true,
|
||||
});
|
||||
}
|
||||
// The root barrel is still importable and the package is pure.
|
||||
expect(pkg.exports["."]).toBeDefined();
|
||||
expect(pkg.sideEffects).toBe(false);
|
||||
});
|
||||
});
|
||||
46
packages/media/audio/audio-core/tests/integration.test.ts
Normal file
46
packages/media/audio/audio-core/tests/integration.test.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import { describe, expect, it } from "@suaveplan/testing/runner";
|
||||
import { AudioDocument } from "../src/document/document.js";
|
||||
|
||||
describe("integration", () => {
|
||||
it("full round-trip: construct, run edits, stream, read, clone, toJSON", {
|
||||
timeout: 30000,
|
||||
}, async () => {
|
||||
const doc = new AudioDocument({
|
||||
sampleRate: 48000,
|
||||
channels: 2,
|
||||
sourceLength: 2048,
|
||||
pages: [
|
||||
{
|
||||
channelData: [
|
||||
new Float32Array(2048).fill(0.5),
|
||||
new Float32Array(2048).fill(0.25),
|
||||
],
|
||||
startSample: 0,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
doc.run({ type: "trim", opts: { start: 0, end: 1024 } });
|
||||
doc.run({ type: "gain", opts: { gain: 2 } });
|
||||
|
||||
expect(doc.length).toBe(1024);
|
||||
|
||||
const readResult = await doc.read(0, 512);
|
||||
expect(readResult[0].length).toBe(512);
|
||||
|
||||
let streamTotal = 0;
|
||||
for await (const block of doc.stream({ blockSize: 256 })) {
|
||||
streamTotal += block[0].length;
|
||||
}
|
||||
expect(streamTotal).toBe(1024);
|
||||
|
||||
const cloned = doc.clone();
|
||||
expect(cloned.length).toBe(doc.length);
|
||||
expect(cloned.id).not.toBe(doc.id);
|
||||
|
||||
const json = doc.toJSON();
|
||||
const restored = AudioDocument.fromJSON(json);
|
||||
expect(restored.sampleRate).toBe(doc.sampleRate);
|
||||
expect(restored.edits.length).toBe(doc.edits.length);
|
||||
});
|
||||
});
|
||||
137
packages/media/audio/audio-core/tests/property.test.ts
Normal file
137
packages/media/audio/audio-core/tests/property.test.ts
Normal file
@@ -0,0 +1,137 @@
|
||||
import { describe, expect, it } from "@suaveplan/testing/runner";
|
||||
import * as fc from "fast-check";
|
||||
import { AudioDocument } from "../src/document/document.js";
|
||||
import { BLOCK_SIZE } from "../src/page/page.js";
|
||||
import { PlanEngine } from "../src/plan/plan-engine.js";
|
||||
import { OpRegistry } from "../src/registry/op-registry.js";
|
||||
|
||||
function makeDoc(
|
||||
sourceLength: number,
|
||||
channels: number,
|
||||
sampleRate: number
|
||||
): AudioDocument {
|
||||
const pageSize = 48000;
|
||||
const pages = [];
|
||||
for (let s = 0; s < sourceLength; s += pageSize) {
|
||||
const len = Math.min(pageSize, sourceLength - s);
|
||||
pages.push({
|
||||
startSample: s,
|
||||
channelData: Array.from(
|
||||
{ length: channels },
|
||||
() => new Float32Array(len)
|
||||
),
|
||||
});
|
||||
}
|
||||
return new AudioDocument({
|
||||
sampleRate,
|
||||
channels,
|
||||
sourceLength,
|
||||
pages,
|
||||
edits: [],
|
||||
});
|
||||
}
|
||||
|
||||
describe("Property: identity edit preserves plan length", () => {
|
||||
it("passes with random source lengths and sample rates", {
|
||||
timeout: 30000,
|
||||
}, () => {
|
||||
fc.assert(
|
||||
fc.property(
|
||||
fc.integer({ min: 1000, max: 500_000 }),
|
||||
fc.integer({ min: 1, max: 8 }),
|
||||
fc.integer({ min: 8000, max: 192_000 }),
|
||||
(sourceLength, channels, sampleRate) => {
|
||||
const doc = makeDoc(sourceLength, channels, sampleRate);
|
||||
const registry = OpRegistry.createWithDefaults();
|
||||
const engine = new PlanEngine(registry);
|
||||
const before = engine.compile(doc, true);
|
||||
doc.run({ type: "speed", opts: { rate: 1 } });
|
||||
const after = engine.compile(doc, true);
|
||||
expect(after.totalLen).toBe(before.totalLen);
|
||||
}
|
||||
)
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Property: plan compilation is deterministic", () => {
|
||||
it("plan compilation is deterministic", { timeout: 30000 }, () => {
|
||||
fc.assert(
|
||||
fc.property(
|
||||
fc.integer({ min: 1000, max: 200_000 }),
|
||||
fc.integer({ min: 1, max: 4 }),
|
||||
fc.integer({ min: 8000, max: 96_000 }),
|
||||
fc.integer({ min: 1, max: 4 }),
|
||||
(sourceLength, channels, sampleRate, repeatTimes) => {
|
||||
const doc = makeDoc(sourceLength, channels, sampleRate);
|
||||
doc.run({ type: "repeat", opts: { times: repeatTimes } });
|
||||
doc.run({ type: "gain", opts: { gain: 0.5 } });
|
||||
const registry = OpRegistry.createWithDefaults();
|
||||
const engine = new PlanEngine(registry);
|
||||
const first = engine.compile(doc, true);
|
||||
const second = engine.compile(doc, true);
|
||||
expect(second).toEqual(first);
|
||||
}
|
||||
)
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Property: stream yields exact total sample count", () => {
|
||||
it("stream yields exact total sample count", {
|
||||
timeout: 30000,
|
||||
}, async () => {
|
||||
await fc.assert(
|
||||
fc.asyncProperty(
|
||||
fc.integer({ min: 1000, max: 200_000 }),
|
||||
fc.integer({ min: 1, max: 4 }),
|
||||
fc.integer({ min: 1, max: BLOCK_SIZE }),
|
||||
async (sourceLength, channels, blockSize) => {
|
||||
const doc = makeDoc(sourceLength, channels, 48000);
|
||||
const registry = OpRegistry.createWithDefaults();
|
||||
const engine = new PlanEngine(registry);
|
||||
const plan = engine.compile(doc, false);
|
||||
let totalSamples = 0;
|
||||
for await (const block of doc.stream({ blockSize })) {
|
||||
totalSamples += block[0]?.length ?? 0;
|
||||
}
|
||||
expect(totalSamples).toBe(plan.totalLen);
|
||||
}
|
||||
)
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Property: clone preserves structure with new id", () => {
|
||||
it("clone toJSON equals original toJSON", { timeout: 30000 }, () => {
|
||||
// The property under test is structural — `clone().toJSON()` equals
|
||||
// the original's `toJSON()` modulo `id`. The doc's *size* is
|
||||
// irrelevant to that invariant, so cap inputs small to keep the
|
||||
// fast-check sweep inside the 30 s budget. The other three
|
||||
// properties in this file deliberately exercise large source
|
||||
// lengths because they probe size-dependent code paths (plan
|
||||
// compilation, streaming); this one does not.
|
||||
fc.assert(
|
||||
fc.property(
|
||||
fc.integer({ min: 1000, max: 10_000 }),
|
||||
fc.integer({ min: 1, max: 4 }),
|
||||
fc.integer({ min: 8000, max: 96_000 }),
|
||||
(sourceLength, channels, sampleRate) => {
|
||||
const doc = makeDoc(sourceLength, channels, sampleRate);
|
||||
doc.run({
|
||||
type: "trim",
|
||||
opts: { start: 0, end: sourceLength },
|
||||
});
|
||||
const cloned = doc.clone();
|
||||
const { id: originalId, ...originalRest } = doc.toJSON();
|
||||
const { id: clonedId, ...clonedRest } = cloned.toJSON();
|
||||
// The clone gets a fresh id but is otherwise an exact
|
||||
// structural copy — toJSON matches on every other field.
|
||||
expect(clonedId).not.toBe(originalId);
|
||||
expect(clonedRest).toEqual(originalRest);
|
||||
}
|
||||
),
|
||||
{ numRuns: 25 }
|
||||
);
|
||||
});
|
||||
});
|
||||
115
packages/media/audio/audio-core/tests/purity.test.ts
Normal file
115
packages/media/audio/audio-core/tests/purity.test.ts
Normal file
@@ -0,0 +1,115 @@
|
||||
import { readdirSync, readFileSync, statSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { metrics, trace } from "@opentelemetry/api";
|
||||
import { describe, expect, it } from "@suaveplan/testing/runner";
|
||||
|
||||
const PKG_ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
|
||||
// The complete set the spec's "Universal purity" requirement allows
|
||||
// in package.json `dependencies`.
|
||||
const ALLOWED_DEPENDENCIES = new Set([
|
||||
"@opentelemetry/api",
|
||||
"@suaveplan/error",
|
||||
"@suaveplan/events",
|
||||
"@suaveplan/serialize",
|
||||
"@suaveplan/streams",
|
||||
"@suaveplan/types",
|
||||
"tslib",
|
||||
"zod",
|
||||
]);
|
||||
|
||||
// Bare-identifier globals with no legitimate use in a universal package.
|
||||
const FORBIDDEN_GLOBALS = [
|
||||
"window",
|
||||
"document",
|
||||
"navigator",
|
||||
"AudioContext",
|
||||
"Buffer",
|
||||
];
|
||||
|
||||
function collectDistJs(dir: string, acc: string[] = []): string[] {
|
||||
for (const entry of readdirSync(dir)) {
|
||||
const full = join(dir, entry);
|
||||
if (statSync(full).isDirectory()) {
|
||||
collectDistJs(full, acc);
|
||||
} else if (entry.endsWith(".js")) {
|
||||
acc.push(full);
|
||||
}
|
||||
}
|
||||
return acc;
|
||||
}
|
||||
|
||||
// Remove comments and string/template literals so import-path substrings
|
||||
// (e.g. "./process/...") and message text cannot trigger false positives.
|
||||
function stripStringsAndComments(src: string): string {
|
||||
return src
|
||||
.replace(/\/\*[\s\S]*?\*\//g, " ")
|
||||
.replace(/\/\/[^\n]*/g, " ")
|
||||
.replace(/"(?:[^"\\]|\\.)*"/g, '""')
|
||||
.replace(/'(?:[^'\\]|\\.)*'/g, "''")
|
||||
.replace(/`(?:[^`\\]|\\.)*`/g, "``");
|
||||
}
|
||||
|
||||
describe("universal purity", () => {
|
||||
it("dist references no browser or Node globals", {
|
||||
timeout: 5000,
|
||||
}, () => {
|
||||
const files = collectDistJs(join(PKG_ROOT, "dist"));
|
||||
expect(files.length).toBeGreaterThan(0);
|
||||
const offenders: string[] = [];
|
||||
for (const file of files) {
|
||||
const raw = readFileSync(file, "utf8");
|
||||
const code = stripStringsAndComments(raw);
|
||||
for (const name of FORBIDDEN_GLOBALS) {
|
||||
const re = new RegExp(`(?<![.\\w])${name}(?![\\w])`);
|
||||
if (re.test(code)) offenders.push(`${file}: ${name}`);
|
||||
}
|
||||
// `process` is also a domain identifier here (audio "process"
|
||||
// ops/methods), so only the Node-global access pattern — a
|
||||
// free `process` followed by member access — is forbidden.
|
||||
if (/(?<![.\w])process\s*\./.test(code)) {
|
||||
offenders.push(`${file}: process global`);
|
||||
}
|
||||
if (/node:fs|node:path/.test(raw)) {
|
||||
offenders.push(`${file}: node: import`);
|
||||
}
|
||||
}
|
||||
expect(offenders).toEqual([]);
|
||||
});
|
||||
|
||||
it("dependency set is limited to the declared workspace and zod", {
|
||||
timeout: 5000,
|
||||
}, () => {
|
||||
const pkg = JSON.parse(
|
||||
readFileSync(join(PKG_ROOT, "package.json"), "utf8")
|
||||
) as { dependencies?: Record<string, string> };
|
||||
const deps = Object.keys(pkg.dependencies ?? {});
|
||||
expect(deps.length).toBeGreaterThan(0);
|
||||
for (const dep of deps) {
|
||||
expect({ dep, allowed: ALLOWED_DEPENDENCIES.has(dep) }).toEqual({
|
||||
dep,
|
||||
allowed: true,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it("importing the package mutates no global state", {
|
||||
timeout: 5000,
|
||||
}, async () => {
|
||||
// Ignore tooling/dependency internals (vitest, zod's registry);
|
||||
// the assertion is that *this package* registers nothing global.
|
||||
const userGlobals = (): string[] =>
|
||||
Object.keys(globalThis)
|
||||
.filter((k) => !k.startsWith("__"))
|
||||
.sort();
|
||||
const globalsBefore = userGlobals();
|
||||
const tracerProviderBefore = trace.getTracerProvider();
|
||||
const meterProviderBefore = metrics.getMeterProvider();
|
||||
await import("../src/index.js");
|
||||
// No new globals, and no global OTel provider registered at import.
|
||||
expect(userGlobals()).toEqual(globalsBefore);
|
||||
expect(trace.getTracerProvider()).toBe(tracerProviderBefore);
|
||||
expect(metrics.getMeterProvider()).toBe(meterProviderBefore);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user